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(plugins): 安装与扩权更新前请用户确认插件权限 (#5088)

Lizi771c5cde3e2e
diff --git a/apps/desktop/help-knowledge/plugins.md b/apps/desktop/help-knowledge/plugins.md
index 67a52b94a1..1b12691936 100644
--- a/apps/desktop/help-knowledge/plugins.md
+++ b/apps/desktop/help-knowledge/plugins.md
@@ -28,9 +28,11 @@ Plugins (internally "意识" / Ghost) extend what the agents can do — they add
**Installing:**
- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).
-- Choosing Install, dragging a package, or picking one from disk installs and enables the selected plugin directly. Installation does not add a permission or version-confirmation step; review its declared capabilities on the plugin detail page.
+- Choosing Install, dragging a package, or picking one from disk first shows a **confirmation dialog** listing everything the plugin declares it can do (network domains, credentials, background tasks, skills, bundled code, panels…). Nothing is installed until you confirm; after that the plugin is enabled right away.
+- When you ask an agent to install a plugin (`ghost_market_install` / `ghost_forge_install`), the same confirmation appears as a card in that task — whatever the task's permission mode, including Full Access. It also works from the phone when you control this computer remotely. If you deny it, nothing is installed.
+- Plugins pushed by your organization (server default installs) are installed and updated silently without a confirmation.
- The server selects the release appropriate for this Cindy version before marketplace delivery. Desktop does not apply a second `minCindyVersion` gate; custom marketplaces and local `.cindy` packages follow the same install policy.
-- Updates from stable marketplace sources are applied automatically when the plugin is idle. Failed attempts retry later; you can still click Update to retry immediately.
+- Updates from stable marketplace sources are applied automatically when the plugin is idle — **as long as the new version doesn't need more permissions**. If it does, the automatic update pauses, the old version keeps working, and the plugin card shows "New permissions need confirmation"; clicking Update shows the added permissions for you to confirm. Failed attempts retry later; you can still click Update to retry immediately.
**Using a plugin with `$command`:**
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
index d70e66b248..eedff4194f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
@@ -35,11 +35,32 @@ describe('Forge OIDC install entry wiring', () => {
expect(body).toContain('const installOrigin = forgeInstallOriginForMembership(membershipKind);');
expect(body).toContain('...(installOrigin ? { installOrigin } : {})');
expect(body).toContain(
- 'ghostInstallApprovalToken(installed.approval),\n installOrigin,',
+ 'ghostInstallApprovalToken(installed.approval),\n consent,\n installOrigin,',
);
expect(body).not.toContain("installOrigin: 'agent-forge'");
});
+ it('Agent 安装先在锁外求得插件确认,再在锁内交给装入事务复核', () => {
+ const body = forgeInstallBody();
+ const consent = body.indexOf('await obtainGhostInstallConsent(');
+ const mutation = body.indexOf('return withGhostInstallLock');
+ expect(consent).toBeGreaterThanOrEqual(0);
+ expect(mutation).toBeGreaterThan(consent);
+ expect(body).toContain("initiator: 'agent', origin: 'forge'");
+ expect(body).toContain('consent: { decision: consent, manifest: inspected.manifest }');
+ expect(body).toContain('inspected.packageSha256');
+ });
+
+ it('packing 时捕获的 owner 由调用方传入,取新租约前若已切换则拒绝', () => {
+ const body = forgeInstallBody();
+ expect(body).toContain('mutationOwner: ActiveAppSession');
+ expect(body).not.toContain('const mutationOwner = captureGhostMutationOwner();');
+ const lock = body.indexOf('return withGhostInstallLock');
+ const lease = body.indexOf('beginGhostMutation(expected.mutationOwner)');
+ expect(lock).toBeGreaterThanOrEqual(0);
+ expect(lease).toBeGreaterThan(lock);
+ });
+
it('tokenBroker 只在企业身份下拿 Forge facts,且不触发 OIDC 确认窗', () => {
const body = forgeInstallBody();
expect(body).toContain('installOrigin ? { installOrigin } : undefined');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
new file mode 100644
index 0000000000..65b1c01b30
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
@@ -0,0 +1,259 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ validateGhostManifest,
+ type GhostInstallApproval,
+ type GhostManifest,
+ type InstalledGhost,
+} from '../../../shared/ghost.js';
+import {
+ abortAllGhostInstallConsentPrompts,
+ assertGhostInstallConsent,
+ isGhostInstallConsentRequiredError,
+ obtainGhostInstallConsent,
+ trackGhostInstallConsentPrompt,
+} from '../ghostInstallConsent.js';
+
+function manifest(hosts: string[], version = '1.0.0'): GhostManifest {
+ const result = validateGhostManifest({
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'weather-chip',
+ name: 'Weather',
+ version,
+ kind: 'chip',
+ entry: 'main.js',
+ network: { hosts },
+ });
+ if (!result.ok) throw new Error('invalid fixture');
+ return result.manifest;
+}
+
+function installed(
+ base: GhostManifest,
+ approval: GhostInstallApproval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+): InstalledGhost {
+ return {
+ manifest: base,
+ dir: '/userData/cindy-brain/weather-chip',
+ enabled: true,
+ approval,
+ };
+}
+
+const userPrompt = (answer: boolean | Error) =>
+ vi.fn(async () => {
+ if (answer instanceof Error) throw answer;
+ return answer;
+ });
+
+const reviewedDigest = 'a'.repeat(64);
+const replacedDigest = 'b'.repeat(64);
+
+describe('obtainGhostInstallConsent', () => {
+ it('prompts on first install and returns a confirmed decision', async () => {
+ const prompt = userPrompt(true);
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt, initiator: 'user', origin: 'market' },
+ null,
+ manifest(['api.weather.test']),
+ reviewedDigest,
+ );
+ expect(decision.mode).toBe('confirmed');
+ expect(prompt).toHaveBeenCalledWith(
+ expect.objectContaining({ initiator: 'user', origin: 'market', facts: expect.objectContaining({ kind: 'install' }) }),
+ );
+ });
+
+ it('does not prompt for an update without new permissions', async () => {
+ const prompt = userPrompt(true);
+ await expect(
+ obtainGhostInstallConsent(
+ { mode: 'prompt', prompt, initiator: 'agent', origin: 'forge' },
+ installed(manifest(['api.weather.test'])),
+ manifest(['api.weather.test'], '1.1.0'),
+ reviewedDigest,
+ ),
+ ).resolves.toEqual({ mode: 'unprompted' });
+ expect(prompt).not.toHaveBeenCalled();
+ });
+
+ it('cancels when the user declines and fails closed when no prompt can be shown', async () => {
+ const policy = (answer: boolean | Error) =>
+ ({ mode: 'prompt', prompt: userPrompt(answer), initiator: 'user', origin: 'local-file' }) as const;
+ await expect(
+ obtainGhostInstallConsent(policy(false), null, manifest(['api.weather.test']), reviewedDigest),
+ ).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+ await expect(
+ obtainGhostInstallConsent(
+ policy(new Error('no window')),
+ null,
+ manifest(['api.weather.test']),
+ reviewedDigest,
+ ),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ });
+
+ it('never confirms on the user’s behalf for background updates', async () => {
+ const error = await obtainGhostInstallConsent(
+ { mode: 'automatic' },
+ installed(manifest(['api.weather.test'])),
+ manifest(['api.weather.test', 'upload.weather.test'], '2.0.0'),
+ reviewedDigest,
+ ).catch((caught: unknown) => caught);
+ expect(isGhostInstallConsentRequiredError(error)).toBe(true);
+ await expect(
+ obtainGhostInstallConsent(
+ { mode: 'automatic' },
+ installed(manifest(['api.weather.test'])),
+ manifest(['api.weather.test'], '1.1.0'),
+ reviewedDigest,
+ ),
+ ).resolves.toEqual({ mode: 'unprompted' });
+ });
+
+ it('skips confirmation only for server default installs', async () => {
+ await expect(
+ obtainGhostInstallConsent(
+ { mode: 'exempt', reason: 'server-default-install' },
+ null,
+ manifest(['api.weather.test']),
+ reviewedDigest,
+ ),
+ ).resolves.toEqual({ mode: 'exempt', reason: 'server-default-install' });
+ });
+});
+
+describe('assertGhostInstallConsent', () => {
+ it('accepts the exact package and receiver the user confirmed', async () => {
+ const next = manifest(['api.weather.test', 'upload.weather.test'], '2.0.0');
+ const current = installed(manifest(['api.weather.test']));
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: userPrompt(true), initiator: 'user', origin: 'market' },
+ current,
+ next,
+ reviewedDigest,
+ );
+ expect(() => assertGhostInstallConsent(decision, current, next, reviewedDigest)).not.toThrow();
+ });
+
+ it('rejects when the package gained permissions after confirmation', async () => {
+ const current = installed(manifest(['api.weather.test']));
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: userPrompt(true), initiator: 'user', origin: 'market' },
+ current,
+ manifest(['api.weather.test', 'upload.weather.test'], '2.0.0'),
+ reviewedDigest,
+ );
+ expect(() =>
+ assertGhostInstallConsent(
+ decision,
+ current,
+ manifest(['api.weather.test', 'upload.weather.test', 'extra.weather.test'], '2.0.0'),
+ reviewedDigest,
+ ),
+ ).toThrow(/PRECONDITION_FAILED/);
+ });
+
+ it('rejects when the reviewed package bytes are replaced after confirmation', async () => {
+ const next = manifest(['api.weather.test']);
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: userPrompt(true), initiator: 'user', origin: 'market' },
+ null,
+ next,
+ reviewedDigest,
+ );
+ expect(() => assertGhostInstallConsent(decision, null, next, reviewedDigest)).not.toThrow();
+ expect(() => assertGhostInstallConsent(decision, null, next, replacedDigest)).toThrow(
+ /PRECONDITION_FAILED/,
+ );
+ });
+
+ it('rejects a confirmed update when the receiver receipt changed but version and permissions did not', async () => {
+ const current = installed(manifest(['api.weather.test']));
+ const next = manifest(['api.weather.test', 'upload.weather.test'], '2.0.0');
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: userPrompt(true), initiator: 'user', origin: 'forge' },
+ current,
+ next,
+ reviewedDigest,
+ );
+ const replacedReceiver = installed(manifest(['api.weather.test']), {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ });
+ expect(() => assertGhostInstallConsent(decision, replacedReceiver, next, reviewedDigest)).toThrow(
+ /PRECONDITION_FAILED/,
+ );
+ });
+
+ it('rejects a confirmed update once the receiver already covers the candidate permissions', async () => {
+ const v1 = installed(manifest(['api.weather.test']));
+ const v2 = manifest(['api.weather.test', 'upload.weather.test'], '2.0.0');
+ const decision = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: userPrompt(true), initiator: 'user', origin: 'market' },
+ v1,
+ v2,
+ reviewedDigest,
+ );
+ const v3 = installed(manifest(['api.weather.test', 'upload.weather.test'], '3.0.0'));
+ expect(() => assertGhostInstallConsent(decision, v3, v2, reviewedDigest)).toThrow(
+ /PRECONDITION_FAILED/,
+ );
+ });
+
+ it('still accepts an originally unprompted decision when consent is no longer needed', () => {
+ expect(() =>
+ assertGhostInstallConsent(
+ { mode: 'unprompted' },
+ installed(manifest(['api.weather.test'], '3.0.0')),
+ manifest(['api.weather.test'], '2.0.0'),
+ reviewedDigest,
+ ),
+ ).not.toThrow();
+ });
+
+ it('rejects an unprompted decision once the install turns out to need consent', () => {
+ const error = (() => {
+ try {
+ assertGhostInstallConsent(
+ { mode: 'unprompted' },
+ null,
+ manifest(['api.weather.test']),
+ reviewedDigest,
+ );
+ } catch (caught) {
+ return caught;
+ }
+ return null;
+ })();
+ expect(isGhostInstallConsentRequiredError(error)).toBe(true);
+ });
+
+ it('lets a server default install through without a prompt', () => {
+ expect(() =>
+ assertGhostInstallConsent(
+ { mode: 'exempt', reason: 'server-default-install' },
+ installed(manifest(['api.weather.test'])),
+ manifest(['api.weather.test', 'upload.weather.test'], '2.0.0'),
+ reviewedDigest,
+ ),
+ ).not.toThrow();
+ });
+});
+
+describe('pending consent prompts', () => {
+ it('are aborted together at an account boundary', () => {
+ const first = new AbortController();
+ const second = new AbortController();
+ trackGhostInstallConsentPrompt(first);
+ const untrack = trackGhostInstallConsentPrompt(second);
+ untrack();
+ abortAllGhostInstallConsentPrompts();
+ expect(first.signal.aborted).toBe(true);
+ expect(second.signal.aborted).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentInteraction.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentInteraction.test.ts
new file mode 100644
index 0000000000..fff06d1c63
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentInteraction.test.ts
@@ -0,0 +1,162 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { GhostPermissionItem } from '../../../shared/ghost.js';
+import type { GhostInstallConsentRequest } from '../../../shared/ghostInstallConsent.js';
+
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+
+import {
+ buildGhostInstallConsentInteraction,
+ createTaskInstallConsentPrompt,
+ renderGhostInstallConsentText,
+} from '../ghostInstallConsentInteraction.js';
+
+const HOST: GhostPermissionItem = {
+ key: 'network:host:api.weather.test',
+ kind: 'network',
+ labelKey: 'networkHost',
+ labelArgs: { host: 'api.weather.test' },
+};
+
+const OAUTH: GhostPermissionItem = {
+ key: 'network:secret:github',
+ kind: 'network',
+ labelKey: 'networkSecretOauth',
+ labelArgs: { name: 'GitHub', host: 'github.com' },
+ detailKey: 'networkSecretOauthDetail',
+ detail: 'repo\nread:user',
+};
+
+const STRINGS: Record<string, string> = {
+ 'settings.ghosts.installConsent.installTitle': 'Install {{name}}?',
+ 'settings.ghosts.installConsent.updateTitle': 'Update {{name}}?',
+ 'settings.ghosts.installConsent.installMeta': 'v{{version}} · {{source}}',
+ 'settings.ghosts.installConsent.updateMeta': 'v{{from}} → v{{to}} · {{source}}',
+ 'settings.ghosts.installConsent.installDescription': 'Confirm to install.',
+ 'settings.ghosts.installConsent.updateDescription': 'Needs more permissions.',
+ 'settings.ghosts.installConsent.grantsTitle': 'It will have:',
+ 'settings.ghosts.installConsent.addedTitle': 'Added:',
+ 'settings.ghosts.installConsent.unchangedCount': 'Unchanged: {{count}}',
+ 'settings.ghosts.installConsent.originMarket': 'From market',
+ 'settings.ghosts.installConsent.originForge': 'Local plugin',
+ 'settings.ghosts.installConsent.initiatedByAgent': 'Agent · {{origin}}',
+ 'settings.ghosts.perm.networkHost': 'Reach {{host}}',
+ 'settings.ghosts.perm.networkSecretOauth': 'Connect {{name}} ({{host}})',
+ 'settings.ghosts.perm.networkSecretOauthDetail': 'Requested scopes:',
+};
+const translate = (key: string) => STRINGS[key] ?? key;
+
+const INSTALL: Omit<GhostInstallConsentRequest, 'requestId'> = {
+ initiator: 'agent',
+ origin: 'market',
+ facts: { kind: 'install', ghostId: 'weather-chip', name: 'Weather', version: '1.0.0', permissions: [HOST] },
+};
+
+describe('plugin install confirmation card', () => {
+ it('renders the source on the first line and the permission list below', () => {
+ expect(renderGhostInstallConsentText(INSTALL, translate)).toEqual({
+ title: 'Install Weather?',
+ description: 'v1.0.0 · Agent · From market\nConfirm to install.\nIt will have:\n• Reach api.weather.test',
+ });
+ });
+
+ it('shows only what changes for an update', () => {
+ const text = renderGhostInstallConsentText(
+ {
+ initiator: 'agent',
+ origin: 'forge',
+ facts: {
+ kind: 'update', ghostId: 'weather-chip', name: 'Weather', version: '2.0.0',
+ previousVersion: '1.0.0', added: [HOST], removed: [], unchangedCount: 2,
+ builtinOauthClientChanged: false,
+ },
+ },
+ translate,
+ );
+ expect(text.title).toBe('Update Weather?');
+ expect(text.description.split('\n')).toEqual([
+ 'v1.0.0 → v2.0.0 · Agent · Local plugin',
+ 'Needs more permissions.',
+ 'Added:',
+ '• Reach api.weather.test',
+ 'Unchanged: 2',
+ ]);
+ });
+
+ it('includes host detail keys and author detail such as OAuth scopes', () => {
+ const text = renderGhostInstallConsentText(
+ {
+ initiator: 'agent',
+ origin: 'market',
+ facts: {
+ kind: 'update',
+ ghostId: 'weather-chip',
+ name: 'Weather',
+ version: '2.0.0',
+ previousVersion: '1.0.0',
+ added: [OAUTH],
+ removed: [],
+ unchangedCount: 0,
+ builtinOauthClientChanged: false,
+ },
+ },
+ translate,
+ );
+ expect(text.description.split('\n')).toEqual([
+ 'v1.0.0 → v2.0.0 · Agent · From market',
+ 'Needs more permissions.',
+ 'Added:',
+ '• Connect GitHub (github.com)',
+ ' Requested scopes:',
+ ' repo',
+ ' read:user',
+ ]);
+ });
+
+ it('is a host-owned permission request without session-wide allow suggestions', () => {
+ const request = buildGhostInstallConsentInteraction('req-1', INSTALL, translate);
+ expect(request).toMatchObject({
+ kind: 'permission',
+ requestId: 'req-1',
+ toolName: 'cindy.plugin.install',
+ input: { ghost_id: 'weather-chip', version: '1.0.0' },
+ metadata: { hostOwnedConfirmation: 'plugin_install' },
+ });
+ expect(request.suggestions).toBeUndefined();
+ });
+});
+
+describe('createTaskInstallConsentPrompt', () => {
+ const task = { sessionId: 'session-1', sessionInstanceId: 'instance-1' };
+
+ it('maps allow and deny from the task card', async () => {
+ const allow = createTaskInstallConsentPrompt(task, async () => ({ kind: 'permission', behavior: 'allow' }));
+ await expect(allow(INSTALL)).resolves.toBe(true);
+ const deny = createTaskInstallConsentPrompt(task, async () => ({
+ kind: 'permission', behavior: 'deny', reason: 'User denied',
+ }));
+ await expect(deny(INSTALL)).resolves.toBe(false);
+ });
+
+ it('sends the confirmation card to the calling task', async () => {
+ const requester = vi.fn(async () => ({ kind: 'permission' as const, behavior: 'allow' as const }));
+ await createTaskInstallConsentPrompt(task, requester)(INSTALL);
+ expect(requester).toHaveBeenCalledWith(
+ 'session-1',
+ 'instance-1',
+ expect.objectContaining({ toolName: 'cindy.plugin.install' }),
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('fails closed when the card never reached the user', async () => {
+ await expect(createTaskInstallConsentPrompt(null, vi.fn())(INSTALL)).rejects.toThrow();
+ await expect(createTaskInstallConsentPrompt(task, undefined)(INSTALL)).rejects.toThrow();
+ await expect(createTaskInstallConsentPrompt(task, async () => null)(INSTALL)).rejects.toThrow();
+ await expect(
+ createTaskInstallConsentPrompt(task, async () => ({
+ kind: 'permission', behavior: 'deny', reason: 'no_interaction_route',
+ }))(INSTALL),
+ ).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentWindowBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentWindowBridge.test.ts
new file mode 100644
index 0000000000..8316e57bee
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsentWindowBridge.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { GhostInstallConsentRequest } from '../../../shared/ghostInstallConsent.js';
+import { GhostInstallConsentWindowBridge } from '../ghostInstallConsentWindowBridge.js';
+
+vi.mock('../../maker-ipc/hostConfirmTiming.js', () => ({ HOST_CONFIRM_TIMEOUT_MS: 60_000 }));
+
+const REQUEST: Omit<GhostInstallConsentRequest, 'requestId'> = {
+ initiator: 'user',
+ origin: 'market',
+ facts: { kind: 'install', ghostId: 'weather-chip', name: 'Weather', version: '1.0.0', permissions: [] },
+};
+
+function target(id: number, delivered = true) {
+ const sent: GhostInstallConsentRequest[] = [];
+ const dismissed: string[] = [];
+ return {
+ sent,
+ dismissed,
+ target: {
+ id,
+ send: (request: GhostInstallConsentRequest) => {
+ sent.push(request);
+ return delivered;
+ },
+ dismiss: (requestId: string) => dismissed.push(requestId),
+ },
+ };
+}
+
+describe('GhostInstallConsentWindowBridge', () => {
+ it('only accepts the answer from the window that started the install', async () => {
+ const bridge = new GhostInstallConsentWindowBridge();
+ const window = target(7);
+ const pending = bridge.request(window.target, REQUEST);
+ const requestId = window.sent[0]!.requestId;
+ expect(bridge.resolve(8, requestId, true)).toBe(false);
+ expect(bridge.resolve(7, requestId, true)).toBe(true);
+ await expect(pending).resolves.toBe(true);
+ expect(window.dismissed).toEqual([requestId]);
+ expect(bridge.pendingCount).toBe(0);
+ });
+
+ it('treats a malformed answer, a closed window or an account switch as cancel', async () => {
+ const bridge = new GhostInstallConsentWindowBridge();
+ const a = target(1);
+ const b = target(2);
+ const c = target(3);
+ const malformed = bridge.request(a.target, REQUEST);
+ bridge.resolve(1, a.sent[0]!.requestId, 'yes');
+ await expect(malformed).resolves.toBe(false);
+ const closed = bridge.request(b.target, REQUEST);
+ bridge.cancelRequester(2);
+ await expect(closed).resolves.toBe(false);
+ const boundary = bridge.request(c.target, REQUEST);
+ bridge.cancelAll();
+ await expect(boundary).resolves.toBe(false);
+ expect(c.dismissed).toHaveLength(1);
+ });
+
+ it('times out as cancel and asks the window to close the dialog', async () => {
+ vi.useFakeTimers();
+ try {
+ const bridge = new GhostInstallConsentWindowBridge({ timeoutMs: 1000 });
+ const window = target(4);
+ const pending = bridge.request(window.target, REQUEST);
+ vi.advanceTimersByTime(1000);
+ await expect(pending).resolves.toBe(false);
+ expect(window.dismissed).toEqual([window.sent[0]!.requestId]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('fails closed when the window cannot receive the request', async () => {
+ const bridge = new GhostInstallConsentWindowBridge();
+ await expect(bridge.request(target(5, false).target, REQUEST)).rejects.toThrow();
+ expect(bridge.pendingCount).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index e8e426201d..cfe8e456c5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -50,7 +50,24 @@ describe('market Ghost session boundary', () => {
const afterCommitBody = installBody.slice(afterCommitStart, afterCommitEnd);
expect(afterCommitBody).toContain('this.withCapturedLedgerMutation(ledger, () => {');
expect(afterCommitBody).not.toContain('requireSameMarketOwner(');
- expect(automaticBody).toContain(' true,\n owner,\n );');
+ expect(automaticBody).toContain(" { mode: 'automatic' },\n owner,\n );");
+ });
+
+ it('releases the custom-source cache lease before waiting for install consent', () => {
+ const installStart = marketServiceSource.indexOf(' private async customInstall(');
+ const installEnd = marketServiceSource.indexOf(
+ '\n private async installDetail(',
+ installStart,
+ );
+ const installBody = marketServiceSource.slice(installStart, installEnd);
+ const lease = installBody.indexOf('manager.withDiscoveredSource(');
+ const pack = installBody.indexOf('packCustomMarketPlugin(');
+ const consent = installBody.indexOf('obtainGhostInstallConsent(');
+ expect(lease).toBeGreaterThan(-1);
+ expect(pack).toBeGreaterThan(lease);
+ expect(consent).toBeGreaterThan(pack);
+ expect(installBody.slice(lease, consent)).toContain('packCustomMarketPlugin(');
+ expect(installBody.slice(consent)).not.toContain('withDiscoveredSource(');
});
it('keeps package placement and market ledger commit in the same owner lease', () => {
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 010955c086..10cddcd277 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -11,7 +11,7 @@
* 调用方(mcp-integrations 接线)处理,本文件不碰 UI。
*
* 安全边界:agent 能写意识源码(它本来就有文件工具),但打包与装入都必须过
- * 同一套清单/真实包校验;安装动作本身不另设能力确认弹窗。
+ * 同一套清单/真实包校验;首装与权限变多的更新还要用户在任务里确认(ghostInstallConsent.ts)。
*/
import fs from 'node:fs';
@@ -1563,12 +1563,15 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册
读透相关章(动手前至少读完"沙箱红线"与"打包与测试"两章) → 在工作目录写源码文件 →
ghost_forge_pack 校验并生成 .cindy 产物;需要发布时改用 publish intent 取得一次性票据。**
-**安装与更新契约**:用户导入本地 \`.cindy\`、点击市场安装,或插件命中
-服务端 \`defaultInstall\`,都是明确的安装依据;
-Cindy 校验真实包后直接安装并启用,不再追加整张能力确认弹窗。唯一的窄确认是:企业作者
+**安装与更新契约**:用户导入本地 \`.cindy\`、点击市场安装、明确要求 Agent 安装,或插件命中
+服务端 \`defaultInstall\`,都是明确的安装依据。Cindy 校验真实包后,首次安装会先列出插件声明的
+全部权限请用户确认(Agent 发起的安装在任务里弹确认卡,不论任务权限档),确认后安装并启用;
+更新只在新版本比已装版本权限变多时请用户确认,权限没变多的更新直接完成。服务端
+\`defaultInstall\` 下发的插件不弹确认。另有一道窄确认:企业作者
用 \`ghost_forge_install\` 安装声明了 \`oidc-token\` 的包时,需核对 id 与注入域名。市场安装会绑定所选来源,
-此后的新版本由 Cindy 静默更新并保留当前启用状态;本地 \`.cindy\` 不自动猜测更新来源,
-需要用户再次导入新版包。当前组织的默认插件可能在严格核对组织、前缀、批准、退订与来源后,
+此后权限没变多的新版本由 Cindy 静默更新并保留当前启用状态;权限变多的新版本会暂停自动更新,
+等用户在插件页确认,在此之前旧版本照常可用。所以发布新版时不要顺手扩大权限,确需新增的在更新
+说明里讲清楚。本地 \`.cindy\` 不自动猜测更新来源,需要用户再次导入新版包。当前组织的默认插件可能在严格核对组织、前缀、批准、退订与来源后,
接管同 id 的普通本地导入;明确通过 \`ghost_forge_install\` 安装或更新的作者自测包会被保护,
不会被这条自动接管路径覆盖。插件自主 Host 能力仍必须完整声明,插件详情会如实展示,Host 运行时按声明
强制守门;市场下载包若超出该版本市场清单声明的能力,会作为包内容不一致被拒绝。
@@ -4689,8 +4692,10 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件
若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
按上一步迁出源码后再打包;未获会话权限时也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`;
3. 用户明确要求当前 Agent 安装或更新这份源码时,调用
- \`ghost_forge_install({ dir: '<绝对路径>' })\`。它会重新校验并打包当前源码,再把这次
- 产生的确切包直接安装;首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、
+ \`ghost_forge_install({ dir: '<绝对路径>' })\`。它会重新校验并打包当前源码,再安装这次
+ 产生的确切包:首次安装、以及权限比已装版本变多的更新,会先在任务里弹确认卡列出权限,
+ 用户允许后才落位;用户拒绝返回 \`MUTATION_CANCELLED\`,不要重试,除非用户再次要求。
+ 首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、
数据与面板位置,同版本也可覆盖。不要因为 scaffold 或 pack 成功就自动调用本工具。
企业身份下若清单声明 \`source:"oidc-token"\`,提交安装前会展示插件名、id 与精确请求
域名,并要求用户手输相同 id;取消不会安装。个人与企业身份下的明确 Forge 安装都会标记为
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
new file mode 100644
index 0000000000..8dd2ddc397
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
@@ -0,0 +1,162 @@
+/**
+ * 插件安装/更新的用户确认(docs/dev-rules/plugin-security-and-authoring.md §3.1)。
+ *
+ * 两段式,缺一不可:
+ * 1. `obtainGhostInstallConsent` 在任何安装锁之外按策略求得确认——弹窗可能等几分钟,
+ * 不能卡住其它插件的安装、卸载或自动更新;
+ * 2. `assertGhostInstallConsent` 在安装锁内、落位前,用真实包、当前受体与确认前
+ * 钉住的包摘要重算一次。确认后权限面、已装版本或包字节变了,就不能沿用这次确认。
+ *
+ * 每条安装路径都必须显式交出一个策略:用户或 Agent 发起的安装走 `prompt`,后台自动
+ * 更新走 `automatic`(需要确认就跳过,不替用户点头),只有服务端默认安装走 `exempt`。
+ */
+import type { GhostManifest, InstalledGhost } from '../../shared/ghost.js';
+import {
+ evaluateGhostInstallConsent,
+ ghostInstallConsentKey,
+ ghostInstallConsentReceiverIdentity,
+ type GhostInstallConsentFacts,
+ type GhostInstallConsentInitiator,
+ type GhostInstallConsentOrigin,
+ type GhostInstallConsentRequest,
+} from '../../shared/ghostInstallConsent.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** 向用户展示确认并等待回答;true = 用户确认安装。 */
+export type GhostInstallConsentPrompt = (
+ request: Omit<GhostInstallConsentRequest, 'requestId'>,
+) => Promise<boolean>;
+
+export type GhostInstallConsentPolicy =
+ | {
+ mode: 'prompt';
+ prompt: GhostInstallConsentPrompt;
+ initiator: GhostInstallConsentInitiator;
+ origin: GhostInstallConsentOrigin;
+ originLabel?: string;
+ }
+ /** 后台自动更新:不能弹窗,需要确认时抛 `GhostInstallConsentRequiredError`。 */
+ | { mode: 'automatic' }
+ /** 服务端默认安装的插件:首装与后续更新都由下发方决定,不向用户确认。 */
+ | { mode: 'exempt'; reason: 'server-default-install' };
+
+/** 求得的确认结论;随安装请求一路交到安装锁内复核。 */
+export type GhostInstallConsentDecision =
+ | { mode: 'confirmed'; key: string }
+ /** 求确认时判定无需确认;落位前必须仍然无需确认。 */
+ | { mode: 'unprompted' }
+ | { mode: 'exempt'; reason: 'server-default-install' };
+
+const pendingPromptAborts = new Set<AbortController>();
+
+/**
+ * 登记一次等待中的确认,账号边界时由 `abortAllGhostInstallConsentPrompts` 一并取消。
+ * 确认不得占用 owner 租约;取消是为了让等待中的安装调用尽快按用户取消收口。
+ * 返回的函数在确认结束后注销。
+ */
+export function trackGhostInstallConsentPrompt(controller: AbortController): () => void {
+ pendingPromptAborts.add(controller);
+ return () => {
+ pendingPromptAborts.delete(controller);
+ };
+}
+
+export function abortAllGhostInstallConsentPrompts(): void {
+ for (const controller of Array.from(pendingPromptAborts)) controller.abort();
+ pendingPromptAborts.clear();
+}
+
+/** 后台路径遇到需要用户确认的安装/更新。调用方据此跳过,而不是记为失败。 */
+export class GhostInstallConsentRequiredError extends Error {
+ readonly code = 'PRECONDITION_FAILED' as const;
+
+ constructor(readonly facts: GhostInstallConsentFacts) {
+ super(
+ facts.kind === 'install'
+ ? 'Plugin installation requires user confirmation'
+ : 'Plugin update adds permissions and requires user confirmation',
+ );
+ this.name = 'GhostInstallConsentRequiredError';
+ }
+}
+
+export function isGhostInstallConsentRequiredError(
+ error: unknown,
+): error is GhostInstallConsentRequiredError {
+ return error instanceof GhostInstallConsentRequiredError;
+}
+
+/**
+ * 按策略求得确认。`packageSha256` 必须是确认前已核验的那份包摘要;用户拒绝抛
+ * `MUTATION_CANCELLED`;确认界面不可用时 fail closed 抛 `PRECONDITION_FAILED`;
+ * 后台路径需要确认时抛 `GhostInstallConsentRequiredError`。
+ */
+export async function obtainGhostInstallConsent(
+ policy: GhostInstallConsentPolicy,
+ installed: InstalledGhost | null | undefined,
+ manifest: GhostManifest,
+ packageSha256: string,
+): Promise<GhostInstallConsentDecision> {
+ if (policy.mode === 'exempt') return { mode: 'exempt', reason: policy.reason };
+ const facts = evaluateGhostInstallConsent(installed, manifest);
+ if (!facts) return { mode: 'unprompted' };
+ if (policy.mode === 'automatic') throw new GhostInstallConsentRequiredError(facts);
+ let confirmed: boolean;
+ try {
+ confirmed = await policy.prompt({
+ initiator: policy.initiator,
+ origin: policy.origin,
+ ...(policy.originLabel ? { originLabel: policy.originLabel } : {}),
+ facts,
+ });
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', '当前无法显示插件安装确认,请稍后重试');
+ }
+ if (!confirmed) {
+ throwIpcError(
+ 'MUTATION_CANCELLED',
+ facts.kind === 'install' ? '用户取消了插件安装' : '用户取消了插件更新',
+ );
+ }
+ return {
+ mode: 'confirmed',
+ key: ghostInstallConsentKey(
+ facts,
+ packageSha256,
+ ghostInstallConsentReceiverIdentity(installed),
+ ),
+ };
+}
+
+/**
+ * 安装锁内、落位前的同步复核。`installedNow` 必须是锁内现读的已装插件,
+ * `manifest` 与 `packageSha256` 必须来自即将落位的那份真实包。
+ */
+export function assertGhostInstallConsent(
+ decision: GhostInstallConsentDecision,
+ installedNow: InstalledGhost | null | undefined,
+ manifest: GhostManifest,
+ packageSha256: string,
+): void {
+ if (decision.mode === 'exempt') return;
+ const facts = evaluateGhostInstallConsent(installedNow, manifest);
+ if (!facts) {
+ // 只有原本判定无需确认的决策,才能在落位时仍然无需确认。用户确认过的更新
+ // 若受体已被换成权限已覆盖候选包的版本,必须按过期拒绝,不能沿用这次确认。
+ if (decision.mode === 'unprompted') return;
+ throwIpcError('PRECONDITION_FAILED', '插件内容在确认后发生了变化,请重新安装');
+ }
+ if (
+ decision.mode === 'confirmed' &&
+ decision.key ===
+ ghostInstallConsentKey(
+ facts,
+ packageSha256,
+ ghostInstallConsentReceiverIdentity(installedNow),
+ )
+ ) {
+ return;
+ }
+ if (decision.mode === 'unprompted') throw new GhostInstallConsentRequiredError(facts);
+ throwIpcError('PRECONDITION_FAILED', '插件内容在确认后发生了变化,请重新安装');
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsentInteraction.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsentInteraction.ts
new file mode 100644
index 0000000000..f6cab83d9f
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsentInteraction.ts
@@ -0,0 +1,188 @@
+/**
+ * Agent 发起的插件安装/更新确认,投成任务里的宿主权限确认卡。
+ *
+ * 复用通用 `permission` 交互(hostOwnedConfirmation 标记),因此桌面对话、手机远控和
+ * IM 渠道卡都能直接显示「允许/拒绝」,旧版手机也不需要升级;它由 Main 主动发起,
+ * 不经 Agent 自身的审批回调,Full Access 也跳不过。
+ *
+ * 文案在 Main 侧按当前界面语言渲染成纯文本:第一行是版本与来源,其后是权限清单。
+ * 手机按原样逐行显示;桌面卡片把第一行作为说明、其余放进可滚动的操作区。
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+
+import type { GhostPermissionItem } from '../../shared/ghost.js';
+import {
+ GHOST_INSTALL_CONSENT_TOOL_NAME,
+ type GhostInstallConsentRequest,
+} from '../../shared/ghostInstallConsent.js';
+import { t as mainTranslate } from '../i18n.js';
+import {
+ trackGhostInstallConsentPrompt,
+ type GhostInstallConsentPrompt,
+} from './ghostInstallConsent.js';
+
+export const GHOST_INSTALL_CONSENT_HOST_CONFIRMATION = 'plugin_install';
+
+type Translate = (key: string) => string;
+
+function interpolate(template: string, args: Record<string, string> | undefined): string {
+ if (!args) return template;
+ return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (match, name: string) =>
+ Object.prototype.hasOwnProperty.call(args, name) ? args[name]! : match,
+ );
+}
+
+function consentText(translate: Translate, key: string, args?: Record<string, string>): string {
+ return interpolate(translate(`settings.ghosts.installConsent.${key}`), args);
+}
+
+/** 来源说明:包从哪里来,Agent 发起时再标明发起方。桌面确认框与任务卡共用。 */
+export function ghostInstallConsentSourceText(
+ translate: Translate,
+ request: Pick<GhostInstallConsentRequest, 'initiator' | 'origin' | 'originLabel'>,
+): string {
+ const origin =
+ request.origin === 'market'
+ ? consentText(translate, 'originMarket')
+ : request.origin === 'custom-market'
+ ? request.originLabel
+ ? consentText(translate, 'originCustomMarket', { name: request.originLabel })
+ : consentText(translate, 'originCustomMarketUnnamed')
+ : request.origin === 'local-file'
+ ? consentText(translate, 'originLocalFile')
+ : consentText(translate, 'originForge');
+ return request.initiator === 'agent'
+ ? consentText(translate, 'initiatedByAgent', { origin })
+ : origin;
+}
+
+function permissionLine(translate: Translate, item: GhostPermissionItem): string {
+ const lines = [
+ `• ${interpolate(translate(`settings.ghosts.perm.${item.labelKey}`), item.labelArgs)}`,
+ ];
+ if (item.detailKey) {
+ lines.push(
+ ` ${interpolate(translate(`settings.ghosts.perm.${item.detailKey}`), item.detailArgs)}`,
+ );
+ }
+ if (item.detail) {
+ for (const detailLine of item.detail.split('\n')) {
+ lines.push(` ${detailLine}`);
+ }
+ }
+ return lines.join('\n');
+}
+
+/** 把一次确认渲染成标题、首行说明与权限清单(纯文本)。 */
+export function renderGhostInstallConsentText(
+ request: Omit<GhostInstallConsentRequest, 'requestId'>,
+ translate: Translate = mainTranslate,
+): { title: string; description: string } {
+ const { facts } = request;
+ const source = ghostInstallConsentSourceText(translate, request);
+ const lines: string[] = [];
+ if (facts.kind === 'install') {
+ lines.push(consentText(translate, 'installMeta', { version: facts.version, source }));
+ lines.push(consentText(translate, 'installDescription'));
+ if (facts.permissions.length === 0) {
+ lines.push(consentText(translate, 'noPermissions'));
+ } else {
+ lines.push(consentText(translate, 'grantsTitle'));
+ for (const item of facts.permissions) lines.push(permissionLine(translate, item));
+ }
+ return {
+ title: consentText(translate, 'installTitle', { name: facts.name }),
+ description: lines.join('\n'),
+ };
+ }
+ lines.push(
+ consentText(translate, 'updateMeta', { from: facts.previousVersion, to: facts.version, source }),
+ );
+ lines.push(consentText(translate, 'updateDescription'));
+ if (facts.builtinOauthClientChanged) lines.push(consentText(translate, 'oauthClientChanged'));
+ if (facts.added.length > 0) {
+ lines.push(consentText(translate, 'addedTitle'));
+ for (const item of facts.added) lines.push(permissionLine(translate, item));
+ }
+ if (facts.removed.length > 0) {
+ lines.push(consentText(translate, 'removedTitle'));
+ for (const item of facts.removed) lines.push(permissionLine(translate, item));
+ }
+ if (facts.unchangedCount > 0) {
+ lines.push(consentText(translate, 'unchangedCount', { count: String(facts.unchangedCount) }));
+ }
+ return {
+ title: consentText(translate, 'updateTitle', { name: facts.name }),
+ description: lines.join('\n'),
+ };
+}
+
+/** 构造投给任务的宿主权限确认卡。不带会话级「总是允许」建议,每次都要用户点头。 */
+export function buildGhostInstallConsentInteraction(
+ requestId: string,
+ request: Omit<GhostInstallConsentRequest, 'requestId'>,
+ translate: Translate = mainTranslate,
+): Extract<InteractionRequest, { kind: 'permission' }> {
+ const text = renderGhostInstallConsentText(request, translate);
+ return {
+ kind: 'permission',
+ requestId,
+ toolName: GHOST_INSTALL_CONSENT_TOOL_NAME,
+ input: { ghost_id: request.facts.ghostId, version: request.facts.version },
+ title: text.title,
+ description: text.description,
+ metadata: { hostOwnedConfirmation: GHOST_INSTALL_CONSENT_HOST_CONFIRMATION },
+ };
+}
+
+/** 向指定任务投宿主权限确认卡并等待回答;会话不存在或实例不匹配返回 null。 */
+export type HostPermissionRequester = (
+ sessionId: string,
+ sessionInstanceId: string,
+ request: Extract<InteractionRequest, { kind: 'permission' }>,
+ signal: AbortSignal,
+) => Promise<InteractionDecision | null>;
+
+/** 路由不存在或处理失败:确认根本没送到用户面前,不能当成用户拒绝。 */
+const INSTALL_CONSENT_UNDELIVERED_REASONS = new Set([
+ 'no_interaction_route',
+ 'interaction_handler_failed',
+ 'duplicate_request_id',
+]);
+
+/**
+ * Agent 发起的插件安装/更新确认:投给调用所在的任务,桌面、手机远控与 IM 渠道卡
+ * 都能处理。缺任务语境或宿主未注入时 fail closed,由调用方按「无法显示确认」收口。
+ */
+export function createTaskInstallConsentPrompt(
+ task: { sessionId: string; sessionInstanceId: string } | null,
+ requestHostPermission: HostPermissionRequester | undefined,
+): GhostInstallConsentPrompt {
+ return async (request) => {
+ if (!task || !requestHostPermission) {
+ throw new Error('Plugin install confirmation requires the calling task');
+ }
+ const controller = new AbortController();
+ const untrack = trackGhostInstallConsentPrompt(controller);
+ try {
+ const decision = await requestHostPermission(
+ task.sessionId,
+ task.sessionInstanceId,
+ buildGhostInstallConsentInteraction(randomUUID(), request),
+ controller.signal,
+ );
+ if (!decision || decision.kind !== 'permission') {
+ throw new Error('The calling task is no longer active');
+ }
+ if (decision.behavior === 'allow') return true;
+ if (decision.reason && INSTALL_CONSENT_UNDELIVERED_REASONS.has(decision.reason)) {
+ throw new Error(`Plugin install confirmation was not delivered: ${decision.reason}`);
+ }
+ return false;
+ } finally {
+ untrack();
+ }
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts
new file mode 100644
index 0000000000..177168f3c4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts
@@ -0,0 +1,94 @@
+/**
+ * 用户在插件页、拖入或双击 `.cindy` 发起安装时的窗口级确认往返。
+ *
+ * 确认只投给发起安装的那个窗口(按 webContents id 绑定),也只接受那个窗口的回答;
+ * 窗口销毁、导航、账号边界或超时都按取消结算,并通知窗口收起还开着的确认框。
+ * Agent 发起的安装不走这里,走任务里的宿主权限确认卡(可在手机上确认)。
+ *
+ * 本模块不依赖 Electron,发送函数由 index.ts 注入,便于单测。
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { GhostInstallConsentRequest } from '../../shared/ghostInstallConsent.js';
+import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';
+
+export interface GhostInstallConsentWindowTarget {
+ /** webContents id;回答必须来自同一个 id。 */
+ id: number;
+ /** 投递确认请求;返回 false 表示窗口不可用。 */
+ send(request: GhostInstallConsentRequest): boolean;
+ /** 通知窗口收起指定确认框(已结算)。 */
+ dismiss(requestId: string): void;
+}
+
+interface PendingConsent {
+ target: GhostInstallConsentWindowTarget;
+ resolve: (confirmed: boolean) => void;
+ timeoutId: ReturnType<typeof setTimeout>;
+}
+
+export class GhostInstallConsentWindowBridge {
+ private readonly pending = new Map<string, PendingConsent>();
+
+ constructor(private readonly deps: { timeoutMs?: number } = {}) {}
+
+ request(
+ target: GhostInstallConsentWindowTarget,
+ request: Omit<GhostInstallConsentRequest, 'requestId'>,
+ ): Promise<boolean> {
+ const requestId = randomUUID();
+ return new Promise<boolean>((resolve, reject) => {
+ const timeoutId = setTimeout(
+ () => this.settle(requestId, false),
+ this.deps.timeoutMs ?? HOST_CONFIRM_TIMEOUT_MS,
+ );
+ this.pending.set(requestId, { target, resolve, timeoutId });
+ let delivered = false;
+ try {
+ delivered = target.send({ ...request, requestId });
+ } catch {
+ delivered = false;
+ }
+ if (!delivered) {
+ this.pending.delete(requestId);
+ clearTimeout(timeoutId);
+ reject(new Error('没有可显示安装确认的窗口'));
+ }
+ });
+ }
+
+ /** 返回是否命中本桥的待确认请求。只接受发起窗口的回答。 */
+ resolve(requesterId: number, requestId: string, confirmed: unknown): boolean {
+ const pending = this.pending.get(requestId);
+ if (!pending || pending.target.id !== requesterId) return false;
+ this.settle(requestId, confirmed === true);
+ return true;
+ }
+
+ cancelRequester(requesterId: number): void {
+ for (const [requestId, pending] of Array.from(this.pending.entries())) {
+ if (pending.target.id === requesterId) this.settle(requestId, false);
+ }
+ }
+
+ cancelAll(): void {
+ for (const requestId of Array.from(this.pending.keys())) this.settle(requestId, false);
+ }
+
+ get pendingCount(): number {
+ return this.pending.size;
+ }
+
+ private settle(requestId: string, confirmed: boolean): void {
+ const pending = this.pending.get(requestId);
+ if (!pending) return;
+ this.pending.delete(requestId);
+ clearTimeout(pending.timeoutId);
+ try {
+ pending.target.dismiss(requestId);
+ } catch {
+ // 窗口已销毁时无需再收起确认框。
+ }
+ pending.resolve(confirmed);
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 4a6d1ae813..8c46a25c73 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -302,6 +302,14 @@ import {
getForgeOidcInstallConfirmBridge,
initForgeOidcInstallConfirmBridge,
} from './forgeOidcInstallConfirmBridge.js';
+import {
+ abortAllGhostInstallConsentPrompts,
+ assertGhostInstallConsent,
+ obtainGhostInstallConsent,
+ type GhostInstallConsentDecision,
+ type GhostInstallConsentPrompt,
+} from './ghostInstallConsent.js';
+import { GhostInstallConsentWindowBridge } from './ghostInstallConsentWindowBridge.js';
import { GhostNetworkSlot } from './networkSlot.js';
import {
type ConnectionAudienceResolution,
@@ -1030,6 +1038,8 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {
getGhostGrantConfirmBridge()?.cleanupAll('session_aborted');
getGhostConfirmDialogBridge()?.cancelAll();
getForgeOidcInstallConfirmBridge()?.cancelAll();
+ installConsentWindowBridge.cancelAll();
+ abortAllGhostInstallConsentPrompts();
runtimeSingleton?.destroyAll();
resetNodeRuntimeBrokerForAccountBoundary();
// Drain in-flight staging.release (tombstone/fsync) before tearing Library
@@ -3066,6 +3076,53 @@ let confirmSlotSingleton: GhostConfirmSlot | null = null;
/** 意识确认弹窗通道(main → **单个**窗口;renderer 用主机同款 ConfirmDialog 渲染)。 */
export const GHOST_CONFIRM_CHANNEL = 'ghosts:confirm-request';
export const FORGE_OIDC_INSTALL_CONFIRM_CHANNEL = 'forge-oidc-install:confirm-request';
+/** 用户在窗口里发起安装时的确认请求与收起通知(main → 发起安装的那个窗口)。 */
+export const GHOST_INSTALL_CONSENT_REQUEST_CHANNEL = 'ghosts:install-consent:request';
+export const GHOST_INSTALL_CONSENT_DISMISSED_CHANNEL = 'ghosts:install-consent:dismissed';
+
+const installConsentWindowBridge = new GhostInstallConsentWindowBridge();
+const trackedInstallConsentRequesters = new WeakSet<WebContents>();
+
+function trackInstallConsentRequester(contents: WebContents): void {
+ if (trackedInstallConsentRequesters.has(contents)) return;
+ trackedInstallConsentRequesters.add(contents);
+ const requesterId = contents.id;
+ const cancelPending = (): void => installConsentWindowBridge.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();
+ });
+}
+
+/**
+ * 发起安装的受信窗口上的确认提示。确认框只投给这个窗口,也只接受它的回答;
+ * 调用方必须已经用 assertTrustedAppRendererEvent 核验过该 webContents。
+ */
+export function createWindowGhostInstallConsentPrompt(
+ contents: WebContents,
+): GhostInstallConsentPrompt {
+ return (request) => {
+ if (contents.isDestroyed()) return Promise.reject(new Error('窗口已关闭'));
+ trackInstallConsentRequester(contents);
+ const ownerStamp = getGhostOwnerPushStamp();
+ return installConsentWindowBridge.request(
+ {
+ id: contents.id,
+ send: (payload) => {
+ if (contents.isDestroyed()) return false;
+ sendGhostContentsPush(contents, GHOST_INSTALL_CONSENT_REQUEST_CHANNEL, payload, ownerStamp);
+ return true;
+ },
+ dismiss: (requestId) => {
+ if (contents.isDestroyed()) return;
+ sendGhostContentsPush(contents, GHOST_INSTALL_CONSENT_DISMISSED_CHANNEL, { requestId });
+ },
+ },
+ request,
+ );
+ };
+}
function ensureForgeOidcInstallConfirmBridge() {
return (
@@ -5792,7 +5849,12 @@ export async function installAndDock(
opts: {
ghostId: string;
enable?: boolean;
- expectedPackageSha256?: string;
+ expectedPackageSha256: string;
+ /**
+ * 锁外求得的用户确认与它所依据的 manifest(来自 expectedPackageSha256 钉住的
+ * 同一份包)。必填,与 ghostId 同理:新增装入路径无法忘记交出确认结论。
+ */
+ consent: { decision: GhostInstallConsentDecision; manifest: GhostManifest };
trustOverride?: GhostHostTrustOverride;
beforePackagePlacement?: () => void;
},
@@ -5806,19 +5868,26 @@ async function installAndDockLocked(
opts: {
ghostId: string;
enable?: boolean;
- expectedPackageSha256?: string;
+ expectedPackageSha256: string;
+ consent: { decision: GhostInstallConsentDecision; manifest: GhostManifest };
trustOverride?: GhostHostTrustOverride;
installOrigin?: 'agent-forge';
beforePackagePlacement?: () => void;
},
): Promise<InstalledGhost> {
+ // 确认依据的 manifest 必须就是 expectedPackageSha256 钉住的那份包;锁内现读受体
+ // 复核,确认后同 id 被别处装上或包内容变化都不能沿用这次确认。
+ assertGhostInstallConsent(
+ opts.consent.decision,
+ manager.list().find((ghost) => ghost.manifest.id === opts.ghostId),
+ opts.consent.manifest,
+ opts.expectedPackageSha256,
+ );
// 初始启用态由入口显式传入;当前用户导入与市场首装都传 true,覆盖更新
// 则走 manager.update 延续既有状态。保留 false 缺省以兼容内部受控调用方。
const result = await manager.install(lizFilePath, {
initiallyEnabled: opts.enable ?? false,
- ...(opts.expectedPackageSha256
- ? { expectedPackageSha256: opts.expectedPackageSha256 }
- : {}),
+ expectedPackageSha256: opts.expectedPackageSha256,
...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
...(opts.installOrigin ? { installOrigin: opts.installOrigin } : {}),
...(opts.beforePackagePlacement ? { beforePackagePlacement: opts.beforePackagePlacement } : {}),
@@ -5870,6 +5939,7 @@ async function updateLocalGhostPackageLocked(
inspected: InspectedGhostPackage,
expectedPackageSha256: string,
expectedInstalledApproval: string,
+ consent: GhostInstallConsentDecision,
installOrigin?: 'agent-forge',
isCurrent?: () => boolean,
): Promise<InstalledGhost> {
@@ -5881,6 +5951,8 @@ async function updateLocalGhostPackageLocked(
ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
);
const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
+ // 锁内按真实包与现读受体复核锁外求得的确认;熄灯之前拒绝,不打断正在用的旧版本。
+ assertGhostInstallConsent(consent, previousGhost, inspected.manifest, expectedPackageSha256);
runtime.stop(inspected.manifest.id);
// 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生
// 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。
@@ -5991,12 +6063,20 @@ async function updateLocalGhostPackageLocked(
}
/**
- * Forge 的显式安装入口。调用方在打包前已经取得 owner lease,并把它持有到本函数
- * 返回;这里复核精确包哈希,再与 Renderer 本地导入共用相同安装/更新事务。
+ * Forge 的显式安装入口。确认在 owner 租约外求得;落位前再取安装锁,并与
+ * Renderer 本地导入共用相同安装/更新事务。调用方必须先复核精确包哈希。
*/
export async function installOrUpdateLocalGhostPackageFromForge(
cindyFilePath: string,
- expected: { ghostId: string; packageSha256: string; isCurrent?: () => boolean },
+ expected: {
+ ghostId: string;
+ packageSha256: string;
+ /** 向发起安装的任务投确认卡;Agent 安装无论任务权限档都要用户确认。 */
+ consentPrompt: GhostInstallConsentPrompt;
+ /** packing 租约内捕获的 owner;确认与等锁都不持租约,落位前用这份身份取新租约。 */
+ mutationOwner: ActiveAppSession;
+ isCurrent?: () => boolean;
+ },
): Promise<{ ghost: InstalledGhost; action: 'installed' | 'updated' }> {
const manager = getGhostManager();
const inspected = await manager.inspect(cindyFilePath);
@@ -6018,6 +6098,13 @@ export async function installOrUpdateLocalGhostPackageFromForge(
inspected.manifest,
installOrigin ? { installOrigin } : undefined,
);
+ // 首装与扩权更新先在任务里请用户确认;权限没变多的更新不打扰。
+ const consent = await obtainGhostInstallConsent(
+ { mode: 'prompt', prompt: expected.consentPrompt, initiator: 'agent', origin: 'forge' },
+ manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id),
+ inspected.manifest,
+ inspected.packageSha256,
+ );
const confirmFacts = forgeOidcInstallConfirmFacts(inspected.manifest, membershipKind);
if (confirmFacts) {
let confirmed = false;
@@ -6038,37 +6125,45 @@ export async function installOrUpdateLocalGhostPackageFromForge(
if (expected.isCurrent?.() === false) {
throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
}
- const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
- if (!installed) {
+ // 确认已在 owner 租约外完成;落位再用 packing 时钉住的 owner 取租约。
+ const releaseMutation = beginGhostMutation(expected.mutationOwner);
+ try {
+ const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
+ if (!installed) {
+ return {
+ ghost: await installAndDockLocked(manager, cindyFilePath, {
+ ghostId: inspected.manifest.id,
+ enable: true,
+ expectedPackageSha256: expected.packageSha256,
+ consent: { decision: consent, manifest: inspected.manifest },
+ ...(installOrigin ? { installOrigin } : {}),
+ }).then((ghost) => {
+ try {
+ markGhostRecommendationInstalled(ghost.manifest.id);
+ } catch {
+ log.warn('ghost recommendation install history unavailable');
+ }
+ return ghost;
+ }),
+ action: 'installed',
+ };
+ }
return {
- ghost: await installAndDockLocked(manager, cindyFilePath, {
- ghostId: inspected.manifest.id,
- enable: true,
- expectedPackageSha256: expected.packageSha256,
- ...(installOrigin ? { installOrigin } : {}),
- }).then((ghost) => {
- try {
- markGhostRecommendationInstalled(ghost.manifest.id);
- } catch {
- log.warn('ghost recommendation install history unavailable');
- }
- return ghost;
- }),
- action: 'installed',
+ ghost: await updateLocalGhostPackageLocked(
+ manager,
+ cindyFilePath,
+ inspected,
+ expected.packageSha256,
+ ghostInstallApprovalToken(installed.approval),
+ consent,
+ installOrigin,
+ expected.isCurrent,
+ ),
+ action: 'updated',
};
+ } finally {
+ releaseMutation();
}
- return {
- ghost: await updateLocalGhostPackageLocked(
- manager,
- cindyFilePath,
- inspected,
- expected.packageSha256,
- ghostInstallApprovalToken(installed.approval),
- installOrigin,
- expected.isCurrent,
- ),
- action: 'updated',
- };
});
}
@@ -6113,6 +6208,11 @@ export async function installOrUpdateMarketGhostPackage(
) => void | Promise<void>;
/** 仅 server-market 主机路径可传;custom/local 不传。 */
officialCindyGithub?: boolean;
+ /**
+ * 调用方在锁外求得的用户确认结论(ghostInstallConsent.ts)。必填:市场首装、
+ * 手动更新、后台更新与服务端默认安装都必须显式交出,本函数在锁内按真实包复核。
+ */
+ consent: GhostInstallConsentDecision;
},
): Promise<InstalledGhost> {
// 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径
@@ -6141,6 +6241,7 @@ async function installOrUpdateMarketGhostPackageLocked(
evidence: MarketGhostPackageCommitEvidence,
) => void | Promise<void>;
officialCindyGithub?: boolean;
+ consent: GhostInstallConsentDecision;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -6213,8 +6314,14 @@ async function installOrUpdateMarketGhostPackageLocked(
: undefined,
);
- // Manifest 能力只用于 Host 注册、校验和运行时守门。用户点击安装后不再
- // 经过插件级权限确认;自定义活目录还必须通过上面的打包窗口一致性校验。
+ // 用户确认在锁外求得;这里用即将落位的真实包与锁内现读的受体复核,确认后
+ // 包内容或已装版本变了就拒绝,后台更新遇到需要确认的扩权直接放弃本轮。
+ assertGhostInstallConsent(
+ expected.consent,
+ installed,
+ inspected.manifest,
+ inspected.packageSha256,
+ );
// Hold the owner-stability lease only for the actual Ghost filesystem
// mutation.
releaseMutation = beginGhostMutation(mutationOwner);
@@ -6231,6 +6338,7 @@ async function installOrUpdateMarketGhostPackageLocked(
ghostId: expected.ghostId,
enable: true,
expectedPackageSha256: inspected.packageSha256,
+ consent: { decision: expected.consent, manifest: inspected.manifest },
beforePackagePlacement: expected.beforeCommitInLock,
...(trustOverride ? { trustOverride } : {}),
});
@@ -7157,6 +7265,24 @@ export function registerGhostIpc(): void {
return { handled: bridge.resolve(p.requestId, p.confirmed) };
});
+ // 安装/更新确认框的回答只认发起安装的那个窗口(按 webContents id 绑定)。
+ ipcMain.handle('ghosts:install-consent:resolve', async (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const p = raw as { requestId?: unknown; confirmed?: unknown } | null;
+ if (
+ !p ||
+ typeof p.requestId !== 'string' ||
+ p.requestId.length === 0 ||
+ p.requestId.length > 128 ||
+ typeof p.confirmed !== 'boolean'
+ ) {
+ throwIpcError('INVALID_PARAMS', 'invalid plugin install confirmation');
+ }
+ return {
+ handled: installConsentWindowBridge.resolve(event.sender.id, p.requestId, p.confirmed),
+ };
+ });
+
// ── 意识聊天卡片取件(卡槽③;宿主 renderer 历史回放用)──────────────
// 查询型 handler:无卡返回 { card: null },renderer 据此降级为通用媒体
// 渲染(远程会话/被 GC 的历史卡都走这条),不抛 NOT_FOUND——规则 13 的
@@ -7626,7 +7752,19 @@ export function registerGhostIpc(): void {
rejectReservedGhostId(probe.manifest.id);
rejectBrokerWithoutDeclaredRedirectPort(probe.manifest);
rejectUnauthorizedTokenBroker(probe.manifest);
- // Node 等高风险能力在插件详情中如实展示;安装事务不追加能力确认弹窗。
+ // 首装一律先在发起安装的窗口里请用户确认插件权限;确认在任何锁与 owner 租约
+ // 之外等待,落位前由 installAndDock 在锁内按同一份包复核。
+ const consent = await obtainGhostInstallConsent(
+ {
+ mode: 'prompt',
+ prompt: createWindowGhostInstallConsentPrompt(event.sender),
+ initiator: 'user',
+ origin: 'local-file',
+ },
+ manager.list().find((ghost) => ghost.manifest.id === probe.manifest.id),
+ probe.manifest,
+ probe.packageSha256,
+ );
const enable = installOpts?.enable === true;
// owner 租约在锁外整段持有(防中途 owner 切换把落位写进新 owner);按 ghostId 的
// 互斥锁由 installAndDock 自动获取(卡点),这里传 id 即可。二者语义不同,叠加保留。
@@ -7637,6 +7775,7 @@ export function registerGhostIpc(): void {
ghostId: probe.manifest.id,
enable,
expectedPackageSha256,
+ consent: { decision: consent, manifest: probe.manifest },
}).then((ghost) => {
try {
markGhostRecommendationInstalled(ghost.manifest.id);
@@ -7686,6 +7825,18 @@ export function registerGhostIpc(): void {
rejectReservedGhostId(inspected.manifest.id);
rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);
rejectUnauthorizedTokenBroker(inspected.manifest);
+ // 新版本权限变多时先请用户确认;权限没变多的更新不打扰。
+ const consent = await obtainGhostInstallConsent(
+ {
+ mode: 'prompt',
+ prompt: createWindowGhostInstallConsentPrompt(event.sender),
+ initiator: 'user',
+ origin: 'local-file',
+ },
+ manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id),
+ inspected.manifest,
+ inspected.packageSha256,
+ );
// 从熄灯到换版收尾整段持 owner 租约:熄灯之后每一步都在改"当前 owner"的插件世界,
// 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。租约在锁外,
// 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。
@@ -7700,6 +7851,7 @@ export function registerGhostIpc(): void {
inspected,
expectedPackageSha256,
expectedInstalledApproval,
+ consent,
),
),
};
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 7184742fc5..cecf976d06 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -179,12 +179,14 @@ async function freshCodexProxyHost() {
}
// CI 忙时本文件首次 import SUT 要付 Vitest transform 整个模块图的冷启动钱:Linux 分片
-// 实测超默认 5s,Windows 分片超 15s,继续抬单测超时只是把死亡线后推。这笔成本属于环境
-// 冷启动,不属于任何断言 —— 文件级 beforeAll 先把模块图焐热(hook 超时独立计),之后各
-// 用例里 resetModules + import 只剩模块求值开销,回到默认超时内。
+// 实测超默认 5s,Windows 分片超 15s。满载 Windows shard 2/2 曾在 60s 文件级 hook
+// 上超时(本文件不 import maker-host/index,与产品改动无关)。这笔成本属于环境
+// 冷启动,不属于任何断言 —— 文件级 beforeAll 先把模块图焐热(hook 超时独立计;
+// Windows 给 120s,其它平台仍 60s),之后各用例里 resetModules + import 只剩模块
+// 求值开销,回到默认超时内。
beforeAll(async () => {
await import('../codex-proxy-host.js');
-}, 60_000);
+}, process.platform === 'win32' ? 120_000 : 60_000);
/** 本地 403 拒绝的 localHandler:执行它并返回写出的状态码与响应体。 */
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 825e25fda2..f09e4a9f0f 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -36,6 +36,7 @@ import {
CodexAgent,
configureDefaultImageResizer,
type AgentKind,
+ type InteractionRequest,
type McpProvider,
} from '@cindy/maker-core';
import type { ProviderView } from '@cindy/model-providers';
@@ -72,6 +73,8 @@ import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import { getWorkerLink, updateWorkerStatus } from '../localDb/orcaTeamStore.js';
import { cleanupSessionTempAttachments } from '../maker-ipc/normalizeAttachments.js';
import { resolveGhostFsSessionSnapshot } from '../maker-ipc/ghostFsSessionSnapshot.js';
+import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';
+import { requestHostInteraction } from '../maker-ipc/interactionRouter.js';
import { markKnownOrcaWorkerSession } from '../maker-ipc/orcaManualInterrupt.js';
import { markOrcaMcpHydratedIfNeeded } from '../maker-ipc/orcaMcpHydrationCache.js';
import { preparePersistedOrcaSessionStart } from '../maker-ipc/orcaSessionStartOptions.js';
@@ -950,6 +953,20 @@ export function getMaker(): Maker {
reviewAction: snapshot?.reviewAction,
};
},
+ // 宿主主动发起的权限确认(如 Agent 安装插件):走与 Agent 权限请求相同的路由,
+ // 桌面、手机远控与 IM 渠道卡都能处理;早于 MCP 工具 10 分钟期限超时。
+ requestHostPermission: async (
+ sessionId: string,
+ sessionInstanceId: string,
+ request: Extract<InteractionRequest, { kind: 'permission' }>,
+ signal: AbortSignal,
+ ) => {
+ const session = _maker?.getSession(sessionId);
+ if (!session || session.instanceId !== sessionInstanceId) return null;
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(HOST_CONFIRM_TIMEOUT_MS)]);
+ return session.runHostInteraction(request, () =>
+ requestHostInteraction(session, request, bounded));
+ },
};
const orcaTeamStoreAdapter = createDesktopOrcaTeamStoreAdapter({
getWorkerLink,
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 40649b8048..aca3058e65 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -100,7 +100,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
title: "Plugins (extending what the agents can do)",
summary: "What plugins are, how to browse / install / enable / disable them, per-working-directory control, the permission model, and invoking one with a $command.",
tab: "ghosts",
- content: "Plugins (internally \"意识\" / Ghost) extend what the agents can do — they add AI-callable tools, dockable UI panels, and \"ask Cindy to make it\" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.\n\n**The Plugins page:**\n\n- Open it from the **Plugins** entry in the left sidebar.\n- Browse by origin: **all / built-in / team-shared / external**. The team-shared (enterprise) group only shows if your account belongs to an organization.\n- Each plugin has a detail page — that's where you enable it, connect an account / enter an API key, and read what it can do.\n\n**Built-in plugins that ship with the app:**\n\n- **Cindy Art** (`$cindy-art`) — generate and edit images and short videos.\n- **Cindy Web Search** (`$cindy-web-search`) — public web search (add your own Brave or Tavily key on its detail page).\n- **Cindy Mermaid** (`$cindy-mermaid`) — build / repair Mermaid diagrams.\n- **Cindy GitHub** (`$cindy-github`) / **Cindy GitLab** (`$cindy-gitlab`) — read / write issues, PRs / MRs, reviews, CI, releases.\n- **Filo Google** (`$filo-google`) — Gmail / Calendar / Drive / Sheets.\n\n**Enabling and disabling:**\n\n- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout position is remembered and restored when you re-enable it.\n- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.\n\n**Installing:**\n\n- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).\n- Choosing Install, dragging a package, or picking one from disk installs and enables the selected plugin directly. Installation does not add a permission or version-confirmation step; review its declared capabilities on the plugin detail page.\n- The server selects the release appropriate for this Cindy version before marketplace delivery. Desktop does not apply a second `minCindyVersion` gate; custom marketplaces and local `.cindy` packages follow the same install policy.\n- Updates from stable marketplace sources are applied automatically when the plugin is idle. Failed attempts retry later; you can still click Update to retry immediately.\n\n**Using a plugin with `$command`:**\n\n- Type its command at the **start** of a message — e.g. `$cindy-art a poster for…`. Only enabled plugins that declare that command match.\n- You don't have to use `$command`: the agents can also pick an enabled plugin's tools on their own when a task calls for it.\n\n**The permission / sandbox model (why plugins are safe):**\n\n- A plugin's sandbox has **no direct filesystem, network, or system access**. The host mediates every operation and enforces its actual execution context.\n- Autonomous/background plugin behavior must stay within the capabilities and scopes declared directly in its manifest. Whether an in-flight plugin tool runs is decided by the existing Agent authorization flow; network and working-directory operations bind to that call, while bundled code and CLIs continue to use the existing Node worker. Plugin authors do not need a client change or a manifest Slot to pre-register a specific command, host, or path.\n- **Autonomous network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into declared requests whose target matches that declaration.\n- Because of this, a plugin **can't see your files** on its own. A file reaches a plugin only when you or the agent explicitly hand one over (an image attachment, or a directory the host passes through after an ownership check).\n\n**Configuring a plugin's account / API key:**\n\n- Do it on the plugin's **detail page**. Plugins that use a key (web-search, GitHub/GitLab tokens) have a field there; the value goes straight into the host's encrypted store and can't be read back.\n- Plugins that use OAuth (for example Filo Google) show a **Connect account** button instead.\n\n**Notes:**\n\n- Enabling or disabling a plugin takes effect on the **next** agent query, not retroactively in the current turn.\n- Skills (`/` slash commands) and Plugins (`$` commands) are two tabs of the same management surface — see the Skills topic for skills.",
+ content: "Plugins (internally \"意识\" / Ghost) extend what the agents can do — they add AI-callable tools, dockable UI panels, and \"ask Cindy to make it\" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.\n\n**The Plugins page:**\n\n- Open it from the **Plugins** entry in the left sidebar.\n- Browse by origin: **all / built-in / team-shared / external**. The team-shared (enterprise) group only shows if your account belongs to an organization.\n- Each plugin has a detail page — that's where you enable it, connect an account / enter an API key, and read what it can do.\n\n**Built-in plugins that ship with the app:**\n\n- **Cindy Art** (`$cindy-art`) — generate and edit images and short videos.\n- **Cindy Web Search** (`$cindy-web-search`) — public web search (add your own Brave or Tavily key on its detail page).\n- **Cindy Mermaid** (`$cindy-mermaid`) — build / repair Mermaid diagrams.\n- **Cindy GitHub** (`$cindy-github`) / **Cindy GitLab** (`$cindy-gitlab`) — read / write issues, PRs / MRs, reviews, CI, releases.\n- **Filo Google** (`$filo-google`) — Gmail / Calendar / Drive / Sheets.\n\n**Enabling and disabling:**\n\n- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout position is remembered and restored when you re-enable it.\n- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.\n\n**Installing:**\n\n- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).\n- Choosing Install, dragging a package, or picking one from disk first shows a **confirmation dialog** listing everything the plugin declares it can do (network domains, credentials, background tasks, skills, bundled code, panels…). Nothing is installed until you confirm; after that the plugin is enabled right away.\n- When you ask an agent to install a plugin (`ghost_market_install` / `ghost_forge_install`), the same confirmation appears as a card in that task — whatever the task's permission mode, including Full Access. It also works from the phone when you control this computer remotely. If you deny it, nothing is installed.\n- Plugins pushed by your organization (server default installs) are installed and updated silently without a confirmation.\n- The server selects the release appropriate for this Cindy version before marketplace delivery. Desktop does not apply a second `minCindyVersion` gate; custom marketplaces and local `.cindy` packages follow the same install policy.\n- Updates from stable marketplace sources are applied automatically when the plugin is idle — **as long as the new version doesn't need more permissions**. If it does, the automatic update pauses, the old version keeps working, and the plugin card shows \"New permissions need confirmation\"; clicking Update shows the added permissions for you to confirm. Failed attempts retry later; you can still click Update to retry immediately.\n\n**Using a plugin with `$command`:**\n\n- Type its command at the **start** of a message — e.g. `$cindy-art a poster for…`. Only enabled plugins that declare that command match.\n- You don't have to use `$command`: the agents can also pick an enabled plugin's tools on their own when a task calls for it.\n\n**The permission / sandbox model (why plugins are safe):**\n\n- A plugin's sandbox has **no direct filesystem, network, or system access**. The host mediates every operation and enforces its actual execution context.\n- Autonomous/background plugin behavior must stay within the capabilities and scopes declared directly in its manifest. Whether an in-flight plugin tool runs is decided by the existing Agent authorization flow; network and working-directory operations bind to that call, while bundled code and CLIs continue to use the existing Node worker. Plugin authors do not need a client change or a manifest Slot to pre-register a specific command, host, or path.\n- **Autonomous network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into declared requests whose target matches that declaration.\n- Because of this, a plugin **can't see your files** on its own. A file reaches a plugin only when you or the agent explicitly hand one over (an image attachment, or a directory the host passes through after an ownership check).\n\n**Configuring a plugin's account / API key:**\n\n- Do it on the plugin's **detail page**. Plugins that use a key (web-search, GitHub/GitLab tokens) have a field there; the value goes straight into the host's encrypted store and can't be read back.\n- Plugins that use OAuth (for example Filo Google) show a **Connect account** button instead.\n\n**Notes:**\n\n- Enabling or disabling a plugin takes effect on the **next** agent query, not retroactively in the current turn.\n- Skills (`/` slash commands) and Plugins (`$` commands) are two tabs of the same management surface — see the Skills topic for skills.",
},
{
id: "providers",
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index b266980dec..d155b297a7 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -24,6 +24,7 @@ import type {
} from '../../cindy-brain/ghostSetupCoordinator';
import { t } from '../../i18n';
import type { CindyGhostsHostDeps } from '../ghost';
+import type { GhostInstallConsentPrompt } from '../../cindy-brain/ghostInstallConsent';
import type { InstalledGhost, GhostSetupAssessment } from '../../../shared/ghost';
const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-workdir-gate-'));
@@ -307,6 +308,7 @@ function makeDeps(
sessionInstanceId: string | null = sessionId ? `${sessionId}-instance` : null,
vendorOptions: Record<string, unknown> = {},
pluginMarket?: CindyGhostsHostDeps['pluginMarket'],
+ requestHostPermission?: CindyGhostsHostDeps['requestHostPermission'],
) {
const ctx = {
agentKind,
@@ -322,6 +324,7 @@ function makeDeps(
pluginMarket,
getAppVersion: appVersionMock,
getLiveSessionGrantState: liveGrantStateMock,
+ ...(requestHostPermission ? { requestHostPermission } : {}),
});
}
@@ -547,6 +550,9 @@ describe('Forge session workdir gate', () => {
expect(forgeInstallPackageMock).toHaveBeenCalledWith(cindyPath, {
ghostId: 'demo',
packageSha256: createHash('sha256').update(bytes).digest('hex'),
+ // Agent 安装的插件确认投给调用所在的任务。
+ consentPrompt: expect.any(Function),
+ mutationOwner: { mode: 'local', dataOwnerId: 'test', generation: 0 },
});
expect(result).toMatchObject({
ok: true,
@@ -557,6 +563,23 @@ describe('Forge session workdir gate', () => {
expect(completeForgePackStagingMock).not.toHaveBeenCalled();
});
+ it('releases the owner lease before waiting for install confirmation', async () => {
+ const waiting = new Promise<never>(() => undefined);
+ packGhostDirMock.mockResolvedValueOnce({
+ ok: true,
+ buf: Buffer.from('packed'),
+ cindyPath: path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy'),
+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },
+ });
+ forgeInstallPackageMock.mockImplementationOnce(() => waiting);
+
+ void makeDeps().forgeInstall({ dir: path.join(WORKDIR, 'plugin-src') });
+ await vi.waitFor(() => {
+ expect(forgeInstallPackageMock).toHaveBeenCalledOnce();
+ });
+ expect(releaseMutationMock).toHaveBeenCalledOnce();
+ });
+
it('does not suggest organization publishing to a personal account after default pack', async () => {
currentPublisherIdentityMock.mockReturnValueOnce(null);
packGhostDirMock.mockResolvedValueOnce({
@@ -2967,14 +2990,18 @@ it.each([false, true])('only marks a teammate setup plan as reauthorization with
});
describe('market install live authority', () => {
- function marketHarness(agentKind: TestAgentKind = 'claude-code') {
+ type InstallContext = { consent: { prompt: GhostInstallConsentPrompt; initiator: string }; assertCurrent?: () => void };
+ function marketHarness(
+ agentKind: TestAgentKind = 'claude-code',
+ requestHostPermission?: CindyGhostsHostDeps['requestHostPermission'],
+ ) {
const ghost = { manifest: { id: 'mail-suite', name: 'Mail', version: '1' }, enabled: true };
const market = {
snapshot: vi.fn(async () => ({ items: [], unavailableReason: null, customSourceNames: [], unavailableCustomSourceNames: [] })),
detail: vi.fn(async () => ({ ghostId: 'mail-suite', releaseId: 'r1', manifest: ghost.manifest })),
- install: vi.fn(async (_id: string, _options: unknown, guard?: () => void) => { guard?.(); return { ghost }; }),
+ install: vi.fn(async (_id: string, _options: unknown, context: InstallContext) => { context.assertCurrent?.(); return { ghost }; }),
};
- const deps = makeDeps(agentKind, 's1', 's1-instance', {}, market as unknown as CindyGhostsHostDeps['pluginMarket']);
+ const deps = makeDeps(agentKind, 's1', 's1-instance', {}, market as unknown as CindyGhostsHostDeps['pluginMarket'], requestHostPermission);
return { deps, market };
}
@@ -2985,7 +3012,8 @@ describe('market install live authority', () => {
expect(market.install).not.toHaveBeenCalled();
expect(await deps.installMarket!({ pluginId: 'p1', releaseId: 'r1' })).toMatchObject({ status: 'installed', ghost_id: 'mail-suite' });
expect(liveGrantStateMock).toHaveBeenCalledWith('s1', 's1-instance');
- expect(releaseMutationMock).toHaveBeenCalledOnce();
+ expect(acquireMutationLeaseMock).not.toHaveBeenCalled();
+ expect(releaseMutationMock).not.toHaveBeenCalled();
expect(authorizationRequestMock).not.toHaveBeenCalled();
expect(dispatchMock).not.toHaveBeenCalled();
});
@@ -2998,20 +3026,48 @@ describe('market install live authority', () => {
expect(acquireMutationLeaseMock).not.toHaveBeenCalled();
});
- it.each(['cancel', 'permission-change'])('rechecks %s at placement and releases the owner lease', async (change) => {
+ it.each(['cancel', 'permission-change'])('rechecks %s at placement without holding an owner lease', async (change) => {
let current = true;
const controller = new AbortController();
liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', isCurrent: () => current });
const { deps, market } = marketHarness();
const place = vi.fn();
- market.install.mockImplementation(async (_id, _options, guard) => {
+ market.install.mockImplementation(async (_id, _options, context) => {
if (change === 'cancel') controller.abort(); else current = false;
- guard?.(); place();
+ context.assertCurrent?.(); place();
throw new Error('unreachable');
});
expect(await deps.installMarket!({ pluginId: 'p1', releaseId: 'r1' }, controller.signal)).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
expect(place).not.toHaveBeenCalled();
- expect(releaseMutationMock).toHaveBeenCalledOnce();
+ expect(acquireMutationLeaseMock).not.toHaveBeenCalled();
+ expect(releaseMutationMock).not.toHaveBeenCalled();
+ });
+
+ it('asks the calling task to confirm the install as a host-owned permission card', async () => {
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', isCurrent: () => true });
+ const requestHostPermission = vi.fn(async () => ({ kind: 'permission' as const, behavior: 'allow' as const }));
+ const { deps, market } = marketHarness('codex', requestHostPermission);
+ market.install.mockImplementation(async (_id, _options, context) => {
+ expect(context.consent.initiator).toBe('agent');
+ const confirmed = await context.consent.prompt({
+ initiator: 'agent',
+ origin: 'market',
+ facts: { kind: 'install', ghostId: 'mail-suite', name: 'Mail', version: '1', permissions: [] },
+ });
+ expect(confirmed).toBe(true);
+ return { ghost: { manifest: { id: 'mail-suite', name: 'Mail', version: '1' }, enabled: true } };
+ });
+ expect(await deps.installMarket!({ pluginId: 'p1', releaseId: 'r1' })).toMatchObject({ status: 'installed' });
+ expect(requestHostPermission).toHaveBeenCalledWith(
+ 's1',
+ 's1-instance',
+ expect.objectContaining({
+ kind: 'permission',
+ toolName: 'cindy.plugin.install',
+ metadata: { hostOwnedConfirmation: 'plugin_install' },
+ }),
+ expect.any(AbortSignal),
+ );
});
it('rejects an already cancelled request before catalog access', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 70e4165ef5..f082c074d9 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -1,4 +1,9 @@
import { createPluginMarketAgentTools } from '../plugin-market/agentTools.js';
+import type { GhostInstallConsentPrompt } from '../cindy-brain/ghostInstallConsent.js';
+import {
+ createTaskInstallConsentPrompt,
+ type HostPermissionRequester,
+} from '../cindy-brain/ghostInstallConsentInteraction.js';
import type { PluginMarketService } from '../plugin-market/service.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { getBotAuthorizationService } from '../maker-ipc/botAuthorizationService.js';
@@ -67,7 +72,11 @@ import {
import { classifyLocalAttachmentPath } from '../cindy-brain/ghostLocalPathGrant.js';
import { toolNotFoundMessage } from '../cindy-brain/pipeDispatcher.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
-import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
+import {
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+ type ActiveAppSession,
+} from '../appSessionState.js';
import {
deriveGhostSessionContext,
type GhostSessionContextInjected,
@@ -457,6 +466,12 @@ export interface CindyGhostsHostDeps {
sessionId: string,
sessionInstanceId: string,
) => GhostGrantLiveSessionState | null;
+ /**
+ * 向当前任务投一张宿主权限确认卡(桌面对话、手机远控与 IM 渠道卡通用),等用户
+ * 允许或拒绝。由 Host 主动发起,不经 Agent 自身审批回调,Full Access 也会弹。
+ * 会话不存在或实例不匹配返回 null。
+ */
+ requestHostPermission?: HostPermissionRequester;
/**
* 把工具结果里的图片(cindy-media:// 地址)转成文字描述(视觉桥,最佳努力)。
* host 侧注入;内部判定视觉桥是否启用、当前 session 模型是否命中、blob 是否可读。
@@ -556,8 +571,8 @@ async function buildGhostSessionContext(
/* ────────────────────────────────────────────────────────────────────────
* Forge C-4 门:Forge 做的是**本机文件写**,裸 MCP workingDir 只是标签,不能
* 直接交给 fs。权威 session 行决定它是否本机、是否当前可写(远程/只读/plan 一律
- * fail closed)。owner lease 在首个 await 前捕获、持到 scaffold/pack + 装入确认
- * 转交结束,账号 teardown 会等它释放。
+ * fail closed)。owner lease 在 scaffold/pack 的首个 await 前捕获并持到打包结束;
+ * 装入确认在租约外求得,落位再取租约,账号 teardown 不会被确认卡拖住。
* ──────────────────────────────────────────────────────────────────────── */
type ForgeSessionFsGate =
@@ -568,11 +583,13 @@ type ForgeSessionFsGate =
message: string;
};
-async function withForgeOwnerLease<T>(operation: () => Promise<T>): Promise<T> {
+async function withForgeOwnerLease<T>(
+ operation: (owner: ActiveAppSession) => Promise<T>,
+): Promise<T> {
const owner = captureGhostMutationOwnerForMcp();
const release = acquireGhostMutationLeaseForMcp(owner);
try {
- return await operation();
+ return await operation(owner);
} finally {
release();
}
@@ -1650,6 +1667,15 @@ export function getCindyGhostsMcpDeps(
): CindyGhostsMcpDeps {
const resolveSessionContext = (): LiziMcpSessionContext | undefined =>
getLiziMcpSessionContext() ?? sessionCtx;
+ const installConsentPrompt = (): GhostInstallConsentPrompt => {
+ const context = resolveSessionContext();
+ return createTaskInstallConsentPrompt(
+ context?.sessionId && context.sessionInstanceId
+ ? { sessionId: context.sessionId, sessionInstanceId: context.sessionInstanceId }
+ : null,
+ hostDeps.requestHostPermission,
+ );
+ };
const marketTools = hostDeps.pluginMarket && createPluginMarketAgentTools({
market: hostDeps.pluginMarket,
installedState: (ghostId) => {
@@ -1683,9 +1709,10 @@ export function getCindyGhostsMcpDeps(
}
};
assertCurrent();
- const owner = captureGhostMutationOwnerForMcp();
- const release = acquireGhostMutationLeaseForMcp(owner);
- return { assertCurrent, release };
+ // 确认卡可能等几分钟,不能占用 owner mutation lease;切号只要等十秒。
+ // 捕获当前 owner 只为边界期 fail closed。落位由市场装入出口自行取租约。
+ captureGhostMutationOwnerForMcp();
+ return { assertCurrent, release: () => undefined, consentPrompt: installConsentPrompt() };
},
});
return {
@@ -2431,8 +2458,8 @@ export function getCindyGhostsMcpDeps(
});
},
async forgeInstall({ dir, iconSource }): Promise<CindyForgeInstallResult> {
- return withForgeOwnerLease(async () => {
- const sessionContext = resolveSessionContext();
+ const sessionContext = resolveSessionContext();
+ const packedAttempt = await withForgeOwnerLease(async (mutationOwner) => {
const gate = await getForgeSessionFsGate(sessionContext);
if (!gate.ok) return gate;
const access = await authorizeForgeOutsideWorkdir({
@@ -2450,44 +2477,60 @@ export function getCindyGhostsMcpDeps(
if (!attempt.ok) return attempt.result;
const stillGranted = assertForgeGrantCurrent(currentAccess);
if (!stillGranted.ok) return stillGranted;
- const { packed, iconNote } = attempt;
- try {
- const installed = await installOrUpdateLocalGhostPackageFromForge(
- packed.cindyPath,
- {
- ghostId: packed.manifest.id,
- packageSha256: createHash('sha256').update(packed.buf).digest('hex'),
- ...(stillGranted.allowOutsideWorkdir && stillGranted.isCurrent
- ? { isCurrent: stillGranted.isCurrent }
- : {}),
- },
- );
- log.info('ghost forge install completed', {
- dir,
- id: installed.ghost.manifest.id,
- version: installed.ghost.manifest.version,
- action: installed.action,
- });
- return {
- ok: true,
- action: installed.action,
- id: installed.ghost.manifest.id,
- name: installed.ghost.manifest.name,
- version: installed.ghost.manifest.version,
- enabled: installed.ghost.enabled,
- note:
- installed.action === 'installed'
- ? `${iconNote}插件已完成校验、打包和安装,并已启用。`
- : `${iconNote}插件已完成校验、打包和原位更新;原有启用状态、配置与数据保持不变。`,
- };
- } catch (err) {
+ return {
+ ok: true as const,
+ packed: attempt.packed,
+ iconNote: attempt.iconNote,
+ mutationOwner,
+ ...(stillGranted.allowOutsideWorkdir && stillGranted.isCurrent
+ ? { isCurrent: stillGranted.isCurrent }
+ : {}),
+ };
+ });
+ if (!packedAttempt.ok) return packedAttempt;
+ try {
+ const installed = await installOrUpdateLocalGhostPackageFromForge(
+ packedAttempt.packed.cindyPath,
+ {
+ ghostId: packedAttempt.packed.manifest.id,
+ packageSha256: createHash('sha256').update(packedAttempt.packed.buf).digest('hex'),
+ consentPrompt: installConsentPrompt(),
+ mutationOwner: packedAttempt.mutationOwner,
+ ...(packedAttempt.isCurrent ? { isCurrent: packedAttempt.isCurrent } : {}),
+ },
+ );
+ log.info('ghost forge install completed', {
+ dir,
+ id: installed.ghost.manifest.id,
+ version: installed.ghost.manifest.version,
+ action: installed.action,
+ });
+ return {
+ ok: true,
+ action: installed.action,
+ id: installed.ghost.manifest.id,
+ name: installed.ghost.manifest.name,
+ version: installed.ghost.manifest.version,
+ enabled: installed.ghost.enabled,
+ note:
+ installed.action === 'installed'
+ ? `${packedAttempt.iconNote}插件已完成校验、打包和安装,并已启用。`
+ : `${packedAttempt.iconNote}插件已完成校验、打包和原位更新;原有启用状态、配置与数据保持不变。`,
+ };
+ } catch (err) {
+ if (isIpcError(err) && err.code === 'MUTATION_CANCELLED') {
return {
ok: false,
- errorCode: isIpcError(err) ? err.code : 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
+ errorCode: 'MUTATION_CANCELLED',
+ message: '用户拒绝了这次插件安装或更新。除非用户再次要求,不要重试。',
};
}
- });
+ return {
+ ok: false,
+ errorCode: isIpcError(err) ? err.code : 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
},
async forgePublish({ token }): Promise<CindyForgePublishResult> {
const boundaryPending = isAppSessionBoundaryPending();
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 307ae52fbc..10bfcf6da1 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -113,6 +113,8 @@ export interface DesktopMcpProvidersDeps {
sessionId: string,
sessionInstanceId: string,
) => GhostGrantLiveSessionState | null;
+ /** Agent 发起插件安装时向该任务投宿主权限确认卡;缺失时安装 fail closed。 */
+ requestHostPermission?: CindyGhostsHostDeps['requestHostPermission'];
/** Reject stale, remote, or already-closed Session tool contexts. */
isCurrentLocalSessionInstance?: (
sessionId: string,
@@ -943,6 +945,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
pluginMarket: getPluginMarketService(),
getAppVersion: deps.getAppVersion,
getLiveSessionGrantState: deps.getLiveSessionGrantState,
+ requestHostPermission: deps.requestHostPermission,
createMediaDownloadContext: deps.createMediaDownloadContext,
describeToolResultImage: deps.describeToolResultImage,
onToolResultImagesFailed: deps.onToolResultImagesFailed,
diff --git a/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts b/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
index c59a144d5f..ae20f85306 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
@@ -3,6 +3,7 @@ import { createPluginMarketAgentTools } from '../agentTools.js';
import type { PluginMarketDetail, PluginMarketSnapshot } from '../../../shared/pluginMarket.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
import { throwIpcError } from '../../utils/ipcValidate.js';
+import type { PluginMarketInstallContext } from '../service.js';
function harness(ghostId = 'mail-suite', name = 'Google Gmail') {
const detail: PluginMarketDetail = {
@@ -20,10 +21,11 @@ function harness(ghostId = 'mail-suite', name = 'Google Gmail') {
if (!state.current) throwIpcError('PERMISSION_DENIED', 'scope changed');
});
const release = vi.fn();
+ const consentPrompt = vi.fn(async () => true);
const market = {
snapshot: vi.fn(async () => snapshot), detail: vi.fn(async () => detail),
- install: vi.fn(async (_id: string, _options: unknown, guard?: () => void) => {
- guard?.();
+ install: vi.fn(async (_id: string, _options: unknown, context: PluginMarketInstallContext) => {
+ context.assertCurrent?.();
state.installed = true;
return { ghost: { manifest: detail.manifest, enabled: true } as InstalledGhost };
}),
@@ -31,9 +33,9 @@ function harness(ghostId = 'mail-suite', name = 'Google Gmail') {
const tools = createPluginMarketAgentTools({
market, installedState: () => ({ exists: state.installed, errorCode: state.errorCode }),
captureRead: () => assertCurrent,
- captureInstall: () => { assertCurrent(); return { assertCurrent, release }; },
+ captureInstall: () => { assertCurrent(); return { assertCurrent, release, consentPrompt }; },
});
- return { tools, market, detail, snapshot, state, release };
+ return { tools, market, detail, snapshot, state, release, consentPrompt };
}
describe('Agent plugin discovery and installation', () => {
@@ -44,7 +46,10 @@ describe('Agent plugin discovery and installation', () => {
expect(h.market.snapshot).toHaveBeenCalledWith({ discoveryOnly: true });
expect(h.market.install).not.toHaveBeenCalled();
expect(await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' })).toMatchObject({ ok: true, status: 'installed', ghost_id: id });
- expect(h.market.install).toHaveBeenCalledWith('catalog-id', { expectedReleaseId: 'release-1', expectedManifest: h.detail.manifest, allowSourceReplacement: false }, expect.any(Function));
+ expect(h.market.install).toHaveBeenCalledWith('catalog-id', { expectedReleaseId: 'release-1', expectedManifest: h.detail.manifest, allowSourceReplacement: false }, {
+ consent: { prompt: h.consentPrompt, initiator: 'agent' },
+ assertCurrent: expect.any(Function),
+ });
expect(h.release).toHaveBeenCalledOnce();
},
);
@@ -77,14 +82,24 @@ describe('Agent plugin discovery and installation', () => {
it.each(['scope', 'concurrent-install'])('checks %s again at package placement', async (change) => {
const h = harness();
- h.market.install.mockImplementation(async (_id, _options, guard) => {
+ h.market.install.mockImplementation(async (_id, _options, context) => {
if (change === 'scope') h.state.current = false; else h.state.installed = true;
- guard?.(); throw new Error('should never reach placement');
+ context.assertCurrent?.(); throw new Error('should never reach placement');
});
expect(await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' })).toMatchObject({ ok: false, errorCode: change === 'scope' ? 'PERMISSION_DENIED' : 'PRECONDITION_FAILED' });
expect(h.release).toHaveBeenCalledOnce();
});
+ it('tells the Agent not to retry when the user declines the install confirmation', async () => {
+ const h = harness();
+ h.market.install.mockImplementation(async () => throwIpcError('MUTATION_CANCELLED', '用户取消了插件安装'));
+ const result = await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' });
+ expect(result).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
+ expect(String(result.message)).toMatch(/Do not retry/);
+ expect(h.state.installed).toBe(false);
+ expect(h.release).toHaveBeenCalledOnce();
+ });
+
it('does not leak service errors or claim connection success after installation fails', async () => {
const h = harness(); h.market.install.mockRejectedValue(new Error('private-token'));
const result = await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' });
diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
index 36b38f4699..f5a5e5a2f6 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
@@ -82,6 +82,8 @@ const GOOD_MANIFEST: GhostManifest = {
const GOOD_IDENTITY = {
expectedGhostId: GOOD_MANIFEST.id,
expectedVersion: GOOD_MANIFEST.version,
+ // 用户确认本身由 ghostInstallConsent 的用例覆盖;这里只验读取与打包闸。
+ resolveConsent: async () => ({ mode: 'unprompted' as const }),
};
let workDir: string;
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 c15d3c24a2..387ef62edb 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -140,8 +140,11 @@ describe('Plugin Market IPC error boundary', () => {
expect(serviceSource).toContain('if (error instanceof SilentUpgradeBusyError) {');
expect(registerSource).toContain('deferReconciliation: true');
+ expect(registerSource).toContain('plugin-market:update-consent-holds-changed');
+ expect(registerSource).toContain('onConsentHoldsChanged:');
expect(ghostPluginPageSource).toContain('const installedGhostMarketKey = useMemo(');
expect(ghostPluginPageSource).toContain('void refreshMarket(true).catch(() => undefined);');
+ expect(ghostPluginPageSource).toContain('onUpdateConsentHoldsChanged');
const ownerTaskStart = bootstrapSource.indexOf(
'authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {',
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 84173a1457..74c45b93a4 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
@@ -157,7 +157,12 @@ import {
ghostManifestDigest,
type PluginMarketInstallationRecord,
} from '../ledger';
-import { PluginMarketService } from '../service';
+import { PluginMarketService, type PluginMarketInstallContext } from '../service';
+
+/** 显式安装的 Main 侧上下文:测试里用户总是确认,确认流程本身另有专门用例。 */
+const TEST_INSTALL_CONTEXT: PluginMarketInstallContext = {
+ consent: { prompt: async () => true, initiator: 'user' },
+};
import { MarketSourceManager } from '../sources';
import { MarketSourceStore } from '../sources/store';
import type { PluginMarketApi } from '../api';
@@ -547,6 +552,50 @@ describe('PluginMarketService 自定义市场聚合', () => {
);
});
+ it('pauses a custom update that adds permissions until the user confirms it', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-consent-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },
+ ]);
+ // 新版本多声明一项文件能力:权限变多,后台不能替用户点头。
+ fs.writeFileSync(
+ path.join(dir, 'plugins', 'alpha', 'ghost.json'),
+ JSON.stringify(ghostManifest('alpha', '2.0.0', { fs: true })),
+ );
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const installedDir = path.join(root, 'installed-alpha');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(installedDir, 'ghost.json'),
+ JSON.stringify(ghostManifest('alpha', '1.0.0')),
+ );
+ runtime.ghosts = [{ manifest: ghostManifest('alpha', '1.0.0'), dir: installedDir, enabled: true }];
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-07-30T02:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items[0]).toMatchObject({
+ installState: 'update-available',
+ updateRequiresConsent: true,
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ version: '1.0.0' });
+ });
+
it('silently updates a tracked custom plugin when the marketplace version advances', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
@@ -1214,7 +1263,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: releaseId,
expectedManifest: selected.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'requires-newer' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
ghostId: 'requires-newer',
@@ -1247,7 +1296,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
expectedManifest: selected.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
});
@@ -1286,7 +1335,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const result = await h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- });
+ }, TEST_INSTALL_CONTEXT);
expect(result.ghost?.manifest.id).toBe('alpha');
expect(runtime.install).toHaveBeenCalledTimes(1);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
@@ -1352,7 +1401,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedReleaseId: reviewed.releaseId,
expectedManifest: reviewed.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1373,7 +1422,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId("team-lib", "cindy-github", "1.0.0"),
expectedManifest: detail.manifest,
- });
+ }, TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
ghostId: 'cindy-github',
@@ -1394,7 +1443,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: 'custom:stale',
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1410,7 +1459,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: detail.releaseId,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1431,7 +1480,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: detail.releaseId,
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1453,7 +1502,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const installPromise = h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: detail.releaseId,
expectedManifest: detail.manifest,
- });
+ }, TEST_INSTALL_CONTEXT);
runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };
await expect(installPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
@@ -1479,7 +1528,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: detail.releaseId,
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
pluginId,
@@ -1530,7 +1579,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: reviewed.releaseId,
expectedManifest: reviewed.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1619,7 +1668,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
runtime.install.mockImplementationOnce(async (_file, options) => {
options.beforeCommitInLock?.();
@@ -1632,7 +1681,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('placement failed');
expect(h.ledger.installationForGhost('alpha')).toEqual(previousRecord);
expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(false);
@@ -1647,7 +1696,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('notification failed after placement');
expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });
expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(true);
@@ -1666,7 +1715,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha'),
@@ -1706,7 +1755,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
});
@@ -1723,7 +1772,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(customMarketPluginId('team-lib', 'server-plugin'), {
expectedReleaseId: customMarketReleaseId("team-lib", "server-plugin", "1.0.0"),
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
});
@@ -1754,7 +1803,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(h.api.download).toHaveBeenCalledTimes(1);
});
@@ -1814,7 +1863,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
expect(reads).toBe(0);
@@ -1856,7 +1905,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const installing = h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- });
+ }, TEST_INSTALL_CONTEXT);
// runtime.install 只会在 beforeCommit 复核之后、SOURCE_MUTATION_KEY 仍被持有时调用。
// 用显式 barrier 等到这个时刻,不能靠固定毫秒数猜测打包是否已经完成。
await installEntered;
@@ -1927,7 +1976,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha', '2.0.0'),
@@ -1965,7 +2014,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),
expectedManifest: detail.manifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
expect(gets).toBeGreaterThan(1);
@@ -2027,7 +2076,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha', '2.0.0'),
@@ -2177,7 +2226,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(h.api.download).toHaveBeenCalled();
});
@@ -2222,7 +2271,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedReleaseId: item.currentRelease.id,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
expect(h.ledger.installationForGhost('server-plugin')).toMatchObject({
@@ -2259,7 +2308,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expectedManifest: detail.manifest,
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowSourceReplacement: true,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha'),
@@ -2329,6 +2378,56 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expect(h.ledger.installationForGhost('alpha')?.installed).toBe(false);
});
+ it('retries a same-version custom package after the extra permissions are removed', 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', version: '2.0.0' },
+ ]);
+ fs.writeFileSync(
+ path.join(dir, 'plugins', 'alpha', 'ghost.json'),
+ JSON.stringify({ ...ghostManifest('alpha', '2.0.0'), fs: true }),
+ );
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ runtime.ghosts = [installedGhost(root, 'alpha', '1.0.0')];
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-09-11T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),
+ });
+
+ const paused = await h.service.snapshot();
+ expect(paused.items[0]).toMatchObject({
+ installState: 'update-available',
+ updateRequiresConsent: true,
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+
+ fs.writeFileSync(
+ path.join(dir, 'plugins', 'alpha', 'ghost.json'),
+ JSON.stringify(ghostManifest('alpha', '2.0.0')),
+ );
+ runtime.install.mockImplementationOnce(async () => {
+ const upgraded = installedGhost(root, 'alpha', '2.0.0');
+ runtime.ghosts = [upgraded];
+ return upgraded;
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ ghostId: 'alpha', installState: 'installed', version: '2.0.0' }],
+ });
+ expect(runtime.install).toHaveBeenCalledOnce();
+ });
+
it('结构守卫:service.ts 不允许出现按路径的 readFile/readFileSync', async () => {
// 已安装目录同样可能被外部进程/同步盘改动,且摘要读取在每次市场快照都会
// 执行;所有此类读取必须走 readBoundedFileNoFollow 系列(单句柄限量闸)。
@@ -2382,7 +2481,7 @@ describe('Agent custom marketplace boundaries', () => {
});
await expect(h.service.install(selected.pluginId, {
expectedReleaseId: selected.releaseId, expectedManifest: selected.manifest,
- }, () => { if (!current) throw new Error('authority expired'); })).rejects.toThrow('authority expired');
+ }, { ...TEST_INSTALL_CONTEXT, assertCurrent: () => { if (!current) throw new Error('authority expired'); } })).rejects.toThrow('authority expired');
expect(place).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost('alpha')).toBeNull();
});
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 7b3b148dad..8dde7e5599 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -185,7 +185,16 @@ import {
legacyNoSlotsGhostManifestDigest,
type PluginMarketInstallationRecord,
} from '../ledger';
-import { organizationDefaultTakeoverEligibility, PluginMarketService } from '../service';
+import {
+ organizationDefaultTakeoverEligibility,
+ PluginMarketService,
+ type PluginMarketInstallContext,
+} from '../service';
+
+/** 显式安装的 Main 侧上下文:测试里用户总是确认,确认流程本身另有专门用例。 */
+const TEST_INSTALL_CONTEXT: PluginMarketInstallContext = {
+ consent: { prompt: async () => true, initiator: 'user' },
+};
import type { PluginMarketApi } from '../api';
import { createOrganizationPrefixStore } from '../organizationPrefixStore';
@@ -896,7 +905,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
await expect(h.service.detail(organizationPlugin.id)).rejects.toThrow('[NOT_FOUND]');
await expect(
- h.service.install(publicPlugin.id, reviewedInstallOptions(publicPlugin)),
+ h.service.install(publicPlugin.id, reviewedInstallOptions(publicPlugin), TEST_INSTALL_CONTEXT),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1553,11 +1562,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'cindy-test' } } });
expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
ghostId: 'cindy-test',
version: '1.0.0',
+ consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
});
});
@@ -1583,7 +1593,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
dir: '/userData/cindy-brain/cindy-test',
enabled: true,
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).resolves.toMatchObject({
ghost: { manifest: { id: 'cindy-test' } },
});
expect(runtime.install).toHaveBeenCalledTimes(1);
@@ -1638,7 +1648,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
expectedManifest: reviewedManifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: actualManifest } });
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
});
@@ -1662,7 +1672,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
expectedManifest: normalizedBrokerManifest,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('[GHOST_BROKER_REDIRECT_PORT_REQUIRED]');
expect(h.api.download).not.toHaveBeenCalled();
expect(runtime.install).not.toHaveBeenCalled();
@@ -1679,11 +1689,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- const { ghost } = await h.service.install(item.id, reviewedInstallOptions(item));
+ const { ghost } = await h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
ghostId: 'cindy-test',
version: '1.0.0',
+ consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
});
// 安装入口用目录 summary 做 detail 身份绑定(防止把 A 的确认导向 B 的内容),
@@ -1711,7 +1722,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
await orgHarness.service.install(orgItem.id, {
...reviewedInstallOptions(orgItem),
expectedManifest: manifest('acme-tool'),
- });
+ }, TEST_INSTALL_CONTEXT);
expect(runtime.install).toHaveBeenCalledWith(
expect.stringMatching(/\.cindy$/),
expect.objectContaining({
@@ -1745,7 +1756,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
const publicHarness = harness([publicItem]);
- await publicHarness.service.install(publicItem.id, reviewedInstallOptions(publicItem));
+ await publicHarness.service.install(publicItem.id, reviewedInstallOptions(publicItem), TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
runtime.install.mockReset();
@@ -1756,7 +1767,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
const personalHarness = harness([personalItem]);
- await personalHarness.service.install(personalItem.id, reviewedInstallOptions(personalItem));
+ await personalHarness.service.install(personalItem.id, reviewedInstallOptions(personalItem), TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
});
@@ -1776,7 +1787,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).resolves.toMatchObject({
ghost: {
manifest: {
setup: { requires: [{ anyOf: [{ kind: 'secret', key: 'api_key' }] }] },
@@ -1797,7 +1808,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const h = harness([selected, other]);
await expect(
- h.service.install(selected.id, reviewedInstallOptions(selected)),
+ h.service.install(selected.id, reviewedInstallOptions(selected), TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: selected.ghostId } } });
expect(h.api.detail).toHaveBeenCalledWith(selected.id);
// 安装入口用目录 summary 绑定 detail 身份,共享 ghostId 的另一条目也一并取回。
@@ -1813,7 +1824,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([github]);
- await h.service.install(github.id, reviewedInstallOptions(github));
+ await h.service.install(github.id, reviewedInstallOptions(github), TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
ghostId: 'cindy-github',
@@ -1828,10 +1839,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
const ordinaryHarness = harness([ordinary]);
- await ordinaryHarness.service.install(ordinary.id, reviewedInstallOptions(ordinary));
+ await ordinaryHarness.service.install(ordinary.id, reviewedInstallOptions(ordinary), TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).toEqual({
ghostId: 'cindy-test',
version: '1.0.0',
+ consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
});
});
@@ -1871,7 +1883,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
expectedReleaseId: item.currentRelease.id,
expectedManifest: rawManifest as unknown as GhostManifest,
allowSourceReplacement: false,
- });
+ }, TEST_INSTALL_CONTEXT);
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
manifestDigest: ghostManifestDigest(rawManifest),
@@ -2279,7 +2291,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await h.service.install(item.id, reviewedInstallOptions(item));
+ await h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
});
@@ -2323,7 +2335,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
await h.service.install(item.id, {
...reviewedInstallOptions(item),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- });
+ }, TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
});
@@ -2356,7 +2368,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item, true),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('placement failed');
expect(h.ledger.installationForGhost(item.ghostId)).toEqual(previousRecord);
expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
@@ -2369,7 +2381,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item, true),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('notification failed after placement');
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);
@@ -2386,7 +2398,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item, true),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({
ghost: { manifest: { version: '2.0.0' } },
});
@@ -2424,7 +2436,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
await h.service.install(item.id, {
...reviewedInstallOptions(item),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- });
+ }, TEST_INSTALL_CONTEXT);
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
});
@@ -3101,7 +3113,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).resolves.toMatchObject({
ghost: { manifest: { id: 'cindy-test' }, enabled: false },
});
expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
@@ -3126,7 +3138,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const order: string[] = [];
- const installing = h.service.install(item.id, reviewedInstallOptions(item));
+ const installing = h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
// 等安装推进到持锁并阻塞在 runtime.install 上。
await vi.waitFor(() => expect(runtime.install).toHaveBeenCalled());
const outsider = withGhostInstallLock(item.ghostId, async () => {
@@ -3158,7 +3170,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[NOT_FOUND]',
);
expect(h.api.detail).not.toHaveBeenCalled();
@@ -3193,7 +3205,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary({ ghostId: 'cindy-art', defaultInstall: true });
const h = harness([item]);
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PERMISSION_DENIED]',
);
expect(h.api.detail).not.toHaveBeenCalled();
@@ -3649,7 +3661,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item, true),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({
ghost: { manifest: { id: item.ghostId } },
});
@@ -3695,7 +3707,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item, true),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(h.api.download).toHaveBeenCalledTimes(1);
@@ -3722,7 +3734,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
};
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
expect(runtime.install).not.toHaveBeenCalled();
@@ -3764,7 +3776,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({
ghost: { manifest: { version: '2.0.0' } },
});
@@ -3801,7 +3813,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -3840,7 +3852,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
h.service.install(item.id, {
...reviewedInstallOptions(item),
expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
- }),
+ }, TEST_INSTALL_CONTEXT),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -3864,7 +3876,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
},
});
- await expect(h.service.install(reviewed.id, reviewedInstallOptions(reviewed))).rejects.toThrow(
+ await expect(h.service.install(reviewed.id, reviewedInstallOptions(reviewed), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
expect(h.api.download).not.toHaveBeenCalled();
@@ -3881,7 +3893,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
sizeBytes: item.currentRelease.sizeBytes,
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
expect(runtime.install).not.toHaveBeenCalled();
@@ -3905,7 +3917,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
};
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
expect(runtime.install).not.toHaveBeenCalled();
@@ -3930,7 +3942,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
return installedGhost;
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).resolves.toMatchObject({
ghost: { manifest: { id: item.ghostId } },
});
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
@@ -4853,12 +4865,12 @@ describe('market detail 响应身份绑定', () => {
h.api.detail.mockImplementation(async () =>
detail({ ...item, id: 'plg_other', ghostId: 'cindy-other' }),
);
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
// 只换 ghostId、id 相同也要拒:可见性与 ghostId 冲突判定都基于目录 summary。
h.api.detail.mockImplementation(async () => detail({ ...item, ghostId: 'cindy-other' }));
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow(
'[PRECONDITION_FAILED]',
);
await expect(h.service.detail(item.id)).rejects.toThrow('[PRECONDITION_FAILED]');
@@ -4897,11 +4909,226 @@ describe('Agent catalog discovery and install boundary', () => {
place();
throw new Error('unreachable');
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item), () => {
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), { ...TEST_INSTALL_CONTEXT, assertCurrent: () => {
if (!current) throw new Error('authority expired');
- })).rejects.toThrow('authority expired');
+ } })).rejects.toThrow('authority expired');
expect(h.api.download).toHaveBeenCalledOnce();
expect(place).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
});
+
+describe('PluginMarketService install consent', () => {
+ function upgradeFixture(options: { defaultInstall?: boolean; nextCapabilities?: readonly ('notify' | 'fs')[] }) {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: options.defaultInstall ?? false,
+ 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-consent-'));
+ 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]);
+ const nextManifest = manifest(item.ghostId, '2.0.0', options.nextCapabilities ?? ['notify']);
+ h.api.detail.mockImplementation(async () => {
+ runtime.inspectedManifest = nextManifest;
+ return { ...item, currentRelease: { ...item.currentRelease, manifest: nextManifest } };
+ });
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ runtime.install.mockImplementation(async () => {
+ const ghost = { manifest: nextManifest, dir: installDir, enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+ return { item, h };
+ }
+
+ it('pauses a background update that adds permissions and keeps the old version', async () => {
+ const { h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
+
+ const first = await h.service.snapshot();
+ expect(first.items[0]).toMatchObject({ installState: 'update-available', updateRequiresConsent: true });
+ await h.service.snapshot();
+
+ expect(runtime.install).not.toHaveBeenCalled();
+ // 同一 release 只下载一次真实包,确认前不会反复重下。
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({ releaseId: 'release-1' });
+ });
+
+ it('notifies after deferred reconciliation records a new consent hold', async () => {
+ const { h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
+ const onConsentHoldsChanged = vi.fn();
+
+ const first = await h.service.snapshot({
+ deferReconciliation: true,
+ onConsentHoldsChanged,
+ });
+ expect(first.items[0]).toMatchObject({ installState: 'update-available' });
+ expect(first.items[0]?.updateRequiresConsent).not.toBe(true);
+
+ await vi.waitFor(() => expect(onConsentHoldsChanged).toHaveBeenCalledOnce());
+ });
+
+ it('does not notify again when deferred reconciliation finds an existing consent hold', async () => {
+ const { h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
+ await h.service.snapshot();
+ const onConsentHoldsChanged = vi.fn();
+
+ await h.service.snapshot({
+ deferReconciliation: true,
+ onConsentHoldsChanged,
+ });
+ await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledTimes(1));
+ expect(onConsentHoldsChanged).not.toHaveBeenCalled();
+ });
+
+ it('keeps silent background updates when permissions do not grow', async () => {
+ const { h } = upgradeFixture({});
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'installed', version: '2.0.0' }],
+ });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({ consent: { mode: 'unprompted' } }),
+ );
+ });
+
+ it('updates server default installs silently even when permissions grow', async () => {
+ const { h } = upgradeFixture({ defaultInstall: true, nextCapabilities: ['notify', 'fs'] });
+
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({ consent: { mode: 'exempt', reason: 'server-default-install' } }),
+ );
+ });
+
+ it('does not silently grow permissions after the user opted out of default install', async () => {
+ const { item, h } = upgradeFixture({ defaultInstall: true, nextCapabilities: ['notify', 'fs'] });
+ h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ installed: true,
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId, '1.0.0')),
+ });
+
+ const first = await h.service.snapshot();
+
+ expect(first.items[0]).toMatchObject({
+ installState: 'update-available',
+ updateRequiresConsent: true,
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('does not hold the plugin mutation while waiting for install confirmation', async () => {
+ const item = summary();
+ const h = harness([item]);
+ const waiting = deferred();
+ let promptStarted = false;
+ const prompt = vi.fn(async () => {
+ promptStarted = true;
+ await waiting.promise;
+ return true;
+ });
+ runtime.install.mockImplementation(async () => {
+ const ghost = {
+ manifest: manifest(item.ghostId),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+
+ const installPromise = h.service.install(item.id, reviewedInstallOptions(item), {
+ consent: { prompt, initiator: 'user' },
+ });
+ await vi.waitFor(() => expect(promptStarted).toBe(true));
+ await expect(h.service.uninstall(item.id)).rejects.toThrow('[NOT_FOUND]');
+ waiting.resolve();
+ await expect(installPromise).resolves.toMatchObject({
+ ghost: { manifest: { id: item.ghostId } },
+ });
+ });
+
+ it('asks before a manual update that adds permissions and cancels when declined', async () => {
+ const { item, h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
+ await h.service.snapshot();
+ const prompt = vi.fn(async () => false);
+
+ await expect(
+ h.service.install(
+ item.id,
+ {
+ ...reviewedInstallOptions(item),
+ expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000001',
+ },
+ { consent: { prompt, initiator: 'user' } },
+ ),
+ ).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+
+ expect(prompt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initiator: 'user',
+ origin: 'market',
+ facts: expect.objectContaining({ kind: 'update', previousVersion: '1.0.0', version: '2.0.0' }),
+ }),
+ );
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({ releaseId: 'release-1' });
+ });
+
+ it('does not ask again for a manual update without new permissions', async () => {
+ const { item, h } = upgradeFixture({});
+ const prompt = vi.fn(async () => true);
+
+ await h.service.install(
+ item.id,
+ {
+ ...reviewedInstallOptions(item),
+ expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000001',
+ },
+ { consent: { prompt, initiator: 'agent' } },
+ );
+
+ expect(prompt).not.toHaveBeenCalled();
+ expect(runtime.install).toHaveBeenCalledOnce();
+ });
+
+ it('asks before every first install, including installs requested by an Agent', async () => {
+ const item = summary();
+ const h = harness([item]);
+ const prompt = vi.fn(async () => true);
+ runtime.install.mockImplementation(async () => {
+ const ghost = { manifest: manifest(item.ghostId), dir: '/userData/cindy-brain/cindy-test', enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+
+ await h.service.install(item.id, reviewedInstallOptions(item), {
+ consent: { prompt, initiator: 'agent' },
+ });
+
+ expect(prompt).toHaveBeenCalledWith(
+ expect.objectContaining({ initiator: 'agent', origin: 'market', facts: expect.objectContaining({ kind: 'install' }) }),
+ );
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({ consent: { mode: 'confirmed', key: expect.any(String) } }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/agentTools.ts b/apps/desktop/src/main/plugin-market/agentTools.ts
index 58ca98c722..9758baf1d5 100644
--- a/apps/desktop/src/main/plugin-market/agentTools.ts
+++ b/apps/desktop/src/main/plugin-market/agentTools.ts
@@ -1,3 +1,4 @@
+import type { GhostInstallConsentPrompt } from '../cindy-brain/ghostInstallConsent.js';
import type { PluginMarketService } from './service.js';
import type { PluginMarketItem } from '../../shared/pluginMarket.js';
import { isIpcError } from '../../shared/ipc-errors.js';
@@ -14,8 +15,16 @@ export interface PluginMarketAgentDeps {
installedState(ghostId: string): InstalledState;
/** Owner generation and caller identity are captured before discovery's first await. */
captureRead(): () => void;
- /** Holds the existing owner lease and live task authority through package placement. */
- captureInstall(signal?: AbortSignal): { assertCurrent(): void; release(): void };
+ /**
+ * Captures live task authority before install. Confirmation must not hold an
+ * owner lease; package placement rechecks `assertCurrent` and takes its own lease.
+ * `consentPrompt` shows the Host-owned install confirmation in the calling task.
+ */
+ captureInstall(signal?: AbortSignal): {
+ assertCurrent(): void;
+ release(): void;
+ consentPrompt: GhostInstallConsentPrompt;
+ };
}
function catalogItem(item: PluginMarketItem, installed: InstalledState) {
@@ -77,11 +86,16 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
throwIpcError('PRECONDITION_FAILED', 'Plugin appeared during installation; inspect it before continuing');
}
};
- const result = await deps.market.install(request.pluginId, {
- expectedReleaseId: request.releaseId,
- expectedManifest: detail.manifest,
- allowSourceReplacement: false,
- }, assertCurrent);
+ // Agent installs always ask the user in the task, whatever its permission mode.
+ const result = await deps.market.install(
+ request.pluginId,
+ {
+ expectedReleaseId: request.releaseId,
+ expectedManifest: detail.manifest,
+ allowSourceReplacement: false,
+ },
+ { consent: { prompt: authority.consentPrompt, initiator: 'agent' }, assertCurrent },
+ );
// Once committed, cancellation cannot turn the durable installation
// into a failure. The live check runs at package placement instead.
return {
@@ -91,6 +105,12 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
next: 'Inspect ghost_info for the real tools and setup. Installation is not account connection or task completion.',
};
} catch (error) {
+ if (isIpcError(error) && error.code === 'MUTATION_CANCELLED') {
+ return {
+ ok: false, errorCode: 'MUTATION_CANCELLED',
+ message: 'The user declined this plugin installation. Do not retry unless the user asks for it again.',
+ };
+ }
return {
ok: false, errorCode: isIpcError(error) ? error.code : 'INSTALL_UNAVAILABLE',
message: 'Installation was not confirmed. Inspect the selected plugin before retrying; do not claim an account connection or completed work.',
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index 02a8b33c1d..4973ef8099 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -34,6 +34,7 @@ import {
type MarketGhostPackageCommitEvidence,
} from '../cindy-brain/index.js';
import type { PluginMarketInstallResult } from '../../shared/pluginMarket.js';
+import type { GhostInstallConsentDecision } from '../cindy-brain/ghostInstallConsent.js';
import { packGhostDirToFile } from '../cindy-brain/forge.js';
import { createLogger } from '../logger.js';
import { isIpcError } from '../../shared/ipc-errors.js';
@@ -47,7 +48,7 @@ import {
/**
* 把插件目录装成运行中的 Ghost。
*
- * 这里先安全打包,再让 Main 从实际 `.cindy` 解析 canonical manifest;
+ * 打包必须在来源 cache-path 租约内完成;确认等待不能占用该租约。
* 校验和落位始终绑定同一个临时包。
*/
const log = createLogger('plugin-market-install');
@@ -62,46 +63,38 @@ function sanitizeInstallDetail(message: string): string {
);
}
-export async function installCustomMarketPlugin(input: {
- pluginDir: string;
- expected?: GhostManifest;
- /** 更新时把发起操作时读取的 Host receipt token 贯穿到最终安装出口。 */
+type CustomMarketInspectedPackage = Awaited<ReturnType<ReturnType<typeof getGhostManager>['inspect']>>;
+
+/** 来源租约内打出的独立临时包;租约释放后仍可确认并落位。调用方负责删除 `tempPath`。 */
+export interface PackedCustomMarketPlugin {
+ tempPath: string;
+ packedManifest: GhostManifest;
+ validatedManifest: GhostManifest;
+ inspected: CustomMarketInspectedPackage;
+}
+
+type CustomMarketCommitHooks = {
expectedInstalledApproval?: string;
- expectedGhostId: string;
- expectedVersion: string;
- /**
- * 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。
- * 调用方按当前账户捕获市场 manifest;打包是异步的,装出前必须重新确认
- * 会话未漂移,避免把账户 A 选择的插件装进当前账户 B 的运行时。
- * 这里同时复核当前账号、所选来源和运行时已安装插件事实。
- */
beforeCommit?: () => void | Promise<void>;
- /** 真实包完成检查后、即将改动运行时前的同步事务钩。 */
beforePackagePlacement?: () => void;
- /** 新包完成原子换位后的同步事务钩。 */
onPackagePlaced?: () => void;
- /**
- * 提交段(复核 + 落位)的互斥包装,与来源增删共享同一把锁。
- *
- * 只在 `beforeCommit` 里复核不够:它返回后 `installOrUpdateMarketGhostPackage`
- * 还要先 await 包检查才开始真正改动运行时,那段时间另一窗口仍能移除或替换
- * 所选来源,复核结论在落位前就过期了。把“复核 + 落位”整段放进锁里,来源
- * 变更插不进来。
- */
withCommitLock?: <T>(fn: () => Promise<T>) => Promise<T>;
- /**
- * 落位成功后、仍在 `withCommitLock` 与 owner mutation lease 内执行的溯源写入钩。
- *
- * 账本写入必须与落位同锁:放在锁外时,另一条路径(本地 .cindy 装入/更新)可以
- * 插在"包已落位"与"写下溯源"之间换掉同 id 的包,账本随后认领一个其实已被替换
- * 的包。抛错则整个安装按失败上报(包已落位,由调用方决定补偿)。
- */
afterCommit?: (
installed: InstalledGhost,
packagedManifest: GhostManifest,
evidence: MarketGhostPackageCommitEvidence,
) => Promise<void>;
-}): Promise<PluginMarketInstallResult> {
+};
+
+/**
+ * 在来源 cache-path 租约内打包并检查真实包。成功时调用方负责删除 `tempPath`。
+ */
+export async function packCustomMarketPlugin(input: {
+ pluginDir: string;
+ expected?: GhostManifest;
+ expectedGhostId: string;
+ expectedVersion: string;
+}): Promise<PackedCustomMarketPlugin> {
// input.pluginDir 是发现层已 realpath、且已校验落在市场根内的规范路径。
// 发现之后、打包之前,若插件目录或其某个父目录被换成指向市场外的符号链接,
// 重新 realpath 会解析到别处——只要外部目录留着同样的 ghost.json,清单摘要
@@ -218,41 +211,134 @@ export async function installCustomMarketPlugin(input: {
);
}
}
- const commit = async (): Promise<PluginMarketInstallResult> => {
- const run = async (): Promise<PluginMarketInstallResult> => {
- await input.beforeCommit?.();
- // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,
- // 不再进入官方市场“下载真实包后复核”的分支。
- const installed = await installOrUpdateMarketGhostPackage(tempPath, {
- // Main 会从真实临时包再次解析并与所选市场条目的身份核对;不能使用
- // 打包前活目录里的值,否则目录在打包窗口变化时会把另一个插件装入。
- ghostId: input.expectedGhostId,
- version: input.expectedVersion,
- // 发现时读到的规范化 Manifest 是这次安装允许的能力上限。打包窗口
- // 中目录若发生能力扩张,Host 会按真实包不一致直接拒绝。
- manifestCap: validated.manifest,
- ...(input.expectedInstalledApproval
- ? { expectedInstalledApproval: input.expectedInstalledApproval }
- : {}),
- ...(input.beforePackagePlacement
- ? { beforeCommitInLock: input.beforePackagePlacement }
- : {}),
- ...(input.onPackagePlaced
- ? { onPackagePlacedInLock: input.onPackagePlaced }
- : {}),
- ...(input.afterCommit
- ? {
- afterCommitInLock: (committed, evidence) =>
- input.afterCommit!(committed, packed.manifest, evidence),
- }
- : {}),
- });
- return { ghost: installed };
- };
- return input.withCommitLock ? input.withCommitLock(run) : run();
+ return {
+ tempPath,
+ packedManifest: packed.manifest,
+ validatedManifest: validated.manifest,
+ inspected,
};
- return await commit();
- } finally {
+ } catch (error) {
await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
+ throw error;
+ }
+}
+
+/** 把已打包的独立临时包交给装入出口。调用方仍负责删除 `packed.tempPath`。 */
+export async function commitCustomMarketPlugin(
+ packed: PackedCustomMarketPlugin,
+ input: {
+ expectedGhostId: string;
+ expectedVersion: string;
+ consent: GhostInstallConsentDecision;
+ } & CustomMarketCommitHooks,
+): Promise<PluginMarketInstallResult> {
+ const run = async (): Promise<PluginMarketInstallResult> => {
+ await input.beforeCommit?.();
+ // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,
+ // 不再进入官方市场“下载真实包后复核”的分支。
+ const installed = await installOrUpdateMarketGhostPackage(packed.tempPath, {
+ // Main 会从真实临时包再次解析并与所选市场条目的身份核对;不能使用
+ // 打包前活目录里的值,否则目录在打包窗口变化时会把另一个插件装入。
+ ghostId: input.expectedGhostId,
+ version: input.expectedVersion,
+ consent: input.consent,
+ // 发现时读到的规范化 Manifest 是这次安装允许的能力上限。打包窗口
+ // 中目录若发生能力扩张,Host 会按真实包不一致直接拒绝。
+ manifestCap: packed.validatedManifest,
+ ...(input.expectedInstalledApproval
+ ? { expectedInstalledApproval: input.expectedInstalledApproval }
+ : {}),
+ ...(input.beforePackagePlacement
+ ? { beforeCommitInLock: input.beforePackagePlacement }
+ : {}),
+ ...(input.onPackagePlaced
+ ? { onPackagePlacedInLock: input.onPackagePlaced }
+ : {}),
+ ...(input.afterCommit
+ ? {
+ afterCommitInLock: (committed, evidence) =>
+ input.afterCommit!(committed, packed.packedManifest, evidence),
+ }
+ : {}),
+ });
+ return { ghost: installed };
+ };
+ return input.withCommitLock ? input.withCommitLock(run) : run();
+}
+
+export async function installCustomMarketPlugin(input: {
+ pluginDir: string;
+ expected?: GhostManifest;
+ /** 更新时把发起操作时读取的 Host receipt token 贯穿到最终安装出口。 */
+ expectedInstalledApproval?: string;
+ expectedGhostId: string;
+ expectedVersion: string;
+ /**
+ * 真实包检查通过后、提交锁之外求得用户确认(ghostInstallConsent.ts)。收到的是
+ * 即将落位那份包的 manifest;结论随安装请求交给装入出口在锁内复核。必填。
+ */
+ resolveConsent: (
+ manifest: GhostManifest,
+ packageSha256: string,
+ ) => Promise<GhostInstallConsentDecision>;
+ /**
+ * 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。
+ * 调用方按当前账户捕获市场 manifest;打包是异步的,装出前必须重新确认
+ * 会话未漂移,避免把账户 A 选择的插件装进当前账户 B 的运行时。
+ * 这里同时复核当前账号、所选来源和运行时已安装插件事实。
+ */
+ beforeCommit?: () => void | Promise<void>;
+ /** 真实包完成检查后、即将改动运行时前的同步事务钩。 */
+ beforePackagePlacement?: () => void;
+ /** 新包完成原子换位后的同步事务钩。 */
+ onPackagePlaced?: () => void;
+ /**
+ * 提交段(复核 + 落位)的互斥包装,与来源增删共享同一把锁。
+ *
+ * 只在 `beforeCommit` 里复核不够:它返回后 `installOrUpdateMarketGhostPackage`
+ * 还要先 await 包检查才开始真正改动运行时,那段时间另一窗口仍能移除或替换
+ * 所选来源,复核结论在落位前就过期了。把“复核 + 落位”整段放进锁里,来源
+ * 变更插不进来。
+ */
+ withCommitLock?: <T>(fn: () => Promise<T>) => Promise<T>;
+ /**
+ * 落位成功后、仍在 `withCommitLock` 与 owner mutation lease 内执行的溯源写入钩。
+ *
+ * 账本写入必须与落位同锁:放在锁外时,另一条路径(本地 .cindy 装入/更新)可以
+ * 插在"包已落位"与"写下溯源"之间换掉同 id 的包,账本随后认领一个其实已被替换
+ * 的包。抛错则整个安装按失败上报(包已落位,由调用方决定补偿)。
+ */
+ afterCommit?: (
+ installed: InstalledGhost,
+ packagedManifest: GhostManifest,
+ evidence: MarketGhostPackageCommitEvidence,
+ ) => Promise<void>;
+}): Promise<PluginMarketInstallResult> {
+ const packed = await packCustomMarketPlugin({
+ pluginDir: input.pluginDir,
+ expected: input.expected,
+ expectedGhostId: input.expectedGhostId,
+ expectedVersion: input.expectedVersion,
+ });
+ try {
+ // 检查失败的包会在装入出口重新解析时被拒;这里只为能解析的真实包求确认。
+ // 等待确认期间不持提交锁,不阻塞其它来源的增删与安装。
+ const consent: GhostInstallConsentDecision =
+ 'rejection' in packed.inspected
+ ? { mode: 'unprompted' }
+ : await input.resolveConsent(packed.inspected.manifest, packed.inspected.packageSha256);
+ return await commitCustomMarketPlugin(packed, {
+ expectedGhostId: input.expectedGhostId,
+ expectedVersion: input.expectedVersion,
+ consent,
+ expectedInstalledApproval: input.expectedInstalledApproval,
+ beforeCommit: input.beforeCommit,
+ beforePackagePlacement: input.beforePackagePlacement,
+ onPackagePlaced: input.onPackagePlaced,
+ withCommitLock: input.withCommitLock,
+ afterCommit: input.afterCommit,
+ });
+ } finally {
+ await fs.promises.rm(packed.tempPath, { force: true }).catch(() => undefined);
}
}
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 356156571c..059bc4a4e5 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -12,6 +12,7 @@ import {
type PluginMarketSnapshot,
} from '../../shared/pluginMarket.js';
import {
+ createWindowGhostInstallConsentPrompt,
sendToTrustedAppWindows,
getGhostManager,
setGhostUninstallLedgerPreparer,
@@ -31,6 +32,7 @@ import {
const log = createLogger('plugin-market-ipc');
let registered = false;
const REMOVAL_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:removal-notice-available';
+const UPDATE_CONSENT_HOLDS_CHANGED_CHANNEL = 'plugin-market:update-consent-holds-changed';
const localIconRequestGate = new LocalIconRequestGate();
function signalRemovalNoticeAvailable(): void {
@@ -38,6 +40,10 @@ function signalRemovalNoticeAvailable(): void {
sendToTrustedAppWindows(REMOVAL_NOTICE_AVAILABLE_CHANNEL, undefined);
}
+function signalUpdateConsentHoldsChanged(): void {
+ sendToTrustedAppWindows(UPDATE_CONSENT_HOLDS_CHANGED_CHANNEL, undefined);
+}
+
async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOptions) {
try {
return await service().snapshot(options);
@@ -129,6 +135,7 @@ export function registerPluginMarketIpc(): void {
return invokePluginMarket(() =>
snapshotAndSignalRemovalNotice({
deferReconciliation: true,
+ onConsentHoldsChanged: signalUpdateConsentHoldsChanged,
}),
);
});
@@ -203,12 +210,22 @@ export function registerPluginMarketIpc(): void {
.map((g) => g.manifest.id),
);
return invokePluginMarket(async () => {
- const result = await service().install(requireString(pluginId, 'pluginId'), {
- expectedReleaseId,
- ...(expectedInstalledApproval !== undefined ? { expectedInstalledApproval } : {}),
- ...(expectedManifest !== undefined ? { expectedManifest } : {}),
- allowSourceReplacement,
- });
+ const result = await service().install(
+ requireString(pluginId, 'pluginId'),
+ {
+ expectedReleaseId,
+ ...(expectedInstalledApproval !== undefined ? { expectedInstalledApproval } : {}),
+ ...(expectedManifest !== undefined ? { expectedManifest } : {}),
+ allowSourceReplacement,
+ },
+ // 首装与扩权更新的确认框投给发起安装的这个窗口。
+ {
+ consent: {
+ prompt: createWindowGhostInstallConsentPrompt(event.sender),
+ initiator: 'user',
+ },
+ },
+ );
if (
getActiveAppSession().generation === owner.generation &&
!previouslyInstalled.has(result.ghost.manifest.id)
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index d2db46560f..53ceb4754a 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -77,10 +77,21 @@ import {
} from '../installedGhostManifest.js';
import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';
import { ghostBrokerRedirectPortInstallError } from '../cindy-brain/ghostBrokerRedirectPort.js';
+import {
+ isGhostInstallConsentRequiredError,
+ obtainGhostInstallConsent,
+ type GhostInstallConsentDecision,
+ type GhostInstallConsentPolicy,
+ type GhostInstallConsentPrompt,
+} from '../cindy-brain/ghostInstallConsent.js';
+import type { GhostInstallConsentInitiator } from '../../shared/ghostInstallConsent.js';
import { PluginMarketApi } from './api.js';
import { createOrganizationPrefixStore } from './organizationPrefixStore.js';
import { downloadVerifiedPlugin } from './download.js';
-import { installCustomMarketPlugin } from './install.js';
+import {
+ commitCustomMarketPlugin,
+ packCustomMarketPlugin,
+} from './install.js';
import {
PluginMarketLedger,
ghostManifestDigest,
@@ -355,6 +366,21 @@ export interface PluginMarketSnapshotOptions {
onDeferredReconciliationSettled?: () => void;
/** Main-only completion signal; it is not part of the Renderer snapshot. */
onDefaultReconciliationOutcome?: (outcome: 'completed' | 'failed') => void;
+ /**
+ * 后台对账新记下「需确认新权限」hold 后通知。扩权暂停不改已装插件,
+ * 没有 ghosts:changed,Renderer 目录要靠这次信号立刻重投影。
+ */
+ onConsentHoldsChanged?: () => void;
+}
+
+/**
+ * 显式安装请求(插件页或 Agent)必须交出的 Main 侧上下文。确认界面随发起方而定:
+ * 插件页投给发起窗口,Agent 投成任务里的权限确认卡。
+ */
+export interface PluginMarketInstallContext {
+ consent: { prompt: GhostInstallConsentPrompt; initiator: GhostInstallConsentInitiator };
+ /** Main-only caller authority, rechecked immediately before package placement. */
+ assertCurrent?: () => void;
}
/**
@@ -611,6 +637,17 @@ export class PluginMarketService {
string,
{ releaseKey: string; failures: number; retryAfter: number }
>();
+ /**
+ * 后台更新因新版本权限变多而暂停、等待用户在插件页确认。
+ * 值同时钉住 release 与包内容:服务端 release 不可变,用 releaseId 即可;
+ * 自定义市场同版本包可能被原地改掉,内容指纹变了就必须重新判定,不能继续跳过。
+ * 只在当前进程内保存,重启后按真实包重新判定一次。
+ */
+ private readonly automaticUpgradeConsentHolds = new Map<
+ string,
+ { releaseKey: string; contentKey: string }
+ >();
+ private consentHoldsChangedListener: (() => void) | null = null;
/**
* Renderer 把 customIconKey 当不可变缓存 generation。每次重新投影市场都换代,
* 使低精度文件系统上的同长度、同 stat 原地改写也会在刷新后重新按需读取。
@@ -665,6 +702,69 @@ export class PluginMarketService {
}
}
+ private isAutomaticUpgradeHeldForConsent(
+ retryKey: string,
+ releaseKey: string,
+ contentKey: string,
+ ): boolean {
+ const held = this.automaticUpgradeConsentHolds.get(retryKey);
+ if (held === undefined) return false;
+ if (held.releaseKey === releaseKey && held.contentKey === contentKey) return true;
+ this.automaticUpgradeConsentHolds.delete(retryKey);
+ return false;
+ }
+
+ private holdAutomaticUpgradeForConsent(
+ retryKey: string,
+ releaseKey: string,
+ contentKey: string,
+ ): void {
+ const held = this.automaticUpgradeConsentHolds.get(retryKey);
+ if (held?.releaseKey === releaseKey && held.contentKey === contentKey) return;
+ this.automaticUpgradeConsentHolds.set(retryKey, { releaseKey, contentKey });
+ this.consentHoldsChangedListener?.();
+ }
+
+ /**
+ * 后台更新免确认只绑当前用户的默认下发资格,不绑目录上的 defaultInstall 标记。
+ * 用户退订后再自行安装时,账本仍是 market,扩权必须停下来请用户确认。
+ */
+ private serverDefaultInstallUpdateConsent(
+ owner: ActiveAppSession,
+ ledger: PluginMarketLedger,
+ plugin: VisiblePluginSummary | VisiblePluginDetail,
+ ): GhostInstallConsentPolicy {
+ if (plugin.defaultInstall !== true) return { mode: 'automatic' };
+ try {
+ if (ledger.isDefaultInstallSuppressed(defaultInstallSubject(owner), plugin.id)) {
+ return { mode: 'automatic' };
+ }
+ } catch {
+ return { mode: 'automatic' };
+ }
+ return { mode: 'exempt', reason: 'server-default-install' };
+ }
+
+ /** 给仍待用户确认新权限的更新打标记,插件页据此提示「需确认新权限」。 */
+ private withUpdateConsentHolds(
+ items: PluginMarketItem[],
+ owner: ActiveAppSession,
+ ): PluginMarketItem[] {
+ if (this.automaticUpgradeConsentHolds.size === 0) return items;
+ return items.map((item) => {
+ if (item.installState !== 'update-available') return item;
+ const retryKey = this.automaticUpgradeRetryKey(
+ owner,
+ item.sourceType === 'server' ? 'server' : 'custom',
+ item.pluginId,
+ );
+ const held = this.automaticUpgradeConsentHolds.get(retryKey);
+ return held?.releaseKey === item.releaseId
+ ? { ...item, updateRequiresConsent: true }
+ : item;
+ });
+ }
+
async snapshot(options: PluginMarketSnapshotOptions = {}): Promise<PluginMarketSnapshot> {
// 自定义市场项完全来自本地数据,不依赖服务端与登录态;服务端不可用时
// 仍然返回,unavailableReason 只表达服务端部分的不可用。
@@ -696,6 +796,9 @@ export class PluginMarketService {
}
return this.snapshotPublicCatalogWithoutOwner();
}
+ if (options.onConsentHoldsChanged) {
+ this.consentHoldsChangedListener = options.onConsentHoldsChanged;
+ }
const iconProjectionGeneration = this.nextCustomIconProjectionGeneration();
const customSourceNames = this.customSourceNamesSafe(owner);
const customDiscoveryPromise = this.discoverCustomEntriesBounded(
@@ -725,7 +828,10 @@ export class PluginMarketService {
if (!options.discoveryOnly && !options.deferReconciliation) await reconcileCustomUpdates();
requireSameMarketOwner(owner);
const snapshot: PluginMarketSnapshot = {
- items: this.projectCustomItems(customDiscovery.entries, this.localInstallSnapshot(ledger)),
+ items: this.withUpdateConsentHolds(
+ this.projectCustomItems(customDiscovery.entries, this.localInstallSnapshot(ledger)),
+ owner,
+ ),
unavailableReason,
customSourceNames,
unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,
@@ -822,7 +928,10 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const local = this.localInstallSnapshot(ledger);
const serverItems = plugins.map((plugin) => this.toItem(plugin, local));
- const items = [...serverItems, ...this.projectCustomItems(customDiscovery.entries, local)];
+ const items = this.withUpdateConsentHolds(
+ [...serverItems, ...this.projectCustomItems(customDiscovery.entries, local)],
+ owner,
+ );
// 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,
// 不把按旧账号解析的自定义项/账本状态发给当前会话。
requireSameMarketOwner(owner);
@@ -1107,13 +1216,25 @@ export class PluginMarketService {
async install(
pluginId: string,
options: PluginMarketInstallOptions,
- /** Main-only caller authority, rechecked immediately before package placement. */
- assertCurrent?: () => void,
+ context: PluginMarketInstallContext,
): Promise<PluginMarketInstallResult> {
+ const { assertCurrent } = context;
assertCurrent?.();
const customRef = parseCustomMarketPluginId(pluginId);
if (customRef) {
- return this.customInstall(customRef, options, false, captureMarketOwner(), assertCurrent);
+ return this.customInstall(
+ customRef,
+ options,
+ {
+ mode: 'prompt',
+ prompt: context.consent.prompt,
+ initiator: context.consent.initiator,
+ origin: 'custom-market',
+ originLabel: customRef.marketName,
+ },
+ captureMarketOwner(),
+ assertCurrent,
+ );
}
if (!isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
@@ -1121,51 +1242,58 @@ export class PluginMarketService {
this.requireConfigured();
const owner = captureMarketOwner();
const ledger = this.ledgerForOwner(owner);
- return this.withMutation(pluginId, async () => {
- requireSameMarketOwner(owner);
- // 安装必须先经目录可见性闸:本地(免账号)模式只允许 public 插件,未通过
- // 可见性的条目在调用 detail 之前就要拒掉,不能把组织私有插件的详情拉下来。
- // 目录 summary 也是 detail 身份绑定的依据:detail 自报的 id/ghostId/scope/
- // 发布必须与用户确认时看到的那份 summary 一致,否则 A 的确认会被导向 B 的内容。
- const listed = await this.api.listAll();
- requireSameMarketOwner(owner);
- this.rememberCurrentOrganization(listed.currentOrganization);
- const catalog = visiblePluginsForOwner(owner, listed.plugins);
- const selected = catalog.find((candidate) => candidate.id === pluginId);
- if (!selected) {
- throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
- }
- if (!isGhostAvailableForActiveSession(selected.ghostId)) {
- throwIpcError('PERMISSION_DENIED', 'This Plugin requires a Cindy account');
- }
- const plugin = await this.api.detail(pluginId);
- requireSameMarketOwner(owner);
- // 详情响应必须与请求的 pluginId 绑定:server 换身份会让用户审阅到别的插件。
- assertDetailMatchesSummary(selected, plugin);
- requirePluginVisibleForOwner(owner, plugin);
- if (plugin.currentRelease.id !== options.expectedReleaseId) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
- }
- const existing = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
- return this.installDetail(
- plugin,
- {
- beforeCommitInLock: assertCurrent,
- expectedInstalled: Boolean(existing),
- ...(options.expectedInstalledApproval !== undefined
- ? { expectedInstalledApproval: options.expectedInstalledApproval }
- : {}),
- sourceReplacementMode:
- options.allowSourceReplacement === true
- ? 'user-requested-source-change'
- : 'preserve-existing-source',
+ requireSameMarketOwner(owner);
+ // 确认必须在 per-plugin mutation 之外求得:用户可能几分钟不点,不能卡住同插件的
+ // 更新或卸载。落位前再取锁,并用即将落位的真实包复核。
+ // 安装必须先经目录可见性闸:本地(免账号)模式只允许 public 插件,未通过
+ // 可见性的条目在调用 detail 之前就要拒掉,不能把组织私有插件的详情拉下来。
+ // 目录 summary 也是 detail 身份绑定的依据:detail 自报的 id/ghostId/scope/
+ // 发布必须与用户确认时看到的那份 summary 一致,否则 A 的确认会被导向 B 的内容。
+ const listed = await this.api.listAll();
+ requireSameMarketOwner(owner);
+ this.rememberCurrentOrganization(listed.currentOrganization);
+ const catalog = visiblePluginsForOwner(owner, listed.plugins);
+ const selected = catalog.find((candidate) => candidate.id === pluginId);
+ if (!selected) {
+ throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
+ }
+ if (!isGhostAvailableForActiveSession(selected.ghostId)) {
+ throwIpcError('PERMISSION_DENIED', 'This Plugin requires a Cindy account');
+ }
+ const plugin = await this.api.detail(pluginId);
+ requireSameMarketOwner(owner);
+ // 详情响应必须与请求的 pluginId 绑定:server 换身份会让用户审阅到别的插件。
+ assertDetailMatchesSummary(selected, plugin);
+ requirePluginVisibleForOwner(owner, plugin);
+ if (plugin.currentRelease.id !== options.expectedReleaseId) {
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
+ }
+ const existing = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ return this.installDetail(
+ plugin,
+ {
+ consent: {
+ mode: 'prompt',
+ prompt: context.consent.prompt,
+ initiator: context.consent.initiator,
+ origin: 'market',
},
- owner,
- ledger,
- );
- });
+ beforeCommitInLock: assertCurrent,
+ expectedInstalled: Boolean(existing),
+ acquireMutation: true,
+ ...(options.expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval: options.expectedInstalledApproval }
+ : {}),
+ sourceReplacementMode:
+ options.allowSourceReplacement === true
+ ? 'user-requested-source-change'
+ : 'preserve-existing-source',
+ },
+ owner,
+ ledger,
+ );
}
async uninstall(pluginId: string): Promise<{ ok: true }> {
@@ -1340,17 +1468,19 @@ export class PluginMarketService {
* release 一致性(重发现后比对 expectedReleaseId)、冲突先装先得、
* 市场 Manifest 能力上限;打包与装入复用 installOrUpdateMarketGhostPackage。
*
- * 全程在 `withDiscoveredSource` 租约内执行:`plugin.dir` 指向 Git 源的缓存版本
+ * 打包在 `withDiscoveredSource` 租约内执行:`plugin.dir` 指向 Git 源的缓存版本
* 目录,打包要逐文件读它。租约必须一直持到打包结束,否则并发刷新的清理能在
- * 打包途中删掉该目录(安装随机失败或产物残缺)。
+ * 打包途中删掉该目录。确认等待在租约外进行;落位再取 mutation,并保留提交时的来源复核。
*/
private async customInstall(
ref: { marketName: string; ghostId: string },
options: PluginMarketInstallOptions,
- automatic = false,
+ /** 显式安装走 prompt;后台更新走 automatic(需要确认就放弃本轮)。 */
+ consent: GhostInstallConsentPolicy,
owner = captureMarketOwner(),
assertCurrent?: () => void,
): Promise<PluginMarketInstallResult> {
+ const automatic = consent.mode === 'automatic';
if (options.expectedManifest === undefined) {
throwIpcError(
'INVALID_PARAMS',
@@ -1359,10 +1489,10 @@ export class PluginMarketService {
}
const ledger = this.ledgerForOwner(owner);
const manager = this.sourceManagerForOwner(owner);
- // 互斥键与 uninstall 一致使用规范化 pluginId,保证同插件的安装/更新/卸载串行。
- return this.withMutation(customMarketPluginId(ref.marketName, ref.ghostId), async () => {
- requireSameMarketOwner(owner);
- return manager.withDiscoveredSource(ref.marketName, async (discovered) => {
+ requireSameMarketOwner(owner);
+ // 打包必须持有来源租约(目录字节);确认等待不能占用 cache-path 租约或
+ // per-plugin mutation。用户未回答时,来源移除/刷新清理与同插件卸载都不能排队。
+ const packedAttempt = await manager.withDiscoveredSource(ref.marketName, async (discovered) => {
if (!discovered.result.ok) {
throwIpcError(discovered.result.code, discovered.result.detail ?? discovered.result.code);
}
@@ -1413,17 +1543,58 @@ export class PluginMarketService {
}
};
assertCustomApprovalStateUnchanged(existing ?? null);
+ requireSameMarketOwner(owner);
+ const packed = await packCustomMarketPlugin({
+ pluginDir: plugin.dir,
+ expected: options.expectedManifest,
+ expectedGhostId: plugin.ghostId,
+ expectedVersion: plugin.version,
+ });
+ return {
+ packed,
+ plugin,
+ pluginId,
+ releaseId,
+ existing,
+ sourceKey,
+ reviewInstalledIdentity,
+ sourceType: discovered.config.source.type,
+ assertCustomApprovalStateUnchanged,
+ };
+ });
+ try {
+ const {
+ packed,
+ plugin,
+ pluginId,
+ releaseId,
+ existing,
+ sourceKey,
+ reviewInstalledIdentity,
+ sourceType,
+ assertCustomApprovalStateUnchanged,
+ } = packedAttempt;
// 来源只决定后台更新路由,不是 ghostId 的永久所有权。只有详情页明确
// 选择“替换”才允许原地切换来源;自动更新和手动重试必须保持当前路由。
let replacedRoute: PluginMarketInstallationRecord | null = null;
let replacedRouteWasSuppressed = false;
let packageLanded = false;
requireSameMarketOwner(owner);
- const installResult = await installCustomMarketPlugin({
- pluginDir: plugin.dir,
- expected: options.expectedManifest,
+ const consentDecision: GhostInstallConsentDecision =
+ 'rejection' in packed.inspected
+ ? { mode: 'unprompted' }
+ : await obtainGhostInstallConsent(
+ consent,
+ getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId),
+ packed.inspected.manifest,
+ packed.inspected.packageSha256,
+ );
+ const installResult = await commitCustomMarketPlugin(packed, {
expectedGhostId: plugin.ghostId,
expectedVersion: plugin.version,
+ consent: consentDecision,
beforeCommit: async () => {
requireSameMarketOwner(owner);
assertCurrent?.();
@@ -1512,7 +1683,9 @@ export class PluginMarketService {
// 按 id 互斥,beforeCommit 的 runtime 复核到 installOrUpdate 落位之间,
// 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。
withCommitLock: (fn) =>
- this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
+ this.withMutation(customMarketPluginId(ref.marketName, ref.ghostId), () =>
+ this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
+ ),
// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):
// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。
// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。
@@ -1534,7 +1707,7 @@ export class PluginMarketService {
sha256: 'custom-unverified',
scope: 'public',
organizationId: null,
- source: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',
+ source: sourceType === 'git' ? 'git-market' : 'local-market',
installed: true,
updatedAt: new Date().toISOString(),
// 来源指纹与 pluginId 一起标识后续自动更新路由。
@@ -1559,8 +1732,9 @@ export class PluginMarketService {
throw error;
});
return installResult;
- });
- });
+ } finally {
+ await fs.promises.rm(packedAttempt.packed.tempPath, { force: true }).catch(() => undefined);
+ }
}
/** 已配置来源名(按添加顺序);存储读取失败时降级为空数组。 */
@@ -1778,6 +1952,11 @@ export class PluginMarketService {
private async installDetail(
plugin: VisiblePluginDetail,
options: {
+ /**
+ * 用户确认策略:显式安装 prompt、后台更新 automatic、服务端默认安装 exempt。
+ * 必填,下载并检查真实包后按它求确认,再交给装入出口在锁内复核。
+ */
+ consent: GhostInstallConsentPolicy;
/** receipt 模型的并发护栏:比对 receipt 派生 token,状态变更即拒(与 main 硬化叠加)。 */
expectedInstalledApproval?: string;
/** 是否保留现有来源,或按明确意图切换来源。 */
@@ -1785,7 +1964,12 @@ export class PluginMarketService {
beforeCommitInLock?: () => void;
/** 发起操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
- } = { expectedInstalled: false },
+ /**
+ * 手动安装已在锁外求确认。确认后、落位前才取 per-plugin mutation,
+ * 避免用户未回答时卡住同插件卸载/更新。后台路径仍由调用方持锁。
+ */
+ acquireMutation?: boolean;
+ },
owner = captureMarketOwner(),
ledger = this.ledgerForOwner(owner),
): Promise<PluginMarketInstallResult> {
@@ -1868,20 +2052,42 @@ export class PluginMarketService {
throwIpcError('GHOST_FILE_INVALID', 'Downloaded Plugin package identity changed');
}
}
- const ghost = await this.commitDownloadedPackage(
- tempPath,
- plugin,
- {
- expectedInstalled: options.expectedInstalled,
- ...(options.expectedInstalledApproval !== undefined
- ? { expectedInstalledApproval: options.expectedInstalledApproval }
- : {}),
- sourceReplacementMode,
- beforeCommitInLock: options.beforeCommitInLock,
- },
- owner,
- ledger,
- );
+ // 权限以真实包为准:下载检查后、任何安装锁之外求确认。检查失败的包会在装入
+ // 出口重新解析时被拒,不为它弹确认。
+ const consent: GhostInstallConsentDecision =
+ 'rejection' in inspected
+ ? { mode: 'unprompted' }
+ : await obtainGhostInstallConsent(
+ options.consent,
+ getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId),
+ inspected.manifest,
+ inspected.packageSha256,
+ );
+ requireSameMarketOwner(owner);
+ const commit = () =>
+ this.commitDownloadedPackage(
+ tempPath,
+ plugin,
+ {
+ consent,
+ expectedInstalled: options.expectedInstalled,
+ ...(options.expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval: options.expectedInstalledApproval }
+ : {}),
+ sourceReplacementMode,
+ beforeCommitInLock: options.beforeCommitInLock,
+ },
+ owner,
+ ledger,
+ );
+ const ghost = options.acquireMutation
+ ? await this.withMutation(plugin.id, async () => {
+ requireSameMarketOwner(owner);
+ return commit();
+ })
+ : await commit();
return { ghost };
} finally {
await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
@@ -1893,6 +2099,7 @@ export class PluginMarketService {
tempPath: string,
plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
+ consent: GhostInstallConsentDecision;
expectedInstalledApproval?: string;
sourceReplacementMode: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
@@ -1971,6 +2178,7 @@ export class PluginMarketService {
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
+ consent: options.consent,
...(plugin.ghostId === 'cindy-github' ? { officialCindyGithub: true } : {}),
...(plugin.scope === 'organization' && plugin.organizationId
? {
@@ -2409,6 +2617,8 @@ export class PluginMarketService {
await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: 'cindy-github',
version: currentRecord.version,
+ // 同一 release 原样重装只补来源信任,权限面不变;万一扩权则放弃本轮而不替用户确认。
+ consent: { mode: 'unprompted' },
expectedInstalledApproval: ghostInstallApprovalToken(currentInstalled.approval),
officialCindyGithub: true,
afterCommitInLock: async (_committed, evidence) => {
@@ -2632,6 +2842,8 @@ export class PluginMarketService {
await this.installDetail(
detail,
{
+ // 服务端为当前身份下发的默认插件由下发方决定,首装与接管都不向用户确认。
+ consent: { mode: 'exempt', reason: 'server-default-install' },
expectedInstalled: freshState === 'conflict',
...(expectedInstalledApproval ? { expectedInstalledApproval } : {}),
sourceReplacementMode:
@@ -2760,7 +2972,8 @@ export class PluginMarketService {
(record?.source !== 'market' && record?.source !== 'legacy-adopted') ||
this.toItem(summary, local).installState !== 'update-available' ||
isGhostBusy(summary.ghostId) ||
- this.shouldDeferAutomaticUpgrade(retryKey, releaseKey)
+ this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||
+ this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, releaseKey)
) {
continue;
}
@@ -2802,6 +3015,10 @@ export class PluginMarketService {
await this.installDetail(
detail,
{
+ // 只有当前用户仍具备该插件的默认下发资格时才免确认。用户退订后再
+ // 自行从市场安装时,账本仍是 market、目录仍可能标 defaultInstall,
+ // 但 opt-out 还在,扩权必须停下来请用户确认。
+ consent: this.serverDefaultInstallUpdateConsent(owner, ledger, detail),
expectedInstalled: true,
expectedInstalledApproval: ghostInstallApprovalToken(freshInstalled.approval),
beforeCommitInLock: () => {
@@ -2817,7 +3034,16 @@ export class PluginMarketService {
local = this.localInstallSnapshot(ledger);
this.clearAutomaticUpgradeFailure(retryKey, releaseKey);
} catch (error) {
- if (error instanceof SilentUpgradeBusyError) {
+ if (isGhostInstallConsentRequiredError(error)) {
+ // 等用户确认不是失败:不退避、不告警,同一 release 不再重复下载。
+ this.holdAutomaticUpgradeForConsent(retryKey, releaseKey, releaseKey);
+ log.info('automatic Plugin update awaits user confirmation of new permissions', {
+ pluginId: summary.id,
+ releaseId: releaseKey,
+ addedPermissions:
+ error.facts.kind === 'update' ? error.facts.added.map((item) => item.key) : [],
+ });
+ } else if (error instanceof SilentUpgradeBusyError) {
reconciled = false;
} else {
reconciled = false;
@@ -2837,12 +3063,14 @@ export class PluginMarketService {
const projected = this.customToItem(entry, local);
const retryKey = this.automaticUpgradeRetryKey(owner, 'custom', projected.pluginId);
const releaseKey = projected.releaseId;
+ const contentKey = ghostManifestDigest(entry.plugin.manifest);
const installed = local.ghostsById.get(projected.ghostId);
if (
projected.installState !== 'update-available' ||
isGhostBusy(projected.ghostId) ||
installed?.approval.state !== 'approved' ||
- this.shouldDeferAutomaticUpgrade(retryKey, releaseKey)
+ this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||
+ this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, contentKey)
) {
continue;
}
@@ -2856,13 +3084,22 @@ export class PluginMarketService {
expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
allowSourceReplacement: false,
},
- true,
+ { mode: 'automatic' },
owner,
);
local = this.localInstallSnapshot(ledger);
this.clearAutomaticUpgradeFailure(retryKey, releaseKey);
} catch (error) {
- if (error instanceof SilentUpgradeBusyError) {
+ if (isGhostInstallConsentRequiredError(error)) {
+ this.holdAutomaticUpgradeForConsent(retryKey, releaseKey, contentKey);
+ log.info('automatic custom Plugin update awaits user confirmation of new permissions', {
+ pluginId: projected.pluginId,
+ market: entry.config.name,
+ releaseId: releaseKey,
+ addedPermissions:
+ error.facts.kind === 'update' ? error.facts.added.map((item) => item.key) : [],
+ });
+ } else if (error instanceof SilentUpgradeBusyError) {
reconciled = false;
} else {
reconciled = false;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 8bd8a5a6fa..4360b1deaf 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -563,6 +563,9 @@ const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored')
const fanOutPluginRemovalNoticeAvailable = createIpcFanOut(
'plugin-market:removal-notice-available',
);
+const fanOutPluginUpdateConsentHoldsChanged = createIpcFanOut(
+ 'plugin-market:update-consent-holds-changed',
+);
// #37: release 端检测到 schema drift 时一次性 toast 提示开发者切回 dev 自动修复
const fanOutSchemaDriftWarning = createIpcFanOut('local-db:schema-drift-warning');
const fanOutProjectAliasesChanged = createIpcFanOut('local-db:project-aliases:changed');
@@ -702,6 +705,9 @@ const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');
// main 只投单个窗口(不广播),所以这里落地的窗口就是该弹框的唯一归属。
const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');
const fanOutForgeOidcInstallConfirmRequest = createIpcFanOut('forge-oidc-install:confirm-request');
+// 插件安装/更新确认(main 只投给发起安装的那个窗口;超时或取消时再发 dismissed 收起)。
+const fanOutGhostInstallConsentRequest = createIpcFanOut('ghosts:install-consent:request');
+const fanOutGhostInstallConsentDismissed = createIpcFanOut('ghosts:install-consent:dismissed');
// 插件预览开页(preview 槽:renderer 在右侧栏开 web-browser 标签)。
const fanOutGhostPreviewOpen = createIpcFanOut('ghosts:preview-open');
// 插件自动化草稿(agent 槽 schedule 加档:renderer 开自动化创建面板并预填)。
@@ -1395,6 +1401,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
confirmed: boolean,
): Promise<{ handled: boolean }> =>
ipcRenderer.invoke('forge-oidc-install:resolve-confirm', { requestId, confirmed }),
+ onInstallConsentRequest: fanOutGhostInstallConsentRequest,
+ onInstallConsentDismissed: fanOutGhostInstallConsentDismissed,
+ resolveInstallConsent: (
+ requestId: string,
+ confirmed: boolean,
+ ): Promise<{ handled: boolean }> =>
+ ipcRenderer.invoke('ghosts:install-consent:resolve', { requestId, confirmed }),
onPreviewOpen: fanOutGhostPreviewOpen,
onScheduleDraft: fanOutGhostScheduleDraft,
getCard: (
@@ -1499,6 +1512,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
import('../shared/pluginMarket').PluginRemovalUserNotice | null
> => ipcRenderer.invoke('plugin-market:consume-removal-notice'),
onRemovalNoticeAvailable: fanOutPluginRemovalNoticeAvailable,
+ onUpdateConsentHoldsChanged: fanOutPluginUpdateConsentHoldsChanged,
listSources: (): Promise<import('../shared/pluginMarket').MarketSourceSummary[]> =>
ipcRenderer.invoke('plugin-market:list-sources'),
pickLocalSource: (
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index eb5ae6504d..53c3a19798 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -32,6 +32,7 @@ import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';
import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';
import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';
import { ForgeOidcInstallConfirmHost } from '@/cindy-brain/ForgeOidcInstallConfirmHost';
+import { GhostInstallConsentHost } from '@/cindy-brain/GhostInstallConsentHost';
import { PluginPublisherConfirmHost } from '@/features/plugin/PluginPublisherConfirmHost';
import { makerChatStore } from '@/lib/makerChatStore';
import {
@@ -421,6 +422,7 @@ export function App() {
都挂、谁收到谁弹,不按窗口类型 gate。 */}
<GhostConfirmDialogHost />
<ForgeOidcInstallConfirmHost />
+ <GhostInstallConsentHost />
<PluginPublisherConfirmHost />
<OwnerScopedRouter />
</EnvCheckGuard>
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx b/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx
new file mode 100644
index 0000000000..0e12cf1c60
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx
@@ -0,0 +1,254 @@
+/**
+ * 插件安装/更新确认框(docs/dev-rules/plugin-security-and-authoring.md §3.1)。
+ *
+ * Main 在用户从插件页、拖入或双击 `.cindy` 发起安装后,检查完真实包、在任何安装锁之外
+ * 把确认请求投给发起安装的这个窗口;首次安装展示全部权限,更新只在权限变多时出现并
+ * 高亮变化。无论确认、取消还是被 Main 收起(超时、账号切换),答案都会回给 Main。
+ * 落位前 Main 还会在锁内用同一份包复核,确认框本身不是授权事实。
+ */
+import { useEffect, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';
+import { permissionItemIcon } from '@/features/plugin/lib/permissionItemIcon';
+import { cn } from '@/lib/utils';
+import type { GhostPermissionItem } from '../../shared/ghost';
+import type {
+ GhostInstallConsentFacts,
+ GhostInstallConsentRequest,
+} from '../../shared/ghostInstallConsent';
+
+type Translate = ReturnType<typeof useTranslation>['t'];
+
+/** 来源说明与 Main 侧任务确认卡同口径(ghostInstallConsentInteraction.ts)。 */
+export function ghostInstallConsentSourceLabel(
+ t: Translate,
+ request: Pick<GhostInstallConsentRequest, 'initiator' | 'origin' | 'originLabel'>,
+): string {
+ const origin =
+ request.origin === 'market'
+ ? t('settings.ghosts.installConsent.originMarket')
+ : request.origin === 'custom-market'
+ ? request.originLabel
+ ? t('settings.ghosts.installConsent.originCustomMarket', { name: request.originLabel })
+ : t('settings.ghosts.installConsent.originCustomMarketUnnamed')
+ : request.origin === 'local-file'
+ ? t('settings.ghosts.installConsent.originLocalFile')
+ : t('settings.ghosts.installConsent.originForge');
+ return request.initiator === 'agent'
+ ? t('settings.ghosts.installConsent.initiatedByAgent', { origin })
+ : origin;
+}
+
+function ConsentPermissionRow({
+ item,
+ change,
+}: {
+ item: GhostPermissionItem;
+ change?: 'added' | 'removed';
+}) {
+ const { t } = useTranslation();
+ const Icon = permissionItemIcon(item);
+ const hostDetail = item.detailKey
+ ? t(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs)
+ : null;
+ return (
+ <li className={cn('flex items-start gap-2.5 py-1.5', change === 'removed' && 'opacity-60')}>
+ <Icon
+ size={16}
+ strokeWidth={1.8}
+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1">
+ <p
+ className={cn(
+ // labelArgs 含作者可控的无空格长串(域名、工具名),必须可断行。
+ 'break-words text-13 leading-5 text-[var(--confirm-title)]',
+ change === 'removed' && 'line-through',
+ )}
+ >
+ {t(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs)}
+ </p>
+ {hostDetail ? (
+ <p className="mt-0.5 whitespace-pre-line break-words text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {hostDetail}
+ </p>
+ ) : null}
+ {item.detail ? (
+ <p className="mt-0.5 whitespace-pre-line break-words text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {item.detail}
+ </p>
+ ) : null}
+ </div>
+ {change === 'added' ? (
+ // 权限新增是一次 diff,沿用 diff 语义色(跨主题 token)。徽章是 chrome,不可选中。
+ <span className="mt-0.5 shrink-0 select-none rounded-full px-1.5 py-px text-11 font-medium bg-[var(--diff-add-bg)] text-[var(--diff-add-fg)]">
+ {t('settings.ghosts.installConsent.addedBadge')}
+ </span>
+ ) : null}
+ </li>
+ );
+}
+
+function ConsentSection({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section className="mt-3 first:mt-0">
+ <h3 className="text-12 font-medium leading-[1.5] text-[var(--text-secondary)]">{title}</h3>
+ <ul className="mt-1">{children}</ul>
+ </section>
+ );
+}
+
+export function GhostInstallConsentContent({ facts }: { facts: GhostInstallConsentFacts }) {
+ const { t } = useTranslation();
+ if (facts.kind === 'install') {
+ return (
+ <div>
+ <p className="text-13 leading-5 text-[var(--confirm-desc)]">
+ {t('settings.ghosts.installConsent.installDescription')}
+ </p>
+ <div className="mt-3">
+ {facts.permissions.length === 0 ? (
+ <p className="text-13 leading-5 text-[var(--confirm-desc)]">
+ {t('settings.ghosts.installConsent.noPermissions')}
+ </p>
+ ) : (
+ <ConsentSection title={t('settings.ghosts.installConsent.grantsTitle')}>
+ {facts.permissions.map((item) => (
+ <ConsentPermissionRow key={item.key} item={item} />
+ ))}
+ </ConsentSection>
+ )}
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div>
+ <p className="text-13 leading-5 text-[var(--confirm-desc)]">
+ {t('settings.ghosts.installConsent.updateDescription')}
+ </p>
+ {facts.builtinOauthClientChanged ? (
+ <p className="mt-2 text-13 leading-5 text-[var(--confirm-desc)]">
+ {t('settings.ghosts.installConsent.oauthClientChanged')}
+ </p>
+ ) : null}
+ <div className="mt-3">
+ {facts.added.length > 0 ? (
+ <ConsentSection title={t('settings.ghosts.installConsent.addedTitle')}>
+ {facts.added.map((item) => (
+ <ConsentPermissionRow key={item.key} item={item} change="added" />
+ ))}
+ </ConsentSection>
+ ) : null}
+ {facts.removed.length > 0 ? (
+ <ConsentSection title={t('settings.ghosts.installConsent.removedTitle')}>
+ {facts.removed.map((item) => (
+ <ConsentPermissionRow key={item.key} item={item} change="removed" />
+ ))}
+ </ConsentSection>
+ ) : null}
+ {facts.unchangedCount > 0 ? (
+ <p className="mt-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.ghosts.installConsent.unchangedCount', { count: facts.unchangedCount })}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function isConsentRequest(payload: unknown): payload is GhostInstallConsentRequest {
+ if (!payload || typeof payload !== 'object') return false;
+ const request = payload as Partial<GhostInstallConsentRequest>;
+ const facts = request.facts as Partial<GhostInstallConsentFacts> | undefined;
+ return (
+ typeof request.requestId === 'string' &&
+ (request.initiator === 'user' || request.initiator === 'agent') &&
+ typeof request.origin === 'string' &&
+ !!facts &&
+ (facts.kind === 'install' || facts.kind === 'update') &&
+ typeof facts.name === 'string' &&
+ typeof facts.version === 'string'
+ );
+}
+
+/** 挂在每个窗口的 ConfirmDialogProvider 内;Main 只把请求投给发起安装的那个窗口。 */
+export function GhostInstallConsentHost() {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+
+ useEffect(() => {
+ const aborts = new Map<string, AbortController>();
+ const unsubscribeDismissed = window.electronAPI.ghosts.onInstallConsentDismissed(
+ (payload) => {
+ if (payload && typeof payload.requestId === 'string') {
+ aborts.get(payload.requestId)?.abort();
+ }
+ },
+ );
+ const unsubscribeRequest = window.electronAPI.ghosts.onInstallConsentRequest(
+ (payload, ownerStamp) => {
+ if (!isConsentRequest(payload)) return;
+ const request = payload;
+ const abort = new AbortController();
+ aborts.set(request.requestId, abort);
+ void (async () => {
+ let confirmed = false;
+ try {
+ // 账号已切换的旧请求不渲染任何插件事实,直接按取消回给 Main。
+ if (ownerStamp !== undefined && !isDataOwnerPushStampCurrent(ownerStamp)) return;
+ const { facts } = request;
+ const source = ghostInstallConsentSourceLabel(t, request);
+ confirmed = await confirm(
+ {
+ title:
+ facts.kind === 'install'
+ ? t('settings.ghosts.installConsent.installTitle', { name: facts.name })
+ : t('settings.ghosts.installConsent.updateTitle', { name: facts.name }),
+ description:
+ facts.kind === 'install'
+ ? t('settings.ghosts.installConsent.installMeta', {
+ version: facts.version,
+ source,
+ })
+ : t('settings.ghosts.installConsent.updateMeta', {
+ from: facts.previousVersion,
+ to: facts.version,
+ source,
+ }),
+ content: <GhostInstallConsentContent facts={facts} />,
+ maxWidth: 460,
+ contentSelectable: true,
+ describeContent: true,
+ confirmText:
+ facts.kind === 'install'
+ ? t('settings.ghosts.installConsent.confirmInstall')
+ : t('settings.ghosts.installConsent.confirmUpdate'),
+ cancelText: t('settings.ghosts.installConsent.cancel'),
+ },
+ abort.signal,
+ );
+ } finally {
+ aborts.delete(request.requestId);
+ try {
+ await window.electronAPI.ghosts.resolveInstallConsent(request.requestId, confirmed);
+ } catch {
+ // 窗口销毁或 Main 已按超时结算时,这次回答不再生效。
+ }
+ }
+ })();
+ },
+ );
+ return () => {
+ unsubscribeRequest();
+ unsubscribeDismissed();
+ for (const abort of aborts.values()) abort.abort();
+ aborts.clear();
+ };
+ }, [confirm, t]);
+
+ return null;
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx
new file mode 100644
index 0000000000..b569f6c084
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ReactNode } from 'react';
+
+import type { GhostInstallConsentRequest } from '../../../shared/ghostInstallConsent';
+import { GhostInstallConsentHost } from '../GhostInstallConsentHost';
+
+const mocks = vi.hoisted(() => ({ confirm: vi.fn() }));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: mocks.confirm }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, args?: Record<string, unknown>) =>
+ args && Object.keys(args).length > 0 ? `${key}:${JSON.stringify(args)}` : key,
+ }),
+}));
+
+type Push = (payload: GhostInstallConsentRequest, ownerStamp?: unknown) => void;
+
+const HOST = {
+ key: 'network:host:upload.weather.test',
+ kind: 'network' as const,
+ labelKey: 'networkHost',
+ labelArgs: { host: 'upload.weather.test' },
+};
+
+describe('GhostInstallConsentHost', () => {
+ let push: Push | undefined;
+ let dismiss: ((payload: { requestId: string }) => void) | undefined;
+ const resolveInstallConsent = vi.fn();
+
+ beforeEach(() => {
+ mocks.confirm.mockReset().mockResolvedValue(true);
+ resolveInstallConsent.mockReset().mockResolvedValue({ handled: true });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ ghosts: {
+ onInstallConsentRequest: (callback: Push) => {
+ push = callback;
+ return () => {};
+ },
+ onInstallConsentDismissed: (callback: typeof dismiss) => {
+ dismiss = callback;
+ return () => {};
+ },
+ resolveInstallConsent,
+ },
+ };
+ });
+
+ afterEach(() => {
+ cleanup();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ });
+
+ it('shows the added permissions of an update and returns the answer to Main', async () => {
+ render(<GhostInstallConsentHost />);
+ await act(async () => {
+ push?.({
+ requestId: 'consent-1',
+ initiator: 'user',
+ origin: 'custom-market',
+ originLabel: 'Team market',
+ facts: {
+ kind: 'update', ghostId: 'weather-chip', name: 'Weather', version: '2.0.0',
+ previousVersion: '1.0.0', added: [HOST], removed: [], unchangedCount: 1,
+ builtinOauthClientChanged: false,
+ },
+ });
+ });
+
+ await waitFor(() => expect(resolveInstallConsent).toHaveBeenCalledWith('consent-1', true));
+ const options = mocks.confirm.mock.calls[0][0] as {
+ title: string;
+ description: string;
+ confirmText: string;
+ content: ReactNode;
+ };
+ expect(options.title).toBe('settings.ghosts.installConsent.updateTitle:{"name":"Weather"}');
+ expect(options.description).toContain('"from":"1.0.0"');
+ expect(options.description).toContain('originCustomMarket');
+ expect(options.confirmText).toBe('settings.ghosts.installConsent.confirmUpdate');
+ render(<>{options.content}</>);
+ expect(screen.getByText('settings.ghosts.perm.networkHost:{"host":"upload.weather.test"}')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.installConsent.addedBadge')).toBeTruthy();
+ });
+
+ it('answers cancel when Main dismisses the pending dialog', async () => {
+ let seenSignal: AbortSignal | undefined;
+ mocks.confirm.mockImplementation(
+ (_options: unknown, signal: AbortSignal) =>
+ new Promise<boolean>((resolve) => {
+ seenSignal = signal;
+ signal.addEventListener('abort', () => resolve(false));
+ }),
+ );
+ render(<GhostInstallConsentHost />);
+ await act(async () => {
+ push?.({
+ requestId: 'consent-2',
+ initiator: 'user',
+ origin: 'local-file',
+ facts: { kind: 'install', ghostId: 'weather-chip', name: 'Weather', version: '1.0.0', permissions: [] },
+ });
+ });
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ dismiss?.({ requestId: 'consent-2' });
+ });
+ expect(seenSignal?.aborted).toBe(true);
+ await waitFor(() => expect(resolveInstallConsent).toHaveBeenCalledWith('consent-2', false));
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 7987292cf1..607bb152ac 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -10,9 +10,9 @@ import {
import { ghostInstallErrorKey } from './installErrorKey';
/**
- * 本地 .cindy 的统一一键安装/更新编排:inspect 验证真实包后直接交给 Main
- * 落位。文件选择、拖入和双击都是用户明确安装动作,不再追加插件权限确认层。
- * 同 id 已安装时转为原位更新;更新继续由 Main 延续当前启用状态。
+ * 本地 .cindy 的统一安装/更新编排:inspect 验证真实包后交给 Main。首装与权限
+ * 变多的更新由 Main 在落位前向本窗口弹确认(GhostInstallConsentHost),用户取消
+ * 时静默收口、不报错。同 id 已安装时转为原位更新;更新继续由 Main 延续当前启用状态。
*/
interface InstallFlowDeps {
@@ -25,9 +25,10 @@ interface InstallFlowDeps {
openPluginPanel?: (ghostId: string) => void;
}
-/** 安装事务失败统一走 toast。 */
+/** 安装事务失败统一走 toast;用户在确认框里取消不算失败。 */
async function showInstallError(error: unknown, deps: InstallFlowDeps): Promise<void> {
const code = extractIpcError(error)?.code;
+ if (code === 'MUTATION_CANCELLED') return;
toast.error(deps.t(ghostInstallErrorKey(code)));
}
@@ -91,7 +92,7 @@ export async function installGhostFromFile(
return;
}
- // 安装动作本身已经由用户通过文件选择/拖入/双击明确发起。安装后默认启用;
+ // 用户通过文件选择/拖入/双击发起安装,Main 会先弹确认框。安装后默认启用;
// tab 型插件在入口能提供页面板宿主时直接打开。
const willOpenPanel = manifest.panel?.position === 'tab' && deps.openPluginPanel !== undefined;
try {
diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
index 3d00135427..e7e9322576 100644
--- a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
@@ -24,6 +24,7 @@ import { Tip } from '@/components/ui/tooltip';
import { Button } from '@/components/ui/button';
import type { PendingPermission } from '@/lib/makerChatStore';
import { describeSessionPermissionScope } from '@/lib/permissionSuggestionScope';
+import { GHOST_INSTALL_CONSENT_TOOL_NAME } from '../../../shared/ghostInstallConsent';
// ---------------------------------------------------------------------------
// Props
@@ -104,14 +105,24 @@ export function PermissionPrompt({ permission, onRespond, companion }: Permissio
const { toolName, input, title, displayName, description, suggestions, autoReviewUnavailable,
submitting, submissionFailed } = permission;
const isMediaDownload = toolName === 'cindy.media.download';
+ // 插件安装确认由 Host 渲染成纯文本:首行是版本与来源,其余是权限清单。手机按原样
+ // 逐行显示;这里首行作说明,清单放进可滚动区域,不显示内部参数。
+ const isPluginInstallConsent = toolName === GHOST_INSTALL_CONSENT_TOOL_NAME;
+ const [consentHead, ...consentBody] = isPluginInstallConsent
+ ? (description ?? '').split('\n')
+ : [];
const promptDescription = autoReviewUnavailable
? t('newChat.permissionPrompt.autoReviewUnavailable')
- : description;
+ : isPluginInstallConsent
+ ? consentHead
+ : description;
const displayTitle = displayName
? t('agentIsland.native.permissionPromptTitleWithTool', { toolName: displayName })
: title || t('agentIsland.native.permissionPromptTitleWithTool', { toolName });
- const codeContent = formatToolInput(toolName, input);
+ const codeContent = isPluginInstallConsent
+ ? consentBody.join('\n')
+ : formatToolInput(toolName, input);
const sessionSuggestions = useMemo(() => filterSessionScopedSuggestions(suggestions), [suggestions]);
const canAlwaysAllowForSession = sessionSuggestions.length > 0;
// 这个按钮加的是 agent 给的一条具体规则(Bash 多为 `curl:*` 这类前缀模式),
@@ -213,12 +224,18 @@ export function PermissionPrompt({ permission, onRespond, companion }: Permissio
{/* Code block */}
<div
className={cn(
- 'mt-3 max-h-[120px] overflow-auto rounded-[8px] border px-3.5 py-2.5',
+ 'mt-3 overflow-auto rounded-[8px] border px-3.5 py-2.5',
'border-[var(--perm-code-border)] bg-[var(--perm-code-bg)]',
- 'font-mono text-[length:calc(var(--app-code-font-size)_-_1px)] leading-relaxed text-[var(--chat-input-text)]',
+ isPluginInstallConsent
+ ? 'max-h-[240px] text-13 leading-relaxed text-[var(--chat-input-text)]'
+ : 'max-h-[120px] font-mono text-[length:calc(var(--app-code-font-size)_-_1px)] leading-relaxed text-[var(--chat-input-text)]',
)}
>
- <pre className="whitespace-pre-wrap break-all">{codeContent}</pre>
+ {isPluginInstallConsent ? (
+ <p className="whitespace-pre-wrap break-words">{codeContent}</p>
+ ) : (
+ <pre className="whitespace-pre-wrap break-all">{codeContent}</pre>
+ )}
</div>
{/* Action buttons — inline text + kbd badges, right-aligned.
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx
index 1d422fa1d7..604c8262e6 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx
@@ -194,3 +194,26 @@ describe('PermissionPrompt 的会话级授权按钮', () => {
);
});
});
+
+describe('PermissionPrompt 的插件安装确认', () => {
+ it('首行作说明,权限清单放进可滚动区域,不显示内部参数', () => {
+ render(
+ <PermissionPrompt
+ permission={{
+ requestId: 'req-install',
+ toolName: 'cindy.plugin.install',
+ input: { ghost_id: 'weather-chip', version: '1.0.0' },
+ title: '安装插件「Weather」?',
+ description: '版本 1.0.0 · 由 Agent 发起 · 来自 Cindy 插件市场\n确认后才会安装。\n安装后它将拥有:\n• 访问 api.weather.test',
+ }}
+ onRespond={vi.fn()}
+ />,
+ );
+ expect(screen.getByText('版本 1.0.0 · 由 Agent 发起 · 来自 Cindy 插件市场')).toBeTruthy();
+ const list = screen.getByText(/安装后它将拥有/);
+ expect(list.textContent).toContain('• 访问 api.weather.test');
+ expect(list.textContent).not.toContain('版本 1.0.0');
+ expect(screen.queryByText(/weather-chip/)).toBeNull();
+ expect(screen.queryByRole('button', { name: /alwaysAllow/ })).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 55ada21317..9fdfa1a8b1 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -15,35 +15,15 @@ import {
AppWindow,
AlertTriangle,
ArrowUp,
- Bot,
ChevronDown,
Copy,
- Cpu,
Download,
MessageCircle,
- FileCode2,
- FilePen,
FolderOpen,
- FolderPlus,
- Globe,
- GraduationCap,
- KeyRound,
LayoutTemplate,
- Library,
- MapPin,
- Megaphone,
- MessageCircleQuestion,
MoreVertical,
- PanelLeft,
- PanelRight,
- Radio,
- Smartphone,
- Sparkles,
- Terminal,
Trash2,
- Wrench,
X,
- type LucideIcon,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -74,6 +54,7 @@ import { GhostPluginIcon } from './GhostPluginIcon';
import { IOSSimulatorPreferences } from './IOSSimulatorPreferences';
import { ghostPluginSummary } from './lib/ghostPluginDetailModel';
import { ghostPrimaryAction } from './lib/ghostPluginViewModel';
+import { permissionItemIcon } from './lib/permissionItemIcon';
import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';
import './plugin-motion.css';
@@ -108,44 +89,6 @@ interface GhostPluginDetailViewProps {
onIconLoadError?: () => void;
}
-const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
- cindy: Sparkles,
- agent: Bot,
- node: Cpu,
- tool: Wrench,
- command: Terminal,
- panel: PanelRight,
- 'main-view': AppWindow,
- code: FileCode2,
- subscribe: Radio,
- card: LayoutTemplate,
- network: Globe,
- notify: Megaphone,
- confirm: MessageCircleQuestion,
- fs: FilePen,
- library: Library,
- 'session-context': MapPin,
- pick: FolderOpen,
- preview: AppWindow,
- skill: GraduationCap,
- 'ios-simulator': Smartphone,
- workspace: FolderPlus,
-};
-
-/** Chooses a visual affordance without changing the host-owned permission title or meaning. */
-function permissionItemIcon(item: GhostPermissionItem): LucideIcon {
- if (item.labelKey === 'panelLeft') return PanelLeft;
- if (
- item.labelKey === 'networkSecret' ||
- item.labelKey === 'networkSecretOauth' ||
- item.labelKey === 'networkSecretGhCli' ||
- item.labelKey === 'networkSecretIdentity'
- ) {
- return KeyRound;
- }
- return PERMISSION_ICON[item.kind];
-}
-
const DETAIL_SECTION_CLASS = 'mt-10';
const DETAIL_SECTION_HEADING_CLASS =
'text-18 font-medium leading-[1.444] text-[var(--text-primary)]';
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 82abf95cc7..f7aace5ec2 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -29,6 +29,7 @@ import {
ChevronRight,
MessageCircle,
Plus,
+ ShieldAlert,
SlidersHorizontal,
Sparkles,
Store,
@@ -399,6 +400,8 @@ export function GhostPluginPage({
const { confirm } = useConfirmDialog();
const showPluginMarketActionError = useCallback(
async (error: unknown) => {
+ // 用户在安装确认框里取消不是失败,不弹错误提示。
+ if (extractIpcError(error)?.code === 'MUTATION_CANCELLED') return;
toast.error(t(pluginMarketErrorKey(error)));
},
[t],
@@ -574,6 +577,11 @@ export function GhostPluginPage({
}, [clearPluginCatalogScrollRestore, refreshMarket, mode, dataOwnerId]);
const refreshMarketOnForeground = useCallback(() => refreshMarket(true), [refreshMarket]);
usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);
+ useEffect(() => {
+ return window.electronAPI.pluginMarket.onUpdateConsentHoldsChanged(() => {
+ void refreshMarket(true).catch(() => undefined);
+ });
+ }, [refreshMarket]);
useEffect(() => {
if (installedGhostMarketKeyRef.current === installedGhostMarketKey) return;
installedGhostMarketKeyRef.current = installedGhostMarketKey;
@@ -1746,6 +1754,7 @@ export function GhostPluginPage({
item={item}
sourceLabel={t(`settings.ghosts.page.origin.${item.origin}`)}
updateVersion={item.marketUpdate?.version}
+ updateNeedsConsent={item.marketUpdate?.updateRequiresConsent === true}
updateBusy={
(item.marketUpdate !== null && marketBusyId !== null) || batchRunning
}
@@ -1775,6 +1784,7 @@ export function GhostPluginPage({
item={item}
sourceLabel={t(`settings.ghosts.page.origin.${item.origin}`)}
updateVersion={item.marketUpdate?.version}
+ updateNeedsConsent={item.marketUpdate?.updateRequiresConsent === true}
updateBusy={
(item.marketUpdate !== null && marketBusyId !== null) || batchRunning
}
@@ -2245,6 +2255,7 @@ export function GhostPluginCard({
item,
sourceLabel,
updateVersion,
+ updateNeedsConsent = false,
updateBusy = false,
updatePending = false,
onUpdate,
@@ -2257,6 +2268,8 @@ export function GhostPluginCard({
sourceLabel?: string;
/** 市场存在新版本时的目标版本;与 onUpdate 同时提供。 */
updateVersion?: string;
+ /** 新版本权限变多、后台更新已暂停等用户确认(Main 按真实包判定)。 */
+ updateNeedsConsent?: boolean;
updateBusy?: boolean;
/** 本卡正在更新:更新胶囊换成 Spinner。 */
updatePending?: boolean;
@@ -2353,6 +2366,12 @@ export function GhostPluginCard({
<Check size={11} className="inline" aria-hidden="true" />
{t('settings.ghosts.page.upToDate')}
</span>
+ ) : updateNeedsConsent ? (
+ <span className="inline-flex items-center gap-1 text-[var(--text-secondary)]">
+ {' · '}
+ <ShieldAlert size={11} className="inline" aria-hidden="true" />
+ {t('settings.ghosts.installConsent.updateNeedsConsent')}
+ </span>
) : null}
{!enabled ? ` · ${t('settings.ghosts.disabledTag')}` : ''}
</span>
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index 2352e15ea8..a9c078a2fb 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -104,6 +104,7 @@ beforeEach(() => {
unavailableCustomSourceNames: [],
}),
detail: loadDetail,
+ onUpdateConsentHoldsChanged: () => () => {},
},
setApplicationMenuLocale: async () => {},
});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts b/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts
new file mode 100644
index 0000000000..176fb7c0ea
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts
@@ -0,0 +1,68 @@
+import {
+ AppWindow,
+ Bot,
+ Cpu,
+ FileCode2,
+ FilePen,
+ FolderOpen,
+ FolderPlus,
+ Globe,
+ GraduationCap,
+ KeyRound,
+ LayoutTemplate,
+ Library,
+ MapPin,
+ Megaphone,
+ MessageCircleQuestion,
+ PanelLeft,
+ PanelRight,
+ Radio,
+ Smartphone,
+ Sparkles,
+ Terminal,
+ Wrench,
+ type LucideIcon,
+} from 'lucide-react';
+
+import type { GhostPermissionItem } from '../../../../shared/ghost';
+
+const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
+ cindy: Sparkles,
+ agent: Bot,
+ node: Cpu,
+ tool: Wrench,
+ command: Terminal,
+ panel: PanelRight,
+ 'main-view': AppWindow,
+ code: FileCode2,
+ subscribe: Radio,
+ card: LayoutTemplate,
+ network: Globe,
+ notify: Megaphone,
+ confirm: MessageCircleQuestion,
+ fs: FilePen,
+ library: Library,
+ 'session-context': MapPin,
+ pick: FolderOpen,
+ preview: AppWindow,
+ skill: GraduationCap,
+ 'ios-simulator': Smartphone,
+ workspace: FolderPlus,
+};
+
+/**
+ * Chooses a visual affordance without changing the host-owned permission title or meaning.
+ * Shared by the plugin detail page and the install confirmation dialog.
+ */
+export function permissionItemIcon(item: GhostPermissionItem): LucideIcon {
+ if (item.labelKey === 'panelLeft') return PanelLeft;
+ if (
+ item.labelKey === 'networkSecret' ||
+ item.labelKey === 'networkSecretOauth' ||
+ item.labelKey === 'networkSecretGhCli' ||
+ item.labelKey === 'networkSecretIdentity'
+ ) {
+ return KeyRound;
+ }
+ return PERMISSION_ICON[item.kind];
+}
diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
index 5ab6714c02..16cb2f963e 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
@@ -45,8 +45,9 @@ export function pluginUpdateForInstalledVersion(
*
* A pending release is the usual case. The same release is also allowed when the
* installation record is incomplete: reinstalling that exact release restores
- * the Host receipt without adding a capability-confirmation step. A verified
- * install at the current release has nothing to recover.
+ * the Host receipt. Without an approved baseline Main cannot prove the previous
+ * permissions, so it asks the user as for a first install. A verified install at
+ * the current release has nothing to recover.
*/
export function marketReviewTargetsInstalledGhost(
item: Pick<PluginMarketItem, 'installState'> | null | undefined,
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index 209ac3ffe0..cef61442b6 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -16,6 +16,7 @@ import {
} from '@/contexts/dataOwnerGeneration';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { ghostInstallApprovalToken } from '../../../../shared/ghost';
+import { extractIpcError } from '@/utils/ipcError';
import { pluginMarketErrorKey } from './pluginMarketErrorKey';
import {
batchSummary,
@@ -181,6 +182,11 @@ async function runQueue(generation: number): Promise<void> {
voidStaleBatch();
return;
}
+ // 新版本权限变多时 Main 会逐个弹确认;用户取消只跳过这一个插件。
+ if (extractIpcError(error)?.code === 'MUTATION_CANCELLED') {
+ patchRow(generation, next.pluginId, { status: 'skipped' });
+ continue;
+ }
patchRow(generation, next.pluginId, {
status: 'failed',
errorText: i18n.t(pluginMarketErrorKey(error)),
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 30946fcdad..e13b8c4cb3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5143,8 +5143,8 @@
"brokerRedirectPortRequired": "This plugin declares an authorization broker but is missing redirectPort in the same OAuth configuration, so it cannot be installed from the plugin marketplace. Contact the publisher to add the field and publish a new release."
},
"securityTitle": "Install and permissions",
- "securityDescription": "Cindy verifies package size and SHA-256 in the main process, validates the plugin manifest, then installs atomically. First-time installs are enabled automatically and can be disabled anytime on the Plugins page; updates keep the current enabled state.",
- "customSecurityDescription": "This plugin comes from a custom marketplace you added and has not been verified by the Cindy server. Its manifest is validated in the main process before install. First-time installs are enabled automatically and can be disabled anytime on the Plugins page.",
+ "securityDescription": "Cindy verifies package size and SHA-256 in the main process, validates the plugin manifest, then installs atomically. You confirm the plugin’s permissions before it is installed; first-time installs are then enabled automatically and can be disabled anytime on the Plugins page. Updates keep the current enabled state, and you are asked first when a new version needs more permissions.",
+ "customSecurityDescription": "This plugin comes from a custom marketplace you added and has not been verified by the Cindy server. Its manifest is validated in the main process and you confirm its permissions before install. First-time installs are enabled automatically and can be disabled anytime on the Plugins page.",
"noPermissions": "This plugin declares no additional capabilities.",
"sources": {
"addMarketplace": "Add Plugin Marketplace…",
@@ -5305,6 +5305,31 @@
"confirm": "Install and allow testing",
"cancel": "Cancel"
},
+ "installConsent": {
+ "installTitle": "Install plugin “{{name}}”?",
+ "updateTitle": "Update plugin “{{name}}”?",
+ "installMeta": "Version {{version}} · {{source}}",
+ "updateMeta": "Version {{from}} → {{to}} · {{source}}",
+ "installDescription": "Nothing is installed until you confirm. The plugin is enabled right after installing, and you can disable or uninstall it anytime on the Plugins page.",
+ "updateDescription": "The new version needs more permissions, so it won’t be installed until you confirm. The current version keeps working in the meantime.",
+ "grantsTitle": "After installing it will have:",
+ "noPermissions": "This plugin declares no additional permissions.",
+ "addedTitle": "New or changed permissions:",
+ "removedTitle": "No longer needed:",
+ "addedBadge": "New",
+ "unchangedCount": "Unchanged permissions: {{count}}",
+ "oauthClientChanged": "This update changes the OAuth client. Connected accounts using the plugin's built-in authorization will expire after the update and must be reconnected.",
+ "originMarket": "From the {{appName}} plugin market",
+ "originCustomMarket": "From custom marketplace “{{name}}”",
+ "originCustomMarketUnnamed": "From a custom marketplace",
+ "originLocalFile": "From a local .cindy file",
+ "originForge": "Locally developed plugin",
+ "initiatedByAgent": "Requested by Agent · {{origin}}",
+ "confirmInstall": "Install",
+ "confirmUpdate": "Update",
+ "cancel": "Cancel",
+ "updateNeedsConsent": "New permissions need confirmation"
+ },
"trust": {
"official": "Official Cindy plugin",
"officialDetail": "Bundled with Cindy.",
@@ -5621,7 +5646,7 @@
"updateAll": {
"title": "Update all · {{count}} plugins",
"collapseDiff": "Collapse",
- "description": "Updates normally run silently. Use this dialog to retry updates that were skipped or failed.",
+ "description": "Updates that don’t add permissions normally run silently; updates that need more permissions ask you one by one. Use this dialog to retry updates that were skipped or failed.",
"versionRange": "v{{from}} → v{{to}}",
"statusPending": "Queued",
"statusInstalling": "Updating…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 85b2ceebb1..25b30cc3d6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5142,8 +5142,8 @@
"brokerRedirectPortRequired": "このプラグインは認可 broker を宣言していますが、同じ OAuth 設定に redirectPort がないため、プラグインマーケットからインストールできません。発行元にこのフィールドを追加して新しいバージョンを公開するよう連絡してください。"
},
"securityTitle": "インストールと権限",
- "securityDescription": "メインプロセスでサイズと SHA-256、プラグインマニフェストを検証してからアトミックにインストールします。初回インストール後は自動的に有効になり、プラグインページからいつでも無効化できます。更新では現在の有効/無効の状態が維持されます。",
- "customSecurityDescription": "このプラグインは追加したカスタムマーケット由来で、Cindy サーバーによる整合性検証は行われていません。インストール前にメインプロセスでマニフェストを検証します。初回インストール後は自動で有効になり、プラグインページでいつでも無効化できます。",
+ "securityDescription": "メインプロセスでサイズと SHA-256、プラグインマニフェストを検証してからアトミックにインストールします。インストール前にプラグインの権限を確認していただき、インストール後は自動的に有効になり、プラグインページからいつでも無効化できます。更新では現在の有効/無効の状態が維持され、新しいバージョンで権限が増える場合は先に確認します。",
+ "customSecurityDescription": "このプラグインは追加したカスタムマーケット由来で、Cindy サーバーによる整合性検証は行われていません。インストール前にメインプロセスでマニフェストを検証し、プラグインの権限を確認していただきます。インストール後は自動で有効になり、プラグインページでいつでも無効化できます。",
"noPermissions": "このプラグインは追加機能を宣言していません。",
"sources": {
"addMarketplace": "プラグインマーケットを追加…",
@@ -5304,6 +5304,31 @@
"confirm": "インストールしてテストを許可",
"cancel": "キャンセル"
},
+ "installConsent": {
+ "installTitle": "プラグイン「{{name}}」をインストールしますか?",
+ "updateTitle": "プラグイン「{{name}}」を更新しますか?",
+ "installMeta": "バージョン {{version}} · {{source}}",
+ "updateMeta": "バージョン {{from}} → {{to}} · {{source}}",
+ "installDescription": "確認するまでインストールされません。インストール後はすぐに有効になり、プラグインページからいつでも無効化・アンインストールできます。",
+ "updateDescription": "新しいバージョンはより多くの権限を必要とするため、確認するまで更新されません。それまでは現在のバージョンをそのまま使えます。",
+ "grantsTitle": "インストール後に持つ権限:",
+ "noPermissions": "このプラグインは追加の権限を宣言していません。",
+ "addedTitle": "追加・変更される権限:",
+ "removedTitle": "不要になる権限:",
+ "addedBadge": "追加",
+ "unchangedCount": "変更のない権限: {{count}} 件",
+ "oauthClientChanged": "この更新で OAuth クライアントが変更されます。プラグイン内蔵の認証を使用している接続済みアカウントは更新後に無効となり、再接続が必要です。",
+ "originMarket": "{{appName}} プラグインマーケットから",
+ "originCustomMarket": "カスタムマーケット「{{name}}」から",
+ "originCustomMarketUnnamed": "カスタムマーケットから",
+ "originLocalFile": "ローカルの .cindy ファイルから",
+ "originForge": "ローカルで開発したプラグイン",
+ "initiatedByAgent": "Agent からのリクエスト · {{origin}}",
+ "confirmInstall": "インストール",
+ "confirmUpdate": "更新",
+ "cancel": "キャンセル",
+ "updateNeedsConsent": "新しい権限の確認が必要"
+ },
"trust": {
"official": "Cindy 公式プラグイン",
"officialDetail": "Cindy に同梱されています。",
@@ -5620,7 +5645,7 @@
"updateAll": {
"title": "すべて更新 · {{count}} 件",
"collapseDiff": "折りたたむ",
- "description": "更新は通常サイレントに実行されます。この画面では、スキップまたは失敗した更新を再試行できます。",
+ "description": "権限が増えない更新は通常サイレントに実行されます。権限が増える更新は 1 件ずつ確認します。この画面では、スキップまたは失敗した更新も再試行できます。",
"versionRange": "v{{from}} → v{{to}}",
"statusPending": "待機中",
"statusInstalling": "更新中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c270142cad..36d3306962 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5142,8 +5142,8 @@
"brokerRedirectPortRequired": "이 플러그인은 인증 broker를 선언했지만 같은 OAuth 설정에 redirectPort가 없어 플러그인 마켓에서 설치할 수 없습니다. 게시자에게 이 필드를 추가해 새 버전을 게시해 달라고 알려 주세요."
},
"securityTitle": "설치 및 권한",
- "securityDescription": "메인 프로세스에서 크기와 SHA-256 및 플러그인 매니페스트를 검증한 뒤 원자적으로 설치합니다. 최초 설치 후 자동으로 활성화되며 플러그인 페이지에서 언제든지 비활성화할 수 있습니다. 업데이트 시 현재 활성화 상태가 유지됩니다.",
- "customSecurityDescription": "이 플러그인은 추가한 사용자 지정 마켓에서 제공되며 Cindy 서버의 무결성 검증을 거치지 않았습니다. 설치 전에 메인 프로세스에서 매니페스트를 검증합니다. 처음 설치하면 자동으로 활성화되며 플러그인 페이지에서 언제든 비활성화할 수 있습니다.",
+ "securityDescription": "메인 프로세스에서 크기와 SHA-256 및 플러그인 매니페스트를 검증한 뒤 원자적으로 설치합니다. 설치 전에 플러그인 권한을 확인받으며, 설치 후 자동으로 활성화되고 플러그인 페이지에서 언제든지 비활성화할 수 있습니다. 업데이트 시 현재 활성화 상태가 유지되며, 새 버전의 권한이 늘어나면 먼저 확인받습니다.",
+ "customSecurityDescription": "이 플러그인은 추가한 사용자 지정 마켓에서 제공되며 Cindy 서버의 무결성 검증을 거치지 않았습니다. 설치 전에 메인 프로세스에서 매니페스트를 검증하고 플러그인 권한을 확인받습니다. 처음 설치하면 자동으로 활성화되며 플러그인 페이지에서 언제든 비활성화할 수 있습니다.",
"noPermissions": "이 플러그인은 추가 기능을 선언하지 않았습니다.",
"sources": {
"addMarketplace": "플러그인 마켓 추가…",
@@ -5304,6 +5304,31 @@
"confirm": "설치 및 테스트 허용",
"cancel": "취소"
},
+ "installConsent": {
+ "installTitle": "플러그인 \"{{name}}\"을(를) 설치할까요?",
+ "updateTitle": "플러그인 \"{{name}}\"을(를) 업데이트할까요?",
+ "installMeta": "버전 {{version}} · {{source}}",
+ "updateMeta": "버전 {{from}} → {{to}} · {{source}}",
+ "installDescription": "확인하기 전에는 설치되지 않습니다. 설치 후 바로 활성화되며 플러그인 페이지에서 언제든 비활성화하거나 제거할 수 있습니다.",
+ "updateDescription": "새 버전에 더 많은 권한이 필요해 확인한 뒤에만 업데이트합니다. 그 전까지는 현재 버전을 그대로 사용할 수 있습니다.",
+ "grantsTitle": "설치 후 갖게 되는 권한:",
+ "noPermissions": "이 플러그인은 추가 권한을 선언하지 않았습니다.",
+ "addedTitle": "추가되거나 변경되는 권한:",
+ "removedTitle": "더 이상 필요 없는 권한:",
+ "addedBadge": "추가",
+ "unchangedCount": "변경 없는 권한: {{count}}개",
+ "oauthClientChanged": "이번 업데이트에서 OAuth 클라이언트가 변경됩니다. 플러그인의 기본 인증을 사용하는 연결된 계정은 업데이트 후 만료되며 다시 연결해야 합니다.",
+ "originMarket": "{{appName}} 플러그인 마켓에서",
+ "originCustomMarket": "사용자 지정 마켓 \"{{name}}\"에서",
+ "originCustomMarketUnnamed": "사용자 지정 마켓에서",
+ "originLocalFile": "로컬 .cindy 파일에서",
+ "originForge": "로컬에서 개발한 플러그인",
+ "initiatedByAgent": "Agent 요청 · {{origin}}",
+ "confirmInstall": "설치",
+ "confirmUpdate": "업데이트",
+ "cancel": "취소",
+ "updateNeedsConsent": "새 권한 확인 필요"
+ },
"trust": {
"official": "Cindy 공식 플러그인",
"officialDetail": "Cindy에 함께 제공됩니다.",
@@ -5620,7 +5645,7 @@
"updateAll": {
"title": "모두 업데이트 · {{count}}개",
"collapseDiff": "접기",
- "description": "업데이트는 보통 알림 없이 실행됩니다. 이 화면에서 건너뛰거나 실패한 업데이트를 다시 시도할 수 있습니다.",
+ "description": "권한이 늘지 않는 업데이트는 보통 알림 없이 실행됩니다. 권한이 늘어나는 업데이트는 하나씩 확인받습니다. 이 화면에서 건너뛰거나 실패한 업데이트도 다시 시도할 수 있습니다.",
"versionRange": "v{{from}} → v{{to}}",
"statusPending": "대기 중",
"statusInstalling": "업데이트 중…",
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 0e7965097d..c2e2e8fb87 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5142,8 +5142,8 @@
"brokerRedirectPortRequired": "该插件声明了授权 broker,但同一项 OAuth 配置缺少 redirectPort,无法从插件市场安装。请联系发布者补充该字段并重新发布。"
},
"securityTitle": "安装与权限",
- "securityDescription": "安装包会在主进程中校验大小与 SHA-256,再经 Cindy 插件清单校验后原子安装。首次安装完成后即自动开启,可随时在插件页停用;更新会保留当前生效状态。",
- "customSecurityDescription": "该插件来自你添加的自定义市场,未经 Cindy 服务端完整性校验。安装前会在主进程校验插件清单;首次安装完成后即自动开启,可随时在插件页停用。",
+ "securityDescription": "安装包会在主进程中校验大小与 SHA-256,再经 Cindy 插件清单校验后原子安装。安装前会请你确认插件的权限,装好后即自动开启,可随时在插件页停用;更新会保留当前生效状态,新版本权限变多时会先请你确认。",
+ "customSecurityDescription": "该插件来自你添加的自定义市场,未经 Cindy 服务端完整性校验。安装前会在主进程校验插件清单并请你确认插件的权限;装好后即自动开启,可随时在插件页停用。",
"noPermissions": "此插件未声明额外能力。",
"sources": {
"addMarketplace": "添加插件市场…",
@@ -5304,6 +5304,31 @@
"confirm": "安装并允许自测",
"cancel": "取消"
},
+ "installConsent": {
+ "installTitle": "安装插件「{{name}}」?",
+ "updateTitle": "更新插件「{{name}}」?",
+ "installMeta": "版本 {{version}} · {{source}}",
+ "updateMeta": "版本 {{from}} → {{to}} · {{source}}",
+ "installDescription": "确认后才会安装,装好后立即启用,可随时在插件页停用或卸载。",
+ "updateDescription": "新版本需要更多权限,确认后才会更新;在此之前旧版本照常可用。",
+ "grantsTitle": "安装后它将拥有:",
+ "noPermissions": "这个插件没有声明额外权限。",
+ "addedTitle": "新增或变化的权限:",
+ "removedTitle": "不再需要的权限:",
+ "addedBadge": "新增",
+ "unchangedCount": "其余 {{count}} 项权限不变",
+ "oauthClientChanged": "本次更新更换了 OAuth 客户端。使用插件内置授权的已连接账号将在更新后失效,需要重新连接。",
+ "originMarket": "来自 {{appName}} 插件市场",
+ "originCustomMarket": "来自自定义市场「{{name}}」",
+ "originCustomMarketUnnamed": "来自自定义市场",
+ "originLocalFile": "来自本地 .cindy 文件",
+ "originForge": "本地开发的插件",
+ "initiatedByAgent": "由 Agent 发起 · {{origin}}",
+ "confirmInstall": "安装",
+ "confirmUpdate": "更新",
+ "cancel": "取消",
+ "updateNeedsConsent": "需确认新权限"
+ },
"trust": {
"official": "Cindy 官方插件",
"officialDetail": "由 Cindy 随应用提供。",
@@ -5620,7 +5645,7 @@
"updateAll": {
"title": "全部更新 · {{count}} 个插件",
"collapseDiff": "收起",
- "description": "更新通常会静默完成;这里用于重试因忙碌跳过或执行失败的更新。",
+ "description": "权限没变多的更新通常会静默完成;新版本权限变多时会逐个请你确认。这里也可重试因忙碌跳过或执行失败的更新。",
"versionRange": "v{{from}} → v{{to}}",
"statusPending": "排队中",
"statusInstalling": "更新中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 08d6707b39..45ce25b079 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5141,8 +5141,8 @@
"brokerRedirectPortRequired": "此插件宣告了授權 broker,但同一項 OAuth 設定缺少 redirectPort,無法從插件市場安裝。請聯絡釋出者補上該欄位並重新釋出。"
},
"securityTitle": "安裝與權限",
- "securityDescription": "安裝包會在主處理程序中校驗大小與 SHA-256,再經 Cindy 插件清單校驗後原子安裝。首次安裝完成後即自動開啟,可隨時在插件頁停用;更新會保留當前生效狀態。",
- "customSecurityDescription": "該插件來自你新增的自定義市場,未經 Cindy 服務端完整性校驗。安裝前會在主處理程序校驗插件清單;首次安裝完成後即自動開啟,可隨時在插件頁停用。",
+ "securityDescription": "安裝包會在主處理程序中校驗大小與 SHA-256,再經 Cindy 插件清單校驗後原子安裝。安裝前會請你確認插件的權限,安裝好後即自動開啟,可隨時在插件頁停用;更新會保留當前生效狀態,新版本權限變多時會先請你確認。",
+ "customSecurityDescription": "該插件來自你新增的自定義市場,未經 Cindy 服務端完整性校驗。安裝前會在主處理程序校驗插件清單並請你確認插件的權限;安裝好後即自動開啟,可隨時在插件頁停用。",
"noPermissions": "此插件未宣告額外能力。",
"sources": {
"addMarketplace": "新增插件市場…",
@@ -5304,6 +5304,31 @@
"confirm": "安裝並允許自測",
"cancel": "取消"
},
+ "installConsent": {
+ "installTitle": "安裝插件「{{name}}」?",
+ "updateTitle": "更新插件「{{name}}」?",
+ "installMeta": "版本 {{version}} · {{source}}",
+ "updateMeta": "版本 {{from}} → {{to}} · {{source}}",
+ "installDescription": "確認後才會安裝,安裝好後立即啟用,可隨時在插件頁停用或解除安裝。",
+ "updateDescription": "新版本需要更多權限,確認後才會更新;在此之前舊版本照常可用。",
+ "grantsTitle": "安裝後它將擁有:",
+ "noPermissions": "這個插件沒有宣告額外權限。",
+ "addedTitle": "新增或變更的權限:",
+ "removedTitle": "不再需要的權限:",
+ "addedBadge": "新增",
+ "unchangedCount": "其餘 {{count}} 項權限不變",
+ "oauthClientChanged": "本次更新更換了 OAuth 用戶端。使用插件內建授權的已連線帳號將在更新後失效,需要重新連線。",
+ "originMarket": "來自 {{appName}} 插件市場",
+ "originCustomMarket": "來自自定義市場「{{name}}」",
+ "originCustomMarketUnnamed": "來自自定義市場",
+ "originLocalFile": "來自本機 .cindy 檔案",
+ "originForge": "本機開發的插件",
+ "initiatedByAgent": "由 Agent 發起 · {{origin}}",
+ "confirmInstall": "安裝",
+ "confirmUpdate": "更新",
+ "cancel": "取消",
+ "updateNeedsConsent": "需確認新權限"
+ },
"trust": {
"official": "Cindy 官方插件",
"officialDetail": "由 Cindy 隨應用提供。",
@@ -5620,7 +5645,7 @@
"updateAll": {
"title": "全部更新 · {{count}} 個插件",
"collapseDiff": "收起",
- "description": "更新通常會靜默完成;這裡用於重試因忙碌跳過或執行失敗的更新。",
+ "description": "權限沒變多的更新通常會靜默完成;新版本權限變多時會逐一請你確認。這裡也可重試因忙碌跳過或執行失敗的更新。",
"versionRange": "v{{from}} → v{{to}}",
"statusPending": "排隊中",
"statusInstalling": "更新中…",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6fc5101076..94aba2960a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1312,6 +1312,19 @@ interface ElectronAPI {
requestId: string,
confirmed: boolean,
) => Promise<{ handled: boolean }>;
+ /** 插件安装/更新确认(只投给发起安装的窗口)。第二个参数是 owner 推送戳。 */
+ onInstallConsentRequest: (
+ callback: (
+ payload: import('../shared/ghostInstallConsent').GhostInstallConsentRequest,
+ ownerStamp?: unknown,
+ ) => void,
+ ) => () => void;
+ /** Main 已结算(超时、取消或账号切换)某次确认,窗口应收起对应确认框。 */
+ onInstallConsentDismissed: (callback: (payload: { requestId: string }) => void) => () => void;
+ resolveInstallConsent: (
+ requestId: string,
+ confirmed: boolean,
+ ) => Promise<{ handled: boolean }>;
/** Plugin 快捷行最近使用顺序(最新在前,首帧同步读取避免排序跳变)。 */
recentUsageSync: () => { ids: string[] };
/** 成功发送一次 Plugin 指令后记录最近使用。 */
@@ -1685,6 +1698,7 @@ interface ElectronAPI {
import('../shared/pluginMarket').PluginRemovalUserNotice | null
>;
onRemovalNoticeAvailable: (callback: () => void) => () => void;
+ onUpdateConsentHoldsChanged: (callback: () => void) => () => void;
listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;
pickLocalSource: (
defaultPath?: string,
diff --git a/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts b/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts
new file mode 100644
index 0000000000..fa95160c45
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ validateGhostManifest,
+ type GhostInstallApproval,
+ type GhostManifest,
+ type InstalledGhost,
+} from '../ghost';
+import {
+ evaluateGhostInstallConsent,
+ ghostInstallConsentKey,
+ ghostUpdateNeedsConsent,
+} from '../ghostInstallConsent';
+
+function manifest(overrides: Record<string, unknown> = {}): GhostManifest {
+ const result = validateGhostManifest({
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'weather-chip',
+ name: 'Weather',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ network: { hosts: ['api.weather.test'] },
+ tools: [{ name: 'forecast', description: 'Read the forecast' }],
+ ...overrides,
+ });
+ if (!result.ok) throw new Error(`invalid fixture: ${JSON.stringify(result)}`);
+ return result.manifest;
+}
+
+function installed(
+ base: GhostManifest,
+ approval: GhostInstallApproval = { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+): InstalledGhost {
+ return { manifest: base, dir: '/userData/cindy-brain/weather-chip', enabled: true, approval };
+}
+
+describe('plugin install consent', () => {
+ it('always asks on first install and lists every non-tool permission', () => {
+ const facts = evaluateGhostInstallConsent(null, manifest());
+ expect(facts).toMatchObject({ kind: 'install', ghostId: 'weather-chip', version: '1.0.0' });
+ if (facts?.kind !== 'install') throw new Error('expected install facts');
+ expect(facts.permissions.map((item) => item.key)).toContain('network:host:api.weather.test');
+ expect(facts.permissions.some((item) => item.kind === 'tool')).toBe(false);
+ });
+
+ it('keeps an update silent when permissions are unchanged', () => {
+ const current = installed(manifest());
+ expect(evaluateGhostInstallConsent(current, manifest({ version: '1.1.0' }))).toBeNull();
+ expect(ghostUpdateNeedsConsent(current, manifest({ version: '1.1.0' }))).toBe(false);
+ });
+
+ it('keeps an update silent when it only removes permissions or changes tools', () => {
+ const current = installed(manifest({ network: { hosts: ['api.weather.test', 'maps.weather.test'] } }));
+ expect(evaluateGhostInstallConsent(current, manifest({ version: '1.1.0' }))).toBeNull();
+ const withMoreTools = manifest({
+ version: '1.2.0',
+ network: { hosts: ['api.weather.test', 'maps.weather.test'] },
+ tools: [
+ { name: 'forecast', description: 'Read the forecast' },
+ { name: 'radar', description: 'Show the radar' },
+ ],
+ });
+ expect(evaluateGhostInstallConsent(current, withMoreTools)).toBeNull();
+ });
+
+ it('asks when an update adds a permission and reports the diff', () => {
+ const facts = evaluateGhostInstallConsent(
+ installed(manifest()),
+ manifest({ version: '2.0.0', network: { hosts: ['api.weather.test', 'upload.weather.test'] } }),
+ );
+ expect(facts).toMatchObject({
+ kind: 'update',
+ previousVersion: '1.0.0',
+ version: '2.0.0',
+ builtinOauthClientChanged: false,
+ });
+ if (facts?.kind !== 'update') throw new Error('expected update facts');
+ expect(facts.added.map((item) => item.key)).toEqual(['network:host:upload.weather.test']);
+ expect(facts.removed).toEqual([]);
+ expect(facts.unchangedCount).toBeGreaterThan(0);
+ });
+
+ it('treats an install without an approved baseline as all-new permissions', () => {
+ const facts = evaluateGhostInstallConsent(
+ installed(manifest(), { state: 'legacy-unapproved' }),
+ manifest({ version: '1.1.0' }),
+ );
+ expect(facts?.kind).toBe('update');
+ if (facts?.kind !== 'update') throw new Error('expected update facts');
+ expect(facts.added.map((item) => item.key)).toContain('network:host:api.weather.test');
+ });
+
+ it('binds the consent key to the exact permission change that was shown', () => {
+ const current = installed(manifest());
+ const next = manifest({ version: '2.0.0', network: { hosts: ['api.weather.test', 'upload.weather.test'] } });
+ const shown = evaluateGhostInstallConsent(current, next)!;
+ const digest = 'a'.repeat(64);
+ const receiver = 'approved:00000000-0000-4000-8000-000000000001';
+ expect(ghostInstallConsentKey(evaluateGhostInstallConsent(current, next)!, digest, receiver)).toBe(
+ ghostInstallConsentKey(shown, digest, receiver),
+ );
+ const widened = manifest({
+ version: '2.0.0',
+ network: { hosts: ['api.weather.test', 'upload.weather.test', 'extra.weather.test'] },
+ });
+ expect(
+ ghostInstallConsentKey(evaluateGhostInstallConsent(current, widened)!, digest, receiver),
+ ).not.toBe(ghostInstallConsentKey(shown, digest, receiver));
+ });
+
+ it('binds the consent key to the reviewed package digest, not just identity and permissions', () => {
+ const facts = evaluateGhostInstallConsent(null, manifest())!;
+ const reviewed = 'a'.repeat(64);
+ const replaced = 'b'.repeat(64);
+ expect(ghostInstallConsentKey(facts, reviewed, null)).toBe(
+ ghostInstallConsentKey(facts, reviewed, null),
+ );
+ expect(ghostInstallConsentKey(facts, reviewed, null)).not.toBe(
+ ghostInstallConsentKey(facts, replaced, null),
+ );
+ });
+
+ it('binds update consent to the reviewed receiver receipt, not just version and permissions', () => {
+ const facts = evaluateGhostInstallConsent(
+ installed(manifest()),
+ manifest({ version: '2.0.0', network: { hosts: ['api.weather.test', 'upload.weather.test'] } }),
+ )!;
+ const digest = 'a'.repeat(64);
+ const reviewed = 'approved:00000000-0000-4000-8000-000000000001';
+ const replaced = 'approved:00000000-0000-4000-8000-000000000002';
+ expect(ghostInstallConsentKey(facts, digest, reviewed)).not.toBe(
+ ghostInstallConsentKey(facts, digest, replaced),
+ );
+ });
+});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index e5354ed307..afe3f378a5 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1882,7 +1882,7 @@ function ghostPermissionProjectionTuple(item: GhostPermissionItem): unknown[] {
];
}
-function ghostPermissionProjectionKey(item: GhostPermissionItem): string {
+export function ghostPermissionProjectionKey(item: GhostPermissionItem): string {
return JSON.stringify(ghostPermissionProjectionTuple(item));
}
diff --git a/apps/desktop/src/shared/ghostInstallConsent.ts b/apps/desktop/src/shared/ghostInstallConsent.ts
new file mode 100644
index 0000000000..19c9d1c283
--- /dev/null
+++ b/apps/desktop/src/shared/ghostInstallConsent.ts
@@ -0,0 +1,147 @@
+/**
+ * 插件安装/更新的用户确认判据(docs/dev-rules/plugin-security-and-authoring.md §3.1)。
+ *
+ * 首次安装一律需要确认;更新只在权限变多时需要确认。「权限」与插件详情页的
+ * 权限区同口径:`ghostPermissionItems` 中除 Agent 工具以外的全部条目。新增条目、
+ * 同 key 条目内容变化(例如多一个域名、换一组授权范围),或内置 OAuth 客户端
+ * 身份变化都算变多;只删除条目不算。
+ *
+ * Main 用它决定是否挂起安装事务等用户确认;Renderer 用同一份实现给插件页的
+ * 更新入口打「需确认新权限」标记。两侧必须同口径,因此住在 shared。
+ */
+import {
+ diffInstalledGhostPermissionItems,
+ ghostInstallApprovalToken,
+ ghostPermissionItems,
+ ghostPermissionProjectionKey,
+ type GhostManifest,
+ type GhostPermissionItem,
+ type InstalledGhost,
+} from './ghost.js';
+
+/**
+ * Agent 发起安装时投给任务的宿主权限确认卡的工具名。桌面卡片据此把首行作为说明、
+ * 其余权限清单放进可滚动区域。
+ */
+export const GHOST_INSTALL_CONSENT_TOOL_NAME = 'cindy.plugin.install';
+
+/** 谁发起了这次安装(只决定确认卡的来源说明,不参与是否需要确认的判断)。 */
+export type GhostInstallConsentInitiator = 'user' | 'agent';
+
+/** 安装包从哪里来(只决定确认卡的来源说明)。 */
+export type GhostInstallConsentOrigin = 'market' | 'custom-market' | 'local-file' | 'forge';
+
+export type GhostInstallConsentFacts =
+ | {
+ kind: 'install';
+ ghostId: string;
+ name: string;
+ version: string;
+ /** 插件声明的全部权限(不含 Agent 工具)。 */
+ permissions: GhostPermissionItem[];
+ }
+ | {
+ kind: 'update';
+ ghostId: string;
+ name: string;
+ version: string;
+ previousVersion: string;
+ /** 相对当前已装版本新增或变化的权限。 */
+ added: GhostPermissionItem[];
+ /** 相对当前已装版本移除或变化前的权限。 */
+ removed: GhostPermissionItem[];
+ /** 未变化的权限条数(确认卡折叠展示)。 */
+ unchangedCount: number;
+ /** 同一凭证的内置 OAuth 客户端身份变化,可能需要重新授权。 */
+ builtinOauthClientChanged: boolean;
+ };
+
+/** Main 投给确认界面的一次确认请求。 */
+export interface GhostInstallConsentRequest {
+ requestId: string;
+ initiator: GhostInstallConsentInitiator;
+ origin: GhostInstallConsentOrigin;
+ /** 自定义市场名称(用户添加来源时起的名字,按原样展示)。 */
+ originLabel?: string;
+ facts: GhostInstallConsentFacts;
+}
+
+/** 与插件详情页「权限」区同口径:Agent 工具不算权限。 */
+export function ghostConsentPermissionItems(manifest: GhostManifest): GhostPermissionItem[] {
+ return ghostPermissionItems(manifest).filter((item) => item.kind !== 'tool');
+}
+
+function withoutTools(items: readonly GhostPermissionItem[]): GhostPermissionItem[] {
+ return items.filter((item) => item.kind !== 'tool');
+}
+
+/**
+ * 计算把 `next` 装到当前受体上需要用户确认的事实;返回 null 表示无需确认。
+ *
+ * - 没有已装版本:首次安装,始终需要确认。
+ * - 已装版本批准态正常:按权限 diff 判断,只有新增/变化或 OAuth 客户端变化才需要。
+ * - 已装版本没有有效批准基线:无法证明旧权限面,按全部权限都是新增处理。
+ */
+export function evaluateGhostInstallConsent(
+ installed: InstalledGhost | null | undefined,
+ next: GhostManifest,
+): GhostInstallConsentFacts | null {
+ if (!installed) {
+ return {
+ kind: 'install',
+ ghostId: next.id,
+ name: next.name,
+ version: next.version,
+ permissions: ghostConsentPermissionItems(next),
+ };
+ }
+ const diff = diffInstalledGhostPermissionItems(installed, next);
+ const added = withoutTools(diff.added);
+ if (added.length === 0 && !diff.builtinOauthClientChanged) return null;
+ return {
+ kind: 'update',
+ ghostId: next.id,
+ name: next.name,
+ version: next.version,
+ previousVersion: installed.manifest.version,
+ added,
+ removed: withoutTools(diff.removed),
+ unchangedCount: withoutTools(diff.unchanged).length,
+ builtinOauthClientChanged: diff.builtinOauthClientChanged,
+ };
+}
+
+/** 更新是否会扩大权限(插件页据此把更新标成「需确认新权限」)。 */
+export function ghostUpdateNeedsConsent(installed: InstalledGhost, next: GhostManifest): boolean {
+ return evaluateGhostInstallConsent(installed, next) !== null;
+}
+
+/** 确认时所对照的已装受体 receipt;首装没有受体,记 null。 */
+export function ghostInstallConsentReceiverIdentity(
+ installed: InstalledGhost | null | undefined,
+): string | null {
+ return installed ? ghostInstallApprovalToken(installed.approval) : null;
+}
+
+/**
+ * 一次确认的规范化指纹。Main 在确认前按它记下用户看到的内容、当时的包摘要,
+ * 以及所对照的已装受体 receipt。落位前在安装锁内用真实包、当前受体与现读摘要重算;
+ * 候选包字节被换、或受体被另一份同 version/同权限投影的安装换掉,都不能沿用这次确认。
+ */
+export function ghostInstallConsentKey(
+ facts: GhostInstallConsentFacts,
+ packageSha256: string,
+ receiverApprovalToken: string | null,
+): string {
+ const items = facts.kind === 'install' ? facts.permissions : facts.added;
+ return JSON.stringify([
+ facts.kind,
+ facts.ghostId,
+ facts.version,
+ facts.kind === 'update' ? facts.previousVersion : null,
+ items.map(ghostPermissionProjectionKey).sort(),
+ facts.kind === 'update' ? facts.builtinOauthClientChanged : false,
+ packageSha256,
+ receiverApprovalToken,
+ ]);
+}
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index a1df4b9128..1e9bf286b2 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -37,6 +37,11 @@ export interface PluginMarketItem {
sourceType: PluginMarketItemSource;
/** 来源市场名(自定义市场项必填;服务端项为 null)。 */
sourceMarketName: string | null;
+ /**
+ * 新版本比已装版本权限变多,后台更新已暂停、等待用户确认。只在 Main 按真实包
+ * 判定过后出现;缺省表示未知或无需确认,不能据此推断可以静默更新。
+ */
+ updateRequiresConsent?: true;
}
/** 市场快照。服务不可用时 renderer 保留本地插件并只展示非阻断提示。 */
export interface PluginMarketSnapshot {
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index dd3549d2cc..2432605e5b 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -76,12 +76,12 @@
运行时也不授予任何能力。未来支持必须新增明确映射,不得按名称猜测。
- v2 的空 `slots` 和历史零能力声明可继续安装,规范化时直接丢弃。v2 → v3 更新按规范化
后的直接能力比较;只删除 `slots`、能力等价时不算新增权限。
-- 安装/更新与能力授权解耦:用户导入 `.cindy`、明确要求当前 Agent 通过 Forge 安装、
- 点击市场安装或命中服务端
- `defaultInstall` 即构成安装依据,真实包校验通过后直接安装并启用,不追加能力确认弹窗。
- 插件自主 Host 能力仍须在 manifest 如实声明、在插件详情展示,并由 Host
- 运行时强制守门;动态资源与 Agent 在途操作不重复建权限实体,继续复用 Cindy 既有
- Agent 授权系统,不新增 grant/申请状态机。
+- 安装/更新前向用户确认插件声明的权限(2026-09-25 用户裁决,取代此前「安装不设能力
+ 确认弹窗」的做法):首次安装一律确认;更新只在新版本权限变多时确认;服务端
+ `defaultInstall` 下发的插件首装与后续更新都不确认。判据、入口与落位前复核见第 3.1 节。
+ 确认只决定这次安装/更新是否进行,不是运行期授权:插件自主 Host 能力仍须在 manifest
+ 如实声明、在插件详情展示,并由 Host 运行时强制守门;动态资源与 Agent 在途操作不重复
+ 建权限实体,继续复用 Cindy 既有 Agent 授权系统,不新增 grant/申请状态机。
## 2. 运行时沙箱与进程隔离
@@ -109,8 +109,9 @@
前再次复核同一 `callId`;直连与系统代理都只能连接该次守门确认的 IP,代理不得
重新解析插件提供的域名。选中代理不构成私网授权;无法证明由当前代理生成的 fake-IP
仍按特殊用途/私有地址拒绝。
-- 安装/更新不以弹窗点击作为能力授权事实;
- **prompt 和前端展示都不构成安全边界**。
+- 安装/更新确认只决定这次落位是否进行,不以弹窗点击作为运行期能力授权事实;
+ **prompt 和前端展示都不构成运行期安全边界**。确认结论由 Main 在安装锁内按真实包复核,
+ 不能由 Renderer 或 Agent 自报(第 3.1 节)。
- 新增或修改能力声明时,除同步编写手册与校验(下节 6)外,还必须同步 shared 类型、
preload/host handler、详情能力 UI(`GhostPluginDetailView.tsx`)、错误边界和测试。
@@ -119,8 +120,31 @@
- 首次安装只来自明确依据:用户导入本地 `.cindy`、明确要求当前 Agent 调用
`ghost_forge_install`、用户点击某个市场条目的安装、当前 Agent 按用户请求与既有操作授权
调用 `ghost_market_install` 安装选定的缺失插件,或服务端为当前 owner 下发
- `defaultInstall`。安装成功默认启用;插件声明哪些能力不改变
- 安装动作是否需要确认,因为安装不设能力确认弹窗。
+ `defaultInstall`。安装成功默认启用。
+- **安装/更新确认**(`shared/ghostInstallConsent.ts` 判据,`main/cindy-brain/ghostInstallConsent.ts`
+ 两段式实现):
+ - 判据:「权限」与插件详情页权限区同口径,即 `ghostPermissionItems` 中除 Agent 工具外的
+ 全部条目。首次安装展示全部权限并确认;更新相对当前已装版本按 `diffInstalledGhostPermissionItems`
+ 比较,新增条目、同 key 条目内容变化或内置 OAuth 客户端变化才算权限变多,只删除不算;
+ 已装版本没有有效批准基线时按全部权限新增处理。
+ - 入口与确认界面:插件页、拖入、双击 `.cindy` 与设置页导入由发起窗口弹确认框
+ (`GhostInstallConsentWindowBridge` → `GhostInstallConsentHost`,只投给、也只接受发起安装
+ 的那个 webContents);Agent 调用 `ghost_market_install`/`ghost_forge_install` 不论任务权限档
+ (含 Full Access)都向调用所在任务投宿主权限确认卡(`permission` 交互 +
+ `hostOwnedConfirmation: 'plugin_install'`,经 `requestHostInteraction` 路由),桌面对话、
+ 手机远控与 IM 渠道卡都能处理,旧版手机无需升级。用户拒绝返回 `MUTATION_CANCELLED`,
+ Agent 不得自行重试;确认界面不可用时 fail closed。
+ - 两段式:确认在任何安装锁、来源锁与 owner 租约之外求得(等待期间不阻塞其它插件);
+ 落位前在按 ghostId 的安装锁内用即将落位的真实包、现读受体 receipt 与确认前钉住的包摘要重算
+ (`assertGhostInstallConsent`),确认后权限面、已装版本、受体 receipt 或包字节变化就拒绝;
+ 用户确认过的更新不能因为受体已被换成权限已覆盖候选包的版本而静默落位。自定义市场在
+ 来源 cache-path 租约内只打包,释放租约后再求确认;提交时仍复核来源。Forge 在 packing
+ 租约内捕获 owner 并传入装入入口,等锁结束后若账号已切换则拒绝取租约。每条装入路径都
+ 必须显式交出确认策略(`prompt`/`automatic`/`exempt`)或锁外求得的结论,签名上必填,
+ 新增路径无法漏掉。
+ - 服务端 `defaultInstall` 插件(首装、组织默认接管与之后的自动更新)按下发方决定,
+ 策略为 `exempt`,不向用户确认。豁免只绑当前用户对该条目的默认下发资格:目录仍标
+ `defaultInstall`、但用户已退订后再自行从市场安装的,扩权更新必须确认。
- 市场安装账本是后续更新来源的唯一事实:服务端市场按 `pluginId + releaseId` 路由,
自定义市场还必须匹配 `sourceKey`;已装目录的原始 `ghost.json` 字节 SHA-256 必须与账本
一致。旧记录缺少 raw 字段时,Host 只能按已发布的 legacy digest 编码核对同一份受限读取
@@ -135,9 +159,15 @@
不进入自动接管;普通 `.cindy` 导入仍是 `manual`,不享受这项保护。自动接管不得复用用户手动
换源的退订语义,不写 `markRemoved` 或 default-install opt-out。普通本地/Forge 换源只把
旧来源记录置为 `installed=false`,不得新增或清除 opt-out;只有用户显式卸载才写 opt-out。
-- 所有仍匹配稳定来源的已装插件都静默自动更新,不限 public/organization、也不限
- `defaultInstall`。更新保持现有启用状态,不弹成功 toast;插件正有调用、派活或 Cindy
- 工作时跳过,下一轮重试。服务端市场按客户端版本投影最近发布、曾上架且仍有效的兼容
+- 仍匹配稳定来源的已装插件自动更新,不限 public/organization;更新保持现有启用状态,
+ 不弹成功 toast;插件正有调用、派活或 Cindy 工作时跳过,下一轮重试。权限没变多的更新
+ 静默完成;新版本权限变多时(按下载后的真实包判定,策略 `automatic`)放弃本轮、不记失败、
+ 不退避,同一 release 在当前进程内不再重复下载,旧版本照常可用;市场条目带
+ `updateRequiresConsent`,插件页标出「需确认新权限」,用户点更新时再弹确认。Renderer
+ 目录走延后对账时,记下新 hold 后立即通知重投影,不等无关前台刷新。自定义
+ 市场暂停记录同时钉住 release 与包内容指纹,同版本包被改掉后必须重新判定。仍具备
+ 默认下发资格的服务端 `defaultInstall` 插件不受此限,权限变多也静默更新。
+- 服务端市场按客户端版本投影最近发布、曾上架且仍有效的兼容
Release;current 不兼容时回退兼容历史版本,没有兼容版本时不展示。Desktop 信任该投影,
不再用 `minCindyVersion` 二次筛选、跳过或弹兼容性确认。自定义市场和本地 `.cindy` 采用
同一安装策略:`minCindyVersion` 是发布/发现元数据,不是客户端安装授权或确认闸门。
@@ -150,14 +180,14 @@
解除。忙碌跳过不记失败,用户手动重试不受退避限制。
- 服务端包必须通过 release SHA/大小及 id/版本校验,安装与运行时能力以真实包内的
Manifest 为准,不将服务端目录的 Manifest 投影作为第二份能力上限。
- 自定义市场以发现并规范化的 manifest 为能力上限。能力上限内的新版声明可静默更新,超出
- 则按包内容不一致拒绝并留待来源修复,不转成用户审批流程。能力上限按 Host 实际消费语义
+ 自定义市场以发现并规范化的 manifest 为能力上限。超出能力上限按包内容不一致拒绝并留待
+ 来源修复,不转成用户审批流程;上限内的新版声明仍按上一条判断是否需要用户确认。能力上限按 Host 实际消费语义
比较:真实包不得从无到有增加 `settingsHtml` 设置 WebView 或扩大固定 `settingsHeight`;
OAuth `scopes` 换序或取子集属于收权,其它 OAuth、凭证标签与注入字段仍须保持在清单上限内;
`setup.requires` 只能保留或删除市场已有的完整需求组,不能增加组、收紧 `anyOf` 或更换引用;
真实包同名工具的 `parameters` JSON Schema 必须与市场规范值一致(仅对象键顺序可不同)。
-- 本地 `.cindy` 没有稳定来源,不自动更新;用户再次导入同 id 新包时直接原位更新,由 Main
- 保持当前启用状态。
+- 本地 `.cindy` 没有稳定来源,不自动更新;用户再次导入同 id 新包时原位更新(权限变多时
+ 先确认),由 Main 保持当前启用状态。
- 市场下载与本地安装使用一致的 Node 包体边界:压缩包最多 128 MiB、解包总量最多
256 MiB、最多 2048 个条目;普通沙箱包仍为 8 MiB/32 MiB/256 个条目。
下载前尚未识别真实包类型,按 128 MiB 限流;下载后由共用安装器按真实包类型校验。
@@ -167,12 +197,13 @@
实现与回归见 `apps/desktop/src/main/plugin-market/download.ts` 及同目录的
`__tests__/download.test.ts`。
- Host receipt 是安装事务和运行完整性的状态记录,不是一次交互式“能力授权”。合法的安装/更新
- 事务直接写入 receipt,钉住 canonical manifest、trust、启停态与随机 `revision`;
+ 事务(已按上文求得确认)写入 receipt,钉住 canonical manifest、trust、启停态与随机 `revision`;
`ghostInstallApprovalToken()` 只是 Renderer 与 Main 之间防止并发漂移的前置条件,不是权限凭证。
- 没有或损坏 receipt 的存量安装优先走自动迁移/对账,不能改成逐插件能力确认弹窗。
+ 没有或损坏 receipt 的存量安装优先走自动迁移/对账,不能改成逐插件能力确认弹窗;安装确认只作用
+ 于新的安装/更新事务,Cindy 升级后已装插件不因此需要重新确认(以当前已装版本为基准)。
- receipt 不等于“安装目录从此不可变”的证明:普通 `packageSha256` 仍是安装时点来源指纹;
真正越出沙箱的技能继续使用 receipt 绑定的字节指纹与 Host 状态根快照。不要把审计字段误写成
- 全量运行时内容校验,也不要因取消能力确认弹窗而删除现有完整性守门。
+ 全量运行时内容校验,也不要把安装确认当成完整性守门而删减现有校验。
- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` /
`ghost_forge_install` 的目标必须是独立作者目录,不得是安装根或状态根;按 realpath
挡住大小写折叠与软链/junction 别名。会话工作目录内直接放行;工作目录外走与
@@ -573,7 +604,10 @@ topic 路由;产品层多端语义见
在详情如实展示并由 Host 守门?是否误把安装弹窗或前端展示当成授权事实?
3. receipt 是否仍只由 Main 的合法安装/更新/迁移事务写入?跨进程更新是否回传
`ghostInstallApprovalToken()` 并在锁内重读比对?缺失或损坏状态是否优先无感迁移,
- 而不是重新引入能力确认?停用方向是否始终可成功?技能快照与字节指纹是否仍受保护?
+ 而不是用安装确认充当恢复方案?停用方向是否始终可成功?技能快照与字节指纹是否仍受保护?
+3.5. 新增或改动的装入路径是否显式交出安装确认策略,并在锁内用真实包复核
+ (`assertGhostInstallConsent`)?确认等待是否在所有安装锁与 owner 租约之外?后台路径是否
+ 只会 `automatic` 放弃、从不替用户确认?Agent 路径是否不受任务权限档影响、始终确认?
4. Agent 在途网络是否仍通过 URL/SSRF/重定向等 Host 守门,自主网络是否限 manifest
白名单,托管凭证是否只向声明且命中的 host 注入、无明文读回?附件/媒体/目录是否经
归属校验的 grant/deposit/ledger 交接,未暴露宿主绝对路径?