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 并完善授权与中断流程 (#3438)
DavidShenXD351cf5bd4f01
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.tsindex e209236f4f..d3521b51fc 100644--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts@@ -30,6 +30,7 @@ const nativePopupWebContentsIds = vi.hoisted(() => new Set<number>());const resourceUsageWebContentsIds = vi.hoisted(() => new Set<number>());const rsbWindowWebContentsIds = vi.hoisted(() => new Set<number>());const ghostPanelWebContentsIds = vi.hoisted(() => new Set<number>());+const reviewArtifactConfirmWebContentsIds = vi.hoisted(() => new Set<number>());vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({isRsbNativePopupWebContentsId: (webContentsId: number) =>@@ -50,6 +51,11 @@ vi.mock('../ghost-panel-window/registry.js', () => ({ghostPanelWebContentsIds.has(webContentsId),}));+vi.mock('../reviewer/reviewArtifactConfirmWindowRegistry.js', () => ({+ isReviewArtifactConfirmWebContentsId: (webContentsId: number) =>+ reviewArtifactConfirmWebContentsIds.has(webContentsId),+}));+// lifecycle 只消费这个查询函数;owner-scoped Electron session 会让 adapter// 依赖 owner 持久化与进程锁,不应把整条运行时链带进退出编排单测。vi.mock('../cindy-brain/runtime/electronSandboxAdapter', () => ({@@ -508,6 +514,7 @@ describe('installQuitHandler render-process-gone', () => {resourceUsageWebContentsIds.clear();rsbWindowWebContentsIds.clear();ghostPanelWebContentsIds.clear();+ reviewArtifactConfirmWebContentsIds.clear();});type RenderGoneHandler = (@@ -623,6 +630,22 @@ describe('installQuitHandler render-process-gone', () => {}});+ it('Review artifact consent renderer crash denies locally without shutting the app down', async () => {+ reviewArtifactConfirmWebContentsIds.add(47);+ const { handler, app, restore } = await installAndGrabHandler();+ try {+ handler(undefined, { id: 47, getType: () => 'window' }, { reason: 'oom', exitCode: 5 });+ await new Promise((r) => setTimeout(r, 20));+ expect(app.exit).not.toHaveBeenCalled();+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ expect.stringContaining('Review artifact consent render-process-gone'),+ );+ expect(mocks.logger.error).not.toHaveBeenCalled();+ } finally {+ restore();+ }+ });+it('main window renderer crash still shuts the app down with exit(1)', async () => {const { handler, app, restore } = await installAndGrabHandler();try {diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.tsindex 2b7210b53a..095f9a121b 100644--- a/apps/desktop/src/main/lifecycle.ts+++ b/apps/desktop/src/main/lifecycle.ts@@ -52,6 +52,7 @@ import { isRsbNativePopupWebContentsId } from './rsb-browser-bridge/native-popupimport { isResourceUsageWebContentsId } from './resource-usage-window/registry.js';import { isRsbWindowWebContentsId } from './right-sidebar-window/registry.js';import { isGhostPanelWebContentsId } from './ghost-panel-window/registry.js';+import { isReviewArtifactConfirmWebContentsId } from './reviewer/reviewArtifactConfirmWindowRegistry.js';/*** 瞬时网络错误的 wire payload (main → renderer)。code 永远存在 (Node 的 ErrnoException@@ -675,6 +676,12 @@ export function installQuitHandler(timeoutMs = 2000): void {);return;}+ if (isReviewArtifactConfirmWebContentsId(webContents.id)) {+ log.warn(+ `Review artifact consent render-process-gone (isolated, access denied): reason=${details.reason} exitCode=${details.exitCode}`,+ );+ return;+ }// arm-first(review P1):所有可隔离恢复的 renderer 分支在上面已 return,// 走到这里必然退出。armShutdownHardKillWatchdog();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.tsindex d331ea7649..3460b53ecb 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts@@ -485,6 +485,57 @@ describe('inline attachment temporary files', () => {await expect(fs.lstat(ownerRoot)).rejects.toMatchObject({ code: 'ENOENT' });});+ it('persists exact liveness before writing an owner record and protects a live owner past its deadline', async () => {+ const owner = {+ instanceId: 'exact-live-owner',+ processId: process.pid,+ } as {+ instanceId: string;+ processId: number;+ liveness?: { version: 1; port: number; token: string };+ };+ const ensureOwnerLiveness = vi.fn(async () => {+ owner.liveness = {+ version: 1,+ port: 43_101,+ token: 'exact-live-owner-token',+ };+ });+ configureTempAttachmentOwner(owner, ensureOwnerLiveness);++ const normalized = await normalizeUserMessage('exact-live-session', {+ type: 'user',+ content: [{+ type: 'file',+ base64: Buffer.from('still in use').toString('base64'),+ mimeType: 'text/plain',+ }],+ });+ if (typeof normalized === 'string' || typeof normalized.content === 'string') {+ throw new Error('expected block message');+ }+ const filePath = normalized.content[0]?.path;+ if (typeof filePath !== 'string') throw new Error('expected materialized file path');+ const ownerRoot = path.dirname(path.dirname(filePath));+ const record = JSON.parse(+ await fs.readFile(path.join(ownerRoot, '.cindy-owner.json'), 'utf8'),+ ) as { expiresAt: number; owner: typeof owner };++ expect(ensureOwnerLiveness).toHaveBeenCalledOnce();+ expect(record.owner.liveness).toEqual(owner.liveness);+ const ownerLivenessProbe = vi.fn(() => 'alive' as const);+ await cleanupOrphanedTempAttachments({+ currentOwner: { instanceId: 'other-main', processId: process.pid + 100_000 },+ root: path.join(tempRoot.value, 'cindy-attachments'),+ processIsAlive: () => true,+ ownerLivenessProbe,+ now: () => record.expiresAt + 1,+ });++ expect(ownerLivenessProbe).toHaveBeenCalledWith(record.owner);+ await expect(fs.lstat(ownerRoot)).resolves.toMatchObject({});+ });+it.each(['shared root', 'session directory'] as const)('refuses a symlinked temporary attachment %s',async (target) => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.tsindex e95352a32e..2f7084bc9c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts@@ -184,6 +184,7 @@ describe('maker:review:start IPC lifecycle', () => {).rejects.toMatchObject({ code: 'INVALID_PARAMS' });expect(deps.assertCaller).toHaveBeenCalledTimes(2);+ expect(deps.waitUntilReady).not.toHaveBeenCalled();expect(deps.prepareRun).not.toHaveBeenCalled();});@@ -202,6 +203,7 @@ describe('maker:review:start IPC lifecycle', () => {reviewerSessionId: 'reviewer-1',});+ expect(deps.waitUntilReady).toHaveBeenCalledWith('source-1');expect(deps.createSourceCard).toHaveBeenCalledWith(expect.objectContaining({sourceSessionId: 'source-1',@@ -284,6 +286,39 @@ describe('maker:review:start IPC lifecycle', () => {expect(meta).not.toHaveProperty('error');});+ it('does not publish a partial result when the user stops Review', async () => {+ const harness = new IpcHarness();+ const reviewer = new FakeReviewer();+ const deps = makeDeps(reviewer);+ const control = registerReviewStartHandler(harness, deps);+ await harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest());++ expect(control.noteReviewerStopRequested('reviewer-1')).toBe(true);+ expect(control.noteReviewerStopRequested('reviewer-1')).toBe(true);+ // Pi and some Claude stop paths close with an ordinary done event, so the+ // host-owned stop marker must win over any partial provider result.+ reviewer.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(deps.updateSourceCard).toHaveBeenCalledTimes(1));++ expect(deps.readReviewerResult).not.toHaveBeenCalled();+ expect(deps.updateSourceCard).toHaveBeenCalledWith(+ expect.objectContaining({+ result: '',+ meta: expect.objectContaining({+ status: 'failed',+ failureCode: 'reviewer-closed',+ }),+ }),+ );+ expect(deps.closeReviewer).toHaveBeenCalledTimes(1);+ expect(deps.releaseSourceLease).toHaveBeenCalledTimes(1);+ expect(control.noteReviewerStopRequested('reviewer-1')).toBe(false);++ await expect(harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest())).resolves.toMatchObject(+ { ok: true, runId: 'run-2' },+ );+ });+it('uses a stable provider failure code only when no diagnostic detail exists', async () => {const harness = new IpcHarness();const reviewer = new FakeReviewer();@@ -729,7 +764,7 @@ describe('maker:review:start IPC lifecycle', () => {expect(deps.readReviewerResult).not.toHaveBeenCalled();});- it('publishes no stale result when final freshness verification fails', async () => {+ it('preserves a completed result as stale when final freshness verification fails', async () => {const harness = new IpcHarness();const reviewer = new FakeReviewer();const staleReason = {@@ -750,7 +785,7 @@ describe('maker:review:start IPC lifecycle', () => {expect(deps.updateSourceCard).toHaveBeenCalledWith(expect.objectContaining({- result: '',+ result: 'P1: real finding',meta: expect.objectContaining({ status: 'failed', failureCode: staleReason.code }),}),);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.tsindex 23b521c759..da7af96444 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts@@ -8,6 +8,7 @@ import { afterEach, describe, expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';import {readPersistedSessionTurnLeases,+ refreshSessionTurnLeaseOwner,releaseSessionTurnLease,replaceSessionTurnLease,SESSION_TURN_LEASE_CLIENT_ID_PREFIX,@@ -56,7 +57,7 @@ describe('shared-process session turn lease', () => {ON messages(session_id, client_id);INSERT INTO sessions(id, status, active_turn_started_at, last_turn_ended_at)- VALUES ('source-1', 'active', 20, 10);+ VALUES ('source-1', 'active', 20, 10), ('source-2', 'active', 20, 10);`);const second = new Database(dbPath);second.pragma('foreign_keys = ON');@@ -222,6 +223,49 @@ describe('shared-process session turn lease', () => {await expect(readPersistedSessionTurnLeases(first, 'source-1')).resolves.toEqual([]);});+ it('refreshes active PID-only leases with exact liveness without overwriting a successor', async () => {+ const { first } = setup();+ const owner = { instanceId: 'first', processId: 101 } as {+ instanceId: string;+ processId: number;+ liveness?: { version: 1; port: number; token: string };+ };+ const tracker = new SessionTurnLeaseTracker({+ getDbClient: () => first,+ owner,+ createTurnId: () => 'fallback',+ now: () => 1,+ ownerProcessEnded: () => false,+ });++ await tracker.markTurnStarted('source-1', 'generation-1');+ const initialLease = (await readPersistedSessionTurnLeases(first, 'source-1'))[0]?.lease;+ expect(initialLease).toMatchObject({ turnId: 'generation-1' });+ expect(initialLease?.owner).not.toHaveProperty('liveness');++ owner.liveness = {+ version: 1,+ port: 31_337,+ token: 'current-instance-token',+ };+ await tracker.refreshActiveLeaseOwners();+ await expect(readPersistedSessionTurnLeases(first, 'source-1')).resolves.toMatchObject([+ { lease: { turnId: 'generation-1', owner: { liveness: owner.liveness } } },+ ]);++ await tracker.markTurnStarted('source-1', 'generation-2');+ await expect(+ refreshSessionTurnLeaseOwner(first, {+ sessionId: 'source-1',+ turnId: 'generation-1',+ owner,+ }),+ ).resolves.toBe(false);+ await expect(readPersistedSessionTurnLeases(first, 'source-1')).resolves.toMatchObject([+ { lease: { turnId: 'generation-2', owner: { liveness: owner.liveness } } },+ ]);+ });+it('makes a peer turn visible until its exact lifecycle ends', async () => {const { first, second } = setup();const firstTracker = new SessionTurnLeaseTracker({@@ -245,7 +289,7 @@ describe('shared-process session turn lease', () => {await expect(secondTracker.isTurnActive('source-1')).resolves.toBe(false);});- it('reclaims dead and malformed leases without acknowledging interrupted-turn markers', async () => {+ it('reclaims dead and malformed leases only for the requested task', async () => {const { first, raw } = setup();const deadOwner = { instanceId: 'dead', processId: 303 };await tryAcquireSessionTurnLease(first, {@@ -254,6 +298,12 @@ describe('shared-process session turn lease', () => {owner: deadOwner,createdAt: 1,});+ await tryAcquireSessionTurnLease(first, {+ sessionId: 'source-2',+ turnId: 'other-dead-turn',+ owner: deadOwner,+ createdAt: 1,+ });raw.prepare(`INSERT INTO messages@@ -269,7 +319,6 @@ describe('shared-process session turn lease', () => {ownerProcessEnded: (owner) => owner.instanceId === deadOwner.instanceId,});- await tracker.reconcileStaleLeases();await expect(tracker.isTurnActive('source-1')).resolves.toBe(false);expect(raw@@ -280,5 +329,8 @@ describe('shared-process session turn lease', () => {.get(),).toEqual({ startedAt: 20, endedAt: 10 });await expect(readPersistedSessionTurnLeases(first, 'source-1')).resolves.toEqual([]);+ await expect(readPersistedSessionTurnLeases(first, 'source-2')).resolves.toMatchObject([+ { lease: { turnId: 'other-dead-turn' } },+ ]);});});diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.tsindex e066cbfd1a..e8e1a82eff 100644--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts@@ -55,6 +55,7 @@ let tempAttachmentOwner: ReviewRunOwner = {instanceId: randomUUID(),processId: process.pid,};+let ensureTempAttachmentOwnerLiveness: (() => Promise<void>) | null = null;interface TempAttachmentOwnerRecord {version: 1;@@ -64,8 +65,12 @@ interface TempAttachmentOwnerRecord {}/** Share the exact Main-process identity used by Review lifecycle recovery. */-export function configureTempAttachmentOwner(owner: ReviewRunOwner): void {+export function configureTempAttachmentOwner(+ owner: ReviewRunOwner,+ ensureOwnerLiveness?: () => Promise<void>,+): void {tempAttachmentOwner = owner;+ ensureTempAttachmentOwnerLiveness = ensureOwnerLiveness ?? null;}const EXT_BY_MIME: Record<string, string> = {@@ -191,6 +196,11 @@ async function ensureTempOwnerRoot(): Promise<string> {const pending = TEMP_OWNER_ROOT_PREPARATIONS.get(ownerRoot);if (pending) return pending;const preparation = (async () => {+ // The cleanup boundary is shared across Desktop instances. Persist an+ // exact incarnation proof before any ordinary turn can leave temporary+ // attachment bytes behind; PID-only records become ambiguous after PID+ // reuse and cannot safely be reclaimed on a fixed deadline.+ await ensureTempAttachmentOwnerLiveness?.();await fs.mkdir(sharedRoot, { recursive: true, mode: 0o700 });await assertRealTempDirectory(sharedRoot);await fs.chmod(sharedRoot, 0o700);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ce3626cd93..c328841d20 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -56,7 +56,7 @@ import {CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,} from '@cindy/device-link';-import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';+import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';import {getActiveAppSession,@@ -234,6 +234,7 @@ import {type ReviewArtifactConfirmationItem,} from '../reviewer/reviewArtifactAuthorization.js';import { buildReviewArtifactConfirmationDialog } from '../reviewer/reviewArtifactDialog.js';+import { showReviewArtifactConfirmWindow } from '../reviewer/reviewArtifactConfirmWindow.js';import {cleanupOrphanedReviewArtifactSnapshots,prepareStableReviewArtifactSnapshots,@@ -253,14 +254,17 @@ import {type ReviewRunOwner,} from '../../shared/reviewRun.js';import {- createRetryableReviewStartup,+ createRetryableReviewInitialization,hasReviewOwnerProcessEnded,shouldFailInterruptedReview,} from '../reviewer/reviewRunRecovery.js';-import { startReviewOwnerLiveness } from '../reviewer/reviewOwnerLiveness.js';+import {+ startReviewOwnerLiveness,+ type ReviewOwnerLivenessHandle,+} from '../reviewer/reviewOwnerLiveness.js';import {discardInvalidReviewSourceLease,- listPersistedReviewSourceLeases,+ readPersistedReviewSourceLease,releaseReviewSourceLease,tryAcquireReviewSourceLease,} from '../reviewer/reviewSourceLease.js';@@ -2873,11 +2877,6 @@ let cancelPendingAgentSwitchHolder: ((sessionId: string) => void) | null = null;let gitSnapshotCoordinator: GitSnapshotCoordinator | null = null;const sessionTurnActivityTracker = new SessionTurnActivityTracker();const reviewRunOwner: ReviewRunOwner = { instanceId: randomUUID(), processId: process.pid };-configureTempAttachmentOwner(reviewRunOwner);-const ensureReviewOwnerLivenessReady = createRetryableReviewStartup(async () => {- const handle = await startReviewOwnerLiveness();- reviewRunOwner.liveness = handle.identity;-});const sessionTurnLeaseTracker = new SessionTurnLeaseTracker({getDbClient,owner: reviewRunOwner,@@ -2885,6 +2884,14 @@ const sessionTurnLeaseTracker = new SessionTurnLeaseTracker({now: Date.now,warn: (message, fields) => log.warn(message, fields),});+let reviewOwnerLivenessHandle: ReviewOwnerLivenessHandle | null = null;+const ensureReviewOwnerLivenessReady = createRetryableReviewInitialization(async () => {+ const handle = reviewOwnerLivenessHandle ?? (await startReviewOwnerLiveness());+ reviewOwnerLivenessHandle = handle;+ reviewRunOwner.liveness = handle.identity;+ await sessionTurnLeaseTracker.refreshActiveLeaseOwners();+});+configureTempAttachmentOwner(reviewRunOwner, ensureReviewOwnerLivenessReady);const silentStopTurnLeaseGate = new SilentStopTurnLeaseGate();function providerTurnLeaseId(sessionInstanceId: string, turnGeneration: number): string {return `${sessionInstanceId}:${turnGeneration}`;@@ -3868,6 +3875,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidbeforeProviderStart: async (turnGeneration) => {if (session.remoteHostId) return;silentStopTurnLeaseGate.supersede(session.id);+ // Keep Review's exact-instance liveness listener lazy. PID-only turn+ // leases remain fail-closed until this process actually starts Review.await sessionTurnLeaseTracker.markTurnStarted(session.id,providerTurnLeaseId(session.instanceId, turnGeneration),@@ -5860,13 +5869,13 @@ async function confirmReviewExternalArtifacts(event: IpcMainInvokeEvent,items: ReviewArtifactConfirmationItem[],): Promise<boolean> {- const options = buildReviewArtifactConfirmationDialog(items, t);- const owner = BrowserWindow.fromWebContents(event.sender);- const result =- owner && !owner.isDestroyed()- ? await dialog.showMessageBox(owner, options)- : await dialog.showMessageBox(options);- return result.response === 1;+ const parent = BrowserWindow.fromWebContents(event.sender);+ if (!parent || parent.isDestroyed()) return false;+ return showReviewArtifactConfirmWindow(+ parent,+ buildReviewArtifactConfirmationDialog(items, t),+ { log },+ );}export interface RegisterMakerIpcOptions {@@ -8060,25 +8069,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),});- const reconcileInterruptedReviews = async (): Promise<void> => {- const dbClient = getDbClient();- const db = dbClient.drizzle;- const [rows, sourceLeases] = await Promise.all([- db- .select({- sessionId: messages.sessionId,- clientId: messages.clientId,- agentMeta: messages.agentMeta,- })- .from(messages)- .where(- and(- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- sql`${messages.agentMeta} LIKE '%"reviewRun"%'`,- ),+ const readSourceReviewCards = async (sourceSessionId: string) =>+ getDbClient()+ .drizzle.select({+ clientId: messages.clientId,+ agentMeta: messages.agentMeta,+ })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sourceSessionId),+ gte(messages.clientId, 'review:'),+ lt(messages.clientId, 'review;'),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),),- listPersistedReviewSourceLeases(dbClient),+ );++ const reconcileReviewForSource = async (sourceSessionId: string): Promise<void> => {+ const dbClient = getDbClient();+ const [rows, sourceLease] = await Promise.all([+ readSourceReviewCards(sourceSessionId),+ readPersistedReviewSourceLease(dbClient, sourceSessionId),]);const interruptedAt = Date.now();for (const row of rows) {@@ -8090,39 +8102,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)completedAt: interruptedAt,failureCode: 'interrupted',};- await updateMessageContent(row.sessionId, row.clientId, '');- await patchMessageAgentMeta(row.sessionId, row.clientId, { reviewRun: failed });- await broadcastMessageAgentMetaUpdate(row.sessionId, row.clientId);+ await updateMessageContent(sourceSessionId, row.clientId, '');+ await patchMessageAgentMeta(sourceSessionId, row.clientId, { reviewRun: failed });+ await broadcastMessageAgentMetaUpdate(sourceSessionId, row.clientId);}- for (const row of sourceLeases) {- if (!row.lease) {- await discardInvalidReviewSourceLease(dbClient, row);- log.warn('discarded malformed Review source lease', {- sourceSessionId: row.sourceSessionId,- leaseRowId: row.id,- });- continue;- }- if (!(await hasReviewOwnerProcessEnded(row.lease.owner, reviewRunOwner))) continue;- await releaseReviewSourceLease(dbClient, {- sourceSessionId: row.sourceSessionId,- runId: row.lease.runId,- owner: row.lease.owner,+ if (!sourceLease) return;+ if (!sourceLease.lease) {+ await discardInvalidReviewSourceLease(dbClient, sourceLease);+ log.warn('discarded malformed Review source lease', {+ sourceSessionId,+ leaseRowId: sourceLease.id,});+ return;}+ if (!(await hasReviewOwnerProcessEnded(sourceLease.lease.owner, reviewRunOwner))) return;+ await releaseReviewSourceLease(dbClient, {+ sourceSessionId,+ runId: sourceLease.lease.runId,+ owner: sourceLease.lease.owner,+ });};const sourceHasPersistedRunningReview = async (sourceSessionId: string): Promise<boolean> => {- const rows = await getDbClient()- .drizzle.select({ agentMeta: messages.agentMeta })- .from(messages)- .where(- and(- eq(messages.sessionId, sourceSessionId),- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- sql`${messages.agentMeta} LIKE '%"reviewRun"%'`,- ),- );+ const rows = await readSourceReviewCards(sourceSessionId);return rows.some((row) => readReviewRunFromAgentMeta(row.agentMeta)?.status === 'running');};const sourceHasActiveTurn = async (sourceSessionId: string): Promise<boolean> => {@@ -8134,15 +8135,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return sessionTurnLeaseTracker.isTurnActive(sourceSessionId);};- const ensureReviewStartupReady = createRetryableReviewStartup(async () => {+ // This is ordinary attachment hygiene rather than Review recovery. Keep its+ // existing startup behavior while Review-specific work remains on demand.+ void cleanupOrphanedTempAttachments({ currentOwner: reviewRunOwner }).catch((error) => {+ log.warn('failed to clean orphaned temporary attachments', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+ const ensureReviewRuntimeReady = createRetryableReviewInitialization(async () => {try {await ensureReviewOwnerLivenessReady();- await Promise.all([- reconcileInterruptedReviews(),- sessionTurnLeaseTracker.reconcileStaleLeases(),- cleanupOrphanedReviewArtifactSnapshots({ currentOwner: reviewRunOwner }),- cleanupOrphanedTempAttachments({ currentOwner: reviewRunOwner }),- ]);+ await cleanupOrphanedReviewArtifactSnapshots({ currentOwner: reviewRunOwner });} catch (error) {log.error('failed to prepare Review runtime state', {error: error instanceof Error ? error.message : String(error),@@ -8150,11 +8153,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throw error;}});- // Registration happens before the renderer can invoke /review. Keep a- // rejection observer here so a startup database failure is logged without- // becoming an unhandled promise. A rejected attempt is forgotten so a later- // START_REVIEW can retry the full reconciliation and still fail closed.- void ensureReviewStartupReady().catch(() => {});const readLatestReviewerResult = async (reviewerSessionId: string): Promise<string> => {const rows = await getDbClient()@@ -8176,15 +8174,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return '';};- registerReviewStartHandler(makerSessionRegistry, {+ const reviewRunControl = registerReviewStartHandler(makerSessionRegistry, {assertCaller: (event) =>assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),- waitUntilReady: async () => {- await ensureReviewStartupReady();- // A supported shared-userData peer can exit after this instance starts.- // Recheck ownership immediately before each run so its stale card can be- // failed, while a still-live peer remains protected by the DB-backed gate.- await reconcileInterruptedReviews();+ waitUntilReady: async (sourceSessionId) => {+ await ensureReviewRuntimeReady();+ // Recover only this task when the user explicitly starts Review again.+ // A live or ambiguous peer remains protected by the DB-backed gate.+ await reconcileReviewForSource(sourceSessionId);},createRunId: randomUUID,createReviewerSessionId: randomUUID,@@ -13788,8 +13785,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sid: string,remote: boolean,opts: unknown,+ intent: 'external-input' | 'stop' = 'external-input',): Promise<MainOwnedInputBoundaryStamp> => {- await assertReviewExternalInputAllowed(sid);+ // Stop is lifecycle control rather than external input. Keep the exception+ // local-only: this Review version does not expand Device Link control.+ if (intent !== 'stop' || remote) 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@@ -14207,7 +14207,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.INPUT_STOP, async (_e, sessionId: unknown, opts?: unknown) => {const sid = requireSessionId(sessionId);- await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ const remote = isDeviceLinkInvoke();+ await assertRemoteInputControlBoundary(sid, remote, opts, 'stop');+ if (!remote) reviewRunControl.noteReviewerStopRequested(sid);// Main 是本机窗口与 Device Link 控制端的 Stop 汇合点;先记账再触发 abort,// 任何 renderer 后续请求推荐都会从同一 ledger fail-closed。notePromptPredictionSessionStopped(sid);diff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.tsindex cebbf72061..3b268dd4ab 100644--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts@@ -9,11 +9,12 @@ import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation';import type { ReviewAttachmentInput } from '../reviewer/reviewEvidence.js';-import type {- ReviewFailureCode,- ReviewRunMeta,- ReviewRunOwner,- ReviewTargetKind,+import {+ isStaleReviewFailureCode,+ type ReviewFailureCode,+ type ReviewRunMeta,+ type ReviewRunOwner,+ type ReviewTargetKind,} from '../../shared/reviewRun.js';import { throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';@@ -137,7 +138,7 @@ export interface PreparedReviewLaunch {reviewerCreateOpts: MakerSessionCreateOpts;/** Fail closed if evidence changed after extraction but before provider start. */verifyBeforeStart(): Promise<ReviewFailureReason | null>;- /** Return a user-facing failure reason instead of publishing a stale result. */+ /** Return why a completed result no longer represents the current source state. */verifyBeforePublish(): Promise<ReviewFailureReason | null>;}@@ -171,7 +172,7 @@ export interface ReviewCardWrite {export interface ReviewStartHandlerDeps {assertCaller(event: unknown): void;- waitUntilReady(): Promise<void>;+ waitUntilReady(sourceSessionId: string): Promise<void>;createRunId(): string;createReviewerSessionId(): string;owner: ReviewRunOwner;@@ -211,6 +212,11 @@ export interface ReviewStartHandlerDeps {warn(message: string, fields: Record<string, unknown>): void;}+export interface ReviewRunControl {+ /** Record local user intent before the shared input coordinator aborts the Reviewer turn. */+ noteReviewerStopRequested(reviewerSessionId: string): boolean;+}+function terminalErrorDetails(event: AgentEvent): {error?: string;failureCode?: ReviewFailureCode;@@ -221,6 +227,12 @@ function terminalErrorDetails(event: AgentEvent): {: { failureCode: 'provider-failed' };}+function isCancelledReviewDone(event: AgentEvent): boolean {+ if (event.type !== 'done') return false;+ const data = event.data as { cancelled?: unknown } | null;+ return data?.cancelled === true;+}+export class ReviewPreconditionError extends Error {constructor(readonly reason: ReviewFailureReason) {super(reason.message);@@ -241,13 +253,14 @@ const REVIEW_TERMINAL_CARD_RETRY_MAX_MS = 5_000;export function registerReviewStartHandler(registry: IpcHandlerRegistry,deps: ReviewStartHandlerDeps,-): void {+): ReviewRunControl {const activeReviewsBySource = new Map<string, { runId: string; reviewerSessionId: string }>();+ const activeStopNotifiersByReviewer = new Map<string, () => boolean>();registry.handle(MAKER_INVOKE.START_REVIEW, async (event, raw: unknown) => {deps.assertCaller(event);- await deps.waitUntilReady();const request = readStartReviewRequest(raw);+ await deps.waitUntilReady(request.sourceSessionId);if (activeReviewsBySource.has(request.sourceSessionId)) {throwIpcError('SESSION_RUNNING', 'This task already has a review in progress');}@@ -277,6 +290,13 @@ export function registerReviewStartHandler(let pendingTerminalCard: ReviewCardWrite | null = null;let terminalCardPersisted = false;let sourceCardWriteChain = Promise.resolve();+ let stopRequested = false;+ const noteStopRequested = (): boolean => {+ if (settled) return false;+ stopRequested = true;+ return true;+ };+ activeStopNotifiersByReviewer.set(reviewerSessionId, noteStopRequested);const enqueueSourceCardWrite = (write: () => Promise<void>): Promise<void> => {const next = sourceCardWriteChain.then(write, write);@@ -332,6 +352,9 @@ export function registerReviewStartHandler(releaseRetryDelayMs = REVIEW_SOURCE_LEASE_RELEASE_RETRY_MS;const active = activeReviewsBySource.get(request.sourceSessionId);if (active?.runId === runId) activeReviewsBySource.delete(request.sourceSessionId);+ if (activeStopNotifiersByReviewer.get(reviewerSessionId) === noteStopRequested) {+ activeStopNotifiersByReviewer.delete(reviewerSessionId);+ }})();releasePromise = pending;void pending.finally(() => {@@ -487,6 +510,11 @@ export function registerReviewStartHandler(settlementCause = 'provider-terminal';disposeReviewerListeners();terminalFinalization = (async () => {+ if (stopRequested || isCancelledReviewDone(reviewEvent)) {+ await updateSourceCard('failed', '', undefined, 'reviewer-closed');+ await closeReviewer();+ return;+ }if (terminalError) {const details = terminalErrorDetails(reviewEvent);await updateSourceCard('failed', '', details.error, details.failureCode);@@ -502,7 +530,14 @@ export function registerReviewStartHandler(}const staleReason = await launch.verifyBeforePublish();if (staleReason) {- await updateSourceCard('failed', '', staleReason.message, staleReason.code);+ if (isStaleReviewFailureCode(staleReason.code)) {+ // Keep the persisted status readable by older clients. The stable+ // reason code distinguishes an out-of-date completed result from+ // a Reviewer execution failure in current clients.+ await updateSourceCard('failed', result, staleReason.message, staleReason.code);+ } else {+ await updateSourceCard('failed', '', staleReason.message, staleReason.code);+ }await closeReviewer();return;}@@ -646,4 +681,9 @@ export function registerReviewStartHandler(throw error;}});++ return {+ noteReviewerStopRequested: (reviewerSessionId) =>+ activeStopNotifiersByReviewer.get(reviewerSessionId)?.() ?? false,+ };}diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts b/apps/desktop/src/main/maker-ipc/sessionTurnLease.tsindex 4917bce68b..efbe073d76 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts@@ -184,6 +184,34 @@ export async function replaceSessionTurnLease(return result.changes === 1;}+/** Refresh one live generation's owner proof without changing its turn identity. */+export async function refreshSessionTurnLeaseOwner(+ dbClient: Pick<DbClient, 'exec'>,+ input: {+ sessionId: string;+ turnId: string;+ owner: ReviewRunOwner;+ },+): Promise<boolean> {+ const lease: SessionTurnLease = {+ version: 1,+ turnId: input.turnId,+ owner: input.owner,+ };+ const result = await dbClient.exec(+ `UPDATE messages+ SET agent_meta = ?+ WHERE session_id = ? AND client_id = ? AND content = ?`,+ [+ sessionTurnLeaseAgentMeta(lease),+ input.sessionId,+ sessionTurnLeaseClientId(input.owner),+ sessionTurnLeaseToken(lease),+ ],+ );+ return result.changes === 1;+}+/** Delete only the exact turn that acquired the row; a delayed end cannot delete its successor. */export async function releaseSessionTurnLease(dbClient: Pick<DbClient, 'exec'>,@@ -198,9 +226,10 @@ export async function releaseSessionTurnLease(return result.changes === 1;}-export async function listPersistedSessionTurnLeases(+/** Read and recover turn leases only when that exact task needs them. */+export async function readPersistedSessionTurnLeases(dbClient: Pick<DbClient, 'query'>,- sessionId?: string,+ sessionId: string,): Promise<PersistedSessionTurnLeaseRow[]> {const rows = await dbClient.query<{id: string;@@ -210,10 +239,8 @@ export async function listPersistedSessionTurnLeases(}>(`SELECT id, client_id AS clientId, session_id AS sessionId, agent_meta AS agentMetaFROM messages- WHERE client_id LIKE ?${sessionId ? ' AND session_id = ?' : ''}`,- sessionId- ? [`${SESSION_TURN_LEASE_CLIENT_ID_PREFIX}%`, sessionId]- : [`${SESSION_TURN_LEASE_CLIENT_ID_PREFIX}%`],+ WHERE session_id = ? AND client_id LIKE ?`,+ [sessionId, `${SESSION_TURN_LEASE_CLIENT_ID_PREFIX}%`],);return rows.map((row) => ({id: row.id,@@ -223,13 +250,6 @@ export async function listPersistedSessionTurnLeases(}));}-export function readPersistedSessionTurnLeases(- dbClient: Pick<DbClient, 'query'>,- sessionId: string,-): Promise<PersistedSessionTurnLeaseRow[]> {- return listPersistedSessionTurnLeases(dbClient, sessionId);-}-/** Remove a malformed row only while its immutable id still identifies the same lease row. */export async function discardInvalidSessionTurnLease(dbClient: Pick<DbClient, 'exec'>,@@ -378,6 +398,26 @@ export class SessionTurnLeaseTracker {});}+ /** Add newly available exact-instance liveness to this process's active leases only. */+ async refreshActiveLeaseOwners(): Promise<void> {+ const activeTurns = [...this.activeTurnIds.entries()];+ await Promise.all(+ activeTurns.map(([sessionId, turnId]) =>+ this.enqueue(sessionId, async () => {+ if (this.activeTurnIds.get(sessionId) !== turnId) return;+ const refreshed = await refreshSessionTurnLeaseOwner(this.deps.getDbClient(), {+ sessionId,+ turnId,+ owner: this.deps.owner,+ });+ if (!refreshed && this.activeTurnIds.get(sessionId) === turnId) {+ throw new Error('could not refresh the active turn lease owner');+ }+ }),+ ),+ );+ }+/** End one exact generation and report whether no local/shared successor remains. */async markTurnEndedAndCheckIdle(sessionId: string, expectedTurnId: string): Promise<boolean> {await this.markTurnEnded(sessionId, expectedTurnId);@@ -395,10 +435,4 @@ export class SessionTurnLeaseTracker {}return active;}-- async reconcileStaleLeases(): Promise<void> {- const dbClient = this.deps.getDbClient();- const rows = await listPersistedSessionTurnLeases(dbClient);- for (const row of rows) await this.clearRecoverableLease(dbClient, row);- }}diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactConfirmWindow.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactConfirmWindow.test.tsnew file mode 100644index 0000000000..d81c0028ac--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactConfirmWindow.test.ts@@ -0,0 +1,227 @@+import { EventEmitter } from 'node:events';++import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { ReviewArtifactConfirmDialogModel } from '../reviewArtifactDialog.js';+import {+ buildReviewArtifactConfirmDocument,+ showReviewArtifactConfirmWindow,+} from '../reviewArtifactConfirmWindow.js';+import { isReviewArtifactConfirmWebContentsId } from '../reviewArtifactConfirmWindowRegistry.js';++const MODEL: ReviewArtifactConfirmDialogModel = {+ title: 'Allow review?',+ message: 'One item is outside the workspace.',+ detail: 'Review the item before allowing access.',+ items: [+ { kind: 'external-path', label: 'report.pdf', path: 'D:\\outside\\report.pdf' },+ { kind: 'inline', label: 'notes.txt', inlineLabel: 'inline attachment' },+ ],+ allowText: 'Allow',+ cancelText: 'Cancel',+};++let nextWebContentsId = 1_000;++class FakeWebContents extends EventEmitter {+ readonly id = nextWebContentsId++;+ loadedUrl = '';+ openHandler: (() => { action: 'deny' }) | null = null;++ setWindowOpenHandler(handler: () => { action: 'deny' }): void {+ this.openHandler = handler;+ }+}++class FakeWindow extends EventEmitter {+ readonly webContents = new FakeWebContents();+ destroyed = false;+ shown = false;+ focused = false;++ isDestroyed(): boolean {+ return this.destroyed;+ }++ destroy(): void {+ if (this.destroyed) return;+ this.destroyed = true;+ this.emit('closed');+ }++ show(): void {+ this.shown = true;+ }++ focus(): void {+ this.focused = true;+ }++ loadURL(url: string): Promise<void> {+ this.webContents.loadedUrl = url;+ return Promise.resolve();+ }+}++function createHarness(timeoutMs = 60_000) {+ const parent = new FakeWindow();+ const dialog = new FakeWindow();+ let windowOptions: BrowserWindowConstructorOptions | null = null;+ const result = showReviewArtifactConfirmWindow(+ parent as unknown as BrowserWindow,+ MODEL,+ {+ timeoutMs,+ isDark: false,+ createWindow: (options) => {+ windowOptions = options;+ return dialog as unknown as BrowserWindow;+ },+ },+ );+ return { parent, dialog, result, getWindowOptions: () => windowOptions };+}++function readEmbeddedStylesheet(document: string): string {+ const match = document.match(+ /<link rel="stylesheet" href="data:text\/css;base64,([^"]+)">/,+ );+ expect(match).not.toBeNull();+ return Buffer.from(match?.[1] ?? '', 'base64').toString('utf8');+}++afterEach(() => {+ vi.useRealTimers();+});++describe('Review artifact confirmation window', () => {+ it('escapes every model field and keeps the document script-free', () => {+ const document = buildReviewArtifactConfirmDocument(+ {+ ...MODEL,+ title: '<img src=x onerror=alert(1)>',+ message: '</title><script>alert(1)</script>',+ items: [+ {+ kind: 'external-path',+ label: '<svg onload=alert(1)>',+ path: 'D:\\<script>bad</script>',+ },+ ],+ },+ true,+ );++ expect(document).toContain('data-theme="dark"');+ expect(document).toContain("default-src 'none'; style-src data:");+ expect(document).not.toContain("'unsafe-inline'");+ expect(document).not.toContain('<script>');+ expect(document).not.toContain('<img');+ expect(document).not.toContain('<svg');+ expect(document).toContain('<script>bad</script>');+ expect(document).toContain('class="button primary" href="#allow" autofocus');+ expect(document).not.toContain('href="#cancel" autofocus');+ });++ it('uses a hardened modal with no preload or renderer authorization bridge', async () => {+ const harness = createHarness();+ const options = harness.getWindowOptions();++ expect(options).toMatchObject({+ parent: harness.parent,+ modal: true,+ show: false,+ backgroundColor: '#f8f8f6',+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ navigateOnDragDrop: false,+ },+ });+ expect(options?.webPreferences).not.toHaveProperty('preload');+ expect(harness.dialog.webContents.openHandler?.()).toEqual({ action: 'deny' });+ expect(isReviewArtifactConfirmWebContentsId(harness.dialog.webContents.id)).toBe(true);++ harness.dialog.emit('ready-to-show');+ expect(harness.dialog.shown).toBe(true);+ expect(harness.dialog.focused).toBe(true);++ const preventDefault = vi.fn();+ harness.dialog.webContents.emit('will-navigate', { preventDefault }, 'https://example.com');+ expect(preventDefault).toHaveBeenCalledOnce();++ harness.dialog.webContents.emit(+ 'did-navigate-in-page',+ {},+ `${harness.dialog.webContents.loadedUrl}#allow`,+ true,+ );+ await expect(harness.result).resolves.toBe(true);+ expect(harness.dialog.destroyed).toBe(true);+ });++ it('keeps consent copy and actions visible while artifact details scroll', () => {+ const document = buildReviewArtifactConfirmDocument(+ {+ ...MODEL,+ items: Array.from({ length: 20 }, (_, index) => ({+ kind: 'external-path' as const,+ label: `artifact-${index}.pdf`,+ path: `D:\\outside\\${'deeply-nested\\'.repeat(20)}artifact-${index}.pdf`,+ })),+ },+ false,+ );+ const stylesheet = readEmbeddedStylesheet(document);++ expect(stylesheet).toContain('height: 100%; overflow: hidden');+ expect(stylesheet).toContain('height: 100vh; min-height: 0');+ expect(stylesheet).toContain(+ 'ul { flex: 1; min-height: 0; margin: 0; padding: 0; overflow-y: auto;',+ );+ expect(stylesheet).toContain('footer { display: flex; flex: none;');+ });++ it('fails closed on cancel, timeout, parent close, and renderer failure', async () => {+ const cancelled = createHarness();+ cancelled.dialog.webContents.emit(+ 'did-navigate-in-page',+ {},+ `${cancelled.dialog.webContents.loadedUrl}#cancel`,+ true,+ );+ await expect(cancelled.result).resolves.toBe(false);++ vi.useFakeTimers();+ const timedOut = createHarness(10);+ await vi.advanceTimersByTimeAsync(10);+ await expect(timedOut.result).resolves.toBe(false);+ expect(timedOut.dialog.destroyed).toBe(true);++ const parentClosed = createHarness();+ parentClosed.parent.emit('closed');+ await expect(parentClosed.result).resolves.toBe(false);++ const rendererGone = createHarness();+ rendererGone.dialog.webContents.emit('render-process-gone');+ await expect(rendererGone.result).resolves.toBe(false);++ const escaped = createHarness();+ const preventDefault = vi.fn();+ escaped.dialog.webContents.emit(+ 'before-input-event',+ { preventDefault },+ { type: 'keyDown', key: 'Escape' },+ );+ await expect(escaped.result).resolves.toBe(false);+ expect(preventDefault).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactDialog.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactDialog.test.tsindex 1a2458c199..630f8ca310 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactDialog.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactDialog.test.ts@@ -12,7 +12,7 @@ const translations: Record<string, string> = {};describe('review external-artifact dialog', () => {- it('fails closed by default and lists every authorized path', () => {+ it('provides explicit cancel copy and lists every authorized path', () => {const items = Array.from({ length: 20 }, (_, index) => ({kind: 'external-path' as const,label: `contract-${index + 1}.pdf`,@@ -20,13 +20,12 @@ describe('review external-artifact dialog', () => {}));const options = buildReviewArtifactConfirmationDialog(items, (key) => translations[key] ?? key);- expect(options.buttons).toEqual(['Cancel', 'Allow']);- expect(options.defaultId).toBe(0);- expect(options.cancelId).toBe(0);- expect(options.detail).toContain('/outside/contract-1.pdf');- expect(options.detail).toContain('/outside/contract-11.pdf');- expect(options.detail).toContain('/outside/contract-20.pdf');- expect(options.detail).not.toContain('and 10 more');+ expect(options.cancelText).toBe('Cancel');+ expect(options.allowText).toBe('Allow');+ expect(options.items).toHaveLength(20);+ expect(options.items[0]).toMatchObject({ path: '/outside/contract-1.pdf' });+ expect(options.items[10]).toMatchObject({ path: '/outside/contract-11.pdf' });+ expect(options.items[19]).toMatchObject({ path: '/outside/contract-20.pdf' });});it('flattens control and bidi characters in labels and paths', () => {@@ -41,7 +40,9 @@ describe('review external-artifact dialog', () => {(key) => translations[key] ?? key,);- expect(options.detail).toContain('safe.pdf Hidden');- expect(options.detail).toContain('/outside/safe.pdf spoofed');+ expect(options.items[0]).toMatchObject({+ label: 'safe.pdf Hidden',+ path: '/outside/safe.pdf spoofed',+ });});});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.tsindex 7058ede05d..59909bca69 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts@@ -26,6 +26,27 @@ describe('Review external input wiring', () => {}});+ it('allows only local Stop through the Review input guard', () => {+ expect(registerSource).toMatch(+ /if \(intent !== 'stop' \|\| remote\) await assertReviewExternalInputAllowed\(sid\);/,+ );+ const stopHandlerStart = registerSource.indexOf(+ 'ipcMain.handle(MAKER_INVOKE.INPUT_STOP',+ );+ const stopHandlerEnd = registerSource.indexOf(+ 'ipcMain.handle(MAKER_INVOKE.INPUT_RESUME',+ stopHandlerStart,+ );+ const stopHandler = registerSource.slice(stopHandlerStart, stopHandlerEnd);+ expect(stopHandler).toContain('const remote = isDeviceLinkInvoke();');+ expect(stopHandler).toContain(+ "await assertRemoteInputControlBoundary(sid, remote, opts, 'stop');",+ );+ expect(stopHandler).toContain(+ 'if (!remote) reviewRunControl.noteReviewerStopRequested(sid);',+ );+ });+it('also rejects local cross-task and Orca delivery into Review tasks', () => {expect(registerSource).toMatch(/async function sendToSessionInternal[\s\S]*?await assertReviewExternalInputAllowed\(targetSessionId\);/,@@ -127,18 +148,47 @@ describe('Review external input wiring', () => {);});- it('retries failed startup reconciliation before admitting another Review', () => {- expect(registerSource.match(/createRetryableReviewStartup\(/g)).toHaveLength(2);- expect(registerSource).toContain('void ensureReviewStartupReady().catch(() => {});');- expect(registerSource).toMatch(- /waitUntilReady: async \(\) => \{\s+await ensureReviewStartupReady\(\);\s+[\s\S]*?await reconcileInterruptedReviews\(\);/,+ it('prepares Review on demand and reconciles only the requested source task', () => {+ expect(registerSource.match(/createRetryableReviewInitialization\(/g)).toHaveLength(2);+ expect(registerSource).not.toContain('void ensureReviewRuntimeReady().catch(() => {});');+ expect(registerSource).not.toContain('reconcileStaleLeases');+ expect(registerSource).not.toContain(`LIKE '%"reviewRun"%'`);+ expect(registerSource).toContain(+ 'await sessionTurnLeaseTracker.refreshActiveLeaseOwners();',+ );+ expect(registerSource).toContain(+ 'void cleanupOrphanedTempAttachments({ currentOwner: reviewRunOwner }).catch',+ );+ const wireSessionStart = registerSource.indexOf('export function wireSessionToIpc');+ const wireSessionEnd = registerSource.indexOf(+ 'export const wireSessionToIpcExternal',+ wireSessionStart,+ );+ expect(registerSource.slice(wireSessionStart, wireSessionEnd)).not.toContain(+ 'ensureReviewOwnerLivenessReady()',);- const reconcileStart = registerSource.indexOf('const reconcileInterruptedReviews');+ expect(reviewStartSource.indexOf('const request = readStartReviewRequest(raw);')).toBeLessThan(+ reviewStartSource.indexOf('await deps.waitUntilReady(request.sourceSessionId);'),+ );+ expect(registerSource).toMatch(+ /waitUntilReady: async \(sourceSessionId\) => \{\s+await ensureReviewRuntimeReady\(\);\s+[\s\S]*?await reconcileReviewForSource\(sourceSessionId\);/,+ );+ const sourceReadStart = registerSource.indexOf('const readSourceReviewCards');+ const sourceReadEnd = registerSource.indexOf('const reconcileReviewForSource', sourceReadStart);+ const sourceRead = registerSource.slice(sourceReadStart, sourceReadEnd);+ expect(sourceRead).toContain('eq(messages.sessionId, sourceSessionId)');+ expect(sourceRead).toContain("gte(messages.clientId, 'review:')");+ expect(sourceRead).toContain("lt(messages.clientId, 'review;')");++ const reconcileStart = registerSource.indexOf('const reconcileReviewForSource');const reconcileEnd = registerSource.indexOf('const sourceHasPersistedRunningReview',reconcileStart,);const reconcileSource = registerSource.slice(reconcileStart, reconcileEnd);+ expect(reconcileSource).toContain(+ 'readPersistedReviewSourceLease(dbClient, sourceSessionId)',+ );expect(reconcileSource.indexOf('patchMessageAgentMeta')).toBeLessThan(reconcileSource.indexOf('releaseReviewSourceLease'),);diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.tsindex 0fd0dfd753..8c7f3b45f9 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewRunRecovery.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import type { ReviewRunMeta, ReviewRunOwner } from '../../../shared/reviewRun.js';import {- createRetryableReviewStartup,+ createRetryableReviewInitialization,shouldFailInterruptedReview,} from '../reviewRunRecovery.js';@@ -22,7 +22,7 @@ function running(owner?: ReviewRunOwner): ReviewRunMeta {}describe('Review run recovery ownership', () => {- it('coalesces startup reconciliation and retries after a transient failure', async () => {+ it('coalesces on-demand initialization and retries after a transient failure', async () => {let rejectFirst!: (error: Error) => void;const firstAttempt = new Promise<void>((_resolve, reject) => {rejectFirst = reject;@@ -31,7 +31,7 @@ describe('Review run recovery ownership', () => {.fn<() => Promise<void>>().mockImplementationOnce(() => firstAttempt).mockResolvedValue(undefined);- const ensureReady = createRetryableReviewStartup(start);+ const ensureReady = createRetryableReviewInitialization(start);const first = ensureReady();const concurrent = ensureReady();diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.tsindex 4fc02d2e11..4b8e12407e 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts@@ -8,7 +8,7 @@ import { afterEach, describe, expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';import {discardInvalidReviewSourceLease,- listPersistedReviewSourceLeases,+ readPersistedReviewSourceLease,releaseReviewSourceLease,REVIEW_SOURCE_LEASE_CLIENT_ID,tryAcquireReviewSourceLease,@@ -47,7 +47,7 @@ describe('Review source lease', () => {);CREATE UNIQUE INDEX uniq_messages_session_clientON messages(session_id, client_id);- INSERT INTO sessions (id, status) VALUES ('source-1', 'active');+ INSERT INTO sessions (id, status) VALUES ('source-1', 'active'), ('source-2', 'active');`);const second = new Database(dbPath);second.pragma('foreign_keys = ON');@@ -98,9 +98,8 @@ describe('Review source lease', () => {const loser = acquired[0]? { client: second, runId: 'run-2', owner: secondOwner }: { client: first, runId: 'run-1', owner: firstOwner };- const rows = await listPersistedReviewSourceLeases(second);- expect(rows).toHaveLength(1);- expect(rows[0]?.lease).toMatchObject({ runId: winner.runId, owner: winner.owner });+ const row = await readPersistedReviewSourceLease(second, 'source-1');+ expect(row?.lease).toMatchObject({ runId: winner.runId, owner: winner.owner });await expect(releaseReviewSourceLease(loser.client, {@@ -126,6 +125,29 @@ describe('Review source lease', () => {).resolves.toBe(true);});+ it('reads only the requested source task lease', async () => {+ const { first } = setup();+ const owner = { instanceId: 'first', processId: 101 };+ await tryAcquireReviewSourceLease(first, {+ sourceSessionId: 'source-1',+ runId: 'run-1',+ owner,+ createdAt: 1,+ });+ await tryAcquireReviewSourceLease(first, {+ sourceSessionId: 'source-2',+ runId: 'run-2',+ owner,+ createdAt: 2,+ });++ await expect(readPersistedReviewSourceLease(first, 'source-1')).resolves.toMatchObject({+ sourceSessionId: 'source-1',+ lease: { runId: 'run-1' },+ });+ await expect(readPersistedReviewSourceLease(first, 'missing')).resolves.toBeNull();+ });+it('reclaims a malformed hidden lease by immutable row id', async () => {const { first, raw } = setup();raw@@ -136,9 +158,9 @@ describe('Review source lease', () => {).run(REVIEW_SOURCE_LEASE_CLIENT_ID);- const [row] = await listPersistedReviewSourceLeases(first);+ const row = await readPersistedReviewSourceLease(first, 'source-1');expect(row?.lease).toBeNull();await expect(discardInvalidReviewSourceLease(first, row!)).resolves.toBe(true);- await expect(listPersistedReviewSourceLeases(first)).resolves.toEqual([]);+ await expect(readPersistedReviewSourceLease(first, 'source-1')).resolves.toBeNull();});});diff --git a/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts b/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.tsnew file mode 100644index 0000000000..730b8153a5--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts@@ -0,0 +1,273 @@+import {+ BrowserWindow,+ nativeTheme,+ type BrowserWindowConstructorOptions,+} from 'electron';++import { resolveAppThemeIsDark } from '../resolved-app-theme.js';+import { readWindowThemeSnapshot } from '../window-theme-mode-store.js';+import type { ReviewArtifactConfirmDialogModel } from './reviewArtifactDialog.js';+import { markReviewArtifactConfirmWebContentsId } from './reviewArtifactConfirmWindowRegistry.js';++const DEFAULT_TIMEOUT_MS = 90_000;++export interface ReviewArtifactConfirmWindowOptions {+ timeoutMs?: number;+ isDark?: boolean;+ createWindow?: (options: BrowserWindowConstructorOptions) => BrowserWindow;+ log?: { warn(message: string, meta?: Record<string, unknown>): void };+}++function escapeHtml(value: string): string {+ return value.replace(+ /[&<>"']/g,+ (character) =>+ ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ })[character] ?? character,+ );+}++const DIALOG_CSS = `+:root {+ color-scheme: light;+ --surface: #f8f8f6;+ --surface-raised: #ffffff;+ --text: #252523;+ --muted: #696966;+ --border: #deded9;+ --accent: #252523;+ --accent-text: #ffffff;+ --hover: #efefeb;+}+:root[data-theme='dark'] {+ color-scheme: dark;+ --surface: #1f1f1e;+ --surface-raised: #292927;+ --text: #f1f1ed;+ --muted: #aaa9a3;+ --border: #41413d;+ --accent: #f1f1ed;+ --accent-text: #242422;+ --hover: #333330;+}+* { box-sizing: border-box; }+html, body { margin: 0; height: 100%; overflow: hidden; background: var(--surface); color: var(--text); }+body { font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }+main { display: flex; height: 100vh; min-height: 0; flex-direction: column; padding: 28px; }+.brand { margin: 0 0 12px; color: var(--muted); font-size: 12px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; }+h1 { margin: 0; font-size: 20px; font-weight: 600; line-height: 1.3; }+.message { margin: 8px 0 0; color: var(--muted); font-size: 14px; line-height: 1.55; }+.detail { margin: 24px 0 10px; font-size: 13px; line-height: 1.5; }+ul { flex: 1; min-height: 0; margin: 0; padding: 0; overflow-y: auto; list-style: none; }+li { margin-top: 8px; padding: 11px 12px; border: 1px solid var(--border); border-radius: 9px; background: var(--surface-raised); }+.label { overflow-wrap: anywhere; font-size: 13px; font-weight: 500; }+.path { margin-top: 4px; overflow-wrap: anywhere; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; }+footer { display: flex; flex: none; justify-content: flex-end; gap: 10px; margin-top: auto; padding-top: 26px; }+.button { display: inline-flex; min-width: 88px; height: 36px; align-items: center; justify-content: center; border: 1px solid var(--border); border-radius: 8px; color: var(--text); font-size: 13px; font-weight: 600; text-decoration: none; }+.button:hover, .button:focus-visible { background: var(--hover); outline: none; }+.primary { border-color: var(--accent); background: var(--accent); color: var(--accent-text); }+.primary:hover, .primary:focus-visible { background: var(--accent); opacity: .88; }+`;++/** Build a script-free document whose only decisions are same-document fragments. */+export function buildReviewArtifactConfirmDocument(+ model: ReviewArtifactConfirmDialogModel,+ isDark: boolean,+): string {+ const stylesheet = `data:text/css;base64,${Buffer.from(DIALOG_CSS).toString('base64')}`;+ const items = model.items+ .map((item) => {+ const secondary =+ item.kind === 'external-path'+ ? item.path+ : item.inlineLabel;+ return `<li><div class="label">${escapeHtml(item.label)}</div>${+ secondary+ ? `<div class="path" dir="ltr">${escapeHtml(secondary)}</div>`+ : ''+ }</li>`;+ })+ .join('');+ return `<!doctype html>+<html lang="und" data-theme="${isDark ? 'dark' : 'light'}">+<head>+ <meta charset="utf-8">+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <link rel="stylesheet" href="${stylesheet}">+ <title>${escapeHtml(model.title)}</title>+</head>+<body>+ <main aria-labelledby="review-confirm-title">+ <p class="brand">Cindy</p>+ <h1 id="review-confirm-title">${escapeHtml(model.title)}</h1>+ <p class="message">${escapeHtml(model.message)}</p>+ <p class="detail">${escapeHtml(model.detail)}</p>+ <ul>${items}</ul>+ <footer>+ <a class="button" href="#cancel">${escapeHtml(model.cancelText)}</a>+ <a class="button primary" href="#allow" autofocus>${escapeHtml(model.allowText)}</a>+ </footer>+ </main>+</body>+</html>`;+}++function readDecision(url: string): boolean | null {+ try {+ const hash = new URL(url).hash;+ if (hash === '#allow') return true;+ if (hash === '#cancel') return false;+ } catch {+ // Invalid or non-URL navigation is denied below.+ }+ return null;+}++/**+ * One authorization request owns one modal window. Reusing this security+ * prompt would risk carrying a stale parent, focus, or decision into another+ * grant, so it intentionally does not use the reusable auxiliary-tool window+ * lifecycle. The document has no preload, IPC, or script: an XSS in the main+ * app Renderer cannot observe or answer this prompt.+ */+export async function showReviewArtifactConfirmWindow(+ parent: BrowserWindow,+ model: ReviewArtifactConfirmDialogModel,+ options: ReviewArtifactConfirmWindowOptions = {},+): Promise<boolean> {+ if (parent.isDestroyed()) return false;+ const persistedTheme = options.isDark === undefined ? readWindowThemeSnapshot() : null;+ const isDark =+ options.isDark ??+ resolveAppThemeIsDark(+ nativeTheme.shouldUseDarkColors,+ persistedTheme?.mode,+ persistedTheme?.resolvedIsDark,+ );+ const createWindow = options.createWindow ?? ((windowOptions) => new BrowserWindow(windowOptions));+ let win: BrowserWindow;+ try {+ win = createWindow({+ parent,+ modal: true,+ width: 600,+ height: Math.min(720, 330 + model.items.length * 76),+ minWidth: 520,+ minHeight: 360,+ show: false,+ resizable: true,+ minimizable: false,+ maximizable: false,+ fullscreenable: false,+ autoHideMenuBar: true,+ title: model.title,+ backgroundColor: isDark ? '#1f1f1e' : '#f8f8f6',+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ spellcheck: false,+ navigateOnDragDrop: false,+ },+ });+ markReviewArtifactConfirmWebContentsId(win.webContents.id);+ } catch (error) {+ options.log?.warn('failed to create Review artifact confirmation window; access denied', {+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }++ return await new Promise<boolean>((resolve) => {+ let settled = false;+ let timeoutId: ReturnType<typeof setTimeout> | null = null;+ const settle = (confirmed: boolean): void => {+ if (settled) return;+ settled = true;+ if (timeoutId) clearTimeout(timeoutId);+ parent.removeListener('closed', onParentClosed);+ win.removeListener('closed', onClosed);+ win.removeListener('ready-to-show', onReadyToShow);+ win.webContents.removeListener('will-navigate', onWillNavigate);+ win.webContents.removeListener('did-navigate-in-page', onDidNavigateInPage);+ win.webContents.removeListener('before-input-event', onBeforeInput);+ win.webContents.removeListener('render-process-gone', onRendererGone);+ if (!win.isDestroyed()) win.destroy();+ resolve(confirmed);+ };+ const onParentClosed = (): void => settle(false);+ const onClosed = (): void => settle(false);+ const onReadyToShow = (): void => {+ if (win.isDestroyed()) return;+ // This data document is already complete and has no script or async+ // resources, so ready-to-show is also its business-content ready signal.+ win.show();+ win.focus();+ };+ const onWillNavigate = (event: { preventDefault(): void }): void => {+ event.preventDefault();+ };+ const onDidNavigateInPage = (+ _event: unknown,+ url: string,+ isMainFrame: boolean,+ ): void => {+ if (!isMainFrame) return;+ const decision = readDecision(url);+ if (decision !== null) settle(decision);+ };+ const onBeforeInput = (+ event: { preventDefault(): void },+ input: { type: string; key: string },+ ): void => {+ if (input.type !== 'keyDown' || input.key !== 'Escape') return;+ event.preventDefault();+ settle(false);+ };+ const onRendererGone = (): void => settle(false);++ parent.once('closed', onParentClosed);+ win.once('closed', onClosed);+ win.once('ready-to-show', onReadyToShow);+ win.webContents.on('will-navigate', onWillNavigate);+ win.webContents.on('did-navigate-in-page', onDidNavigateInPage);+ win.webContents.on('before-input-event', onBeforeInput);+ win.webContents.on('render-process-gone', onRendererGone);+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));++ timeoutId = setTimeout(() => {+ options.log?.warn('review artifact confirmation timed out; access denied');+ settle(false);+ }, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);+ timeoutId.unref?.();++ const document = buildReviewArtifactConfirmDocument(model, isDark);+ try {+ void win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(document)}`).catch(+ (error) => {+ options.log?.warn('failed to load Review artifact confirmation; access denied', {+ error: error instanceof Error ? error.message : String(error),+ });+ settle(false);+ },+ );+ } catch (error) {+ options.log?.warn('failed to load Review artifact confirmation; access denied', {+ error: error instanceof Error ? error.message : String(error),+ });+ settle(false);+ }+ });+}diff --git a/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindowRegistry.ts b/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindowRegistry.tsnew file mode 100644index 0000000000..a606261b7b--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewArtifactConfirmWindowRegistry.ts@@ -0,0 +1,17 @@+/**+ * Review artifact consent windows are isolated, independently disposable+ * renderers. Their local lifecycle fails the pending grant closed, so a crash+ * must not escalate into the main application's fatal renderer shutdown path.+ * WebContents ids are not reused within one Electron process; keeping this+ * registry add-only also covers the gone/closed event ordering race.+ */++const reviewArtifactConfirmWebContentsIds = new Set<number>();++export function markReviewArtifactConfirmWebContentsId(id: number): void {+ reviewArtifactConfirmWebContentsIds.add(id);+}++export function isReviewArtifactConfirmWebContentsId(id: number): boolean {+ return reviewArtifactConfirmWebContentsIds.has(id);+}diff --git a/apps/desktop/src/main/reviewer/reviewArtifactDialog.ts b/apps/desktop/src/main/reviewer/reviewArtifactDialog.tsindex 63311be258..90a264d911 100644--- a/apps/desktop/src/main/reviewer/reviewArtifactDialog.ts+++ b/apps/desktop/src/main/reviewer/reviewArtifactDialog.ts@@ -1,9 +1,23 @@-import type { MessageBoxOptions } from 'electron';-import type { ReviewArtifactConfirmationItem } from './reviewArtifactAuthorization.js';type Translate = (key: string) => string;+export interface ReviewArtifactConfirmItem {+ kind: 'external-path' | 'inline';+ label: string;+ path?: string;+ inlineLabel?: string;+}++export interface ReviewArtifactConfirmDialogModel {+ title: string;+ message: string;+ detail: string;+ items: ReviewArtifactConfirmItem[];+ allowText: string;+ cancelText: string;+}+function dialogLine(value: string, max = 600): string {return (value@@ -14,34 +28,33 @@ function dialogLine(value: string, max = 600): string {}/**- * Native consent is the final boundary before out-of-workspace bytes reach a- * configured model. Every item remains visible and Cancel owns both Enter and- * Escape so approval always requires an explicit click.+ * Main owns the consent copy and sanitizes every value before the isolated+ * Cindy consent window renders it. Every item remains visible and approval+ * requires an explicit click.*/export function buildReviewArtifactConfirmationDialog(items: readonly ReviewArtifactConfirmationItem[],translate: Translate,-): MessageBoxOptions {- const lines = items.map((item) => {+): ReviewArtifactConfirmDialogModel {+ const dialogItems = items.map((item) => {const label = dialogLine(item.label);return item.kind === 'external-path'- ? `• ${label}\n ${dialogLine(item.path ?? '', 1_200)}`- : `• ${label} (${translate('review.externalArtifactConfirm.inline')})`;+ ? { kind: item.kind, label, path: dialogLine(item.path ?? '', 1_200) }+ : {+ kind: item.kind,+ label,+ inlineLabel: translate('review.externalArtifactConfirm.inline'),+ };});return {- type: 'warning',title: translate('review.externalArtifactConfirm.title'),message: translate('review.externalArtifactConfirm.message').replace('{{count}}',String(items.length),),- detail: `${translate('review.externalArtifactConfirm.detail')}\n\n${lines.join('\n')}`,- buttons: [- translate('review.externalArtifactConfirm.cancel'),- translate('review.externalArtifactConfirm.allow'),- ],- defaultId: 0,- cancelId: 0,- noLink: true,+ detail: translate('review.externalArtifactConfirm.detail'),+ items: dialogItems,+ allowText: translate('review.externalArtifactConfirm.allow'),+ cancelText: translate('review.externalArtifactConfirm.cancel'),};}diff --git a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts b/apps/desktop/src/main/reviewer/reviewRunRecovery.tsindex 523cc4b3bd..369c98f45b 100644--- a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts+++ b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts@@ -11,10 +11,10 @@ export type ReviewOwnerLivenessProbe = (export type ReviewRunOwnerStatus = 'alive' | 'ended' | 'unknown';/**- * Coalesce concurrent startup reconciliation, but forget a rejected attempt so- * the next /review can recover from a transient database failure without an app restart.+ * Coalesce concurrent on-demand initialization, but forget a rejected attempt+ * so the next /review can recover from a transient failure without an app restart.*/-export function createRetryableReviewStartup(+export function createRetryableReviewInitialization(start: () => Promise<void>,): () => Promise<void> {let attempt: Promise<void> | null = null;diff --git a/apps/desktop/src/main/reviewer/reviewSourceLease.ts b/apps/desktop/src/main/reviewer/reviewSourceLease.tsindex fd0746a559..f8ffa612b2 100644--- a/apps/desktop/src/main/reviewer/reviewSourceLease.ts+++ b/apps/desktop/src/main/reviewer/reviewSourceLease.ts@@ -116,9 +116,11 @@ export async function releaseReviewSourceLease(return result.changes === 1;}-export async function listPersistedReviewSourceLeases(+/** Read one task's lease through the existing (session_id, client_id) index. */+export async function readPersistedReviewSourceLease(dbClient: Pick<DbClient, 'query'>,-): Promise<PersistedReviewSourceLeaseRow[]> {+ sourceSessionId: string,+): Promise<PersistedReviewSourceLeaseRow | null> {const rows = await dbClient.query<{id: string;sourceSessionId: string;@@ -126,14 +128,18 @@ export async function listPersistedReviewSourceLeases(}>(`SELECT id, session_id AS sourceSessionId, agent_meta AS agentMetaFROM messages- WHERE client_id = ?`,- [REVIEW_SOURCE_LEASE_CLIENT_ID],+ WHERE session_id = ? AND client_id = ?+ LIMIT 1`,+ [sourceSessionId, REVIEW_SOURCE_LEASE_CLIENT_ID],);- return rows.map((row) => ({- id: row.id,- sourceSessionId: row.sourceSessionId,- lease: readReviewSourceLeaseFromAgentMeta(row.agentMeta),- }));+ const row = rows[0];+ return row+ ? {+ id: row.id,+ sourceSessionId: row.sourceSessionId,+ lease: readReviewSourceLeaseFromAgentMeta(row.agentMeta),+ }+ : null;}/** Remove a malformed legacy/corrupt row only if its immutable id still matches. */diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex dc9b46a6af..e9a62d94f4 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5579,7 +5579,6 @@ contextBridge.exposeInMainWorld('electronAPI', {}>;}): Promise<{ ok: true; runId: string; reviewerSessionId: string }> =>ipcRenderer.invoke('maker:review:start', input),-listAgentCommands: (agentKind: 'claude-code' | 'codex' | 'pi',params: { sessionId?: string; allowManagedPiPackagePreview?: boolean } = {},diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 34af384c3f..7ad7f19e8a 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -373,7 +373,7 @@ export function App() {内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口都挂、谁收到谁弹,不按窗口类型 gate。 */}<GhostConfirmDialogHost />- <ForgeOidcInstallConfirmHost />+ <ForgeOidcInstallConfirmHost /><PluginPublisherConfirmHost /><OwnerScopedRouter /></EnvCheckGuard>diff --git a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.tsindex 075ea6c9a4..17ed2aa897 100644--- a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts+++ b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts@@ -10,6 +10,9 @@ const sessionViewSource = readFileSync(const dispatchStart = sessionViewSource.indexOf('const maybeDispatchDesktopSlashCommand');const dispatchEnd = sessionViewSource.indexOf('const maybeShowContextUsage', dispatchStart);const dispatchSource = sessionViewSource.slice(dispatchStart, dispatchEnd);+const handleSendStart = sessionViewSource.indexOf('const handleSend = useCallback');+const handleSendEnd = sessionViewSource.indexOf('const handleStopSession', handleSendStart);+const handleSendSource = sessionViewSource.slice(handleSendStart, handleSendEnd);describe('/review command dispatch', () => {it('crosses the Main boundary with this invocation attachment snapshot before returning', () => {@@ -67,4 +70,13 @@ describe('/review command dispatch', () => {expect(dispatchSource).toContain('pending.onDeferredAccepted?.();');expect(dispatchSource).toContain('waitForLeadHistory: false');});++ it('re-consumes an accepted desktop command without overwriting newer input', () => {+ expect(handleSendSource).toMatch(+ /if \(slashDispatch\.handled\) \{\s+if \(slashDispatch\.accepted\) \{\s+\/\/ Desktop commands[\s\S]*?opts\?\.onDeferredAccepted\?\.\(\);/,+ );+ expect(handleSendSource.indexOf('opts?.onDeferredAccepted?.();')).toBeLessThan(+ handleSendSource.indexOf('return slashDispatch.accepted;'),+ );+ });});diff --git a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsxindex 84ae503076..746b2c7b91 100644--- a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx+++ b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx@@ -17,8 +17,20 @@ vi.mock('@/features/learn/LearnStatusCard', () => ({}));vi.mock('@/components/chat/MarkdownRenderer', () => ({- MarkdownRenderer: ({ content, workingDir }: { content: string; workingDir: string }) => (- <div data-testid="review-markdown" data-working-dir={workingDir}>+ MarkdownRenderer: ({+ content,+ workingDir,+ allowPrivilegedLinks,+ }: {+ content: string;+ workingDir: string;+ allowPrivilegedLinks?: boolean;+ }) => (+ <div+ data-testid="review-markdown"+ data-working-dir={workingDir}+ data-allow-privileged-links={String(allowPrivilegedLinks)}+ >{content}</div>),@@ -59,11 +71,73 @@ describe('SystemCard Review', () => {const markdown = screen.getByTestId('review-markdown');expect(markdown.textContent).toContain('src/auth.ts:42');expect(markdown.getAttribute('data-working-dir')).toBe('/project');+ expect(markdown.getAttribute('data-allow-privileged-links')).toBe('true');fireEvent.click(screen.getByText('chat.systemCard.review.openTask'));expect(screen.getByTestId('location').textContent).toBe('/cc-agent/review-task');});+ it('renders a completed stale result with its rerun reason', () => {+ renderCard({+ status: 'failed',+ reviewerSessionId: 'review-task',+ failureCode: 'source-conversation-changed',+ result: 'P2: finding from the reviewed snapshot',+ });++ expect(screen.getByText('chat.systemCard.review.stale')).toBeTruthy();+ expect(+ screen.getByText('chat.systemCard.review.failure.sourceConversationChanged'),+ ).toBeTruthy();+ const markdown = screen.getByTestId('review-markdown');+ expect(markdown.textContent).toContain('reviewed snapshot');+ expect(markdown.getAttribute('data-allow-privileged-links')).toBe('false');+ expect(screen.getByText('chat.systemCard.review.openTask')).toBeTruthy();+ });++ it.each(['source-workspace-changed', 'source-files-changed', 'artifact-changed'])(+ 'does not resolve stale findings for %s against current files',+ (failureCode) => {+ renderCard({+ status: 'failed',+ reviewerSessionId: 'review-task',+ failureCode,+ result: 'P1: src/auth.ts:42 belongs to the reviewed snapshot',+ });++ const markdown = screen.getByTestId('review-markdown');+ expect(markdown.textContent).toContain('src/auth.ts:42');+ expect(markdown.getAttribute('data-working-dir')).toBe('/project');+ expect(markdown.getAttribute('data-allow-privileged-links')).toBe('false');+ },+ );++ it('renders a linked legacy stale failure as out of date without inventing result content', () => {+ renderCard({+ status: 'failed',+ reviewerSessionId: 'legacy-review-task',+ failureCode: 'source-conversation-changed',+ result: '',+ });++ expect(screen.getByText('chat.systemCard.review.stale')).toBeTruthy();+ expect(screen.queryByText('chat.systemCard.review.failed')).toBeNull();+ expect(screen.queryByTestId('review-markdown')).toBeNull();+ expect(screen.getByText('chat.systemCard.review.openTask')).toBeTruthy();+ });++ it('keeps a pre-start freshness failure as failed when no Reviewer task exists', () => {+ renderCard({+ status: 'failed',+ failureCode: 'artifact-changed',+ result: '',+ });++ expect(screen.getByText('chat.systemCard.review.failed')).toBeTruthy();+ expect(screen.queryByText('chat.systemCard.review.stale')).toBeNull();+ expect(screen.queryByText('chat.systemCard.review.openTask')).toBeNull();+ });+it('translates a stable persisted failure code ahead of internal diagnostic text', () => {renderCard({status: 'failed',diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex 3499d65e42..4292f1a2ae 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -25,6 +25,7 @@ import { Collapse } from '@/components/ui/collapse';import { Spinner } from '@/components/ui/spinner';import { LearnStatusCard } from '@/features/learn/LearnStatusCard';import {+ isStaleReviewFailureCode,readReviewFailureCode,reviewFailureCodeFromLegacyError,type ReviewFailureCode,@@ -1212,14 +1213,18 @@ const REVIEW_FAILURE_I18N_KEY: Record<ReviewFailureCode, string> = {function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; workingDir?: string }) {const { t } = useTranslation();const navigate = useNavigate();- const status =- data?.status === 'completed' || data?.status === 'failed' ? data.status : 'running';const reviewerSessionId =typeof data?.reviewerSessionId === 'string' ? data.reviewerSessionId : '';const result = typeof data?.result === 'string' ? data.result : '';const error = typeof data?.error === 'string' ? data.error : '';const failureCode =readReviewFailureCode(data?.failureCode) ?? reviewFailureCodeFromLegacyError(error);+ const status =+ data?.status === 'failed' && reviewerSessionId && isStaleReviewFailureCode(failureCode)+ ? 'stale'+ : data?.status === 'completed' || data?.status === 'failed'+ ? data.status+ : 'running';const failureMessage = failureCode? t(REVIEW_FAILURE_I18N_KEY[failureCode]): error || t('chat.systemCard.review.noResult');@@ -1231,6 +1236,8 @@ function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; work<Spinner size={15} className="text-muted-foreground" />) : status === 'completed' ? (<Check size={15} className="shrink-0 text-muted-foreground" />+ ) : status === 'stale' ? (+ <RefreshCw size={15} className="shrink-0 text-muted-foreground" />) : (<X size={15} className="shrink-0 text-[var(--error-fg)]" />)}@@ -1251,12 +1258,23 @@ function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; work{t('chat.systemCard.review.readOnlyHint')}</p>)}- {status === 'failed' && (- <p className="mt-1.5 pl-[23px] text-xs text-[var(--error-fg)]">{failureMessage}</p>+ {(status === 'stale' || status === 'failed') && (+ <p+ className={cn(+ 'mt-1.5 pl-[23px] text-xs',+ status === 'stale' ? 'text-muted-foreground' : 'text-[var(--error-fg)]',+ )}+ >+ {failureMessage}+ </p>)}- {status === 'completed' && result && (+ {(status === 'completed' || status === 'stale') && result && (<div className="mt-3 border-t border-border pt-3">- <MarkdownRenderer content={result} workingDir={workingDir ?? ''} />+ <MarkdownRenderer+ content={result}+ workingDir={workingDir ?? ''}+ allowPrivilegedLinks={status !== 'stale'}+ /></div>)}</div>diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex cd2a1b1331..18274696b5 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3178,14 +3178,20 @@ export function CCAgentSessionView({piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,});if (slashDispatch.handled) {- if (slashDispatch.accepted && sessionId) {- requestFollowLatest(sessionId, readSendFollowCancelGeneration(sessionId));- void dispatchDeferredUiAssignment(sessionId, undefined, {- waitForLeadHistory: false,- }).catch((err) => {- log.error('recover deferred Worker assignment after slash command failed', err);- toast.error(t('newChat.collaboration.assignmentFailed'));- });+ if (slashDispatch.accepted) {+ // Desktop commands can wait in Main long enough for draft hydration to+ // restore the click-time command. Re-consume only that snapshot after+ // acceptance; the callback preserves anything typed in the meantime.+ opts?.onDeferredAccepted?.();+ if (sessionId) {+ requestFollowLatest(sessionId, readSendFollowCancelGeneration(sessionId));+ void dispatchDeferredUiAssignment(sessionId, undefined, {+ waitForLeadHistory: false,+ }).catch((err) => {+ log.error('recover deferred Worker assignment after slash command failed', err);+ toast.error(t('newChat.collaboration.assignmentFailed'));+ });+ }}return slashDispatch.accepted;}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f683af6a95..3700922729 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7737,6 +7737,7 @@"review": {"running": "Reviewing current work","completed": "Review complete",+ "stale": "Review complete · result out of date","failed": "Review did not complete","openTask": "Open review task","readOnlyHint": "Independent task · no development memory · read-only",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 0ab0a35133..c67c875a2d 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7734,6 +7734,7 @@"review": {"running": "現在の成果をレビュー中","completed": "レビュー完了",+ "stale": "レビュー完了・結果は期限切れ","failed": "レビューを完了できませんでした","openTask": "レビュータスクを開く","readOnlyHint": "独立タスク・開発メモリなし・読み取り専用",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6062ecc580..bd1c1f9290 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7734,6 +7734,7 @@"review": {"running": "현재 결과물을 검토하는 중","completed": "검토 완료",+ "stale": "검토 완료 · 결과 만료됨","failed": "검토를 완료하지 못했습니다","openTask": "검토 작업 열기","readOnlyHint": "독립 작업 · 개발 메모리 없음 · 읽기 전용",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 81b8f9f81d..ebde6549d5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7726,6 +7726,7 @@"review": {"running": "正在审查当前成果","completed": "审查完成",+ "stale": "审查已完成 · 结果已过期","failed": "审查未完成","openTask": "打开审查任务","readOnlyHint": "独立任务 · 无开发记忆 · 只读",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 27b2406170..5fa93af6cd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7725,6 +7725,7 @@"review": {"running": "正在審查當前成果","completed": "審查完成",+ "stale": "審查已完成 · 結果已過期","failed": "審查未完成","openTask": "開啟審查任務","readOnlyHint": "獨立任務 · 無開發記憶 · 只讀",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1577820a41..3d5f12119c 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5036,7 +5036,6 @@ interface ElectronAPI {focus?: string;attachments?: import('./lib/fileTypes').SerializedAttachedFile[];}) => Promise<{ ok: true; runId: string; reviewerSessionId: string }>;-listAgentCommands: (agentKind: 'claude-code' | 'codex' | 'pi',params?: { sessionId?: string; allowManagedPiPackagePreview?: boolean },diff --git a/apps/desktop/src/shared/__tests__/reviewRun.test.ts b/apps/desktop/src/shared/__tests__/reviewRun.test.tsindex 2460731687..2eea3e5259 100644--- a/apps/desktop/src/shared/__tests__/reviewRun.test.ts+++ b/apps/desktop/src/shared/__tests__/reviewRun.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {+ isStaleReviewFailureCode,readReviewFailureCode,readReviewRunMeta,reviewFailureCodeFromLegacyError,@@ -47,6 +48,8 @@ describe('ReviewRunMeta', () => {).toMatchObject({ failureCode: 'reviewer-closed' });expect(readReviewRunMeta({ ...base, status: 'failed', failureCode: 'made-up' })).toBeNull();expect(readReviewFailureCode('artifact-changed')).toBe('artifact-changed');+ expect(isStaleReviewFailureCode('artifact-changed')).toBe(true);+ expect(isStaleReviewFailureCode('provider-failed')).toBe(false);expect(readReviewFailureCode(123)).toBeNull();});diff --git a/apps/desktop/src/shared/reviewRun.ts b/apps/desktop/src/shared/reviewRun.tsindex 52a51655c3..c81254148e 100644--- a/apps/desktop/src/shared/reviewRun.ts+++ b/apps/desktop/src/shared/reviewRun.ts@@ -19,12 +19,25 @@ export type ReviewFailureCode = (typeof REVIEW_FAILURE_CODES)[number];const REVIEW_FAILURE_CODE_SET = new Set<string>(REVIEW_FAILURE_CODES);+const STALE_REVIEW_FAILURE_CODE_SET = new Set<ReviewFailureCode>([+ 'source-workspace-changed',+ 'source-conversation-changed',+ 'source-files-changed',+ 'artifact-changed',+]);+export function readReviewFailureCode(value: unknown): ReviewFailureCode | null {return typeof value === 'string' && REVIEW_FAILURE_CODE_SET.has(value)? (value as ReviewFailureCode): null;}+export function isStaleReviewFailureCode(+ value: ReviewFailureCode | null,+): value is ReviewFailureCode {+ return value !== null && STALE_REVIEW_FAILURE_CODE_SET.has(value);+}+const LEGACY_REVIEW_FAILURE_CODE_BY_ERROR = new Map<string, ReviewFailureCode>([['Reviewer returned no visible conclusion', 'no-visible-result'],['Reviewer task was closed before it finished', 'reviewer-closed'],diff --git a/docs/product-rules/review-product-direction.md b/docs/product-rules/review-product-direction.mdindex da8ad17370..0e4551a532 100644--- a/docs/product-rules/review-product-direction.md+++ b/docs/product-rules/review-product-direction.md@@ -21,8 +21,17 @@ Cindy Review 的北极星是减少用户在交付或提交后,才被外部 rev### 1.2 产品定义-`/review` 是 Cindy 的通用成果复核能力,不是只服务 GitHub 的 Git Code Review。-Code Review 是一个 profile,不是产品本身。+`/review` 是 Cindy 客户端内置、由用户按需触发的常规成果复核功能,不是只服务 GitHub+的 Git Code Review。Code Review 是一种复核场景,不是另一个产品。++这里的“内置”只表示功能随客户端提供,不表示 Review 是 Cindy Core 的常驻基础设施。+用户没有触发 Review 时,它不得进入普通任务的生命周期,不得拖慢 Desktop 启动,也不得+为恢复 Review 状态执行全库消息扫描。Review 所需的准备、对账与恢复只在用户再次对相关+任务触发 Review 时按需执行;仅打开任务不启动 Review 对账。++Review 按需化不引入数据库 schema migration,也不批量回填、转换或清理历史 Review+数据。旧卡片保持原样,新实现只保证上线后新创建的 Review;再次触发 Review 时如果当前+任务恰有旧运行锁阻塞,可以只对该任务做精确恢复,这属于当次运行恢复,不是历史迁移。Review 至少面向以下成果:@@ -42,6 +51,8 @@ DeepSeek 等模型只要能在相应 harness 的普通任务中使用,也应- 每次复核新建独立、无开发记忆、只读的 Reviewer 任务,不 resume 来源开发会话。- 默认沿用来源任务的 harness、provider 和 model。+- Review 运行时按需初始化;未使用 Review 的用户不承担常驻后台任务、全局数据库查询或+ Review 专用消息索引的成本。- 只向 Reviewer 提供带来源标记的结构化证据:用户需求及修正、验收条件、成果快照、真实测试结果和明确技术决策。- 不传开发 reasoning,也不把开发 Agent 的自述视为事实。Reviewer 必须重新读取成果并@@ -50,6 +61,8 @@ DeepSeek 等模型只要能在相应 harness 的普通任务中使用,也应与正确性问题分开表达。- 结果回到来源任务,用户可从来源任务打开独立 Reviewer 任务。- 审阅对象或来源任务变化后,旧结论立即失效;异常、重启或关闭路径都必须 fail closed。+- Reviewer 已产出结论后才发现来源任务变化时,结果应标记为“已过期”并保留为只读审计记录,+ 不得误报为 Reviewer 未完成,也不得把过期结果当作当前有效结论。- 完成后的 Reviewer 任务是可查看的审计记录,不能继续聊天,也不能修改模型、来源、权限、目录等冻结配置。- Reviewer 只复核,不自动修码。修复回到来源任务,修复后的成果需要再次复核。@@ -95,16 +108,16 @@ Review 必须同时验证代码路径和真实交付结果,不能用“格式## 3. 后续路线-以下是已讨论的架构分工方向,不代表 #2269 的实现范围,也不把尚未裁决的细节变成承诺。+以下是已讨论的功能分工方向,不代表 #2269 的实现范围,也不把尚未裁决的细节变成承诺。-- **Cindy Core**:负责 ReviewJob、成果快照、独立任务、硬只读、Finding 协议、结果 UI- 与失效生命周期。+- **客户端内置 Review 模块**:只在用户触发后负责成果快照、独立 Reviewer 任务、硬只读、+ Finding 协议、结果 UI 与失效生命周期;它不是 Cindy Core 的常驻控制面。- **人类入口**:`/review` 或“复核成果”按钮。- **Agent 主动入口**:未来可提供 `review_start` 工具。- **高频或强制复核**:必须由宿主生命周期 gate 执行,不能只靠 Skill 文案;模型可能跳过Skill,或用“我自己检查过”冒充独立复核。- **Skill**:声明何时复核,以及采用什么 rubric 或策略。-- **插件**:承载法律、品牌、视觉等专业扩展与富交互,不承载核心 Reviewer。+- **插件**:承载法律、品牌、视觉等专业扩展与富交互,不替代客户端内置的普通复核入口。- **官方本地或 Web reviewer**:未来可以作为“额外第二意见”的 ReviewRunner,不是默认主路径或 fallback。Web 路径还需要单独处理账号、GitHub App、代码外发、费用和结果回收。