Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(local-agent): 使用 Cindy 主题确认授权与撤销

DavidShen334089cc3fe4
diff --git a/apps/desktop/scripts/fixtures/local-agent-confirmation/fixture.tsx b/apps/desktop/scripts/fixtures/local-agent-confirmation/fixture.tsx
new file mode 100644
index 0000000000..7be86662d5
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-agent-confirmation/fixture.tsx
@@ -0,0 +1,17 @@
+import { mountPage, subscription } from '../../ui-page/harness';
+import { LocalAgentConfirmationHost } from '../../../src/renderer/components/LocalAgentConfirmationHost';
+
+mountPage({
+ host: {
+ localAgent: {
+ onConfirmation: subscription('confirmation'),
+ onConfirmationDismissed: subscription('dismiss'),
+ answerConfirmation: async (requestId: string, confirmed: boolean) => {
+ const state = window as unknown as { answers: unknown[] };
+ (state.answers ??= []).push({ requestId, confirmed });
+ return true;
+ },
+ },
+ },
+ render: () => <LocalAgentConfirmationHost />,
+});
diff --git a/apps/desktop/scripts/fixtures/local-agent-confirmation/ui-page.mjs b/apps/desktop/scripts/fixtures/local-agent-confirmation/ui-page.mjs
new file mode 100644
index 0000000000..7772f0a65d
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-agent-confirmation/ui-page.mjs
@@ -0,0 +1,64 @@
+export default {
+ name: 'local-agent-confirmation', entry: './fixture.tsx', viewport: { width: 900, height: 650 },
+ real: 'LocalAgentConfirmationHost, ConfirmDialogProvider and themed ConfirmDialog',
+ notCovered: 'Main IPC sender validation and actual API grants are verified separately in service and isolated Desktop checks.',
+ cases: {
+ default: { about: 'Approve through the shared themed confirmation', data: { action: 'allow' } },
+ cancel: { about: 'Cancel returns a negative decision', data: { action: 'cancel' } },
+ escape: { about: 'Escape dismisses without granting', data: { action: 'escape' } },
+ revoke: { about: 'Confirm revocation with the existing localized copy', data: { action: 'revoke' } },
+ abort: { about: 'Main dismissal cannot yield a late approval', data: { action: 'abort' } },
+ queued: { about: 'Cancelling the first request preserves the second', data: { action: 'queued' } },
+ narrow: { about: 'Long unverified identity wraps at 320px', viewport: { width: 320, height: 640 }, data: { action: 'allow', long: true } },
+ },
+ async check(page, ui) {
+ const app = ui.data.long ? 'ApplicationWithAnUnbrokenLongName独立客户端'.repeat(3) : 'Notes';
+ const revoke = ui.data.action === 'revoke';
+ const request = {
+ requestId: 'first',
+ title: await ui.t(revoke ? 'localAgent.title' : 'localAgent.connectTitle'),
+ message: await ui.t(revoke ? 'localAgent.revokeOneMessage' : 'localAgent.connectMessage', { app }),
+ detail: await ui.t(revoke ? 'localAgent.revokeOneDetail' : 'localAgent.connectDetail'),
+ confirmText: await ui.t(revoke ? 'localAgent.revoke' : 'localAgent.allow'),
+ cancelText: await ui.t('localAgent.cancel'),
+ };
+ if (!revoke) request.detail += '\n\n' + await ui.t('localAgent.clientIdentity', { id: 'org.example.notes', version: '1.2' });
+ const emit = (name, payload) => page.evaluate(({ name, payload }) => window.__uiPage.emit(name, payload), { name, payload });
+ await emit('confirmation', request);
+ const dialog = page.getByRole('alertdialog');
+ await dialog.waitFor();
+ const cancel = dialog.getByRole('button', { name: request.cancelText, exact: true });
+ await cancel.waitFor();
+ if (!(await cancel.evaluate(el => el === document.activeElement))) throw new Error('Cancel must receive initial focus');
+ for (let i = 0; i < 3; i++) {
+ await page.keyboard.press('Tab');
+ if (!(await dialog.evaluate(el => el.contains(document.activeElement)))) throw new Error('Focus escaped modal');
+ }
+ if (!(await dialog.evaluate(el => {
+ const b = el.getBoundingClientRect();
+ return b.left >= 0 && b.right <= innerWidth && b.top >= 0 && b.bottom <= innerHeight && el.scrollWidth <= el.clientWidth;
+ }))) throw new Error('Dialog overflows viewport');
+ if (ui.data.action === 'queued') {
+ await emit('confirmation', { ...request, requestId: 'second' });
+ await emit('dismiss', 'first');
+ await page.waitForFunction(() => document.querySelector('[role=alertdialog]')?.getAttribute('data-state') === 'open');
+ // Wait for the shared provider's exit/next transition, not a second modal implementation.
+ // real-wait: shared production modal exit animation finishes before the next queue item.
+ await page.waitForTimeout(250);
+ await dialog.getByRole('button', { name: request.confirmText, exact: true }).click();
+ } else if (ui.data.action === 'abort') await emit('dismiss', 'first');
+ else if (ui.data.action === 'escape') await page.keyboard.press('Escape');
+ else if (ui.data.action === 'cancel') await cancel.click();
+ else await dialog.getByRole('button', { name: request.confirmText, exact: true }).click();
+ await dialog.waitFor({ state: 'hidden' });
+ const answers = await page.evaluate(() => window.answers ?? []);
+ const expected = ui.data.action === 'abort' ? [] : [{
+ requestId: ui.data.action === 'queued' ? 'second' : 'first',
+ confirmed: !['cancel', 'escape'].includes(ui.data.action),
+ }];
+ if (JSON.stringify(answers) !== JSON.stringify(expected)) throw new Error('Wrong/late confirmation reply');
+ // Leave the production dialog visible for the theme/locale screenshot and audit.
+ await emit('confirmation', { ...request, requestId: 'screenshot' });
+ await dialog.waitFor();
+ },
+};
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index a7c96b9b2f..27c222d7a7 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -417,6 +417,7 @@ import {
isCindyPersonalRuntime,
} from './cindy-make/versionRuntimeIdentity.js';
import { createStorageIpcHandlers } from './cindy-media/storageIpc';
+import { registerLocalAgentConfirmationIpc, cancelLocalAgentConfirmations } from './local-agent/confirmation.js';
import { disposeLocalAgentHost, localAgentConnections, localAgentDeveloperConnection, revokeLocalAgentConnections } from './local-agent/service.js';
import { clearLocalEntries } from './device-link/remoteMediaCacheStore';
import {
@@ -2536,6 +2537,7 @@ registerGhostIpc();
registerPluginMarketIpc();
registerPluginPublisherIpc();
setAppSessionCommitBoundaryHook(() => {
+ cancelLocalAgentConfirmations();
// 进行中的 Claude Code 登录属于旧 owner:结束 CLI 子进程,不让它在新 owner 下完成。
cancelClaudeCliLogin();
clearAllSessionAttention();
@@ -8554,6 +8556,7 @@ const registerIpcHandlers = () => {
? Promise.resolve({ bytes: 0, fileCount: 0 })
: withActiveChatAttachmentRoot((rootDir) => getFixedDirectoryStats(rootDir)),
});
+ registerLocalAgentConfirmationIpc(() => mainWindowRef);
ipcMain.handle('local-agent:connections', (event) => {
assertTrustedAppRendererEvent(event);
return localAgentConnections(() => assertTrustedAppRendererEvent(event));
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts
index 030400415a..ef882b6094 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsentWindowBridge.ts
@@ -7,95 +7,21 @@
*
* 本模块不依赖 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;
- taskCapabilityPluginId?: string;
- 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 taskCapabilityPluginId = request.purpose === 'task-capability' ? request.facts.ghostId : undefined;
- // Reuse the existing pending-dialog owner. Concurrent capability attempts
- // fail closed instead of queuing more prompts or sharing another call's grant.
- if (taskCapabilityPluginId && [...this.pending.values()].some(
- pending => pending.taskCapabilityPluginId === taskCapabilityPluginId,
- )) return Promise.resolve(false);
- 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, taskCapabilityPluginId });
- 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;
- }
+import { WindowConfirmationBridge, type WindowConfirmationTarget } from '../windowConfirmationBridge.js';
- 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);
- }
+type Consent = Omit<GhostInstallConsentRequest, 'requestId'>;
+export type GhostInstallConsentWindowTarget = WindowConfirmationTarget<Consent>;
- get pendingCount(): number {
- return this.pending.size;
+/** Preserve the plugin-specific contract and duplicate capability policy. */
+export class GhostInstallConsentWindowBridge extends WindowConfirmationBridge<Consent> {
+ constructor(deps: { timeoutMs?: number } = {}) {
+ super({ ...deps, unavailableMessage: '没有可显示安装确认的窗口' });
}
- 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);
+ override request(target: GhostInstallConsentWindowTarget, request: Consent): Promise<boolean> {
+ return super.request(target, request, {
+ key: request.purpose === 'task-capability' ? request.facts.ghostId : undefined,
+ });
}
}
diff --git a/apps/desktop/src/main/local-agent/__tests__/service.test.ts b/apps/desktop/src/main/local-agent/__tests__/service.test.ts
index 6186d3ca3f..b09e5f7282 100644
--- a/apps/desktop/src/main/local-agent/__tests__/service.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/service.test.ts
@@ -1,9 +1,10 @@
/**
- * 测试价值:Main 原生授权和撤销必须显示申请方、只作用于选中的服务端授权。
+ * 测试价值:Main 主进程授权和撤销必须显示申请方、只作用于选中的服务端授权。
* 依据:通用应用授权边界;socket 测试不经过 Electron 弹窗或设置 adapter。
* 最小失败输入:名称含替换元字符、两个授权只撤销其一、取消、非法或过期编号。
* tier: unit(注入 Electron 与服务,不读取 profile、不使用模型或网络)。
*/
+import { EventEmitter } from 'node:events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
@@ -11,7 +12,9 @@ const mock = vi.hoisted(() => ({
owner: 'owner-a',
generation: 1,
startupError: undefined as Error | undefined,
- dialog: vi.fn(async (..._args: any[]) => ({ response: 1 })),
+ confirm: vi.fn(async (..._args: any[]) => true),
+ window: undefined as any,
+ handlers: new Map<string, (...args: any[]) => any>(),
revoke: vi.fn(async (_id: string) => true),
revokeAll: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -34,11 +37,10 @@ vi.mock('electron', () => ({
getPreferredSystemLanguages: () => ['zh-CN'],
},
BrowserWindow: {
- getAllWindows: () => [
- { isDestroyed: () => false, isVisible: () => true, webContents: { send: mock.send } },
- ],
+ getAllWindows: () => [mock.window],
+ fromWebContents: (contents: any) => contents === mock.window.webContents ? mock.window : null,
},
- dialog: { showMessageBox: mock.dialog },
+ ipcMain: { handle: (channel: string, handler: (...args: any[]) => any) => mock.handlers.set(channel, handler) },
}));
vi.mock('../../../shared/brandRegion.js', () => ({
get CURRENT_CINDY_REGION() {
@@ -62,8 +64,8 @@ vi.mock('../../appSessionState.js', () => ({
isAppSessionBoundaryPending: () => false,
ownerScopedUserDataPath: () => 'unused',
}));
-vi.mock('../../security/trustedAppRenderer.js', () => ({
- isTrustedAppRendererWindow: () => mock.trusted,
+vi.mock('../../windowFocusClassifier.js', () => ({
+ isAppContentWindow: (window: any) => window === mock.window && mock.trusted,
}));
vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
getDesktopProviderService: vi.fn(),
@@ -95,6 +97,13 @@ vi.mock('../server.js', () => ({
};
},
}));
+import { registerLocalAgentConfirmationIpc, cancelLocalAgentConfirmations } from '../confirmation.js';
+
+function answer(requestId: string, value: unknown, event?: any) {
+ const contents = mock.window.webContents;
+ return mock.handlers.get('local-agent:confirmation:answer')!(event ?? { sender: contents, senderFrame: contents.mainFrame }, requestId, value);
+}
+
import {
disposeLocalAgentHost,
installLocalAgentHost,
@@ -105,6 +114,15 @@ import {
beforeEach(async () => {
vi.clearAllMocks();
+ vi.stubGlobal('MAIN_WINDOW_VITE_DEV_SERVER_URL', 'http://localhost:5173');
+ vi.stubGlobal('MAIN_WINDOW_VITE_NAME', 'main_window');
+ const contents = Object.assign(new EventEmitter(), { id: 1, send: mock.send, isDestroyed: () => false,
+ mainFrame: { url: 'http://localhost:5173', parent: null } });
+ mock.window = Object.assign(new EventEmitter(), { webContents: contents, isVisible: () => true, isDestroyed: () => false });
+ registerLocalAgentConfirmationIpc(() => mock.window);
+ mock.send.mockImplementation((channel: string, payload: any) => {
+ if (channel === 'local-agent:confirmation') void mock.confirm(payload).then(value => answer(payload.requestId, value));
+ });
mock.owner = 'owner-a';
mock.generation = 1;
mock.trusted = true;
@@ -115,16 +133,70 @@ beforeEach(async () => {
mock.nonce = 0;
mock.startupGate = undefined;
mock.startupError = undefined;
- mock.dialog.mockResolvedValue({ response: 1 });
+ mock.confirm.mockResolvedValue(true);
installLocalAgentHost({} as any);
await localAgentConnections();
mock.send.mockClear();
});
afterEach(async () => {
await disposeLocalAgentHost();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
});
-describe('generic local app native authorization', () => {
+describe('generic local app Cindy authorization', () => {
+ // Regression: the old OS dialog owned cancellation. The shared Renderer round trip
+ // must now retire the exact request, including queued prompts and late replies.
+ it.each(['abort', 'close', 'destroyed', 'render-process-gone', 'navigation', 'in-page', 'timeout', 'owner'] as const)(
+ 'retires a pending confirmation on %s and rejects its late approval', async reason => {
+ vi.useFakeTimers();
+ mock.confirm.mockImplementationOnce(() => new Promise<boolean>(() => {}));
+ const controller = new AbortController();
+ const pending = mock.deps.approve(controller.signal, { id: 'notes', name: 'Notes' });
+ const id = mock.confirm.mock.calls[0][0].requestId;
+ const contents = mock.window.webContents;
+ if (reason === 'abort') controller.abort();
+ else if (reason === 'close') mock.window.emit('close');
+ else if (reason === 'navigation' || reason === 'in-page')
+ contents.emit('did-start-navigation', {}, 'http://localhost:5173/#/elsewhere', reason === 'in-page', true);
+ else if (reason === 'timeout') await vi.runOnlyPendingTimersAsync();
+ else if (reason === 'owner') { mock.generation++; cancelLocalAgentConfirmations(); }
+ else contents.emit(reason);
+ expect(await pending).toBe(false);
+ expect(answer(id, true)).toBe(false);
+ expect(mock.send).toHaveBeenCalledWith('local-agent:confirmation:dismissed', id);
+ },
+ );
+
+ it('rejects subframe, foreign window and malformed replies without approving the pending request', async () => {
+ mock.confirm.mockImplementationOnce(() => new Promise<boolean>(() => {}));
+ const pending = mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' });
+ const id = mock.confirm.mock.calls[0][0].requestId;
+ const contents = mock.window.webContents;
+ expect(() => answer(id, true, { sender: contents, senderFrame: { ...contents.mainFrame, parent: contents.mainFrame } })).toThrow('PERMISSION_DENIED');
+ const foreign = { ...contents, id: 999, mainFrame: contents.mainFrame };
+ expect(() => answer(id, true, { sender: foreign, senderFrame: foreign.mainFrame })).toThrow('PERMISSION_DENIED');
+ expect(answer(id, 'true')).toBe(false);
+ expect(answer('unknown-request', true)).toBe(false);
+ expect(answer(id, false)).toBe(true);
+ expect(await pending).toBe(false);
+ });
+
+ it('keeps concurrent allow and revoke decisions separate and cancels all on host disposal', async () => {
+ mock.confirm.mockImplementation(() => new Promise<boolean>(() => {}));
+ const allow = mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' });
+ const revoke = revokeLocalAgentConnections('grant-b');
+ await Promise.resolve();
+ const [a, b] = mock.confirm.mock.calls.map(call => call[0].requestId);
+ expect(a).not.toBe(b);
+ expect(answer(b, true)).toBe(true);
+ expect(await revoke).toBe(true);
+ expect(mock.revoke).toHaveBeenCalledExactlyOnceWith('grant-b');
+ await disposeLocalAgentHost();
+ expect(await allow).toBe(false);
+ expect(answer(a, true)).toBe(false);
+ });
+
it('shows the unverified client identity literally without expanding replacement metacharacters', async () => {
expect(
await mock.deps.approve(new AbortController().signal, {
@@ -133,7 +205,7 @@ describe('generic local app native authorization', () => {
version: '1.2',
}),
).toBe(true);
- const options = mock.dialog.mock.calls[0][1];
+ const options = mock.confirm.mock.calls[0][0];
expect(options.message).toContain('Notes $&');
expect(options.message).not.toContain('{{app}}');
expect(options.detail).toContain('org.example.notes');
@@ -141,24 +213,24 @@ describe('generic local app native authorization', () => {
expect(options.detail).toContain('1.2');
expect(options.detail).not.toMatch(/\{\{(?:id|version)\}\}/);
});
- it('revokes only the selected connection through the native confirmation', async () => {
+ it('revokes only the selected connection through the Cindy confirmation', async () => {
expect(await revokeLocalAgentConnections('grant-b')).toBe(true);
expect(mock.revoke).toHaveBeenCalledWith('grant-b');
expect(mock.revokeAll).not.toHaveBeenCalled();
- expect(mock.dialog.mock.calls[0][0].message).toContain('Board');
+ expect(mock.confirm.mock.calls[0][0].message).toContain('Board');
});
it('keeps connections on cancellation and does not turn invalid IDs into revoke-all', async () => {
- mock.dialog.mockResolvedValue({ response: 0 });
+ mock.confirm.mockResolvedValue(false);
expect(await revokeLocalAgentConnections('grant-a')).toBe(false);
expect(await revokeLocalAgentConnections('gone')).toBe(false);
await expect(revokeLocalAgentConnections({})).rejects.toThrow('INVALID_PARAMS');
expect(mock.revoke).not.toHaveBeenCalled();
expect(mock.revokeAll).not.toHaveBeenCalled();
});
- it('rejects native consent if the account changed while the prompt was open', async () => {
- mock.dialog.mockImplementationOnce(async () => {
+ it('rejects Cindy consent if the account changed while the prompt was open', async () => {
+ mock.confirm.mockImplementationOnce(async () => {
mock.owner = 'owner-b';
- return { response: 1 };
+ return true;
});
expect(
await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
@@ -173,21 +245,21 @@ describe('generic local app native authorization', () => {
});
// appSessionState.activeOwnerScopeKey includes generation: A→B→A cannot revive an old approval.
it('rejects stale consent after the same owner is recommitted', async () => {
- mock.dialog.mockImplementationOnce(async () => {
+ mock.confirm.mockImplementationOnce(async () => {
mock.generation++;
- return { response: 1 };
+ return true;
});
expect(
await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
).toBe(false);
});
- it('rechecks the IPC caller after native confirmation and keeps raw storage errors out of IPC', async () => {
+ it('rechecks the IPC caller after Cindy confirmation and keeps raw storage errors out of IPC', async () => {
const assertCaller = vi.fn();
- mock.dialog.mockImplementationOnce(async () => {
+ mock.confirm.mockImplementationOnce(async () => {
assertCaller.mockImplementation(() => {
throw new Error('caller navigated');
});
- return { response: 1 };
+ return true;
});
await expect(revokeLocalAgentConnections('grant-a', assertCaller)).rejects.toThrow(
'[INTERNAL]',
@@ -196,13 +268,13 @@ describe('generic local app native authorization', () => {
mock.revoke.mockRejectedValueOnce(new Error('PRIVATE storage path or credential'));
await expect(revokeLocalAgentConnections('grant-a')).rejects.toThrow('[INTERNAL]');
});
- it('uses trusted app windows for native consent and local notifications', async () => {
+ it('uses trusted app windows for Cindy consent and local notifications', async () => {
mock.trusted = false;
expect(
await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
).toBe(false);
mock.deps.changed();
- expect(mock.dialog).not.toHaveBeenCalled();
+ expect(mock.confirm).not.toHaveBeenCalled();
expect(mock.send).not.toHaveBeenCalled();
});
it('does not load another grant snapshot when a shared-profile instance already owns discovery', async () => {
diff --git a/apps/desktop/src/main/local-agent/confirmation.ts b/apps/desktop/src/main/local-agent/confirmation.ts
new file mode 100644
index 0000000000..e513e82ce6
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/confirmation.ts
@@ -0,0 +1,62 @@
+import { ipcMain, type BrowserWindow, type WebContents } from 'electron';
+import type { LocalAgentConfirmation } from '../../shared/localAgent.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { assertTrustedAppRendererEvent, isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
+import { WindowConfirmationBridge } from '../windowConfirmationBridge.js';
+
+type Copy = Omit<LocalAgentConfirmation, 'requestId'>;
+const bridge = new WindowConfirmationBridge<Copy>();
+let getWindow: () => BrowserWindow | null = () => null;
+const tracked = new WeakSet<WebContents>();
+
+/** Local only: no device-link allowlist or external HTTP decision endpoint. */
+export function registerLocalAgentConfirmationIpc(window: () => BrowserWindow | null): void {
+ getWindow = window;
+ ipcMain.handle('local-agent:confirmation:answer', (event, requestId: unknown, confirmed: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof requestId !== 'string' || requestId.length > 128 || typeof confirmed !== 'boolean')
+ return false;
+ if (isAppSessionBoundaryPending()) return false;
+ return bridge.resolve(event.sender.id, requestId, confirmed);
+ });
+}
+
+export function cancelLocalAgentConfirmations(): void { bridge.cancelAll(); }
+
+export async function confirmLocalAgent(copy: Copy, signal?: AbortSignal): Promise<boolean> {
+ const parent = getWindow();
+ if (!parent || !isTrustedAppRendererWindow(parent) || !parent.isVisible() ||
+ signal?.aborted || isAppSessionBoundaryPending()) return false;
+ const contents = parent.webContents;
+ const owner = activeOwnerScopeKey();
+ if (!tracked.has(contents)) {
+ tracked.add(contents);
+ const cancel = () => bridge.cancelRequester(contents.id);
+ parent.on('close', cancel);
+ contents.once('destroyed', cancel);
+ contents.on('render-process-gone', cancel);
+ // Even an in-page navigation retires the prompt and its queued response.
+ contents.on('did-start-navigation', (_event, _url, _sameDocument, mainFrame) => {
+ if (mainFrame) cancel();
+ });
+ }
+ const current = () => !signal?.aborted && !isAppSessionBoundaryPending() &&
+ activeOwnerScopeKey() === owner && isTrustedAppRendererWindow(parent);
+ try {
+ const approved = await bridge.request({
+ id: contents.id,
+ send: request => {
+ if (!current()) return false;
+ contents.send('local-agent:confirmation', request);
+ return true;
+ },
+ dismiss: requestId => {
+ if (isTrustedAppRendererWindow(parent))
+ contents.send('local-agent:confirmation:dismissed', requestId);
+ },
+ }, copy, { signal });
+ return approved && current();
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/src/main/local-agent/service.ts b/apps/desktop/src/main/local-agent/service.ts
index 86986755d6..2fb4b32129 100644
--- a/apps/desktop/src/main/local-agent/service.ts
+++ b/apps/desktop/src/main/local-agent/service.ts
@@ -1,4 +1,4 @@
-import { app, BrowserWindow, dialog } from 'electron';
+import { app, BrowserWindow } from 'electron';
import { createHash } from 'node:crypto';
import path from 'node:path';
import fs from 'node:fs/promises';
@@ -29,6 +29,8 @@ import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
import { openLocalAgentRuntime } from './runtime.js';
import { localAgentMessage } from './messages.js';
+import { confirmLocalAgent, cancelLocalAgentConfirmations } from './confirmation.js';
+
const log = createLogger('local-agent');
let current: Promise<Awaited<ReturnType<typeof createLocalAgentServer>>> | undefined;
let startupFailure: unknown;
@@ -135,29 +137,16 @@ export function installLocalAgentHost(maker: Maker): void {
return localAgentModels(providers, maker.listAvailableAgents());
},
async approve(signal, client) {
- const parent = BrowserWindow.getAllWindows().find(
- (window) => isTrustedAppRendererWindow(window) && window.isVisible(),
- );
- if (!parent || signal.aborted) return false;
- const result = await dialog.showMessageBox(parent, {
- signal,
- type: 'question',
+ const approved = await confirmLocalAgent({
title: t('localAgent.connectTitle'),
message: t('localAgent.connectMessage').replaceAll('{{app}}', () => client.name),
detail: `${t('localAgent.connectDetail')}\n\n${t('localAgent.clientIdentity')
.replaceAll('{{id}}', () => client.id)
.replaceAll('{{version}}', () => client.version ?? '—')}`,
- buttons: [t('localAgent.cancel'), t('localAgent.allow')],
- defaultId: 0,
- cancelId: 0,
- noLink: true,
- });
- return (
- result.response === 1 &&
- !signal.aborted &&
- scopeNow() === scope &&
- isTrustedAppRendererWindow(parent)
- );
+ confirmText: t('localAgent.allow'),
+ cancelText: t('localAgent.cancel'),
+ }, signal);
+ return approved && !signal.aborted && scopeNow() === scope;
},
open: (input, bridge) =>
openLocalAgentRuntime(maker, directory, input, bridge, localAgentMessage),
@@ -266,21 +255,18 @@ export async function revokeLocalAgentConnections(
? undefined
: server.connections().find((connection) => connection.id === connectionId);
if (connectionId !== undefined && !selected) return false;
- const result = await dialog.showMessageBox({
- type: 'warning',
+ const approved = await confirmLocalAgent({
title: t('localAgent.title'),
message: selected
? t('localAgent.revokeOneMessage').replaceAll('{{app}}', () => selected.name)
: t('localAgent.revokeMessage'),
detail: selected ? t('localAgent.revokeOneDetail') : t('localAgent.revokeDetail'),
- buttons: [t('localAgent.cancel'), t('localAgent.revoke')],
- cancelId: 0,
- defaultId: 0,
- noLink: true,
+ cancelText: t('localAgent.cancel'),
+ confirmText: t('localAgent.revoke'),
});
assertCaller();
if (
- result.response !== 1 ||
+ !approved ||
owner !== activeOwnerScopeKey() ||
isAppSessionBoundaryPending() ||
current !== pendingServer
@@ -293,6 +279,7 @@ export async function revokeLocalAgentConnections(
}
export async function disposeLocalAgentHost(): Promise<void> {
+ cancelLocalAgentConfirmations();
const previous = current;
current = undefined;
readyServer = undefined;
diff --git a/apps/desktop/src/main/windowConfirmationBridge.ts b/apps/desktop/src/main/windowConfirmationBridge.ts
new file mode 100644
index 0000000000..b3a45bc213
--- /dev/null
+++ b/apps/desktop/src/main/windowConfirmationBridge.ts
@@ -0,0 +1,82 @@
+import { randomUUID } from 'node:crypto';
+import { HOST_CONFIRM_TIMEOUT_MS } from './maker-ipc/hostConfirmTiming.js';
+
+export interface WindowConfirmationTarget<T> {
+ id: number;
+ send(request: T & { requestId: string }): boolean;
+ dismiss(requestId: string): void;
+}
+
+interface PendingConfirmation<T> {
+ target: WindowConfirmationTarget<T>;
+ key?: string;
+ resolve(confirmed: boolean): void;
+ timer: ReturnType<typeof setTimeout>;
+ signal?: AbortSignal;
+ abort(): void;
+}
+
+/** Shared window-bound round trip extracted from the install-consent bridge.
+ * Main owns the pending decision; delivery, abort and timeout never grant consent. */
+export class WindowConfirmationBridge<T> {
+ private readonly pending = new Map<string, PendingConfirmation<T>>();
+
+ constructor(private readonly deps: { timeoutMs?: number; unavailableMessage?: string } = {}) {}
+
+ request(
+ target: WindowConfirmationTarget<T>,
+ request: T,
+ options: { signal?: AbortSignal; key?: string } = {},
+ ): Promise<boolean> {
+ if (options.signal?.aborted) return Promise.resolve(false);
+ if (options.key && [...this.pending.values()].some(entry => entry.key === options.key))
+ return Promise.resolve(false);
+ const requestId = randomUUID();
+ return new Promise<boolean>((resolve, reject) => {
+ const abort = () => this.settle(requestId, false);
+ const timer = setTimeout(abort, this.deps.timeoutMs ?? HOST_CONFIRM_TIMEOUT_MS);
+ this.pending.set(requestId, { target, key: options.key, resolve, timer, signal: options.signal, abort });
+ options.signal?.addEventListener('abort', abort, { once: true });
+ let delivered = false;
+ try {
+ delivered = target.send({ ...request, requestId });
+ } catch {
+ // A closed or unavailable window cannot approve.
+ }
+ if (!delivered && this.pending.has(requestId)) {
+ this.pending.delete(requestId);
+ clearTimeout(timer);
+ options.signal?.removeEventListener('abort', abort);
+ reject(new Error(this.deps.unavailableMessage ?? 'Confirmation window unavailable'));
+ } else if (options.signal?.aborted) abort();
+ });
+ }
+
+ resolve(requesterId: number, requestId: string, confirmed: unknown): boolean {
+ const entry = this.pending.get(requestId);
+ if (!entry || entry.target.id !== requesterId) return false;
+ this.settle(requestId, confirmed === true);
+ return true;
+ }
+
+ cancelRequester(requesterId: number): void {
+ for (const [id, entry] of [...this.pending])
+ if (entry.target.id === requesterId) this.settle(id, false);
+ }
+
+ cancelAll(): void {
+ for (const id of [...this.pending.keys()]) this.settle(id, false);
+ }
+
+ get pendingCount(): number { return this.pending.size; }
+
+ private settle(id: string, confirmed: boolean): void {
+ const entry = this.pending.get(id);
+ if (!entry) return;
+ this.pending.delete(id);
+ clearTimeout(entry.timer);
+ entry.signal?.removeEventListener('abort', entry.abort);
+ try { entry.target.dismiss(id); } catch { /* Window already gone. */ }
+ entry.resolve(confirmed);
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 00c6adc98b..555b4ded01 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1077,6 +1077,18 @@ const appearanceSettingsInfo = ipcRenderer.sendSync(
contextBridge.exposeInMainWorld('electronAPI', {
localAgent: {
+ onConfirmation: (listener: (request: import('../shared/localAgent').LocalAgentConfirmation) => void): (() => void) => {
+ const receive = (_event: Electron.IpcRendererEvent, request: import('../shared/localAgent').LocalAgentConfirmation) => listener(request);
+ ipcRenderer.on('local-agent:confirmation', receive);
+ return () => ipcRenderer.removeListener('local-agent:confirmation', receive);
+ },
+ onConfirmationDismissed: (listener: (requestId: string) => void): (() => void) => {
+ const receive = (_event: Electron.IpcRendererEvent, requestId: string) => listener(requestId);
+ ipcRenderer.on('local-agent:confirmation:dismissed', receive);
+ return () => ipcRenderer.removeListener('local-agent:confirmation:dismissed', receive);
+ },
+ answerConfirmation: (requestId: string, confirmed: boolean): Promise<boolean> =>
+ ipcRenderer.invoke('local-agent:confirmation:answer', requestId, confirmed),
developerConnection: (): Promise<import('../shared/localAgent').LocalAgentDeveloperConnection | null> => ipcRenderer.invoke('local-agent:developer-connection'),
connections: (): Promise<import('../shared/localAgent').LocalAgentConnection[]> => ipcRenderer.invoke('local-agent:connections'),
revoke: (connectionId?: string): Promise<boolean> => ipcRenderer.invoke('local-agent:revoke', connectionId),
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 3c1feeaa70..5474e2142e 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -32,6 +32,7 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';
import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';
import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';
+import { LocalAgentConfirmationHost } from '@/components/LocalAgentConfirmationHost';
import { ForgeOidcInstallConfirmHost } from '@/cindy-brain/ForgeOidcInstallConfirmHost';
import { GhostInstallConsentHost } from '@/cindy-brain/GhostInstallConsentHost';
import { PluginPublisherConfirmHost } from '@/features/plugin/PluginPublisherConfirmHost';
@@ -460,6 +461,7 @@ export function App() {
内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口
都挂、谁收到谁弹,不按窗口类型 gate。 */}
<GhostConfirmDialogHost />
+ <LocalAgentConfirmationHost />
<ForgeOidcInstallConfirmHost />
<GhostInstallConsentHost />
<PluginPublisherConfirmHost />
diff --git a/apps/desktop/src/renderer/components/LocalAgentConfirmationHost.tsx b/apps/desktop/src/renderer/components/LocalAgentConfirmationHost.tsx
new file mode 100644
index 0000000000..dbb308cc3d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/LocalAgentConfirmationHost.tsx
@@ -0,0 +1,45 @@
+import { useEffect } from 'react';
+import { useConfirmDialog } from './ui/confirm-dialog-provider';
+
+/** Reuse Cindy's modal queue, focus trap, theme and dismiss/abort behavior. */
+export function LocalAgentConfirmationHost() {
+ const { confirm } = useConfirmDialog();
+ useEffect(() => {
+ const pending = new Map<string, AbortController>();
+ const api = window.electronAPI.localAgent;
+ const offDismiss = api.onConfirmationDismissed(id => pending.get(id)?.abort());
+ const offRequest = api.onConfirmation(request => {
+ if (pending.has(request.requestId)) return;
+ const controller = new AbortController();
+ pending.set(request.requestId, controller);
+ void (async () => {
+ try {
+ const approved = await confirm({
+ title: request.title,
+ description: request.message,
+ textClassName: '[overflow-wrap:anywhere]',
+ content: <p className="whitespace-pre-wrap text-13 leading-normal text-[var(--confirm-desc)] [overflow-wrap:anywhere]">{request.detail}</p>,
+ describeContent: true,
+ confirmText: request.confirmText,
+ cancelText: request.cancelText,
+ }, controller.signal);
+ if (!controller.signal.aborted)
+ await api.answerConfirmation(request.requestId, approved);
+ } catch {
+ // Main's bounded request lifecycle fails closed if the renderer is gone.
+ } finally {
+ pending.delete(request.requestId);
+ }
+ })();
+ });
+ return () => {
+ offRequest(); offDismiss();
+ for (const [id, controller] of pending) {
+ controller.abort();
+ void api.answerConfirmation(id, false).catch(() => {});
+ }
+ pending.clear();
+ };
+ }, [confirm]);
+ return null;
+}
diff --git a/apps/desktop/src/shared/localAgent.ts b/apps/desktop/src/shared/localAgent.ts
index fd277cb3a8..c5cb4da707 100644
--- a/apps/desktop/src/shared/localAgent.ts
+++ b/apps/desktop/src/shared/localAgent.ts
@@ -10,6 +10,19 @@ export interface LocalAgentSettingsApi {
connections(): Promise<LocalAgentConnection[]>;
revoke(connectionId?: string): Promise<boolean>;
onConnectionsChanged(listener: () => void): () => void;
+ onConfirmation(listener: (request: LocalAgentConfirmation) => void): () => void;
+ onConfirmationDismissed(listener: (requestId: string) => void): () => void;
+ answerConfirmation(requestId: string, confirmed: boolean): Promise<boolean>;
+}
+
+/** Main-owned display copy. No grant, token or permission decision is sent here. */
+export interface LocalAgentConfirmation {
+ requestId: string;
+ title: string;
+ message: string;
+ detail: string;
+ confirmText: string;
+ cancelText: string;
}
/** Unauthenticated build self-description; never proof of a publisher or an app grant. */
diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.md
index 663936435a..3618bc97c3 100644
--- a/docs/dev-rules/repo-map.md
+++ b/docs/dev-rules/repo-map.md
@@ -62,7 +62,7 @@
## 本机应用 Agent 接入
-Desktop 的 `main/local-agent/` 提供经原生授权的通用本机 Agent API,复用 maker-core 的引擎与内存 Session;应用自己的界面、记录、上下文和业务工具留在调用方。协议、存储和兼容边界见 [本机应用接入](../local-agent-api.md),独立客户端示例在 `scripts/examples/`。
+Desktop 的 `main/local-agent/` 提供经 Cindy 主题确认授权的通用本机 Agent API,复用 maker-core 的引擎与内存 Session;应用自己的界面、记录、上下文和业务工具留在调用方。协议、存储和兼容边界见 [本机应用接入](../local-agent-api.md),独立客户端示例在 `scripts/examples/`。
## 校验下载与工具安装
diff --git a/docs/local-agent-api.md b/docs/local-agent-api.md
index 99e204e6d1..e637371dea 100644
--- a/docs/local-agent-api.md
+++ b/docs/local-agent-api.md
@@ -15,7 +15,7 @@ node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/
node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/discovery.json" --provider "<provider-id>" --engine pi --model "<opaque-model-id>" --cwd "<absolute-folder>"
```
-每次在 Cindy 的原生弹窗允许该应用。第二条命令运行一个只做文本回显的 `client_echo` 工具,再接收模型回答。可用 `--client-id org.example.notes --client-name Notes` 和另一组身份同时启动两份示例;两者可使用相同会话编号。`--prompt` 自定输入,`--native-tools` 显式启用原生执行。模型调用会消费所选供应商额度。
+每次在 Cindy 的主题确认弹窗允许该应用。第二条命令运行一个只做文本回显的 `client_echo` 工具,再接收模型回答。可用 `--client-id org.example.notes --client-name Notes` 和另一组身份同时启动两份示例;两者可使用相同会话编号。`--prompt` 自定输入,`--native-tools` 显式启用原生执行。模型调用会消费所选供应商额度。
示例令牌只在进程内存中,退出时关闭自己的会话并撤销自己的授权,不打印、保存或复用令牌。需要长期连接的产品自行通过 OS 凭据库保存此应用令牌;不得复制供应商登录。命令行参数不接收秘密。`--list-models` 不调用模型生成。
@@ -31,7 +31,7 @@ node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/
node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<port>:<instance>" --list-models
```
-独立Node示例保留 `--discovery` 旧入口,两个入口必须二选一。接码后只向 `http://127.0.0.1:<port>/rpc` 发无Bearer的 `capabilities`,携带码中nonce,拒绝重定向;握手超时750ms、响应上限32KiB。先核对protocol和instance,再核对 `features.instanceMetadata:true` 和 `instanceInfo:{kind,region}`;开发入口必须为 `kind:"development"`,region只能是global/cn/dev。缺元数据报 `INSTANCE_METADATA_UNSUPPORTED`,类型不符报 `INSTANCE_METADATA_MISMATCH`,端点代次不符报 `INSTANCE_CHANGED`,网络/超时/非法JSON不能验证时为 `CONNECTION_UNAVAILABLE`。只有握手通过后才按原 `connect/start` / 原生确认 / `connect/poll` 申请授权;拒绝、取消和超时保持原协议,不自动批准。
+独立Node示例保留 `--discovery` 旧入口,两个入口必须二选一。接码后只向 `http://127.0.0.1:<port>/rpc` 发无Bearer的 `capabilities`,携带码中nonce,拒绝重定向;握手超时750ms、响应上限32KiB。先核对protocol和instance,再核对 `features.instanceMetadata:true` 和 `instanceInfo:{kind,region}`;开发入口必须为 `kind:"development"`,region只能是global/cn/dev。缺元数据报 `INSTANCE_METADATA_UNSUPPORTED`,类型不符报 `INSTANCE_METADATA_MISMATCH`,端点代次不符报 `INSTANCE_CHANGED`,网络/超时/非法JSON不能验证时为 `CONNECTION_UNAVAILABLE`。只有握手通过后才按原 `connect/start` / Cindy 确认 / `connect/poll` 申请授权;拒绝、取消和超时保持原协议,不自动批准。
`instanceInfo` 是可选的两字段构建自述,版本继续使用capabilities顶层 `version`。只有实际packaged、非已验证个人构建且region非dev才是installed;unpackaged、CindyDev或个人构建均为development,不能按版本号或profile路径猜。region来自既有构建区域,默认global规则不变。元数据用于避免错连,不是对同OS用户恶意程序的发行认证。
@@ -66,8 +66,10 @@ node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<
## 应用授权
1. `connect/start`:`{"client":{"id":"org.example.notes","name":"Notes","version":"1.0"}}`,返回 `{id,claim,url}`。id 最多 128 字符,只含字母、数字、点、下划线、连字符且以字母或数字开头;名称最多 80 字符,version 可省略、最多 64 字符。名称/版本不接受控制或双向覆盖字符。
-2. Cindy 在**本机**显示应用自报名称、编号及能力说明,由用户允许或取消。客户端无需打开返回的兼容网页才能触发弹窗。
+2. Cindy 在**本机**显示应用自报名称、编号及能力说明,由用户允许或取消。客户端无需打开返回的兼容网页才能触发弹窗。允许连接和撤销连接复用 Cindy 的主题确认组件及确认队列,默认焦点在取消,支持 Esc、Tab 焦点约束;不会弹出操作系统消息框。
3. `connect/poll`:`{id,claim}`,返回 `{state:"waiting"|"denied"|"approved",token?}`;通过后才有 token。申请两分钟过期。`connect/cancel` 用同一组 id/claim 取消并撤销该申请已经签发的授权。
+确认请求由 Main 生成不可复用的编号,只投递到当前可信主窗口;回包必须来自同一窗口的顶层 Cindy 页面。窗口关闭、崩溃、导航(含页内导航)、账号换代、宿主关闭、请求取消或超时都会取消待确认项,迟到回包不能批准。Renderer 只提供用户选择,Main 在执行前再次核对 owner generation 与请求归属;HTTP 客户端不能提交确认回包。并发请求沿用 Cindy 的确认队列,各自独立结算。
+
4. 后续请求带 `Authorization: Bearer <token>`。`connect/revoke` 无参数,只撤销**当前令牌自己的授权**。
应用名称、id、version 都是申请方自报的展示资料,不能证明安装包或发布者身份。相同 app id / 名称不会得到已有授权或会话;每次经用户允许产生独立、不可猜测的 bearer 凭据。名字不是认证依据,不按品牌自动批准。
@@ -136,13 +138,16 @@ Claude client-only 关闭原生 tools/settings/skills;Pi 仅开启客户端网
常见可判断错误:`UNAUTHORIZED`(重新授权)、`INSTANCE_CHANGED`(重新发现)、`MODEL_UNAVAILABLE`(重新选择有效来源)、`RESUME_UNAVAILABLE`(新会话并交接上下文)、`SESSION_UNAVAILABLE`(原会话已关闭或不属于此授权)、`UNSUPPORTED_ACCESS`(策略不支持/矛盾)、`ID_REUSED` / `REQUEST_EXPIRED`(未重复执行)、`GRANT_STORE_INVALID`(保留原文件并检查版本/存储)。
-错误 code 保持稳定,展示文案、原生确认及兼容结果页通过 Cindy 当前语言的五语资源提供。设置 IPC 复用受信顶层窗口校验与统一 IPC 错误协议;等待原生确认后再次校验发起窗口及 owner generation,不向 Renderer 返回原始存储异常。
+错误 code 保持稳定,展示文案、Cindy 确认及兼容结果页通过 Cindy 当前语言的五语资源提供。设置 IPC 复用受信顶层窗口校验与统一 IPC 错误协议;等待 Cindy 确认后再次校验发起窗口及 owner generation,不向 Renderer 返回原始存储异常。
-此入口只管理当前电脑的本机应用,不执行 SSH 工作区任务,不加入 device-link 的通用 invoke/push 白名单,也未新增 Mobile 入口。远程管理此类授权需要另行定义目标电脑的原生确认和授权范围,不能把本机 handler 隐式开放给远端。
+此入口只管理当前电脑的本机应用,不执行 SSH 工作区任务,不加入 device-link 的通用 invoke/push 白名单,也未新增 Mobile 入口。远程管理此类授权需要另行定义目标电脑的 Cindy 确认和授权范围,不能把本机 handler 隐式开放给远端。
## 验证入口
- `apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts`:真实 loopback、独立示例进程、同编号并行、越权拒绝、单项撤销、重启恢复及旧存储迁移;模型执行可注入,不能把它说成真实供应商验收。
- `runtime.test.ts`:目录和事件不重复投影,通用及历史 namespace。
- `maker-core` 对应适配器:Claude SDK 隔离选项;Pi 真二进制 + 本机模型响应夹具;Codex 真 app-server(需 `CINDY_CODEX_TEST_BINARY`)。
-- `apps/desktop/scripts/fixtures/local-agent/`:真实设置组件,多应用单项撤销、取消、失败、手机宽度、五种语言与深浅主题;宿主接口由场景提供,不替代原生授权与真实 IPC 验收。
+- `apps/desktop/scripts/fixtures/local-agent/`:真实设置组件,多应用单项撤销、取消、失败、手机宽度、五种语言与深浅主题;宿主接口由场景提供,不替代真实授权与 IPC 验收。
+
+- `service.test.ts`:真实 service/确认桥接/可信 IPC handler 联动,批准、取消、abort、超时、导航/关闭、账号换代、伪造回包和并发撤销隔离。
+- `apps/desktop/scripts/fixtures/local-agent-confirmation/`:生产确认 Host 与共用 ConfirmDialog,五语言、双主题、320px、默认取消焦点、Tab/Esc、队列取消;主进程与实际授权另由隔离 Desktop 验证。