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。

fix(desktop): 支持撤销精确记录的部分变更

DavidShen0ff0af277e03
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
index 3dbdf5275b..a84ae0f3c0 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
@@ -559,7 +559,82 @@ describe('turn change-set sidecar store', () => {
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'] });
+ expect(summary).toMatchObject({
+ state: 'partial',
+ incompleteReasons: ['opaque-tool'],
+ isReversible: true,
+ });
+
+ await applyTurnChangeSetAction('session-1', summary!.id, 'undo');
+ expect(await fs.readFile(target, 'utf8')).toBe('old\n');
+ await applyTurnChangeSetAction('session-1', summary!.id, 'reapply');
+ expect(await fs.readFile(target, 'utf8')).toBe('new\n');
+ });
+
+ it('reads a v2 partial index with the exact captured-subset capability', async () => {
+ const target = path.join(workdir, 'legacy-partial.ts');
+ await fs.writeFile(target, 'old\n', 'utf8');
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: target,
+ });
+ await fs.writeFile(target, 'new\n', 'utf8');
+ noteOpaqueTurnChange({ sessionId: 'session-1', provider: 'claude-code', cwd: workdir });
+ await finalizeTurnChangeSet('session-1', null, 'complete');
+
+ await vi.waitFor(async () => expect(await listTurnChangeSets('session-1')).toHaveLength(1));
+ const indexPath = path.join(
+ mocks.userDataRoot,
+ 'cc-agent',
+ 'turn-change-sets',
+ 'session-1',
+ 'index.json',
+ );
+ const index = JSON.parse(await fs.readFile(indexPath, 'utf8')) as {
+ version: number;
+ entries: Array<{ isReversible: boolean }>;
+ };
+ index.version = 2;
+ index.entries[0]!.isReversible = false;
+ await fs.writeFile(indexPath, `${JSON.stringify(index)}\n`, 'utf8');
+
+ const [legacySummary] = await listTurnChangeSets('session-1');
+ expect(legacySummary?.isReversible).toBe(true);
+ expect(JSON.parse(await fs.readFile(indexPath, 'utf8'))).toMatchObject({ version: 2 });
+
+ const nextTarget = path.join(workdir, 'next.ts');
+ await fs.writeFile(nextTarget, 'before\n', 'utf8');
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ });
+ await captureKnownFileBefore({
+ sessionId: 'session-1',
+ provider: 'claude-code',
+ cwd: workdir,
+ targetPath: nextTarget,
+ });
+ await fs.writeFile(nextTarget, 'after\n', 'utf8');
+ await finalizeTurnChangeSet('session-1', null, 'complete');
+ expect(await listTurnChangeSets('session-1')).toHaveLength(2);
+
+ const upgradedIndex = JSON.parse(await fs.readFile(indexPath, 'utf8')) as {
+ version: number;
+ entries: Array<{ id: string; isReversible: boolean }>;
+ };
+ expect(upgradedIndex.version).toBe(3);
+ expect(upgradedIndex.entries.find((entry) => entry.id === legacySummary!.id))
+ .toMatchObject({ isReversible: true });
});
it('persists a zero-file partial entry for an opaque tool with unknown targets', async () => {
@@ -578,6 +653,7 @@ describe('turn change-set sidecar store', () => {
incompleteReasons: ['opaque-tool'],
fileCount: 0,
files: [],
+ isReversible: false,
});
});
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
index 5c29d62989..cf7bb9292d 100644
--- a/apps/desktop/src/main/turn-change-set/store.ts
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -68,8 +68,8 @@ interface PendingTurnChangeSet {
incompleteReasons: Set<TurnChangeIncompleteReason>;
}
-interface TurnChangeIndexV2 {
- version: 2;
+interface TurnChangeIndexV3 {
+ version: 3;
entries: TurnChangeSetSummary[];
detailBytes: Record<string, number>;
}
@@ -134,6 +134,7 @@ const pendingWorkspaceBySession = new Map<string, string>();
const pendingWorkspaceCounts = new Map<string, number>();
const retainedSessionDirs = new Map<string, number>();
const activeActionPromises = new Set<Promise<unknown>>();
+const legacyReversibleCapabilityByDetailPath = new Map<string, boolean>();
let storageWriteChain = Promise.resolve();
function byteLength(value: string): number {
@@ -214,7 +215,6 @@ function filterSensitiveDiffBlocks(
function isReversiblePatch(value: PersistedTurnChangeSetV1): boolean {
if (
value.reversibleFormat !== 'exact-text-v1'
- || value.state !== 'complete'
|| value.unifiedDiff.length === 0
|| value.files.length === 0
) {
@@ -402,17 +402,21 @@ async function pruneActionState(
writeActionStateFile(sessionId, { version: 1, states });
}
-async function readIndexState(sessionId: string): Promise<TurnChangeIndexV2> {
+async function readIndexState(sessionId: string): Promise<TurnChangeIndexV3> {
try {
const raw = await fs.readFile(path.join(sessionDir(sessionId), INDEX_FILE), 'utf8');
- const parsed = JSON.parse(raw) as Partial<Omit<TurnChangeIndexV2, 'version'>> & {
+ const parsed = JSON.parse(raw) as Partial<Omit<TurnChangeIndexV3, 'version'>> & {
version?: unknown;
};
- if ((parsed.version !== 1 && parsed.version !== 2) || !Array.isArray(parsed.entries)) {
- return { version: 2, entries: [], detailBytes: {} };
+ if (
+ (parsed.version !== 1 && parsed.version !== 2 && parsed.version !== 3)
+ || !Array.isArray(parsed.entries)
+ ) {
+ return { version: 3, entries: [], detailBytes: {} };
}
- const reversibleIndex = parsed.version === 2;
- const entries = parsed.entries
+ const sourceVersion = parsed.version;
+ const reversibleIndex = sourceVersion >= 2;
+ let entries = parsed.entries
.filter((entry) => isSummary(entry, sessionId))
.map((entry) => ({
...entry,
@@ -437,12 +441,32 @@ async function readIndexState(sessionId: string): Promise<TurnChangeIndexV2> {
const stat = await fs.stat(detailPath(sessionId, entry.id)).catch(() => null);
if (stat?.isFile()) detailBytes[entry.id] = stat.size;
}
- return { version: 2, entries, detailBytes };
+
+ if (sourceVersion < 3) {
+ entries = await Promise.all(entries.map(async (entry) => {
+ const needsCapabilityUpgrade = sourceVersion === 1 || entry.state === 'partial';
+ if (!needsCapabilityUpgrade) return entry;
+ const currentDetailPath = detailPath(sessionId, entry.id);
+ let isReversible = legacyReversibleCapabilityByDetailPath.get(currentDetailPath);
+ if (isReversible === undefined) {
+ const rawDetail = await fs.readFile(currentDetailPath, 'utf8').catch(() => null);
+ const detail = rawDetail === null ? null : parsePersisted(rawDetail);
+ isReversible = detail ? isReversiblePatch(detail) : false;
+ // A transient read failure must remain retryable. Otherwise the next normal
+ // persist could write a false capability into v3 permanently.
+ if (rawDetail !== null) {
+ legacyReversibleCapabilityByDetailPath.set(currentDetailPath, isReversible);
+ }
+ }
+ return { ...entry, isReversible };
+ }));
+ }
+ return { version: 3, entries, detailBytes };
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
log.warn('turn change-set index read failed', { sessionId, error });
}
- return { version: 2, entries: [], detailBytes: {} };
+ return { version: 3, entries: [], detailBytes: {} };
}
}
@@ -620,7 +644,7 @@ async function persistValue(value: PersistedTurnChangeSetV1): Promise<void> {
);
atomicWriteFileSync(
path.join(dir, INDEX_FILE),
- `${JSON.stringify({ version: 2, entries: next, detailBytes: nextDetailBytes } satisfies TurnChangeIndexV2)}\n`,
+ `${JSON.stringify({ version: 3, entries: next, detailBytes: nextDetailBytes } satisfies TurnChangeIndexV3)}\n`,
);
indexPublished = true;
const storedFiles = await fs.readdir(dir).catch(() => []);
diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
index 1deed1ee76..c093d649b0 100644
--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
@@ -110,6 +110,7 @@ export function TurnChangesCard({
const hiddenCount = changeSet.fileCount - visibleFiles.length;
const omittedCount = Math.max(0, changeSet.fileCount - files.length);
const workspaceState = workspaceStateOverride ?? changeSet.workspaceState;
+ const appliesCapturedSubset = changeSet.state === 'partial' && changeSet.isReversible;
useEffect(() => {
setWorkspaceStateOverride((current) => (
@@ -144,9 +145,13 @@ export function TurnChangesCard({
: result.summary.workspaceState,
);
toast.success(t(
- action === 'undo'
- ? 'chat.turnChanges.undoSuccess'
- : 'chat.turnChanges.reapplySuccess',
+ appliesCapturedSubset
+ ? action === 'undo'
+ ? 'chat.turnChanges.undoPartialSuccess'
+ : 'chat.turnChanges.reapplyPartialSuccess'
+ : action === 'undo'
+ ? 'chat.turnChanges.undoSuccess'
+ : 'chat.turnChanges.reapplySuccess',
));
} catch (error) {
const code = extractIpcError(error)?.code;
@@ -182,7 +187,11 @@ export function TurnChangesCard({
{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>
+ <span>{t(
+ appliesCapturedSubset
+ ? 'chat.turnChanges.partialReversible'
+ : 'chat.turnChanges.partial',
+ )}</span>
</div>
)}
</div>
@@ -191,10 +200,17 @@ export function TurnChangesCard({
<button
type="button"
disabled={applying}
+ title={appliesCapturedSubset
+ ? t('chat.turnChanges.partialActionHint')
+ : undefined}
aria-label={t(
- workspaceState === 'undone'
- ? 'chat.turnChanges.reapplyAria'
- : 'chat.turnChanges.undoAria',
+ appliesCapturedSubset
+ ? workspaceState === 'undone'
+ ? 'chat.turnChanges.reapplyPartialAria'
+ : 'chat.turnChanges.undoPartialAria'
+ : workspaceState === 'undone'
+ ? 'chat.turnChanges.reapplyAria'
+ : 'chat.turnChanges.undoAria',
)}
onClick={() => void applyTurnChange()}
className={cn(
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
index 25de297267..db88f6573e 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
@@ -178,7 +178,43 @@ describe('TurnChangesCard file actions', () => {
expect(mocks.toastSuccess).toHaveBeenCalledWith('chat.turnChanges.undoSuccess');
});
- it('does not offer undo for a partial or otherwise non-reversible patch', () => {
+ it('offers partial undo for the exactly captured subset and explains the boundary', async () => {
+ const partial: TurnChangeSetSummary = {
+ ...CHANGE_SET,
+ state: 'partial',
+ isReversible: true,
+ incompleteReasons: ['opaque-tool'],
+ };
+ mocks.applyTurnChangeSet
+ .mockResolvedValueOnce({
+ action: 'undo',
+ changed: true,
+ summary: { ...partial, workspaceState: 'undone' },
+ })
+ .mockResolvedValueOnce({
+ action: 'reapply',
+ changed: true,
+ summary: { ...partial, workspaceState: 'applied' },
+ });
+ render(<TurnChangesCard sessionId="session-1" changeSet={partial} />);
+
+ expect(screen.getByText('chat.turnChanges.partialReversible')).toBeTruthy();
+ const undo = screen.getByRole('button', { name: 'chat.turnChanges.undoPartialAria' });
+ expect(undo.getAttribute('title')).toBe('chat.turnChanges.partialActionHint');
+ fireEvent.click(undo);
+
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith(
+ 'chat.turnChanges.undoPartialSuccess',
+ ));
+ fireEvent.click(await screen.findByRole('button', {
+ name: 'chat.turnChanges.reapplyPartialAria',
+ }));
+ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith(
+ 'chat.turnChanges.reapplyPartialSuccess',
+ ));
+ });
+
+ it('does not offer undo for a non-reversible patch', () => {
render(
<TurnChangesCard
sessionId="session-1"
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 088e502fc2..6cb7fc3308 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6202,15 +6202,21 @@
"review": "Review",
"undo": "Undo",
"undoAria": "Undo changes from this turn",
+ "undoPartialAria": "Undo exactly captured changes from this turn",
"reapply": "Reapply",
"reapplyAria": "Reapply changes from this turn",
+ "reapplyPartialAria": "Reapply exactly captured changes from this turn",
"undoSuccess": "Changes from this turn were undone",
"reapplySuccess": "Changes from this turn were reapplied",
+ "undoPartialSuccess": "Exactly captured changes were undone; uncaptured changes were not undone",
+ "reapplyPartialSuccess": "Exactly captured changes were reapplied; uncaptured changes were not 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",
+ "partialReversible": "Only exactly captured changes can be undone or reapplied; uncaptured changes are not handled",
+ "partialActionHint": "Only undo or reapply exactly captured file changes",
"showMore": "Show {{count}} more files",
"reviewRemaining": "Review {{count}} more files",
"showLess": "Show less"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index adaa2c0fa0..dbf1071529 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6200,15 +6200,21 @@
"review": "レビュー",
"undo": "元に戻す",
"undoAria": "このターンの変更を元に戻す",
+ "undoPartialAria": "このターンで正確に取得された変更を元に戻す",
"reapply": "再適用",
"reapplyAria": "このターンの変更を再適用する",
+ "reapplyPartialAria": "このターンで正確に取得された変更を再適用する",
"undoSuccess": "このターンの変更を元に戻しました",
"reapplySuccess": "このターンの変更を再適用しました",
+ "undoPartialSuccess": "正確に取得された変更を元に戻しました。取得されていない変更は元に戻していません",
+ "reapplyPartialSuccess": "正確に取得された変更を再適用しました。取得されていない変更は再適用していません",
"actionRunning": "現在の応答が完了してからワークスペースを変更してください",
"actionConflict": "ワークスペースが変更されたため、このパッチを安全に適用できません。現在の変更を先にレビューしてください",
"actionUnavailable": "このターンには安全に元に戻せないファイル変更が含まれています",
"actionFailed": "変更を適用できませんでした。もう一度お試しください",
"partial": "正確に取得できた変更のみ表示しています",
+ "partialReversible": "元に戻す操作と再適用の対象は正確に取得された変更のみです。取得されていない変更は処理されません",
+ "partialActionHint": "正確に取得されたファイル変更のみを元に戻すか再適用します",
"showMore": "さらに {{count}} ファイルを表示",
"reviewRemaining": "残り {{count}} ファイルをレビューで表示",
"showLess": "折りたたむ"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e28992a522..28b9728996 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6200,15 +6200,21 @@
"review": "검토",
"undo": "실행 취소",
"undoAria": "이번 턴의 변경 사항 실행 취소",
+ "undoPartialAria": "이번 턴에서 정확히 캡처된 변경 사항 실행 취소",
"reapply": "다시 적용",
"reapplyAria": "이번 턴의 변경 사항 다시 적용",
+ "reapplyPartialAria": "이번 턴에서 정확히 캡처된 변경 사항 다시 적용",
"undoSuccess": "이번 턴의 변경 사항을 실행 취소했습니다",
"reapplySuccess": "이번 턴의 변경 사항을 다시 적용했습니다",
+ "undoPartialSuccess": "정확히 캡처된 변경 사항을 실행 취소했습니다. 캡처되지 않은 변경 사항은 실행 취소하지 않았습니다",
+ "reapplyPartialSuccess": "정확히 캡처된 변경 사항을 다시 적용했습니다. 캡처되지 않은 변경 사항은 다시 적용하지 않았습니다",
"actionRunning": "현재 응답이 끝난 후 작업 공간을 변경하세요",
"actionConflict": "작업 공간이 변경되어 이 패치를 안전하게 적용할 수 없습니다. 현재 변경 사항을 먼저 검토하세요",
"actionUnavailable": "이번 턴에는 안전하게 실행 취소할 수 없는 파일 변경 사항이 포함되어 있습니다",
"actionFailed": "변경 사항을 적용하지 못했습니다. 다시 시도하세요",
"partial": "정확히 캡처된 변경 사항만 표시됩니다",
+ "partialReversible": "실행 취소와 다시 적용은 정확히 캡처된 변경 사항만 처리하며 캡처되지 않은 변경 사항은 처리하지 않습니다",
+ "partialActionHint": "정확히 캡처된 파일 변경 사항만 실행 취소하거나 다시 적용합니다",
"showMore": "파일 {{count}}개 더 보기",
"reviewRemaining": "나머지 파일 {{count}}개를 검토에서 보기",
"showLess": "접기"
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 c750bd48df..ef8bc97ff2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6200,15 +6200,21 @@
"review": "审查",
"undo": "撤销",
"undoAria": "撤销本轮改动",
+ "undoPartialAria": "撤销本轮中已精确记录的改动",
"reapply": "重新应用",
"reapplyAria": "重新应用本轮改动",
+ "reapplyPartialAria": "重新应用本轮中已精确记录的改动",
"undoSuccess": "已撤销本轮改动",
"reapplySuccess": "已重新应用本轮改动",
+ "undoPartialSuccess": "已撤销精确记录的改动;未记录的改动未被撤销",
+ "reapplyPartialSuccess": "已重新应用精确记录的改动;未记录的改动未被重新应用",
"actionRunning": "请等待当前回复结束后再更改工作区",
"actionConflict": "工作区内容已变化,无法安全应用本轮补丁;请先审查当前改动",
"actionUnavailable": "本轮包含无法安全撤销的文件变更",
"actionFailed": "未能应用本轮改动,请重试",
"partial": "仅记录了可精确捕获的部分变更",
+ "partialReversible": "仅撤销或重新应用已精确记录的变更;未记录的改动不会由此操作处理",
+ "partialActionHint": "仅撤销或重新应用已精确记录的文件变更",
"showMore": "再显示 {{count}} 个文件",
"reviewRemaining": "在审查中查看其余 {{count}} 个文件",
"showLess": "收起"
diff --git a/apps/desktop/src/shared/turnChangeSet.ts b/apps/desktop/src/shared/turnChangeSet.ts
index 968aeec8ea..50ebfee6d7 100644
--- a/apps/desktop/src/shared/turnChangeSet.ts
+++ b/apps/desktop/src/shared/turnChangeSet.ts
@@ -39,7 +39,7 @@ export interface TurnChangeSetSummary {
state: TurnChangeSetState;
/** Last successful patch direction recorded by Main. */
workspaceState: TurnChangeWorkspaceState;
- /** Whether the immutable payload can be safely applied in either direction. */
+ /** Whether the exact recorded payload can be safely applied in either direction. */
isReversible: boolean;
incompleteReasons: TurnChangeIncompleteReason[];
createdAt: number;