Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 对齐本轮工作区变更与精确审查

DavidShencae0b58d7a17
diff --git a/apps/desktop/src/main/git-review/diffParser.ts b/apps/desktop/src/main/git-review/diffParser.ts
index 6537b2965f..713f758df3 100644
--- a/apps/desktop/src/main/git-review/diffParser.ts
+++ b/apps/desktop/src/main/git-review/diffParser.ts
@@ -216,12 +216,12 @@ function ensurePreviousNoNewline(hunk: Hunk | null): void {
* Stable per-source file identity. Deliberately content-independent so the
* renderer's expand state survives refreshes while the agent keeps editing.
*/
-function makeFileId(source: 'staged' | 'unstaged' | 'commit' | 'branch', path: string, idPrefix?: string): string {
+function makeFileId(source: FileDiff['source'], path: string, idPrefix?: string): string {
return idPrefix ? `${source}:${idPrefix}:${path}` : `${source}:${path}`;
}
export function parseGitDiff(raw: string, opts: {
- source: 'staged' | 'unstaged' | 'commit' | 'branch';
+ source: FileDiff['source'];
idPrefix?: string;
pathHint?: string | null;
oldPathHint?: string | null;
@@ -403,7 +403,7 @@ export function parseGitDiff(raw: string, opts: {
}
export function parseGitDiffs(raw: string, opts: {
- source: 'staged' | 'unstaged' | 'commit' | 'branch';
+ source: FileDiff['source'];
idPrefix?: string;
kind?: FileDiff['kind'];
size?: number | null;
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index f23da9a6e0..f9dea0822f 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -795,6 +795,15 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):
.limit(1);
const effectiveClearedAt = updated?.clearedAt ?? ts;
const effectiveUpdatedAt = updated?.updatedAt ?? effectiveClearedAt;
+ try {
+ const { removeTurnChangeSetsForSession } = await import('../../turn-change-set/store.js');
+ await removeTurnChangeSetsForSession(sessionId);
+ } catch (error) {
+ log.warn('turn change-set cleanup after clear failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
void recomputePrRefsForSession(sessionId).catch(() => undefined);
if (isOwnerScopeCurrent(ownerScope)) {
broadcastSessionPatched(
@@ -1609,6 +1618,16 @@ export async function setSessionsStatusInDb(
*/
function removeHookAttachmentDir(sessionId: string, status: unknown): void {
if (status !== 'deleted' && status !== 'archived') return;
+ if (status === 'deleted') {
+ void import('../../turn-change-set/store.js')
+ .then(({ removeTurnChangeSetsForSession }) => removeTurnChangeSetsForSession(sessionId))
+ .catch((err) => {
+ log.warn('turn change-set cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ });
+ }
const attachRoot = path.join(app.getPath('userData'), 'hook-attachments');
const attachDir = path.join(attachRoot, sessionId);
if (!attachDir.startsWith(attachRoot + path.sep)) return;
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 0c28c5be67..10f5306b68 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -128,6 +128,10 @@ import {
} from './codex-proxy-host.js';
import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';
import { readContactsSettings } from './contacts-settings-store.js';
+import {
+ captureKnownFileBefore,
+ noteOpaqueTurnChange,
+} from '../turn-change-set/store.js';
/**
* 最近一次成功构建的 codex spawn 配置里, 通讯录开关的实际取值(null = 尚未
@@ -743,6 +747,10 @@ export function getMaker(): Maker {
runtimeConfig: buildDesktopClaudeRuntimeConfig(getClaudeEndpoint),
binaryPath: claudePath,
logger: desktopMakerLogger,
+ turnChangeCapture: {
+ beforeKnownFileWrite: captureKnownFileBefore,
+ noteOpaqueWrite: noteOpaqueTurnChange,
+ },
reviewAutoPermissionAction,
// 每个 session 的 cc 子进程 debug 写到 sessions/<id>/cc-debug.raw.log (logger 拼路径
// + mkdir), tailer 再归一化汇入该 session 的 <date>.ndjson。
@@ -1425,6 +1433,10 @@ export function getMaker(): Maker {
const piAgent = buildPiAgent({
logger: desktopMakerLogger,
+ turnChangeCapture: {
+ beforeKnownFileWrite: captureKnownFileBefore,
+ noteOpaqueWrite: noteOpaqueTurnChange,
+ },
reviewAutoPermissionAction,
capabilityAdditions: {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 2aeca31020..5464b548ef 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -186,6 +186,7 @@ function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {
export interface BuildPiAgentOpts {
logger: AgentDeps['logger'];
+ turnChangeCapture?: AgentDeps['turnChangeCapture'];
capabilityAdditions?: AgentDeps['capabilityAdditions'];
reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'];
/** Cindy MCP providers(与 claude/codex 同源工厂产物);经 HTTP bridge 暴露给 pi。 */
@@ -361,6 +362,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
runtimeConfig: buildDesktopPiRuntimeConfig(),
binaryPath,
logger: opts.logger,
+ turnChangeCapture: opts.turnChangeCapture,
capabilityAdditions: opts.capabilityAdditions,
reviewAutoPermissionAction: opts.reviewAutoPermissionAction,
mcpProviders: opts.mcpProviders,
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 4044ca5a5e..3b556c7624 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -7,6 +7,8 @@
export const MAKER_INVOKE = {
CREATE_SESSION: 'maker:create-session',
+ TURN_CHANGE_SETS_LIST: 'maker:turn-change-sets:list',
+ TURN_CHANGE_SETS_GET: 'maker:turn-change-sets:get',
MARK_ORCA_ROLE: 'maker:mark-orca-role',
/**
* F-COLLAB: 中途开关协同模式 (Orca workflow toggle)。
@@ -727,6 +729,7 @@ export const MAKER_SEND = {
export const MAKER_PUSH = {
EVENT: 'maker:event',
+ TURN_CHANGE_SET_UPDATED: 'maker:turn-change-set:updated',
STATUS_CHANGED: 'maker:status-changed',
/** 用户从独立 Computer Use 授权引导浮窗主动取消。 */
COMPUTER_PERMISSION_GUIDE_CANCELLED: 'maker:computer:permission-guide-cancelled',
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 33685bce46..844f56a9e5 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -451,6 +451,16 @@ import {
} from './handoffWorktree.js';
import { validateHandoffWorkingDir } from './handoffWorkingDir.js';
import { registerProjectPluginPolicyHandlers } from './projectPluginPolicyHandlers.js';
+import {
+ TURN_CHANGE_SET_DETAIL_ID_LIMIT,
+ beginTurnChangeSet,
+ clearPendingTurnChangeSets,
+ finalizeTurnChangeSet,
+ getTurnChangeSets,
+ listTurnChangeSets,
+ noteTurnDiffEvent,
+ waitForTurnChangeSetSeal,
+} from '../turn-change-set/store.js';
import { registerPrecreatedWorktreeDiscardHandler } from './precreatedWorktreeDiscardHandler.js';
import { registerNewMakerWorktreePreferenceHandler } from './newMakerWorktreePreferenceHandler.js';
import { registerNewMakerWorktreeBranchPreferenceHandler } from './newMakerWorktreeBranchPreferenceHandler.js';
@@ -3107,6 +3117,7 @@ function settleSilentStopDone(
sessionId: string,
reason: 'exhausted' | 'skip' | 'send-failed',
): void {
+ void finalizeTurnChangeSet(sessionId, null, 'complete');
sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(sessionId);
noteClaudeSessionTurnState(sessionId, false);
agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');
@@ -3267,9 +3278,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
registration.disposers.push(() => {
ghostSessionTap.dispose();
installInteractionLifecycleObserver(session, null);
+ clearPendingTurnChangeSets(session.id);
});
registration.disposers.push(
session.onEvent((event: AgentEvent) => {
+ noteTurnDiffEvent(session.id, event);
ghostSessionTap.handleEvent(
event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },
);
@@ -3280,6 +3293,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 让 renderer chat store 不必扫所有 vendor-raw 找它。
registration.disposers.push(
session.onEvent((event: AgentEvent) => {
+ // Exact patches are main-owned durable data. They have a dedicated summary push and
+ // on-demand detail IPC; forwarding the raw diff through maker:event would duplicate a
+ // potentially multi-megabyte payload to every renderer and device-link controller.
+ if (event.type === 'turn_diff') return;
// 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的
// terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token
// 盖到事件上,首个匹配 token 的事件即视为 provider accepted。
@@ -3423,6 +3440,16 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
}
}
if (event.type === 'done') {
+ const rawTurn = (event.data as { raw?: { id?: unknown; status?: unknown } } | null)?.raw;
+ const isSilentStopDone =
+ (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;
+ if (!isContinuationBoundary && !isSilentStopDone) {
+ finalizeTurnChangeSet(
+ session.id,
+ typeof rawTurn?.id === 'string' ? rawTurn.id : null,
+ rawTurn && rawTurn.status !== 'completed' ? 'partial' : 'complete',
+ );
+ }
// turn 正常收尾但一路没有实质产出时,上一条重连记录同样不能停在"结果未回填":
// 成功路径已在产出事件里 settle 成 succeeded(此处 no-op),走到这里就是没产出。
const doneAttemptToken = event.turnAttemptToken;
@@ -3430,8 +3457,6 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
autoResumeBookkeeping.settleOutcome(session.id, doneAttemptToken, 'failed');
interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, doneAttemptToken);
}
- const isSilentStopDone =
- (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;
// silent-stop done:自动续跑会在 1.5s 后启动新 turn(或弹耗尽横幅),
// 不标 idle/不触发 goal idle/不通知 coordinator done——避免 renderer
// 在 500ms 完成去抖窗口内显示假完成通知,下一个 turn 开始后又跳回 running。
@@ -3468,6 +3493,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
let isPlannedUpgradeClose = false;
let isRemoteAuthRetry = false;
if (isTerminalTurnErrorEvent(event)) {
+ finalizeTurnChangeSet(session.id, null, 'partial');
// **任何**终态失败都先把上一条重连记录钉成失败 —— 不管这次错误本身是否值得自愈。
// 只在"命中白名单、准备再接管"时才 settle 的话,非白名单的终态(认证 / 计费 /
// invalid-request)会让记录悬空,随后一个无关 turn 的首个产出事件就把它标成
@@ -4728,6 +4754,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return maker.listAvailableAgents();
});
+ ipcMain.handle(MAKER_INVOKE.TURN_CHANGE_SETS_LIST, async (event, sessionId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256) {
+ throwIpcError('INVALID_PARAMS', 'Invalid sessionId');
+ }
+ return listTurnChangeSets(sessionId);
+ });
+
+ ipcMain.handle(
+ MAKER_INVOKE.TURN_CHANGE_SETS_GET,
+ async (event, sessionId: unknown, ids: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256) {
+ throwIpcError('INVALID_PARAMS', 'Invalid sessionId');
+ }
+ if (
+ !Array.isArray(ids)
+ || ids.length > TURN_CHANGE_SET_DETAIL_ID_LIMIT
+ || ids.some((id) => typeof id !== 'string' || id.length === 0 || id.length > 256)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set ids');
+ }
+ return getTurnChangeSets(sessionId, ids as string[]);
+ },
+ );
+
ipcMain.handle(MAKER_INVOKE.ANY_SESSION_IN_TURN, () => {
return anySessionInTurn(maker);
});
@@ -9610,18 +9662,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}),
onUserMessageRewritten: (sessionId, item, info) =>
broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info }),
- beforeDispatchUserTurn: (sessionId, item) => {
+ beforeDispatchUserTurn: async (sessionId, item) => {
autoResumeBookkeeping.markReplacementDispatching(sessionId, item.clientId);
+ await waitForTurnChangeSetSeal(sessionId);
+ await finalizeTurnChangeSet(sessionId, null, 'partial');
+ await waitForTurnChangeSetSeal(sessionId);
+ const liveSession = maker.getSession(sessionId);
+ if (liveSession) {
+ beginTurnChangeSet({
+ sessionId,
+ anchorClientId: item.clientId,
+ provider: liveSession.agentKind,
+ cwd: liveSession.workDir,
+ remote: liveSession.remoteHostId !== null,
+ });
+ }
// hook 续跑回流的**权威归属点**: 在 vendor dispatch 之前(本回调被 await), 所以
// 观察器挂上就不丢正文开头, 而 live session 此刻必然已就绪。clientId 对得上的
// 才是目标续跑轮 —— 绕过 coordinator 的 turn(silent-stop 自动续跑)不走这里,
// 结构上不可能被误认。详见 uiContinuationSignal 的模块注释。
publishUiTurnDispatching(sessionId, item.clientId);
- return gitSnapshotCoordinator?.onTurnStart(sessionId);
+ await gitSnapshotCoordinator?.onTurnStart(sessionId);
},
onUndispatchedUserTurn: (sessionId, item, disposition) => {
// 目标轮落库了却没能 dispatch(取消 / 失败): 记账该立刻还回去, 而不是等超时。
publishUiTurnUndispatched(sessionId, item.clientId);
+ clearPendingTurnChangeSets(sessionId);
gitSnapshotCoordinator?.onTurnAbort(sessionId);
autoResumeBookkeeping.rollbackReplacementPreview(sessionId, item.clientId);
const autoResume = item.autoResume === true;
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index e85e35e1f8..cb423dfc4d 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -105,6 +105,37 @@ function parseCommand(raw: unknown): RsbWindowCommand {
...(hasFocusTaskId ? { focusTaskId: r.focusTaskId as string | null } : {}),
};
}
+ if (r.type === 'open-turn-review') {
+ if (
+ !Array.isArray(r.changeSetIds)
+ || r.changeSetIds.length === 0
+ || r.changeSetIds.length > 16
+ || r.changeSetIds.some((id) => typeof id !== 'string' || id.length === 0 || id.length > 256)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'command.changeSetIds must contain 1-16 ids');
+ }
+ if (r.selectedPath !== undefined && r.selectedPath !== null && typeof r.selectedPath !== 'string') {
+ throwIpcError('INVALID_PARAMS', 'command.selectedPath must be string | null');
+ }
+ if (
+ r.selectedDiffId !== undefined
+ && r.selectedDiffId !== null
+ && (typeof r.selectedDiffId !== 'string' || r.selectedDiffId.length > 512)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'command.selectedDiffId must be string | null');
+ }
+ if (typeof r.requestNonce !== 'number' || !Number.isSafeInteger(r.requestNonce)) {
+ throwIpcError('INVALID_PARAMS', 'command.requestNonce must be an integer');
+ }
+ return {
+ type: 'open-turn-review',
+ sessionId: r.sessionId,
+ changeSetIds: r.changeSetIds as string[],
+ selectedDiffId: typeof r.selectedDiffId === 'string' ? r.selectedDiffId : null,
+ selectedPath: typeof r.selectedPath === 'string' ? r.selectedPath : null,
+ requestNonce: r.requestNonce,
+ };
+ }
if (r.type === 'open-file-browser') {
if (r.targetKind === 'external-file') {
if (typeof r.absPath !== 'string' || r.absPath.length === 0) {
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.test.ts
new file mode 100644
index 0000000000..1697380f0c
--- /dev/null
+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.test.ts
@@ -0,0 +1,337 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const mocks = vi.hoisted(() => ({
+ userDataRoot: '',
+ query: vi.fn(),
+ send: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: () => mocks.userDataRoot },
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({ query: mocks.query }),
+}));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerStamp: undefined }),
+ isDataOwnerBroadcastScopeCurrent: () => true,
+ tapWindowBroadcast: mocks.send,
+}));
+
+import {
+ beginTurnChangeSet,
+ captureKnownFileBefore,
+ clearPendingTurnChangeSets,
+ finalizeTurnChangeSet,
+ getTurnChangeSets,
+ listTurnChangeSets,
+ noteOpaqueTurnChange,
+ noteTurnDiffEvent,
+} from '../store';
+
+describe('turn change-set sidecar store', () => {
+ let root = '';
+ let workdir = '';
+
+ beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-turn-change-set-'));
+ workdir = path.join(root, 'workspace');
+ await fs.mkdir(workdir);
+ mocks.userDataRoot = path.join(root, 'user-data');
+ mocks.query.mockReset();
+ mocks.send.mockReset();
+ mocks.query.mockImplementation(async (sql: string) => {
+ if (sql.includes('SELECT id FROM sessions')) return [{ id: 'session-1' }];
+ if (sql.includes('client_id IN')) return [{ clientId: 'user-1' }];
+ return [];
+ });
+ clearPendingTurnChangeSets('session-1');
+ });
+
+ afterEach(async () => {
+ clearPendingTurnChangeSets('session-1');
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('persists the native Codex patch under the dispatch anchor without a database write', async () => {
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-1',
+ cwd: workdir,
+ diff: [
+ 'diff --git a/a.ts b/a.ts',
+ 'index 1111111..2222222 100644',
+ '--- a/a.ts',
+ '+++ b/a.ts',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ '',
+ ].join('\n'),
+ },
+ });
+ finalizeTurnChangeSet('session-1', 'turn-1', 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ providerTurnId: 'turn-1',
+ state: 'complete',
+ additions: 1,
+ deletions: 1,
+ });
+ });
+
+ it('captures only the first preimage for a known-path Claude write', async () => {
+ const target = path.join(workdir, 'a.ts');
+ await fs.writeFile(target, 'old\n', 'utf8');
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: 'a.ts',
+ });
+ await fs.writeFile(target, 'middle\n', 'utf8');
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: 'a.ts',
+ });
+ await fs.writeFile(target, 'new\n', 'utf8');
+ finalizeTurnChangeSet('session-1', null, 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ provider: 'claude-code', state: 'complete' });
+ expect(summary?.files[0]).toMatchObject({ path: 'a.ts', additions: 1, deletions: 1 });
+ });
+
+ it('filters sensitive files from a native Codex patch', async () => {
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-1',
+ cwd: workdir,
+ diff: [
+ 'diff --git a/a.ts b/a.ts',
+ '--- a/a.ts',
+ '+++ b/a.ts',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ 'diff --git a/.env b/.env',
+ '--- a/.env',
+ '+++ b/.env',
+ '@@ -1 +1 @@',
+ '-TOKEN=old',
+ '+TOKEN=new',
+ '',
+ ].join('\n'),
+ },
+ });
+ finalizeTurnChangeSet('session-1', 'turn-1', 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ state: 'partial', incompleteReasons: ['sensitive-file'] });
+ expect(summary?.files.map((file) => file.path)).toEqual(['a.ts']);
+ const detailRaw = await fs.readFile(
+ path.join(mocks.userDataRoot, 'cc-agent', 'turn-change-sets', 'session-1', `${summary?.id}.json`),
+ 'utf8',
+ );
+ expect(detailRaw).not.toContain('TOKEN=');
+ });
+
+ it('labels the captured subset partial after an opaque Pi tool result', async () => {
+ const target = path.join(workdir, 'a.ts');
+ await fs.writeFile(target, 'old\n', 'utf8');
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'pi',
+ cwd: workdir,
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'pi',
+ cwd: workdir,
+ targetPath: target,
+ });
+ await fs.writeFile(target, 'new\n', 'utf8');
+ noteOpaqueTurnChange({ sessionId: 'session-1', provider: 'pi', cwd: workdir });
+ finalizeTurnChangeSet('session-1', null, 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ state: 'partial', incompleteReasons: ['opaque-tool'] });
+ });
+
+ it('persists a zero-file partial entry for an opaque tool with unknown targets', async () => {
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'pi',
+ cwd: workdir,
+ });
+ noteOpaqueTurnChange({ sessionId: 'session-1', provider: 'pi', cwd: workdir });
+ await finalizeTurnChangeSet('session-1', null, 'complete');
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({
+ state: 'partial',
+ incompleteReasons: ['opaque-tool'],
+ fileCount: 0,
+ files: [],
+ });
+ });
+
+ it('does not persist remote workspace patches while remote review is unsupported', async () => {
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ remote: true,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-remote',
+ cwd: workdir,
+ diff: [
+ 'diff --git a/a.ts b/a.ts',
+ '--- a/a.ts',
+ '+++ b/a.ts',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ '',
+ ].join('\n'),
+ },
+ });
+ await finalizeTurnChangeSet('session-1', 'turn-remote', 'complete');
+
+ expect(await listTurnChangeSets('session-1')).toEqual([]);
+ });
+
+ it('bounds the card index while preserving the complete patch for exact review', async () => {
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ const diff = Array.from({ length: 55 }, (_, index) => [
+ `diff --git a/file-${index}.ts b/file-${index}.ts`,
+ `--- a/file-${index}.ts`,
+ `+++ b/file-${index}.ts`,
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ '',
+ ].join('\n')).join('');
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: { turnId: 'turn-many-files', cwd: workdir, diff },
+ });
+ await finalizeTurnChangeSet('session-1', 'turn-many-files', 'complete');
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ state: 'complete', fileCount: 55 });
+ expect(summary?.files).toHaveLength(50);
+ const [detail] = await getTurnChangeSets('session-1', [summary!.id]);
+ expect(detail?.diffs).toHaveLength(55);
+ });
+
+ it('removes orphan detail files after the next successful index publish', async () => {
+ const sidecarDir = path.join(
+ mocks.userDataRoot,
+ 'cc-agent',
+ 'turn-change-sets',
+ 'session-1',
+ );
+ await fs.mkdir(sidecarDir, { recursive: true });
+ const orphanPath = path.join(sidecarDir, 'orphan.json');
+ await fs.writeFile(orphanPath, '{}\n', 'utf8');
+
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'pi',
+ cwd: workdir,
+ });
+ noteOpaqueTurnChange({ sessionId: 'session-1', provider: 'pi', cwd: workdir });
+ await finalizeTurnChangeSet('session-1', null, 'complete');
+
+ await expect(fs.stat(orphanPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await listTurnChangeSets('session-1')).toHaveLength(1);
+ });
+
+ it('never persists sensitive file contents in a captured subset', async () => {
+ const safeTarget = path.join(workdir, 'a.ts');
+ const secretTarget = path.join(workdir, '.env');
+ await fs.writeFile(safeTarget, 'old\n', 'utf8');
+ await fs.writeFile(secretTarget, 'TOKEN=old\n', 'utf8');
+ beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: 'a.ts',
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: '.env',
+ });
+ await fs.writeFile(safeTarget, 'new\n', 'utf8');
+ await fs.writeFile(secretTarget, 'TOKEN=new\n', 'utf8');
+ finalizeTurnChangeSet('session-1', null, 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ state: 'partial', incompleteReasons: ['sensitive-file'] });
+ expect(summary?.files.map((file) => file.path)).toEqual(['a.ts']);
+ const detailRaw = await fs.readFile(
+ path.join(mocks.userDataRoot, 'cc-agent', 'turn-change-sets', 'session-1', `${summary?.id}.json`),
+ 'utf8',
+ );
+ expect(detailRaw).not.toContain('TOKEN=');
+ });
+});
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
new file mode 100644
index 0000000000..05e04434ad
--- /dev/null
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -0,0 +1,789 @@
+import { app, BrowserWindow } from 'electron';
+import { createId } from '@paralleldrive/cuid2';
+import { createTwoFilesPatch } from 'diff';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import type { AgentEvent, TurnDiffEventData } from '@cindy/maker-core';
+import type {
+ PersistedTurnChangeSetV1,
+ TurnChangeFileSummary,
+ TurnChangeIncompleteReason,
+ TurnChangeProvider,
+ TurnChangeSetDetail,
+ TurnChangeSetState,
+ TurnChangeSetSummary,
+ TurnChangeSetUpdatedPayload,
+} from '../../shared/turnChangeSet.js';
+import { TURN_CHANGE_SET_MAX_DIFF_BYTES } from '../../shared/turnChangeSet.js';
+import type { FileDiff } from '../../shared/gitReviewWire.js';
+import { parseGitDiffs } from '../git-review/diffParser.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { createLogger } from '../logger.js';
+import { detectSensitivePath } from '../security/sensitivePath.js';
+import * as broadcastTap from '../device-link/broadcast-tap.js';
+import { MAKER_PUSH } from '../maker-ipc/channels.js';
+import { atomicWriteFileSync } from '../utils/atomicWriteFile.js';
+
+const log = createLogger('turn-change-set');
+const MAX_LIST_ROWS = 100;
+const MAX_DETAIL_IDS = 16;
+const MAX_CAPTURED_FILES = 200;
+const MAX_SUMMARY_FILES = 50;
+const MAX_CAPTURE_FILE_BYTES = 10 * 1024 * 1024;
+const MAX_CAPTURE_TOTAL_BYTES = 12 * 1024 * 1024;
+// Bounds the whole copy-on-write cycle, including both preimages and after-images.
+const MAX_CAPTURE_IO_BYTES = 24 * 1024 * 1024;
+const MAX_DETAIL_STORAGE_BYTES = 16 * 1024 * 1024;
+const MAX_SESSION_DETAIL_BYTES = 32 * 1024 * 1024;
+const MAX_STORED_SESSION_DIRS = 32;
+const INDEX_FILE = 'index.json';
+
+interface CapturedFile {
+ absolutePath: string;
+ relativePath: string;
+ beforeExists: boolean;
+ beforeText: string;
+}
+
+interface PendingTurnChangeSet {
+ id: string;
+ provider: TurnChangeProvider;
+ providerTurnId: string | null;
+ cwd: string;
+ createdAt: number;
+ anchorClientId: string | null;
+ nativeDiff: string | null | undefined;
+ nativeFiles: TurnChangeFileSummary[];
+ capturedFiles: Map<string, CapturedFile>;
+ captureTasks: Map<string, Promise<void>>;
+ capturedBytes: number;
+ incompleteReasons: Set<TurnChangeIncompleteReason>;
+}
+
+interface TurnChangeIndexV1 {
+ version: 1;
+ entries: TurnChangeSetSummary[];
+ detailBytes: Record<string, number>;
+}
+
+const PROVIDERS = new Set<TurnChangeProvider>(['codex', 'claude-code', 'pi']);
+const STATES = new Set<TurnChangeSetState>(['complete', 'partial']);
+const INCOMPLETE_REASONS = new Set<TurnChangeIncompleteReason>([
+ 'opaque-tool',
+ 'outside-workspace',
+ 'remote-session',
+ 'file-too-large',
+ 'binary-file',
+ 'sensitive-file',
+ 'read-failed',
+ 'diff-too-large',
+ 'turn-failed',
+]);
+const FILE_STATUSES = new Set<FileDiff['status']>([
+ 'added',
+ 'modified',
+ 'deleted',
+ 'renamed',
+ 'copied',
+ 'typechange',
+ 'untracked',
+ 'unknown',
+]);
+
+export interface KnownFileWriteCapture {
+ sessionId: string;
+ provider: TurnChangeProvider;
+ cwd: string;
+ targetPath: string;
+ remote?: boolean;
+}
+
+export interface OpaqueTurnChangeCapture {
+ sessionId: string;
+ provider: TurnChangeProvider;
+ cwd: string;
+ remote?: boolean;
+}
+
+export interface BeginTurnChangeSetInput {
+ sessionId: string;
+ anchorClientId: string;
+ provider: TurnChangeProvider;
+ cwd: string;
+ remote?: boolean;
+}
+
+const pendingBySession = new Map<string, PendingTurnChangeSet>();
+const sessionWriteChains = new Map<string, Promise<void>>();
+let storageWriteChain = Promise.resolve();
+
+function byteLength(value: string): number {
+ return Buffer.byteLength(value, 'utf8');
+}
+
+function assertSafeSegment(value: string, label: string): void {
+ if (
+ !value
+ || value.length > 256
+ || value.includes('/')
+ || value.includes('\\')
+ || value.includes('..')
+ || value.includes('\0')
+ || value.includes(':')
+ ) {
+ throw new Error(`Invalid ${label}`);
+ }
+}
+
+function storageRoot(): string {
+ return path.join(app.getPath('userData'), 'cc-agent', 'turn-change-sets');
+}
+
+function sessionDir(sessionId: string): string {
+ assertSafeSegment(sessionId, 'session id');
+ return path.join(storageRoot(), sessionId);
+}
+
+function detailPath(sessionId: string, id: string): string {
+ assertSafeSegment(id, 'turn change-set id');
+ return path.join(sessionDir(sessionId), `${id}.json`);
+}
+
+function normalizedStatus(diff: FileDiff): FileDiff['status'] {
+ if (diff.status !== 'unknown') return diff.status;
+ return diff.hunks.length > 0 || diff.isBinary ? 'modified' : 'unknown';
+}
+
+function parseDiffs(idPrefix: string, unifiedDiff: string): FileDiff[] {
+ return parseGitDiffs(unifiedDiff, { source: 'turn', idPrefix })
+ .map((diff) => ({ ...diff, status: normalizedStatus(diff) }));
+}
+
+function summarizeDiffs(diffs: FileDiff[]): TurnChangeFileSummary[] {
+ return diffs.map((diff) => ({
+ id: diff.id,
+ path: diff.path,
+ oldPath: diff.oldPath,
+ status: diff.status,
+ additions: diff.additions,
+ deletions: diff.deletions,
+ }));
+}
+
+function filterSensitiveDiffBlocks(
+ pending: PendingTurnChangeSet,
+ unifiedDiff: string,
+): string {
+ const blocks = unifiedDiff.split(/(?=^diff --git )/m).filter(Boolean);
+ if (blocks.length === 0) return unifiedDiff;
+ const safeBlocks: string[] = [];
+ for (const block of blocks) {
+ const files = parseDiffs(pending.id, block);
+ const isSensitive = files.some((file) =>
+ detectSensitivePath(file.path, { allowEnvTemplates: true })
+ || (file.oldPath && detectSensitivePath(file.oldPath, { allowEnvTemplates: true })),
+ );
+ if (isSensitive) {
+ addIncompleteReason(pending, 'sensitive-file');
+ } else {
+ safeBlocks.push(block);
+ }
+ }
+ return safeBlocks.join('');
+}
+
+function toSummary(value: PersistedTurnChangeSetV1): TurnChangeSetSummary {
+ return {
+ id: value.id,
+ sessionId: value.sessionId,
+ anchorClientId: value.anchorClientId,
+ provider: value.provider,
+ providerTurnId: value.providerTurnId,
+ cwd: value.cwd,
+ state: value.state,
+ incompleteReasons: value.incompleteReasons,
+ createdAt: value.createdAt,
+ completedAt: value.completedAt,
+ files: value.files.slice(0, MAX_SUMMARY_FILES),
+ fileCount: value.files.length,
+ additions: value.files.reduce((sum, file) => sum + file.additions, 0),
+ deletions: value.files.reduce((sum, file) => sum + file.deletions, 0),
+ };
+}
+
+function isFiniteNonNegative(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
+}
+
+function isFileSummary(value: unknown): value is TurnChangeFileSummary {
+ if (!value || typeof value !== 'object') return false;
+ const file = value as Partial<TurnChangeFileSummary>;
+ return typeof file.id === 'string'
+ && typeof file.path === 'string'
+ && (file.oldPath === null || typeof file.oldPath === 'string')
+ && FILE_STATUSES.has(file.status as FileDiff['status'])
+ && isFiniteNonNegative(file.additions)
+ && isFiniteNonNegative(file.deletions);
+}
+
+function isSummary(value: unknown, sessionId: string): value is TurnChangeSetSummary {
+ if (!value || typeof value !== 'object') return false;
+ const summary = value as Partial<TurnChangeSetSummary>;
+ return typeof summary.id === 'string'
+ && summary.sessionId === sessionId
+ && typeof summary.anchorClientId === 'string'
+ && PROVIDERS.has(summary.provider as TurnChangeProvider)
+ && (summary.providerTurnId === null || typeof summary.providerTurnId === 'string')
+ && typeof summary.cwd === 'string'
+ && STATES.has(summary.state as TurnChangeSetState)
+ && Array.isArray(summary.incompleteReasons)
+ && summary.incompleteReasons.every((reason) => INCOMPLETE_REASONS.has(reason))
+ && isFiniteNonNegative(summary.createdAt)
+ && isFiniteNonNegative(summary.completedAt)
+ && Array.isArray(summary.files)
+ && summary.files.every(isFileSummary)
+ && isFiniteNonNegative(summary.fileCount)
+ && Number.isSafeInteger(summary.fileCount)
+ && summary.fileCount >= summary.files.length
+ && summary.files.length <= MAX_SUMMARY_FILES
+ && isFiniteNonNegative(summary.additions)
+ && isFiniteNonNegative(summary.deletions);
+}
+
+function parsePersisted(raw: string): PersistedTurnChangeSetV1 | null {
+ try {
+ const value = JSON.parse(raw) as Partial<PersistedTurnChangeSetV1>;
+ if (
+ value.version !== 1
+ || typeof value.id !== 'string'
+ || typeof value.sessionId !== 'string'
+ || typeof value.anchorClientId !== 'string'
+ || !PROVIDERS.has(value.provider as TurnChangeProvider)
+ || (value.providerTurnId !== null && typeof value.providerTurnId !== 'string')
+ || typeof value.cwd !== 'string'
+ || !STATES.has(value.state as TurnChangeSetState)
+ || !Array.isArray(value.incompleteReasons)
+ || !value.incompleteReasons.every((reason) => INCOMPLETE_REASONS.has(reason))
+ || !isFiniteNonNegative(value.createdAt)
+ || !isFiniteNonNegative(value.completedAt)
+ || typeof value.unifiedDiff !== 'string'
+ || !Array.isArray(value.files)
+ || !value.files.every(isFileSummary)
+ ) return null;
+ return value as PersistedTurnChangeSetV1;
+ } catch {
+ return null;
+ }
+}
+
+async function readIndexState(sessionId: string): Promise<TurnChangeIndexV1> {
+ try {
+ const raw = await fs.readFile(path.join(sessionDir(sessionId), INDEX_FILE), 'utf8');
+ const parsed = JSON.parse(raw) as Partial<TurnChangeIndexV1>;
+ if (parsed.version !== 1 || !Array.isArray(parsed.entries)) {
+ return { version: 1, entries: [], detailBytes: {} };
+ }
+ const entries = parsed.entries
+ .filter((entry) => isSummary(entry, sessionId))
+ .slice(-MAX_LIST_ROWS);
+ const rawDetailBytes = parsed.detailBytes && typeof parsed.detailBytes === 'object'
+ ? parsed.detailBytes
+ : {};
+ const detailBytes: Record<string, number> = {};
+ for (const entry of entries) {
+ const bytes = rawDetailBytes[entry.id];
+ if (isFiniteNonNegative(bytes) && Number.isSafeInteger(bytes)) {
+ detailBytes[entry.id] = bytes;
+ continue;
+ }
+ const stat = await fs.stat(detailPath(sessionId, entry.id)).catch(() => null);
+ if (stat?.isFile()) detailBytes[entry.id] = stat.size;
+ }
+ return { version: 1, entries, detailBytes };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn('turn change-set index read failed', { sessionId, error });
+ }
+ return { version: 1, entries: [], detailBytes: {} };
+ }
+}
+
+async function readIndex(sessionId: string): Promise<TurnChangeSetSummary[]> {
+ return (await readIndexState(sessionId)).entries;
+}
+
+function enqueueSessionWrite(sessionId: string, operation: () => Promise<void>): Promise<void> {
+ const previous = sessionWriteChains.get(sessionId) ?? Promise.resolve();
+ const current = previous.catch(() => undefined).then(operation).finally(() => {
+ if (sessionWriteChains.get(sessionId) === current) sessionWriteChains.delete(sessionId);
+ });
+ sessionWriteChains.set(sessionId, current);
+ return current;
+}
+
+function enqueueStorageWrite(operation: () => Promise<void>): Promise<void> {
+ const current = storageWriteChain.catch(() => undefined).then(operation);
+ storageWriteChain = current.catch(() => undefined);
+ return current;
+}
+
+async function pruneStoredSessionDirs(currentSessionId: string): Promise<void> {
+ const root = storageRoot();
+ const dirents = await fs.readdir(root, { withFileTypes: true }).catch(() => []);
+ const candidates = await Promise.all(
+ dirents
+ .filter((entry) => entry.isDirectory() && entry.name !== currentSessionId)
+ .map(async (entry) => {
+ const dir = path.join(root, entry.name);
+ const stat = await fs.lstat(dir).catch(() => null);
+ if (!stat || stat.isSymbolicLink()) return null;
+ const indexStat = await fs.stat(path.join(dir, INDEX_FILE)).catch(() => stat);
+ return { dir, updatedAt: indexStat.mtimeMs };
+ }),
+ );
+ const removable = candidates
+ .filter((entry): entry is { dir: string; updatedAt: number } => entry !== null)
+ .sort((a, b) => b.updatedAt - a.updatedAt)
+ .slice(Math.max(0, MAX_STORED_SESSION_DIRS - 1));
+ await Promise.all(removable.map((entry) => fs.rm(entry.dir, { recursive: true, force: true })));
+}
+
+async function persistValue(value: PersistedTurnChangeSetV1): Promise<void> {
+ await enqueueStorageWrite(async () => {
+ const dir = sessionDir(value.sessionId);
+ await fs.mkdir(dir, { recursive: true });
+ const detailContents = `${JSON.stringify(value)}\n`;
+ const currentDetailBytes = byteLength(detailContents);
+ if (currentDetailBytes > MAX_DETAIL_STORAGE_BYTES) {
+ throw new Error('Turn change-set detail exceeds storage limit');
+ }
+ // Detail ids are immutable and unique. Write them asynchronously before publishing the
+ // bounded index so a multi-megabyte patch never blocks Electron's main thread.
+ const currentDetailPath = detailPath(value.sessionId, value.id);
+ await fs.writeFile(currentDetailPath, detailContents, {
+ encoding: 'utf8',
+ mode: 0o600,
+ flag: 'wx',
+ });
+ let indexPublished = false;
+ try {
+ const previous = await readIndexState(value.sessionId);
+ const combined = [
+ ...previous.entries.filter((entry) => entry.id !== value.id),
+ toSummary(value),
+ ];
+ const detailBytes = { ...previous.detailBytes, [value.id]: currentDetailBytes };
+ const nextReversed: TurnChangeSetSummary[] = [];
+ let retainedBytes = 0;
+ for (const entry of combined.slice(-MAX_LIST_ROWS).reverse()) {
+ const bytes = detailBytes[entry.id] ?? 0;
+ if (retainedBytes + bytes > MAX_SESSION_DETAIL_BYTES) continue;
+ retainedBytes += bytes;
+ nextReversed.push(entry);
+ }
+ const next = nextReversed.reverse();
+ const retainedIds = new Set(next.map((entry) => entry.id));
+ const nextDetailBytes = Object.fromEntries(
+ next.map((entry) => [entry.id, detailBytes[entry.id] ?? 0]),
+ );
+ atomicWriteFileSync(
+ path.join(dir, INDEX_FILE),
+ `${JSON.stringify({ version: 1, entries: next, detailBytes: nextDetailBytes } satisfies TurnChangeIndexV1)}\n`,
+ );
+ indexPublished = true;
+ const storedFiles = await fs.readdir(dir).catch(() => []);
+ await Promise.all(storedFiles.map((name) => {
+ if (name === INDEX_FILE || !name.endsWith('.json')) return Promise.resolve();
+ const id = name.slice(0, -'.json'.length);
+ return retainedIds.has(id)
+ ? Promise.resolve()
+ : fs.rm(path.join(dir, name), { force: true });
+ }));
+ await pruneStoredSessionDirs(value.sessionId);
+ } catch (error) {
+ if (!indexPublished) await fs.rm(currentDetailPath, { force: true }).catch(() => undefined);
+ throw error;
+ }
+ });
+}
+
+function broadcastUpdated(payload: TurnChangeSetUpdatedPayload): void {
+ const ownerScope = broadcastTap.captureDataOwnerBroadcastScope();
+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(ownerScope)) return;
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (win.isDestroyed()) continue;
+ try {
+ win.webContents.send(MAKER_PUSH.TURN_CHANGE_SET_UPDATED, payload, ownerScope.ownerStamp);
+ } catch (error) {
+ log.warn('renderer turn change-set broadcast failed', { error });
+ }
+ }
+}
+
+function ensurePending(
+ sessionId: string,
+ provider: TurnChangeProvider,
+ cwd: string,
+): PendingTurnChangeSet {
+ const current = pendingBySession.get(sessionId);
+ if (current) return current;
+ const pending: PendingTurnChangeSet = {
+ id: createId(),
+ provider,
+ providerTurnId: null,
+ cwd,
+ createdAt: Date.now(),
+ anchorClientId: null,
+ nativeDiff: undefined,
+ nativeFiles: [],
+ capturedFiles: new Map(),
+ captureTasks: new Map(),
+ capturedBytes: 0,
+ incompleteReasons: new Set(),
+ };
+ pendingBySession.set(sessionId, pending);
+ return pending;
+}
+
+/** Establishes the Cindy product-turn identity before vendor dispatch. */
+export function beginTurnChangeSet(input: BeginTurnChangeSetInput): void {
+ const existing = pendingBySession.get(input.sessionId);
+ if (existing) {
+ if (existing.anchorClientId === input.anchorClientId) return;
+ log.warn('replacing unfinished turn change-set at dispatch boundary', {
+ sessionId: input.sessionId,
+ previousAnchorClientId: existing.anchorClientId,
+ anchorClientId: input.anchorClientId,
+ });
+ pendingBySession.delete(input.sessionId);
+ }
+ const pending = ensurePending(input.sessionId, input.provider, input.cwd);
+ pending.anchorClientId = input.anchorClientId;
+ if (input.remote) addIncompleteReason(pending, 'remote-session');
+}
+
+function addIncompleteReason(
+ pending: PendingTurnChangeSet,
+ reason: TurnChangeIncompleteReason,
+): void {
+ pending.incompleteReasons.add(reason);
+}
+
+function safeRelativeTarget(cwd: string, targetPath: string): { absolutePath: string; relativePath: string } | null {
+ if (!cwd || !targetPath) return null;
+ const root = path.resolve(cwd);
+ const absolutePath = path.resolve(root, targetPath);
+ const relativePath = path.relative(root, absolutePath);
+ if (
+ relativePath === ''
+ || relativePath === '..'
+ || relativePath.startsWith(`..${path.sep}`)
+ || path.isAbsolute(relativePath)
+ ) return null;
+ return { absolutePath, relativePath: relativePath.split(path.sep).join('/') };
+}
+
+function isInsideRoot(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
+}
+
+async function isRealTargetInsideWorkspace(cwd: string, absolutePath: string): Promise<boolean> {
+ const realRoot = await fs.realpath(path.resolve(cwd)).catch(() => null);
+ if (!realRoot) return false;
+ const realTarget = await fs.realpath(absolutePath).catch(async (error: NodeJS.ErrnoException) => {
+ if (error.code !== 'ENOENT') return null;
+ let ancestor = path.dirname(absolutePath);
+ for (;;) {
+ try {
+ return await fs.realpath(ancestor);
+ } catch (ancestorError) {
+ if ((ancestorError as NodeJS.ErrnoException).code !== 'ENOENT') return null;
+ const parent = path.dirname(ancestor);
+ if (parent === ancestor) return null;
+ ancestor = parent;
+ }
+ }
+ });
+ return realTarget !== null && isInsideRoot(realRoot, realTarget);
+}
+
+async function readTextFileForCapture(
+ absolutePath: string,
+ remainingBytes = MAX_CAPTURE_FILE_BYTES,
+): Promise<{ exists: boolean; text: string } | TurnChangeIncompleteReason> {
+ try {
+ const stat = await fs.stat(absolutePath);
+ if (!stat.isFile()) return 'read-failed';
+ if (stat.size > MAX_CAPTURE_FILE_BYTES) return 'file-too-large';
+ if (stat.size > remainingBytes) return 'diff-too-large';
+ const data = await fs.readFile(absolutePath);
+ try {
+ return { exists: true, text: new TextDecoder('utf-8', { fatal: true }).decode(data) };
+ } catch {
+ return 'binary-file';
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { exists: false, text: '' };
+ return 'read-failed';
+ }
+}
+
+/** Low-I/O copy-on-write capture for tools whose target path is known before execution. */
+export async function captureKnownFileBefore(input: KnownFileWriteCapture): Promise<void> {
+ const pending = ensurePending(input.sessionId, input.provider, input.cwd);
+ if (input.remote) {
+ addIncompleteReason(pending, 'remote-session');
+ return;
+ }
+ const target = safeRelativeTarget(input.cwd, input.targetPath);
+ if (!target) {
+ addIncompleteReason(pending, 'outside-workspace');
+ return;
+ }
+ if (detectSensitivePath(target.relativePath, { allowEnvTemplates: true })) {
+ addIncompleteReason(pending, 'sensitive-file');
+ return;
+ }
+ if (pending.capturedFiles.has(target.absolutePath)) return;
+ const inFlight = pending.captureTasks.get(target.absolutePath);
+ if (inFlight) return inFlight;
+ const captureTask = (async () => {
+ if (!await isRealTargetInsideWorkspace(input.cwd, target.absolutePath)) {
+ addIncompleteReason(pending, 'outside-workspace');
+ return;
+ }
+ if (pending.capturedFiles.size >= MAX_CAPTURED_FILES) {
+ addIncompleteReason(pending, 'diff-too-large');
+ return;
+ }
+ const before = await readTextFileForCapture(target.absolutePath);
+ if (typeof before === 'string') {
+ addIncompleteReason(pending, before);
+ return;
+ }
+ const captureBytes = byteLength(before.text);
+ if (pending.capturedBytes + captureBytes > MAX_CAPTURE_TOTAL_BYTES) {
+ addIncompleteReason(pending, 'diff-too-large');
+ return;
+ }
+ pending.capturedFiles.set(target.absolutePath, {
+ ...target,
+ beforeExists: before.exists,
+ beforeText: before.text,
+ });
+ pending.capturedBytes += captureBytes;
+ })().finally(() => pending.captureTasks.delete(target.absolutePath));
+ pending.captureTasks.set(target.absolutePath, captureTask);
+ return captureTask;
+}
+
+/** Marks an executed tool whose filesystem writes cannot be determined ahead of time. */
+export function noteOpaqueTurnChange(input: OpaqueTurnChangeCapture): void {
+ const pending = ensurePending(input.sessionId, input.provider, input.cwd);
+ addIncompleteReason(pending, input.remote ? 'remote-session' : 'opaque-tool');
+}
+
+export function noteTurnDiffEvent(sessionId: string, event: AgentEvent): void {
+ if (event.type !== 'turn_diff' || event.source !== 'codex') return;
+ const data = event.data as Partial<TurnDiffEventData> | null;
+ if (!data || typeof data.turnId !== 'string' || typeof data.diff !== 'string' || typeof data.cwd !== 'string') {
+ return;
+ }
+ const pending = ensurePending(sessionId, 'codex', data.cwd);
+ if (pending.incompleteReasons.has('remote-session')) return;
+ if (pending.providerTurnId && pending.providerTurnId !== data.turnId) return;
+ pending.providerTurnId = data.turnId;
+ pending.incompleteReasons.delete('sensitive-file');
+ pending.incompleteReasons.delete('diff-too-large');
+ const safeDiff = filterSensitiveDiffBlocks(pending, data.diff);
+ if (byteLength(safeDiff) > TURN_CHANGE_SET_MAX_DIFF_BYTES) {
+ pending.nativeDiff = null;
+ // Without the immutable detail payload, showing file rows would imply that they
+ // can be reviewed exactly. Keep only an explicit partial-coverage card instead.
+ pending.nativeFiles = [];
+ addIncompleteReason(pending, 'diff-too-large');
+ return;
+ }
+ pending.nativeDiff = safeDiff;
+ pending.nativeFiles = [];
+}
+
+function createCapturedFilePatch(file: CapturedFile, afterExists: boolean, afterText: string): string {
+ const oldName = file.beforeExists ? `a/${file.relativePath}` : '/dev/null';
+ const newName = afterExists ? `b/${file.relativePath}` : '/dev/null';
+ const mode = !file.beforeExists && afterExists
+ ? 'new file mode 100644\n'
+ : file.beforeExists && !afterExists
+ ? 'deleted file mode 100644\n'
+ : '';
+ return [
+ `diff --git a/${file.relativePath} b/${file.relativePath}\n`,
+ mode,
+ createTwoFilesPatch(oldName, newName, file.beforeText, afterText, '', '', { context: 3 }),
+ ].join('');
+}
+
+async function buildCapturedPatch(pending: PendingTurnChangeSet): Promise<string> {
+ let unifiedDiff = '';
+ let afterImageBytes = 0;
+ for (const file of pending.capturedFiles.values()) {
+ if (!await isRealTargetInsideWorkspace(pending.cwd, file.absolutePath)) {
+ addIncompleteReason(pending, 'outside-workspace');
+ continue;
+ }
+ const remainingBytes = MAX_CAPTURE_IO_BYTES - pending.capturedBytes - afterImageBytes;
+ if (remainingBytes <= 0) {
+ addIncompleteReason(pending, 'diff-too-large');
+ break;
+ }
+ const after = await readTextFileForCapture(file.absolutePath, remainingBytes);
+ if (typeof after === 'string') {
+ addIncompleteReason(pending, after);
+ continue;
+ }
+ afterImageBytes += byteLength(after.text);
+ if (file.beforeExists === after.exists && file.beforeText === after.text) continue;
+ const nextPatch = createCapturedFilePatch(file, after.exists, after.text);
+ if (byteLength(unifiedDiff) + byteLength(nextPatch) > TURN_CHANGE_SET_MAX_DIFF_BYTES) {
+ addIncompleteReason(pending, 'diff-too-large');
+ break;
+ }
+ unifiedDiff += nextPatch;
+ }
+ return unifiedDiff;
+}
+
+async function persistPending(
+ sessionId: string,
+ pending: PendingTurnChangeSet,
+ terminalState: TurnChangeSetState,
+): Promise<void> {
+ await Promise.all(pending.captureTasks.values());
+ if (terminalState === 'partial') addIncompleteReason(pending, 'turn-failed');
+ // Remote workspaces are deliberately unsupported in this phase. Do not retain a
+ // patch that no local renderer is allowed to review.
+ if (pending.incompleteReasons.has('remote-session')) return;
+ const unifiedDiff = pending.nativeDiff !== undefined
+ ? (pending.nativeDiff ?? '')
+ : await buildCapturedPatch(pending);
+ const diffs = unifiedDiff ? parseDiffs(pending.id, unifiedDiff) : [];
+ const files = diffs.length > 0 ? summarizeDiffs(diffs) : pending.nativeFiles;
+ // An opaque tool with no known paths is still important turn metadata. Persist a
+ // zero-file partial entry so the UI never silently represents it as fully tracked.
+ if (files.length === 0 && pending.incompleteReasons.size === 0) return;
+ const anchorClientId = pending.anchorClientId;
+ if (!anchorClientId) {
+ log.warn('turn change-set has no visible user anchor', { sessionId, id: pending.id });
+ return;
+ }
+ const incompleteReasons = [...pending.incompleteReasons];
+ let value: PersistedTurnChangeSetV1 = {
+ version: 1,
+ id: pending.id,
+ sessionId,
+ anchorClientId,
+ provider: pending.provider,
+ providerTurnId: pending.providerTurnId,
+ cwd: pending.cwd,
+ state: terminalState === 'complete' && incompleteReasons.length === 0 ? 'complete' : 'partial',
+ incompleteReasons,
+ createdAt: pending.createdAt,
+ completedAt: Date.now(),
+ unifiedDiff,
+ files,
+ };
+ if (byteLength(`${JSON.stringify(value)}\n`) > MAX_DETAIL_STORAGE_BYTES) {
+ const fallbackReasons = new Set(value.incompleteReasons);
+ fallbackReasons.add('diff-too-large');
+ value = {
+ ...value,
+ state: 'partial',
+ incompleteReasons: [...fallbackReasons],
+ unifiedDiff: '',
+ files: [],
+ };
+ }
+ await persistValue(value);
+ broadcastUpdated({ sessionId, summary: toSummary(value) });
+}
+
+export function finalizeTurnChangeSet(
+ sessionId: string,
+ _providerTurnId: string | null,
+ terminalState: TurnChangeSetState,
+): Promise<void> {
+ const pending = pendingBySession.get(sessionId);
+ if (!pending) return Promise.resolve();
+ pendingBySession.delete(sessionId);
+ return enqueueSessionWrite(sessionId, () => persistPending(sessionId, pending, terminalState))
+ .catch((error) => log.warn('turn change-set persist failed', { sessionId, error }));
+}
+
+/** Prevents the next product turn from mutating files before the prior after-image is sealed. */
+export async function waitForTurnChangeSetSeal(sessionId: string): Promise<void> {
+ await (sessionWriteChains.get(sessionId) ?? Promise.resolve());
+}
+
+export function clearPendingTurnChangeSets(sessionId: string): void {
+ pendingBySession.delete(sessionId);
+}
+
+async function validAnchorIds(sessionId: string, summaries: readonly TurnChangeSetSummary[]): Promise<Set<string>> {
+ if (summaries.length === 0) return new Set();
+ const sessionRows = await getDbClient().query<{ id: string }>(
+ 'SELECT id FROM sessions WHERE id = ? LIMIT 1',
+ [sessionId],
+ );
+ if (sessionRows.length === 0) return new Set();
+ const ids = [...new Set(summaries.map((summary) => summary.anchorClientId))];
+ const placeholders = ids.map(() => '?').join(', ');
+ const rows = await getDbClient().query<{ clientId: string }>(
+ `SELECT client_id AS clientId FROM messages
+ WHERE session_id = ? AND role = 'user' AND rewind_at IS NULL
+ AND client_id IN (${placeholders})`,
+ [sessionId, ...ids],
+ );
+ return new Set(rows.map((row) => row.clientId));
+}
+
+export async function listTurnChangeSets(sessionId: string): Promise<TurnChangeSetSummary[]> {
+ const summaries = await readIndex(sessionId);
+ const anchors = await validAnchorIds(sessionId, summaries);
+ return summaries.filter((summary) => anchors.has(summary.anchorClientId));
+}
+
+export async function getTurnChangeSets(
+ sessionId: string,
+ ids: string[],
+): Promise<TurnChangeSetDetail[]> {
+ if (ids.length === 0) return [];
+ if (ids.length > MAX_DETAIL_IDS) throw new Error('Too many turn change sets requested');
+ const summaries = await listTurnChangeSets(sessionId);
+ const allowed = new Map(summaries.map((summary) => [summary.id, summary]));
+ const details: TurnChangeSetDetail[] = [];
+ for (const id of ids) {
+ const summary = allowed.get(id);
+ if (!summary) continue;
+ try {
+ const value = parsePersisted(await fs.readFile(detailPath(sessionId, id), 'utf8'));
+ if (!value || value.id !== id || value.sessionId !== sessionId) continue;
+ const detailSummary = toSummary(value);
+ if (JSON.stringify(detailSummary) !== JSON.stringify(summary)) continue;
+ details.push({ ...detailSummary, diffs: parseDiffs(value.id, value.unifiedDiff) });
+ } catch (error) {
+ log.warn('turn change-set detail read failed', { sessionId, id, error });
+ }
+ }
+ return details;
+}
+
+export async function removeTurnChangeSetsForSession(sessionId: string): Promise<void> {
+ pendingBySession.delete(sessionId);
+ await enqueueSessionWrite(sessionId, async () => {
+ await fs.rm(sessionDir(sessionId), { recursive: true, force: true });
+ });
+}
+
+export const TURN_CHANGE_SET_DETAIL_ID_LIMIT = MAX_DETAIL_IDS;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7159cd83c2..3633648f8d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -548,6 +548,7 @@ const fanOutHookControlWorkspaceProviderSource = createIpcFanOut(
// ─── Maker Core 一阶段重构(新链路)── 与 cc-agent:* / codex:* 双轨并行 ─────
const fanOutMakerEvent = createIpcFanOut('maker:event');
+const fanOutMakerTurnChangeSetUpdated = createIpcFanOut('maker:turn-change-set:updated');
const fanOutMakerStatusChanged = createIpcFanOut('maker:status-changed');
const fanOutMakerInputProjection = createIpcFanOut('maker:input:projection');
const fanOutMakerInteractionRequest = createIpcFanOut('maker:interaction-request');
@@ -4702,6 +4703,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:list-available-agents'),
getCapabilities: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<unknown> =>
ipcRenderer.invoke('maker:get-capabilities', agentKind),
+ listTurnChangeSets: (
+ sessionId: string,
+ ): Promise<import('../shared/turnChangeSet').TurnChangeSetSummary[]> =>
+ ipcRenderer.invoke('maker:turn-change-sets:list', sessionId),
+ getTurnChangeSets: (
+ sessionId: string,
+ ids: string[],
+ ): Promise<import('../shared/turnChangeSet').TurnChangeSetDetail[]> =>
+ ipcRenderer.invoke('maker:turn-change-sets:get', sessionId, ids),
// workflow 逐 agent 进度树(只读)。读不到 / 解析失败返回 null,由 renderer 回退到
// workflow 级卡片。数据源是 Claude Code 内部记录文件(见 main workflow-progress/reader)。
@@ -5674,6 +5684,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 事件订阅
onEvent: fanOutMakerEvent,
+ onTurnChangeSetUpdated: fanOutMakerTurnChangeSetUpdated,
onStatusChanged: fanOutMakerStatusChanged,
onInputProjection: fanOutMakerInputProjection,
onInteractionRequest: fanOutMakerInteractionRequest,
@@ -5686,6 +5697,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
// dev-only 调用, prod renderer 不会 HMR 也不会调。
__resetMakerFanOuts: (): void => {
fanOutMakerEvent.__reset();
+ fanOutMakerTurnChangeSetUpdated.__reset();
fanOutMakerStatusChanged.__reset();
fanOutMakerInputProjection.__reset();
fanOutMakerInteractionRequest.__reset();
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
index 5868fe410b..704bfc830e 100644
--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts
@@ -30,6 +30,7 @@ import {
type RenderItem,
} from '../components/chat/MessageStream';
import type { ChatMessage } from '@/lib/makerChatStore';
+import type { TurnChangeSetSummary } from '../../shared/turnChangeSet';
// ── 工厂 / 用例构造工具 ────────────────────────────────────────────────────
@@ -274,40 +275,54 @@ describe('collectTurnFinalAssistantClientIds', () => {
// ── case 1: 流式追加 token 不改变 message item key ────────────────────────
describe('buildRenderItems — key stability', () => {
- it('bounds historical command-generated files by the next user turn timestamp', () => {
- const firstUser = { ...mkUser('u1'), createdAt: '2026-08-05T10:00:00.000Z' };
- const command = {
- ...mkTool('cmd1', 'Bash', { command: "python gen.py 'out/report.xlsx'" }),
- createdAt: '2026-08-05T10:00:05.000Z',
+ it('anchors exact change sets to the owning visible user turn', () => {
+ const firstUser = mkUser('u1');
+ const secondUser = mkUser('u2');
+ const firstSet: TurnChangeSetSummary = {
+ id: 'cs1',
+ sessionId: 's1',
+ anchorClientId: 'u1',
+ provider: 'codex',
+ providerTurnId: 'turn-1',
+ cwd: 'C:/work',
+ state: 'complete',
+ incompleteReasons: [],
+ createdAt: 1,
+ completedAt: 2,
+ files: [{
+ id: 'turn-1:a.ts',
+ path: 'a.ts',
+ oldPath: null,
+ status: 'modified',
+ additions: 2,
+ deletions: 1,
+ }],
+ fileCount: 1,
+ additions: 2,
+ deletions: 1,
};
- const nextUser = { ...mkUser('u2'), createdAt: '2026-08-05T10:01:00.000Z' };
- const { items } = buildRenderItems([firstUser, command, nextUser], undefined, undefined, {
- workingDir: 'C:/work',
- });
- const card = items.find(
- (it): it is Extract<RenderItem, { type: 'generated_files' }> =>
- it.type === 'generated_files',
- );
-
- expect(card?.turnStartMs).toBe(Date.parse(firstUser.createdAt));
- expect(card?.turnEndMs).toBe(Date.parse(nextUser.createdAt));
- });
-
- it('leaves the current tail turn unbounded above', () => {
- const user = { ...mkUser('u1'), createdAt: '2026-08-05T10:00:00.000Z' };
- const command = {
- ...mkTool('cmd1', 'Bash', { command: "python gen.py 'out/report.xlsx'" }),
- createdAt: '2026-08-05T10:00:05.000Z',
+ const secondSet = {
+ ...firstSet,
+ id: 'cs2',
+ anchorClientId: 'u2',
+ providerTurnId: 'turn-2',
+ createdAt: 3,
+ completedAt: 4,
};
- const { items } = buildRenderItems([user, command], undefined, undefined, {
- workingDir: 'C:/work',
- });
- const card = items.find(
- (it): it is Extract<RenderItem, { type: 'generated_files' }> =>
- it.type === 'generated_files',
+
+ const { items } = buildRenderItems(
+ [firstUser, mkAssistant('a1'), secondUser, mkAssistant('a2')],
+ undefined,
+ undefined,
+ { turnChangeSets: [firstSet, secondSet] },
+ );
+ const cards = items.filter(
+ (item): item is Extract<RenderItem, { type: 'turn_changes' }> => item.type === 'turn_changes',
);
- expect(card?.turnEndMs).toBeNull();
+ expect(cards.map((card) => card.key)).toEqual(['turnchanges-cs1', 'turnchanges-cs2']);
+ expect(cards.map((card) => card.changeSet.id)).toEqual(['cs1', 'cs2']);
+ expect(items.indexOf(cards[0])).toBeGreaterThan(items.findIndex((item) => item.key === 'msg-a1'));
});
it('streaming token append to an assistant message keeps the same item key', () => {
diff --git a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
deleted file mode 100644
index d5d598e830..0000000000
--- a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { collectGeneratedFiles, extractCommandPathCandidates } from '../lib/generatedFiles';
-
-const WORKDIR = '/work';
-
-function toolUse(toolName: string, toolInput: unknown) {
- return { role: 'tool_use', toolName, toolInput };
-}
-
-describe('collectGeneratedFiles', () => {
- it('collects Write (claude) and write (pi) created files', () => {
- const files = collectGeneratedFiles(
- [
- toolUse('Write', { file_path: 'report.md', content: 'x' }),
- toolUse('write', { path: 'data/out.csv', content: 'y' }),
- ],
- WORKDIR,
- );
- expect(files.map((f) => f.name)).toEqual(['report.md', 'out.csv']);
- // 相对路径按 workingDir 解析成绝对路径。
- expect(files[0].path.replace(/\\/g, '/')).toContain('/work/report.md');
- });
-
- it('collects codex file_change add entries but not updates', () => {
- // codex 协议形态:change 需带 kind.type 与 diff 字符串,缺任一整次降级 generic。
- const files = collectGeneratedFiles(
- [
- toolUse('file_change', {
- changes: [
- { path: 'new.txt', kind: { type: 'add' }, diff: '+hi' },
- { path: 'existing.txt', kind: { type: 'update' }, diff: '-a\n+b' },
- ],
- }),
- ],
- WORKDIR,
- );
- expect(files.map((f) => f.name)).toEqual(['new.txt']);
- });
-
- it('excludes edits, reads and searches', () => {
- const files = collectGeneratedFiles(
- [
- toolUse('Edit', { file_path: 'a.ts', old_string: 'a', new_string: 'b' }),
- toolUse('Read', { file_path: 'b.ts' }),
- toolUse('Grep', { pattern: 'foo' }),
- ],
- WORKDIR,
- );
- expect(files).toEqual([]);
- });
-
- it('dedupes the same created path across tool calls, keeping first order', () => {
- const files = collectGeneratedFiles(
- [
- toolUse('Write', { file_path: 'dup.md', content: '1' }),
- toolUse('Write', { file_path: 'other.md', content: '2' }),
- toolUse('Write', { file_path: 'dup.md', content: '3' }),
- ],
- WORKDIR,
- );
- expect(files.map((f) => f.name)).toEqual(['dup.md', 'other.md']);
- });
-
- it('folds case only for Windows-shaped paths, keeps POSIX case-sensitive', () => {
- // Windows 绝对路径:大小写不敏感,C:/A.md 与 c:/a.md 视为同一文件。
- const win = collectGeneratedFiles(
- [
- toolUse('Write', { file_path: 'C:/work/A.md', content: '1' }),
- toolUse('Write', { file_path: 'c:/work/a.md', content: '2' }),
- ],
- 'C:/work',
- );
- expect(win).toHaveLength(1);
-
- // POSIX 绝对路径:大小写敏感,/w/A.txt 与 /w/a.txt 是两个不同文件,不合并。
- const posix = collectGeneratedFiles(
- [
- toolUse('write', { path: '/w/A.txt', content: '1' }),
- toolUse('write', { path: '/w/a.txt', content: '2' }),
- ],
- '/w',
- );
- expect(posix.map((f) => f.name).sort()).toEqual(['A.txt', 'a.txt']);
- });
-
- it('ignores non-tool_use messages', () => {
- const files = collectGeneratedFiles(
- [
- { role: 'assistant', toolName: 'Write', toolInput: { file_path: 'no.md' } },
- toolUse('Write', { file_path: 'yes.md', content: 'x' }),
- ],
- WORKDIR,
- );
- expect(files.map((f) => f.name)).toEqual(['yes.md']);
- });
-
- it('collects script-generated paths from Bash commands as command-source candidates', () => {
- // Issue 场景:xlsx 由 python openpyxl 脚本生成,没有文件工具记录。
- const cmd =
- 'python -c "\nimport openpyxl\nwb = openpyxl.Workbook()\n' +
- "wb.save(r'C:\\Users\\Admin\\Documents\\测试表格.xlsx')\nprint('done')\n\"\n";
- const files = collectGeneratedFiles([toolUse('Bash', { command: cmd })], 'C:/work');
- expect(files).toHaveLength(1);
- expect(files[0].name).toBe('测试表格.xlsx');
- expect(files[0].source).toBe('command');
- });
-
- it('canonicalizes Windows-shaped paths to backslashes and dedupes across slash forms', () => {
- // 正斜杠 Windows 路径(命令文本常见)必须归一成反斜杠本机形态:Explorer
- // /select 与 shell.openPath 对正斜杠会失败;且与 Write 记录的反斜杠形态
- // 是同一文件,不归一会重复出 chip。
- const files = collectGeneratedFiles(
- [
- toolUse('Write', { file_path: 'C:\\work\\report.docx', content: 'x' }),
- toolUse('Bash', { command: "open 'C:/work/report.docx'" }),
- toolUse('Bash', { command: "save 'C:/work/输出/表格.xlsx'" }),
- ],
- 'C:\\work',
- );
- expect(files.map((f) => f.path)).toEqual(['C:\\work\\report.docx', 'C:\\work\\输出\\表格.xlsx']);
- expect(files[0].source).toBe('tool');
- });
-
- it('excludes command mentions of files edited by file tools this turn', () => {
- // 编码会话形态:Edit 改了源码文件,随后命令引用它(跑测试)。它是编辑不是
- // 新建,不能因 mtime 落在本轮窗口就被当成产物。
- const files = collectGeneratedFiles(
- [
- toolUse('Bash', { command: 'pnpm vitest run C:/work/src/openWithApps.test.ts' }),
- toolUse('Edit', {
- file_path: 'C:/work/src/openWithApps.test.ts',
- old_string: 'a',
- new_string: 'b',
- }),
- toolUse('Bash', { command: "python gen.py > 'C:/work/out/report.csv'" }),
- ],
- 'C:/work',
- );
- // Edit 出现在命令之后也要生效(两遍扫描),真产物 report.csv 不受影响。
- expect(files.map((f) => f.name)).toEqual(['report.csv']);
- });
-
- it('marks file-tool creates as tool source and wins over command mentions of the same path', () => {
- const files = collectGeneratedFiles(
- [
- toolUse('Bash', { command: 'ls C:/work/report.md' }),
- toolUse('Write', { file_path: 'C:/work/report.md', content: 'x' }),
- ],
- 'C:/work',
- );
- expect(files).toHaveLength(1);
- expect(files[0].source).toBe('tool');
- });
-});
-
-describe('extractCommandPathCandidates', () => {
- it('extracts quoted paths (CJK, spaces) and bare absolute paths', () => {
- expect(
- extractCommandPathCandidates("wb.save(r'C:\\Users\\A\\My Docs\\报表 v2.xlsx')"),
- ).toEqual(['C:\\Users\\A\\My Docs\\报表 v2.xlsx']);
- expect(extractCommandPathCandidates('node gen.js > C:/out/result.json')).toContain(
- 'C:/out/result.json',
- );
- expect(extractCommandPathCandidates('cp a "/home/u/输出/report.pdf"')).toContain(
- '/home/u/输出/report.pdf',
- );
- });
-
- it('skips temp dirs, extension-less tokens, plain filenames and URLs', () => {
- expect(extractCommandPathCandidates("save('/tmp/x.xlsx')")).toEqual([]);
- expect(extractCommandPathCandidates("save('C:\\Users\\A\\AppData\\Local\\Temp\\x.xlsx')")).toEqual([]);
- expect(extractCommandPathCandidates('cat /dev/null && echo done')).toEqual([]);
- // 纯文件名不收(随机带点 token 误报率太高),相对路径需含分隔符。
- expect(extractCommandPathCandidates("save('输出.xlsx')")).toEqual([]);
- expect(extractCommandPathCandidates("save('out/输出.xlsx')")).toEqual(['out/输出.xlsx']);
- expect(extractCommandPathCandidates('curl https://x.com/a.js')).toEqual([]);
- expect(extractCommandPathCandidates('')).toEqual([]);
- });
-
- it('dedupes the same path appearing quoted and bare', () => {
- expect(
- extractCommandPathCandidates('python gen.py C:/out/a.csv && stat "C:/out/a.csv"'),
- ).toEqual(['C:/out/a.csv']);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
deleted file mode 100644
index 874bfea9dd..0000000000
--- a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isLocalGeneratedFileInTurn } from '../components/chat/GeneratedFilesCard';
-import type { GeneratedFileRef } from '../lib/generatedFiles';
-
-const START = Date.parse('2026-08-05T10:00:00.000Z');
-const END = Date.parse('2026-08-05T10:01:00.000Z');
-
-const toolFile: GeneratedFileRef = {
- path: 'C:\\work\\report.md',
- name: 'report.md',
- source: 'tool',
-};
-const commandFile: GeneratedFileRef = { ...toolFile, source: 'command' };
-
-describe('isLocalGeneratedFileInTurn', () => {
- it('accepts a tool-created file whose birthtime falls in the turn', () => {
- expect(
- isLocalGeneratedFileInTurn(
- toolFile,
- { kind: 'file', birthtimeMs: START + 5_000, mtimeMs: START + 5_000 },
- START,
- END,
- ),
- ).toBe(true);
- });
-
- it('rejects Write against an existing file even when mtime is current', () => {
- expect(
- isLocalGeneratedFileInTurn(
- toolFile,
- { kind: 'file', birthtimeMs: START - 60_000, mtimeMs: START + 5_000 },
- START,
- END,
- ),
- ).toBe(false);
- });
-
- it('rejects a failed tool path that only appears in a later turn', () => {
- expect(
- isLocalGeneratedFileInTurn(
- toolFile,
- { kind: 'file', birthtimeMs: END + 5_000, mtimeMs: END + 5_000 },
- START,
- END,
- ),
- ).toBe(false);
- });
-
- it('fails closed for tool entries when birthtime is unavailable', () => {
- expect(
- isLocalGeneratedFileInTurn(
- toolFile,
- { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },
- START,
- END,
- ),
- ).toBe(false);
- });
-
- it('keeps the mtime fallback for command candidates on filesystems without birthtime', () => {
- expect(
- isLocalGeneratedFileInTurn(
- commandFile,
- { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },
- START,
- END,
- ),
- ).toBe(true);
- });
-});
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
deleted file mode 100644
index c7b6a75c52..0000000000
--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
+++ /dev/null
@@ -1,287 +0,0 @@
-/**
- * GeneratedFilesCard — 每个 user turn 结尾的「本轮产出文件」卡。
- * ---------------------------------------------------------------------------
- * 对标 Codex Desktop 回复尾部的 artifact 文件卡:agent 本轮新建的文件不再只能
- * 靠模型在正文里写对 Markdown 链接才可见(Issue #1811 场景),而是从 tool_use
- * 结构化派生后集中呈现。文件来源判定见 lib/generatedFiles.ts。
- *
- * 交互:
- * - 左键 → 与正文文件链接同策(对齐 MarkdownRenderer activateResolvedLocalTarget):
- * 可识别文件直接在 Cindy 内打开——文本/代码 → TextLightbox,图片 → ImageLightbox,
- * glb/gltf → ModelLightbox;其余(xlsx / pdf 等)交系统默认应用(远程会话取回
- * 缓存副本再打开)。
- * - 右键 → 共享文件 chip 菜单(复制 / 路径 / 定位 / 打开方式…),与聊天里其它
- * 文件 chip 一致。
- *
- * 存在性门槛(DESIGN.md §14.5「可点必存在」):本地会话渲染前 stat 过滤,不存在
- * 的文件不出 chip,整卡为空则不渲染。远程会话经 verifyRemotePathCached 远端 stat
- * 复核:先按 tool_use 记录乐观呈现,verdict 回来后 nonfile/directory 摘掉;
- * unknown(断链 / 限流)保持乐观——与正文 chip 的远程点亮不变量同策。
- *
- * 本地文件统一要求时间戳落在本轮 `[turnStartMs, turnEndMs)` 窗口内。tool 来源
- * (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能
- * 被后续轮次创建;因此它必须有落在窗口内的 birthtime,不可用时宁可不出。
- * command 来源为兼容不提供 birthtime 的 Linux FS 允许 mtime 回退,但同样受完整
- * 时间窗约束。远程会话无法读取创建时间,维持远端 stat 的存在性复核。
- */
-
-import { useEffect, useState } from 'react';
-import { ChevronDown, ChevronUp, FileText } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { cn } from '@/lib/utils';
-import type { GeneratedFileRef } from '@/lib/generatedFiles';
-import { classifyMarkdownHref, toLocalFileUrl } from '@/lib/localPathResolver';
-import { isRemoteFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
-import {
- fetchChatFileWithToasts,
- revealRemoteChatFile,
- verifyRemotePathCached,
-} from '@/lib/remoteFileOpen';
-import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
-import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
-import { useChatSessionFile } from './ChatSessionFileContext';
-import { useFileChipContextMenu } from './useFileChipContextMenu';
-import { ImageLightbox } from './ImageLightbox';
-import { TextLightbox } from './TextLightbox';
-import { ModelLightbox } from './ModelLightbox';
-
-function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {
- const fileCtx = useChatSessionFile();
- const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
- const ctxMenu = useFileChipContextMenu({
- getAbsPath: () => file.path,
- // 生成物常是 .xlsx / .pdf / 图片等,"打开方式"对它们最有用;会话上下文
- // (含侧边栏定位目标)由 useFileChipContextMenu 内部从 ChatSessionFileContext 取。
- canOpenInBrowser: false,
- });
-
- const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
- const [textLightboxOpen, setTextLightboxOpen] = useState(false);
- const [modelLightboxPath, setModelLightboxPath] = useState<string | null>(null);
-
- // 左键与正文文件链接同策(见文件头注释)。非文本兜底交给
- // shouldOpenTextLightboxForOrigin:本地 openPath、远程取回缓存副本,均含失败 toast。
- const open = async (): Promise<void> => {
- const kind = classifyMarkdownHref(file.path);
- if (kind === 'image-local') {
- const localUrl = toLocalFileUrl(file.path);
- if (!remoteOrigin) {
- setLightboxSrc(localUrl);
- return;
- }
- // 远程:xdt-file:// 经 origin 改写走 cindy-remote-media 管线;改写不了
- // (ssh workdir 外)→ 取回缓存副本后按本机文件预览(与正文链接同策)。
- const rewritten = rewriteToRemoteMediaOrigin(
- localUrl,
- toRemoteMediaOrigin(fileCtx.origin, fileCtx.workingDir),
- );
- if (rewritten !== localUrl) {
- setLightboxSrc(rewritten);
- return;
- }
- const cachePath = await fetchChatFileWithToasts(remoteOrigin, fileCtx.workingDir, file.path);
- if (cachePath) setLightboxSrc(toLocalFileUrl(cachePath));
- return;
- }
- if (kind === 'model-local') {
- if (remoteOrigin) {
- await revealRemoteChatFile(remoteOrigin, fileCtx.workingDir, file.path);
- return;
- }
- // FBX 无应用内预览且 openPath 有误导弹窗风险(正文链接同款取舍)→ 定位。
- if (/\.fbx$/i.test(file.path)) {
- void window.electronAPI.showItemInFolder({ filePath: file.path });
- return;
- }
- setModelLightboxPath(file.path);
- return;
- }
- if (!(await shouldOpenTextLightboxForOrigin(fileCtx, file.path))) return;
- setTextLightboxOpen(true);
- };
-
- return (
- <>
- <button
- type="button"
- title={file.path}
- onClick={() => void open()}
- onContextMenu={ctxMenu.onContextMenu}
- className={cn(
- 'inline-flex items-center gap-1.5',
- 'h-7 px-2.5 py-1.5 max-w-[280px]',
- 'rounded-[9999px]',
- 'bg-[var(--msg-md-inline-code-bg)]',
- 'text-[13px] font-medium text-[var(--msg-assistant-text)]',
- 'hover:bg-[var(--cmd-palette-item-hover)]',
- 'transition-colors cursor-pointer',
- )}
- >
- <FileText size={14} className="shrink-0 opacity-70" />
- <span className="truncate">{file.name}</span>
- </button>
- {ctxMenu.menu}
- {lightboxSrc && <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />}
- {textLightboxOpen && (
- <TextLightbox
- filePath={file.path}
- fileName={file.name}
- onClose={() => setTextLightboxOpen(false)}
- />
- )}
- {modelLightboxPath && (
- <ModelLightbox
- source={{ kind: 'local', absPath: modelLightboxPath }}
- onClose={() => setModelLightboxPath(null)}
- />
- )}
- </>
- );
-}
-
-/** command 候选 mtime 下界的时钟余量:消息落库时间与文件写盘时间的抖动缓冲。 */
-const TURN_START_SLACK_MS = 120_000;
-
-interface GeneratedFileStat {
- kind: 'dir' | 'file' | 'missing';
- birthtimeMs?: number;
- mtimeMs?: number;
-}
-
-/**
- * 本地文件是否有足够证据归属于该 turn。tool 来源必须有真实创建时间:
- * Write 也可能覆盖既有文件,仅凭成功/mtime 不能把它当成“新建”;birthtime
- * 不可用时宁可不出。command 来源为兼容不提供 birthtime 的 Linux FS,维持
- * mtime 回退,但仍受完整 turn 时间窗约束。
- */
-export function isLocalGeneratedFileInTurn(
- file: GeneratedFileRef,
- stat: GeneratedFileStat,
- turnStartMs: number | null,
- turnEndMs: number | null,
-): boolean {
- if (stat.kind !== 'file' || turnStartMs === null) return false;
- const birthtimeMs =
- typeof stat.birthtimeMs === 'number' && stat.birthtimeMs > 0 ? stat.birthtimeMs : null;
- const ts = file.source === 'tool' ? birthtimeMs : (birthtimeMs ?? stat.mtimeMs);
- // tool 来源的 birthtime 是同机 FS 事实,不放宽下界:放 2 分钟 slack 会把本轮
- // 覆盖的旧文件误当新建。command 来源保留消息落库/执行时序抖动余量。
- const lowerBound =
- file.source === 'tool' ? turnStartMs : turnStartMs - TURN_START_SLACK_MS;
- return (
- typeof ts === 'number' &&
- ts >= lowerBound &&
- (turnEndMs === null || ts < turnEndMs)
- );
-}
-
-/** 折叠阈值:约两行 chip。超过则收起为「前 N 个 + 再显示 M 个文件」。 */
-const MAX_VISIBLE_FILES = 6;
-
-export function GeneratedFilesCard({
- files,
- turnStartMs,
- turnEndMs,
-}: {
- files: readonly GeneratedFileRef[];
- turnStartMs: number | null;
- turnEndMs: number | null;
-}) {
- const { t } = useTranslation();
- const fileCtx = useChatSessionFile();
- const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
- // 本地会话:stat 过滤到真实存在的文件(null = 尚未算完,不渲染,避免闪现后
- // 又被过滤掉);远程:tool 来源先乐观呈现、远端 stat 复核,command 候选无法
- // 验证 mtime 一律不出(见文件头注释)。
- const [existing, setExisting] = useState<GeneratedFileRef[] | null>(
- remoteOrigin ? files.filter((f) => f.source === 'tool') : null,
- );
- const [expanded, setExpanded] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
- if (remoteOrigin) {
- const toolFiles = files.filter((f) => f.source === 'tool');
- setExisting(toolFiles);
- void (async () => {
- const checks = await Promise.all(
- toolFiles.map(async (f) => {
- const verdict = await verifyRemotePathCached(remoteOrigin, fileCtx.workingDir, f.path);
- // nonfile(不存在 / 非普通文件)/ directory 是远端确定结论 → 摘掉;
- // unknown(断链 / 限流)保持乐观。
- return verdict !== 'nonfile' && verdict !== 'directory';
- }),
- );
- if (!cancelled) setExisting(toolFiles.filter((_, idx) => checks[idx]));
- })();
- return () => {
- cancelled = true;
- };
- }
- void (async () => {
- const checks = await Promise.all(
- files.map(async (f) => {
- try {
- const r = await window.electronAPI.fsBrowse.statPath(f.path);
- return isLocalGeneratedFileInTurn(f, r, turnStartMs, turnEndMs);
- } catch {
- return false;
- }
- }),
- );
- if (!cancelled) setExisting(files.filter((_, idx) => checks[idx]));
- })();
- return () => {
- cancelled = true;
- };
- }, [files, remoteOrigin, turnStartMs, turnEndMs, fileCtx.workingDir]);
-
- if (!existing || existing.length === 0) return null;
-
- // 折叠(对标 Codex 的可展开产物列表):超过 MAX_VISIBLE_FILES 时只显示前
- // MAX_VISIBLE_FILES 个 + 「再显示 N 个文件」;展开后提供「收起」回折。
- const visible = expanded ? existing : existing.slice(0, MAX_VISIBLE_FILES);
- const hiddenCount = existing.length - visible.length;
-
- return (
- <div className="my-1 flex flex-col gap-1.5">
- <span className="text-12 text-[var(--text-secondary)]">
- {t('chat.generatedFiles.title')}
- </span>
- <div className="flex flex-wrap gap-1.5">
- {visible.map((f) => (
- <GeneratedFileChip key={f.path} file={f} />
- ))}
- {hiddenCount > 0 && (
- <button
- type="button"
- onClick={() => setExpanded(true)}
- className={cn(
- 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',
- 'text-[13px] text-[var(--text-secondary)]',
- 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',
- )}
- >
- {t('chat.generatedFiles.showMore', { count: hiddenCount })}
- <ChevronDown size={14} className="shrink-0" />
- </button>
- )}
- {expanded && existing.length > MAX_VISIBLE_FILES && (
- <button
- type="button"
- onClick={() => setExpanded(false)}
- className={cn(
- 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',
- 'text-[13px] text-[var(--text-secondary)]',
- 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',
- )}
- >
- {t('chat.generatedFiles.showLess')}
- <ChevronUp size={14} className="shrink-0" />
- </button>
- )}
- </div>
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 6cb1a81046..0a20aec86f 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -48,7 +48,11 @@ import { Spinner } from '@/components/ui/spinner';
import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreference';
import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';
import type { KnownLocalFileRef } from '@/lib/localPathResolver';
-import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';
+import {
+ isRemoteSessionSticky,
+ makerApiFor,
+ subscribeTurnChangeSetUpdated,
+} from '@/lib/makerTransport';
import { createLogger } from '@/lib/logger';
import { stopAllMedia } from '@/lib/mediaPlaybackBus';
import {
@@ -155,7 +159,7 @@ import { NewMessageIndicator } from './NewMessageIndicator';
import { ThinkingCard } from './ThinkingCard';
import { AgentActionsBlock } from './AgentActionsBlock';
import { AgentTaskCard } from './AgentTaskCard';
-import { GeneratedFilesCard } from './GeneratedFilesCard';
+import { TurnChangesCard } from './TurnChangesCard';
import { WorkGroupBlock, type WorkGroupChild } from './WorkGroupBlock';
import {
extractAnchorCardId,
@@ -213,6 +217,7 @@ import { useNavigationKeyListener } from './useNavigationKeyListener';
import { suppressScrollbarActivation } from '@/lib/scrollbarAutoHide';
import { collectAssistantTurnUsageDetails } from '@/lib/userTurnUsage';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
+import type { TurnChangeSetSummary } from '../../../shared/turnChangeSet';
interface MessageStreamProps {
/** Active session id — used to reset scroll state on session switch. */
@@ -318,16 +323,11 @@ type ForkOriginRenderItem = {
parentSessionId: string;
forkedAtMessageId: string;
};
-type GeneratedFilesRenderItem = {
- /** 每个 user turn 结尾聚合的「本轮 agent 新建文件」卡(Codex artifact 卡对标)。
- * 纯派生自 turn 内 tool_use;存在性过滤在组件里做,全不存在则整卡不渲染。 */
- type: 'generated_files';
+type TurnChangesRenderItem = {
+ /** Exact provider patches attached to one visible user turn. */
+ type: 'turn_changes';
key: string;
- files: GeneratedFileRef[];
- /** 本轮首条消息时间(unix ms);command 候选的时间窗下界校验用,不可得为 null。 */
- turnStartMs: number | null;
- /** 下一条 user 边界时间(unix ms);已结束 turn 的 command 候选时间窗上界。 */
- turnEndMs: number | null;
+ changeSet: TurnChangeSetSummary;
};
/** 原子工作子项:tool / agent task / thinking / assistant 工作文字。 */
@@ -358,7 +358,7 @@ export type RenderItem =
| ToolSegmentRenderItem
| AgentTaskRenderItem
| ForkOriginRenderItem
- | GeneratedFilesRenderItem
+ | TurnChangesRenderItem
| {
/** tool-result-media: 把 tool_result 里的 xdt_image_url(s) / xdt_video_urls
* 提取出来作为独立视觉消息渲染,跳出 tool_segment 折叠卡片。统一容器,
@@ -905,8 +905,8 @@ export function buildRenderItems(
* 「父调用在不在 messages 里」做的归属判定都不可信,必须放宽而不是丢弃。
*/
historyWindowIncomplete?: boolean;
- /** 会话工作目录:把 tool_use 里的相对路径解析成绝对路径供「本轮产出文件」卡使用。 */
- workingDir?: string;
+ /** Main-persisted exact patches, anchored to their visible user message. */
+ turnChangeSets?: readonly TurnChangeSetSummary[];
},
): {
items: RenderItem[];
@@ -1051,46 +1051,30 @@ export function buildRenderItems(
pendingSegmentGhostCards = [];
};
- // 「本轮产出文件」卡:按 user turn 切片派生新建文件,在**下一个** user 边界
- // (或流末尾)把上一轮的产出 flush 到该轮所有内容之下。turnStartIdx 指向当前
- // turn 的首条消息。workingDir 缺省时跳过(无从解析相对路径,不出卡)。
- const workingDir = opts?.workingDir ?? '';
let turnStartIdx = 0;
- const flushGeneratedFiles = (lo: number, hi: number): void => {
- if (!workingDir || hi <= lo) return;
- const slice = messages.slice(lo, hi);
- const files = collectGeneratedFiles(slice, workingDir);
- if (files.length === 0) return;
- // 本轮时间窗:下界取切片内最早 createdAt;上界取 hi 处的下一条 user
- // 边界。历史 command 候选必须同时落在这个窗口内,否则后续 turn 在同一路径
- // 创建/改写文件时,旧卡会被当前 stat 的新时间戳错误点亮(PR #1835 review)。
- let turnStartMs: number | null = null;
- for (const m of slice) {
- const ts = m.createdAt ? Date.parse(m.createdAt) : NaN;
- if (Number.isFinite(ts) && (turnStartMs === null || ts < turnStartMs)) turnStartMs = ts;
+ const flushTurnChanges = (lo: number, hi: number): void => {
+ if (hi <= lo) return;
+ const anchorClientId = messages[lo]?.clientId;
+ if (!anchorClientId) return;
+ const changeSets = (opts?.turnChangeSets ?? []).filter(
+ (changeSet) => changeSet.anchorClientId === anchorClientId,
+ );
+ for (const changeSet of changeSets) {
+ items.push({
+ type: 'turn_changes',
+ key: `turnchanges-${changeSet.id}`,
+ changeSet,
+ });
}
- const boundaryCreatedAt = hi < messages.length ? messages[hi]?.createdAt : undefined;
- const parsedTurnEndMs = boundaryCreatedAt ? Date.parse(boundaryCreatedAt) : NaN;
- const turnEndMs = Number.isFinite(parsedTurnEndMs) ? parsedTurnEndMs : null;
- // key 锚定该 turn 首条消息 clientId,窗口滚动 / 流式增量下稳定。
- items.push({
- type: 'generated_files',
- key: `genfiles-${messages[lo].clientId}`,
- files,
- turnStartMs,
- turnEndMs,
- });
};
-
let i = 0;
while (i < messages.length) {
const msg = messages[i];
- // user turn 边界(非 steer、非合成触发):先 flush 上一轮的产出文件卡,
- // 再进入常规处理。第一条 user 消息时 lo==hi,flushGeneratedFiles 自身 no-op。
+ // User turn boundary: attach the sealed patch after the turn it belongs to.
if (msg.role === 'user' && msg.delivery !== 'steer' && !msg.isSyntheticTrigger) {
flushSegment();
- flushGeneratedFiles(turnStartIdx, i);
+ flushTurnChanges(turnStartIdx, i);
turnStartIdx = i;
}
@@ -1389,7 +1373,7 @@ export function buildRenderItems(
// ends mid-segment (no closing text yet).
flushSegment();
// 末尾 turn 的产出文件卡(没有后续 user 边界触发)。
- flushGeneratedFiles(turnStartIdx, messages.length);
+ flushTurnChanges(turnStartIdx, messages.length);
if (taskUpdates) {
// 父会话自己的 Bash 调用集合:local_bash 任务卡(#247 的「后台命令」卡,含
@@ -2405,6 +2389,41 @@ export function MessageStream({
}
}, [messages]);
+ const [turnChangeSets, setTurnChangeSets] = useState<TurnChangeSetSummary[]>([]);
+ useEffect(() => {
+ if (!sessionId || remoteHostId !== null || isRemoteSessionSticky(sessionId)) {
+ setTurnChangeSets([]);
+ return;
+ }
+ let cancelled = false;
+ setTurnChangeSets([]);
+ const off = subscribeTurnChangeSetUpdated(sessionId, ({ summary }) => {
+ if (cancelled) return;
+ setTurnChangeSets((current) => {
+ const next = current.filter((item) => item.id !== summary.id);
+ next.push(summary);
+ next.sort((a, b) => a.createdAt - b.createdAt);
+ return next;
+ });
+ });
+ void window.electronAPI.maker.listTurnChangeSets(sessionId)
+ .then((next) => {
+ if (cancelled) return;
+ setTurnChangeSets((current) => {
+ const merged = new Map(next.map((item) => [item.id, item]));
+ for (const item of current) merged.set(item.id, item);
+ return Array.from(merged.values()).sort((a, b) => a.createdAt - b.createdAt);
+ });
+ })
+ .catch(() => {
+ // A live push may already have arrived; keep it instead of clearing the card.
+ });
+ return () => {
+ cancelled = true;
+ off();
+ };
+ }, [remoteHostId, sessionId]);
+
// 全量 build:折叠 / 丢弃 / 反向膨胀的所有规则一次性吸收 — 窗口看到的就是
// 用户看到的。流式中每 token messages 引用变 → 这里跑一次 O(n) 单线性扫描,
// 实测 N=1000 < 2ms (Windows),如果未来发现瓶颈再走增量化(out of scope)。
@@ -2412,9 +2431,9 @@ export function MessageStream({
() =>
buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {
historyWindowIncomplete: Boolean(hasMoreMessages),
- workingDir,
+ turnChangeSets,
}),
- [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, workingDir],
+ [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, turnChangeSets],
);
const assistantsWithFollowingUserBoundary = useMemo(
() => collectAssistantsWithFollowingUserBoundary(messages),
@@ -3723,13 +3742,13 @@ export function MessageStream({
return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;
}
- if (item.type === 'generated_files') {
+ if (item.type === 'turn_changes') {
+ if (!sessionId) return null;
return (
- <GeneratedFilesCard
+ <TurnChangesCard
key={item.key}
- files={item.files}
- turnStartMs={item.turnStartMs}
- turnEndMs={item.turnEndMs}
+ sessionId={sessionId}
+ changeSet={item.changeSet}
/>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
new file mode 100644
index 0000000000..9f0497fcf1
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
@@ -0,0 +1,187 @@
+import { useRef, useState } from 'react';
+import { AlertTriangle, ChevronDown, ChevronUp, FileDiff, FileText } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { openTurnReview } from '@/features/right-sidebar/lib/openTurnReview';
+import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
+import { resolveToolFilePath } from '@/lib/localPathResolver';
+import { basename, cn } from '@/lib/utils';
+import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';
+import type { TurnChangeFileSummary, TurnChangeSetSummary } from '../../../shared/turnChangeSet';
+import { useChatSessionFile } from './ChatSessionFileContext';
+import { TextLightbox } from './TextLightbox';
+import { useFileChipContextMenu } from './useFileChipContextMenu';
+import { isHtmlFilePath } from './useOpenWithMenu';
+
+const MAX_VISIBLE_FILES = 3;
+
+function TurnChangeFileRow({
+ sessionId,
+ cwd,
+ file,
+ onOpenReview,
+}: {
+ sessionId: string;
+ cwd: string;
+ file: TurnChangeFileSummary;
+ onOpenReview: () => void;
+}) {
+ const fileRowRef = useRef<HTMLButtonElement>(null);
+ const [sourcePreviewOpen, setSourcePreviewOpen] = useState(false);
+ const sessionFileContext = useChatSessionFile();
+ const absolutePath = resolveToolFilePath(file.path, cwd);
+ const htmlWithSession = isHtmlFilePath(absolutePath) ? sessionId : undefined;
+ const contextMenu = useFileChipContextMenu({
+ getAbsPath: () => absolutePath,
+ canOpenInBrowser: isBrowserOpenablePath(absolutePath),
+ sidebarOpenSessionId: htmlWithSession,
+ onViewSource: htmlWithSession
+ ? async () => {
+ if (!(await shouldOpenTextLightboxForOrigin(sessionFileContext, absolutePath))) return;
+ setSourcePreviewOpen(true);
+ }
+ : undefined,
+ });
+
+ return (
+ <>
+ <button
+ ref={fileRowRef}
+ type="button"
+ title={absolutePath}
+ onClick={onOpenReview}
+ onContextMenu={contextMenu.onContextMenu}
+ className="flex h-9 w-full items-center gap-2 rounded-lg px-2 text-left transition-colors hover:bg-[var(--surface-hover)]"
+ >
+ <FileText size={15} className="shrink-0 text-[var(--text-secondary)]" />
+ <span className="min-w-0 flex-1 truncate text-[13px] text-[var(--text-primary)]">
+ {file.path}
+ </span>
+ <span className="shrink-0 whitespace-nowrap font-mono text-[12px] tabular-nums">
+ {file.additions > 0 && (
+ <span className="text-[var(--diff-add-fg)]">+{file.additions}</span>
+ )}{' '}
+ {file.deletions > 0 && (
+ <span className="text-[var(--diff-del-fg)]">-{file.deletions}</span>
+ )}
+ </span>
+ </button>
+ {contextMenu.menu}
+ {sourcePreviewOpen && (
+ <TextLightbox
+ filePath={absolutePath}
+ fileName={basename(absolutePath)}
+ triggerRef={fileRowRef}
+ onClose={() => setSourcePreviewOpen(false)}
+ />
+ )}
+ </>
+ );
+}
+
+export function TurnChangesCard({
+ sessionId,
+ changeSet,
+}: {
+ sessionId: string;
+ changeSet: TurnChangeSetSummary;
+}) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+ const files = changeSet.files;
+ const visibleFiles = expanded ? files : files.slice(0, MAX_VISIBLE_FILES);
+ const hiddenCount = changeSet.fileCount - visibleFiles.length;
+ const omittedCount = Math.max(0, changeSet.fileCount - files.length);
+
+ const openReview = (selectedDiffId?: string): void => {
+ void openTurnReview(sessionId, [changeSet.id], {
+ selectedDiffId: selectedDiffId ?? null,
+ });
+ };
+
+ return (
+ <section className="my-1 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
+ <div className="flex min-h-16 items-center gap-3 px-4 py-3">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <FileDiff size={18} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-medium text-[var(--text-primary)]">
+ {files.length > 0
+ ? t('chat.turnChanges.title', { count: changeSet.fileCount })
+ : t('chat.turnChanges.partialTitle')}
+ </div>
+ <div className="mt-0.5 font-mono text-[12px] tabular-nums">
+ <span className="text-[var(--diff-add-fg)]">+{changeSet.additions}</span>{' '}
+ <span className="text-[var(--diff-del-fg)]">-{changeSet.deletions}</span>
+ </div>
+ {changeSet.state === 'partial' && (
+ <div className="mt-1 flex items-center gap-1 text-[11px] text-[var(--warning-fg)]">
+ <AlertTriangle size={12} />
+ <span>{t('chat.turnChanges.partial')}</span>
+ </div>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={() => openReview()}
+ className="h-8 shrink-0 rounded-lg border border-[var(--border-default)] px-3 text-[13px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)]"
+ >
+ {t('chat.turnChanges.review')}
+ </button>
+ </div>
+
+ {files.length > 0 && (
+ <div className="border-t border-[var(--border-default)] px-3 py-2">
+ {visibleFiles.map((file) => (
+ <TurnChangeFileRow
+ key={file.id}
+ sessionId={sessionId}
+ cwd={changeSet.cwd}
+ file={file}
+ onOpenReview={() => openReview(file.id)}
+ />
+ ))}
+ {!expanded && hiddenCount > 0 && (
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ className={cn(
+ 'flex h-8 items-center gap-1 rounded-lg px-2 text-[13px] text-[var(--text-secondary)]',
+ 'transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ {t('chat.turnChanges.showMore', { count: hiddenCount })}
+ <ChevronDown size={14} />
+ </button>
+ )}
+ {expanded && omittedCount > 0 && (
+ <button
+ type="button"
+ onClick={() => openReview()}
+ className={cn(
+ 'flex h-8 items-center gap-1 rounded-lg px-2 text-[13px] text-[var(--text-secondary)]',
+ 'transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ {t('chat.turnChanges.reviewRemaining', { count: omittedCount })}
+ </button>
+ )}
+ {expanded && files.length > MAX_VISIBLE_FILES && (
+ <button
+ type="button"
+ onClick={() => setExpanded(false)}
+ className={cn(
+ 'flex h-8 items-center gap-1 rounded-lg px-2 text-[13px] text-[var(--text-secondary)]',
+ 'transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ {t('chat.turnChanges.showLess')}
+ <ChevronUp size={14} />
+ </button>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
new file mode 100644
index 0000000000..332bf24451
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
@@ -0,0 +1,148 @@
+// @vitest-environment jsdom
+
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ onContextMenu: vi.fn(),
+ openTurnReview: vi.fn(async () => undefined),
+ shouldOpenTextLightboxForOrigin: vi.fn(async () => true),
+ useFileChipContextMenu: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: { count?: number }) =>
+ values?.count === undefined ? key : `${key}:${values.count}`,
+ }),
+}));
+
+vi.mock('@/features/right-sidebar/lib/openTurnReview', () => ({
+ openTurnReview: mocks.openTurnReview,
+}));
+
+vi.mock('@/lib/filePreview', () => ({
+ shouldOpenTextLightboxForOrigin: mocks.shouldOpenTextLightboxForOrigin,
+}));
+
+vi.mock('../TextLightbox', () => ({
+ TextLightbox: ({ filePath, fileName }: { filePath: string; fileName: string }) => (
+ <div data-testid="text-lightbox">{`${fileName}:${filePath}`}</div>
+ ),
+}));
+
+vi.mock('../useFileChipContextMenu', () => ({
+ useFileChipContextMenu: mocks.useFileChipContextMenu,
+}));
+
+import { TurnChangesCard } from '../TurnChangesCard';
+import type { TurnChangeSetSummary } from '../../../../shared/turnChangeSet';
+
+const CHANGE_SET: TurnChangeSetSummary = {
+ id: 'change-1',
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ providerTurnId: 'turn-1',
+ cwd: 'C:\\repo',
+ state: 'complete',
+ incompleteReasons: [],
+ createdAt: 1,
+ completedAt: 2,
+ files: [{
+ id: 'file-1',
+ path: 'src/test.ts',
+ oldPath: null,
+ status: 'modified',
+ additions: 3,
+ deletions: 1,
+ }],
+ fileCount: 1,
+ additions: 3,
+ deletions: 1,
+};
+
+const HTML_CHANGE_SET: TurnChangeSetSummary = {
+ ...CHANGE_SET,
+ files: [{
+ ...CHANGE_SET.files[0],
+ id: 'file-html',
+ path: 'web/page.html',
+ }],
+};
+
+describe('TurnChangesCard file actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.useFileChipContextMenu.mockReturnValue({
+ onContextMenu: mocks.onContextMenu,
+ openAt: vi.fn(),
+ menu: <div>file-context-menu</div> as ReactNode,
+ });
+ });
+
+ it('opens the shared file context menu with the turn cwd resolved path', () => {
+ render(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);
+
+ const fileRow = screen.getByRole('button', { name: /src\/test\.ts/ });
+ fireEvent.contextMenu(fileRow);
+
+ expect(mocks.onContextMenu).toHaveBeenCalledTimes(1);
+ expect(mocks.useFileChipContextMenu).toHaveBeenCalledTimes(1);
+ const [{ getAbsPath, canOpenInBrowser, sidebarOpenSessionId, onViewSource }] =
+ mocks.useFileChipContextMenu.mock.calls[0] as [{
+ getAbsPath: () => string;
+ canOpenInBrowser: boolean;
+ sidebarOpenSessionId?: string;
+ onViewSource?: () => Promise<void>;
+ }];
+ expect(getAbsPath()).toBe('C:\\repo\\src\\test.ts');
+ expect(canOpenInBrowser).toBe(false);
+ expect(sidebarOpenSessionId).toBeUndefined();
+ expect(onViewSource).toBeUndefined();
+ expect(screen.getByText('file-context-menu')).toBeTruthy();
+ });
+
+ it('matches markdown HTML file actions and lazily opens the current source', async () => {
+ render(<TurnChangesCard sessionId="session-1" changeSet={HTML_CHANGE_SET} />);
+
+ const [{ getAbsPath, canOpenInBrowser, sidebarOpenSessionId, onViewSource }] =
+ mocks.useFileChipContextMenu.mock.calls[0] as [{
+ getAbsPath: () => string;
+ canOpenInBrowser: boolean;
+ sidebarOpenSessionId?: string;
+ onViewSource?: () => Promise<void>;
+ }];
+
+ expect(getAbsPath()).toBe('C:\\repo\\web\\page.html');
+ expect(canOpenInBrowser).toBe(true);
+ expect(sidebarOpenSessionId).toBe('session-1');
+ expect(onViewSource).toEqual(expect.any(Function));
+ expect(mocks.shouldOpenTextLightboxForOrigin).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await onViewSource?.();
+ });
+
+ expect(mocks.shouldOpenTextLightboxForOrigin).toHaveBeenCalledWith(
+ expect.objectContaining({ origin: { kind: 'local' } }),
+ 'C:\\repo\\web\\page.html',
+ );
+ expect(screen.getByTestId('text-lightbox').textContent).toBe(
+ 'page.html:C:\\repo\\web\\page.html',
+ );
+ });
+
+ it('keeps left click routed to exact turn review', () => {
+ render(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /src\/test\.ts/ }));
+
+ expect(mocks.openTurnReview).toHaveBeenCalledWith(
+ 'session-1',
+ ['change-1'],
+ { selectedDiffId: 'file-1' },
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
index 4622df841d..43a09f5a72 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
@@ -12,6 +12,7 @@ import {
openFileInSidebarFileBrowser,
} from './openInSidebarFileBrowser';
import { openBackgroundTasksTab } from './openBackgroundTasksTab';
+import { openTurnReview } from './openTurnReview';
import { openUrlInSidebarBrowser } from './openInSidebarBrowser';
/** 在 main 已选定的当前 renderer host 中执行命令,不自行选择宿主。 */
@@ -50,6 +51,14 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<
});
return;
}
+ if (command.type === 'open-turn-review') {
+ await openTurnReview(command.sessionId, command.changeSetIds, {
+ selectedDiffId: command.selectedDiffId ?? null,
+ selectedPath: command.selectedPath ?? null,
+ requestNonce: command.requestNonce,
+ });
+ return;
+ }
await ensureHydrated(command.sessionId);
await addOrFocusSingletonTab(command.sessionId, 'terminal');
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts
new file mode 100644
index 0000000000..8dcacc1f3a
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts
@@ -0,0 +1,43 @@
+import {
+ addOrFocusSingletonTab,
+ ensureHydrated,
+ patchTabState,
+} from '../store';
+import { routeSidebarCommand } from './detachedSidebarRouting';
+import { requestRightSidebarVisibility } from './sidebarCommands';
+
+let nextRequestNonce = 0;
+
+export async function openTurnReview(
+ sessionId: string,
+ changeSetIds: string[],
+ opts: { selectedDiffId?: string | null; selectedPath?: string | null; requestNonce?: number } = {},
+): Promise<void> {
+ const requestNonce = opts.requestNonce ?? ++nextRequestNonce;
+ const command = {
+ type: 'open-turn-review' as const,
+ sessionId,
+ changeSetIds,
+ selectedDiffId: opts.selectedDiffId ?? null,
+ selectedPath: opts.selectedPath ?? null,
+ requestNonce,
+ };
+ const routeResult = await routeSidebarCommand(command);
+ if (routeResult !== 'attached') {
+ if (routeResult === 'routed') requestRightSidebarVisibility('open', { sessionId });
+ return;
+ }
+
+ await ensureHydrated(sessionId);
+ const tab = await addOrFocusSingletonTab(sessionId, 'review', null);
+ await patchTabState(sessionId, tab.id, (current) => ({
+ ...(current && typeof current === 'object' ? current as Record<string, unknown> : {}),
+ turnTarget: {
+ changeSetIds,
+ selectedDiffId: opts.selectedDiffId ?? null,
+ selectedPath: opts.selectedPath ?? null,
+ requestNonce,
+ },
+ }));
+ requestRightSidebarVisibility('open', { sessionId });
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
index 8e7e04e19d..0c3a6712d8 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
@@ -58,6 +58,8 @@ import type {
} from '@/lib/gitReview.types';
import { formatSidebarTime } from '@/features/cc-agent/lib/formatSidebarTime';
import { makerChatStore } from '@/lib/makerChatStore';
+import { makerApiFor } from '@/lib/makerTransport';
+import type { TurnChangeSetDetail } from '../../../../../shared/turnChangeSet';
import { extractIpcError } from '@/utils/ipcError';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
@@ -366,7 +368,143 @@ export function useClearReviewOperationNoticeOnSourceChange(
}, [clearOperationNotice, source]);
}
-export function ReviewTabBody({ state, ctx }: ReviewTabBodyProps) {
+export function ReviewTabBody(props: ReviewTabBodyProps) {
+ if (props.state.turnTarget) return <TurnChangeSetReviewBody {...props} />;
+ return <GitReviewTabBody {...props} />;
+}
+
+function TurnChangeSetReviewBody({ state, ctx }: ReviewTabBodyProps) {
+ const { t } = useTranslation();
+ const target = state.turnTarget;
+ const [changeSets, setChangeSets] = useState<TurnChangeSetDetail[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [reloadToken, setReloadToken] = useState(0);
+ const targetIdsKey = target?.changeSetIds.join('\0') ?? '';
+ const diffs = useMemo(() => changeSets.flatMap((set) => set.diffs), [changeSets]);
+ const isPartial = changeSets.some((set) => set.state === 'partial');
+ const collapsedSet = useMemo(() => new Set(state.collapsedPaths ?? []), [state.collapsedPaths]);
+ const visibleDiffs = useMemo(
+ () => filterWhitespaceHiddenDiffs(diffs, state.hideWhitespace ?? false),
+ [diffs, state.hideWhitespace],
+ );
+ const expandedSet = useMemo(
+ () => getExpandedDiffSet(visibleDiffs, collapsedSet),
+ [collapsedSet, visibleDiffs],
+ );
+
+ useEffect(() => {
+ if (!targetIdsKey) return;
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ if (ctx.remoteHostId !== null || ctx.deviceLinkDeviceId !== null) {
+ setChangeSets([]);
+ setError(t('rightSidebar.review.turn.localOnly'));
+ setLoading(false);
+ return;
+ }
+ void window.electronAPI.maker.getTurnChangeSets(ctx.sessionId, targetIdsKey.split('\0'))
+ .then((sets) => {
+ if (cancelled) return;
+ setChangeSets(sets);
+ })
+ .catch((reason: unknown) => {
+ if (cancelled) return;
+ setError(extractIpcError(reason)?.message ?? (reason instanceof Error ? reason.message : String(reason)));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [ctx.deviceLinkDeviceId, ctx.remoteHostId, ctx.sessionId, reloadToken, t, targetIdsKey]);
+
+ const selectedDiff = target?.selectedDiffId
+ ? visibleDiffs.find((diff) => diff.id === target.selectedDiffId)
+ : target?.selectedPath
+ ? visibleDiffs.find((diff) => diff.path === target.selectedPath || diff.oldPath === target.selectedPath)
+ : null;
+ const jumpRequest = selectedDiff && target
+ ? { id: selectedDiff.id, nonce: target.requestNonce }
+ : null;
+ const togglePath = useCallback((id: string) => {
+ const next = new Set(collapsedSet);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ ctx.patchState({ collapsedPaths: Array.from(next) });
+ }, [collapsedSet, ctx]);
+ const totalAdd = visibleDiffs.reduce((sum, diff) => sum + diff.additions, 0);
+ const totalDel = visibleDiffs.reduce((sum, diff) => sum + diff.deletions, 0);
+ const unavailablePreview = useCallback(() => Promise.reject(new Error('Historical preview unavailable')), []);
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
+ <header className="flex min-h-12 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-3 py-2">
+ <FileDiffIcon size={15} className="shrink-0 text-[var(--text-secondary)]" />
+ <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-[var(--text-primary)]">
+ {t('rightSidebar.review.turn.title')}
+ </span>
+ <span className="shrink-0 whitespace-nowrap font-mono text-[11px] tabular-nums">
+ <span className="text-[var(--diff-add-fg)]">+{totalAdd}</span>{' '}
+ <span className="text-[var(--diff-del-fg)]">-{totalDel}</span>
+ </span>
+ <button
+ type="button"
+ onClick={() => ctx.patchState({ turnTarget: null })}
+ className="h-7 shrink-0 rounded-full px-2 text-[11px] font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ {t('rightSidebar.review.turn.currentWorkspace')}
+ </button>
+ </header>
+ {!loading && !error && isPartial && (
+ <div className="flex shrink-0 items-start gap-2 border-b border-[var(--border-default)] bg-[var(--warning-bg-soft)] px-3 py-2 text-[11px] leading-relaxed text-[var(--text-secondary)]">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" />
+ <span>{t('rightSidebar.review.turn.partialNotice')}</span>
+ </div>
+ )}
+ {loading ? (
+ <CenteredState icon={<Spinner size={24} />} title={t('rightSidebar.review.loadingTitle')} desc={t('rightSidebar.review.loadingDesc')} />
+ ) : error ? (
+ <CenteredState
+ icon={<AlertTriangle size={24} />}
+ title={t('rightSidebar.review.errorTitle')}
+ desc={error}
+ actionLabel={t('rightSidebar.review.refresh')}
+ onAction={() => setReloadToken((value) => value + 1)}
+ />
+ ) : visibleDiffs.length === 0 ? (
+ <CenteredState
+ icon={<FileDiffIcon size={24} />}
+ title={t('rightSidebar.review.turn.emptyTitle')}
+ desc={t('rightSidebar.review.turn.emptyDesc')}
+ />
+ ) : (
+ <DiffList
+ diffs={visibleDiffs}
+ expandedSet={expandedSet}
+ onToggleDiff={togglePath}
+ onRefresh={() => setReloadToken((value) => value + 1)}
+ refreshPending={loading}
+ viewMode={state.diffViewMode ?? 'unified'}
+ onViewModeChange={(diffViewMode) => ctx.patchState({ diffViewMode })}
+ onRichMarkdownPreviewChange={(richMarkdownPreview) => ctx.patchState({ richMarkdownPreview })}
+ wordWrap={state.wordWrap ?? false}
+ wordDiff={state.wordDiff ?? true}
+ fileTreeVisible={state.fileTreeVisible ?? false}
+ jumpRequest={jumpRequest}
+ loadImagePreview={unavailablePreview}
+ loadMarkdownPreview={unavailablePreview}
+ richMarkdownPreview={false}
+ onOpenFile={() => undefined}
+ />
+ )}
+ </div>
+ );
+}
+
+function GitReviewTabBody({ state, ctx }: ReviewTabBodyProps) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
const sessionId = ctx.sessionId || null;
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
index bc0c1bcc1c..6486a9a2b7 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
@@ -22,6 +22,13 @@ import { ReviewTabBody } from './ReviewTabBody';
import type { DiffViewMode } from './DiffViewer/PlainUnifiedDiff';
export interface ReviewState {
+ /** Programmatic exact-turn review target. Null keeps the normal Git-backed review surface. */
+ turnTarget: {
+ changeSetIds: string[];
+ selectedDiffId: string | null;
+ selectedPath: string | null;
+ requestNonce: number;
+ } | null;
/** 用户收起过哪些 diff id。空数组表示所有当前 diff 默认展开。 */
collapsedPaths: string[];
/** diff 展示模式。写操作仍回到原始 unified DiffLine.index。 */
@@ -41,6 +48,7 @@ export interface ReviewState {
}
const DEFAULT_STATE: ReviewState = {
+ turnTarget: null,
collapsedPaths: [],
diffViewMode: 'unified',
fileTreeVisible: false,
@@ -100,7 +108,26 @@ const plugin: TabKindPlugin<ReviewState> = {
const branchBaseRef = typeof obj.branchBaseRef === 'string' && isSafeBranchBaseRef(obj.branchBaseRef.trim())
? obj.branchBaseRef.trim()
: null;
- return { collapsedPaths, diffViewMode, fileTreeVisible, wordWrap, wordDiff, hideWhitespace, richMarkdownPreview, branchBaseRef };
+ const rawTurnTarget = obj.turnTarget;
+ const turnTarget = rawTurnTarget && typeof rawTurnTarget === 'object'
+ && Array.isArray((rawTurnTarget as { changeSetIds?: unknown }).changeSetIds)
+ && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.length > 0
+ && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.length <= 16
+ && (rawTurnTarget as { changeSetIds: unknown[] }).changeSetIds.every((id) => typeof id === 'string')
+ ? {
+ changeSetIds: (rawTurnTarget as { changeSetIds: string[] }).changeSetIds,
+ selectedDiffId: typeof (rawTurnTarget as { selectedDiffId?: unknown }).selectedDiffId === 'string'
+ ? (rawTurnTarget as { selectedDiffId: string }).selectedDiffId
+ : null,
+ selectedPath: typeof (rawTurnTarget as { selectedPath?: unknown }).selectedPath === 'string'
+ ? (rawTurnTarget as { selectedPath: string }).selectedPath
+ : null,
+ requestNonce: typeof (rawTurnTarget as { requestNonce?: unknown }).requestNonce === 'number'
+ ? (rawTurnTarget as { requestNonce: number }).requestNonce
+ : 0,
+ }
+ : null;
+ return { turnTarget, collapsedPaths, diffViewMode, fileTreeVisible, wordWrap, wordDiff, hideWhitespace, richMarkdownPreview, branchBaseRef };
},
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0389d2a91a..eeaed5eed6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4470,6 +4470,14 @@
"spawnFailed": "Failed to start terminal: {{detail}}"
},
"review": {
+ "turn": {
+ "title": "Changes from this turn",
+ "currentWorkspace": "Current workspace",
+ "localOnly": "Exact turn changes are not available for remote sessions yet.",
+ "partialNotice": "This turn includes command or tool writes that could not be tracked exactly. Only the captured subset is shown; it is not a complete patch.",
+ "emptyTitle": "No recorded changes",
+ "emptyDesc": "The recorded patch for this turn has no displayable file changes."
+ },
"fileCount_one": "{{count}} file",
"fileCount_other": "{{count}} files",
"emptyTitle": "No changes yet",
@@ -6188,9 +6196,13 @@
"DEVICE_LINK_CONTROL_DISABLED": "Control for this device is off; the message was not sent.",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "Attachment transfer failed; the message was not sent. Please try again."
},
- "generatedFiles": {
- "title": "Files created this turn",
- "showMore": "Show {{count}} more",
+ "turnChanges": {
+ "title": "Changed {{count}} files",
+ "partialTitle": "File changes were not fully captured",
+ "review": "Review",
+ "partial": "Only the changes captured exactly are shown",
+ "showMore": "Show {{count}} more files",
+ "reviewRemaining": "Review {{count}} more files",
"showLess": "Show less"
},
"agentActions": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f270cde795..7771947db2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4468,6 +4468,14 @@
"spawnFailed": "ターミナルを起動できません: {{detail}}"
},
"review": {
+ "turn": {
+ "title": "このターンの変更",
+ "currentWorkspace": "現在のワークスペース",
+ "localOnly": "ターン単位の正確な変更は、リモートタスクではまだ利用できません。",
+ "partialNotice": "このターンには正確に追跡できないコマンドまたはツールの書き込みが含まれます。以下は取得できた一部のみで、完全なパッチではありません。",
+ "emptyTitle": "記録された変更はありません",
+ "emptyDesc": "このターンで保存されたパッチに表示可能なファイル変更はありません。"
+ },
"fileCount_one": "{{count}} ファイル",
"fileCount_other": "{{count}} ファイル",
"emptyTitle": "変更はまだありません",
@@ -6186,9 +6194,13 @@
"DEVICE_LINK_CONTROL_DISABLED": "このデバイスの操作はオフです。メッセージは送信されていません。",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "添付ファイルの転送に失敗しました。メッセージは送信されていません。もう一度お試しください。"
},
- "generatedFiles": {
- "title": "このターンで生成されたファイル",
- "showMore": "さらに {{count}} 件を表示",
+ "turnChanges": {
+ "title": "{{count}} ファイルを変更",
+ "partialTitle": "このターンのファイル変更を完全には取得できませんでした",
+ "review": "レビュー",
+ "partial": "正確に取得できた変更のみ表示しています",
+ "showMore": "さらに {{count}} ファイルを表示",
+ "reviewRemaining": "残り {{count}} ファイルをレビューで表示",
"showLess": "折りたたむ"
},
"agentActions": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5adb540980..b188e47189 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4468,6 +4468,14 @@
"spawnFailed": "터미널을 시작할 수 없습니다: {{detail}}"
},
"review": {
+ "turn": {
+ "title": "이번 턴의 변경 사항",
+ "currentWorkspace": "현재 작업 공간",
+ "localOnly": "턴별 정확한 변경 사항은 아직 원격 작업에서 사용할 수 없습니다.",
+ "partialNotice": "이번 턴에는 정확히 추적할 수 없는 명령 또는 도구 쓰기가 포함되어 있습니다. 아래에는 캡처된 일부만 표시되며 완전한 패치가 아닙니다.",
+ "emptyTitle": "기록된 변경 사항 없음",
+ "emptyDesc": "이번 턴에 저장된 패치에 표시할 수 있는 파일 변경 사항이 없습니다."
+ },
"fileCount_one": "{{count}}개 파일",
"fileCount_other": "{{count}}개 파일",
"emptyTitle": "아직 변경 사항이 없습니다",
@@ -6186,9 +6194,13 @@
"DEVICE_LINK_CONTROL_DISABLED": "이 기기의 제어가 꺼져 있어 메시지가 전송되지 않았습니다.",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "첨부 파일 전송에 실패했습니다. 메시지가 전송되지 않았습니다. 다시 시도하세요."
},
- "generatedFiles": {
- "title": "이번 턴에 생성된 파일",
- "showMore": "{{count}}개 더 보기",
+ "turnChanges": {
+ "title": "파일 {{count}}개 변경",
+ "partialTitle": "이번 턴의 파일 변경 사항이 완전히 캡처되지 않았습니다",
+ "review": "검토",
+ "partial": "정확히 캡처된 변경 사항만 표시됩니다",
+ "showMore": "파일 {{count}}개 더 보기",
+ "reviewRemaining": "나머지 파일 {{count}}개를 검토에서 보기",
"showLess": "접기"
},
"agentActions": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 2c2e699d34..df4dc4178d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4468,6 +4468,14 @@
"spawnFailed": "无法启动终端:{{detail}}"
},
"review": {
+ "turn": {
+ "title": "本轮变更",
+ "currentWorkspace": "当前工作区",
+ "localOnly": "本轮精确变更暂不支持远程任务。",
+ "partialNotice": "本轮包含无法精确追踪的命令或工具写入;以下仅展示已精确捕获的部分,不能视为完整补丁。",
+ "emptyTitle": "没有已记录的变更",
+ "emptyDesc": "本轮保存的补丁中没有可显示的文件变更。"
+ },
"fileCount_one": "{{count}} 个文件",
"fileCount_other": "{{count}} 个文件",
"emptyTitle": "暂无改动",
@@ -6186,9 +6194,13 @@
"DEVICE_LINK_CONTROL_DISABLED": "已关闭对该设备的控制,消息未发送。",
"DEVICE_LINK_MEDIA_TRANSFER_FAILED": "附件传输失败,消息未发送。请重试。"
},
- "generatedFiles": {
- "title": "本轮生成的文件",
+ "turnChanges": {
+ "title": "已更改 {{count}} 个文件",
+ "partialTitle": "本轮文件变更未完整记录",
+ "review": "审查",
+ "partial": "仅记录了可精确捕获的部分变更",
"showMore": "再显示 {{count}} 个文件",
+ "reviewRemaining": "在审查中查看其余 {{count}} 个文件",
"showLess": "收起"
},
"agentActions": {
diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.ts
deleted file mode 100644
index 31369d5adc..0000000000
--- a/apps/desktop/src/renderer/lib/generatedFiles.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- * generatedFiles — 从一轮回复的 tool_use 消息里派生「本轮 agent 新建的文件」。
- * ---------------------------------------------------------------------------
- * 纯派生、不新增持久化:tool_use 消息本身已落库并原样回放,所以历史会话重开后
- * 这张卡能稳定重建。跨 agent(claude-code / codex / pi)的工具名差异统一交给
- * `describeToolUse` 归一化,不自己维护工具名表:
- * - kind==='file' 且 action==='create' → Write / write(claude / pi 新建文件)
- * - kind==='fileChange' 的 changes 里 action==='add' → codex file_change 新增文件
- * - kind==='command' → 从命令文本启发式提取产物路径候选(source:'command')。
- * Excel / Word / PDF 等二进制产物只能靠脚本(Bash/exec 跑 python、node)生成,
- * 没有文件工具记录;不补这个盲区,卡在「帮我生成个表格」主场景直接失灵。
- * 「修改已有文件」(edit / update)与读取不算产出(产品口径:只收新建,见
- * AskUserQuestion 决策)。move / delete 同样排除。
- *
- * 误报防线(source:'command' 特有,由渲染方 GeneratedFilesCard 执行):
- * 命令文本里出现路径 ≠ 命令创建了它(可能只是读输入)。所以 command 候选除
- * 存在性外,还必须满足「文件 mtime 落在本轮时间窗内」才出 chip;窗口不可得
- * (消息无 createdAt / 远程会话无法 stat)时宁可不出。tool 来源保持原判定。
- */
-
-import { describeToolUse } from '@cindy/maker-shared';
-
-import { resolveToolFilePath } from './localPathResolver';
-import { basename } from './utils';
-
-export interface GeneratedFileRef {
- /** 已按 workingDir 解析的绝对路径(用于存在性校验与 chip 打开)。 */
- path: string;
- /** 展示用文件名(basename)。 */
- name: string;
- /**
- * 'tool' = 文件工具结构化新建记录,存在即列;
- * 'command' = 命令文本启发式候选,渲染前还需 mtime 时间窗校验。
- */
- source: 'tool' | 'command';
-}
-
-interface ToolUseLike {
- role: string;
- toolName?: string;
- toolInput?: unknown;
-}
-
-/**
- * 去重 key。**只对 Windows 路径形态**(盘符前缀或含反斜杠)做大小写不敏感折叠——
- * NTFS 上 `A.txt` 与 `a.txt` 是同一文件;POSIX 路径(Linux 本地会话 / 远程 Linux
- * workdir)必须保留原大小写,否则会把两个真实不同的文件错误合并、丢掉一个
- * (PR #1835 review)。macOS 虽默认大小写不敏感,但无法从纯 POSIX 路径形态区分
- * macOS 与 Linux;两害相权取轻:宁可 macOS 偶尔多出一个重复 chip,也不能在 Linux
- * 上丢文件。
- */
-function dedupeKeyForPath(abs: string): string {
- const isWindowsShape = /^[a-zA-Z]:[\\/]/.test(abs) || abs.includes('\\');
- // 斜杠也归一:`C:/x/a.md`(命令文本常见形态)与 `C:\x\a.md`(Write 记录)是
- // 同一文件,不折叠会重复出 chip。
- return isWindowsShape ? abs.replace(/\//g, '\\').toLowerCase() : abs;
-}
-
-/**
- * Windows 形态的绝对路径统一成反斜杠本机形态再往下传:Explorer `/select`
- * (定位)对正斜杠路径静默无反应,`shell.openPath` 在仅用户层文件关联的机器上
- * 对正斜杠也会解析失败(实测「本轮产出」卡 docx chip 打不开的根因)。POSIX
- * 路径原样保留。
- */
-function canonicalizeWindowsShape(abs: string): string {
- return /^[a-zA-Z]:[\\/]/.test(abs) ? abs.replace(/\//g, '\\') : abs;
-}
-
-/** 单条 tool_use 消息 → 它新建的文件原始路径列表(可能为空)。 */
-function createdPathsFromToolUse(toolName: string, input: unknown): string[] {
- const descriptor = describeToolUse(toolName, input);
- if (descriptor.kind === 'file') {
- return descriptor.action === 'create' && descriptor.filePath ? [descriptor.filePath] : [];
- }
- if (descriptor.kind === 'fileChange') {
- return descriptor.changes
- .filter((c) => c.action === 'add' && c.path)
- .map((c) => c.path);
- }
- return [];
-}
-
-/** 带扩展名(1–8 位字母数字,不含纯数字)的路径才算候选;`a.b.c` 取末段。 */
-const EXT_RE = /\.[A-Za-z][A-Za-z0-9]{0,7}$/;
-
-/** 临时目录里的产物是脚本自身/中间文件的高发区,一律不算「本轮产出」。 */
-const TEMP_DIR_RE = /(^|[\\/])(tmp|temp)([\\/])|[\\/]AppData[\\/]Local[\\/]Temp[\\/]/i;
-
-function isPathCandidate(raw: string): boolean {
- const s = raw.trim();
- if (s.length < 3 || s.length > 512) return false;
- if (!EXT_RE.test(s)) return false;
- if (TEMP_DIR_RE.test(s)) return false;
- // 绝对路径,或含分隔符的相对路径(交给 resolveToolFilePath 按 workingDir 解析)。
- // 纯文件名(`输出.xlsx`)不收:随机带点 token 误报率太高。
- const isAbs = /^[A-Za-z]:[\\/]/.test(s) || s.startsWith('/');
- const hasSep = s.includes('/') || s.includes('\\');
- return isAbs || hasSep;
-}
-
-/**
- * 命令文本 → 产物路径候选。两个来源:
- * 1. 引号字符串(`'...'` / `"..."`):脚本内路径的主形态,可含空格与 CJK,
- * 如 python 的 `wb.save(r'C:\Users\x\表格.xlsx')`;
- * 2. 裸 token:重定向 / CLI 参数里的无引号绝对路径(不含空格)。
- * 只做形态过滤,不判断读写意图——读写区分交给渲染方的 mtime 时间窗。
- */
-export function extractCommandPathCandidates(command: string): string[] {
- if (!command) return [];
- const out: string[] = [];
- const seen = new Set<string>();
- const push = (raw: string): void => {
- const s = raw.trim();
- if (!isPathCandidate(s)) return;
- if (seen.has(s)) return;
- seen.add(s);
- out.push(s);
- };
- for (const m of command.matchAll(/'([^'\r\n]+)'|"([^"\r\n]+)"/g)) {
- push(m[1] ?? m[2] ?? '');
- }
- // 裸 Windows 盘符路径与裸 POSIX 绝对路径(前面是行首/空白/常见分隔)。
- // 盘符前不允许字母数字:排除 URL scheme 尾字母被当盘符(https://…)。
- for (const m of command.matchAll(/(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s'"<>|?*]+/g)) push(m[0]);
- for (const m of command.matchAll(/(?:^|[\s=(,>])(\/[^\s'"<>|?*:]+)/g)) push(m[1]);
- return out;
-}
-
-/**
- * 一组消息(通常是一个 turn 的切片,但对任意切片都成立)→ 新建文件的有序去重
- * 列表。路径经 `resolveToolFilePath` 解析成绝对路径;`workingDir` 为空时按原样
- * 保留(与其它 chip 解析同策)。存在性(及 command 候选的 mtime 时间窗)校验由
- * 调用方在渲染前做(异步 IPC)。同一路径同时有 tool 与 command 来源时按 tool 计
- * (tool 是结构化实锤,不该被降级成启发式候选)。
- */
-export function collectGeneratedFiles(
- messages: readonly ToolUseLike[],
- workingDir: string,
-): GeneratedFileRef[] {
- // 第一遍:收「本轮被文件工具**修改**过」的路径。它们是编辑不是新建,命令文本
- // 里再出现也不算产物候选——否则跑测试 / 构建命令引用刚编辑过的源码文件
- // (`vitest run src/x.test.ts`)会被 mtime 窗口放行,把编码会话的改动文件全
- // 误收进卡。read 不排除:agent 生成后回读验证是常见动作,不该反杀真产物。
- const editedKeys = new Set<string>();
- for (const msg of messages) {
- if (msg.role !== 'tool_use' || !msg.toolName) continue;
- const d = describeToolUse(msg.toolName, msg.toolInput);
- if (d.kind === 'file' && d.action === 'edit' && d.filePath) {
- editedKeys.add(dedupeKeyForPath(resolveToolFilePath(d.filePath, workingDir)));
- } else if (d.kind === 'fileChange') {
- for (const c of d.changes) {
- if (c.action !== 'add' && c.path) {
- editedKeys.add(dedupeKeyForPath(resolveToolFilePath(c.path, workingDir)));
- }
- }
- }
- }
-
- const byKey = new Map<string, GeneratedFileRef>();
- for (const msg of messages) {
- if (msg.role !== 'tool_use') continue;
- const toolName = msg.toolName ?? '';
- if (!toolName) continue;
-
- const addPath = (rawPath: string, source: GeneratedFileRef['source']): void => {
- const abs = canonicalizeWindowsShape(resolveToolFilePath(rawPath, workingDir));
- const key = dedupeKeyForPath(abs);
- if (source === 'command' && editedKeys.has(key)) return;
- const prev = byKey.get(key);
- if (prev) {
- if (prev.source === 'command' && source === 'tool') prev.source = 'tool';
- return;
- }
- byKey.set(key, { path: abs, name: basename(abs), source });
- };
-
- for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {
- addPath(rawPath, 'tool');
- }
- const descriptor = describeToolUse(toolName, msg.toolInput);
- if (descriptor.kind === 'command' && descriptor.command) {
- for (const rawPath of extractCommandPathCandidates(descriptor.command)) {
- addPath(rawPath, 'command');
- }
- }
- }
- return [...byKey.values()];
-}
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index c6e520826b..df6df07785 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -18,6 +18,7 @@ import {
getSessionDeviceId,
remoteProjectsStore,
} from '@/features/device-link/remoteProjectsStore';
+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import {
accountCounterAtRequestStart,
@@ -31,6 +32,7 @@ import type { Message, Session } from '@/lib/ccAgent.types';
import * as messageService from '@/lib/messageService';
import * as sessionService from '@/lib/sessionService';
import { extractIpcError } from '@/utils/ipcError';
+import type { TurnChangeSetUpdatedPayload } from '../../shared/turnChangeSet';
type FullMaker = typeof window.electronAPI.maker;
@@ -221,6 +223,40 @@ export function makerApiForSticky(sessionId: string): RoutableMaker {
return deviceId ? makerApiForDevice(deviceId) : window.electronAPI.maker;
}
+/** Subscribe to local exact-turn updates; remote sessions deliberately fail closed in this phase. */
+export function subscribeTurnChangeSetUpdated(
+ sessionId: string,
+ cb: (payload: TurnChangeSetUpdatedPayload) => void,
+): () => void {
+ const bind = (deviceId: string | undefined): (() => void) => {
+ if (!deviceId) {
+ return window.electronAPI.maker.onTurnChangeSetUpdated((raw, ownerStamp) => {
+ if (!isDataOwnerPushCurrent(ownerStamp)) return;
+ const payload = raw as Partial<TurnChangeSetUpdatedPayload> | null;
+ if (payload?.sessionId !== sessionId || !payload.summary) return;
+ cb(payload as TurnChangeSetUpdatedPayload);
+ });
+ }
+ // Exact patches can exceed the 2 MiB device-link frame. This phase fails closed for
+ // controlled sessions instead of truncating a patch and presenting it as exact.
+ return () => {};
+ };
+
+ let currentDeviceId = getStickySessionDeviceId(sessionId);
+ let offInner = bind(currentDeviceId);
+ const offStore = remoteProjectsStore.subscribe(() => {
+ const nextDeviceId = getStickySessionDeviceId(sessionId);
+ if (nextDeviceId === currentDeviceId) return;
+ currentDeviceId = nextDeviceId;
+ offInner();
+ offInner = bind(nextDeviceId);
+ });
+ return () => {
+ offStore();
+ offInner();
+ };
+}
+
/** 是否远程(device-link)会话。 */
export function isRemoteSession(sessionId: string): boolean {
return getSessionDeviceId(sessionId) !== undefined;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 271fb3bf45..8a55bb4b84 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5293,6 +5293,16 @@ interface ElectronAPI {
xaiOAuthCancel: () => Promise<{ authorized: boolean }>;
// Push channels
+ listTurnChangeSets: (
+ sessionId: string,
+ ) => Promise<import('../shared/turnChangeSet').TurnChangeSetSummary[]>;
+ getTurnChangeSets: (
+ sessionId: string,
+ ids: string[],
+ ) => Promise<import('../shared/turnChangeSet').TurnChangeSetDetail[]>;
+ onTurnChangeSetUpdated: (
+ cb: (data: unknown, ownerStamp?: unknown) => void,
+ ) => () => void;
onEvent: (cb: (data: unknown) => void) => () => void;
onStatusChanged: (cb: (data: unknown) => void) => () => void;
onInteractionRequest: (cb: (data: unknown) => void) => () => void;
diff --git a/apps/desktop/src/shared/gitReviewWire.ts b/apps/desktop/src/shared/gitReviewWire.ts
index 99345c406b..f24ac5f612 100644
--- a/apps/desktop/src/shared/gitReviewWire.ts
+++ b/apps/desktop/src/shared/gitReviewWire.ts
@@ -141,7 +141,7 @@ export interface Hunk {
export interface FileDiff {
id: string;
- source: 'staged' | 'unstaged' | 'commit' | 'branch';
+ source: 'staged' | 'unstaged' | 'commit' | 'branch' | 'turn';
path: string;
oldPath: string | null;
status: DiffChangeKind;
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index 01ab334eca..ae341e93c6 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -49,6 +49,14 @@ export type RsbWindowCommand =
sessionId: string;
focusTaskId?: string | null;
}
+ | {
+ type: 'open-turn-review';
+ sessionId: string;
+ changeSetIds: string[];
+ selectedDiffId?: string | null;
+ selectedPath?: string | null;
+ requestNonce: number;
+ }
| {
type: 'open-file-browser';
sessionId: string;
diff --git a/apps/desktop/src/shared/turnChangeSet.ts b/apps/desktop/src/shared/turnChangeSet.ts
new file mode 100644
index 0000000000..dabc67de20
--- /dev/null
+++ b/apps/desktop/src/shared/turnChangeSet.ts
@@ -0,0 +1,70 @@
+import type { DiffChangeKind, FileDiff } from './gitReviewWire';
+
+export const TURN_CHANGE_SET_MAX_DIFF_BYTES = 12 * 1024 * 1024;
+
+export type TurnChangeProvider = 'codex' | 'claude-code' | 'pi';
+export type TurnChangeSetState = 'complete' | 'partial';
+export type TurnChangeIncompleteReason =
+ | 'opaque-tool'
+ | 'outside-workspace'
+ | 'remote-session'
+ | 'file-too-large'
+ | 'binary-file'
+ | 'sensitive-file'
+ | 'read-failed'
+ | 'diff-too-large'
+ | 'turn-failed';
+
+export interface TurnChangeFileSummary {
+ id: string;
+ path: string;
+ oldPath: string | null;
+ status: DiffChangeKind;
+ additions: number;
+ deletions: number;
+}
+
+export interface TurnChangeSetSummary {
+ /** Cindy-owned product-turn identity. */
+ id: string;
+ sessionId: string;
+ /** Visible user message that owns this product turn. */
+ anchorClientId: string;
+ provider: TurnChangeProvider;
+ /** Optional provider identity (Codex app-server turn id today). */
+ providerTurnId: string | null;
+ cwd: string;
+ state: TurnChangeSetState;
+ incompleteReasons: TurnChangeIncompleteReason[];
+ createdAt: number;
+ completedAt: number;
+ files: TurnChangeFileSummary[];
+ fileCount: number;
+ additions: number;
+ deletions: number;
+}
+
+export interface TurnChangeSetDetail extends TurnChangeSetSummary {
+ diffs: FileDiff[];
+}
+
+export interface PersistedTurnChangeSetV1 {
+ version: 1;
+ id: string;
+ sessionId: string;
+ anchorClientId: string;
+ provider: TurnChangeProvider;
+ providerTurnId: string | null;
+ cwd: string;
+ state: TurnChangeSetState;
+ incompleteReasons: TurnChangeIncompleteReason[];
+ createdAt: number;
+ completedAt: number;
+ unifiedDiff: string;
+ files: TurnChangeFileSummary[];
+}
+
+export interface TurnChangeSetUpdatedPayload {
+ sessionId: string;
+ summary: TurnChangeSetSummary;
+}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 8fffad7270..0c2e4048fb 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -284,7 +284,27 @@ export class CodexResumePreparationBlockedError extends Error {
}
}
+export interface TurnChangeCaptureHooks {
+ /** Capture one known target before the provider is allowed to mutate it. */
+ beforeKnownFileWrite(input: {
+ sessionId: string;
+ provider: 'claude-code' | 'pi';
+ cwd: string;
+ targetPath: string;
+ remote?: boolean;
+ }): Promise<void>;
+ /** Record a tool whose filesystem effects cannot be known before execution. */
+ noteOpaqueWrite(input: {
+ sessionId: string;
+ provider: 'claude-code' | 'pi';
+ cwd: string;
+ remote?: boolean;
+ }): void;
+}
+
export interface AgentDeps {
+ /** Optional low-I/O, provider-neutral turn change recorder supplied by the host. */
+ turnChangeCapture?: TurnChangeCaptureHooks;
auth: AuthAdapter;
runtimeConfig: AgentRuntimeConfig;
/**
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
index 145004f917..2625cd8a27 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
@@ -199,6 +199,7 @@ async function startSession(
status: string;
scope?: string;
}>;
+ turnChangeCapture?: AgentDeps['turnChangeCapture'];
},
) {
const configDir = await makeTempDir();
@@ -214,6 +215,7 @@ async function startSession(
const deps = createDeps(policy, options?.mcpServerNames);
deps.capabilityRouting = options?.capabilityRouting;
+ deps.turnChangeCapture = options?.turnChangeCapture;
const agent = new ClaudeCodeAgent(deps);
const handle = await agent.startSession({
sessionId: 'session-mcp-policy',
@@ -250,6 +252,7 @@ async function startSession(
canUseTool: queryOptions.canUseTool,
hooks: queryOptions.hooks,
seen,
+ workingDir,
};
}
@@ -272,6 +275,47 @@ afterEach(async () => {
});
describe('ClaudeCodeAgent canUseTool honors the host MCP approval policy', () => {
+ it('captures known writes before execution and marks Bash opaque only after execution', async () => {
+ const beforeKnownFileWrite = vi.fn(async () => undefined);
+ const noteOpaqueWrite = vi.fn();
+ const { handle, hooks, workingDir } = await startSession(undefined, {
+ turnChangeCapture: { beforeKnownFileWrite, noteOpaqueWrite },
+ });
+ const pre = hooks?.PreToolUse?.[0]?.hooks[0];
+ const post = hooks?.PostToolUse?.[0]?.hooks[0];
+ if (!pre || !post) throw new Error('expected turn change capture hooks');
+
+ await pre({
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: 'a.ts', content: 'next' },
+ });
+ await pre({
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'touch b.ts' },
+ });
+ expect(beforeKnownFileWrite).toHaveBeenCalledWith({
+ sessionId: 'session-mcp-policy',
+ provider: 'claude-code',
+ cwd: workingDir,
+ targetPath: 'a.ts',
+ });
+ expect(noteOpaqueWrite).not.toHaveBeenCalled();
+
+ await post({
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Bash',
+ tool_input: { command: 'touch b.ts' },
+ });
+ expect(noteOpaqueWrite).toHaveBeenCalledWith({
+ sessionId: 'session-mcp-policy',
+ provider: 'claude-code',
+ cwd: workingDir,
+ });
+ await handle.close();
+ });
+
it('injects the local route as a PreToolUse guard even in Full access', async () => {
const capabilityRouting = {
overrides: [
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 4a0a624c5c..b20433ead8 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -30,7 +30,15 @@ import {
query as sdkQuery,
forkSession as sdkForkSession,
} from '@anthropic-ai/claude-agent-sdk';
-import type { Query, CanUseTool, McpServerConfig, PermissionUpdate, Settings } from '@anthropic-ai/claude-agent-sdk';
+import type {
+ Query,
+ CanUseTool,
+ HookCallback,
+ McpServerConfig,
+ PermissionUpdate,
+ PreToolUseHookInput,
+ Settings,
+} from '@anthropic-ai/claude-agent-sdk';
import { discoverSubagentDefinitions } from './subagent-definitions.js';
import {
reportSubagentModelDiagnostics,
@@ -1231,6 +1239,44 @@ export class ClaudeCodeAgent extends BaseAgent {
.filter(Boolean)
.join('\n');
};
+ const turnChangeCaptureHook: HookCallback = async (input) => {
+ const captureCwd = opts.workingDir;
+ const captureSessionId = opts.sessionId;
+ if (!this.deps.turnChangeCapture || !captureCwd || !captureSessionId) {
+ return { continue: true };
+ }
+ if (input.hook_event_name === 'PreToolUse') {
+ const pre = input as PreToolUseHookInput;
+ const toolInput = pre.tool_input as Record<string, unknown> | undefined;
+ const targetPath = ['file_path', 'path', 'notebook_path']
+ .map((key) => toolInput?.[key])
+ .find((value): value is string => typeof value === 'string' && value.length > 0);
+ if (targetPath && ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(pre.tool_name)) {
+ await this.deps.turnChangeCapture.beforeKnownFileWrite({
+ sessionId: captureSessionId,
+ provider: 'claude-code',
+ cwd: captureCwd,
+ targetPath,
+ ...(opts.remoteHostId ? { remote: true } : {}),
+ });
+ }
+ } else if (
+ input.hook_event_name === 'PostToolUse'
+ || input.hook_event_name === 'PostToolUseFailure'
+ ) {
+ const toolName = (input as { tool_name?: unknown }).tool_name;
+ if (typeof toolName !== 'string' || (toolName !== 'Bash' && !toolName.startsWith('mcp__'))) {
+ return { continue: true };
+ }
+ this.deps.turnChangeCapture.noteOpaqueWrite({
+ sessionId: captureSessionId,
+ provider: 'claude-code',
+ cwd: captureCwd,
+ ...(opts.remoteHostId ? { remote: true } : {}),
+ });
+ }
+ return { continue: true };
+ };
const localClaudeHooks = mergeClaudeHookSets(
buildClaudeLocalToolGuardHooks(
this.deps.capabilityRouting,
@@ -1244,6 +1290,11 @@ export class ClaudeCodeAgent extends BaseAgent {
},
() => nonHarnessMcpServerNames,
),
+ {
+ PreToolUse: [{ hooks: [turnChangeCaptureHook] }],
+ PostToolUse: [{ hooks: [turnChangeCaptureHook] }],
+ PostToolUseFailure: [{ hooks: [turnChangeCaptureHook] }],
+ },
this.deps.claudeHooks,
);
const deniedCapabilityRoute = (toolName: string) => {
diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.ts
index 95ce431913..98f3af0314 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts
@@ -1038,11 +1038,13 @@ describe('AppServerHost descendant notification routing', () => {
const itemStarted = vi.fn();
const tokenUsageUpdated = vi.fn();
const turnCompleted = vi.fn();
+ const turnDiffUpdated = vi.fn();
const subscription = host.subscribeThread('root-thread', {
descendantNotification,
itemStarted,
tokenUsageUpdated,
turnCompleted,
+ turnDiffUpdated,
});
transport.emit({
@@ -1066,32 +1068,45 @@ describe('AppServerHost descendant notification routing', () => {
method: 'turn/completed',
params: { threadId: 'grandchild-thread', turn: { id: 'turn-g1', status: 'completed' } },
};
+ const childDiff = {
+ method: 'turn/diff/updated',
+ params: { threadId: 'child-thread', turnId: 'turn-c1', diff: 'diff --git a/a b/a' },
+ };
transport.emit(childItem);
transport.emit(childUsage);
transport.emit(grandchildTurn);
+ transport.emit(childDiff);
expect(descendantNotification.mock.calls).toEqual([
['child-thread', 'item/started', childItem.params],
['child-thread', 'thread/tokenUsage/updated', childUsage.params],
['grandchild-thread', 'turn/completed', grandchildTurn.params],
+ ['child-thread', 'turn/diff/updated', childDiff.params],
]);
// 关键隔离:子线程事件绝不能进主线程 handler —— 否则子代理的 exec 会被渲染成
// 主会话自己的工具调用,并污染主 turn 的 usage 与状态机。
expect(itemStarted).not.toHaveBeenCalled();
expect(tokenUsageUpdated).not.toHaveBeenCalled();
expect(turnCompleted).not.toHaveBeenCalled();
+ expect(turnDiffUpdated).not.toHaveBeenCalled();
// 主线程自己的同名事件照旧走主通道。
transport.emit({
method: 'item/started',
params: { threadId: 'root-thread', turnId: 'turn-r1', item: { id: 'i-2', type: 'commandExecution' } },
});
+ const rootDiff = {
+ method: 'turn/diff/updated',
+ params: { threadId: 'root-thread', turnId: 'turn-r1', diff: 'diff --git a/b b/b' },
+ };
+ transport.emit(rootDiff);
expect(itemStarted).toHaveBeenCalledTimes(1);
- expect(descendantNotification).toHaveBeenCalledTimes(3);
+ expect(turnDiffUpdated).toHaveBeenCalledWith(rootDiff.params);
+ expect(descendantNotification).toHaveBeenCalledTimes(4);
await subscription.release();
transport.emit(childItem);
- expect(descendantNotification).toHaveBeenCalledTimes(3);
+ expect(descendantNotification).toHaveBeenCalledTimes(4);
// thread/started 只走专用的 descendantThreadStarted,不重复出现在本通道。
expect(descendantNotification.mock.calls.some(([, method]) => method === 'thread/started')).toBe(false);
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 04f4a11eaf..85d8c40a21 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -57,6 +57,7 @@ import {
type ThreadUnsubscribeResponse,
type TurnPlanUpdatedNotification,
type TurnCompletedNotification,
+ type TurnDiffUpdatedNotification,
type TurnStartedNotification,
type ReasoningSummaryTextDeltaNotification,
type ReasoningSummaryPartAddedNotification,
@@ -81,6 +82,7 @@ const SUBSCRIBED_METHODS = [
'thread/started',
'turn/started',
'turn/completed',
+ 'turn/diff/updated',
'thread/tokenUsage/updated', // Codex usage 走单独通知 (不在 turn/completed 上), 必订
'item/started',
'item/updated',
@@ -104,8 +106,6 @@ const NOTIFICATIONS_TO_OPT_OUT = [
'item/plan/delta',
'item/commandExecution/outputDelta',
'item/fileChange/outputDelta',
- // 后续要做实时 patch / plan 流时再去掉:
- 'turn/diff/updated',
];
const DEFAULT_THREAD_UNSUBSCRIBE_TIMEOUT_MS = 5_000;
@@ -136,6 +136,7 @@ export interface ThreadEventHandlers {
descendantNotification?: (childThreadId: string, method: string, params: unknown) => void;
turnStarted?: (params: TurnStartedNotification['params']) => void;
turnCompleted?: (params: TurnCompletedNotification['params']) => void;
+ turnDiffUpdated?: (params: TurnDiffUpdatedNotification['params']) => void;
/** 每次 turn 都会推一次 (turn 完成前), 与 turn/completed 在同 turnId 下成对出现。 */
tokenUsageUpdated?: (params: ThreadTokenUsageUpdatedNotification['params']) => void;
itemStarted?: (params: ItemStartedNotification['params']) => void;
@@ -1371,6 +1372,7 @@ export class AppServerHost {
case 'thread/started': fn = handlers.threadStarted as (p: never) => void; break;
case 'turn/started': fn = handlers.turnStarted as (p: never) => void; break;
case 'turn/completed': fn = handlers.turnCompleted as (p: never) => void; break;
+ case 'turn/diff/updated': fn = handlers.turnDiffUpdated as (p: never) => void; break;
case 'thread/tokenUsage/updated': fn = handlers.tokenUsageUpdated as (p: never) => void; break;
case 'item/started': fn = handlers.itemStarted as (p: never) => void; break;
case 'item/updated': fn = handlers.itemUpdated as (p: never) => void; break;
diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.ts
index fc240b5a35..1d49481793 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -802,6 +802,11 @@ export interface TurnStartedNotification {
params: { threadId: string; turn: { id: string; [k: string]: unknown }; [k: string]: unknown };
}
+export interface TurnDiffUpdatedNotification {
+ method: 'turn/diff/updated';
+ params: { threadId: string; turnId: string; diff: string; [k: string]: unknown };
+}
+
/**
* v2.rs TurnCompletedNotification: { thread_id, turn: Turn }
* Turn 包含 status (TurnStatus enum: completed/interrupted/failed/inProgress)
@@ -1154,6 +1159,7 @@ export interface ItemEnvelope {
export type ServerNotification =
| ThreadStartedNotification
| TurnStartedNotification
+ | TurnDiffUpdatedNotification
| TurnCompletedNotification
| ThreadTokenUsageUpdatedNotification
| ItemStartedNotification
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 31c68d3728..8db8dfd461 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -7848,6 +7848,19 @@ export class CodexAgent extends BaseAgent {
});
}
},
+ turnDiffUpdated: (params) => {
+ if (enqueueIfBufferedTurn(params.turnId, () => handlers.turnDiffUpdated?.(params))) return;
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
+ eventQueue.push({
+ type: 'turn_diff',
+ data: {
+ turnId: params.turnId,
+ diff: params.diff,
+ cwd: opts.workingDir,
+ },
+ source: 'codex',
+ });
+ },
turnCompleted: (params) => {
// buffered turn 的终态同样进队列等对账 (greptile R11 P1 + codex R12 P1):
// 合法 → 激活后按序重放, handleTurnCompleted 自然收口 send; 孤儿 →
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 1caddfb145..f8c2e844d0 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -29,4 +29,12 @@ describe('cindy-bridge extension source', () => {
expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain('`');
expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain('${');
});
+
+ it('captures known writes before execution and marks opaque tools only after a result', () => {
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on('tool_call'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('FILE_WRITE_BUILTINS.has(event.toolName)');
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on('tool_result'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("event.toolName !== 'bash'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("startsWith('mcp__')");
+ });
});
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 38f1c17dba..08cdfbedf0 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -43,6 +43,7 @@ import {
} from '@earendil-works/pi-coding-agent';
const PERMISSION_TITLE = 'cindy:permission';
+const TURN_CHANGE_CAPTURE_TITLE = 'cindy:turn-change-capture';
const READONLY_BUILTINS = new Set(['read', 'grep', 'find', 'ls']);
const FILE_WRITE_BUILTINS = new Set(['edit', 'write']);
const MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH';
@@ -633,6 +634,23 @@ export default async function cindyBridge(pi: any) {
// ── 权限门 ────────────────────────────────────────────────────────────────
pi.on('tool_call', async (event: any, ctx: any) => {
+ if (FILE_WRITE_BUILTINS.has(event.toolName)) {
+ try {
+ // Internal synchronization point: the host snapshots only the target file for
+ // known-path writes. The result is deliberately ignored; capture must never turn
+ // an observability failure into a tool-execution failure.
+ await ctx.ui.confirm(
+ TURN_CHANGE_CAPTURE_TITLE,
+ JSON.stringify({
+ toolName: event.toolName,
+ toolUseId: event.toolCallId,
+ input: event.input ?? {},
+ }),
+ );
+ } catch {
+ // Best-effort capture; the permission boundary below remains authoritative.
+ }
+ }
const permission = currentPermissionState();
// Extra Dirs 的结构化写工具永远禁止,即使 Full access 也不能把“只读引用”静默
// 升级成写目录。bash 仍由 Cindy 审批/模型指令约束(Pi 暂无 OS sandbox API)。
@@ -676,6 +694,22 @@ export default async function cindyBridge(pi: any) {
}
});
+ pi.on('tool_result', async (event: any, ctx: any) => {
+ if (event.toolName !== 'bash' && !String(event.toolName ?? '').startsWith('mcp__')) return;
+ try {
+ await ctx.ui.confirm(
+ TURN_CHANGE_CAPTURE_TITLE,
+ JSON.stringify({
+ toolName: event.toolName,
+ toolUseId: event.toolCallId,
+ input: event.input ?? {},
+ }),
+ );
+ } catch {
+ // Best-effort capture; tool results must never fail because observability did.
+ }
+ });
+
// ── MCP 桥 ────────────────────────────────────────────────────────────────
const raw = process.env.CINDY_PI_MCP_BRIDGE;
if (!raw) return;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 0a60469388..82b2b970bc 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -1225,6 +1225,9 @@ export class PiAgent extends BaseAgent {
notifyAutoReviewUnavailable: () => autoReviewUnavailableNotice.notify(),
registeredMcpServerNames,
registerPendingPrompt,
+ sessionId: opts.sessionId ?? '',
+ workingDir: opts.workingDir ?? '',
+ remote: Boolean(opts.remoteHostId),
}));
return;
}
@@ -2241,6 +2244,9 @@ export class PiAgent extends BaseAgent {
notifyAutoReviewUnavailable: () => void;
/** 本会话实际注册过的桥接 MCP server 名;MCP 归属判定只认这批(防冒名顶替)。 */
registeredMcpServerNames: ReadonlySet<string>;
+ sessionId: string;
+ workingDir: string;
+ remote: boolean;
/**
* 把一张挂起的权限卡登记进会话级表,返回注销函数。档位切换 / 关闭会话时由
* `dismissAllPendingPrompts` 强制 settle,避免放宽档位后调用仍卡在失效的卡上。
@@ -2255,6 +2261,50 @@ export class PiAgent extends BaseAgent {
const id = typeof event.id === 'string' ? event.id : undefined;
if (!id) return;
+ if (method === 'confirm' && event.title === 'cindy:turn-change-capture') {
+ let toolName = '';
+ let input: Record<string, unknown> = {};
+ try {
+ const payload = JSON.parse(typeof event.message === 'string' ? event.message : '{}') as {
+ toolName?: unknown;
+ input?: unknown;
+ };
+ if (typeof payload.toolName === 'string') toolName = payload.toolName;
+ if (payload.input && typeof payload.input === 'object') input = payload.input as Record<string, unknown>;
+ } catch {
+ // Malformed capture payload is non-fatal; let the tool proceed and mark it opaque.
+ }
+ const context = getPermissionCtx();
+ void (async () => {
+ if (!context.sessionId || !context.workingDir) return;
+ const targetPath = typeof input.path === 'string' ? input.path : null;
+ if (targetPath && (toolName === 'edit' || toolName === 'write')) {
+ await this.deps.turnChangeCapture?.beforeKnownFileWrite({
+ sessionId: context.sessionId,
+ provider: 'pi',
+ cwd: context.workingDir,
+ targetPath,
+ ...(context.remote ? { remote: true } : {}),
+ });
+ } else {
+ this.deps.turnChangeCapture?.noteOpaqueWrite({
+ sessionId: context.sessionId,
+ provider: 'pi',
+ cwd: context.workingDir,
+ ...(context.remote ? { remote: true } : {}),
+ });
+ }
+ })().catch((error) => {
+ this.deps.logger.warn('pi turn change capture failed', {
+ toolName,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }).finally(() => {
+ proc.send({ type: 'extension_ui_response', id, confirmed: true });
+ });
+ return;
+ }
+
if (method === 'confirm' && event.title === 'cindy:permission') {
let toolName = 'tool';
let input: Record<string, unknown> = {};
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index 94182f19c8..cac1ccd53a 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -20,6 +20,7 @@ export type AgentEventType =
| 'agent_task_update' // 子 agent / task 状态更新(Claude Code task_* + Codex collab agent)
| 'image' // 模型查看 / 生成的图片 (codex 独有, claude SDK 不会发)
| 'account_usage' // vendor-specific 账号级用量 (codex rateLimits 等); data shape 由 emit 端自定, renderer 按 source/字段嗅探
+ | 'turn_diff' // provider 对本轮工作区变更的累计 unified diff
| 'interaction_request' // 需要用户决策(permission / ask_user_question / plan_review)
| 'interaction_dismissed' // pending interaction 被自动 resolve(如 setPermissionMode 切换)
| 'plan_mode_changed' // agent 自行切换计划模式(典型: 计划批准后自动退出), data: { enabled: boolean }; host 据此回写持久化 + 广播 UI
@@ -29,6 +30,15 @@ export type AgentEventType =
| 'done' // 一轮 turn 完成
| 'error'; // 错误(是否结束 turn 由 error data 的 isTerminal 显式表达)
+export interface TurnDiffEventData {
+ /** Provider-owned turn identity. Same id updates replace, rather than append to, the prior diff. */
+ turnId: string;
+ /** Cumulative unified diff for this provider turn. */
+ diff: string;
+ /** Workspace root used when the provider computed the patch. */
+ cwd: string;
+}
+
export interface AgentErrorEventData {
message: string;
/**