Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持本轮改动撤销与重新应用
DavidShen3516c5cebee3
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 0960eb5a6d..7c255c0d8c 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -37,6 +37,7 @@ import {} from './devStartupStatus';import { prewarmMacComputerPermissionGuideHelper } from './computer-permission-guide/MacComputerPermissionGuideNativeHost.js';import { handleOpenChatGPTApp } from './chatgpt-app.js';+import { waitForTurnChangeSetActions } from './turn-change-set/store.js';const PROCESS_STARTED_AT_MS = Date.now();// Official Linux binaries total hundreds of MB. Keep one shared deadline for@@ -78,6 +79,8 @@ app.commandLine.appendSwitch('enable-features', 'SharedArrayBuffer');// Windows 上 codex app-server 子进程不会随父死 → 残留孤儿, 持有 binary 文件锁,// 用户下次启动时撞 EBUSY / 端口占用 (anthropic-compat-proxy 等)。async function shutdownMaker(): Promise<void> {+ // Do not terminate Main while one workspace patch command is settling.+ await waitForTurnChangeSetActions();// 退出前先把 onClose 重副作用(worktree stash/删除、临时附件清理)一刀切抑制掉:// shutdown 触发的批量 onClose 是 fire-and-forget 的,不会被 await,worktree 回收会// 和 app.exit 竞争——可能 stash 了一半进程就没了,留下半拆的 worktree。退出期不做@@ -1011,6 +1014,9 @@ async function ensureLifecycleDbClient(userId: string) {}async function teardownAuthAccountBoundary(reason: string): Promise<void> {+ // The boundary is already marked pending by every caller. New actions now+ // fail closed; drain an action that crossed the boundary before closing its DB.+ await waitForTurnChangeSetActions();skillhubAutoSyncService.cancelInFlight();// Custom provider routes are owner-scoped but the active catalog is process-global.// Clear synchronously at the boundary; the next owner's tracked readiness reloads themdiff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 3b556c7624..12e3cba66a 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -9,6 +9,7 @@ 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',+ TURN_CHANGE_SET_APPLY: 'maker:turn-change-set:apply',MARK_ORCA_ROLE: 'maker:mark-orca-role',/*** F-COLLAB: 中途开关协同模式 (Orca workflow toggle)。diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 844f56a9e5..6701f7c4fd 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -453,6 +453,8 @@ import { validateHandoffWorkingDir } from './handoffWorkingDir.js';import { registerProjectPluginPolicyHandlers } from './projectPluginPolicyHandlers.js';import {TURN_CHANGE_SET_DETAIL_ID_LIMIT,+ TurnChangeSetActionError,+ applyTurnChangeSetAction,beginTurnChangeSet,clearPendingTurnChangeSets,finalizeTurnChangeSet,@@ -672,7 +674,10 @@ import {SessionTurnActivityTracker,} from './sessionTurnActivityTracker.js';import { resolveClearSessionBoundary } from './clearSessionBoundary.js';-import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import {+ captureDataOwnerBroadcastScope,+ tapWindowBroadcast,+} from '../device-link/broadcast-tap.js';import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js';import {markRemoteSettingPersistedInsideHandler,@@ -4780,6 +4785,60 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},);+ ipcMain.handle(+ MAKER_INVOKE.TURN_CHANGE_SET_APPLY,+ async (event, sessionId: unknown, id: unknown, action: unknown) => {+ assertTrustedAppRendererEvent(event);+ const ownerScope = captureDataOwnerBroadcastScope();+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256) {+ throwIpcError('INVALID_PARAMS', 'Invalid sessionId');+ }+ if (typeof id !== 'string' || id.length === 0 || id.length > 256) {+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set id');+ }+ if (action !== 'undo' && action !== 'reapply') {+ throwIpcError('INVALID_PARAMS', 'Invalid turn change-set action');+ }+ const meta = await maker.getSessionMeta(sessionId);+ if (!meta) throwIpcError('NOT_FOUND', 'Task not found.');+ if (meta.remoteHostId) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote workspace restore is not available.');+ }+ const normalizedWorkDir = process.platform === 'win32'+ ? path.resolve(meta.workDir).toLocaleLowerCase('en-US')+ : path.resolve(meta.workDir);+ const workspaceIsBusy = (): boolean => maker.listActiveSessions().some((session) => {+ if (session.remoteHostId) return false;+ const currentWorkDir = process.platform === 'win32'+ ? path.resolve(session.workDir).toLocaleLowerCase('en-US')+ : path.resolve(session.workDir);+ return currentWorkDir === normalizedWorkDir+ && (session.isTurnRunning() || getClaudeSessionBackgroundActivity(session.id));+ });+ if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {+ throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');+ }+ await waitForTurnChangeSetSeal(sessionId);+ if (workspaceIsBusy() || isSessionTurnPendingCompletion(sessionId)) {+ throwIpcError('SESSION_RUNNING', 'Wait for the current response to finish.');+ }+ try {+ return await applyTurnChangeSetAction(sessionId, id, action, ownerScope);+ } catch (error) {+ if (!(error instanceof TurnChangeSetActionError)) {+ log.warn('turn change-set action failed', { sessionId, id, action, error });+ throwIpcError('INTERNAL', 'The recorded changes could not be applied.');+ }+ if (error.kind === 'not-found') throwIpcError('NOT_FOUND', error.message);+ if (error.kind === 'busy') throwIpcError('SESSION_RUNNING', error.message);+ if (error.kind === 'wrong-state') throwIpcError('PRECONDITION_FAILED', error.message);+ if (error.kind === 'unsupported') throwIpcError('UNSUPPORTED_CAPABILITY', error.message);+ if (error.kind === 'conflict') throwIpcError('STALE_DIFF', error.message);+ throwIpcError('INTERNAL', error.message);+ }+ },+ );+ipcMain.handle(MAKER_INVOKE.ANY_SESSION_IN_TURN, () => {return anySessionInTurn(maker);});@@ -9669,7 +9728,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await waitForTurnChangeSetSeal(sessionId);const liveSession = maker.getSession(sessionId);if (liveSession) {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId,anchorClientId: item.clientId,provider: liveSession.agentKind,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.tsindex 1697380f0c..3dbdf5275b 100644--- a/apps/desktop/src/main/turn-change-set/__tests__/store.test.ts+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.test.ts@@ -2,11 +2,13 @@ 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';+import { runGit } from '../../git-review/gitRunner';const mocks = vi.hoisted(() => ({userDataRoot: '',query: vi.fn(),send: vi.fn(),+ ownerCurrent: true,}));vi.mock('electron', () => ({@@ -18,11 +20,13 @@ vi.mock('../../localDb/client/current.js', () => ({}));vi.mock('../../device-link/broadcast-tap.js', () => ({captureDataOwnerBroadcastScope: () => ({ ownerStamp: undefined }),- isDataOwnerBroadcastScopeCurrent: () => true,+ isDataOwnerBroadcastScopeCurrent: () => mocks.ownerCurrent,tapWindowBroadcast: mocks.send,}));import {+ TurnChangeSetActionError,+ applyTurnChangeSetAction,beginTurnChangeSet,captureKnownFileBefore,clearPendingTurnChangeSets,@@ -44,21 +48,27 @@ describe('turn change-set sidecar store', () => {mocks.userDataRoot = path.join(root, 'user-data');mocks.query.mockReset();mocks.send.mockReset();+ mocks.ownerCurrent = true;mocks.query.mockImplementation(async (sql: string) => {+ if (sql.includes('working_dir AS workingDir')) {+ return [{ workingDir: workdir, remoteHostId: null }];+ }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');+ clearPendingTurnChangeSets('session-2');});afterEach(async () => {clearPendingTurnChangeSets('session-1');+ clearPendingTurnChangeSets('session-2');await fs.rm(root, { recursive: true, force: true });});it('persists the native Codex patch under the dispatch anchor without a database write', async () => {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'codex',@@ -96,10 +106,368 @@ describe('turn change-set sidecar store', () => {});});+ it('undoes and reapplies an exact text patch without changing chat history', async () => {+ const target = path.join(workdir, 'a.ts');+ await fs.writeFile(target, 'new\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-action',+ 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-action', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');++ const undo = await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');+ expect(await fs.readFile(target, 'utf8')).toBe('old\n');+ expect(undo).toMatchObject({ action: 'undo', changed: true });+ expect(undo.summary.workspaceState).toBe('undone');+ expect((await listTurnChangeSets('session-1'))[0]?.workspaceState).toBe('undone');++ const reapply = await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');+ expect(await fs.readFile(target, 'utf8')).toBe('new\n');+ expect(reapply.summary.workspaceState).toBe('applied');+ });++ it('keeps every file unchanged when one hunk conflicts', async () => {+ const first = path.join(workdir, 'a.ts');+ const second = path.join(workdir, 'b.ts');+ await fs.writeFile(first, 'new-a\n', 'utf8');+ await fs.writeFile(second, 'new-b\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-conflict',+ cwd: workdir,+ diff: [+ 'diff --git a/a.ts b/a.ts',+ '--- a/a.ts',+ '+++ b/a.ts',+ '@@ -1 +1 @@',+ '-old-a',+ '+new-a',+ 'diff --git a/b.ts b/b.ts',+ '--- a/b.ts',+ '+++ b/b.ts',+ '@@ -1 +1 @@',+ '-old-b',+ '+new-b',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-conflict', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');+ await fs.writeFile(second, 'user-edit\n', 'utf8');++ await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'conflict' } satisfies Partial<TurnChangeSetActionError>);+ expect(await fs.readFile(first, 'utf8')).toBe('new-a\n');+ expect(await fs.readFile(second, 'utf8')).toBe('user-edit\n');+ expect((await listTurnChangeSets('session-1'))[0]?.workspaceState).toBe('applied');+ });++ it('undoes and reapplies a newly created file for Claude without a Git repository', async () => {+ const target = path.join(workdir, 'created.txt');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'claude-code',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'claude-code',+ cwd: workdir,+ targetPath: 'created.txt',+ });+ await fs.writeFile(target, 'created\n', 'utf8');+ await finalizeTurnChangeSet('session-1', null, 'complete');+ const [recorded] = await listTurnChangeSets('session-1');++ await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');+ await expect(fs.stat(target)).rejects.toMatchObject({ code: 'ENOENT' });++ await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');+ expect(await fs.readFile(target, 'utf8')).toBe('created\n');+ });++ it('undoes and reapplies a deleted file for Pi without a Git repository', async () => {+ const target = path.join(workdir, 'deleted.txt');+ await fs.writeFile(target, 'before deletion\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'pi',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'pi',+ cwd: workdir,+ targetPath: 'deleted.txt',+ });+ await fs.rm(target);+ await finalizeTurnChangeSet('session-1', null, 'complete');+ const [recorded] = await listTurnChangeSets('session-1');++ await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');+ expect(await fs.readFile(target, 'utf8')).toBe('before deletion\n');++ await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');+ await expect(fs.stat(target)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('preserves a UTF-8 BOM byte-for-byte through Claude undo and reapply', async () => {+ const target = path.join(workdir, 'bom.txt');+ const before = Buffer.from([0xef, 0xbb, 0xbf, ...Buffer.from('old\n')]);+ const after = Buffer.from([0xef, 0xbb, 0xbf, ...Buffer.from('new\n')]);+ await fs.writeFile(target, before);+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'claude-code',+ cwd: workdir,+ });+ await captureKnownFileBefore({+ sessionId: 'session-1',+ provider: 'claude-code',+ cwd: workdir,+ targetPath: 'bom.txt',+ });+ await fs.writeFile(target, after);+ await finalizeTurnChangeSet('session-1', null, 'complete');+ const [recorded] = await listTurnChangeSets('session-1');++ await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');+ expect(await fs.readFile(target)).toEqual(before);+ await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');+ expect(await fs.readFile(target)).toEqual(after);+ });++ it('keeps legacy sidecar patches review-only', async () => {+ const target = path.join(workdir, 'legacy.txt');+ await fs.writeFile(target, 'new\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-legacy',+ cwd: workdir,+ diff: [+ 'diff --git a/legacy.txt b/legacy.txt',+ '--- a/legacy.txt',+ '+++ b/legacy.txt',+ '@@ -1 +1 @@',+ '-old',+ '+new',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-legacy', 'complete');+ const sidecarDir = path.join(mocks.userDataRoot, 'cc-agent', 'turn-change-sets', 'session-1');+ const indexPath = path.join(sidecarDir, 'index.json');+ const index = JSON.parse(await fs.readFile(indexPath, 'utf8')) as {+ version: number;+ entries: Array<{ id: string }>;+ };+ index.version = 1;+ await fs.writeFile(indexPath, `${JSON.stringify(index)}\n`, 'utf8');+ const detailPath = path.join(sidecarDir, `${index.entries[0]!.id}.json`);+ const detail = JSON.parse(await fs.readFile(detailPath, 'utf8')) as {+ reversibleFormat?: string;+ };+ delete detail.reversibleFormat;+ await fs.writeFile(detailPath, `${JSON.stringify(detail)}\n`, 'utf8');++ expect((await listTurnChangeSets('session-1'))[0]?.isReversible).toBe(false);+ await expect(applyTurnChangeSetAction('session-1', index.entries[0]!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'unsupported' } satisfies Partial<TurnChangeSetActionError>);+ expect(await fs.readFile(target, 'utf8')).toBe('new\n');+ });++ it('rejects undo while another task is changing the same workspace', async () => {+ const target = path.join(workdir, 'busy.txt');+ await fs.writeFile(target, 'new\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-busy',+ cwd: workdir,+ diff: [+ 'diff --git a/busy.txt b/busy.txt',+ '--- a/busy.txt',+ '+++ b/busy.txt',+ '@@ -1 +1 @@',+ '-old',+ '+new',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-busy', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');+ await beginTurnChangeSet({+ sessionId: 'session-2',+ anchorClientId: 'user-2',+ provider: 'pi',+ cwd: workdir,+ });++ await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'busy' } satisfies Partial<TurnChangeSetActionError>);+ expect(await fs.readFile(target, 'utf8')).toBe('new\n');+ clearPendingTurnChangeSets('session-2');+ });++ it('fails closed before mutation when the data-owner scope is stale', async () => {+ const target = path.join(workdir, 'owner.txt');+ await fs.writeFile(target, 'new\n', 'utf8');+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-owner',+ cwd: workdir,+ diff: [+ 'diff --git a/owner.txt b/owner.txt',+ '--- a/owner.txt',+ '+++ b/owner.txt',+ '@@ -1 +1 @@',+ '-old',+ '+new',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-owner', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');+ mocks.ownerCurrent = false;++ await expect(applyTurnChangeSetAction('session-1', recorded!.id, 'undo'))+ .rejects.toMatchObject({ kind: 'busy' } satisfies Partial<TurnChangeSetActionError>);+ expect(await fs.readFile(target, 'utf8')).toBe('new\n');+ mocks.ownerCurrent = true;+ expect((await listTurnChangeSets('session-1'))[0]?.workspaceState).toBe('applied');+ expect(mocks.send).not.toHaveBeenCalled();+ });++ it('reverses and reapplies a pure Codex rename through Git apply', async () => {+ await runGit(['init', '-q'], { cwd: workdir });+ const oldTarget = path.join(workdir, 'old.txt');+ const newTarget = path.join(workdir, 'new.txt');+ await fs.writeFile(oldTarget, 'same\n', 'utf8');+ await runGit(['add', 'old.txt'], { cwd: workdir });+ await fs.rename(oldTarget, newTarget);+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-rename',+ cwd: workdir,+ diff: [+ 'diff --git a/old.txt b/new.txt',+ 'similarity index 100%',+ 'rename from old.txt',+ 'rename to new.txt',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-rename', 'complete');+ const [recorded] = await listTurnChangeSets('session-1');+ expect(recorded?.isReversible).toBe(true);++ await applyTurnChangeSetAction('session-1', recorded!.id, 'undo');+ expect(await fs.readFile(oldTarget, 'utf8')).toBe('same\n');+ await expect(fs.stat(newTarget)).rejects.toMatchObject({ code: 'ENOENT' });++ await applyTurnChangeSetAction('session-1', recorded!.id, 'reapply');+ expect(await fs.readFile(newTarget, 'utf8')).toBe('same\n');+ await expect(fs.stat(oldTarget)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('does not advertise a binary-only native patch as reversible', async () => {+ await beginTurnChangeSet({+ sessionId: 'session-1',+ anchorClientId: 'user-1',+ provider: 'codex',+ cwd: workdir,+ });+ noteTurnDiffEvent('session-1', {+ type: 'turn_diff',+ source: 'codex',+ data: {+ turnId: 'turn-binary',+ cwd: workdir,+ diff: [+ 'diff --git a/image.png b/image.png',+ 'index 1111111..2222222 100644',+ 'Binary files a/image.png and b/image.png differ',+ '',+ ].join('\n'),+ },+ });+ await finalizeTurnChangeSet('session-1', 'turn-binary', 'complete');++ const [recorded] = await listTurnChangeSets('session-1');+ expect(recorded).toMatchObject({ isReversible: false });+ });+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({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'claude-code',@@ -128,7 +496,7 @@ describe('turn change-set sidecar store', () => {});it('filters sensitive files from a native Codex patch', async () => {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'codex',@@ -173,7 +541,7 @@ describe('turn change-set sidecar store', () => {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({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'pi',@@ -195,7 +563,7 @@ describe('turn change-set sidecar store', () => {});it('persists a zero-file partial entry for an opaque tool with unknown targets', async () => {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'pi',@@ -214,7 +582,7 @@ describe('turn change-set sidecar store', () => {});it('does not persist remote workspace patches while remote review is unsupported', async () => {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'codex',@@ -244,7 +612,7 @@ describe('turn change-set sidecar store', () => {});it('bounds the card index while preserving the complete patch for exact review', async () => {- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'codex',@@ -284,7 +652,7 @@ describe('turn change-set sidecar store', () => {const orphanPath = path.join(sidecarDir, 'orphan.json');await fs.writeFile(orphanPath, '{}\n', 'utf8');- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'pi',@@ -302,7 +670,7 @@ describe('turn change-set sidecar store', () => {const secretTarget = path.join(workdir, '.env');await fs.writeFile(safeTarget, 'old\n', 'utf8');await fs.writeFile(secretTarget, 'TOKEN=old\n', 'utf8');- beginTurnChangeSet({+ await beginTurnChangeSet({sessionId: 'session-1',anchorClientId: 'user-1',provider: 'claude-code',diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.tsindex 05e04434ad..5c29d62989 100644--- a/apps/desktop/src/main/turn-change-set/store.ts+++ b/apps/desktop/src/main/turn-change-set/store.ts@@ -1,12 +1,15 @@import { app, BrowserWindow } from 'electron';import { createId } from '@paralleldrive/cuid2';-import { createTwoFilesPatch } from 'diff';+import { createTwoFilesPatch, formatPatch, parsePatch, reversePatch } from 'diff';+import { realpathSync } from 'node:fs';import fs from 'node:fs/promises';import path from 'node:path';import type { AgentEvent, TurnDiffEventData } from '@cindy/maker-core';import type {PersistedTurnChangeSetV1,+ TurnChangeAction,+ TurnChangeActionResult,TurnChangeFileSummary,TurnChangeIncompleteReason,TurnChangeProvider,@@ -14,10 +17,12 @@ import type {TurnChangeSetState,TurnChangeSetSummary,TurnChangeSetUpdatedPayload,+ TurnChangeWorkspaceState,} 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 { GitRunError, runGit } from '../git-review/gitRunner.js';import { getDbClient } from '../localDb/client/current.js';import { createLogger } from '../logger.js';import { detectSensitivePath } from '../security/sensitivePath.js';@@ -38,12 +43,14 @@ 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';+const ACTION_STATE_FILE = 'action-state.json';interface CapturedFile {absolutePath: string;relativePath: string;beforeExists: boolean;beforeText: string;+ beforeMode: number | null;}interface PendingTurnChangeSet {@@ -61,14 +68,20 @@ interface PendingTurnChangeSet {incompleteReasons: Set<TurnChangeIncompleteReason>;}-interface TurnChangeIndexV1 {- version: 1;+interface TurnChangeIndexV2 {+ version: 2;entries: TurnChangeSetSummary[];detailBytes: Record<string, number>;}+interface TurnChangeActionStateV1 {+ version: 1;+ states: Record<string, { workspaceState: TurnChangeWorkspaceState; updatedAt: number }>;+}+const PROVIDERS = new Set<TurnChangeProvider>(['codex', 'claude-code', 'pi']);const STATES = new Set<TurnChangeSetState>(['complete', 'partial']);+const WORKSPACE_STATES = new Set<TurnChangeWorkspaceState>(['applied', 'undone']);const INCOMPLETE_REASONS = new Set<TurnChangeIncompleteReason>(['opaque-tool','outside-workspace',@@ -115,7 +128,12 @@ export interface BeginTurnChangeSetInput {}const pendingBySession = new Map<string, PendingTurnChangeSet>();-const sessionWriteChains = new Map<string, Promise<void>>();+const sessionWriteChains = new Map<string, Promise<unknown>>();+const workspaceActionChains = new Map<string, Promise<unknown>>();+const pendingWorkspaceBySession = new Map<string, string>();+const pendingWorkspaceCounts = new Map<string, number>();+const retainedSessionDirs = new Map<string, number>();+const activeActionPromises = new Set<Promise<unknown>>();let storageWriteChain = Promise.resolve();function byteLength(value: string): number {@@ -193,7 +211,42 @@ function filterSensitiveDiffBlocks(return safeBlocks.join('');}-function toSummary(value: PersistedTurnChangeSetV1): TurnChangeSetSummary {+function isReversiblePatch(value: PersistedTurnChangeSetV1): boolean {+ if (+ value.reversibleFormat !== 'exact-text-v1'+ || value.state !== 'complete'+ || value.unifiedDiff.length === 0+ || value.files.length === 0+ ) {+ return false;+ }+ if (/^(?:GIT binary patch|Binary files .* differ)$/m.test(value.unifiedDiff)) return false;+ if (/^(?:old mode|new mode)\s+/m.test(value.unifiedDiff)) return false;+ if (/\b160000\b/.test(value.unifiedDiff)) return false;+ const fileModes = [...value.unifiedDiff.matchAll(/^(?:new file mode|deleted file mode)\s+(\d+)$/gm)];+ // Reformatting add/delete patches makes them work outside Git repositories, but+ // does not carry executable-bit metadata. Keep those records review-only.+ if (fileModes.some((match) => match[1] !== '100644')) return false;++ const diffs = parseDiffs(value.id, value.unifiedDiff);+ if (diffs.length !== value.files.length) return false;+ return diffs.every((diff) => {+ if (!['added', 'modified', 'deleted', 'renamed'].includes(diff.status)) return false;+ if (!safeRelativeTarget(value.cwd, diff.path)) return false;+ if (diff.oldPath && !safeRelativeTarget(value.cwd, diff.oldPath)) return false;+ if (diff.status === 'renamed' && !diff.oldPath) return false;+ if (diff.status === 'modified' && diff.hunks.length === 0) return false;+ if ((diff.status === 'added' || diff.status === 'deleted') && diff.hunks.length === 0) {+ return false;+ }+ return true;+ });+}++function toSummary(+ value: PersistedTurnChangeSetV1,+ workspaceState: TurnChangeWorkspaceState = 'applied',+): TurnChangeSetSummary {return {id: value.id,sessionId: value.sessionId,@@ -202,6 +255,8 @@ function toSummary(value: PersistedTurnChangeSetV1): TurnChangeSetSummary {providerTurnId: value.providerTurnId,cwd: value.cwd,state: value.state,+ workspaceState,+ isReversible: isReversiblePatch(value),incompleteReasons: value.incompleteReasons,createdAt: value.createdAt,completedAt: value.completedAt,@@ -237,6 +292,9 @@ function isSummary(value: unknown, sessionId: string): value is TurnChangeSetSum&& (summary.providerTurnId === null || typeof summary.providerTurnId === 'string')&& typeof summary.cwd === 'string'&& STATES.has(summary.state as TurnChangeSetState)+ && (summary.workspaceState === undefined+ || WORKSPACE_STATES.has(summary.workspaceState as TurnChangeWorkspaceState))+ && (summary.isReversible === undefined || typeof summary.isReversible === 'boolean')&& Array.isArray(summary.incompleteReasons)&& summary.incompleteReasons.every((reason) => INCOMPLETE_REASONS.has(reason))&& isFiniteNonNegative(summary.createdAt)@@ -268,6 +326,7 @@ function parsePersisted(raw: string): PersistedTurnChangeSetV1 | null {|| !isFiniteNonNegative(value.createdAt)|| !isFiniteNonNegative(value.completedAt)|| typeof value.unifiedDiff !== 'string'+ || (value.reversibleFormat !== undefined && value.reversibleFormat !== 'exact-text-v1')|| !Array.isArray(value.files)|| !value.files.every(isFileSummary)) return null;@@ -277,15 +336,93 @@ function parsePersisted(raw: string): PersistedTurnChangeSetV1 | null {}}-async function readIndexState(sessionId: string): Promise<TurnChangeIndexV1> {+async function readActionState(sessionId: string): Promise<TurnChangeActionStateV1> {+ try {+ const raw = await fs.readFile(path.join(sessionDir(sessionId), ACTION_STATE_FILE), 'utf8');+ const parsed = JSON.parse(raw) as Partial<TurnChangeActionStateV1>;+ if (parsed.version !== 1 || !parsed.states || typeof parsed.states !== 'object') {+ return { version: 1, states: {} };+ }+ const states: TurnChangeActionStateV1['states'] = {};+ for (const [id, entry] of Object.entries(parsed.states).slice(-MAX_LIST_ROWS)) {+ if (+ !id+ || id.length > 256+ || !entry+ || typeof entry !== 'object'+ || !WORKSPACE_STATES.has(entry.workspaceState)+ || !isFiniteNonNegative(entry.updatedAt)+ ) continue;+ states[id] = {+ workspaceState: entry.workspaceState,+ updatedAt: entry.updatedAt,+ };+ }+ return { version: 1, states };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn('turn change-set action state read failed', { sessionId, error });+ }+ return { version: 1, states: {} };+ }+}++function writeActionStateFile(sessionId: string, state: TurnChangeActionStateV1): void {+ atomicWriteFileSync(+ path.join(sessionDir(sessionId), ACTION_STATE_FILE),+ `${JSON.stringify(state)}\n`,+ );+}++async function persistWorkspaceState(+ sessionId: string,+ id: string,+ workspaceState: TurnChangeWorkspaceState,+): Promise<void> {+ await enqueueStorageWrite(async () => {+ const current = await readActionState(sessionId);+ current.states[id] = { workspaceState, updatedAt: Date.now() };+ writeActionStateFile(sessionId, current);+ });+}++async function pruneActionState(+ sessionId: string,+ retainedIds: ReadonlySet<string>,+): Promise<void> {+ const current = await readActionState(sessionId);+ const states = Object.fromEntries(+ Object.entries(current.states).filter(([id]) => retainedIds.has(id)),+ );+ if (Object.keys(states).length === Object.keys(current.states).length) return;+ if (Object.keys(states).length === 0) {+ await fs.rm(path.join(sessionDir(sessionId), ACTION_STATE_FILE), { force: true });+ return;+ }+ writeActionStateFile(sessionId, { version: 1, states });+}++async function readIndexState(sessionId: string): Promise<TurnChangeIndexV2> {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 parsed = JSON.parse(raw) as Partial<Omit<TurnChangeIndexV2, 'version'>> & {+ version?: unknown;+ };+ if ((parsed.version !== 1 && parsed.version !== 2) || !Array.isArray(parsed.entries)) {+ return { version: 2, entries: [], detailBytes: {} };}+ const reversibleIndex = parsed.version === 2;const entries = parsed.entries.filter((entry) => isSummary(entry, sessionId))+ .map((entry) => ({+ ...entry,+ workspaceState: WORKSPACE_STATES.has(entry.workspaceState)+ ? entry.workspaceState+ : 'applied' as const,+ isReversible: reversibleIndex && typeof entry.isReversible === 'boolean'+ ? entry.isReversible+ : false,+ })).slice(-MAX_LIST_ROWS);const rawDetailBytes = parsed.detailBytes && typeof parsed.detailBytes === 'object'? parsed.detailBytes@@ -300,20 +437,27 @@ async function readIndexState(sessionId: string): Promise<TurnChangeIndexV1> {const stat = await fs.stat(detailPath(sessionId, entry.id)).catch(() => null);if (stat?.isFile()) detailBytes[entry.id] = stat.size;}- return { version: 1, entries, detailBytes };+ return { version: 2, 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: {} };+ return { version: 2, entries: [], detailBytes: {} };}}async function readIndex(sessionId: string): Promise<TurnChangeSetSummary[]> {- return (await readIndexState(sessionId)).entries;+ const [index, actionState] = await Promise.all([+ readIndexState(sessionId),+ readActionState(sessionId),+ ]);+ return index.entries.map((entry) => ({+ ...entry,+ workspaceState: actionState.states[entry.id]?.workspaceState ?? 'applied',+ }));}-function enqueueSessionWrite(sessionId: string, operation: () => Promise<void>): Promise<void> {+function enqueueSessionWrite<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {const previous = sessionWriteChains.get(sessionId) ?? Promise.resolve();const current = previous.catch(() => undefined).then(operation).finally(() => {if (sessionWriteChains.get(sessionId) === current) sessionWriteChains.delete(sessionId);@@ -322,6 +466,85 @@ function enqueueSessionWrite(sessionId: string, operation: () => Promise<void>):return current;}+function workspaceKey(cwd: string): string {+ const lexical = path.resolve(cwd);+ let resolved = lexical;+ try {+ resolved = realpathSync.native(lexical);+ } catch {+ // A removed workspace cannot be mutated; retain the stable lexical key so+ // concurrent failure paths still serialize with one another.+ }+ return process.platform === 'win32' ? resolved.toLocaleLowerCase('en-US') : resolved;+}++function registerPendingWorkspace(sessionId: string, cwd: string): void {+ if (pendingWorkspaceBySession.has(sessionId)) return;+ const key = workspaceKey(cwd);+ pendingWorkspaceBySession.set(sessionId, key);+ pendingWorkspaceCounts.set(key, (pendingWorkspaceCounts.get(key) ?? 0) + 1);+}++function unregisterPendingWorkspace(sessionId: string): void {+ const key = pendingWorkspaceBySession.get(sessionId);+ if (!key) return;+ pendingWorkspaceBySession.delete(sessionId);+ const next = (pendingWorkspaceCounts.get(key) ?? 1) - 1;+ if (next <= 0) pendingWorkspaceCounts.delete(key);+ else pendingWorkspaceCounts.set(key, next);+}++async function waitForWorkspaceActions(cwd: string): Promise<void> {+ const key = workspaceKey(cwd);+ for (;;) {+ const current = workspaceActionChains.get(key);+ if (!current) return;+ await current.catch(() => undefined);+ if (workspaceActionChains.get(key) === current) return;+ }+}++async function enqueueWorkspaceAction<T>(+ cwd: string,+ operation: () => Promise<T>,+): Promise<T> {+ const key = workspaceKey(cwd);+ if ((pendingWorkspaceCounts.get(key) ?? 0) > 0) {+ throw new TurnChangeSetActionError('busy', 'The workspace is still producing file changes.');+ }+ const previous = workspaceActionChains.get(key) ?? Promise.resolve();+ const current = previous.catch(() => undefined).then(operation).finally(() => {+ if (workspaceActionChains.get(key) === current) workspaceActionChains.delete(key);+ });+ workspaceActionChains.set(key, current);+ return current;+}++function retainSessionDir(sessionId: string): () => void {+ retainedSessionDirs.set(sessionId, (retainedSessionDirs.get(sessionId) ?? 0) + 1);+ let released = false;+ return () => {+ if (released) return;+ released = true;+ const next = (retainedSessionDirs.get(sessionId) ?? 1) - 1;+ if (next <= 0) retainedSessionDirs.delete(sessionId);+ else retainedSessionDirs.set(sessionId, next);+ };+}++function trackAction<T>(promise: Promise<T>): Promise<T> {+ activeActionPromises.add(promise);+ void promise.finally(() => activeActionPromises.delete(promise)).catch(() => undefined);+ return promise;+}++/** Drains destructive workspace actions before an account owner is torn down. */+export async function waitForTurnChangeSetActions(): Promise<void> {+ while (activeActionPromises.size > 0) {+ await Promise.allSettled([...activeActionPromises]);+ }+}+function enqueueStorageWrite(operation: () => Promise<void>): Promise<void> {const current = storageWriteChain.catch(() => undefined).then(operation);storageWriteChain = current.catch(() => undefined);@@ -333,7 +556,10 @@ async function pruneStoredSessionDirs(currentSessionId: string): Promise<void> {const dirents = await fs.readdir(root, { withFileTypes: true }).catch(() => []);const candidates = await Promise.all(dirents- .filter((entry) => entry.isDirectory() && entry.name !== currentSessionId)+ .filter((entry) =>+ entry.isDirectory()+ && entry.name !== currentSessionId+ && !retainedSessionDirs.has(entry.name)).map(async (entry) => {const dir = path.join(root, entry.name);const stat = await fs.lstat(dir).catch(() => null);@@ -346,7 +572,12 @@ async function pruneStoredSessionDirs(currentSessionId: string): Promise<void> {.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 })));+ await Promise.all(removable.map((entry) => {+ const sessionId = path.basename(entry.dir);+ return retainedSessionDirs.has(sessionId)+ ? Promise.resolve()+ : fs.rm(entry.dir, { recursive: true, force: true });+ }));}async function persistValue(value: PersistedTurnChangeSetV1): Promise<void> {@@ -389,17 +620,20 @@ async function persistValue(value: PersistedTurnChangeSetV1): Promise<void> {);atomicWriteFileSync(path.join(dir, INDEX_FILE),- `${JSON.stringify({ version: 1, entries: next, detailBytes: nextDetailBytes } satisfies TurnChangeIndexV1)}\n`,+ `${JSON.stringify({ version: 2, entries: next, detailBytes: nextDetailBytes } satisfies TurnChangeIndexV2)}\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();+ if (name === INDEX_FILE || name === ACTION_STATE_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 pruneActionState(value.sessionId, retainedIds);await pruneStoredSessionDirs(value.sessionId);} catch (error) {if (!indexPublished) await fs.rm(currentDetailPath, { force: true }).catch(() => undefined);@@ -408,8 +642,10 @@ async function persistValue(value: PersistedTurnChangeSetV1): Promise<void> {});}-function broadcastUpdated(payload: TurnChangeSetUpdatedPayload): void {- const ownerScope = broadcastTap.captureDataOwnerBroadcastScope();+function broadcastUpdated(+ payload: TurnChangeSetUpdatedPayload,+ ownerScope = broadcastTap.captureDataOwnerBroadcastScope(),+): void {if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(ownerScope)) return;for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;@@ -443,12 +679,13 @@ function ensurePending(incompleteReasons: new Set(),};pendingBySession.set(sessionId, pending);+ registerPendingWorkspace(sessionId, cwd);return pending;}/** Establishes the Cindy product-turn identity before vendor dispatch. */-export function beginTurnChangeSet(input: BeginTurnChangeSetInput): void {- const existing = pendingBySession.get(input.sessionId);+export async function beginTurnChangeSet(input: BeginTurnChangeSetInput): Promise<void> {+ let existing = pendingBySession.get(input.sessionId);if (existing) {if (existing.anchorClientId === input.anchorClientId) return;log.warn('replacing unfinished turn change-set at dispatch boundary', {@@ -457,6 +694,14 @@ export function beginTurnChangeSet(input: BeginTurnChangeSetInput): void {anchorClientId: input.anchorClientId,});pendingBySession.delete(input.sessionId);+ unregisterPendingWorkspace(input.sessionId);+ }+ await waitForWorkspaceActions(input.cwd);+ existing = pendingBySession.get(input.sessionId);+ if (existing?.anchorClientId === input.anchorClientId) return;+ if (existing) {+ pendingBySession.delete(input.sessionId);+ unregisterPendingWorkspace(input.sessionId);}const pending = ensurePending(input.sessionId, input.provider, input.cwd);pending.anchorClientId = input.anchorClientId;@@ -512,7 +757,7 @@ async function isRealTargetInsideWorkspace(cwd: string, absolutePath: string): Pasync function readTextFileForCapture(absolutePath: string,remainingBytes = MAX_CAPTURE_FILE_BYTES,-): Promise<{ exists: boolean; text: string } | TurnChangeIncompleteReason> {+): Promise<{ exists: boolean; text: string; mode: number | null } | TurnChangeIncompleteReason> {try {const stat = await fs.stat(absolutePath);if (!stat.isFile()) return 'read-failed';@@ -520,12 +765,18 @@ async function readTextFileForCapture(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) };+ return {+ exists: true,+ text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(data),+ mode: stat.mode,+ };} catch {return 'binary-file';}} catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { exists: false, text: '' };+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { exists: false, text: '', mode: null };+ }return 'read-failed';}}@@ -572,6 +823,7 @@ export async function captureKnownFileBefore(input: KnownFileWriteCapture): Prom...target,beforeExists: before.exists,beforeText: before.text,+ beforeMode: before.mode,});pending.capturedBytes += captureBytes;})().finally(() => pending.captureTasks.delete(target.absolutePath));@@ -610,14 +862,25 @@ export function noteTurnDiffEvent(sessionId: string, event: AgentEvent): void {pending.nativeFiles = [];}-function createCapturedFilePatch(file: CapturedFile, afterExists: boolean, afterText: string): string {+function gitFileMode(mode: number | null): '100644' | '100755' {+ return mode !== null && (mode & 0o111) !== 0 ? '100755' : '100644';+}++function createCapturedFilePatch(+ file: CapturedFile,+ afterExists: boolean,+ afterText: string,+ afterMode: number | null,+): 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'+ ? `new file mode ${gitFileMode(afterMode)}\n`: file.beforeExists && !afterExists- ? 'deleted file mode 100644\n'- : '';+ ? `deleted file mode ${gitFileMode(file.beforeMode)}\n`+ : file.beforeExists && afterExists && gitFileMode(file.beforeMode) !== gitFileMode(afterMode)+ ? `old mode ${gitFileMode(file.beforeMode)}\nnew mode ${gitFileMode(afterMode)}\n`+ : '';return [`diff --git a/${file.relativePath} b/${file.relativePath}\n`,mode,@@ -645,7 +908,7 @@ async function buildCapturedPatch(pending: PendingTurnChangeSet): Promise<string}afterImageBytes += byteLength(after.text);if (file.beforeExists === after.exists && file.beforeText === after.text) continue;- const nextPatch = createCapturedFilePatch(file, after.exists, after.text);+ const nextPatch = createCapturedFilePatch(file, after.exists, after.text, after.mode);if (byteLength(unifiedDiff) + byteLength(nextPatch) > TURN_CHANGE_SET_MAX_DIFF_BYTES) {addIncompleteReason(pending, 'diff-too-large');break;@@ -681,6 +944,7 @@ async function persistPending(const incompleteReasons = [...pending.incompleteReasons];let value: PersistedTurnChangeSetV1 = {version: 1,+ reversibleFormat: 'exact-text-v1',id: pending.id,sessionId,anchorClientId,@@ -718,7 +982,8 @@ export function finalizeTurnChangeSet(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 }));+ .catch((error) => log.warn('turn change-set persist failed', { sessionId, error }))+ .finally(() => unregisterPendingWorkspace(sessionId));}/** Prevents the next product turn from mutating files before the prior after-image is sealed. */@@ -726,8 +991,251 @@ export async function waitForTurnChangeSetSeal(sessionId: string): Promise<void>await (sessionWriteChains.get(sessionId) ?? Promise.resolve());}+export type TurnChangeSetActionErrorKind =+ | 'not-found'+ | 'busy'+ | 'wrong-state'+ | 'unsupported'+ | 'conflict'+ | 'apply-failed';++export class TurnChangeSetActionError extends Error {+ constructor(readonly kind: TurnChangeSetActionErrorKind, message: string, cause?: unknown) {+ super(message);+ this.name = 'TurnChangeSetActionError';+ if (cause !== undefined) this.cause = cause;+ }+}++async function loadLocalSessionWorkspace(sessionId: string): Promise<string> {+ const rows = await getDbClient().query<{ workingDir: string; remoteHostId: string | null }>(+ `SELECT working_dir AS workingDir, remote_host_id AS remoteHostId+ FROM sessions WHERE id = ? LIMIT 1`,+ [sessionId],+ );+ const session = rows[0];+ if (!session) {+ throw new TurnChangeSetActionError('not-found', 'The owning task was not found.');+ }+ if (session.remoteHostId) {+ throw new TurnChangeSetActionError('unsupported', 'Remote workspace restore is not available.');+ }+ return session.workingDir;+}++function assertTurnChangeSetWorkspace(value: PersistedTurnChangeSetV1, workingDir: string): void {+ const expected = path.resolve(workingDir);+ const recorded = path.resolve(value.cwd);+ const matches = process.platform === 'win32'+ ? expected.toLocaleLowerCase('en-US') === recorded.toLocaleLowerCase('en-US')+ : expected === recorded;+ if (!matches) {+ throw new TurnChangeSetActionError(+ 'unsupported',+ 'The task workspace no longer matches the recorded patch.',+ );+ }+}++function assertOwnerScopeCurrent(scope: broadcastTap.DataOwnerBroadcastScope): void {+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(scope)) {+ throw new TurnChangeSetActionError('busy', 'The active account is changing.');+ }+}++async function validatePatchTargets(value: PersistedTurnChangeSetV1): Promise<void> {+ const diffs = parseDiffs(value.id, value.unifiedDiff);+ if (diffs.length !== value.files.length) {+ throw new TurnChangeSetActionError('unsupported', 'The recorded patch is incomplete.');+ }+ const seen = new Set<string>();+ for (const diff of diffs) {+ const currentDiffPaths = new Set<string>();+ for (const relativePath of [diff.oldPath, diff.path]) {+ if (!relativePath) continue;+ const target = safeRelativeTarget(value.cwd, relativePath);+ if (!target || !await isRealTargetInsideWorkspace(value.cwd, target.absolutePath)) {+ throw new TurnChangeSetActionError('unsupported', 'The recorded patch contains an unsafe path.');+ }+ const normalized = process.platform === 'win32'+ ? target.absolutePath.toLocaleLowerCase('en-US')+ : target.absolutePath;+ if (currentDiffPaths.has(normalized)) continue;+ if (seen.has(normalized)) {+ throw new TurnChangeSetActionError('unsupported', 'The recorded patch contains overlapping paths.');+ }+ currentDiffPaths.add(normalized);+ seen.add(normalized);+ }+ }+}++function patchApplyArgs(revert: boolean, check: boolean): string[] {+ // The patch already records its line endings. Global autocrlf must not rewrite+ // a non-Git workspace (or make check/apply disagree with the captured bytes).+ const args = ['-c', 'core.autocrlf=false', '-c', 'core.safecrlf=false', 'apply'];+ if (revert) args.push('-R');+ if (check) args.push('--check');+ args.push('--binary', '--whitespace=nowarn', '-');+ return args;+}++function usesPortableTextPatch(value: PersistedTurnChangeSetV1): boolean {+ const diffs = parseDiffs(value.id, value.unifiedDiff);+ return diffs.length > 0+ && diffs.every((diff) => ['added', 'modified', 'deleted'].includes(diff.status));+}++function directionalPatch(+ value: PersistedTurnChangeSetV1,+ revert: boolean,+): { patch: string; useReverseFlag: boolean } {+ if (!usesPortableTextPatch(value)) {+ // Rename metadata is not represented by `diff`'s StructuredPatch type.+ // Preserve the vendor patch verbatim and let Git reverse it as one unit.+ return { patch: value.unifiedDiff, useReverseFlag: revert };+ }+ const patches = parsePatch(value.unifiedDiff);+ if (patches.length !== value.files.length || patches.some((patch) => patch.hunks.length === 0)) {+ throw new TurnChangeSetActionError('unsupported', 'The recorded text patch is malformed.');+ }+ return {+ patch: formatPatch(revert ? reversePatch(patches) : patches),+ useReverseFlag: false,+ };+}++async function canApplyRecordedPatch(+ value: PersistedTurnChangeSetV1,+ revert: boolean,+): Promise<boolean> {+ const directed = directionalPatch(value, revert);+ try {+ await runGit(patchApplyArgs(directed.useReverseFlag, true), {+ cwd: value.cwd,+ stdin: directed.patch,+ timeoutMs: 30_000,+ });+ return true;+ } catch (error) {+ if (error instanceof GitRunError && error.exitCode !== null) return false;+ throw new TurnChangeSetActionError(+ 'unsupported',+ 'Git is required to apply the recorded patch.',+ error,+ );+ }+}++async function applyRecordedPatch(+ value: PersistedTurnChangeSetV1,+ revert: boolean,+): Promise<void> {+ const directed = directionalPatch(value, revert);+ try {+ await runGit(patchApplyArgs(directed.useReverseFlag, false), {+ cwd: value.cwd,+ stdin: directed.patch,+ timeoutMs: 30_000,+ });+ } catch (error) {+ if (error instanceof GitRunError && error.exitCode !== null) {+ throw new TurnChangeSetActionError(+ 'conflict',+ 'The workspace changed before the patch could be applied.',+ error,+ );+ }+ throw new TurnChangeSetActionError(+ 'apply-failed',+ 'The recorded patch could not be applied.',+ error,+ );+ }+}++/** Applies the immutable turn patch without mutating chat history or Git's index. */+export function applyTurnChangeSetAction(+ sessionId: string,+ id: string,+ action: TurnChangeAction,+ ownerScope = broadcastTap.captureDataOwnerBroadcastScope(),+): Promise<TurnChangeActionResult> {+ const releaseSessionDir = retainSessionDir(sessionId);+ const operation = (async () => {+ try {+ // If pruning was already in flight when the lease was acquired, let that+ // storage operation settle before reading the immutable detail.+ await storageWriteChain.catch(() => undefined);+ return await enqueueSessionWrite(sessionId, async () => {+ assertOwnerScopeCurrent(ownerScope);+ const workingDir = await loadLocalSessionWorkspace(sessionId);+ return enqueueWorkspaceAction(workingDir, async () => {+ assertOwnerScopeCurrent(ownerScope);+ if (pendingBySession.has(sessionId)) {+ throw new TurnChangeSetActionError('busy', 'The task is still producing file changes.');+ }+ const summaries = await listTurnChangeSets(sessionId);+ const currentSummary = summaries.find((summary) => summary.id === id);+ if (!currentSummary) {+ throw new TurnChangeSetActionError('not-found', 'The recorded turn change set was not found.');+ }+ const expectedState: TurnChangeWorkspaceState = action === 'undo' ? 'applied' : 'undone';+ const nextState: TurnChangeWorkspaceState = action === 'undo' ? 'undone' : 'applied';+ if (currentSummary.workspaceState !== expectedState) {+ throw new TurnChangeSetActionError('wrong-state', 'The recorded patch state has changed.');+ }++ const value = parsePersisted(await fs.readFile(detailPath(sessionId, id), 'utf8'));+ if (!value || value.id !== id || value.sessionId !== sessionId) {+ throw new TurnChangeSetActionError('not-found', 'The recorded turn change set was not found.');+ }+ if (!isReversiblePatch(value)) {+ throw new TurnChangeSetActionError(+ 'unsupported',+ 'This turn was not captured as a reversible text patch.',+ );+ }+ assertTurnChangeSetWorkspace(value, workingDir);+ await validatePatchTargets(value);++ const revert = action === 'undo';+ const canApply = await canApplyRecordedPatch(value, revert);+ assertOwnerScopeCurrent(ownerScope);+ if (!canApply) {+ // A workspace mutation may have succeeded immediately before a state-file write failed.+ // Heal that narrow crash window when the opposite direction proves the target state.+ const targetAlreadyApplied = await canApplyRecordedPatch(value, !revert);+ assertOwnerScopeCurrent(ownerScope);+ if (!targetAlreadyApplied) {+ throw new TurnChangeSetActionError(+ 'conflict',+ 'The workspace no longer matches the recorded patch.',+ );+ }+ await persistWorkspaceState(sessionId, id, nextState);+ const summary = toSummary(value, nextState);+ broadcastUpdated({ sessionId, summary }, ownerScope);+ return { action, changed: false, summary };+ }++ await applyRecordedPatch(value, revert);+ await persistWorkspaceState(sessionId, id, nextState);+ const summary = toSummary(value, nextState);+ broadcastUpdated({ sessionId, summary }, ownerScope);+ return { action, changed: true, summary };+ });+ });+ } finally {+ releaseSessionDir();+ }+ })();+ return trackAction(operation);+}+export function clearPendingTurnChangeSets(sessionId: string): void {pendingBySession.delete(sessionId);+ unregisterPendingWorkspace(sessionId);}async function validAnchorIds(sessionId: string, summaries: readonly TurnChangeSetSummary[]): Promise<Set<string>> {@@ -769,8 +1277,10 @@ export async function getTurnChangeSets(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;+ const detailSummary = toSummary(value, summary.workspaceState);+ const detailIdentity = { ...detailSummary, workspaceState: 'applied' as const, isReversible: false };+ const summaryIdentity = { ...summary, workspaceState: 'applied' as const, isReversible: false };+ if (JSON.stringify(detailIdentity) !== JSON.stringify(summaryIdentity)) continue;details.push({ ...detailSummary, diffs: parseDiffs(value.id, value.unifiedDiff) });} catch (error) {log.warn('turn change-set detail read failed', { sessionId, id, error });@@ -781,6 +1291,7 @@ export async function getTurnChangeSets(export async function removeTurnChangeSetsForSession(sessionId: string): Promise<void> {pendingBySession.delete(sessionId);+ unregisterPendingWorkspace(sessionId);await enqueueSessionWrite(sessionId, async () => {await fs.rm(sessionDir(sessionId), { recursive: true, force: true });});diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 3633648f8d..f50621ff47 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4712,6 +4712,12 @@ contextBridge.exposeInMainWorld('electronAPI', {ids: string[],): Promise<import('../shared/turnChangeSet').TurnChangeSetDetail[]> =>ipcRenderer.invoke('maker:turn-change-sets:get', sessionId, ids),+ applyTurnChangeSet: (+ sessionId: string,+ id: string,+ action: import('../shared/turnChangeSet').TurnChangeAction,+ ): Promise<import('../shared/turnChangeSet').TurnChangeActionResult> =>+ ipcRenderer.invoke('maker:turn-change-set:apply', sessionId, id, action),// workflow 逐 agent 进度树(只读)。读不到 / 解析失败返回 null,由 renderer 回退到// workflow 级卡片。数据源是 Claude Code 内部记录文件(见 main workflow-progress/reader)。diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.tsindex 704bfc830e..d9480797f3 100644--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts@@ -286,6 +286,8 @@ describe('buildRenderItems — key stability', () => {providerTurnId: 'turn-1',cwd: 'C:/work',state: 'complete',+ workspaceState: 'applied',+ isReversible: true,incompleteReasons: [],createdAt: 1,completedAt: 2,diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsxindex 9f0497fcf1..1deed1ee76 100644--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx@@ -1,11 +1,22 @@-import { useRef, useState } from 'react';-import { AlertTriangle, ChevronDown, ChevronUp, FileDiff, FileText } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import {+ AlertTriangle,+ ChevronDown,+ ChevronUp,+ FileDiff,+ FileText,+ LoaderCircle,+ Redo2,+ Undo2,+} 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 { toast } from '@/lib/toast';import { basename, cn } from '@/lib/utils';+import { extractIpcError } from '@/utils/ipcError';import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';import type { TurnChangeFileSummary, TurnChangeSetSummary } from '../../../shared/turnChangeSet';import { useChatSessionFile } from './ChatSessionFileContext';@@ -88,10 +99,28 @@ export function TurnChangesCard({}) {const { t } = useTranslation();const [expanded, setExpanded] = useState(false);+ const [applying, setApplying] = useState(false);+ const [workspaceStateOverride, setWorkspaceStateOverride] = useState<+ TurnChangeSetSummary['workspaceState'] | null+ >(null);+ const latestWorkspaceStateRef = useRef(changeSet.workspaceState);+ latestWorkspaceStateRef.current = changeSet.workspaceState;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 workspaceState = workspaceStateOverride ?? changeSet.workspaceState;++ useEffect(() => {+ setWorkspaceStateOverride((current) => (+ current === changeSet.workspaceState ? null : current+ ));+ }, [changeSet.workspaceState]);++ useEffect(() => {+ setWorkspaceStateOverride(null);+ setApplying(false);+ }, [changeSet.id]);const openReview = (selectedDiffId?: string): void => {void openTurnReview(sessionId, [changeSet.id], {@@ -99,6 +128,41 @@ export function TurnChangesCard({});};+ const applyTurnChange = async (): Promise<void> => {+ if (applying || !changeSet.isReversible) return;+ const action = workspaceState === 'undone' ? 'reapply' : 'undo';+ setApplying(true);+ try {+ const result = await window.electronAPI.maker.applyTurnChangeSet(+ sessionId,+ changeSet.id,+ action,+ );+ setWorkspaceStateOverride(+ result.summary.workspaceState === latestWorkspaceStateRef.current+ ? null+ : result.summary.workspaceState,+ );+ toast.success(t(+ action === 'undo'+ ? 'chat.turnChanges.undoSuccess'+ : 'chat.turnChanges.reapplySuccess',+ ));+ } catch (error) {+ const code = extractIpcError(error)?.code;+ const key = code === 'SESSION_RUNNING'+ ? 'chat.turnChanges.actionRunning'+ : code === 'STALE_DIFF' || code === 'PRECONDITION_FAILED'+ ? 'chat.turnChanges.actionConflict'+ : code === 'UNSUPPORTED_CAPABILITY'+ ? 'chat.turnChanges.actionUnavailable'+ : 'chat.turnChanges.actionFailed';+ toast.error(t(key));+ } finally {+ setApplying(false);+ }+ };+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">@@ -122,13 +186,43 @@ export function TurnChangesCard({</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 className="flex shrink-0 items-center gap-2">+ {changeSet.isReversible && (+ <button+ type="button"+ disabled={applying}+ aria-label={t(+ workspaceState === 'undone'+ ? 'chat.turnChanges.reapplyAria'+ : 'chat.turnChanges.undoAria',+ )}+ onClick={() => void applyTurnChange()}+ className={cn(+ 'flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium',+ 'text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ {applying+ ? <LoaderCircle size={15} className="animate-spin" />+ : workspaceState === 'undone'+ ? <Redo2 size={15} />+ : <Undo2 size={15} />}+ {t(+ workspaceState === 'undone'+ ? 'chat.turnChanges.reapply'+ : 'chat.turnChanges.undo',+ )}+ </button>+ )}+ <button+ type="button"+ onClick={() => openReview()}+ className="h-8 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></div>{files.length > 0 && (diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsxindex 332bf24451..25de297267 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { act, fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -8,6 +8,9 @@ const mocks = vi.hoisted(() => ({onContextMenu: vi.fn(),openTurnReview: vi.fn(async () => undefined),shouldOpenTextLightboxForOrigin: vi.fn(async () => true),+ applyTurnChangeSet: vi.fn(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),useFileChipContextMenu: vi.fn(),}));@@ -26,6 +29,10 @@ vi.mock('@/lib/filePreview', () => ({shouldOpenTextLightboxForOrigin: mocks.shouldOpenTextLightboxForOrigin,}));+vi.mock('@/lib/toast', () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}));+vi.mock('../TextLightbox', () => ({TextLightbox: ({ filePath, fileName }: { filePath: string; fileName: string }) => (<div data-testid="text-lightbox">{`${fileName}:${filePath}`}</div>@@ -47,6 +54,8 @@ const CHANGE_SET: TurnChangeSetSummary = {providerTurnId: 'turn-1',cwd: 'C:\\repo',state: 'complete',+ workspaceState: 'applied',+ isReversible: true,incompleteReasons: [],createdAt: 1,completedAt: 2,@@ -75,6 +84,10 @@ const HTML_CHANGE_SET: TurnChangeSetSummary = {describe('TurnChangesCard file actions', () => {beforeEach(() => {vi.clearAllMocks();+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { maker: { applyTurnChangeSet: mocks.applyTurnChangeSet } },+ });mocks.useFileChipContextMenu.mockReturnValue({onContextMenu: mocks.onContextMenu,openAt: vi.fn(),@@ -145,4 +158,73 @@ describe('TurnChangesCard file actions', () => {{ selectedDiffId: 'file-1' },);});++ it('switches from undo to reapply only after Main applies the patch', async () => {+ mocks.applyTurnChangeSet.mockResolvedValue({+ action: 'undo',+ changed: true,+ summary: { ...CHANGE_SET, workspaceState: 'undone' },+ });+ render(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);++ fireEvent.click(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' }));++ await waitFor(() => expect(mocks.applyTurnChangeSet).toHaveBeenCalledWith(+ 'session-1',+ 'change-1',+ 'undo',+ ));+ expect(await screen.findByRole('button', { name: 'chat.turnChanges.reapplyAria' })).toBeTruthy();+ expect(mocks.toastSuccess).toHaveBeenCalledWith('chat.turnChanges.undoSuccess');+ });++ it('does not offer undo for a partial or otherwise non-reversible patch', () => {+ render(+ <TurnChangesCard+ sessionId="session-1"+ changeSet={{ ...CHANGE_SET, state: 'partial', isReversible: false }}+ />,+ );++ expect(screen.queryByRole('button', { name: 'chat.turnChanges.undoAria' })).toBeNull();+ expect(screen.getByRole('button', { name: 'chat.turnChanges.review' })).toBeTruthy();+ });++ it('does not retain a stale local state when the Main push arrives before the IPC result', async () => {+ let resolveApply!: (value: unknown) => void;+ mocks.applyTurnChangeSet.mockReturnValue(new Promise((resolve) => {+ resolveApply = resolve;+ }));+ const view = render(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);+ fireEvent.click(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' }));++ view.rerender(+ <TurnChangesCard+ sessionId="session-1"+ changeSet={{ ...CHANGE_SET, workspaceState: 'undone' }}+ />,+ );+ await act(async () => {+ resolveApply({+ action: 'undo',+ changed: true,+ summary: { ...CHANGE_SET, workspaceState: 'undone' },+ });+ });+ view.rerender(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);++ expect(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' })).toBeTruthy();+ });++ it('keeps the current action when Main rejects a stale workspace', async () => {+ mocks.applyTurnChangeSet.mockRejectedValue(new Error('[STALE_DIFF] stale'));+ render(<TurnChangesCard sessionId="session-1" changeSet={CHANGE_SET} />);++ fireEvent.click(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' }));++ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith(+ 'chat.turnChanges.actionConflict',+ ));+ expect(screen.getByRole('button', { name: 'chat.turnChanges.undoAria' })).toBeTruthy();+ });});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex eeaed5eed6..088e502fc2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6200,6 +6200,16 @@"title": "Changed {{count}} files","partialTitle": "File changes were not fully captured","review": "Review",+ "undo": "Undo",+ "undoAria": "Undo changes from this turn",+ "reapply": "Reapply",+ "reapplyAria": "Reapply changes from this turn",+ "undoSuccess": "Changes from this turn were undone",+ "reapplySuccess": "Changes from this turn were reapplied",+ "actionRunning": "Wait for the current response to finish before changing the workspace",+ "actionConflict": "The workspace has changed, so this patch cannot be applied safely. Review the current changes first",+ "actionUnavailable": "This turn includes file changes that cannot be safely undone",+ "actionFailed": "The changes could not be applied. Try again","partial": "Only the changes captured exactly are shown","showMore": "Show {{count}} more files","reviewRemaining": "Review {{count}} more files",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7771947db2..adaa2c0fa0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6198,6 +6198,16 @@"title": "{{count}} ファイルを変更","partialTitle": "このターンのファイル変更を完全には取得できませんでした","review": "レビュー",+ "undo": "元に戻す",+ "undoAria": "このターンの変更を元に戻す",+ "reapply": "再適用",+ "reapplyAria": "このターンの変更を再適用する",+ "undoSuccess": "このターンの変更を元に戻しました",+ "reapplySuccess": "このターンの変更を再適用しました",+ "actionRunning": "現在の応答が完了してからワークスペースを変更してください",+ "actionConflict": "ワークスペースが変更されたため、このパッチを安全に適用できません。現在の変更を先にレビューしてください",+ "actionUnavailable": "このターンには安全に元に戻せないファイル変更が含まれています",+ "actionFailed": "変更を適用できませんでした。もう一度お試しください","partial": "正確に取得できた変更のみ表示しています","showMore": "さらに {{count}} ファイルを表示","reviewRemaining": "残り {{count}} ファイルをレビューで表示",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b188e47189..e28992a522 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6198,6 +6198,16 @@"title": "파일 {{count}}개 변경","partialTitle": "이번 턴의 파일 변경 사항이 완전히 캡처되지 않았습니다","review": "검토",+ "undo": "실행 취소",+ "undoAria": "이번 턴의 변경 사항 실행 취소",+ "reapply": "다시 적용",+ "reapplyAria": "이번 턴의 변경 사항 다시 적용",+ "undoSuccess": "이번 턴의 변경 사항을 실행 취소했습니다",+ "reapplySuccess": "이번 턴의 변경 사항을 다시 적용했습니다",+ "actionRunning": "현재 응답이 끝난 후 작업 공간을 변경하세요",+ "actionConflict": "작업 공간이 변경되어 이 패치를 안전하게 적용할 수 없습니다. 현재 변경 사항을 먼저 검토하세요",+ "actionUnavailable": "이번 턴에는 안전하게 실행 취소할 수 없는 파일 변경 사항이 포함되어 있습니다",+ "actionFailed": "변경 사항을 적용하지 못했습니다. 다시 시도하세요","partial": "정확히 캡처된 변경 사항만 표시됩니다","showMore": "파일 {{count}}개 더 보기","reviewRemaining": "나머지 파일 {{count}}개를 검토에서 보기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex df4dc4178d..c750bd48df 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6198,6 +6198,16 @@"title": "已更改 {{count}} 个文件","partialTitle": "本轮文件变更未完整记录","review": "审查",+ "undo": "撤销",+ "undoAria": "撤销本轮改动",+ "reapply": "重新应用",+ "reapplyAria": "重新应用本轮改动",+ "undoSuccess": "已撤销本轮改动",+ "reapplySuccess": "已重新应用本轮改动",+ "actionRunning": "请等待当前回复结束后再更改工作区",+ "actionConflict": "工作区内容已变化,无法安全应用本轮补丁;请先审查当前改动",+ "actionUnavailable": "本轮包含无法安全撤销的文件变更",+ "actionFailed": "未能应用本轮改动,请重试","partial": "仅记录了可精确捕获的部分变更","showMore": "再显示 {{count}} 个文件","reviewRemaining": "在审查中查看其余 {{count}} 个文件",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8a55bb4b84..95d264510f 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5300,6 +5300,11 @@ interface ElectronAPI {sessionId: string,ids: string[],) => Promise<import('../shared/turnChangeSet').TurnChangeSetDetail[]>;+ applyTurnChangeSet: (+ sessionId: string,+ id: string,+ action: import('../shared/turnChangeSet').TurnChangeAction,+ ) => Promise<import('../shared/turnChangeSet').TurnChangeActionResult>;onTurnChangeSetUpdated: (cb: (data: unknown, ownerStamp?: unknown) => void,) => () => void;diff --git a/apps/desktop/src/shared/turnChangeSet.ts b/apps/desktop/src/shared/turnChangeSet.tsindex dabc67de20..968aeec8ea 100644--- a/apps/desktop/src/shared/turnChangeSet.ts+++ b/apps/desktop/src/shared/turnChangeSet.ts@@ -4,6 +4,8 @@ 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 TurnChangeWorkspaceState = 'applied' | 'undone';+export type TurnChangeAction = 'undo' | 'reapply';export type TurnChangeIncompleteReason =| 'opaque-tool'| 'outside-workspace'@@ -35,6 +37,10 @@ export interface TurnChangeSetSummary {providerTurnId: string | null;cwd: string;state: TurnChangeSetState;+ /** Last successful patch direction recorded by Main. */+ workspaceState: TurnChangeWorkspaceState;+ /** Whether the immutable payload can be safely applied in either direction. */+ isReversible: boolean;incompleteReasons: TurnChangeIncompleteReason[];createdAt: number;completedAt: number;@@ -50,6 +56,8 @@ export interface TurnChangeSetDetail extends TurnChangeSetSummary {export interface PersistedTurnChangeSetV1 {version: 1;+ /** Present only for patches captured with the current lossless/reversible format. */+ reversibleFormat?: 'exact-text-v1';id: string;sessionId: string;anchorClientId: string;@@ -68,3 +76,10 @@ export interface TurnChangeSetUpdatedPayload {sessionId: string;summary: TurnChangeSetSummary;}++export interface TurnChangeActionResult {+ action: TurnChangeAction;+ /** False when Main only reconciled a stale sidecar state. */+ changed: boolean;+ summary: TurnChangeSetSummary;+}