Skip to content

Commit c7c9f7b

Browse files
author
s3-1395 lane
committed
fix(editor): scope the write result report to the save that produced it
1 parent 047c3f8 commit c7c9f7b

4 files changed

Lines changed: 121 additions & 11 deletions

File tree

‎src/core/tools/WriteToFileTool.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { unescapeHtmlEntities } from "../../utils/text-normalization"
1414
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
1515
import { convertNewFileToUnifiedDiff, computeDiffStats, sanitizeUnifiedDiff } from "../diff/stats"
1616
import type { ToolUse } from "../../shared/tools"
17+
import type { WriteSaveResults } from "../../integrations/editor/DiffViewProvider"
1718

1819
import { BaseTool, ToolCallbacks } from "./BaseTool"
1920

@@ -410,6 +411,11 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
410411
EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION,
411412
)
412413

414+
// Whatever this write's own save computed. Both save paths report the pair, and the report
415+
// below is built from it rather than from the copies parked on the shared provider, which a
416+
// retry or another write can overwrite before the report is serialized.
417+
let saveResults: WriteSaveResults | undefined
418+
413419
if (isPreventFocusDisruptionEnabled) {
414420
task.diffViewProvider.editType = fileExists ? "modify" : "create"
415421
if (fileExists) {
@@ -446,7 +452,13 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
446452
return
447453
}
448454

449-
await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs)
455+
saveResults = await task.diffViewProvider.saveDirectly(
456+
relPath,
457+
newContent,
458+
false,
459+
diagnosticsEnabled,
460+
writeDelayMs,
461+
)
450462
// saveDirectly() performs the write itself and reports a failing write, so returning
451463
// means the content is on disk: from here the rollback has to stand down.
452464
writeCommitted = true
@@ -485,7 +497,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
485497
return
486498
}
487499

488-
await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs, () => {
500+
saveResults = await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs, () => {
489501
// Signalled by saveChanges() at the document save, not when it returns: the editor
490502
// bookkeeping and diagnostics that follow can still reject, and by then the file
491503
// has already landed.
@@ -499,7 +511,7 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
499511

500512
task.didEditFile = true
501513

502-
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists)
514+
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, !fileExists, saveResults)
503515

504516
pushToolResult(message)
505517

‎src/core/tools/__tests__/writeToFileTool.spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,29 @@ describe("writeToFileTool", () => {
749749
expect.stringContaining("editedExistingFile"),
750750
)
751751
})
752+
753+
it("hands the report the results of its own save instead of leaving it to read the provider", async () => {
754+
// The provider parks both results and the report used to read them back from there. A second
755+
// write on the same provider parks its own pair in between, and the report then names the
756+
// other write's patch and problems. The call now carries its own pair to the report.
757+
const userEditsValue = "- old line\n+ new line"
758+
mockCline.diffViewProvider.saveChanges.mockResolvedValue({
759+
newProblemsMessage: " with warnings",
760+
userEdits: userEditsValue,
761+
finalContent: "modified content",
762+
})
763+
mockCline.diffViewProvider.userEdits = "- other old line\n+ other new line"
764+
mockCline.diffViewProvider.newProblemsMessage = " warnings from the other write"
765+
766+
await executeWriteFileTool({}, { fileExists: true })
767+
768+
expect(mockCline.diffViewProvider.pushToolWriteResult).toHaveBeenCalledWith(
769+
mockCline,
770+
mockCline.cwd,
771+
false,
772+
{ newProblemsMessage: " with warnings", userEdits: userEditsValue, finalContent: "modified content" },
773+
)
774+
})
752775
})
753776

