Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: address review — isolate reviewer input and owner leases
Chris5ab34d6055bf
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex 690664ea7f..46403fae15 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -29,6 +29,7 @@ vi.mock('../voice-input/index.js', () => ({import {markRemoteSettingPersistedInsideHandler,runInvoke,+ setRemoteReviewInputGuard,setRemoteWorkingDirGuard,setRemoteSettingsPersist,handleControllerOffline,@@ -49,6 +50,7 @@ beforeEach(() => {registry.reset();dispatchTesting.reset(); // 清订阅 registry / tap / onControllersChanged / activeClientsetRemoteWorkingDirGuard(null); // 默认不注入,行为同生产未就绪态(放行)+ setRemoteReviewInputGuard(null);setRemoteSettingsPersist(null);fetchLocalMediaToOssMock.mockReset();transcribeRemoteVoiceInputMock.mockReset();@@ -87,6 +89,43 @@ describe('runInvoke 双层校验', () => {expect(r).toEqual({ ok: true, result: ['session-x'] });});+ it('Review 外部输入在 device-link handler 前整族拒绝', async () => {+ const handler = vi.fn(() => ({ accepted: true }));+ const channels = [+ 'maker:send',+ 'maker:steer',+ 'maker:input:enqueue',+ 'maker:input:steer',+ 'maker:input:resume',+ 'maker:input:update-content',+ 'maker:input:clear-session',+ ];+ for (const channel of channels) registry.register(channel, handler);+ setRemoteReviewInputGuard((sessionId) => {+ if (sessionId === 'review-1') {+ throw new Error(+ '[UNSUPPORTED_CAPABILITY] Review tasks only accept the host-owned initial review prompt',+ );+ }+ });++ for (const channel of channels) {+ await expect(runInvoke('ctrl', { channel, args: ['review-1'] })).resolves.toMatchObject({+ ok: false,+ error: {+ code: 'IPC_ERROR',+ message: expect.stringContaining('[UNSUPPORTED_CAPABILITY]'),+ },+ });+ }+ expect(handler).not.toHaveBeenCalled();++ await expect(+ runInvoke('ctrl', { channel: 'maker:send', args: ['desktop-1', 'hello'] }),+ ).resolves.toEqual({ ok: true, result: { accepted: true } });+ expect(handler).toHaveBeenCalledTimes(1);+ });+it('远程 invoke 期间给本机 handler 暴露 device-link 上下文,结束后不泄漏', async () => {registry.register('maker:list-active', () => ({active: isDeviceLinkInvoke(),diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex a250b16eb2..0a46d7a677 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -25,6 +25,7 @@ import {MAX_FRAME_BYTES,PROTOCOL_VERSION,REMOTE_INVOKE_ALLOWLIST,+ REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS,topicForPush,DL_SUBSCRIBE_CHANNEL,DL_UNSUBSCRIBE_CHANNEL,@@ -214,6 +215,11 @@ type RemoteWorkingDirGuardValue = boolean | RemoteWorkingDirCheckResult;/** host 注入的 workingDir 校验器(null = 未注入,放行;布尔返回值仅作旧测试兼容) */let workingDirGuard: ((dir: string) => RemoteWorkingDirGuardValue | Promise<RemoteWorkingDirGuardValue>) | null = null;+type RemoteReviewInputGuard = (sessionId: string) => void | Promise<void>;++/** Main injects the DB-backed sessions.source authorization check once ready. */+let remoteReviewInputGuard: RemoteReviewInputGuard | null = null;+/** 注入远程 create-session/worktree:create 的本地目录校验器(register.ts 在 maker 就绪后接入)。 */export function setRemoteWorkingDirGuard(guard: ((dir: string) => RemoteWorkingDirGuardValue | Promise<RemoteWorkingDirGuardValue>) | null,@@ -221,6 +227,10 @@ export function setRemoteWorkingDirGuard(workingDirGuard = guard;}+export function setRemoteReviewInputGuard(guard: RemoteReviewInputGuard | null): void {+ remoteReviewInputGuard = guard;+}+/** 从 args[0] 里取待收敛的路径字段(见 PATH_GUARDED_CHANNELS);取不到返回 null。 */function extractGuardedPath(args: unknown[], field: 'workingDir' | 'baseRepo'): string | null {const o = args[0];@@ -2619,6 +2629,27 @@ export async function runInvoke(};}+ // Review sessions may be mirrored to controllers for visibility, but their+ // only input is the host's direct reviewer.send() call. Reject before the+ // synthetic ipcMain event is dispatched, then let the handler repeat the+ // same DB-backed check as defense in depth for local Renderer calls.+ if (REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS.has(payload.channel) && remoteReviewInputGuard) {+ const sessionId = payload.args?.[0];+ if (typeof sessionId === 'string') {+ try {+ await remoteReviewInputGuard(sessionId);+ } catch (error) {+ return {+ ok: false,+ error: {+ code: 'IPC_ERROR',+ message: error instanceof Error ? error.message : String(error),+ },+ };+ }+ }+ }+// device-link:media:fetch 不是 ipcMain handler(同 subscribe),在此拦截:解析本机媒体 →// 上传 OSS 中转 → 回 { ossKey, mimeType, size }。已过三道 gate,等同受信本地访问。if (payload.channel === DL_MEDIA_FETCH_CHANNEL) {@@ -2862,6 +2893,7 @@ export const __testing = {cancelAllLinkAcceptRetries();setBroadcastTapListener(null);presenceOfflineCheck = null;+ remoteReviewInputGuard = null;},getActiveControllers,getUpdateRelaunchControllers,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.tsindex c4a41779ca..5a2ed9c056 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts@@ -65,6 +65,26 @@ describe('maker session SEND IPC handler', () => {);});+ it('does not reach the send transaction when the Main input boundary rejects Review', async () => {+ const harness = new IpcHarness();+ const sendToAgentAccepted = vi.fn();+ const assertRemoteInputControlBoundary = vi+ .fn()+ .mockRejectedValue(+ Object.assign(new Error('Review input rejected'), { code: 'UNSUPPORTED_CAPABILITY' }),+ );++ registerMakerSessionSendHandler(harness, {+ sendToAgentAccepted,+ assertRemoteInputControlBoundary,+ });++ await expect(harness.invoke(MAKER_INVOKE.SEND, 'review-1', 'hello')).rejects.toMatchObject({+ code: 'UNSUPPORTED_CAPABILITY',+ });+ expect(sendToAgentAccepted).not.toHaveBeenCalled();+ });+it('keeps a validated clear token when the optional boundary hook is absent', async () => {const harness = new IpcHarness();const sendToAgentAccepted = vi.fn().mockResolvedValue({ accepted: true });diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.tsindex c4c0f44b59..440efb7edf 100644--- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts+++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts@@ -99,6 +99,7 @@ export type OrcaInterAgentSendToSessionInternalResult =| 'DELETED'| 'BUSY'| 'AGENT_NOT_READY'+ | 'UNSUPPORTED_CAPABILITY'// create 显式执行配置专用;dispatcher 恒走 jump,仅镜像共用函数的联合形状。| 'BUDGET_MODEL_REQUIRES_API_MODE'| 'PROVIDER_ROUTE_UNAVAILABLE'diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex cfb4d30bb4..23e042e472 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -213,6 +213,7 @@ import {hasReviewOwnerProcessEnded,shouldFailInterruptedReview,} from '../reviewer/reviewRunRecovery.js';+import { startReviewOwnerLiveness } from '../reviewer/reviewOwnerLiveness.js';import {discardInvalidReviewSourceLease,listPersistedReviewSourceLeases,@@ -748,6 +749,7 @@ import {import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js';import {markRemoteSettingPersistedInsideHandler,+ setRemoteReviewInputGuard as setDeviceLinkRemoteReviewInputGuard,setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,} from '../device-link/dispatch.js';@@ -768,6 +770,7 @@ import {isPluginSetupInteractionDecision,} from './interactionResolveOrigin.js';import { checkRemoteWorkingDir } from '../device-link/remote-workdir-guard.js';+import { assertReviewSessionExternalInputAllowed } from '../reviewer/reviewSessionInputPolicy.js';import { createWorkerTurnStartSequencer } from './workerTurnStartSequencer.js';import { createBusinessSessionId } from '../sessionIds.js';import { forkSessionAtMessage } from '../maker-orchestration/fork.js';@@ -1382,6 +1385,7 @@ type SendToSessionInternalResult =| 'DELETED'| 'BUSY'| 'AGENT_NOT_READY'+ | 'UNSUPPORTED_CAPABILITY'| 'BUDGET_MODEL_REQUIRES_API_MODE'| 'PROVIDER_ROUTE_UNAVAILABLE'// create 分支专用:dispatcher 无 session 上下文时无法继承配置新建。@@ -2432,6 +2436,16 @@ const reviewRunOwner: ReviewRunOwner = {instanceId: randomUUID(),processId: process.pid,};+let reviewOwnerLivenessReady: Promise<void> | null = null;++function ensureReviewOwnerLivenessReady(): Promise<void> {+ if (!reviewOwnerLivenessReady) {+ reviewOwnerLivenessReady = startReviewOwnerLiveness().then((handle) => {+ reviewRunOwner.liveness = handle.identity;+ });+ }+ return reviewOwnerLivenessReady;+}const sessionTurnLeaseTracker = new SessionTurnLeaseTracker({getDbClient,owner: reviewRunOwner,@@ -5028,6 +5042,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// device-link 参数级收敛:远程 create-session 的 workingDir / worktree:create 的 baseRepo// 必须是本机当前可访问的目录,挡掉控制端用任意路径越权起进程或执行 git。setDeviceLinkRemoteWorkingDirGuard(checkRemoteWorkingDir);+ setDeviceLinkRemoteReviewInputGuard(assertReviewExternalInputAllowed);// device-link 远程 set-* 持久化回流:effort/permission/fastMode/extraDirs 等// runtime-only handler 经这个注入写被控端 DB + 广播 patched。SET_MODEL 是例外:@@ -6007,13 +6022,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)enforceReviewCreateOptions(o);}- async function assertReviewSettingsUnlocked(sessionId: string): Promise<void> {+ async function readSessionSource(sessionId: string): Promise<string | null> {const [row] = await getDbClient().drizzle.select({ source: sessions.source }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);- if (row?.source === 'review') {+ return row?.source ?? null;+ }++ async function assertReviewExternalInputAllowed(sessionId: string): Promise<void> {+ await assertReviewSessionExternalInputAllowed(sessionId, readSessionSource);+ }++ async function assertReviewSettingsUnlocked(sessionId: string): Promise<void> {+ if ((await readSessionSource(sessionId)) === 'review') {throwIpcError('UNSUPPORTED_CAPABILITY', 'Review task settings are fixed to the source task');}}@@ -6704,7 +6727,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const interruptedAt = Date.now();for (const row of rows) {const reviewRun = readReviewRunFromAgentMeta(row.agentMeta);- if (!reviewRun || !shouldFailInterruptedReview(reviewRun, reviewRunOwner)) continue;+ if (!reviewRun || !(await shouldFailInterruptedReview(reviewRun, reviewRunOwner))) continue;const failed: ReviewRunMeta = {...reviewRun,status: 'failed',@@ -6724,7 +6747,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});continue;}- if (!hasReviewOwnerProcessEnded(row.lease.owner, reviewRunOwner)) continue;+ if (!(await hasReviewOwnerProcessEnded(row.lease.owner, reviewRunOwner))) continue;await releaseReviewSourceLease(dbClient, {sourceSessionId: row.sourceSessionId,runId: row.lease.runId,@@ -6755,11 +6778,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return sessionTurnLeaseTracker.isTurnActive(sourceSessionId);};- const reviewStartupReady = Promise.all([- reconcileInterruptedReviews(),- sessionTurnLeaseTracker.reconcileStaleLeases(),- cleanupOrphanedReviewArtifactSnapshots(),- ])+ const reviewStartupReady = ensureReviewOwnerLivenessReady()+ .then(() =>+ Promise.all([+ reconcileInterruptedReviews(),+ sessionTurnLeaseTracker.reconcileStaleLeases(),+ cleanupOrphanedReviewArtifactSnapshots(),+ ]),+ ).then(() => undefined).catch((error) => {log.error('failed to prepare Review runtime state', {@@ -7506,6 +7532,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};}+ if (targetSessionId) {+ try {+ await assertReviewExternalInputAllowed(targetSessionId);+ } catch (error) {+ if ((error as { code?: unknown }).code !== 'UNSUPPORTED_CAPABILITY') throw error;+ return {+ ok: false,+ errorCode: 'UNSUPPORTED_CAPABILITY',+ message: error instanceof Error ? error.message : String(error),+ };+ }+ }+// ── create 分支 ──────────────────────────────────────────────────────────// 不传 targetSessionId → 为业务对象起一个全新的专属 session,继承 dispatcher// (调用方)session 的配置后投递首条消息,把新 id 回传给调用方建立关联。@@ -8503,8 +8542,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)isSessionRunningError,log,});- const dispatchOrEnqueueOrcaInterAgentMessage =- orcaInterAgentDispatcher.dispatchOrEnqueueOrcaInterAgentMessage;+ const dispatchOrEnqueueOrcaInterAgentMessage: OrcaInterAgentDispatcher['dispatchOrEnqueueOrcaInterAgentMessage'] =+ async (params) => {+ try {+ await assertReviewExternalInputAllowed(params.targetSessionId);+ } catch (error) {+ return {+ ok: false,+ dispatchOutcome: {+ ...createHostSendFailure(+ 'SEND_FAILED',+ error instanceof Error ? error.message : String(error),+ ),+ source: params.meta.source,+ context: params.meta.context,+ },+ };+ }+ return orcaInterAgentDispatcher.dispatchOrEnqueueOrcaInterAgentMessage(params);+ };dispatchInterAgentMessageHolder = dispatchOrEnqueueOrcaInterAgentMessage;ipcMain.handle(@@ -9642,6 +9698,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const sendToAgentAccepted: typeof sendToAgentAcceptedUnlocked = async (...args) => {const [sessionId] = args;if (typeof sessionId !== 'string') return await sendToAgentAcceptedUnlocked(...args);+ await assertReviewExternalInputAllowed(sessionId);return await withSendToSessionLock(sessionId, () => sendToAgentAcceptedUnlocked(...args));};/**@@ -9659,6 +9716,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sendOpts?: unknown,): Promise<void> => {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');+ await assertReviewExternalInputAllowed(sessionId);const sess = maker.getSession(sessionId);if (!sess) {log.warn('steer: session not running', { sessionId });@@ -11268,6 +11326,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)remote: boolean,opts: unknown,): Promise<MainOwnedInputBoundaryStamp> => {+ await assertReviewExternalInputAllowed(sid);// Capture the coordinator generation before the first database await. A// concurrent /clear replaces the in-memory state; after that await we must// reject the old request rather than treating the new generation as its@@ -11324,6 +11383,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)MAKER_INVOKE.INPUT_ENQUEUE,async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {const sid = requireSessionId(sessionId);+ await assertReviewExternalInputAllowed(sid);const deviceLinkInvoke = isDeviceLinkInvoke();const parsed = requireQueuedMessage(item);assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);@@ -11473,6 +11533,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)MAKER_INVOKE.INPUT_STEER,async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {const sid = requireSessionId(sessionId);+ await assertReviewExternalInputAllowed(sid);const deviceLinkInvoke = isDeviceLinkInvoke();const steerOpts =opts && typeof opts === 'object'@@ -11940,6 +12001,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throwIpcError('INVALID_PARAMS', 'clearedAt must be an ISO timestamp');}const sid = requireSessionId(sessionId);+ await assertReviewExternalInputAllowed(sid);// Fence remote content-bearing controls for the whole clear lifecycle,// including the DB await below. Local clear is gated too so a remote// controller cannot enter the same sealing window through another peer.diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts b/apps/desktop/src/main/maker-ipc/sessionTurnLease.tsindex 9848eede3a..4917bce68b 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts@@ -1,6 +1,6 @@import { createId } from '@paralleldrive/cuid2';-import type { ReviewRunOwner } from '../../shared/reviewRun.js';+import { readReviewRunOwner, type ReviewRunOwner } from '../../shared/reviewRun.js';import type { DbClient } from '../localDb/client/DbClient.js';import { hasReviewOwnerProcessEnded } from '../reviewer/reviewRunRecovery.js';@@ -113,15 +113,7 @@ export function readSessionTurnLeaseFromAgentMeta(value: unknown): SessionTurnLe) {return null;}- const ownerRecord = owner as Record<string, unknown>;- if (- typeof ownerRecord.instanceId !== 'string' ||- !ownerRecord.instanceId ||- !Number.isSafeInteger(ownerRecord.processId) ||- (ownerRecord.processId as number) <= 0- ) {- return null;- }+ if (!readReviewRunOwner(owner)) return null;return valueRecord as unknown as SessionTurnLease;}@@ -256,7 +248,10 @@ export interface SessionTurnLeaseTrackerDeps {owner: ReviewRunOwner;createTurnId(): string;now(): number;- ownerProcessEnded?(owner: ReviewRunOwner, currentOwner: ReviewRunOwner): boolean;+ ownerProcessEnded?(+ owner: ReviewRunOwner,+ currentOwner: ReviewRunOwner,+ ): boolean | Promise<boolean>;warn?(message: string, fields: Record<string, unknown>): void;}@@ -289,7 +284,7 @@ export class SessionTurnLeaseTracker {return next;}- private ownerProcessEnded(owner: ReviewRunOwner): boolean {+ private ownerProcessEnded(owner: ReviewRunOwner): boolean | Promise<boolean> {return (this.deps.ownerProcessEnded ?? hasReviewOwnerProcessEnded)(owner, this.deps.owner);}@@ -306,7 +301,7 @@ export class SessionTurnLeaseTracker {owner: row.lease.owner,});}- if (!this.ownerProcessEnded(row.lease.owner)) return false;+ if (!(await this.ownerProcessEnded(row.lease.owner))) return false;return releaseSessionTurnLease(dbClient, {sessionId: row.sessionId,turnId: row.lease.turnId,diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.tsnew file mode 100644index 0000000000..a4fac69ebc--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts@@ -0,0 +1,49 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++const registerSource = readFileSync(+ resolve(import.meta.dirname, '../../maker-ipc/register.ts'),+ 'utf8',+);+const reviewStartSource = readFileSync(+ resolve(import.meta.dirname, '../../maker-ipc/reviewStartHandler.ts'),+ 'utf8',+);++describe('Review external input wiring', () => {+ it('guards direct send/steer and every input-queue mutation at Main', () => {+ expect(registerSource).toMatch(+ /const assertRemoteInputControlBoundary[\s\S]*?await assertReviewExternalInputAllowed\(sid\);/,+ );+ for (const channel of ['INPUT_ENQUEUE', 'INPUT_STEER', 'INPUT_CLEAR_SESSION']) {+ expect(registerSource).toMatch(+ new RegExp(+ `MAKER_INVOKE\\.${channel}[\\s\\S]{0,700}await assertReviewExternalInputAllowed\\(sid\\);`,+ ),+ );+ }+ });++ it('also rejects local cross-task and Orca delivery into Review tasks', () => {+ expect(registerSource).toMatch(+ /async function sendToSessionInternal[\s\S]*?await assertReviewExternalInputAllowed\(targetSessionId\);/,+ );+ expect(registerSource).toMatch(+ /const dispatchOrEnqueueOrcaInterAgentMessage[\s\S]*?await assertReviewExternalInputAllowed\(params\.targetSessionId\);/,+ );+ expect(registerSource).toMatch(+ /const sendToAgentAccepted[\s\S]*?await assertReviewExternalInputAllowed\(sessionId\);/,+ );+ expect(registerSource).toMatch(+ /const steerToAgentAccepted[\s\S]*?await assertReviewExternalInputAllowed\(sessionId\);/,+ );+ });++ it('keeps the one allowed initial prompt on the host-only direct Session handle', () => {+ expect(reviewStartSource).toContain('const sendResult = await reviewer.send(launch.message');+ expect(reviewStartSource).not.toContain('MAKER_INVOKE.SEND');+ expect(reviewStartSource).not.toContain('MAKER_INVOKE.INPUT_ENQUEUE');+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewOwnerLiveness.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewOwnerLiveness.test.tsnew file mode 100644index 0000000000..f5e3304030--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewOwnerLiveness.test.ts@@ -0,0 +1,34 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ probeReviewOwnerLiveness,+ startReviewOwnerLiveness,+ type ReviewOwnerLivenessHandle,+} from '../reviewOwnerLiveness.js';++describe('Review owner exact liveness', () => {+ let handle: ReviewOwnerLivenessHandle | null = null;++ afterEach(async () => {+ await handle?.close();+ handle = null;+ });++ it('recognizes only the exact live Main instance challenge', async () => {+ handle = await startReviewOwnerLiveness();++ await expect(probeReviewOwnerLiveness(handle.identity)).resolves.toBe('alive');+ await expect(+ probeReviewOwnerLiveness({ ...handle.identity, token: 'wrong-instance-token' }),+ ).resolves.toBe('ended');+ });++ it('reports the owner ended after its endpoint closes', async () => {+ handle = await startReviewOwnerLiveness();+ const identity = handle.identity;+ await handle.close();+ handle = null;++ await expect(probeReviewOwnerLiveness(identity)).resolves.toBe('ended');+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.tsindex 566c0ebf60..f907b4aeb8 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts@@ -19,49 +19,83 @@ function running(owner?: ReviewRunOwner): ReviewRunMeta {}describe('Review run recovery ownership', () => {- it('does not fail a run owned by this process instance', () => {+ it('does not fail a run owned by this process instance', async () => {const probe = vi.fn(() => false);- expect(shouldFailInterruptedReview(running(currentOwner), currentOwner, probe)).toBe(false);+ await expect(+ shouldFailInterruptedReview(running(currentOwner), currentOwner, probe),+ ).resolves.toBe(false);expect(probe).not.toHaveBeenCalled();});- it('preserves a run while its foreign owner process is alive', () => {+ it('preserves a legacy run while its foreign owner process is alive', async () => {const probe = vi.fn(() => true);- expect(+ await expect(shouldFailInterruptedReview(running({ instanceId: 'other', processId: 300 }),currentOwner,probe,),- ).toBe(false);+ ).resolves.toBe(false);expect(probe).toHaveBeenCalledWith(300);});- it('fails only after the foreign owner is confirmed dead', () => {- expect(+ it('fails a legacy run only after the foreign owner is confirmed dead', async () => {+ await expect(shouldFailInterruptedReview(running({ instanceId: 'other', processId: 300 }),currentOwner,() => false,),- ).toBe(true);+ ).resolves.toBe(true);});- it('recognizes PID reuse by the current differently identified instance', () => {+ it('recognizes PID reuse by the current differently identified instance', async () => {const probe = vi.fn(() => true);- expect(+ await expect(shouldFailInterruptedReview(running({ instanceId: 'previous', processId: currentOwner.processId }),currentOwner,probe,),- ).toBe(true);+ ).resolves.toBe(true);expect(probe).not.toHaveBeenCalled();});- it('leaves owner-less cards from older clients untouched', () => {+ it('uses the exact instance probe instead of a reused PID', async () => {+ const processProbe = vi.fn(() => true);+ const owner = {+ instanceId: 'previous',+ processId: 300,+ liveness: { version: 1 as const, port: 1234, token: '1234567890abcdef' },+ };+ const livenessProbe = vi.fn(() => 'ended' as const);++ await expect(+ shouldFailInterruptedReview(running(owner), currentOwner, processProbe, livenessProbe),+ ).resolves.toBe(true);+ expect(livenessProbe).toHaveBeenCalledWith(owner);+ expect(processProbe).not.toHaveBeenCalled();+ });++ it('preserves the lease when an exact instance probe is temporarily ambiguous', async () => {+ const owner = {+ instanceId: 'other',+ processId: 300,+ liveness: { version: 1 as const, port: 1234, token: '1234567890abcdef' },+ };+ await expect(+ shouldFailInterruptedReview(+ running(owner),+ currentOwner,+ () => false,+ () => 'unknown',+ ),+ ).resolves.toBe(false);+ });++ it('leaves owner-less cards from older clients untouched', async () => {const probe = vi.fn(() => false);- expect(shouldFailInterruptedReview(running(), currentOwner, probe)).toBe(false);+ await expect(shouldFailInterruptedReview(running(), currentOwner, probe)).resolves.toBe(false);expect(probe).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSessionInputPolicy.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSessionInputPolicy.test.tsnew file mode 100644index 0000000000..b68acd39ca--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSessionInputPolicy.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it, vi } from 'vitest';++import { assertReviewSessionExternalInputAllowed } from '../reviewSessionInputPolicy.js';++describe('Review external input policy', () => {+ it('rejects an isolated Review task before input dispatch', async () => {+ const readSource = vi.fn().mockResolvedValue('review');++ await expect(+ assertReviewSessionExternalInputAllowed('review-1', readSource),+ ).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });+ expect(readSource).toHaveBeenCalledWith('review-1');+ });++ it('allows ordinary and not-yet-persisted tasks', async () => {+ await expect(+ assertReviewSessionExternalInputAllowed('desktop-1', async () => 'desktop'),+ ).resolves.toBeUndefined();+ await expect(+ assertReviewSessionExternalInputAllowed('draft-1', async () => null),+ ).resolves.toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.tsindex fc5a4d51d2..4fc02d2e11 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts@@ -61,7 +61,11 @@ describe('Review source lease', () => {it('admits exactly one shared-database owner and allows a successor after CAS release', async () => {const { first, second, raw } = setup();- const firstOwner = { instanceId: 'first', processId: 101 };+ const firstOwner = {+ instanceId: 'first',+ processId: 101,+ liveness: { version: 1 as const, port: 43101, token: 'first-owner-token' },+ };const secondOwner = { instanceId: 'second', processId: 202 };const acquired = await Promise.all([diff --git a/apps/desktop/src/main/reviewer/reviewOwnerLiveness.ts b/apps/desktop/src/main/reviewer/reviewOwnerLiveness.tsnew file mode 100644index 0000000000..8a80eb5cac--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewOwnerLiveness.ts@@ -0,0 +1,102 @@+import { randomUUID } from 'node:crypto';+import net from 'node:net';++import type { ReviewRunOwnerLiveness } from '../../shared/reviewRun.js';++const LOOPBACK_HOST = '127.0.0.1';+const PROBE_PREFIX = 'cindy-review-owner-v1:';+const DEFAULT_PROBE_TIMEOUT_MS = 1_000;++export type ReviewOwnerLivenessProbeResult = 'alive' | 'ended' | 'unknown';++export interface ReviewOwnerLivenessHandle {+ identity: ReviewRunOwnerLiveness;+ close(): Promise<void>;+}++/**+ * Bind one challenge endpoint to this exact Main-process incarnation.+ * The OS releases the port on crash; a later unrelated port owner cannot pass+ * the random challenge even when the process id or port is reused.+ */+export async function startReviewOwnerLiveness(): Promise<ReviewOwnerLivenessHandle> {+ const token = randomUUID();+ const expectedReply = `${PROBE_PREFIX}${token}\n`;+ const server = net.createServer((socket) => {+ socket.end(expectedReply);+ });+ // A post-listen socket error must degrade the probe, not crash Desktop.+ server.on('error', () => undefined);++ await new Promise<void>((resolve, reject) => {+ const onError = (error: Error) => {+ server.off('listening', onListening);+ reject(error);+ };+ const onListening = () => {+ server.off('error', onError);+ resolve();+ };+ server.once('error', onError);+ server.once('listening', onListening);+ server.listen({ host: LOOPBACK_HOST, port: 0, exclusive: true });+ });+ server.unref();++ const address = server.address();+ if (!address || typeof address === 'string') {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ throw new Error('Review owner liveness endpoint did not expose a TCP port');+ }++ return {+ identity: { version: 1, port: address.port, token },+ close: () =>+ new Promise<void>((resolve, reject) => {+ if (!server.listening) {+ resolve();+ return;+ }+ server.close((error) => {+ if (error) reject(error);+ else resolve();+ });+ }),+ };+}++/**+ * Verify an exact owner. Ambiguous transport failures are fail-closed: they+ * preserve the lease instead of risking concurrent Review runs.+ */+export async function probeReviewOwnerLiveness(+ identity: ReviewRunOwnerLiveness,+ timeoutMs = DEFAULT_PROBE_TIMEOUT_MS,+): Promise<ReviewOwnerLivenessProbeResult> {+ const expectedReply = `${PROBE_PREFIX}${identity.token}\n`;+ return await new Promise<ReviewOwnerLivenessProbeResult>((resolve) => {+ let settled = false;+ let received = '';+ const socket = net.createConnection({ host: LOOPBACK_HOST, port: identity.port });+ const finish = (result: ReviewOwnerLivenessProbeResult) => {+ if (settled) return;+ settled = true;+ socket.destroy();+ resolve(result);+ };+ socket.setEncoding('utf8');+ socket.setTimeout(timeoutMs);+ socket.on('data', (chunk) => {+ received += chunk;+ if (received === expectedReply) finish('alive');+ else if (!expectedReply.startsWith(received)) finish('ended');+ else if (received.length >= expectedReply.length) finish('ended');+ });+ socket.on('end', () => finish(received === expectedReply ? 'alive' : 'ended'));+ socket.on('timeout', () => finish('unknown'));+ socket.on('error', (error: NodeJS.ErrnoException) => {+ if (error.code === 'ECONNREFUSED' || error.code === 'ENOENT') finish('ended');+ else finish('unknown');+ });+ });+}diff --git a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts b/apps/desktop/src/main/reviewer/reviewRunRecovery.tsindex 8e6fc1a623..fc0e2542fc 100644--- a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts+++ b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts@@ -1,6 +1,13 @@import type { ReviewRunMeta, ReviewRunOwner } from '../../shared/reviewRun.js';+import {+ probeReviewOwnerLiveness,+ type ReviewOwnerLivenessProbeResult,+} from './reviewOwnerLiveness.js';export type ReviewProcessAliveProbe = (processId: number) => boolean;+export type ReviewOwnerLivenessProbe = (+ owner: ReviewRunOwner,+) => ReviewOwnerLivenessProbeResult | Promise<ReviewOwnerLivenessProbeResult>;export function isReviewProcessAlive(processId: number): boolean {try {@@ -11,15 +18,26 @@ export function isReviewProcessAlive(processId: number): boolean {}}-export function hasReviewOwnerProcessEnded(+export async function hasReviewOwnerProcessEnded(owner: ReviewRunOwner,currentOwner: ReviewRunOwner,processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,-): boolean {+ ownerLivenessProbe: ReviewOwnerLivenessProbe = (candidate) =>+ candidate.liveness ? probeReviewOwnerLiveness(candidate.liveness) : 'unknown',+): Promise<boolean> {if (owner.instanceId === currentOwner.instanceId) return false;// This process now owns the same PID, so the differently identified previous// owner has definitely terminated even if the OS immediately reused the PID.if (owner.processId === currentOwner.processId) return true;+ if (owner.liveness) {+ const result = await ownerLivenessProbe(owner);+ if (result === 'alive') return false;+ if (result === 'ended') return true;+ // A timeout or other ambiguous local transport failure must not let two+ // Desktop instances own the same Review source concurrently.+ return false;+ }+ // Compatibility for leases/cards written before exact instance probes existed.return !processIsAlive(owner.processId);}@@ -28,11 +46,17 @@ export function hasReviewOwnerProcessEnded(* the Main process which owns it has ended. Owner-less cards from older builds* remain untouched because another older instance may still be running them.*/-export function shouldFailInterruptedReview(+export async function shouldFailInterruptedReview(reviewRun: ReviewRunMeta,currentOwner: ReviewRunOwner,processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,-): boolean {+ ownerLivenessProbe?: ReviewOwnerLivenessProbe,+): Promise<boolean> {if (reviewRun.status !== 'running' || !reviewRun.owner) return false;- return hasReviewOwnerProcessEnded(reviewRun.owner, currentOwner, processIsAlive);+ return hasReviewOwnerProcessEnded(+ reviewRun.owner,+ currentOwner,+ processIsAlive,+ ownerLivenessProbe,+ );}diff --git a/apps/desktop/src/main/reviewer/reviewSessionInputPolicy.ts b/apps/desktop/src/main/reviewer/reviewSessionInputPolicy.tsnew file mode 100644index 0000000000..6e183c2a10--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewSessionInputPolicy.ts@@ -0,0 +1,17 @@+import { throwIpcError } from '../utils/ipcValidate.js';++export type ReviewSessionSourceReader = (+ sessionId: string,+) => string | null | Promise<string | null>;++/** Reject every user/controller input path for a host-owned isolated Review task. */+export async function assertReviewSessionExternalInputAllowed(+ sessionId: string,+ readSessionSource: ReviewSessionSourceReader,+): Promise<void> {+ if ((await readSessionSource(sessionId)) !== 'review') return;+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ 'Review tasks only accept the host-owned initial review prompt',+ );+}diff --git a/apps/desktop/src/main/reviewer/reviewSourceLease.ts b/apps/desktop/src/main/reviewer/reviewSourceLease.tsindex ac1846b6c2..fd0746a559 100644--- a/apps/desktop/src/main/reviewer/reviewSourceLease.ts+++ b/apps/desktop/src/main/reviewer/reviewSourceLease.ts@@ -1,6 +1,6 @@import { createId } from '@paralleldrive/cuid2';-import type { ReviewRunOwner } from '../../shared/reviewRun.js';+import { readReviewRunOwner, type ReviewRunOwner } from '../../shared/reviewRun.js';import type { DbClient } from '../localDb/client/DbClient.js';/** One hidden row per source task makes the cross-process Review gate atomic. */@@ -54,15 +54,7 @@ export function readReviewSourceLeaseFromAgentMeta(value: unknown): ReviewSource) {return null;}- const ownerRecord = owner as Record<string, unknown>;- if (- typeof ownerRecord.instanceId !== 'string' ||- !ownerRecord.instanceId ||- !Number.isSafeInteger(ownerRecord.processId) ||- (ownerRecord.processId as number) <= 0- ) {- return null;- }+ if (!readReviewRunOwner(owner)) return null;return valueRecord as unknown as ReviewSourceLease;}diff --git a/apps/desktop/src/shared/reviewRun.ts b/apps/desktop/src/shared/reviewRun.tsindex d72cdae95c..51ccceb1e8 100644--- a/apps/desktop/src/shared/reviewRun.ts+++ b/apps/desktop/src/shared/reviewRun.ts@@ -2,10 +2,54 @@ export type ReviewRunStatus = 'running' | 'completed' | 'failed';export type ReviewTargetKind = 'changes' | 'artifacts' | 'task' | 'mixed';+export interface ReviewRunOwnerLiveness {+ version: 1;+ /** Loopback-only port owned by this exact Desktop Main instance. */+ port: number;+ /** Random challenge returned by the owner; prevents an unrelated port reuse from matching. */+ token: string;+}+export interface ReviewRunOwner {/** Random per-Main-process identity; distinguishes PID reuse from the original owner. */instanceId: string;processId: number;+ /**+ * Exact cross-process liveness proof for owners created by current builds.+ * Optional only for leases/cards written by older clients.+ */+ liveness?: ReviewRunOwnerLiveness;+}++export function readReviewRunOwner(value: unknown): ReviewRunOwner | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const owner = value as Record<string, unknown>;+ if (+ typeof owner.instanceId !== 'string' ||+ !owner.instanceId ||+ !Number.isSafeInteger(owner.processId) ||+ (owner.processId as number) <= 0+ ) {+ return null;+ }+ if (owner.liveness !== undefined) {+ if (!owner.liveness || typeof owner.liveness !== 'object' || Array.isArray(owner.liveness)) {+ return null;+ }+ const liveness = owner.liveness as Record<string, unknown>;+ if (+ liveness.version !== 1 ||+ !Number.isSafeInteger(liveness.port) ||+ (liveness.port as number) <= 0 ||+ (liveness.port as number) > 65_535 ||+ typeof liveness.token !== 'string' ||+ liveness.token.length < 16 ||+ liveness.token.length > 256+ ) {+ return null;+ }+ }+ return value as ReviewRunOwner;}/**@@ -56,18 +100,7 @@ export function readReviewRunMeta(value: unknown): ReviewRunMeta | null {return null;}if (record.owner !== undefined) {- if (!record.owner || typeof record.owner !== 'object' || Array.isArray(record.owner)) {- return null;- }- const owner = record.owner as Record<string, unknown>;- if (- typeof owner.instanceId !== 'string' ||- !owner.instanceId ||- !Number.isSafeInteger(owner.processId) ||- (owner.processId as number) <= 0- ) {- return null;- }+ if (!readReviewRunOwner(record.owner)) return null;}return record as unknown as ReviewRunMeta;}diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex e4449e587c..dbbae99026 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -5,6 +5,7 @@import { describe, it, expect } from 'vitest';import {REMOTE_INVOKE_ALLOWLIST,+ REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS,PUSH_FORWARD_ALLOWLIST,INVOKE_TIMEOUT_OVERRIDES_MS,computeAllowlistHash,@@ -21,6 +22,13 @@ import {import { SESSION_ACTIVITY_CHANNEL } from '../topics.js';describe('REMOTE_INVOKE_ALLOWLIST', () => {+ it('keeps every Review external-input classification inside the remote allowlist', () => {+ for (const channel of REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS) {+ expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);+ }+ expect(REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS.has('maker:input:get-projection')).toBe(false);+ });+it('放行核心会话链路', () => {for (const ch of ['maker:create-session',diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 7932340c37..1f852bb534 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -486,6 +486,31 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [DL_TELEGRAM_SET_ONLINE_CHANNEL,];+/**+ * Session-scoped input mutations that must be re-authorized by the controlled+ * Desktop before dispatch. Review tasks are visible over device-link but are+ * host-owned audit runs, so none of these channels may inject or mutate input.+ */+export const REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS: ReadonlySet<string> = new Set([+ 'maker:send',+ 'maker:steer',+ 'maker:input:enqueue',+ 'maker:input:compact',+ 'maker:input:steer',+ 'maker:input:stop',+ 'maker:input:resume',+ 'maker:input:retry-last-error',+ 'maker:input:clear-error',+ 'maker:input:remove',+ 'maker:input:update-text',+ 'maker:input:update-content',+ 'maker:input:move',+ 'maker:input:set-expanded',+ 'maker:input:set-interaction-lock',+ 'maker:input:set-edit-lock',+ 'maker:input:clear-session',+]);+/** 远程可调用的 invoke channel 全集(被控端 dispatch 前的权威校验依据) */export const REMOTE_INVOKE_ALLOWLIST: ReadonlySet<string> = new Set([...CORE_INVOKE_CHANNELS,diff --git a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts b/packages/lizi-mcps/src/xdt-helper/send_to_session.tsindex 800a6fedf5..2099ebe234 100644--- a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts+++ b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts@@ -55,6 +55,7 @@ export type SendToSessionCallback = (params: {| "DELETED"| "BUSY"| "AGENT_NOT_READY"+ | "UNSUPPORTED_CAPABILITY"| "BUDGET_MODEL_REQUIRES_API_MODE"| "PROVIDER_ROUTE_UNAVAILABLE"| "INVALID_ARGS"@@ -98,6 +99,7 @@ const DESCRIPTION = ["- BUSY: 仅 create 模式的罕见兜底(新建 session 意外已有 turn 在跑)。jump 模式撞忙不再返 BUSY,而是入队并成功返回 wake_kind=queued。","- WORKTREE_UNAVAILABLE: 仅 create + use_worktree=true:无法创建 worktree(非 git 仓库 / git 未装 / git worktree add 失败,message 带具体原因)。skill 决定是去掉 use_worktree 重试还是放弃。","- AGENT_NOT_READY: 目标 session 恢复或投递时 agent 未能启动。skill 应告知用户稍后重试。",+ "- UNSUPPORTED_CAPABILITY: 目标 session 不接受跨任务投递(例如 host 管理的隔离 Review)。skill 不应重试或改走其它输入入口。","- HOST_NOT_READY: 主进程服务尚未就绪。skill 应告知用户稍等几秒后重试。","","【重要】这不是 chat 对话工具,而是 session 间 handoff 的控制层入口。不要拿它替代普通的 user→agent 对话。",