Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge remote-tracking branch 'upstream/main' into cindy-reviewer
Chrisddeebc6b02fb
diff --cc apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex d35467d4f1,d35467d4f1..650fd12854--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@@ -667,7 -667,7 +667,9 @@@ describe('sendToSession ordering', () =expect(orcaWorkerCreationServiceSource).toContain("return agent === 'codex' || agent === 'pi';",);-- expect(orcaLifecycleServiceSource).toContain('createWorkerInTeam({ ...params, teamId: team.id })');++ expect(orcaLifecycleServiceSource).toMatch(++ /createWorkerInTeam\(\{\s*\n\s*\.\.\.params,\s*\n\s*teamId: team\.id,/,++ );});it('delegates worker terminal runtime to OrcaTeamService', () => {diff --cc apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.tsindex 90089a9347,49407f02f1..79ddc20467--- a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts+++ b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts@@@ -10,13 -10,11 +10,17 @@@ vi.mock('electron', () => ({ app: { getconst writeFile = vi.hoisted(() => vi.fn(async () => {}));const mkdir = vi.hoisted(() => vi.fn(async () => {}));+const chmod = vi.hoisted(() => vi.fn(async () => {}));++const lstat = vi.hoisted(() =>++ vi.fn(async () => ({ isDirectory: () => true, isSymbolicLink: () => false })),++);const readFile = vi.hoisted(() => vi.fn(async () => Buffer.from('image-bytes')));vi.mock('node:fs/promises', () => ({- default: { writeFile, mkdir, chmod, readFile, rm: vi.fn(async () => {}) },- default: { writeFile, mkdir, readFile, rm: vi.fn(async () => {}) },++ default: { writeFile, mkdir, chmod, lstat, readFile, rm: vi.fn(async () => {}) },writeFile,mkdir,+ chmod,++ lstat,readFile,rm: vi.fn(async () => {}),}));@@@ -408,12 -406,12 +412,14 @@@ describe('materializeDirectSendOssAttacconst persistedContent = JSON.stringify({text: 'run check',images: [],-- files: [{-- name: 'setup.exe',-- path: ref,-- size: 15,-- sha256: ATTACHMENT_SHA256,-- }],++ files: [++ {++ name: 'setup.exe',++ path: ref,++ size: 15,++ sha256: ATTACHMENT_SHA256,++ },++ ],});const out = await materializeDirectSendOssAttachments(@@@ -525,19 -523,19 +531,15 @@@{ type: 'file', path: fileRef, mimeType: 'application/pdf' },],};-- const out = await materializeDirectSendOssAttachments(-- 'sess-1',-- message,-- {-- persistUserMessage: {-- content: JSON.stringify({-- text: '',-- images: [],-- files: [{ name: 'doc.pdf', path: fileRef }],-- }),-- },++ const out = await materializeDirectSendOssAttachments('sess-1', message, {++ persistUserMessage: {++ content: JSON.stringify({++ text: '',++ images: [],++ files: [{ name: 'doc.pdf', path: fileRef }],++ }),},-- );++ });assert.deepEqual((out.message as typeof message).content[0], {type: 'image',base64: 'inline-image',diff --cc apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.tsindex f3042098f3,0000000000..6be169e2c8mode 100644,000000..100644--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts@@@ -1,74 -1,0 +1,108 @@@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const tempRoot = vi.hoisted(() => ({ value: '' }));++vi.mock('electron', () => ({+ app: { getPath: () => tempRoot.value },+}));+vi.mock('../../imageCacheStore.js', () => ({+ resolveSafe: vi.fn(),+}));+vi.mock('../../cindy-media/blobStore.js', () => ({+ resolveSafe: vi.fn(),+}));+vi.mock('../../cindy-media/ledger.js', () => ({}));+vi.mock('../../cindy-media/ingest.js', () => ({ ingestMedia: vi.fn() }));+vi.mock('../../device-link/mediaTransfer.js', () => ({+ downloadToFile: vi.fn(),+ removeRemote: vi.fn(),+}));+vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++import { cleanupSessionTempAttachments, normalizeUserMessage } from '../normalizeAttachments.js';++const tempDirs: string[] = [];++beforeEach(async () => {+ tempRoot.value = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-inline-test-'));+ tempDirs.push(tempRoot.value);+});++afterEach(async () => {+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));+});++describe('inline attachment temporary files', () => {+ it('writes private bytes and removes them even before Maker owns the session', async () => {+ const sessionId = 'reviewer-session';+ const normalized = await normalizeUserMessage(sessionId, {+ type: 'user',+ content: [+ { type: 'text', text: 'Review this image' },+ {+ type: 'image',+ base64: Buffer.from('private image bytes').toString('base64'),+ mimeType: 'image/png',+ },+ ],+ });+ if (typeof normalized === 'string' || typeof normalized.content === 'string') {+ throw new Error('expected block message');+ }+ const imageBlock = normalized.content.find((block) => block.type === 'image');+ const imagePath = imageBlock?.path;+ if (typeof imagePath !== 'string') throw new Error('expected materialized image path');+ const sessionTempDir = path.dirname(imagePath);++ await expect(fs.readFile(imagePath, 'utf8')).resolves.toBe('private image bytes');+ if (process.platform !== 'win32') {+ expect((await fs.stat(sessionTempDir)).mode & 0o777).toBe(0o700);+ expect((await fs.stat(imagePath)).mode & 0o777).toBe(0o600);+ }++ await cleanupSessionTempAttachments(sessionId);++ await expect(fs.lstat(sessionTempDir)).rejects.toMatchObject({ code: 'ENOENT' });+ await cleanupSessionTempAttachments(sessionId);+ });++++ it.each(['shared root', 'session directory'] as const)(++ 'refuses a symlinked temporary attachment %s',++ async (target) => {++ if (process.platform === 'win32') return;++ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-inline-outside-'));++ tempDirs.push(outside);++ const sharedRoot = path.join(tempRoot.value, 'cindy-attachments');++ if (target === 'shared root') {++ await fs.symlink(outside, sharedRoot);++ } else {++ await fs.mkdir(sharedRoot);++ await fs.symlink(outside, path.join(sharedRoot, 'reviewer-session'));++ }++++ const normalized = await normalizeUserMessage('reviewer-session', {++ type: 'user',++ content: [++ { type: 'text', text: 'Review this image' },++ {++ type: 'image',++ base64: Buffer.from('private image bytes').toString('base64'),++ mimeType: 'image/png',++ },++ ],++ });++++ if (typeof normalized === 'string' || typeof normalized.content === 'string') {++ throw new Error('expected block message');++ }++ expect(normalized.content).toEqual([{ type: 'text', text: 'Review this image' }]);++ await expect(fs.readdir(outside)).resolves.toEqual([]);++ },++ );+});diff --cc apps/desktop/src/main/maker-ipc/normalizeAttachments.tsindex ede18e9155,16455441c4..5a7ea6882b--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts@@@ -46,15 -46,14 +46,38 @@@ const EXT_BY_MIME: Record<string, strin'text/plain': '.txt',};++function assertSafeTempSessionId(sessionId: string): void {++ if (!sessionId || sessionId === '.' || sessionId === '..' || /[\\/\0]/.test(sessionId)) {++ throw new Error('Unsafe session id for temporary attachments');++ }++}++++function tempRoot(): string {++ return path.join(app.getPath('temp'), 'cindy-attachments');++}++function tempDirFor(sessionId: string): string {-- return path.join(app.getPath('temp'), 'cindy-attachments', sessionId);++ assertSafeTempSessionId(sessionId);++ return path.join(tempRoot(), sessionId);++}++++async function assertRealTempDirectory(dir: string): Promise<void> {++ const entry = await fs.lstat(dir);++ if (entry.isSymbolicLink() || !entry.isDirectory()) {++ throw new Error('Temporary attachment directory must be a real directory');++ }}/** 在 session 临时目录下分配一个唯一文件路径(建目录,不写内容)。 */async function ensureTempPath(sessionId: string, mimeType: string | undefined): Promise<string> {++ const root = tempRoot();const dir = tempDirFor(sessionId);- await fs.mkdir(dir, { recursive: true });++ await fs.mkdir(root, { recursive: true, mode: 0o700 });++ await assertRealTempDirectory(root);++ await fs.chmod(root, 0o700);+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });++ await assertRealTempDirectory(dir);+ await fs.chmod(dir, 0o700);TEMP_DIRS_BY_SESSION.set(sessionId, dir);const ext = (mimeType && EXT_BY_MIME[mimeType]) ?? '.bin';return path.join(dir, `${randomUUID()}${ext}`);diff --cc apps/desktop/src/main/maker-ipc/register.tsindex 65548a4111,d8eacc4216..28b09171dd--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -3497,9 -3363,9 +3499,9 @@@ export function wireSessionToIpc(sessio// potentially multi-megabyte payload to every renderer and device-link controller.if (event.type === 'turn_diff') return;if (-- event.turnScope === 'background'-- && Object.prototype.hasOwnProperty.call(event, 'backgroundTurnStartedAt')-- && backgroundTurnPredatesSessionClear(session.id, event.backgroundTurnStartedAt)++ event.turnScope === 'background' &&++ Object.prototype.hasOwnProperty.call(event, 'backgroundTurnStartedAt') &&++ backgroundTurnPredatesSessionClear(session.id, event.backgroundTurnStartedAt)) {return;}@@@ -3798,7 -3653,7 +3800,8 @@@const eventAgentMeta = (event as { agentMeta?: AgentMeta | null }).agentMeta ?? null;// 跟踪会话最近一次非空 agentMeta(镜像 renderer state.lastAgentMeta),给 interaction// 边界 flush 当兜底锚点,保 agent_meta 不丢(rewind/fork)。-- if (eventAgentMeta && event.turnScope !== 'background') noteAgentMeta(session.id, eventAgentMeta);++ if (eventAgentMeta && event.turnScope !== 'background')++ noteAgentMeta(session.id, eventAgentMeta);let persistId: string | undefined;// tool_result 家族:main 解析出的权威内容,盖进 payload 让 renderer 即时显示// (Option C:内容重排状态机只在 main 一份,与落库同源同值)。@@@ -4036,6 -3891,22 +4039,23 @@@// A claim-bearing done seals this SDK segment, but the product turn is// still running and may emit another continuation segment. Reset the// per-SDK-turn persistence maps while deferring the logical turn marker.+ // 没有 done 的终态 error(Codex 在 terminal error 后显式压掉迟到的+ // turnCompleted,persistCodexPlanOnDone 永远不会跑到):本 turn 的计划行+ // 既没有章也没有 turnCompleted:false,面板会把全勾完的失败计划当旧数据+ // 兜底退场。在这里补失败印记——只盖 turn 存活标记,不动步骤状态。+ if (+ !isContinuationBoundary &&+ event.source === 'codex' &&+ event.type !== 'done' &&+ isTerminalTurnErrorEvent(event)+ ) {+ const errorTurnId =- typeof (event.data as { raw?: { id?: unknown } } | null | undefined)?.raw?.id === 'string'++ typeof (event.data as { raw?: { id?: unknown } } | null | undefined)?.raw?.id ===++ 'string'+ ? ((event.data as { raw?: { id?: unknown } }).raw!.id as string)+ : null;+ persistCodexPlanOnTerminalError(session.id, errorTurnId);+ }if (!isContinuationBoundary && event.source === 'codex' && event.type === 'done') {// Renderer applies this terminal snapshot immediately. Persist the// same state before sealing the persist queue and clearing the@@@ -4081,7 -3956,7 +4105,8 @@@const replyText = typeof doneResult === 'string' ? doneResult : '';if (replyText.length > 0 && hasEnabledGhostAssistantHook()) {const turnModel =-- turnModelPromiseBySession.get(session.id) ?? Promise.resolve(session.model || 'unknown');++ turnModelPromiseBySession.get(session.id) ??++ Promise.resolve(session.model || 'unknown');const assistantPersistId = turnAssistantPersistId;withGhostAssistantHookModel(turnModel, () => {runGhostAssistantReplyHook(session.id, assistantPersistId, replyText);@@@ -6655,474 -6471,57 +6684,475 @@@ export function registerMakerIpc(maker};const makerSessionRegistry = createElectronIpcHandlerRegistry();- registerMakerSessionCreateHandler(- makerSessionRegistry,- {- // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab- // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于- // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的- // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。- bootstrapSession: async (co) => {- await ensureRemoteReadyForSessionStart({ createOpts: co });- const result = await bootstrapSession(co);- // maker:create-session 是手机 / device-link 的创建入口,不经过- // local-db:sessions:create,因此后者维护 recent_workdirs 的逻辑不会运行。- // worktree 两步流此时 co.workingDir 已是隔离目录;picker 需要记住用户选的- // 项目根,而不是 auto-* 运行目录。worktreeStore 以同一预生成 sessionId- // 保存了权威 baseRepo。先完成 best-effort upsert 再让 handler 广播 created,- // 这样 renderer 收到广播重拉 recent 表时不会撞到写入竞态。- if (co.workspaceKind !== 'dialogue' && !co.remoteHostId) {- const recentProjectDir = worktreeStore.get(result.session.id)?.baseRepo- ?? getManagedWorktreeBasePath(co.workingDir)- ?? co.workingDir;- await upsertRecentWorkdir(recentProjectDir);- }- return result;- },- markOrcaRoleIfNeeded,- markKnownNonOrcaIfApplicable,- allocateDialogueWorkspace: ensureDialogueWorkspaceDir,- createSessionId: createId,- now: Date.now,- withSessionLock: withSendToSessionLock,- sendWorkerReadyMessage: (session) => {- // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,- // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。- observeFireAndForgetSendOutcome(- session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),- {- owner: 'orca-worker-ready',- entrypoint: 'CREATE_SESSION',- sessionId: session.id,- agentKind: session.agentKind,- action: 'worker-ready-placeholder',- context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,- },- );- },- broadcastSessionCreated,- logCreateSession: (fields) => log.info('create-session invoked', fields),- warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),+ registerMakerSessionCreateHandler(makerSessionRegistry, {+ // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab+ // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于+ // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的+ // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。+ bootstrapSession: async (co) => {+ await ensureRemoteReadyForSessionStart({ createOpts: co });+ const result = await bootstrapSession(co);+ // maker:create-session 是手机 / device-link 的创建入口,不经过+ // local-db:sessions:create,因此后者维护 recent_workdirs 的逻辑不会运行。+ // worktree 两步流此时 co.workingDir 已是隔离目录;picker 需要记住用户选的+ // 项目根,而不是 auto-* 运行目录。worktreeStore 以同一预生成 sessionId+ // 保存了权威 baseRepo。先完成 best-effort upsert 再让 handler 广播 created,+ // 这样 renderer 收到广播重拉 recent 表时不会撞到写入竞态。+ if (co.workspaceKind !== 'dialogue' && !co.remoteHostId) {+ const recentProjectDir =+ worktreeStore.get(result.session.id)?.baseRepo ??+ getManagedWorktreeBasePath(co.workingDir) ??+ co.workingDir;+ await upsertRecentWorkdir(recentProjectDir);+ }+ return result;},- );+ markOrcaRoleIfNeeded,+ markKnownNonOrcaIfApplicable,+ allocateDialogueWorkspace: ensureDialogueWorkspaceDir,+ createSessionId: createId,+ now: Date.now,+ withSessionLock: withSendToSessionLock,+ sendWorkerReadyMessage: (session) => {+ // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,+ // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。+ observeFireAndForgetSendOutcome(+ session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),+ {+ owner: 'orca-worker-ready',+ entrypoint: 'CREATE_SESSION',+ sessionId: session.id,+ agentKind: session.agentKind,+ action: 'worker-ready-placeholder',+ context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,+ },+ );+ },+ broadcastSessionCreated,+ logCreateSession: (fields) => log.info('create-session invoked', fields),+ 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"%'`,+ ),+ ),+ listPersistedReviewSourceLeases(dbClient),+ ]);+ const interruptedAt = Date.now();+ for (const row of rows) {+ const reviewRun = readReviewRunFromAgentMeta(row.agentMeta);+ if (!reviewRun || !(await shouldFailInterruptedReview(reviewRun, reviewRunOwner))) continue;+ const failed: ReviewRunMeta = {+ ...reviewRun,+ status: 'failed',+ completedAt: interruptedAt,+ error: 'Review was interrupted when Cindy closed. Run /review again.',+ };+ await updateMessageContent(row.sessionId, row.clientId, '');+ await patchMessageAgentMeta(row.sessionId, row.clientId, { reviewRun: failed });+ await broadcastMessageAgentMetaUpdate(row.sessionId, 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,+ });+ }+ };+ 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"%'`,+ ),+ );+ return rows.some((row) => readReviewRunFromAgentMeta(row.agentMeta)?.status === 'running');+ };+ const sourceHasActiveTurn = async (sourceSessionId: string): Promise<boolean> => {+ if (+ maker.getSession(sourceSessionId)?.isTurnRunning() ||+ sessionTurnActivityTracker.isSessionInTurn(sourceSessionId)+ ) {+ return true;+ }+ return sessionTurnLeaseTracker.isTurnActive(sourceSessionId);+ };+ const reviewStartupReady = ensureReviewOwnerLivenessReady()+ .then(() =>+ Promise.all([+ reconcileInterruptedReviews(),+ sessionTurnLeaseTracker.reconcileStaleLeases(),+ cleanupOrphanedReviewArtifactSnapshots({ currentOwner: reviewRunOwner }),+ ]),+ )+ .then(() => undefined)+ .catch((error) => {+ log.error('failed to prepare Review runtime state', {+ error: error instanceof Error ? error.message : String(error),+ });+ 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; START_REVIEW still awaits and fails closed.+ void reviewStartupReady.catch(() => {});++ const readLatestReviewerResult = async (reviewerSessionId: string): Promise<string> => {+ const rows = await getDbClient()+ .drizzle.select({ content: messages.content })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, reviewerSessionId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ ),+ )+ .orderBy(desc(messages.createdAt), desc(messages.id))+ .limit(8);+ for (const row of rows) {+ const text = visibleMessageTextForConversationSearch('assistant', row.content);+ if (text) return text;+ }+ return '';+ };++ registerReviewStartHandler(makerSessionRegistry, {+ assertCaller: (event) =>+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),+ waitUntilReady: async () => {+ await reviewStartupReady;+ // 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();+ },+ createRunId: randomUUID,+ createReviewerSessionId: randomUUID,+ owner: reviewRunOwner,+ now: Date.now,+ acquireSourceLease: (input) => tryAcquireReviewSourceLease(getDbClient(), input),+ releaseSourceLease: async (input) => {+ await releaseReviewSourceLease(getDbClient(), input);+ },+ prepareRun: async ({ event, request, reviewerSessionId }) => {+ const db = getDbClient().drizzle;+ const [source] = await db+ .select({+ id: sessions.id,+ title: sessions.title,+ workingDir: sessions.workingDir,+ workspaceKind: sessions.workspaceKind,+ model: sessions.model,+ effort: sessions.effort,+ fastMode: sessions.fastMode,+ providerId: sessions.providerId,+ agentKind: sessions.agentKind,+ source: sessions.source,+ remoteHostId: sessions.remoteHostId,+ status: sessions.status,+ })+ .from(sessions)+ .where(eq(sessions.id, request.sourceSessionId))+ .limit(1);+ if (!source || source.status !== 'active') {+ throwIpcError('NOT_FOUND', 'Source task not found');+ }+ if (await sourceHasPersistedRunningReview(source.id)) {+ throwIpcError('SESSION_RUNNING', 'This task already has a review in progress');+ }+ if (source.source === 'review') {+ throwIpcError('INVALID_PARAMS', 'A review task cannot start another review');+ }+ if (source.remoteHostId) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Review is local-only in this version');+ }+ if (!source.workingDir) {+ throwIpcError('INVALID_PARAMS', 'The source task has no working directory to review');+ }+ const sourceWorkingDir = source.workingDir;+ if (await sourceHasActiveTurn(source.id)) {+ throwIpcError(+ 'SESSION_RUNNING',+ 'Wait for the current task turn to finish before reviewing',+ );+ }++ let evidence: Awaited<ReturnType<typeof loadReviewEvidence>>;+ let sourceArtifactFingerprint = '';+ let authorizedArtifactPaths: string[] = [];+ let cleanupPreparedArtifacts: (() => Promise<void>) | null = null;+ try {+ const historicalAttachments = await listReviewHistoricalAttachments(source.id);+ const explicitArtifactGrant = await authorizeReviewExplicitArtifacts({+ workingDir: sourceWorkingDir,+ focus: request.focus,+ attachments: [...request.attachments, ...historicalAttachments],+ resolvePath: resolveReviewArtifactPath,+ confirm: (items) => confirmReviewExternalArtifacts(event as IpcMainInvokeEvent, items),+ });+ authorizedArtifactPaths = explicitArtifactGrant.paths;+ const prepared = await prepareStableReviewArtifactSnapshots({+ workingDir: sourceWorkingDir,+ grant: explicitArtifactGrant,+ owner: reviewRunOwner,+ prepare: (snapshotGrant) =>+ loadReviewEvidence({+ sourceSessionId: source.id,+ workingDir: sourceWorkingDir,+ focus: request.focus,+ attachments: request.attachments,+ explicitArtifactGrant: snapshotGrant,+ }),+ });+ cleanupPreparedArtifacts = prepared.cleanup;+ evidence = prepared.value;+ sourceArtifactFingerprint = prepared.fingerprint;+ } catch (error) {+ await cleanupPreparedArtifacts?.();+ if (+ error instanceof ReviewArtifactAuthorizationError ||+ error instanceof SensitiveReviewPathError+ ) {+ throwIpcError('PERMISSION_DENIED', error.message);+ }+ throw error;+ }+ if (+ evidence.context.length === 0 &&+ !evidence.workspace?.dirty &&+ !evidence.changeSet &&+ evidence.artifacts.length === 0 &&+ !request.focus+ ) {+ await cleanupPreparedArtifacts?.();+ throwIpcError('INVALID_PARAMS', 'The current task has no reviewable content yet');+ }+ let builtPrompt: ReturnType<typeof buildReviewPrompt>;+ try {+ builtPrompt = buildReviewPrompt({+ focus: evidence.focusPath ? `审查路径:${evidence.focusPath}` : request.focus,+ context: evidence.context,+ workspace: evidence.workspace,+ changeSet: evidence.changeSet,+ artifacts: evidence.artifacts,+ artifactsOmitted: evidence.artifactsOmitted,+ artifactExcerpts: evidence.artifactExcerpts,+ artifactWarnings: evidence.artifactWarnings,+ });+ } catch (error) {+ await cleanupPreparedArtifacts?.();+ throw error;+ }++ return {+ sourceAgentKind: source.agentKind as 'cc' | 'codex' | 'pi',+ prompt: builtPrompt.prompt,+ targetKind: builtPrompt.targetKind,+ cleanup: async () => {+ await cleanupPreparedArtifacts?.();+ },+ prepareLaunch: async () => {+ const rawReviewMessage: IpcUserMessage = {+ type: 'user',+ content: [{ type: 'text', text: builtPrompt.prompt }, ...evidence.attachmentBlocks],+ };+ const reviewMessage = await prepareUserMessageForAgent(+ reviewerSessionId,+ rawReviewMessage,+ 'send',+ );+ const readRoots = new Set(evidence.readRoots);+ const reviewReadPaths = new Set(evidence.reviewReadPaths);+ if (typeof reviewMessage !== 'string' && Array.isArray(reviewMessage.content)) {+ for (const block of reviewMessage.content) {+ if (+ (block.type === 'image' || block.type === 'file') &&+ typeof block.path === 'string' &&+ path.isAbsolute(block.path)+ ) {+ readRoots.add(path.dirname(block.path));+ reviewReadPaths.add(block.path);+ }+ }+ }- const artifactPaths = [- ...reviewReadPaths,- ...(evidence.workspaceFingerprint ? [] : [sourceWorkingDir]),- ];++ // Every harness grants read access to the source working directory.++ // Git identity/diff fingerprints do not cover ignored build output,++ // caches or nested-submodule contents, so the reusable result must++ // also bind the complete non-sensitive readable workspace content.++ const artifactPaths = [...reviewReadPaths, sourceWorkingDir];+ const artifactFingerprint = await fingerprintReviewArtifacts(artifactPaths);++ return {+ message: reviewMessage as UserMessage,+ reviewerCreateOpts: buildCreateOptsWithStderr({+ id: reviewerSessionId,+ agentKind: dbToMakerAgentKind(source.agentKind),+ workingDir: sourceWorkingDir,+ workspaceKind: source.workspaceKind,+ model: source.model,+ effort: source.effort as CreateOpts['effort'],+ fastMode: !!source.fastMode,+ providerId: source.providerId,+ title: buildReviewSessionTitle(source.title),+ permissionMode: 'ask',+ planMode: false,+ reviewMode: true,+ reviewReadPaths: [...reviewReadPaths],+ makerMemoryEnabled: false,+ ...(readRoots.size > 0 ? { extraDirs: [...readRoots] } : {}),+ }),+ verifyBeforeStart: async () => {+ if (+ (await sourceHasActiveTurn(source.id)) ||+ (await readReviewContextFingerprint(source.id)) !== evidence.contextFingerprint+ ) {+ throw new Error(+ 'The task conversation changed before Review started. Run /review again for the current context.',+ );+ }+ if (+ !(await reviewWorkspaceFingerprintIsCurrent(+ source.id,+ evidence.workspaceFingerprint,+ ))+ ) {+ throw new Error(+ 'The task files changed before Review started. Run /review again for the current result.',+ );+ }+ if (+ (await fingerprintReviewArtifacts(authorizedArtifactPaths)) !==+ sourceArtifactFingerprint+ ) {+ throw new Error(+ 'A review artifact changed before Review started. Run /review again for the current result.',+ );+ }+ },+ verifyBeforePublish: async (): Promise<string | null> => {+ const [currentSource] = await db+ .select({+ workingDir: sessions.workingDir,+ workspaceKind: sessions.workspaceKind,+ status: sessions.status,+ })+ .from(sessions)+ .where(eq(sessions.id, source.id))+ .limit(1);+ if (!reviewSourceIdentityMatches(source, currentSource ?? null)) {+ return 'The source task workspace changed while Review was running. Run /review again in the current workspace.';+ }+ if (+ (await sourceHasActiveTurn(source.id)) ||+ (await readReviewContextFingerprint(source.id)) !== evidence.contextFingerprint+ ) {+ return 'The task conversation changed while Review was running. Run /review again for the current context.';+ }+ if (+ !(await reviewWorkspaceFingerprintIsCurrent(+ source.id,+ evidence.workspaceFingerprint,+ ))+ ) {+ return 'The task files changed while Review was running. Run /review again for the current result.';+ }+ if (+ (await fingerprintReviewArtifacts(authorizedArtifactPaths)) !==+ sourceArtifactFingerprint+ ) {+ return 'A review artifact changed while Review was running. Run /review again for the current result.';+ }+ const currentArtifactFingerprint = await fingerprintReviewArtifacts(artifactPaths);+ if (currentArtifactFingerprint !== artifactFingerprint) {+ return 'A review artifact changed while Review was running. Run /review again for the current result.';+ }+ return null;+ },+ };+ },+ };+ },+ createSourceCard: async ({ sourceSessionId, sourceCardClientId, sourceAgentKind, meta }) => {+ await createDbMessage(sourceSessionId, {+ clientId: sourceCardClientId,+ role: 'assistant',+ content: '',+ agentMeta: { reviewRun: meta },+ agentKind: sourceAgentKind,+ });+ },+ updateSourceCard: async ({ sourceSessionId, sourceCardClientId, meta, result }) => {+ await updateMessageContent(sourceSessionId, sourceCardClientId, result);+ await patchMessageAgentMeta(sourceSessionId, sourceCardClientId, { reviewRun: meta });+ await broadcastMessageAgentMetaUpdate(sourceSessionId, sourceCardClientId);+ },+ publishReviewerLink: async ({ sourceSessionId, sourceCardClientId, meta }) => {+ await patchMessageAgentMeta(sourceSessionId, sourceCardClientId, { reviewRun: meta });+ await broadcastMessageAgentMetaUpdate(sourceSessionId, sourceCardClientId);+ },+ startReviewer: async (createOpts) => {+ const { session } = await bootstrapSession(createOpts);+ return session;+ },+ markReviewerStarted: async (reviewerSessionId, startedAt) => {+ await getDbClient()+ .drizzle.update(sessions)+ .set({ userSendAt: startedAt, updatedAt: startedAt })+ .where(eq(sessions.id, reviewerSessionId));+ },+ broadcastReviewerCreated: broadcastSessionCreated,+ persistReviewerPrompt: async ({ reviewerSessionId, runId, prompt, sourceAgentKind }) => {+ await createDbMessage(reviewerSessionId, {+ clientId: `review-prompt:${runId}`,+ role: 'user',+ content: prompt,+ agentKind: sourceAgentKind,+ });+ },+ drainPersistQueue,+ readReviewerResult: readLatestReviewerResult,+ closeReviewer: async (reviewerSessionId) => {+ try {+ await maker.closeSession(reviewerSessionId);+ } finally {+ // startSession can fail after F6/base64 attachments were materialized+ // but before Maker owns the session, so its onClose hook is not enough.+ await cleanupSessionTempAttachments(reviewerSessionId);+ }+ },+ warn: (message, fields) => log.warn(message, fields),+ });registerPrecreatedWorktreeDiscardHandler(makerSessionRegistry, {assertCaller: (event) => {// device-link 的真实调用身份由 invoke async context + allowlist 证明;本机直调仍diff --cc apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.tsindex e72693ca82,0000000000..5063e28179mode 100644,000000..100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts@@@ -1,199 -1,0 +1,213 @@@+import { constants, promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ fingerprintReviewArtifacts,+ prepareWithStableReviewArtifacts,+ ReviewArtifactChangedDuringPreparationError,+ ReviewArtifactFingerprintChangedError,+ ReviewArtifactFingerprintLimitError,+} from '../reviewArtifactFingerprint.js';++const tempDirs: string[] = [];++async function makeTempDir(): Promise<string> {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-fingerprint-'));+ tempDirs.push(dir);+ return dir;+}++afterEach(async () => {+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));+});++describe('review artifact fingerprint', () => {+ it('changes for same-size file edits and nested directory edits', async () => {+ const dir = await makeTempDir();+ const nested = path.join(dir, 'nested');+ await fs.mkdir(nested);+ const file = path.join(nested, 'draft.txt');+ await fs.writeFile(file, 'alpha');+ const before = await fingerprintReviewArtifacts([dir]);++ await fs.writeFile(file, 'bravo');+ const after = await fingerprintReviewArtifacts([dir]);++ expect(after).not.toBe(before);+ });++ it('hashes the unchanged-metadata middle of large files instead of sampling their ends', async () => {+ const dir = await makeTempDir();+ const file = path.join(dir, 'large.bin');+ const fixedTime = new Date('2024-01-01T00:00:00.000Z');+ await fs.writeFile(file, Buffer.alloc(9 * 1024 * 1024, 0x61));+ await fs.utimes(file, fixedTime, fixedTime);+ const beforeStat = await fs.stat(file);+ const before = await fingerprintReviewArtifacts([file]);++ const handle = await fs.open(file, 'r+');+ try {+ await handle.write(Buffer.from('changed!'), 0, 8, 4 * 1024 * 1024);+ } finally {+ await handle.close();+ }+ await fs.utimes(file, fixedTime, fixedTime);+ const afterStat = await fs.stat(file);+ const after = await fingerprintReviewArtifacts([file]);++ expect(afterStat.size).toBe(beforeStat.size);+ expect(afterStat.mtimeMs).toBe(beforeStat.mtimeMs);+ expect(after).not.toBe(before);+ });++ it('uses locale-independent ordering for directory entries', async () => {+ const dir = await makeTempDir();+ await fs.writeFile(path.join(dir, 'z.txt'), 'z');+ await fs.writeFile(path.join(dir, 'ä.txt'), 'a');+ const localeCompare = vi.spyOn(String.prototype, 'localeCompare').mockImplementation(() => {+ throw new Error('locale-dependent ordering must not be used');+ });++ try {+ await expect(fingerprintReviewArtifacts([dir])).resolves.toMatch(/^[a-f0-9]{64}$/);+ } finally {+ localeCompare.mockRestore();+ }+ });++ it('does not read or fingerprint credential paths', async () => {+ const dir = await makeTempDir();+ await fs.writeFile(path.join(dir, 'draft.txt'), 'public');+ await fs.writeFile(path.join(dir, '.env.local'), 'TOKEN=first');+ const before = await fingerprintReviewArtifacts([dir]);++ await fs.writeFile(path.join(dir, '.env.local'), 'TOKEN=other');+ const after = await fingerprintReviewArtifacts([dir]);+++ expect(after).toBe(before);++ });++++ it('does not read or fingerprint denied dependency trees', async () => {++ const dir = await makeTempDir();++ const dependencyDir = path.join(dir, 'node_modules', 'dependency');++ await fs.mkdir(dependencyDir, { recursive: true });++ await fs.writeFile(path.join(dir, 'draft.txt'), 'public');++ await fs.writeFile(path.join(dependencyDir, 'index.js'), 'first');++ const before = await fingerprintReviewArtifacts([dir]);++++ await fs.writeFile(path.join(dependencyDir, 'index.js'), 'other');++ const after = await fingerprintReviewArtifacts([dir]);+++ expect(after).toBe(before);+ });++ it('changes when an explicit artifact disappears', async () => {+ const dir = await makeTempDir();+ const file = path.join(dir, 'draft.txt');+ await fs.writeFile(file, 'draft');+ const before = await fingerprintReviewArtifacts([file]);++ await fs.unlink(file);+ const after = await fingerprintReviewArtifacts([file]);++ expect(after).not.toBe(before);+ });++ it('fails closed instead of returning a truncated directory fingerprint', async () => {+ const dir = await makeTempDir();+ await fs.writeFile(path.join(dir, 'a.txt'), 'a');+ await fs.writeFile(path.join(dir, 'b.txt'), 'b');++ await expect(+ fingerprintReviewArtifacts([dir], { maxDirectoryEntries: 2 }),+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintLimitError);+ });++ it('fails closed instead of using metadata when the complete-content budget is exhausted', async () => {+ const dir = await makeTempDir();+ const file = path.join(dir, 'draft.txt');+ await fs.writeFile(file, '12345');++ await expect(fingerprintReviewArtifacts([file], { maxContentBytes: 4 })).rejects.toBeInstanceOf(+ ReviewArtifactFingerprintLimitError,+ );+ });++ it('rejects an atomic replacement between lstat and open', async () => {+ const dir = await makeTempDir();+ const file = path.join(dir, 'approved.txt');+ const replacement = path.join(dir, 'replacement.txt');+ await fs.writeFile(file, 'approved bytes');+ await fs.writeFile(replacement, 'different bytes');+ const artifactPath = await fs.realpath(file);+ let replaced = false;++ await expect(+ fingerprintReviewArtifacts([artifactPath], {+ openFile: async (filePath, flags) => {+ if (filePath === artifactPath && !replaced) {+ replaced = true;+ await fs.rm(file);+ await fs.rename(replacement, file);+ }+ return fs.open(filePath, flags);+ },+ }),+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);+ });++ it('opens files with O_NOFOLLOW when the host supports it', async () => {+ if (typeof constants.O_NOFOLLOW !== 'number' || constants.O_NOFOLLOW === 0) return;+ const dir = await makeTempDir();+ const file = path.join(dir, 'approved.txt');+ const sensitive = path.join(dir, 'private-key');+ await fs.writeFile(file, 'approved bytes');+ await fs.writeFile(sensitive, 'sensitive bytes');+ const artifactPath = await fs.realpath(file);+ let capturedFlags = 0;++ await expect(+ fingerprintReviewArtifacts([artifactPath], {+ openFile: async (filePath, flags) => {+ capturedFlags = flags;+ await fs.rm(file);+ await fs.symlink(sensitive, file);+ return fs.open(filePath, flags);+ },+ }),+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);+ expect(capturedFlags & constants.O_NOFOLLOW).toBe(constants.O_NOFOLLOW);+ });++ it('does not follow a symlink that already replaced an artifact root', async () => {+ if (process.platform === 'win32') return;+ const dir = await makeTempDir();+ const link = path.join(dir, 'approved.txt');+ const sensitive = path.join(dir, 'private-key');+ await fs.writeFile(sensitive, 'sensitive bytes');+ await fs.symlink(sensitive, link);+ const openFile = vi.fn((filePath: string, flags: number) => fs.open(filePath, flags));++ await expect(fingerprintReviewArtifacts([link], { openFile })).resolves.toMatch(+ /^[a-f0-9]{64}$/,+ );+ expect(openFile).not.toHaveBeenCalled();+ });++ it('rejects a same-size replacement between extraction and the first baseline', async () => {+ const dir = await makeTempDir();+ const file = path.join(dir, 'draft.txt');+ await fs.writeFile(file, 'alpha');++ await expect(+ prepareWithStableReviewArtifacts([file], async () => {+ const extracted = await fs.readFile(file, 'utf8');+ await fs.writeFile(file, 'bravo');+ return extracted;+ }),+ ).rejects.toBeInstanceOf(ReviewArtifactChangedDuringPreparationError);+ });+});diff --cc apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.tsindex a4fac69ebc,0000000000..37b8bf3a86mode 100644,000000..100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts@@@ -1,49 -1,0 +1,58 @@@+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');+ });++++ it('binds Git reviews to readable workspace content outside the Git snapshot', () => {++ expect(registerSource).toContain(++ 'const artifactPaths = [...reviewReadPaths, sourceWorkingDir];',++ );++ expect(registerSource).not.toContain(++ '...(evidence.workspaceFingerprint ? [] : [sourceWorkingDir])',++ );++ });+});diff --cc apps/desktop/src/main/reviewer/reviewArtifactFingerprint.tsindex e3661cba79,0000000000..5d53a2e88dmode 100644,000000..100644--- a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts+++ b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts@@@ -1,293 -1,0 +1,293 @@@+import { createHash } from 'node:crypto';+import { constants, promises as fs, type Stats } from 'node:fs';+import path from 'node:path';++import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';++import { reviewArtifactPathIdentityMatches } from './reviewArtifactAuthorization.js';+- const MAX_DIRECTORY_ENTRIES = 10_000;++const MAX_DIRECTORY_ENTRIES = 50_000;+const READ_CHUNK_BYTES = 128 * 1024;- const MAX_TOTAL_CONTENT_BYTES = 128 * 1024 * 1024;++const MAX_TOTAL_CONTENT_BYTES = 512 * 1024 * 1024;+const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;++export type ReviewArtifactFileOpener = (+ filePath: string,+ flags: number,+) => ReturnType<typeof fs.open>;++interface FingerprintState {+ hash: ReturnType<typeof createHash>;+ entries: number;+ maxDirectoryEntries: number;+ contentBytesRemaining: number;+ openFile: ReviewArtifactFileOpener;+}++export interface ReviewArtifactFingerprintOptions {+ /** Test seam; production uses the bounded fail-closed default. */+ maxDirectoryEntries?: number;+ /** Test seam; production hashes at most the bounded total before failing closed. */+ maxContentBytes?: number;+ /** Test seam for deterministic lstat/open replacement coverage. */+ openFile?: ReviewArtifactFileOpener;+}++export class ReviewArtifactFingerprintLimitError extends Error {}+export class ReviewArtifactFingerprintChangedError extends Error {}++async function assertCanonicalReviewArtifactPath(absolutePath: string): Promise<void> {+ const canonicalPath = await fs.realpath(absolutePath).catch(() => null);+ if (!canonicalPath || path.resolve(canonicalPath) !== path.resolve(absolutePath)) {+ throw new ReviewArtifactFingerprintChangedError(+ 'A review artifact path changed while its content fingerprint was being prepared',+ );+ }+}++async function resolveFingerprintRoot(rawPath: string): Promise<string> {+ const normalizedPath = path.normalize(rawPath);+ const before = await fs.lstat(normalizedPath).catch(() => null);+ if (!before || before.isSymbolicLink()) return normalizedPath;++ const canonicalPath = await fs.realpath(normalizedPath).catch(() => null);+ if (!canonicalPath) return normalizedPath;+ const [afterRawPath, afterCanonicalPath] = await Promise.all([+ fs.lstat(normalizedPath).catch(() => null),+ fs.lstat(canonicalPath).catch(() => null),+ ]);+ if (+ !afterRawPath ||+ afterRawPath.isSymbolicLink() ||+ !afterCanonicalPath ||+ afterCanonicalPath.isSymbolicLink() ||+ !reviewArtifactPathIdentityMatches(before, afterRawPath) ||+ !reviewArtifactPathIdentityMatches(before, afterCanonicalPath)+ ) {+ throw new ReviewArtifactFingerprintChangedError(+ 'A review artifact root changed while its content fingerprint was being prepared',+ );+ }+ return canonicalPath;+}++function addRecord(state: FingerprintState, ...parts: Array<string | number>): void {+ state.hash.update(parts.join('\0')).update('\n');+}++function isSensitive(rawPath: string, relativePath = ''): boolean {+ return (+ isReviewSensitiveCredentialPath(rawPath) ||+ (!!relativePath && isReviewSensitiveCredentialPath(relativePath))+ );+}++async function hashRange(+ handle: Awaited<ReturnType<typeof fs.open>>,+ state: FingerprintState,+ start: number,+ length: number,+): Promise<number> {+ const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, Math.max(1, length)));+ let position = start;+ let remaining = length;+ let totalBytesRead = 0;+ while (remaining > 0) {+ const requested = Math.min(buffer.length, remaining);+ const { bytesRead } = await handle.read(buffer, 0, requested, position);+ if (bytesRead <= 0) break;+ state.hash.update(buffer.subarray(0, bytesRead));+ totalBytesRead += bytesRead;+ position += bytesRead;+ remaining -= bytesRead;+ }+ return totalBytesRead;+}++async function addFile(+ absolutePath: string,+ relativePath: string,+ stat: Stats,+ state: FingerprintState,+): Promise<void> {+ if (+ !Number.isSafeInteger(stat.size) ||+ stat.size < 0 ||+ stat.size > state.contentBytesRemaining+ ) {+ throw new ReviewArtifactFingerprintLimitError(+ 'Review artifacts exceed the complete-content fingerprint byte limit',+ );+ }++ // Content, path, size and mode define the reusable result. Mutable file+ // timestamps are checked for TOCTOU below, but are intentionally omitted+ // from the digest so the regression exercises the complete content hash.+ addRecord(state, 'file', relativePath, stat.size, stat.mode);+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try {+ handle = await state.openFile(absolutePath, constants.O_RDONLY | NOFOLLOW_FLAG);+ const opened = await handle.stat();+ if (!opened.isFile() || !reviewArtifactPathIdentityMatches(stat, opened)) {+ throw new ReviewArtifactFingerprintChangedError(+ 'A review artifact changed while its content fingerprint was being prepared',+ );+ }++ const bytesRead = await hashRange(handle, state, 0, opened.size);+ const afterHandle = await handle.stat();+ const afterPath = await fs.lstat(absolutePath).catch(() => null);+ if (+ bytesRead !== opened.size ||+ !reviewArtifactPathIdentityMatches(opened, afterHandle) ||+ !afterPath ||+ afterPath.isSymbolicLink() ||+ !reviewArtifactPathIdentityMatches(opened, afterPath)+ ) {+ throw new ReviewArtifactFingerprintChangedError(+ 'A review artifact changed while its content fingerprint was being prepared',+ );+ }+ state.contentBytesRemaining -= bytesRead;+ addRecord(state, 'file-end', relativePath, bytesRead);+ } catch (error) {+ if (error instanceof ReviewArtifactFingerprintChangedError) throw error;+ throw new ReviewArtifactFingerprintChangedError(+ 'A review artifact could not be safely opened for content fingerprinting',+ { cause: error },+ );+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++async function walk(+ absolutePath: string,+ relativePath: string,+ state: FingerprintState,+): Promise<void> {+ if (isSensitive(absolutePath, relativePath)) return;+ if (state.entries >= state.maxDirectoryEntries) {+ throw new ReviewArtifactFingerprintLimitError(+ `Review artifact directory exceeds the ${state.maxDirectoryEntries.toLocaleString('en-US')}-entry fingerprint limit`,+ );+ }+ state.entries += 1;++ let stat: Stats;+ try {+ stat = await fs.lstat(absolutePath);+ } catch (error) {+ addRecord(+ state,+ 'missing-or-unreadable',+ relativePath,+ error instanceof Error ? error.name : 'unknown',+ );+ return;+ }++ if (stat.isSymbolicLink()) {+ let target = '';+ try {+ target = await fs.readlink(absolutePath);+ } catch {+ target = 'unreadable';+ }+ addRecord(state, 'symlink', relativePath, target, stat.mtimeMs, stat.ctimeMs);+ return;+ }+ if (stat.isFile() || stat.isDirectory()) {+ // Reject an intermediate directory that became a symlink after its parent+ // was enumerated; O_NOFOLLOW only protects the final path component.+ await assertCanonicalReviewArtifactPath(absolutePath);+ }+ if (stat.isFile()) {+ await addFile(absolutePath, relativePath, stat, state);+ return;+ }+ if (!stat.isDirectory()) {+ addRecord(state, 'other', relativePath, stat.size, stat.mtimeMs, stat.mode);+ return;+ }++ addRecord(state, 'directory', relativePath, stat.mtimeMs, stat.ctimeMs, stat.mode);+ let entries;+ try {+ entries = await fs.readdir(absolutePath, { withFileTypes: true });+ } catch (error) {+ addRecord(+ state,+ 'directory-read-error',+ relativePath,+ error instanceof Error ? error.name : 'unknown',+ );+ return;+ }+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+ for (const entry of entries) {+ const childRelative = relativePath ? `${relativePath}/${entry.name}` : entry.name;+ if (isSensitive(entry.name, childRelative)) continue;+ await walk(path.join(absolutePath, entry.name), childRelative, state);+ }+}++/**+ * Build a local-only identity for explicit review artifacts. The manifest is+ * deliberately bounded, ignores credential paths, and hashes every readable+ * file byte. Exceeding the byte budget fails closed instead of degrading to a+ * sampled or metadata-only identity that could reuse a stale Review result.+ */+export async function fingerprintReviewArtifacts(+ paths: readonly string[],+ options: ReviewArtifactFingerprintOptions = {},+): Promise<string> {+ const maxDirectoryEntries = options.maxDirectoryEntries ?? MAX_DIRECTORY_ENTRIES;+ if (!Number.isSafeInteger(maxDirectoryEntries) || maxDirectoryEntries <= 0) {+ throw new TypeError('maxDirectoryEntries must be a positive safe integer');+ }+ const maxContentBytes = options.maxContentBytes ?? MAX_TOTAL_CONTENT_BYTES;+ if (!Number.isSafeInteger(maxContentBytes) || maxContentBytes < 0) {+ throw new TypeError('maxContentBytes must be a non-negative safe integer');+ }+ const state: FingerprintState = {+ hash: createHash('sha256'),+ entries: 0,+ maxDirectoryEntries,+ contentBytesRemaining: maxContentBytes,+ openFile: options.openFile ?? ((filePath, flags) => fs.open(filePath, flags)),+ };+ const canonicalRoots = new Set<string>();+ for (const rawPath of paths) {+ if (!path.isAbsolute(rawPath) || isSensitive(rawPath)) continue;+ const canonical = await resolveFingerprintRoot(rawPath);+ if (!isSensitive(canonical)) canonicalRoots.add(canonical);+ }+ for (const root of [...canonicalRoots].sort()) {+ addRecord(state, 'root', root);+ await walk(root, '.', state);+ }+ return state.hash.digest('hex');+}++export class ReviewArtifactChangedDuringPreparationError extends Error {}++/**+ * Brackets evidence extraction with the same content fingerprint. This closes+ * the window where an old excerpt could otherwise be paired with a new first+ * baseline and later be reported as a fresh completed review.+ */+export async function prepareWithStableReviewArtifacts<T>(+ paths: readonly string[],+ prepare: () => Promise<T>,+): Promise<{ value: T; fingerprint: string }> {+ const before = await fingerprintReviewArtifacts(paths);+ const value = await prepare();+ const after = await fingerprintReviewArtifacts(paths);+ if (after !== before) {+ throw new ReviewArtifactChangedDuringPreparationError(+ 'A review artifact changed while evidence was being prepared',+ );+ }+ return { value, fingerprint: after };+}diff --cc apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.tsindex 77f22f781e,f582df58c4..dbc6bc8eb7--- a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts@@@ -137,11 -137,66 +137,73 @@@ describe('NewMakerDraftRoute Orca worke);expect(sessionViewSource).toContain('if (sessionHandoffPreparing) return false;');expect(sessionViewSource).not.toContain('if (worktreePreparing) return false;');- expect(sessionViewSource).toContain('disabled={remoteHandoffPreparing}');+ expect(sessionViewSource).toContain(+ "disabled={remoteHandoffPreparing || session?.source === 'review'}",+ );});+ it('rebases delayed-create inline metadata after rewriting a Pi skill alias', () => {- const pendingBranch = sessionViewSource.slice(- sessionViewSource.indexOf('const pending = consumePending(sessionId);'),- sessionViewSource.indexOf('const pendingGoalConsumedRef'),- ).replace(/\r\n/g, '\n');++ const pendingBranch = sessionViewSource++ .slice(++ sessionViewSource.indexOf('const pending = consumePending(sessionId);'),++ sessionViewSource.indexOf('const pendingGoalConsumedRef'),++ )++ .replace(/\r\n/g, '\n');++ expect(pendingBranch).toContain(+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.agentReferences,',+ );+ expect(pendingBranch).toContain(+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.pastedTextRanges,',+ );- expect(pendingBranch).toContain(- 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.slashCommandRanges,',++ expect(pendingBranch).toMatch(++ /rebaseInlineRangesAfterSlashCommandRewrite\(\s*\n\s*pending\.slashCommandRanges,/,+ );+ expect(pendingBranch).toContain('agentReferences: pendingAgentReferences');+ expect(pendingBranch).toContain('pastedTextRanges: pendingPastedTextRanges');+ expect(pendingBranch).toContain('slashCommandRanges: pendingSlashCommandRanges');+ expect(pendingBranch).toContain('PI_RUNTIME_SKILL_RETRY_DELAYS_MS');+ });++ it('reconciles Pi skill aliases after the user selects a working directory', () => {- const workingDirHandler = sessionViewSource.slice(- sessionViewSource.indexOf('const handleWorkingDirChange = useCallback('),- sessionViewSource.indexOf('const maybeShowContextUsage'),- ).replace(/\r\n/g, '\n');++ const workingDirHandler = sessionViewSource++ .slice(++ sessionViewSource.indexOf('const handleWorkingDirChange = useCallback('),++ sessionViewSource.indexOf('const maybeShowContextUsage'),++ )++ .replace(/\r\n/g, '\n');++ expect(sessionViewSource).toContain('const commands = options?.workingDirOverride');+ expect(workingDirHandler).toContain('workingDirOverride: newDir');- expect(workingDirHandler).toContain(- 'piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS',- );++ expect(workingDirHandler).toContain('piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS');+ expect(workingDirHandler).toContain('preparePiRuntime: async () =>');+ expect(workingDirHandler).toContain("'maker:create-session'");+ expect(workingDirHandler).toContain('window.electronAPI.maker.createSession(createOpts)');+ expect(workingDirHandler).toContain(+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.agentReferences,',+ );+ expect(workingDirHandler).toContain(+ 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.pastedTextRanges,',+ );- expect(workingDirHandler).toContain(- 'rebaseInlineRangesAfterSlashCommandRewrite(\n pending.slashCommandRanges,',++ expect(workingDirHandler).toMatch(++ /rebaseInlineRangesAfterSlashCommandRewrite\(\s*\n\s*pending\.slashCommandRanges,/,+ );+ expect(workingDirHandler).toContain('slashDispatch.message,');+ });++ it('uses bounded Pi runtime reconciliation for ordinary sends and steering', () => {- const slashDispatchBranch = sessionViewSource.slice(- sessionViewSource.indexOf('const originalMessage = message;'),- sessionViewSource.indexOf('if (slashDispatch.handled) return;'),- ).replace(/\r\n/g, '\n');++ const slashDispatchBranch = sessionViewSource++ .slice(++ sessionViewSource.indexOf('const originalMessage = message;'),++ sessionViewSource.indexOf('if (slashDispatch.handled) return slashDispatch.accepted;'),++ )++ .replace(/\r\n/g, '\n');+- expect(slashDispatchBranch.match(/piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS/g))- .toHaveLength(2);++ expect(++ slashDispatchBranch.match(/piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS/g),++ ).toHaveLength(2);+ });+it('refreshes the remote mirror even when the remote enableOrca reports failure', () => {// 控制端的 invoke 超时**不会取消**被控端正在跑的 enableOrca,所以「控制端报失败、// 对端稍后仍建成 team」是真实终态(codex review P1)。回流放在 finally 里,让diff --cc apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.tsindex 9ad389e652,0000000000..327eeafd3amode 100644,000000..100644--- a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts+++ b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts@@@ -1,41 -1,0 +1,62 @@@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++const sessionViewSource = readFileSync(+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSessionView.tsx'),+ 'utf8',+).replace(/\r\n/g, '\n');+const dispatchStart = sessionViewSource.indexOf('const maybeDispatchDesktopSlashCommand');+const dispatchEnd = sessionViewSource.indexOf('const maybeShowContextUsage', dispatchStart);+const dispatchSource = sessionViewSource.slice(dispatchStart, dispatchEnd);++describe('/review command dispatch', () => {+ it('crosses the Main boundary with this invocation attachment snapshot before returning', () => {+ expect(dispatchSource).toContain("if (hit.name === 'review')");+ expect(dispatchSource).toContain('serializeAttachedFiles(files)');+ expect(dispatchSource).toContain('.startReview({');+ expect(dispatchSource).toContain('await window.electronAPI.maker.startReview({');- expect(dispatchSource).toContain("return 'accepted'");- expect(dispatchSource).toContain("return 'rejected'");- expect(sessionViewSource).toContain(- "if (desktopCommand !== 'not-handled') return desktopCommand === 'accepted'",- );++ expect(dispatchSource).toContain('return { handled: true, accepted: true, message }');++ expect(dispatchSource).toContain('return { handled: true, accepted: false, message }');++ expect(sessionViewSource).toContain('if (slashDispatch.handled) return slashDispatch.accepted');+ expect(dispatchSource.indexOf('.startReview({')).toBeLessThan(+ dispatchSource.indexOf('void dispatchCommand(hit'),+ );+ });++ it('does not hand Review attachments through a shared mutable ref or renderer event', () => {+ expect(sessionViewSource).not.toContain('pendingReviewFilesRef');+ expect(sessionViewSource).not.toContain("payload.command !== 'review'");+ });++ it('restores a rejected pending first Review with both text and attachments', () => {- expect(sessionViewSource).toContain("if (desktopCommand === 'rejected')");++ expect(sessionViewSource).toContain('if (!slashDispatch.accepted)');+ expect(sessionViewSource).toContain('restoreRemoteOptimisticDraft(sessionId, {');+ expect(sessionViewSource).toContain('text: plainTextToTiptapDoc(pending.text)');+ expect(sessionViewSource).toContain('attachments: pending.files ?? []');+ });++++ it('consumes the handoff copy after a rejected Review is restored to the composer', () => {++ const pendingReviewBranch = sessionViewSource.slice(++ sessionViewSource.indexOf(++ 'if (slashDispatch.handled) {',++ sessionViewSource.indexOf('const pending = consumePending(sessionId);'),++ ),++ sessionViewSource.indexOf(++ 'const pendingAgentReferences',++ sessionViewSource.indexOf('const pending = consumePending(sessionId);'),++ ),++ );++++ expect(pendingReviewBranch).toContain('restoreRemoteOptimisticDraft(sessionId, {');++ expect(pendingReviewBranch).toContain(++ 'await deliverRecoverableHandoff(sessionId, () => true);',++ );++ expect(pendingReviewBranch).not.toContain('() => slashDispatch.accepted');++ });++++ it('only clears a deferred composer after Main accepts the Review', () => {++ expect(dispatchSource).toContain('if (slashDispatch.accepted) pending.onDeferredAccepted?.();');++ });+});diff --cc apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 1a00fb3b20,9681e8d27a..f213654897--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@@ -199,10 -207,10 +209,7 @@@ importimport { getCollaborationStartErrorMessage } from './collaborationErrors';import { useCollabProjectPolicy } from './hooks/useCollabProjectPolicy';import { resolveCollabEntryPolicy } from './collabEntryPolicy';--import {-- consumePendingRemoteCollab,-- enableRemoteCollabForSession,--} from './remoteCollabHandoff';++import { consumePendingRemoteCollab, enableRemoteCollabForSession } from './remoteCollabHandoff';import { shouldFallbackVendorModel } from './lib/vendorModelFallback';import { localizeAgentStatus } from './lib/localizeAgentStatus';import { createSessionRefreshSequence } from './lib/sessionRefreshSequence';@@@ -1203,7 -1211,10 +1210,15 @@@ export function CCAgentSessionView(// (与 ChatInput palette 同源)。否则此 cache 取的是控制端命令,maybeDispatchDesktopSlashCommand// 会把被控端 skill/builtin 影子掉的 /clear、/help 等误判成 desktop 命令、在控制端执行。// 本机会话 remoteDeviceId=undefined → 行为不变。desktop 命令始终本地(见 loadAllCommands)。- loadAllCommands(agentKind, wd, { skipAgentSkills: isRemoteSession }, remoteDeviceId)- loadAllCommands(agentKind, wd, {- skipAgentSkills: isRemoteSession,- sessionId: session?.id,- }, remoteDeviceId)++ loadAllCommands(++ agentKind,++ wd,++ {++ skipAgentSkills: isRemoteSession,++ sessionId: session?.id,++ },++ remoteDeviceId,++ ).then((cmds) => {if (!cancelled) setAllCommands(cmds);})@@@ -2405,42 -2351,67 +2354,93 @@@async (message: string,files?: AttachedFile[],- ): Promise<'not-handled' | 'accepted' | 'rejected'> => {+ options?: {+ allowDesktopDispatch?: boolean;+ piRuntimeRetryDelaysMs?: readonly number[];+ workingDirOverride?: string;+ preparePiRuntime?: () => Promise<void>;+ },- ): Promise<{ handled: boolean; message: string }> => {++ ): Promise<{ handled: boolean; accepted: boolean; message: string }> => {const slashMatch = message.match(/^\/(\S+)(?:\s+(.*))?$/s);- if (!slashMatch) return 'not-handled';- if (!slashMatch) return { handled: false, message };++ if (!slashMatch) return { handled: false, accepted: false, message };const cmdName = slashMatch[1].toLowerCase();const args = slashMatch[2] ?? '';+ const allowDesktopDispatch = options?.allowDesktopDispatch ?? true;+ const workingDir = options?.workingDirOverride ?? session?.workingDir;const cached = allCommandsRef.current;- const commands = cached.length > 0 ? cached : await getHelpCommandsSnapshot();- const hit = commands.find((c) => c.name.toLowerCase() === cmdName);- if (hit?.kind !== 'desktop') return 'not-handled';+ // A newly selected project changes command ownership, so do not let a+ // pre-selection global hit suppress the forced project catalog refresh.+ const commands = options?.workingDirOverride+ ? []+ : cached.length > 0+ ? cached+ : await getHelpCommandsSnapshot();+ const agentKind = dbToMakerAgentKind(session?.agentKind);+ const reconcileParams = {+ agentKind,+ sessionId: session?.id,+ commandName: cmdName,+ commands,- reload: () => loadAllCommands(- agentKind,- workingDir,- {- skipAgentSkills: isRemoteSession,- sessionId: session?.id,- forceReload: true,- },- remoteDeviceId,- ),++ reload: () =>++ loadAllCommands(++ agentKind,++ workingDir,++ {++ skipAgentSkills: isRemoteSession,++ sessionId: session?.id,++ forceReload: true,++ },++ remoteDeviceId,++ ),+ };+ const reconciled = options?.piRuntimeRetryDelaysMs+ ? await reconcilePiRuntimeCommandForDispatchWithRetry({+ ...reconcileParams,+ prepareRuntime: options.preparePiRuntime,+ retryDelaysMs: options.piRuntimeRetryDelaysMs,+ })+ : await reconcilePiRuntimeCommandForDispatch(reconcileParams);+ if (reconciled.commands !== commands) {+ allCommandsRef.current = reconciled.commands;+ setAllCommands(reconciled.commands);+ }+ const hit = reconciled.command;+ if (hit?.kind !== 'desktop') {+ return {+ handled: false,- message: agentKind === 'pi'- ? rewriteAgentSkillInvocationForDispatch(message, hit)- : message,++ accepted: false,++ message:++ agentKind === 'pi' ? rewriteAgentSkillInvocationForDispatch(message, hit) : message,+ };+ }- if (!allowDesktopDispatch) return { handled: false, message };++ if (!allowDesktopDispatch) return { handled: false, accepted: false, message };+ // Review is handed to Main immediately with this invocation's serialized+ // attachments. It must not depend on this React view remaining mounted,+ // nor share a mutable attachment ref with a later command.+ if (hit.name === 'review') {- if (!sessionId) return 'rejected';++ if (!sessionId) return { handled: true, accepted: false, message };+ if (remoteDeviceId) {+ toast.warning(t('review.toast.remoteUnsupported'));- return 'rejected';++ return { handled: true, accepted: false, message };+ }+ const attachments = files?.length ? serializeAttachedFiles(files) : undefined;+ try {+ await window.electronAPI.maker.startReview({+ sourceSessionId: sessionId,+ ...(args.trim() ? { focus: args.trim() } : {}),+ ...(attachments?.length ? { attachments } : {}),+ });- return 'accepted';++ return { handled: true, accepted: true, message };+ } catch (err) {+ const ipcError = extractIpcError(err);+ toast.error(+ ipcError?.message || (err instanceof Error ? err.message : t('review.toast.failed')),+ );- return 'rejected';++ return { handled: true, accepted: false, message };+ }+ }- // /issue still uses the existing command event because its action runs- // inside this mounted composer. Other desktop commands have no files.+ // 仅 /issue 需要携带附件:snapshot 到 ref,DESKTOP_COMMAND_TRIGGERED 回流时消费。+ // 其它 desktop 命令(/help /clear /cmd ...)不涉及附件,不写 ref。if (hit.name === 'issue') {pendingIssueFilesRef.current = files && files.length > 0 ? files : undefined;}@@@ -2454,9 -2425,149 +2454,151 @@@...(args ? { args } : {}),...(remoteDeviceId ? { deviceId: remoteDeviceId } : {}),});- return 'accepted';- return { handled: true, message };++ return { handled: true, accepted: true, message };},- [getHelpCommandsSnapshot, session?.workingDir, sessionId, remoteDeviceId, t],+ [+ getHelpCommandsSnapshot,+ isRemoteSession,+ session?.agentKind,+ session?.id,+ session?.workingDir,+ sessionId,+ remoteDeviceId,++ t,+ ],+ );++ const handleWorkingDirChange = useCallback(+ (newDir: string | null) => {+ // ChatInput already persists workingDir to server; we just refresh our local copy.+ refreshServerSession();++ // Auto-continue: if there's a pending send and a valid dir was selected, execute step ③.+ // The first slash reconciliation ran before this directory existed, so refresh again with+ // the selected project before dispatching and keep inline metadata aligned with any alias rewrite.+ const pending = pendingSendRef.current;+ if (!newDir || !pending) return;+ pendingSendRef.current = null;+ void (async () => {+ try {+ const slashDispatch = await maybeDispatchDesktopSlashCommand(+ pending.message,+ pending.files,+ {+ allowDesktopDispatch: pending.deliveryMode !== 'steer',+ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,+ workingDirOverride: newDir,+ preparePiRuntime: async () => {+ if (!sessionId || dbToMakerAgentKind(session?.agentKind) !== 'pi') return;+ const createOpts = {+ id: sessionId,+ ...buildCreateOptsForCurrentSession(+ sessionId,+ pending.model,+ pending.effort,+ pending.permissionMode,+ newDir,+ pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : undefined,+ ),+ agentKind: 'pi' as const,+ workingDir: newDir,+ orcaRole: session?.orcaRole ?? null,+ };+ if (remoteDeviceId) {+ await window.electronAPI.deviceLink.invoke(+ remoteDeviceId,+ 'maker:create-session',+ [createOpts],+ );+ } else {+ await window.electronAPI.maker.createSession(createOpts);+ }+ },+ },+ );+ if (slashDispatch.handled) {- pending.onDeferredAccepted?.();++ if (slashDispatch.accepted) pending.onDeferredAccepted?.();+ return;+ }++ const pendingAgentReferences = pending.agentReferences+ ? rebaseInlineRangesAfterSlashCommandRewrite(+ pending.agentReferences,+ pending.message,+ slashDispatch.message,+ )+ : undefined;+ const pendingPastedTextRanges = pending.pastedTextRanges+ ? rebaseInlineRangesAfterSlashCommandRewrite(+ pending.pastedTextRanges,+ pending.message,+ slashDispatch.message,+ )+ : undefined;- const pendingSlashCommandRanges = pending.slashCommandRanges !== undefined- ? rebaseInlineRangesAfterSlashCommandRewrite(- pending.slashCommandRanges,- pending.message,- slashDispatch.message,- )- : undefined;++ const pendingSlashCommandRanges =++ pending.slashCommandRanges !== undefined++ ? rebaseInlineRangesAfterSlashCommandRewrite(++ pending.slashCommandRanges,++ pending.message,++ slashDispatch.message,++ )++ : undefined;+ const dispatch = pending.deliveryMode === 'steer' ? steerMessage : sendMessage;+ const accepted = await dispatch(+ slashDispatch.message,+ pending.model,+ pending.effort,+ pending.permissionMode,+ newDir,+ pending.files,+ pending.mentions,+ pending.quotesEncoded ||+ pending.vendorOptions !== undefined ||+ pendingAgentReferences?.length ||+ pendingPastedTextRanges?.length ||+ pendingSlashCommandRanges !== undefined ||+ pending.onRemoteOptimisticFailure !== undefined ||+ pending.onDeferredAccepted !== undefined+ ? {+ ...(pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : {}),+ ...(pending.quotesEncoded ? { quotesEncoded: true } : {}),+ ...(pendingAgentReferences?.length+ ? { agentReferences: pendingAgentReferences }+ : {}),+ ...(pendingPastedTextRanges?.length+ ? { pastedTextRanges: pendingPastedTextRanges }+ : {}),+ ...(pendingSlashCommandRanges !== undefined+ ? { slashCommandRanges: pendingSlashCommandRanges }+ : {}),+ ...(pending.onRemoteOptimisticFailure+ ? { onRemoteOptimisticFailure: pending.onRemoteOptimisticFailure }+ : {}),+ ...(pending.onDeferredAccepted+ ? { onDeferredAccepted: pending.onDeferredAccepted }+ : {}),+ }+ : undefined,+ );+ if (accepted) pending.onDeferredAccepted?.();+ } catch (error) {+ log.warn(+ 'pending send after working directory selection failed:',+ error instanceof Error ? error.message : String(error),+ );+ }+ })();+ },+ [+ maybeDispatchDesktopSlashCommand,+ refreshServerSession,+ remoteDeviceId,+ session?.agentKind,+ session?.orcaRole,+ sessionId,+ sendMessage,+ steerMessage,+ ],);const maybeShowContextUsage = useCallback(@@@ -2563,9 -2674,48 +2705,49 @@@// 广播回 renderer (上面 useEffect 订阅), 不发给 agent。// - agent-builtin / agent-skill / 没命中任何已知命令 → 走默认 send,// 原文(含前导 `/`)直接送 agent, 由 SDK 自己识别 (/compact 等)。- if (deliveryMode !== 'steer') {- const desktopCommand = await maybeDispatchDesktopSlashCommand(message, files);- if (desktopCommand !== 'not-handled') return desktopCommand === 'accepted';+ const originalMessage = message;- const slashDispatch = deliveryMode === 'steer'- ? await maybeDispatchDesktopSlashCommand(message, files, {- allowDesktopDispatch: false,- piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,- })- : await maybeDispatchDesktopSlashCommand(message, files, {- piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,- });- if (slashDispatch.handled) return;++ const slashDispatch =++ deliveryMode === 'steer'++ ? await maybeDispatchDesktopSlashCommand(message, files, {++ allowDesktopDispatch: false,++ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,++ })++ : await maybeDispatchDesktopSlashCommand(message, files, {++ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,++ });++ if (slashDispatch.handled) return slashDispatch.accepted;+ message = slashDispatch.message;+ if (message !== originalMessage && opts) {+ opts = {+ ...opts,+ ...(opts.agentReferences+ ? {+ agentReferences: rebaseInlineRangesAfterSlashCommandRewrite(+ opts.agentReferences,+ originalMessage,+ message,+ ),+ }+ : {}),+ ...(opts.pastedTextRanges+ ? {+ pastedTextRanges: rebaseInlineRangesAfterSlashCommandRewrite(+ opts.pastedTextRanges,+ originalMessage,+ message,+ ),+ }+ : {}),+ ...(opts.slashCommandRanges !== undefined+ ? {+ slashCommandRanges: rebaseInlineRangesAfterSlashCommandRewrite(+ opts.slashCommandRanges,+ originalMessage,+ message,+ ),+ }+ : {}),+ };}// ① 本机会话维持既有 readiness gate。device-link 已建任务不把视图生命周期内@@@ -3027,22 -3177,38 +3209,49 @@@}// 三处交接统一走 deliverRecoverableHandoff:交付成功才丢副本,// resolve false / 抛错都保留(见该函数注释)。- const desktopCommand = await maybeDispatchDesktopSlashCommand(pending.text, pending.files);- if (desktopCommand !== 'not-handled') {- if (desktopCommand === 'rejected') {+ let pendingText = pending.text;- const dispatched = await deliverRecoverableHandoff(sessionId, async () => {- const slashDispatch = await maybeDispatchDesktopSlashCommand(- pending.text,- pending.files,- { piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS },- );- pendingText = slashDispatch.message;- return slashDispatch.handled;++ const slashDispatch = await maybeDispatchDesktopSlashCommand(pending.text, pending.files, {++ piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,+ });- if (dispatched) return;++ pendingText = slashDispatch.message;++ if (slashDispatch.handled) {++ if (!slashDispatch.accepted) {+ // NewMaker 已把源草稿移交并清空;Main 没受理 `/review` 时,把正文和附件+ // 一起放回新会话输入框。复用失败发送的 FIFO 恢复器,避免覆盖用户在- // IPC 等待期间已经输入的新内容。++ // IPC 等待期间已经输入的新内容。恢复成功后 composer/draft 已成为新的++ // 可靠归宿,旧交接副本必须消费,避免下次空输入框再次恢复过期命令。+ restoreRemoteOptimisticDraft(sessionId, {+ clientId: `pending-review:${pending.createdAt}`,+ text: plainTextToTiptapDoc(pending.text),+ attachments: pending.files ?? [],+ browserComments: [],+ });+ }- await deliverRecoverableHandoff(sessionId, () => desktopCommand === 'accepted');++ await deliverRecoverableHandoff(sessionId, () => true);+ return;+ }+ const pendingAgentReferences = pending.agentReferences+ ? rebaseInlineRangesAfterSlashCommandRewrite(+ pending.agentReferences,+ pending.text,+ pendingText,+ )+ : undefined;+ const pendingPastedTextRanges = pending.pastedTextRanges+ ? rebaseInlineRangesAfterSlashCommandRewrite(+ pending.pastedTextRanges,+ pending.text,+ pendingText,+ )+ : undefined;- const pendingSlashCommandRanges = pending.slashCommandRanges !== undefined- ? rebaseInlineRangesAfterSlashCommandRewrite(- pending.slashCommandRanges,- pending.text,- pendingText,- )- : undefined;++ const pendingSlashCommandRanges =++ pending.slashCommandRanges !== undefined++ ? rebaseInlineRangesAfterSlashCommandRewrite(++ pending.slashCommandRanges,++ pending.text,++ pendingText,++ )++ : undefined;// 必须 await:sendMessage 在设备离线 / 访问被撤销 / 远端 enqueue 拒绝时不抛错,// 而是 resolve false —— 不等它就丢副本,正文会从界面和磁盘上一起消失(codex P1)。await deliverRecoverableHandoff(sessionId, () =>@@@ -3268,12 -3434,12 +3477,12 @@@worktreePreparing ||Boolean(pendingPlanReview ||-- pendingPermission ||-- pendingAskUser ||-- pendingPluginSetup ||-- pendingIssueConfirm ||-- pendingRenameSessionsConfirm ||-- pendingGhostGrantConfirm,++ pendingPermission ||++ pendingAskUser ||++ pendingPluginSetup ||++ pendingIssueConfirm ||++ pendingRenameSessionsConfirm ||++ pendingGhostGrantConfirm,);useEffect(() => {if (shareSelectionActive && shareSelectionBlocked) shareSelectionStore.exit();@@@ -4021,10 -4187,10 +4231,7 @@@<Spinner size={12} className="text-[var(--workingdir-icon)]" /><span className="block min-w-0 truncate text-12 font-medium leading-none text-[var(--workingdir-text)]">{t('ccAgent.layout.worktreeCreating', '正在创建 worktree')}{' '}-- <code className="font-mono text-11 opacity-80">-- {worktreeCreation.name}-- </code>-- …++ <code className="font-mono text-11 opacity-80">{worktreeCreation.name}</code>…</span></div>) : worktreeCreation?.status === 'failed' ? (diff --cc packages/maker-core/src/agents/claude-code/index.tsindex a3e55d94f9,9d1d8e9583..f0761fb2d4--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@@ -1868,9 -1760,20 +1868,20 @@@ export class ClaudeCodeAgent extends Ba// (eg. summarized reasoning UI 本地有 remote 没)。getter 让 memOverride /// mutableFastMode 读最新值 (setMemory / setFastMode 运行时改) 而不是 buildQuery// 时快照。装配逻辑(含 apiKeyHelper 恒置空的鉴权防线)在 flag-settings.ts。- const buildSettings = (): Settings =>- buildClaudeFlagSettings({+ const buildSettings = (): Settings => {+ const settings = buildClaudeFlagSettings({showThinkingSummaries,+ // availableModels is the SDK's highest-priority allowlist. Convert the+ // whole current catalog and the selected model through the one+ // catalog-id → wire-string mapper so startup and live switches share+ // the same [1m] and legacy conversion rules. Keep the selected model+ // even when it is temporarily outside the catalog.+ availableModels: [+ ...new Set([+ ...this.capabilities.availableModels.map(({ id }) => sdkModelFor(id)),+ sdkModelFor(mutableModel),+ ]),+ ],// Do not carry the local manager's native-memory suppression across the// SSH boundary: the remote host retains its own Claude memory// configuration. Maker Memory on remote sessions is injected via thediff --cc packages/maker-core/src/agents/shared/sensitive-credential-paths.test.tsindex cbb6ebd63c,0000000000..e0a647ce21mode 100644,000000..100644--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts@@@ -1,52 -1,0 +1,67 @@@+import { describe, expect, it } from "vitest";++import {+ REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS,+ isReviewSensitiveCredentialPath,+ isReviewSensitiveCredentialSelector,+ isSensitiveCredentialPath,+} from "./sensitive-credential-paths.js";++describe("Review credential path policy", () => {+ it("adds dotenv files without treating arbitrary .env text as a path", () => {+ expect(isSensitiveCredentialPath("/repo/.env.local")).toBe(false);+ expect(isReviewSensitiveCredentialPath("/repo/.env.local")).toBe(true);+ expect(isReviewSensitiveCredentialPath("jq .env data.json")).toBe(false);+ });++ it("retains the shared credential path protections", () => {+ expect(isReviewSensitiveCredentialPath("/Users/me/.ssh/id_ed25519")).toBe(+ true,+ );+ expect(isReviewSensitiveCredentialPath("/repo/.git/config")).toBe(true);+ expect(isReviewSensitiveCredentialPath("/repo/.gitignore")).toBe(false);+ expect(isReviewSensitiveCredentialPath("/repo/src/environment.ts")).toBe(+ false,+ );+ });+++ it("keeps generated dependency trees outside the Review read scope", () => {++ expect(++ isReviewSensitiveCredentialPath("/repo/node_modules/pkg/index.js"),++ ).toBe(true);++ expect(++ isReviewSensitiveCredentialPath("/repo/packages/app/node_modules"),++ ).toBe(true);++ expect(++ isReviewSensitiveCredentialPath("/repo/src/node_modules-helper.ts"),++ ).toBe(false);++ });+++ it("recognizes credentials hidden behind file selector syntax", () => {+ for (const selector of [+ "**/*.pem",+ "**/.env*",+ "{src/**,**/.ssh/**}",+ "**/{safe.ts,.env.local}",+ ]) {+ expect(isReviewSensitiveCredentialSelector(selector)).toBe(true);+ }- expect(isReviewSensitiveCredentialSelector("{src,test}/**/*.{ts,tsx}")).toBe(false);++ expect(++ isReviewSensitiveCredentialSelector("{src,test}/**/*.{ts,tsx}"),++ ).toBe(false);+ });++ it("keeps directory search denies aligned for common credential files", () => {+ expect(REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS).toEqual(+ expect.arrayContaining([+ "**/.env.*",+ "**/.git/**",++ "**/node_modules/**",+ "**/credentials.json",+ "**/auth.json",+ "**/*.pem",+ "**/id_ed25519",+ ]),+ );+ });+});diff --cc packages/maker-core/src/agents/shared/sensitive-credential-paths.tsindex 3a97a960a5,e83412691d..835b1947c3--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts@@@ -6,107 -6,22 +6,141 @@@* generated extension instead of maintaining a second handwritten regex list.*/export const SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [-- { source: String.raw`(?:^|[\\/\s'"~])\.(?:ssh|aws|gnupg|kube|docker|azure|claude|codex)\b`, flags: 'i' },-- { source: String.raw`(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc|git-credentials)\b`, flags: 'i' },-- { source: String.raw`[\\/]\.cargo[\\/]credentials(?:\.toml)?\b`, flags: 'i' },-- { source: String.raw`[\\/]\.m2[\\/]settings(?:-security)?\.xml\b`, flags: 'i' },-- { source: String.raw`\bapplication_default_credentials\b`, flags: 'i' },-- { source: String.raw`\bcredentials\.json\b`, flags: 'i' },-- { source: String.raw`[\\/](?:codex|claude|gcloud|containers)[\\/]auth\.json\b`, flags: 'i' },-- { source: String.raw`[\\/]\.config[\\/](?:gh|hub|glab|op|gcloud)\b`, flags: 'i' },-- { source: String.raw`/proc/[^\s]*/environ\b`, flags: 'i' },-- { source: String.raw`\bid_rsa\b|\bid_ed25519\b|\bid_ecdsa\b|\bid_dsa\b|\.pem\b|\.p12\b`, flags: 'i' },++ {++ source: String.raw`(?:^|[\\/\s'"~])\.(?:ssh|aws|gnupg|kube|docker|azure|claude|codex)\b`,++ flags: "i",++ },++ {++ source: String.raw`(?:^|[\\/\s'"~])\.(?:netrc|npmrc|pgpass|pypirc|git-credentials)\b`,++ flags: "i",++ },++ { source: String.raw`[\\/]\.cargo[\\/]credentials(?:\.toml)?\b`, flags: "i" },++ {++ source: String.raw`[\\/]\.m2[\\/]settings(?:-security)?\.xml\b`,++ flags: "i",++ },++ { source: String.raw`\bapplication_default_credentials\b`, flags: "i" },++ { source: String.raw`\bcredentials\.json\b`, flags: "i" },++ {++ source: String.raw`[\\/](?:codex|claude|gcloud|containers)[\\/]auth\.json\b`,++ flags: "i",++ },++ {++ source: String.raw`[\\/]\.config[\\/](?:gh|hub|glab|op|gcloud)\b`,++ flags: "i",++ },++ { source: String.raw`/proc/[^\s]*/environ\b`, flags: "i" },++ {++ source: String.raw`\bid_rsa\b|\bid_ed25519\b|\bid_ecdsa\b|\bid_dsa\b|\.pem\b|\.p12\b`,++ flags: "i",++ },+] as const;++/**+ * Review tools receive structured file paths rather than arbitrary shell+ * source, so they can safely treat dotenv files as credentials without+ * misclassifying data expressions such as `jq .env`.+ */+export const REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [+ ...SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,- { source: String.raw`(?:^|[\\/])\.env(?:\.[^\\/]+)?$`, flags: 'i' },++ { source: String.raw`(?:^|[\\/])\.env(?:\.[^\\/]+)?$`, flags: "i" },+ // Git config can contain credential-bearing remote URLs, while object storage+ // can reconstruct a sensitive tracked file even when its worktree path is+ // denied. Review receives a sanitized diff and never needs raw .git access.- { source: String.raw`(?:^|[\\/])\.git(?:[\\/]|$)`, flags: 'i' },++ { source: String.raw`(?:^|[\\/])\.git(?:[\\/]|$)`, flags: "i" },++ // Generated dependency trees are not delivery artifacts. Keeping them out of++ // the Review read scope also keeps the full-workspace freshness fingerprint++ // bounded without leaving readable ignored content outside that baseline.++ { source: String.raw`(?:^|[\\/])node_modules(?:[\\/]|$)`, flags: "i" },+] as const;++/**+ * File-search deny globs shared by Review harnesses.+ *+ * Path regexes protect explicit reads and symlink targets. Directory-wide+ * Grep/Glob/Find tools need a second, execution/result-level boundary because+ * their input can be only a granted directory with no concrete file selector.+ */+export const REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS = [- '**/.env',- '**/.env.*',- '**/.git',- '**/.git/**',- '**/.ssh/**',- '**/.aws/**',- '**/.gnupg/**',- '**/.kube/**',- '**/.docker/**',- '**/.azure/**',- '**/.claude/**',- '**/.codex/**',- '**/.netrc',- '**/.npmrc',- '**/.pgpass',- '**/.pypirc',- '**/.git-credentials',- '**/.cargo/credentials',- '**/.cargo/credentials.toml',- '**/.m2/settings.xml',- '**/.m2/settings-security.xml',- '**/application_default_credentials*',- '**/credentials.json',- '**/auth.json',- '**/.config/gh/**',- '**/.config/hub/**',- '**/.config/glab/**',- '**/.config/op/**',- '**/.config/gcloud/**',- '**/environ',- '**/*.pem',- '**/*.p12',- '**/id_rsa',- '**/id_ed25519',- '**/id_ecdsa',- '**/id_dsa',++ "**/.env",++ "**/.env.*",++ "**/.git",++ "**/.git/**",++ "**/node_modules",++ "**/node_modules/**",++ "**/.ssh/**",++ "**/.aws/**",++ "**/.gnupg/**",++ "**/.kube/**",++ "**/.docker/**",++ "**/.azure/**",++ "**/.claude/**",++ "**/.codex/**",++ "**/.netrc",++ "**/.npmrc",++ "**/.pgpass",++ "**/.pypirc",++ "**/.git-credentials",++ "**/.cargo/credentials",++ "**/.cargo/credentials.toml",++ "**/.m2/settings.xml",++ "**/.m2/settings-security.xml",++ "**/application_default_credentials*",++ "**/credentials.json",++ "**/auth.json",++ "**/.config/gh/**",++ "**/.config/hub/**",++ "**/.config/glab/**",++ "**/.config/op/**",++ "**/.config/gcloud/**",++ "**/environ",++ "**/*.pem",++ "**/*.p12",++ "**/id_rsa",++ "**/id_ed25519",++ "**/id_ecdsa",++ "**/id_dsa",] as const;export const SENSITIVE_CREDENTIAL_PATH_PATTERNS: readonly RegExp[] =-- SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS.map(({ source, flags }) => new RegExp(source, flags));++ SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS.map(++ ({ source, flags }) => new RegExp(source, flags),++ );export function isSensitiveCredentialPath(target: string): boolean {-- return typeof target === 'string'-- && SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) => pattern.test(target));++ return (++ typeof target === "string" &&++ SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) => pattern.test(target))++ );+}++const REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERNS: readonly RegExp[] =+ REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS.map(+ ({ source, flags }) => new RegExp(source, flags),+ );++export function isReviewSensitiveCredentialPath(target: string): boolean {- return typeof target === 'string'- && REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) => pattern.test(target));++ return (++ typeof target === "string" &&++ REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) =>++ pattern.test(target),++ )++ );+}++/**+ * File selectors are not concrete paths: glob metacharacters can hide a+ * sensitive basename from an otherwise path-shaped check. Inspect each+ * alternative and a metacharacter-free form before a Review search runs.+ */+export function isReviewSensitiveCredentialSelector(selector: string): boolean {- if (typeof selector !== 'string') return false;++ if (typeof selector !== "string") return false;+ const candidates = [selector, ...selector.split(/[{},|]/)];+ return candidates.some((candidate) => {+ if (isReviewSensitiveCredentialPath(candidate)) return true;- const literalized = candidate.replace(/[*?[\]{}()!+@]/g, '');- return literalized !== candidate && isReviewSensitiveCredentialPath(literalized);++ const literalized = candidate.replace(/[*?[\]{}()!+@]/g, "");++ return (++ literalized !== candidate && isReviewSensitiveCredentialPath(literalized)++ );+ });}