Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 支持在被控端执行远控 Review (#5329)
DavidShenXD504f7bd37d04
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.tsindex 06c861d89b..d1ea78a8d8 100644--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts@@ -20,6 +20,12 @@ vi.mock('../../logger', () => ({import { rewriteOutboundMedia, withPeerAttachmentUpload, __testing } from '../outboundMedia';import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';import { buildUserMessageAttachmentPayload } from '../../../renderer/lib/messageAttachmentPayload';+import { REVIEW_START_REQUEST_LIMITS } from '../../maker-ipc/reviewStartHandler';++// Authorization/snapshot behavior has its own filesystem-backed regression suite.+vi.mock('../../maker-ipc/reviewOutboundInput', () => ({+ withPreparedOutboundReview: (request: unknown, upload: (value: unknown) => unknown) => upload(request),+}));import { withSharedTaskMedia } from '../sharedTaskMediaContext.js';import { assertSharedTaskReferences } from '../sharedTaskDispatch.js';import { parseAttachmentOssRef, isAttachmentOssRef } from '../../../shared/attachmentOssRef';@@ -43,6 +49,43 @@ beforeEach(() => {});describe('rewriteOutboundMedia — channel gating', () => {+ it.each([+ ['count', () => Array.from({ length: 21 }, () => ({ name: 'a', path: '/controller/a' }))],+ ['metadata', () => [{ name: 'a', path: '/controller/a' }, { name: 'x'.repeat(4097), path: '/controller/b' }]],+ ['total metadata', () => Array.from({ length: 5 }, () => ({ name: 'a', url: 'a'.repeat(64 * 1024) }))],+ ['single inline payload', () => [{ name: 'a', base64: 'a'.repeat(REVIEW_START_REQUEST_LIMITS.attachmentBase64Chars + 1) }]],+ ['total inline payload', () => Array.from({ length: 3 }, () => ({ name: 'a', base64: 'a'.repeat(24 * 1024 * 1024) }))],+ ] as const)('rejects Review %s limits before reading, compressing or staging any attachment', async (_label, attachments) => {+ const peerUpload = vi.fn();+ await expect(withPeerAttachmentUpload(peerUpload, () => rewriteOutboundMedia('maker:review:start', [{+ sourceSessionId: 'source', attachments: attachments(),+ }]))).rejects.toThrow('INVALID_PARAMS');+ expect(peerUpload).not.toHaveBeenCalled();+ expect(uploadLocalFile).not.toHaveBeenCalled();+ expect(uploadBuffer).not.toHaveBeenCalled();+ expect(resolveSafe).not.toHaveBeenCalled();+ });++ it('uploads Review attachments and strips controller-local paths without mutating the request', async () => {+ const request = { sourceSessionId: 'source', focus: 'docs', attachments: [+ { name: 'notes.md', path: '/controller/notes.md', category: 'text' },+ ] };+ const result = await rewriteOutboundMedia('maker:review:start', [request]);+ const rewritten = result[0] as typeof request;+ expect(rewritten.sourceSessionId).toBe('source');+ expect(rewritten.focus).toBe('docs');+ expect(isAttachmentOssRef(rewritten.attachments[0].path)).toBe(true);+ expect(JSON.stringify(result)).not.toContain('/controller/notes.md');+ expect(request.attachments[0].path).toBe('/controller/notes.md');+ expect(uploadLocalFile).toHaveBeenCalledOnce();+ });++ it('rejects Review when attachment upload fails', async () => {+ uploadLocalFile.mockRejectedValue(new Error('upload failed'));+ await expect(rewriteOutboundMedia('maker:review:start', [{+ sourceSessionId: 'source', attachments: [{ name: 'notes.md', path: '/controller/notes.md' }],+ }])).rejects.toThrow('upload failed');+ });it('uses peer staging for exact file bytes, preserves the name and retains OSS fallback', async () => {const direct = vi.fn(async () => buildPeerAttachmentRef({ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 10, sha256: SHA256, mimeType: 'text/plain' }));const args = ['session', { type: 'user', content: [{ type: 'file', path: '/controller/a.txt', originalName: 'a.txt' }] }];diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.tsindex 54e0fece33..1a1d8a5fd6 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts@@ -5,6 +5,21 @@ import {afterEach(() => setRemoteBotSessionLookup(null));+it('checks the normalized source task before remote Review and rechecks visibility changes', async () => {+ let hidden = false;+ const lookup = vi.fn(async () => hidden ? 'hidden' as const : 'ordinary' as const);+ setRemoteBotSessionLookup(lookup);+ const args = [{ sourceSessionId: ' source ' }];+ await assertRemoteBotInvocationAllowed(args, 'maker:review:start');+ expect(lookup).toHaveBeenCalledWith('source', 'session');+ hidden = true;+ await expect(assertRemoteBotInvocationAllowed(args, 'maker:review:start')).rejects.toThrow('[NOT_FOUND]');+});++it.each([undefined, '', ' ', 123, 'x'.repeat(513)])('rejects invalid Review source ID %s', async (sourceSessionId) => {+ await expect(assertRemoteBotInvocationAllowed([{ sourceSessionId }], 'maker:review:start')).rejects.toThrow('[INVALID_PARAMS]');+});+it.each(['turn-list', 'turn-get'])('rechecks nested %s targets before returning remote snapshots', async (op) => {let hidden = false;setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex be1b6d99fe..75b6602a6f 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -62,6 +62,8 @@ import {} from './index';import { getActiveControllers } from './dispatch';import { rewriteOutboundMedia, withPeerAttachmentUpload } from './outboundMedia';+import { withOutboundReviewConfirmation } from '../maker-ipc/reviewOutboundInput.js';+import { confirmReviewArtifacts } from '../reviewer/confirmReviewArtifacts.js';import { tryUploadPeerAttachment } from './filePeer';import { parseSharedTaskPeer } from '@cindy/device-link';import { withSharedTaskMedia } from './sharedTaskMediaContext.js';@@ -1404,6 +1406,13 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown };+ if (p.channel === 'maker:review:start') {+ assertTrustedAppRendererEvent(e);+ return withOutboundReviewConfirmation(+ (items) => confirmReviewArtifacts(e, items),+ () => handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args),+ );+ }return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args);});// 多窗口订阅引用计数:每个发起订阅的窗口(WebContents)挂一次 'destroyed' 清理,diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.tsindex d32d0da83d..c1aa16d0a1 100644--- a/apps/desktop/src/main/device-link/outboundMedia.ts+++ b/apps/desktop/src/main/device-link/outboundMedia.ts@@ -31,6 +31,8 @@ import {mayCompressOutboundImage,} from './outboundImageCompress';import { buildLegacyAttachmentOssRef, parseAttachmentOssRef } from '../../shared/attachmentOssRef';+import { readStartReviewRequest } from '../maker-ipc/reviewStartHandler.js';+import { withPreparedOutboundReview } from '../maker-ipc/reviewOutboundInput.js';const log = createLogger('device-link:outboundMedia');@@ -380,6 +382,14 @@ async function rewriteQueued(item: unknown, existing: ReadonlySet<string> = new* 抛错由 handleInvoke 转 MEDIA_TRANSFER_FAILED。*/export async function rewriteOutboundMedia(channel: string, args: unknown[], existing: ReadonlySet<string> = new Set()): Promise<unknown[]> {+ if (channel === 'maker:review:start') {+ // Validate the complete batch before any compression, disk read or upload.+ const request = readStartReviewRequest(args[0]);+ return withPreparedOutboundReview(request, async (prepared) => {+ const rewritten = await rewriteQueued({ files: prepared.attachments }) as { files: unknown[] };+ return [{ ...prepared, attachments: rewritten.files }, ...args.slice(1)];+ });+ }const steerOpts = args[2];if (channel === 'maker:input:steer' &&diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.tsindex d396d2f0b4..536019abae 100644--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts@@ -24,6 +24,16 @@ function sessionIds(value: unknown): string[] {/** Resolve channel-specific Bot IDs before checking generic Session references. */export async function assertRemoteBotInvocationAllowed(args: unknown[], channel = ''): Promise<void> {+ if (channel === 'maker:review:start') {+ const id = record(args[0])?.sourceSessionId;+ if (typeof id !== 'string' || !id.trim() || id.length > 512) {+ throw new Error('[INVALID_PARAMS] Invalid review source session ID');+ }+ if (lookup && await lookup(id.trim(), 'session') === 'hidden') {+ throw new Error('[NOT_FOUND] Session does not exist');+ }+ return;+ }// Review queries nest the target under payload; recheck it before execution// and on cached/queued replies just like top-level Session reads.if (channel === 'git-review:remote-op') {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewOutboundInput.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewOutboundInput.test.tsnew file mode 100644index 0000000000..d8e783c8a8--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewOutboundInput.test.ts@@ -0,0 +1,139 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { buildAttachmentOssRef, buildPeerAttachmentRef } from '@cindy/device-link';+import type { StartReviewRequest } from '../reviewStartHandler';+import { withOutboundReviewConfirmation, withPreparedOutboundReview } from '../reviewOutboundInput';++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));+});++async function setup(managed = false) {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-outbound-'));+ roots.push(root);+ const file = path.join(root, 'external.md');+ await fs.writeFile(file, 'approved bytes');+ const request = { sourceSessionId: 'remote-source', focus: '/host/only.md', attachments: [{ name: 'external.md', path: file }] };+ const deps = {+ owner: { instanceId: 'outbound-test', processId: process.pid, liveness: { version: 1 as const, port: 65534, token: 'outbound-test-token' } },+ ensureOwnerReady: vi.fn(async () => {}),+ resolvePath: async (raw: string) => ({ absPath: await fs.realpath(raw), managed }),+ };+ return { request, deps, file };+}++describe('controller Review attachment authorization', () => {+ const integrity = { size: 1, sha256: 'a'.repeat(64) };+ const sensitiveAttachments: Array<[string, StartReviewRequest['attachments'][number]]> = [+ ['inline dotenv', { name: '.env', base64: 'ZmFrZQ==' }],+ ['inline key', { name: 'id_rsa', base64: 'ZmFrZQ==' }],+ ['cached label', { name: '.env.local', url: 'xdt-image://task/ordinary.txt' }],+ ['cached original name', { name: 'ordinary.txt', originalName: 'id_rsa', url: 'cindy-media://blobs/ordinary.txt' }],+ ['masked name', { name: '.env', originalName: 'ordinary.txt', base64: 'ZmFrZQ==' }],+ ['source path', { name: 'ordinary.txt', path: path.join(os.tmpdir(), 'fake-review-fixture', '.env') }],+ ['alternate path', { name: 'ordinary.txt', url: 'xdt-image://task/ordinary.txt', path: path.join(os.tmpdir(), 'fake-review-fixture', 'id_rsa') }],+ ['peer original name', { name: 'ordinary.txt', url: buildPeerAttachmentRef({ ...integrity, ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', originalName: '.env' }) }],+ ['OSS original name', { name: 'ordinary.txt', url: buildAttachmentOssRef({ ...integrity, ossKey: 'cindy/device-link/fake/ordinary.txt', originalName: 'id_rsa' }) }],+ ];++ it.each(sensitiveAttachments)('rejects %s before preparing or uploading any attachment', async (_label, attachment) => {+ const { request, deps } = await setup();+ deps.resolvePath = vi.fn();+ const confirm = vi.fn(async () => true);+ const upload = vi.fn();+ const batch = { ...request, attachments: [...request.attachments, attachment] };+ await expect(withOutboundReviewConfirmation(confirm, () => withPreparedOutboundReview(batch, upload, deps))).rejects.toThrow('PERMISSION_DENIED');+ expect(deps.resolvePath).not.toHaveBeenCalled();+ expect(deps.ensureOwnerReady).not.toHaveBeenCalled();+ expect(confirm).not.toHaveBeenCalled();+ expect(upload).not.toHaveBeenCalled();+ });++ it.each(['.environment', '.envrc', 'environment.ts'])('keeps ordinary similarly named attachments usable (%s)', async (name) => {+ const { request, deps } = await setup();+ const upload = vi.fn(async () => 'uploaded');+ const batch = { ...request, attachments: [{ ...request.attachments[0], name }] };+ await expect(withOutboundReviewConfirmation(async () => true, () => withPreparedOutboundReview(batch, upload, deps))).resolves.toBe('uploaded');+ expect(upload).toHaveBeenCalledOnce();+ });++ it.each([false, undefined])('uploads nothing when native confirmation is denied or unavailable (%s)', async (decision) => {+ const { request, deps } = await setup();+ const upload = vi.fn();+ const operation = () => withPreparedOutboundReview(request, upload, deps);+ const run = decision === undefined ? operation() : withOutboundReviewConfirmation(async () => decision, operation);+ await expect(run).rejects.toThrow('cancelled');+ expect(upload).not.toHaveBeenCalled();+ expect(deps.ensureOwnerReady).not.toHaveBeenCalled();+ });++ it.each([false, true])('uploads only confirmed immutable bytes and cleans snapshots after success/failure (%s)', async (fail) => {+ const { request, deps, file } = await setup();+ let snapshotPath = '';+ const confirm = vi.fn(async () => true);+ const operation = withOutboundReviewConfirmation(confirm, () => withPreparedOutboundReview(request, async (prepared) => {+ snapshotPath = prepared.attachments[0].path!;+ expect(snapshotPath).not.toBe(file);+ await fs.writeFile(file, 'changed after snapshot');+ expect(await fs.readFile(snapshotPath, 'utf8')).toBe('approved bytes');+ expect(prepared.focus).toBe('/host/only.md');+ expect(prepared.attachments[0].url).toBeUndefined();+ if (fail) throw new Error('upload failed');+ return 'uploaded';+ }, deps));+ if (fail) await expect(operation).rejects.toThrow('upload failed');+ else await expect(operation).resolves.toBe('uploaded');+ expect(confirm).toHaveBeenCalledWith([{ kind: 'external-path', label: 'external.md', path: await fs.realpath(file) }]);+ await expect(fs.stat(snapshotPath)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(request.attachments[0].path).toBe(file);+ });++ it('rejects a file replaced while confirmation is open before uploading', async () => {+ const { request, deps, file } = await setup();+ const upload = vi.fn();+ await expect(withOutboundReviewConfirmation(async () => {+ await fs.writeFile(file, 'different file content after confirmation');+ return true;+ }, () => withPreparedOutboundReview(request, upload, deps))).rejects.toThrow('changed after permission');+ expect(upload).not.toHaveBeenCalled();+ });++ it('retains the no-extra-confirmation rule for controller-managed artifacts', async () => {+ const { request, deps } = await setup(true);+ const confirm = vi.fn(async () => false);+ const upload = vi.fn(async () => 'uploaded');+ await expect(withOutboundReviewConfirmation(confirm, () => withPreparedOutboundReview(request, upload, deps))).resolves.toBe('uploaded');+ expect(confirm).not.toHaveBeenCalled();+ });++ it('requires confirmation for inline bytes and never uploads an unapproved alternate path', async () => {+ const { deps } = await setup();+ const request = { sourceSessionId: 'remote-source', attachments: [{ name: 'inline.txt', base64: 'YQ==', path: 'clipboard://item' }] };+ const upload = vi.fn(async (prepared) => prepared);+ await expect(withPreparedOutboundReview(request, upload, deps)).rejects.toThrow('cancelled');+ const prepared = await withOutboundReviewConfirmation(async () => true, () => withPreparedOutboundReview(request, upload, deps));+ expect(prepared.attachments[0]).toEqual({ name: 'inline.txt', base64: 'YQ==', path: undefined, url: undefined });+ });++ it('does not resolve already uploaded peer references as controller paths', async () => {+ const { deps } = await setup();+ const ref = buildPeerAttachmentRef({ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 1, sha256: 'a'.repeat(64) });+ deps.resolvePath = vi.fn();+ const request = { sourceSessionId: 'remote-source', attachments: [{ name: 'a', url: ref }] };+ await withPreparedOutboundReview(request, async (prepared) => expect(prepared).toBe(request), deps);+ expect(deps.resolvePath).not.toHaveBeenCalled();+ });++ it('does not suppress sensitive-path rejections from the existing Review resolver', async () => {+ const { request, deps } = await setup();+ deps.resolvePath = async () => { throw new Error('Review refused a credential or key path'); };+ const confirm = vi.fn(async () => true);+ const upload = vi.fn();+ await expect(withOutboundReviewConfirmation(confirm, () => withPreparedOutboundReview(request, upload, deps))).rejects.toThrow('credential or key path');+ expect(confirm).not.toHaveBeenCalled();+ expect(upload).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewRemoteInput.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewRemoteInput.test.tsnew file mode 100644index 0000000000..fcea484933--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewRemoteInput.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest';+import { buildPeerAttachmentRef } from '@cindy/device-link';+import { prepareRemoteReviewAttachments } from '../reviewRemoteInput';++describe('remote Review attachment preparation', () => {+ const ref = buildPeerAttachmentRef({ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 10, sha256: 'a'.repeat(64), mimeType: 'text/plain' });+ const request = { sourceSessionId: 'source', attachments: [{ name: 'notes.md', url: ref, path: ref }] };++ it('releases transport staging on acceptance but retains host files until terminal cleanup', async () => {+ const cleanupAfterAcceptance = vi.fn();+ const cleanupLocalMaterialization = vi.fn().mockResolvedValue(undefined);+ const files = [{ name: 'notes.md', url: 'xdt-image://reviewer/notes.md' }];+ const materialize = vi.fn().mockResolvedValue({ item: { files }, cleanupAfterAcceptance, cleanupLocalMaterialization });+ const prepared = await prepareRemoteReviewAttachments(request, 'reviewer', materialize);+ expect(materialize).toHaveBeenCalledWith('reviewer', { files: request.attachments });+ expect(prepared.attachments).toEqual(files);+ expect(cleanupAfterAcceptance).not.toHaveBeenCalled();+ expect(cleanupLocalMaterialization).not.toHaveBeenCalled();+ prepared.onAccepted();+ prepared.onAccepted();+ expect(cleanupAfterAcceptance).toHaveBeenCalledOnce();+ expect(cleanupLocalMaterialization).not.toHaveBeenCalled();+ await prepared.cleanup();+ await prepared.cleanup();+ expect(cleanupAfterAcceptance).toHaveBeenCalledOnce();+ expect(cleanupLocalMaterialization).toHaveBeenCalledOnce();+ });++ it('keeps unaccepted uploads retryable and releases only their local materializations', async () => {+ const cleanupAfterAcceptance = vi.fn();+ const cleanupBeforeAcceptance = vi.fn(async () => {});+ const cleanupLocalMaterialization = vi.fn(async () => {});+ const materialize = vi.fn().mockResolvedValue({+ item: { files: [{ name: 'notes.md', url: 'xdt-image://reviewer/notes.md' }] },+ cleanupAfterAcceptance, cleanupBeforeAcceptance, cleanupLocalMaterialization,+ });+ const prepared = await prepareRemoteReviewAttachments(request, 'reviewer', materialize);+ await prepared.cleanup();+ await prepared.cleanup();+ expect(cleanupBeforeAcceptance).toHaveBeenCalledOnce();+ expect(cleanupAfterAcceptance).not.toHaveBeenCalled();+ expect(cleanupLocalMaterialization).not.toHaveBeenCalled();+ });++ it.each(['/controller/notes.md', 'cindy-media://blobs/local.png', 'https://example.com/file'])('does not interpret controller input %s as a host file', async (url) => {+ const materialize = vi.fn();+ await expect(prepareRemoteReviewAttachments({ ...request, attachments: [{ name: 'notes.md', url }] }, 'reviewer', materialize)).rejects.toThrow('INVALID_PARAMS');+ expect(materialize).not.toHaveBeenCalled();+ });++ it('fails and releases local materializations if the transfer leaves unresolved references', async () => {+ const cleanupLocalMaterialization = vi.fn().mockResolvedValue(undefined);+ const cleanupAfterAcceptance = vi.fn();+ const materialize = vi.fn().mockResolvedValue({ item: { files: request.attachments }, cleanupLocalMaterialization, cleanupAfterAcceptance });+ await expect(prepareRemoteReviewAttachments(request, 'reviewer', materialize)).rejects.toThrow('DEVICE_LINK_MEDIA_TRANSFER_FAILED');+ expect(cleanupLocalMaterialization).toHaveBeenCalledOnce();+ expect(cleanupAfterAcceptance).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.tsindex 905dbbbba3..5b1a1d1993 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts@@ -1,5 +1,7 @@import type { AgentEvent, SessionSendOptions, UserMessage } from '@cindy/maker-core';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { assertRemoteBotInvocationAllowed, setRemoteBotSessionLookup } from '../../device-link/remoteBotSessionBoundary.js';+import { isBotVisibleRemotely } from '../../localDb/ipc/botRemoteVisibility.js';import { MAKER_INVOKE } from '../channels.js';import {@@ -13,6 +15,8 @@ import {type ReviewStartHandlerDeps,} from '../reviewStartHandler.js';import { IpcHarness } from './helpers/ipcHarness.js';+import { buildAttachmentOssRef } from '@cindy/device-link';+import { prepareRemoteReviewAttachments } from '../reviewRemoteInput.js';class FakeReviewer implements ReviewRunnerHandle {private listener: ((event: AgentEvent) => void) | null = null;@@ -20,6 +24,7 @@ class FakeReviewer implements ReviewRunnerHandle {null;accepted = true;readonly send = vi.fn(async (_message: UserMessage, options: SessionSendOptions) => {+ await options.beforeProviderStart?.();await options.onAccepted?.();return this.accepted? ({ accepted: true } as const)@@ -88,6 +93,7 @@ function makeDeps(const launch = makeLaunch();return {assertCaller: vi.fn(),+ captureSourceAccessGuard: vi.fn(() => async () => {}),waitUntilReady: vi.fn(async () => undefined),createRunId: vi.fn(() => `run-${++id}`),createReviewerSessionId: vi.fn(() => `reviewer-${id}`),@@ -116,6 +122,135 @@ function reviewRequest(sourceSessionId = 'source-1') {}describe('maker:review:start IPC lifecycle', () => {+ afterEach(() => setRemoteBotSessionLookup(null));++ it('releases uploaded staging after prompt acceptance while retaining local files throughout Review', async () => {+ const harness = new IpcHarness();+ const reviewer = new FakeReviewer();+ const cleanupAfterAcceptance = vi.fn();+ const cleanupLocalMaterialization = vi.fn(async () => {});+ const remote = await prepareRemoteReviewAttachments({+ sourceSessionId: 'source-1',+ attachments: [{ name: 'notes.md', url: buildAttachmentOssRef({ ossKey: 'cindy/device-link/fake/notes.md', size: 10, sha256: 'a'.repeat(64) }) }],+ }, 'reviewer-1', vi.fn().mockResolvedValue({+ item: { files: [{ name: 'notes.md', url: 'xdt-image://reviewer-1/notes.md' }] },+ cleanupAfterAcceptance, cleanupLocalMaterialization,+ }));+ let finishPersistence!: () => void;+ const persistence = new Promise<void>((resolve) => { finishPersistence = resolve; });+ const deps = makeDeps(reviewer, {+ prepareRun: vi.fn(async () => makePreparedRun(makeLaunch(), {+ onAccepted: remote.onAccepted, cleanup: remote.cleanup,+ })),+ persistReviewerPrompt: vi.fn(() => persistence),+ });+ registerReviewStartHandler(harness, deps);+ const result = harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest());+ await vi.waitFor(() => expect(deps.persistReviewerPrompt).toHaveBeenCalledOnce());+ expect(cleanupAfterAcceptance).not.toHaveBeenCalled();+ finishPersistence();+ await expect(result).resolves.toMatchObject({ ok: true });+ expect(cleanupAfterAcceptance).toHaveBeenCalledOnce();+ expect(cleanupLocalMaterialization).not.toHaveBeenCalled();+ reviewer.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(deps.releaseSourceLease).toHaveBeenCalledOnce());+ expect(cleanupLocalMaterialization).toHaveBeenCalledOnce();+ expect(cleanupAfterAcceptance).toHaveBeenCalledOnce();+ });++ it('does not release retryable staging if prompt acceptance fails', async () => {+ const harness = new IpcHarness();+ const reviewer = new FakeReviewer();+ const onAccepted = vi.fn();+ const cleanup = vi.fn(async () => {});+ const deps = makeDeps(reviewer, {+ prepareRun: vi.fn(async () => makePreparedRun(makeLaunch(), { onAccepted, cleanup })),+ persistReviewerPrompt: vi.fn(async () => { throw new Error('persist failed'); }),+ });+ registerReviewStartHandler(harness, deps);+ await expect(harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest())).rejects.toThrow('persist failed');+ expect(onAccepted).not.toHaveBeenCalled();+ expect(cleanup).toHaveBeenCalledOnce();+ expect(deps.releaseSourceLease).toHaveBeenCalledOnce();+ });++ it.each(['hidden', 'archived'] as const)('rejects a companion made %s while collecting evidence and permits a later visible retry', async (change) => {+ const harness = new IpcHarness();+ const reviewer = new FakeReviewer();+ const profile = { hiddenAt: null as number | null, status: 'active' };+ setRemoteBotSessionLookup(async () => isBotVisibleRemotely(profile) ? 'visible' : 'hidden');+ const cleanup = vi.fn(async () => {});+ const prepared = makePreparedRun(makeLaunch(), { cleanup });+ let finishPreparation!: (value: PreparedReviewRun) => void;+ const preparation = new Promise<PreparedReviewRun>((resolve) => { finishPreparation = resolve; });+ const deps = makeDeps(reviewer, {+ captureSourceAccessGuard: (sourceSessionId) => () => assertRemoteBotInvocationAllowed([{ sourceSessionId }], MAKER_INVOKE.START_REVIEW),+ prepareRun: vi.fn(() => preparation),+ });+ registerReviewStartHandler(harness, deps);+ await assertRemoteBotInvocationAllowed([reviewRequest()], MAKER_INVOKE.START_REVIEW);+ const result = harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest());+ const rejected = expect(result).rejects.toThrow('[NOT_FOUND]');+ await vi.waitFor(() => expect(deps.prepareRun).toHaveBeenCalledOnce());+ if (change === 'hidden') profile.hiddenAt = 123;+ else profile.status = 'archived';+ finishPreparation(prepared);+ await rejected;+ expect(deps.startReviewer).not.toHaveBeenCalled();+ expect(deps.createSourceCard).not.toHaveBeenCalled();+ expect(deps.broadcastReviewerCreated).not.toHaveBeenCalled();+ expect(deps.publishReviewerLink).not.toHaveBeenCalled();+ expect(deps.persistReviewerPrompt).not.toHaveBeenCalled();+ expect(reviewer.send).not.toHaveBeenCalled();+ expect(cleanup).toHaveBeenCalledOnce();+ profile.hiddenAt = null;+ profile.status = 'active';+ await expect(harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest())).resolves.toMatchObject({ ok: true });+ });++ it.each(['fingerprint', 'bootstrap', 'provider-start'] as const)('rechecks source visibility after asynchronous %s preparation', async (stage) => {+ const harness = new IpcHarness();+ const reviewer = new FakeReviewer();+ let visible = true;+ setRemoteBotSessionLookup(async () => visible ? 'visible' : 'hidden');+ const cleanup = vi.fn(async () => {});+ const launch = makeLaunch({+ verifyBeforeStart: vi.fn(async () => {+ if (stage === 'fingerprint') visible = false;+ return null;+ }),+ });+ const deps = makeDeps(reviewer, {+ captureSourceAccessGuard: (sourceSessionId) => () => assertRemoteBotInvocationAllowed([{ sourceSessionId }], MAKER_INVOKE.START_REVIEW),+ prepareRun: vi.fn(async () => makePreparedRun(launch, { cleanup })),+ startReviewer: vi.fn(async () => {+ if (stage === 'bootstrap') visible = false;+ return reviewer;+ }),+ });+ if (stage === 'provider-start') {+ reviewer.send.mockImplementationOnce(async (_message, options) => {+ visible = false;+ await options.beforeProviderStart?.();+ await options.onAccepted?.();+ return { accepted: true };+ });+ }+ registerReviewStartHandler(harness, deps);+ await expect(harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest())).rejects.toThrow('[NOT_FOUND]');+ if (stage === 'fingerprint') expect(deps.startReviewer).not.toHaveBeenCalled();+ if (stage !== 'provider-start') {+ expect(deps.broadcastReviewerCreated).not.toHaveBeenCalled();+ expect(deps.publishReviewerLink).not.toHaveBeenCalled();+ expect(reviewer.send).not.toHaveBeenCalled();+ }+ expect(deps.persistReviewerPrompt).not.toHaveBeenCalled();+ expect(deps.closeReviewer).toHaveBeenCalledOnce();+ expect(deps.releaseSourceLease).toHaveBeenCalledOnce();+ expect(cleanup).toHaveBeenCalledOnce();+ expect(deps.updateSourceCard).toHaveBeenCalledWith(expect.objectContaining({ meta: expect.objectContaining({ status: 'failed' }) }));+ });+it.each(Object.entries(REVIEW_START_REQUEST_LIMITS.attachmentMetadataChars) as Array<[keyof typeof REVIEW_START_REQUEST_LIMITS.attachmentMetadataChars, number]diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex bb168a52da..fe4f5cce4e 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -329,8 +329,9 @@ import {ReviewArtifactAuthorizationError,type ReviewArtifactConfirmationItem,} from '../reviewer/reviewArtifactAuthorization.js';-import { buildReviewArtifactConfirmationDialog } from '../reviewer/reviewArtifactDialog.js';-import { showReviewArtifactConfirmWindow } from '../reviewer/reviewArtifactConfirmWindow.js';+import { confirmReviewArtifacts } from '../reviewer/confirmReviewArtifacts.js';+import { configureOutboundReviewPreparation } from './reviewOutboundInput.js';+import { assertRemoteBotInvocationAllowed } from '../device-link/remoteBotSessionBoundary.js';import {cleanupOrphanedReviewArtifactSnapshots,prepareStableReviewArtifactSnapshots,@@ -789,6 +790,7 @@ import {materializeQueuedOssAttachmentsDeferred,} from './normalizeAttachments.js';import { QueuedAttachmentOwnershipRegistry } from './queuedAttachmentOwnership.js';+import { prepareRemoteReviewAttachments } from './reviewRemoteInput.js';import { AGENT_ISLAND_DISPLAY_CONFIG } from '../agent-island/displayConfig.js';import {shouldClearAgentIslandSessionForOrcaWorker,@@ -3505,6 +3507,11 @@ const ensureReviewOwnerLivenessReady = createRetryableReviewInitialization(asyncawait sessionTurnLeaseTracker.refreshActiveLeaseOwners();});configureTempAttachmentOwner(reviewRunOwner, ensureReviewOwnerLivenessReady);+configureOutboundReviewPreparation({+ owner: reviewRunOwner,+ ensureOwnerReady: ensureReviewOwnerLivenessReady,+ resolvePath: resolveReviewArtifactPath,+});const silentStopTurnLeaseGate = new SilentStopTurnLeaseGate();function providerTurnLeaseId(sessionInstanceId: string, turnGeneration: number): string {return `${sessionInstanceId}:${turnGeneration}`;@@ -5068,11 +5075,10 @@ async function confirmReviewExternalArtifacts(event: IpcMainInvokeEvent,items: ReviewArtifactConfirmationItem[],): Promise<boolean> {- const parent = BrowserWindow.fromWebContents(event.sender);- if (!parent || parent.isDestroyed()) return false;- return showReviewArtifactConfirmWindow(parent, buildReviewArtifactConfirmationDialog(items, t), {- log,- });+ // Remote invokes have no Renderer sender. Until this confirmation has a+ // remote UI, retain the explicit-grant requirement rather than auto-approve.+ if (isDeviceLinkInvoke()) return false;+ return confirmReviewArtifacts(event, items);}export interface RegisterMakerIpcOptions {@@ -8055,8 +8061,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};const reviewRunControl = registerReviewStartHandler(makerSessionRegistry, {- assertCaller: (event) =>- assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),+ captureSourceAccessGuard: (sourceSessionId) => {+ // Capture trusted origin while still in the invoke context, including for+ // a later provider-start callback that may run outside that await chain.+ const remote = isDeviceLinkInvoke();+ return async () => {+ if (remote) {+ await assertRemoteBotInvocationAllowed([{ sourceSessionId }], MAKER_INVOKE.START_REVIEW);+ }+ };+ },+ assertCaller: (event) => {+ // A device-link invoke is already authenticated by the relay, controller+ // lease and remote invoke allowlist. Its synthetic IPC event has no real+ // BrowserWindow sender, so only local Renderer calls use the sender guard.+ if (!isDeviceLinkInvoke()) {+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);+ }+ },waitUntilReady: async (sourceSessionId) => {await ensureReviewRuntimeReady();// Recover only this task when the user explicitly starts Review again.@@ -8118,7 +8140,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)let sourceArtifactFingerprint = '';let authorizedArtifactPaths: string[] = [];let cleanupPreparedArtifacts: (() => Promise<void>) | null = null;+ let cleanupRemoteAttachments: (() => Promise<void>) | null = null;+ let acceptRemoteAttachments: (() => void) | null = null;try {+ if (isDeviceLinkInvoke() && request.attachments.length) {+ const remote = await prepareRemoteReviewAttachments(+ request, reviewerSessionId, materializeQueuedOssAttachmentsDeferred,+ );+ request.attachments = remote.attachments;+ acceptRemoteAttachments = remote.onAccepted;+ cleanupRemoteAttachments = remote.cleanup;+ cleanupPreparedArtifacts = remote.cleanup;+ }const historicalAttachments = await listReviewHistoricalAttachments(source.id);const explicitArtifactGrant = await authorizeReviewExplicitArtifacts({workingDir: sourceWorkingDir,@@ -8141,7 +8174,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)explicitArtifactGrant: snapshotGrant,}),});- cleanupPreparedArtifacts = prepared.cleanup;+ cleanupPreparedArtifacts = async () => {+ try {+ await prepared.cleanup();+ } finally {+ await cleanupRemoteAttachments?.();+ }+ };evidence = prepared.value;sourceArtifactFingerprint = prepared.fingerprint;} catch (error) {@@ -8201,6 +8240,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sourceAgentKind: source.agentKind as 'cc' | 'codex' | 'pi',prompt: builtPrompt.prompt,targetKind: builtPrompt.targetKind,+ onAccepted: () => acceptRemoteAttachments?.(),cleanup: async () => {await cleanupPreparedArtifacts?.();},diff --git a/apps/desktop/src/main/maker-ipc/reviewOutboundInput.ts b/apps/desktop/src/main/maker-ipc/reviewOutboundInput.tsnew file mode 100644index 0000000000..6d2bba20d8--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/reviewOutboundInput.ts@@ -0,0 +1,90 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import path from 'node:path';+import { parseAttachmentOssRef, parsePeerAttachmentRef } from '@cindy/device-link';+import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';+import { throwIpcError } from '../utils/ipcValidate.js';+import {+ assertReviewExplicitPathGranted,+ assertReviewInlineAttachmentGranted,+ authorizeReviewExplicitArtifacts,+ ReviewArtifactAuthorizationError,+ type ReviewArtifactConfirmationItem,+} from '../reviewer/reviewArtifactAuthorization.js';+import { materializeReviewArtifactSnapshots } from '../reviewer/reviewArtifactSnapshot.js';+import type { ReviewRunOwner } from '../../shared/reviewRun.js';+import type { StartReviewRequest } from './reviewStartHandler.js';++type Confirm = (items: ReviewArtifactConfirmationItem[]) => Promise<boolean>;+interface PreparationDeps {+ owner: ReviewRunOwner;+ ensureOwnerReady(): Promise<void>;+ resolvePath: Parameters<typeof authorizeReviewExplicitArtifacts>[0]['resolvePath'];+}+let preparationDeps: PreparationDeps | undefined;+const confirmationContext = new AsyncLocalStorage<Confirm>();++export function configureOutboundReviewPreparation(deps: PreparationDeps): void {+ preparationDeps = deps;+}++/** The callback comes only from the trusted local IPC event, never the payload. */+export function withOutboundReviewConfirmation<T>(confirm: Confirm, operation: () => Promise<T>): Promise<T> {+ return confirmationContext.run(confirm, operation);+}++/** Grant and snapshot controller files before uploads erase their original provenance. */+export async function withPreparedOutboundReview<T>(+ request: StartReviewRequest,+ upload: (request: StartReviewRequest) => Promise<T>,+ deps = preparationDeps,+): Promise<T> {+ if (!request.attachments.length) return upload(request);+ // Reject the whole batch before staging can erase filenames or path provenance.+ // Cached/inline bytes may have a harmless storage path but a sensitive label.+ for (const file of request.attachments) {+ const refs = [file.url, file.path].filter((ref): ref is string => Boolean(ref));+ const names = refs.map((ref) => (parseAttachmentOssRef(ref) ?? parsePeerAttachmentRef(ref))?.originalName);+ if ([file.name, file.originalName, ...refs, ...names].some(+ (candidate) => candidate && isReviewSensitiveCredentialPath(candidate),+ )) {+ throwIpcError('PERMISSION_DENIED', 'Review refused a credential or key attachment');+ }+ }+ if (!deps) throwIpcError('PERMISSION_DENIED', 'Review attachment authorization is unavailable');+ const local = request.attachments.filter((file) => {+ const ref = file.url || file.path || '';+ return Boolean(file.base64) || !(parseAttachmentOssRef(ref) || parsePeerAttachmentRef(ref));+ });+ if (!local.length) return upload(request);+ // A remote workspace never grants access to similarly named controller paths.+ const resolvePath: PreparationDeps['resolvePath'] = async (raw, workingDir) => {+ if (!path.isAbsolute(raw) && !raw.startsWith('xdt-image://') && !raw.startsWith('cindy-media://')) return null;+ return deps.resolvePath(raw, workingDir);+ };+ const grant = await authorizeReviewExplicitArtifacts({+ workingDir: null, attachments: local, resolvePath,+ confirm: confirmationContext.getStore() ?? (async () => false),+ });+ await deps.ensureOwnerReady();+ const snapshot = await materializeReviewArtifactSnapshots({ workingDir: null, grant, owner: deps.owner });+ try {+ const attachments = await Promise.all(request.attachments.map(async (file) => {+ if (!local.includes(file)) return file;+ for (const raw of [file.url, file.path]) {+ if (!raw) continue;+ const resolved = await resolvePath(raw, '');+ if (resolved) {+ return { ...file, url: undefined, base64: undefined, path: assertReviewExplicitPathGranted(resolved.absPath, snapshot.grant) };+ }+ }+ if (file.base64) {+ assertReviewInlineAttachmentGranted(file, snapshot.grant);+ return { ...file, path: undefined, url: undefined };+ }+ throw new ReviewArtifactAuthorizationError('Review attachment has no authorized source');+ }));+ return await upload({ ...request, attachments });+ } finally {+ await snapshot.cleanup();+ }+}diff --git a/apps/desktop/src/main/maker-ipc/reviewRemoteInput.ts b/apps/desktop/src/main/maker-ipc/reviewRemoteInput.tsnew file mode 100644index 0000000000..a8835fa471--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/reviewRemoteInput.ts@@ -0,0 +1,49 @@+import { isAttachmentOssRef, isPeerAttachmentRef, parseAttachmentOssRef, parsePeerAttachmentRef } from '@cindy/device-link';+import { throwIpcError } from '../utils/ipcValidate.js';+import { readStartReviewRequest, type StartReviewRequest } from './reviewStartHandler.js';+import type { materializeQueuedOssAttachmentsDeferred } from './normalizeAttachments.js';++/** Translate controller uploads before Review authorizes and snapshots host files. */+export async function prepareRemoteReviewAttachments(+ request: StartReviewRequest,+ reviewerSessionId: string,+ materialize: typeof materializeQueuedOssAttachmentsDeferred,+): Promise<{ attachments: StartReviewRequest['attachments']; onAccepted(): void; cleanup(): Promise<void> }> {+ // Controller-local paths must never be resolved against the host filesystem.+ for (const attachment of request.attachments) {+ const ref = attachment.url || attachment.path;+ const parsed = ref && (isPeerAttachmentRef(ref) ? parsePeerAttachmentRef(ref) : parseAttachmentOssRef(ref));+ if (!parsed || parsed.size === undefined) {+ throwIpcError('INVALID_PARAMS', 'Remote review attachments must be uploaded before review');+ }+ }+ const prepared = await materialize(reviewerSessionId, { files: request.attachments });+ let accepted = false;+ const onAccepted = () => {+ if (accepted) return;+ accepted = true;+ prepared.cleanupAfterAcceptance?.();+ };+ let cleanupPromise: Promise<void> | undefined;+ // Acceptance releases only transport staging. Review still reads and checks+ // the host materialization until its terminal cleanup. Rejections retain+ // the upload for retry, as required by the shared materializer contract.+ const cleanup = () => cleanupPromise ??= (async () => {+ if (!accepted && prepared.cleanupBeforeAcceptance) {+ await prepared.cleanupBeforeAcceptance();+ } else {+ await prepared.cleanupLocalMaterialization?.();+ }+ })();+ try {+ const files = (prepared.item as { files: unknown }).files;+ const { attachments } = readStartReviewRequest({ ...request, attachments: files });+ if (attachments.some((file) => isAttachmentOssRef(file.url || file.path) || isPeerAttachmentRef(file.url || file.path))) {+ throwIpcError('DEVICE_LINK_MEDIA_TRANSFER_FAILED', 'Review attachment was not downloaded');+ }+ return { attachments, onAccepted, cleanup };+ } catch (error) {+ await cleanup();+ throw error;+ }+}diff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.tsindex 49c84e8b99..9b63fad98f 100644--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts@@ -153,6 +153,8 @@ export interface PreparedReviewRun {prompt: string;targetKind: ReviewTargetKind;prepareLaunch(): Promise<PreparedReviewLaunch>;+ /** Release transport staging once the Review prompt is durably accepted. */+ onAccepted?(): void;cleanup?(): Promise<void>;}@@ -172,6 +174,8 @@ export interface ReviewCardWrite {export interface ReviewStartHandlerDeps {assertCaller(event: unknown): void;+ /** Capture trusted invocation origin now; refresh source visibility at each launch boundary. */+ captureSourceAccessGuard(sourceSessionId: string): () => Promise<void>;waitUntilReady(sourceSessionId: string): Promise<void>;createRunId(): string;createReviewerSessionId(): string;@@ -266,6 +270,7 @@ export function registerReviewStartHandler(registry.handle(MAKER_INVOKE.START_REVIEW, async (event, raw: unknown) => {deps.assertCaller(event);const request = readStartReviewRequest(raw);+ const assertSourceAccess = deps.captureSourceAccessGuard(request.sourceSessionId);await deps.waitUntilReady(request.sourceSessionId);if (activeReviewsBySource.has(request.sourceSessionId)) {throwIpcError('SESSION_RUNNING', 'This task already has a review in progress');@@ -468,6 +473,7 @@ export function registerReviewStartHandler(try {const prepared = await deps.prepareRun({ event, request, runId, reviewerSessionId });preparedRunCleanup = prepared.cleanup?.bind(prepared) ?? null;+ await assertSourceAccess();const preparedSourceAgentKind = prepared.sourceAgentKind;sourceAgentKind = preparedSourceAgentKind;const startedAt = deps.now();@@ -503,6 +509,8 @@ export function registerReviewStartHandler(const launch = await prepared.prepareLaunch();const startFailure = await launch.verifyBeforeStart();if (startFailure) throw new ReviewPreconditionError(startFailure);+ // Evidence/fingerprint preparation can outlive the source's remote visibility.+ await assertSourceAccess();const reviewer = await deps.startReviewer(launch.reviewerCreateOpts);const linkedRunningMeta: ReviewRunMeta = { ...runningMeta, reviewerSessionId };runningMeta = linkedRunningMeta;@@ -594,6 +602,7 @@ export function registerReviewStartHandler(// created broadcast and listener registration, leaving the source gate// permanently occupied.await deps.markReviewerStarted(reviewerSessionId, startedAt);+ await assertSourceAccess();if (settled) {await terminalFinalization;throwIpcError('PRECONDITION_FAILED', 'Reviewer task closed before it started');@@ -619,6 +628,7 @@ export function registerReviewStartHandler(const sendResult = await reviewer.send(launch.message, {planMode: false,+ beforeProviderStart: assertSourceAccess,onAccepted: async () => {await deps.persistReviewerPrompt({reviewerSessionId,@@ -626,6 +636,7 @@ export function registerReviewStartHandler(prompt: prepared.prompt,sourceAgentKind: preparedSourceAgentKind,});+ prepared.onAccepted?.();},});if (!sendResult.accepted) {diff --git a/apps/desktop/src/main/reviewer/__tests__/confirmReviewArtifacts.test.ts b/apps/desktop/src/main/reviewer/__tests__/confirmReviewArtifacts.test.tsnew file mode 100644index 0000000000..7e4ea177e3--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/confirmReviewArtifacts.test.ts@@ -0,0 +1,44 @@+import type { IpcMainInvokeEvent } from 'electron';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ trust: vi.fn(), parent: vi.fn(), show: vi.fn() }));+vi.mock('electron', () => ({ BrowserWindow: { fromWebContents: mocks.parent } }));+vi.mock('../../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent: mocks.trust }));+vi.mock('../../i18n', () => ({ t: (key: string) => key }));+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../reviewArtifactConfirmWindow', () => ({ showReviewArtifactConfirmWindow: mocks.show }));++import { confirmReviewArtifacts } from '../confirmReviewArtifacts';++beforeEach(() => {+ vi.resetAllMocks();+ mocks.parent.mockReturnValue({ isDestroyed: () => false });+ mocks.show.mockResolvedValue(true);+});++describe('Review native confirmation sender boundary', () => {+ const event = { sender: { id: 42 } } as IpcMainInvokeEvent;+ const items = [{ kind: 'external-path' as const, label: 'external.md' }];++ it('uses the requesting app window and awaits its native decision', async () => {+ await expect(confirmReviewArtifacts(event, items)).resolves.toBe(true);+ expect(mocks.trust).toHaveBeenCalledWith(event);+ expect(mocks.parent).toHaveBeenCalledWith(event.sender);+ expect(mocks.show).toHaveBeenCalledOnce();+ mocks.show.mockResolvedValue(false);+ await expect(confirmReviewArtifacts(event, items)).resolves.toBe(false);+ });++ it('rejects an untrusted sender before opening any window', async () => {+ mocks.trust.mockImplementation(() => { throw new Error('untrusted'); });+ await expect(confirmReviewArtifacts(event, items)).rejects.toThrow('untrusted');+ expect(mocks.parent).not.toHaveBeenCalled();+ expect(mocks.show).not.toHaveBeenCalled();+ });++ it.each([null, { isDestroyed: () => true }])('denies when the sender has no live app window', async (parent) => {+ mocks.parent.mockReturnValue(parent);+ await expect(confirmReviewArtifacts(event, items)).resolves.toBe(false);+ expect(mocks.show).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/reviewer/confirmReviewArtifacts.ts b/apps/desktop/src/main/reviewer/confirmReviewArtifacts.tsnew file mode 100644index 0000000000..9a075e2e61--- /dev/null+++ b/apps/desktop/src/main/reviewer/confirmReviewArtifacts.ts@@ -0,0 +1,19 @@+import { BrowserWindow, type IpcMainInvokeEvent } from 'electron';+import { t } from '../i18n.js';+import { createLogger } from '../logger.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import type { ReviewArtifactConfirmationItem } from './reviewArtifactAuthorization.js';+import { buildReviewArtifactConfirmationDialog } from './reviewArtifactDialog.js';+import { showReviewArtifactConfirmWindow } from './reviewArtifactConfirmWindow.js';++const log = createLogger('review:artifact-confirmation');++export async function confirmReviewArtifacts(+ event: IpcMainInvokeEvent,+ items: ReviewArtifactConfirmationItem[],+): Promise<boolean> {+ assertTrustedAppRendererEvent(event);+ const parent = BrowserWindow.fromWebContents(event.sender);+ if (!parent || parent.isDestroyed()) return false;+ return showReviewArtifactConfirmWindow(parent, buildReviewArtifactConfirmationDialog(items, t), { log });+}diff --git a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.tsindex 419d64a75d..0477dbc49c 100644--- a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts+++ b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts@@ -134,20 +134,20 @@ export async function reviewArtifactFileLinkLayoutIsSafe(* renderer-only inline bytes require an explicit native confirmation.*/export async function authorizeReviewExplicitArtifacts(input: {- workingDir: string;+ workingDir: string | null;focus?: string;attachments: ReviewArtifactAuthorizationAttachment[];resolvePath: (rawPath: string, workingDir: string) => Promise<ResolvedReviewArtifactPath | null>;confirm: (items: ReviewArtifactConfirmationItem[]) => Promise<boolean>;}): Promise<ReviewExplicitArtifactGrant> {- const canonicalWorkingDir = await fs.realpath(input.workingDir).catch(() => null);+ const canonicalWorkingDir = input.workingDir ? await fs.realpath(input.workingDir).catch(() => null) : null;const grantedPaths = new Set<string>();const pathIdentities = new Map<string, ReviewArtifactPathIdentity>();const confirmationItems: ReviewArtifactConfirmationItem[] = [];const confirmationKeys = new Set<string>();const addResolved = async (rawPath: string, label: string): Promise<boolean> => {- const resolved = await input.resolvePath(rawPath, input.workingDir);+ const resolved = await input.resolvePath(rawPath, input.workingDir ?? '');if (!resolved) return false;const stat = await fs.lstat(resolved.absPath).catch(() => null);if (!stat || stat.isSymbolicLink()) {diff --git a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.tsindex 15b8f99a53..d1c54cb3f5 100644--- a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts+++ b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts@@ -353,7 +353,7 @@ async function copyOpenFile(* approved path after consent cannot change the bytes sent to the model.*/export async function materializeReviewArtifactSnapshots(input: {- workingDir: string;+ workingDir: string | null;grant: ReviewExplicitArtifactGrant;owner: ReviewRunOwner;/** Test seam for deterministic lstat/open replacement coverage. */@@ -366,7 +366,7 @@ export async function materializeReviewArtifactSnapshots(input: {) {throw new Error('Review artifact snapshot owner is not ready');}- const canonicalWorkingDir = await fs.realpath(input.workingDir).catch(() => null);+ const canonicalWorkingDir = input.workingDir ? await fs.realpath(input.workingDir).catch(() => null) : null;const snapshotPaths = new Map<string, string>();const liveDirectoryPaths: string[] = [];let snapshotRoot: string | null = null;diff --git a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.tsindex 17ed2aa897..a88e1d7325 100644--- a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts+++ b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts@@ -18,13 +18,13 @@ describe('/review command dispatch', () => {it('crosses the Main boundary with this invocation attachment snapshot before returning', () => {expect(dispatchSource).toContain("if (hit.name === 'review')");expect(dispatchSource).toContain('serializeAttachedFiles(files)');- expect(dispatchSource).toContain('.startReview({');- expect(dispatchSource).toContain('await window.electronAPI.maker.startReview({');+ expect(dispatchSource).toContain('await startReviewOnDevice(request, rightSidebarDeviceLinkDeviceId)');+ expect(dispatchSource).not.toContain('if (remoteDeviceId || session?.remoteHostId)');expect(dispatchSource).toContain('return { handled: true, accepted: true, message }');expect(dispatchSource).toContain('return { handled: true, accepted: false, message }');expect(sessionViewSource).toContain('if (slashDispatch.handled) {');expect(sessionViewSource).toContain('waitForLeadHistory: false');- expect(dispatchSource.indexOf('.startReview({')).toBeLessThan(+ expect(dispatchSource.indexOf('await startReviewOnDevice(')).toBeLessThan(dispatchSource.indexOf('void dispatchCommand(hit'),);});diff --git a/apps/desktop/src/renderer/__tests__/startReviewOnDevice.test.ts b/apps/desktop/src/renderer/__tests__/startReviewOnDevice.test.tsnew file mode 100644index 0000000000..19cbec44fb--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/startReviewOnDevice.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { startReviewOnDevice } from '../lib/startReviewOnDevice';++afterEach(() => vi.unstubAllGlobals());++describe('Review execution device', () => {+ const request = { sourceSessionId: 'source-task', focus: 'changes' };++ function setup() {+ const invoke = vi.fn().mockResolvedValue({ reviewerSessionId: 'reviewer' });+ const startReview = vi.fn().mockResolvedValue({ reviewerSessionId: 'local-reviewer' });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke }, maker: { startReview } } });+ return { invoke, startReview };+ }++ it('creates local Reviews through the local Main handler', async () => {+ const { invoke, startReview } = setup();+ await startReviewOnDevice(request, null);+ expect(startReview).toHaveBeenCalledWith(request);+ expect(invoke).not.toHaveBeenCalled();+ });++ it('passes the source and attachments only to the controlled device', async () => {+ const { invoke, startReview } = setup();+ const remoteRequest = { ...request, attachments: [{+ id: 'notes', name: 'notes.md', path: 'notes.md', ext: '.md', size: 10,+ category: 'text' as const, mimeType: 'text/markdown',+ }] };+ await startReviewOnDevice(remoteRequest, 'controlled-device');+ expect(invoke).toHaveBeenCalledWith('controlled-device', 'maker:review:start', [remoteRequest]);+ expect(startReview).not.toHaveBeenCalled();+ });++ it.each([undefined, ''])('does not dispatch before task ownership resolves (%s)', async (deviceId) => {+ const { invoke, startReview } = setup();+ await expect(startReviewOnDevice(request, deviceId)).rejects.toThrow('DEVICE_LINK_NOT_CONNECTED');+ expect(invoke).not.toHaveBeenCalled();+ expect(startReview).not.toHaveBeenCalled();+ });++ it.each(['CHANNEL_NOT_ALLOWED', 'DEVICE_LINK_NOT_CONNECTED', 'TIMEOUT'])(+ 'never falls back locally or retries on %s', async (code) => {+ const { invoke, startReview } = setup();+ invoke.mockRejectedValue(new Error(code));+ await expect(startReviewOnDevice(request, 'controlled-device')).rejects.toThrow(code);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(startReview).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 607244f80f..ca9de9cded 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -242,6 +242,7 @@ import {import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import type { AttachedFile, ComposerBotMention, MentionedResource } from '@/lib/fileTypes';import { serializeAttachedFiles } from '@/lib/messageAttachmentPayload';+import { startReviewOnDevice } from '@/lib/startReviewOnDevice';import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';import {isQueueComposerEditCurrent,@@ -3291,19 +3292,20 @@ export function CCAgentSessionView({// nor share a mutable attachment ref with a later command.if (hit.name === 'review') {if (!sessionId) return { handled: true, accepted: false, message };- if (remoteDeviceId || session?.remoteHostId) {- // 轮 35 HIGH-2:SSH 远端会话同样不支持 /review —— 与 device-link 并列- // 前置拦截, 避免命令进入 main 后被 UNSUPPORTED_CAPABILITY 拒绝。+ if (session?.remoteHostId) {+ // SSH workspaces still have no Review transport. Device-link tasks+ // use the controlled Desktop's local Review lifecycle below.toast.warning(t('review.toast.remoteUnsupported'));return { handled: true, accepted: false, message };}const attachments = files?.length ? serializeAttachedFiles(files) : undefined;try {- await window.electronAPI.maker.startReview({+ const request = {sourceSessionId: sessionId,...(args.trim() ? { focus: args.trim() } : {}),...(attachments?.length ? { attachments } : {}),- });+ };+ await startReviewOnDevice(request, rightSidebarDeviceLinkDeviceId);return { handled: true, accepted: true, message };} catch (err) {const ipcError = extractIpcError(err);@@ -3344,6 +3346,7 @@ export function CCAgentSessionView({session?.workingDir,sessionId,remoteDeviceId,+ rightSidebarDeviceLinkDeviceId,t,],);diff --git a/apps/desktop/src/renderer/lib/startReviewOnDevice.ts b/apps/desktop/src/renderer/lib/startReviewOnDevice.tsnew file mode 100644index 0000000000..f7b8d273a8--- /dev/null+++ b/apps/desktop/src/renderer/lib/startReviewOnDevice.ts@@ -0,0 +1,15 @@+/** Keep the Reviewer on the source task's device, including while reconnecting. */+export async function startReviewOnDevice(+ request: Parameters<Window['electronAPI']['maker']['startReview']>[0],+ deviceId: string | null | undefined,+): Promise<void> {+ // Only an explicitly resolved local owner may use local IPC.+ if (deviceId === undefined || deviceId === '') {+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] Review task ownership is unresolved');+ }+ if (deviceId !== null) {+ await window.electronAPI.deviceLink.invoke(deviceId, 'maker:review:start', [request]);+ } else {+ await window.electronAPI.maker.startReview(request);+ }+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex bae4de93d2..0ee8c28b7b 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -11,6 +11,23 @@> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。+## Desktop 设备互联 Review++桌面控制端的 /review 通过 maker:review:start 请求被控 Desktop 执行。证据收集、Reviewer+任务创建、只读生命周期和 Review 卡片持久化始终发生在被控端;结果沿现有 session、message+和 maker:event 推送回控制端,不新增独立结果协议。该 channel 仅加入+packages/device-link 的 invoke allowlist,仍受控制租约、会话可见性和被控端 Review 输入+保护约束;SSH remoteHostId 不因此获得 Review 能力。++旧被控端不认识该 channel 时返回 CHANNEL_NOT_ALLOWED,控制端沿用 Review 失败提示,+不得回退到控制端本机执行。Review Reviewer session 的后续输入仍被远程 Review 外部输入门禁拒绝。+控制端先整批校验 Review 请求,再复用现有上传/被控端物化链路。控制端外部文件与内联+内容在上传前通过原生确认,文件只上传已授权的只读快照;被控端的工作区不授予控制端同名+路径的读取权。禁止把控制端本机路径当作被控端文件。被控端自身仍需本机确认的工作区外+成果不自动放行;确认尚无远控入口时返回权限错误。归属未解析的任务不启动 Review,只有+明确归属本机才调用本机入口;已知远端归属在重连期间仍沿用远端。写请求不新增自动重试,+90 秒超时仅作用于该请求,超时不代表被控端未创建 Reviewer,应先查看任务里的 Review 卡片。+## SkillHub 发布失败原因发布错误继续使用 `{ error: { code, message } }`,Desktop 保留已知业务码与具体原因,diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex c6763fda45..8143d38836 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -27,6 +27,9 @@ import {} from '../remoteResources.js';describe('REMOTE_INVOKE_ALLOWLIST', () => {+ it('allows Review start to run on the data-owning Desktop', () => {+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:review:start')).toBe(true);+ });it('allows the reduced teammate directory while keeping native configuration local', () => {for (const channel of ['local-db:bots:list', 'local-db:bots:get']) {expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex e341ddb6a7..6f17cb83ad 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -162,6 +162,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = ['maker:list-active','maker:any-session-in-turn','maker:session-in-turn',+ // Review evidence and the Reviewer session are created on the data-owning+ // device. The handler remains host-owned; this only permits the explicit+ // start request to cross the device-link tunnel.+ 'maker:review:start',// —— 输入队列(input queue 全集,无本机副作用)——DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,'maker:input:get-projection',@@ -740,6 +744,9 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([* client-agnostic:mobile/web 控制端应使用同一映射(与 allowlist 同为协议契约)。*/export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {+ // Evidence collection may include git diff and bounded artifact reads before+ // the host can acknowledge the newly-created Reviewer session.+ 'maker:review:start': 90_000,// Two Git preflight/apply stages each allow 30s, plus snapshot and queue overhead.'maker:turn-change-set:apply': 90_000,[FILE_PEER_CHANNEL]: 30_000,