Skip to content

Commit 987d47a

Browse files
committed
feat(editor): async post-save diagnostics on chat-diff save path (L1, #1375)
1 parent 4a71d20 commit 987d47a

3 files changed

Lines changed: 255 additions & 38 deletions

File tree

‎src/eslint-suppressions.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1171,7 +1171,7 @@
11711171
},
11721172
"integrations/editor/__tests__/DiffViewProvider.spec.ts": {
11731173
"@typescript-eslint/no-explicit-any": {
1174-
"count": 310
1174+
"count": 306
11751175
}
11761176
},
11771177
"integrations/editor/__tests__/EditorUtils.spec.ts": {

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 66 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,8 +1152,11 @@ export class DiffViewProvider {
11521152
}> {
11531153
const absolutePath = path.resolve(this.cwd, relPath)
11541154

1155-
// Get diagnostics before editing the file
1156-
this.preDiagnostics = vscode.languages.getDiagnostics()
1155+
// Get diagnostics before editing the file. Capture the snapshot locally:
1156+
// overlapping saveDirectly calls (multi-file edits) must not let a later
1157+
// call overwrite this one's baseline before its diagnostics tail runs.
1158+
const preDiagnostics = vscode.languages.getDiagnostics()
1159+
this.preDiagnostics = preDiagnostics
11571160

11581161
// Write the content directly to the file
11591162
await createDirectoriesForFile(absolutePath)
@@ -1176,23 +1179,64 @@ export class DiffViewProvider {
11761179
await doc.save()
11771180
}
11781181

1179-
// Force a small delay to ensure diagnostics are triggered
1180-
await new Promise((resolve) => setTimeout(resolve, 100))
1182+
// The 100 ms diagnostics-settle wait is carried by the
1183+
// emitPostSaveDiagnostics tail (inMemoryDocument) instead of here:
1184+
// blocking the save path delayed every openFile=false save even when
1185+
// diagnostics were disabled or the write delay was 0.
11811186
}
11821187

1183-
let newProblemsMessage = ""
1184-
1188+
// L1 (A2): resolve without awaiting the LSP diagnostics settle. The
1189+
// diagnostics check becomes a fire-and-forget tail that emits any new
1190+
// problems via the existing "error" ClineSay type; the returned
1191+
// newProblemsMessage is therefore always undefined.
11851192
if (diagnosticsEnabled) {
1186-
// Add configurable delay to allow linters time to process
1187-
const safeDelayMs = Math.max(0, writeDelayMs)
1193+
// The method's outer try/catch guarantees it never rejects, so the
1194+
// fire-and-forget call needs no .catch wrapper.
1195+
void this.emitPostSaveDiagnostics(relPath, writeDelayMs, preDiagnostics, !openFile)
1196+
}
11881197

1189-
try {
1190-
await delay(safeDelayMs)
1191-
} catch (error) {
1192-
console.warn(`Failed to apply write delay: ${error}`)
1193-
}
1198+
// Store the results for formatFileWriteResponse
1199+
this.newProblemsMessage = undefined
1200+
this.userEdits = undefined
1201+
this.relPath = relPath
1202+
this.newContent = content
11941203

1195-
const postDiagnostics = vscode.languages.getDiagnostics()
1204+
return {
1205+
newProblemsMessage: undefined,
1206+
userEdits: undefined,
1207+
finalContent: content,
1208+
}
1209+
}
1210+
1211+
// L1 (A2): fire-and-forget post-save diagnostics. After the write delay,
1212+
// collects new Error-severity problems and emits them via the existing
1213+
// "error" ClineSay type (only Error-severity diagnostics reach this branch;
1214+
// "error" carries no task-failure semantics in core). Abort-safe: say()
1215+
// rejects when the task is aborted, so the whole body sits inside a
1216+
// try/catch that degrades to a console.warn — the tail can never reject.
1217+
private async emitPostSaveDiagnostics(
1218+
relPath: string,
1219+
writeDelayMs: number,
1220+
preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][],
1221+
inMemoryDocument = false,
1222+
): Promise<void> {
1223+
try {
1224+
// Add configurable delay to allow linters time to process. When the
1225+
// document was opened in memory (openFile=false), the tail also
1226+
// carries the 100 ms diagnostics-settle wait that used to block
1227+
// saveDirectly. delay() never rejects, so no catch is required here.
1228+
const safeDelayMs = Math.max(0, writeDelayMs) + (inMemoryDocument ? 100 : 0)
1229+
await delay(safeDelayMs)
1230+
1231+
// Filter to the saved file: saveDirectly resolves before this tail
1232+
// completes, so in a multi-file write sequence (e.g. apply_patch)
1233+
// a later file's problems must not be attributed to this relPath.
1234+
const savedFilePath = path.resolve(this.cwd, relPath)
1235+
// arePathsEqual: case-insensitive on Windows, where a relPath whose
1236+
// casing differs from the diagnostic URI is still the same file.
1237+
const postDiagnostics = vscode.languages
1238+
.getDiagnostics()
1239+
.filter(([uri]) => arePathsEqual(uri.fsPath, savedFilePath))
11961240

11971241
// Get diagnostic settings from state
11981242
const task = this.taskRef.deref()
@@ -1201,27 +1245,20 @@ export class DiffViewProvider {
12011245
const maxDiagnosticMessages = state?.maxDiagnosticMessages ?? 50
12021246

12031247
const newProblems = await diagnosticsToProblemsString(
1204-
getNewDiagnostics(this.preDiagnostics, postDiagnostics),
1248+
getNewDiagnostics(preDiagnostics, postDiagnostics),
12051249
[vscode.DiagnosticSeverity.Error],
12061250
this.cwd,
12071251
includeDiagnosticMessages,
12081252
maxDiagnosticMessages,
12091253
)
12101254

1211-
newProblemsMessage =
1212-
newProblems.length > 0 ? `\n\nNew problems detected after saving the file:\n${newProblems}` : ""
1213-
}
1214-
1215-
// Store the results for formatFileWriteResponse
1216-
this.newProblemsMessage = newProblemsMessage
1217-
this.userEdits = undefined
1218-
this.relPath = relPath
1219-
this.newContent = content
1220-
1221-
return {
1222-
newProblemsMessage,
1223-
userEdits: undefined,
1224-
finalContent: content,
1255+
if (newProblems.length > 0) {
1256+
await task?.say("error", `New problems detected after saving file: ${relPath}\n\n${newProblems}`)
1257+
}
1258+
} catch (error) {
1259+
// Abort-safe: never let a post-save diagnostic emit become an
1260+
// unhandled rejection (say() rejects when the task is aborted).
1261+
console.warn(`Post-save diagnostics emit failed: ${error}`)
12251262
}
12261263
}
12271264
}

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