754777
describe("error handling", () => {

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,17 @@ export class DocumentSaveFailedError extends Error {
4343
export const DIFF_VIEW_URI_SCHEME = "cline-diff"
4444
export const DIFF_VIEW_LABEL_CHANGES = "Original ↔ Zoo's Changes"
4545

46+
/**
47+
* What one save computed for its own edit: the patch the user typed into the diff view and the
48+
* problems that showed up after that save. saveChanges() also parks this pair on the provider, and
49+
* a retry or a second write on the same provider can park its own pair before the first save's
50+
* report is serialized, so the report is built from the pair that travelled with the call.
51+
*/
52+
export interface WriteSaveResults {
53+
newProblemsMessage: string | undefined
54+
userEdits: string | undefined
55+
}
56+
4657
// TODO: https://github.com/cline/cline/pull/3354
4758
export class DiffViewProvider {
4859
// Properties to store the results of saveChanges
@@ -539,18 +550,33 @@ export class DiffViewProvider {
539550
* @param isNewFile Whether this is a new file or an existing file being modified
540551
* @returns Formatted message (JSON)
541552
*/
542-
async pushToolWriteResult(task: Task, cwd: string, isNewFile: boolean): Promise<string> {
553+
async pushToolWriteResult(
554+
task: Task,
555+
cwd: string,
556+
isNewFile: boolean,
557+
// The results of the save whose call this reports, taken from that save rather than from the
558+
// copies it parked on the provider: a retry or a second write on the same provider parks its own
559+
// pair before this call runs, and the parked pair then describes a different edit.
560+
savedResults?: WriteSaveResults,
561+
): Promise<string> {
543562
if (!this.relPath) {
544563
throw new Error("No file path available in DiffViewProvider")
545564
}
546565

566+
// The pair this report is about. When the caller handed one over, the report is scoped to that
567+
// save; when it did not, the report falls back to the pair parked on the provider, which is the
568+
// behaviour the tools that have not threaded a result yet depend on.
569+
const userEdits = savedResults === undefined ? this.userEdits : savedResults.userEdits
570+
const newProblemsMessage =
571+
savedResults === undefined ? this.newProblemsMessage : savedResults.newProblemsMessage
572+
547573
// Only send user_feedback_diff if userEdits exists
548-
if (this.userEdits) {
574+
if (userEdits) {
549575
// Create say object for UI feedback
550576
const say: ClineSayTool = {
551577
tool: isNewFile ? "newFileCreated" : "editedExistingFile",
552578
path: getReadablePath(cwd, this.relPath),
553-
diff: this.userEdits,
579+
diff: userEdits,
554580
}
555581

556582
// Send the user feedback
@@ -561,7 +587,7 @@ export class DiffViewProvider {
561587
const notices = [
562588
"You do not need to re-read the file, as you have seen all changes",
563589
"Proceed with the task using these changes as the new baseline.",
564-
...(this.userEdits
590+
...(userEdits
565591
? [
566592
"If the user's edits have addressed part of the task or changed the requirements, adjust your approach accordingly.",
567593
]
@@ -580,12 +606,12 @@ export class DiffViewProvider {
580606
notice: notices.join(" "),
581607
}
582608

583-
if (this.userEdits) {
584-
result.user_edits = this.userEdits
609+
if (userEdits) {
610+
result.user_edits = userEdits
585611
}
586612

587-
if (this.newProblemsMessage) {
588-
result.problems = this.newProblemsMessage
613+
if (newProblemsMessage) {
614+
result.problems = newProblemsMessage
589615
}
590616

591617
return JSON.stringify(result)

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,55 @@ describe("DiffViewProvider", () => {
10671067
})
10681068
})
10691069

1070+
describe("pushToolWriteResult result scoping", () => {
1071+
beforeEach(() => {
1072+
diffViewProvider["relPath"] = "test.ts"
1073+
diffViewProvider["preDiagnostics"] = []
1074+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
1075+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
1076+
})
1077+
1078+
it("lines 520 and 527: reports the patch of the save whose call it reports, not of the save that parked last", async () => {
1079+
// Two saves on one provider, which is the interleaving the thread describes: the first
1080+
// edit's report is serialized only after a second edit has parked its own pair on the
1081+
// provider. A report that reads the parked pair hands the second edit's patch to the first
1082+
// edit's caller, under the first edit's path.
1083+
const say = vi.fn().mockResolvedValue(undefined)
1084+
// pushToolWriteResult only reaches task.say(), so the double carries only that member.
1085+
const reportTask = { say } as unknown as Task
1086+
1087+
diffViewProvider["newContent"] = "aaa"
1088+
diffViewProvider["activeDiffEditor"] = makeTextEditor({
1089+
document: makeTextDocument({ getText: vi.fn().mockReturnValue("aaa\nuser typed one"), isDirty: false }),
1090+
})
1091+
const saveA = await diffViewProvider.saveChanges(false, 0)
1092+
1093+
diffViewProvider["newContent"] = "bbb"
1094+
diffViewProvider["activeDiffEditor"] = makeTextEditor({
1095+
document: makeTextDocument({ getText: vi.fn().mockReturnValue("bbb\nuser typed two"), isDirty: false }),
1096+
})
1097+
const saveB = await diffViewProvider.saveChanges(false, 0)
1098+
1099+
// Both saves typed a patch, and the parked pair now holds save B.
1100+
expect(saveA.userEdits).toBeTruthy()
1101+
expect(saveB.userEdits).toBeTruthy()
1102+
expect(saveA.userEdits).not.toBe(saveB.userEdits)
1103+
expect(diffViewProvider.userEdits).toBe(saveB.userEdits)
1104+
1105+
const reportA: { path: string; user_edits?: string } = JSON.parse(
1106+
await diffViewProvider.pushToolWriteResult(reportTask, mockCwd, false, saveA),
1107+
)
1108+
1109+
expect(reportA.user_edits).toBe(saveA.userEdits)
1110+
expect(reportA.path).toBe("test.ts")
1111+
const card: { tool: string; path: string; diff: string } = JSON.parse(String(say.mock.calls[0]?.[1]))
1112+
1113+
expect(card.tool).toBe("editedExistingFile")
1114+
expect(card.diff).toBe(saveA.userEdits)
1115+
expect(card.diff).not.toBe(saveB.userEdits)
1116+
})
1117+
})
1118+
10701119
describe("preEditScrollLine capture and restore", () => {
10711120
it("should capture scroll line from visible editor at open() time", async () => {
10721121
const mockEditor = makeTextEditor({

0 commit comments

Comments
 (0)