Lines changed: 188 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,14 @@ vi.mock("../../../utils/fs", () => ({
3333
// Mock path
3434
vi.mock("path", () => ({
3535
resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`),
36+
normalize: vi.fn((p: string) => p),
3637
basename: vi.fn((path) => path.split("/").pop()),
3738
dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"),
3839
join: (...args: string[]) => args.join("/"),
40+
// diagnosticsToProblemsString formats its output header via
41+
// path.relative(cwd, uri.fsPath).toPosix(); the object-with-toPosix shape
42+
// mirrors the repo's own diagnostics.spec.ts mock.
43+
relative: vi.fn((cwd: string, p: string) => ({ toPosix: () => p.replace(`${cwd}/`, "") })),
3944
}))
4045

4146
// Mock vscode
@@ -174,6 +179,8 @@ describe("DiffViewProvider", () => {
174179
}),
175180
}),
176181
},
182+
// L1: saveDirectly's fire-and-forget diagnostics tail emits via say().
183+
say: vi.fn().mockResolvedValue(true),
177184
}
178185

179186
diffViewProvider = new DiffViewProvider(mockCwd, mockTask)
@@ -811,12 +818,17 @@ describe("DiffViewProvider", () => {
811818
{ preview: false, preserveFocus: true },
812819
)
813820

814-
// Verify diagnostics were checked after delay
821+
// L1: saveDirectly resolves before the fire-and-forget diagnostics
822+
// tail runs; flush one macrotask tick so the mocked delay (and the
823+
// post-write getDiagnostics) have been reached before asserting.
824+
await new Promise((resolve) => setTimeout(resolve, 0))
825+
826+
// Verify the tail applied the configured write delay
815827
expect(mockDelay).toHaveBeenCalledWith(2000)
816828
expect(vscode.languages.getDiagnostics).toHaveBeenCalled()
817829

818-
// Verify result
819-
expect(result.newProblemsMessage).toBe("")
830+
// Verify result: L1 no longer returns a problems message
831+
expect(result.newProblemsMessage).toBeUndefined()
820832
expect(result.userEdits).toBeUndefined()
821833
expect(result.finalContent).toBe("new content")
822834
})
@@ -847,6 +859,10 @@ describe("DiffViewProvider", () => {
847859
expect(mockDelay).not.toHaveBeenCalled()
848860
// getDiagnostics is called once for pre-diagnostics, but not for post-diagnostics
849861
expect(vscode.languages.getDiagnostics).toHaveBeenCalledTimes(1)
862+
863+
// L1: no diagnostics tail is launched, so nothing is ever emitted
864+
await new Promise((resolve) => setTimeout(resolve, 0))
865+
expect(mockTask.say).not.toHaveBeenCalled()
850866
})
851867

852868
it("should handle negative delay values", async () => {
@@ -855,18 +871,182 @@ describe("DiffViewProvider", () => {
855871

856872
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, -500)
857873

874+
// L1: the tail runs after resolve; flush one macrotask tick first.
875+
await new Promise((resolve) => setTimeout(resolve, 0))
876+
858877
// Verify delay was called with 0 (safe minimum)
859878
expect(mockDelay).toHaveBeenCalledWith(0)
860879
})
861880

862881
it("should store results for formatFileWriteResponse", async () => {
863882
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 1000)
864883

865-
// Verify internal state was updated
866-
expect((diffViewProvider as any).newProblemsMessage).toBe("")
867-
expect((diffViewProvider as any).userEdits).toBeUndefined()
868-
expect((diffViewProvider as any).relPath).toBe("test.ts")
869-
expect((diffViewProvider as any).newContent).toBe("new content")
884+
// Verify internal state was updated (L1: the problems message is no
885+
// longer stored; it is emitted asynchronously via say("error"))
886+
expect(diffViewProvider["newProblemsMessage"]).toBeUndefined()
887+
expect(diffViewProvider["userEdits"]).toBeUndefined()
888+
expect(diffViewProvider["relPath"]).toBe("test.ts")
889+
expect(diffViewProvider["newContent"]).toBe("new content")
890+
})
891+
892+
it("resolves immediately and emits new problems via say('error') after the write delay", async () => {
893+
const mockDelay = vi.mocked(delay)
894+
mockDelay.mockClear()
895+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
896+
897+
// Pre-write diagnostics are empty; the post-write snapshot (read by
898+
// the fire-and-forget tail) reports one new Error-severity problem.
899+
// vscode.workspace.fs.stat is an unimplemented vi.fn() mock, so
900+
// diagnosticsToProblemsString takes its "(unavailable)" fallback
901+
// branch and still formats the line.
902+
const newDiag: vscode.Diagnostic = {
903+
severity: vscode.DiagnosticSeverity.Error,
904+
range: new vscode.Range(0, 0, 0, 1),
905+
message: "boom",
906+
}
907+
const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [newDiag]]]
908+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics)
909+
910+
const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100)
911+
912+
// L1: saveDirectly resolves before the tail emits anything.
913+
expect(result.newProblemsMessage).toBeUndefined()
914+
expect(mockTask.say).not.toHaveBeenCalled()
915+
916+
// Flush the fire-and-forget tail (the mocked delay resolves immediately).
917+
await new Promise((resolve) => setTimeout(resolve, 0))
918+
919+
expect(mockDelay).toHaveBeenCalledWith(100)
920+
expect(mockTask.say).toHaveBeenCalledTimes(1)
921+
// The existing "error" ClineSay type is used, with the new-problems text.
922+
expect(mockTask.say).toHaveBeenCalledWith(
923+
"error",
924+
expect.stringContaining("New problems detected after saving file: test.ts"),
925+
)
926+
expect(mockTask.say.mock.calls[0]?.[1]).toContain("boom")
927+
})
928+
929+
it("attributes only the saved file's new problems to the saved file", async () => {
930+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
931+
932+
// Multi-file write sequence: a later file's new error must not be
933+
// attributed to this tail's relPath by the workspace-wide snapshot.
934+
const ownDiag: vscode.Diagnostic = {
935+
severity: vscode.DiagnosticSeverity.Error,
936+
range: new vscode.Range(0, 0, 0, 1),
937+
message: "own-problem",
938+
}
939+
const otherDiag: vscode.Diagnostic = {
940+
severity: vscode.DiagnosticSeverity.Error,
941+
range: new vscode.Range(0, 0, 0, 1),
942+
message: "other-file-problem",
943+
}
944+
const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [
945+
[makeUri(`${mockCwd}/test.ts`), [ownDiag]],
946+
[makeUri(`${mockCwd}/other.ts`), [otherDiag]],
947+
]
948+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics)
949+
950+
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100)
951+
952+
// Flush the fire-and-forget tail.
953+
await new Promise((resolve) => setTimeout(resolve, 0))
954+
955+
expect(mockTask.say).toHaveBeenCalledTimes(1)
956+
expect(mockTask.say.mock.calls[0]?.[1]).toContain("own-problem")
957+
expect(mockTask.say.mock.calls[0]?.[1]).not.toContain("other-file-problem")
958+
})
959+
960+
it("attributes diagnostics to the saved file when the URI casing differs (Windows)", async () => {
961+
const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("win32")
962+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
963+
964+
// The diagnostic URI uses different casing than the saved relPath:
965+
// on Windows this is still the same file (arePathsEqual).
966+
const newDiag: vscode.Diagnostic = {
967+
severity: vscode.DiagnosticSeverity.Error,
968+
range: new vscode.Range(0, 0, 0, 1),
969+
message: "case-mismatch-problem",
970+
}
971+
const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/Test.ts`), [newDiag]]]
972+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics)
973+
974+
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 100)
975+
976+
// Flush the fire-and-forget tail.
977+
await new Promise((resolve) => setTimeout(resolve, 0))
978+
979+
expect(mockTask.say).toHaveBeenCalledTimes(1)
980+
expect(mockTask.say.mock.calls[0]?.[1]).toContain("case-mismatch-problem")
981+
platformSpy.mockRestore()
982+
})
983+
984+
it("does not block the save on a diagnostics settle delay when diagnostics are disabled", async () => {
985+
// openFile=false used to await a 100 ms settle delay even when
986+
// diagnostics were disabled; that delay now lives in the tail, which
987+
// does not run at all when diagnosticsEnabled is false.
988+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
989+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
990+
const mockDelay = vi.mocked(delay)
991+
mockDelay.mockClear()
992+
993+
const result = await diffViewProvider.saveDirectly("test.ts", "new content", false, false)
994+
995+
expect(result.finalContent).toBe("new content")
996+
expect(mockDelay).not.toHaveBeenCalled()
997+
expect(mockTask.say).not.toHaveBeenCalled()
998+
})
999+
1000+
it("carries the in-memory settle delay in the tail for openFile=false saves", async () => {
1001+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
1002+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
1003+
const mockDelay = vi.mocked(delay)
1004+
mockDelay.mockClear()
1005+
1006+
await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 100)
1007+
1008+
// writeDelayMs (100) + the 100 ms in-memory diagnostics settle, both
1009+
// applied by the tail instead of the save path.
1010+
expect(mockDelay).toHaveBeenCalledWith(200)
1011+
})
1012+
1013+
it("never calls say when there are no new problems", async () => {
1014+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
1015+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([])
1016+
1017+
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 50)
1018+
1019+
// Flush the fire-and-forget tail (pre/post snapshots are both empty,
1020+
// so diagnosticsToProblemsString returns "" and nothing is emitted).
1021+
await new Promise((resolve) => setTimeout(resolve, 0))
1022+
1023+
expect(mockTask.say).not.toHaveBeenCalled()
1024+
})
1025+
1026+
it("logs a warning instead of an unhandled rejection when the post-save say() is aborted", async () => {
1027+
const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
1028+
vi.mocked(vscode.languages.getDiagnostics).mockClear()
1029+
1030+
// One new Error-severity problem so the tail reaches say().
1031+
const newDiag: vscode.Diagnostic = {
1032+
severity: vscode.DiagnosticSeverity.Error,
1033+
range: new vscode.Range(0, 0, 0, 1),
1034+
message: "boom",
1035+
}
1036+
const postDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [[makeUri(`${mockCwd}/test.ts`), [newDiag]]]
1037+
vi.mocked(vscode.languages.getDiagnostics).mockReturnValueOnce([]).mockReturnValue(postDiagnostics)
1038+
1039+
// The task is aborted while the diagnostics tail is emitting: say() rejects.
1040+
mockTask.say.mockRejectedValueOnce(new Error("aborted"))
1041+
1042+
await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 0)
1043+
// Flush the fire-and-forget tail.
1044+
await new Promise((resolve) => setTimeout(resolve, 0))
1045+
1046+
// The method's outer catch swallows the rejection with a warning.
1047+
expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Post-save diagnostics emit failed:"))
1048+
1049+
consoleWarnSpy.mockRestore()
8701050
})
8711051
})
8721052

0 commit comments

Comments
 (0)