Skip to content

Commit 42dace5

Browse files
committed
fix(checkpoints): fail loudly on lost commits and keep card diffs out of cloud capture
Two pre-merge review findings on the change-card persistence path: - A saveCheckpoint rejection was swallowed for every call: with write metadata the file write had already happened, so the tool reported a success whose rollback metadata did not exist. Write-metadata saves now propagate the failure (checkpoints still disabled); the legacy swallow is reserved for non-write calls such as the task-start baseline. - Full-detail change cards embed raw unified diffs, and task sync captured every non-partial message, uploading the content of secret-bearing files (.env, PII) to the cloud endpoint. change_card messages are now excluded from cloud task-message capture in both addToClineMessages and updateClineMessage; cards stay local to the webview. Regression tests: write-metadata rejection propagates with no journal entry and no change card; non-write failures keep the legacy swallow; change_card says never reach CloudService.captureEvent while ordinary says still sync. Negative controls: removing the write-metadata branch -> exactly 1 red; removing each capture-site guard -> exactly 1 red.
1 parent f92312f commit 42dace5

4 files changed

Lines changed: 151 additions & 13 deletions

File tree

‎src/core/checkpoints/__tests__/checkpointJournal.test.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,14 +172,39 @@ describe("checkpointSave change-journal wiring (B2)", () => {
172172
expect(entries.map((entry) => entry.operation)).toEqual(["create", "update", "delete"])
173173
})
174174

175-
it("keeps the existing error-swallowing behavior and skips the journal on save failure", async () => {
175+
it("keeps the existing error-swallowing behavior for non-write saves on failure", async () => {
176+
// The legacy swallow (log + disable + resolve undefined) is reserved
177+
// for checkpoint calls without write metadata, e.g. the task-start
178+
// baseline: no file write has happened, so there is no orphaned write
179+
// to report.
176180
saveCheckpointSpy.mockRejectedValueOnce(new Error("git exploded"))
177181

178-
await expect(checkpointSave(mockTask as Task, false, true, write)).resolves.toBeUndefined()
182+
await expect(checkpointSave(mockTask as Task)).resolves.toBeUndefined()
179183
expect(mockTask.enableCheckpoints).toBe(false)
180184
expect(await loadChanges(tmpStorageDir, TASK_ID)).toEqual([])
181185
})
182186

187+
it("propagates a saveCheckpoint rejection for a write-metadata save", async () => {
188+
// The file write already happened: swallowing the commit failure
189+
// would report a tool success whose rollback metadata does not exist.
190+
saveCheckpointSpy.mockRejectedValueOnce(new Error("git exploded"))
191+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined)
192+
193+
await expect(checkpointSave(mockTask as Task, false, true, write)).rejects.toThrow(/no rollback metadata/)
194+
195+
// Checkpoints are still disabled on failure, and neither the journal
196+
// nor the change card is written for a commit that never happened.
197+
expect(mockTask.enableCheckpoints).toBe(false)
198+
expect(await loadChanges(tmpStorageDir, TASK_ID)).toEqual([])
199+
const cardCalls = vi.mocked(mockTask.say).mock.calls.filter((call) => call[0] === "change_card")
200+
expect(cardCalls).toHaveLength(0)
201+
expect(consoleErrorSpy).toHaveBeenCalledWith(
202+
expect.stringContaining("caught unexpected error"),
203+
expect.anything(),
204+
)
205+
consoleErrorSpy.mockRestore()
206+
})
207+
183208
it("does not write a journal entry when the checkpoint save is a no-op (empty commit)", async () => {
184209
saveCheckpointSpy.mockResolvedValueOnce(undefined)
185210

‎src/core/checkpoints/index.ts‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -284,17 +284,37 @@ export async function checkpointSave(
284284

285285
TelemetryService.instance.captureCheckpointCreated(task.taskId)
286286

287-
// Start the checkpoint process in the background.
288-
// Save failures keep the historical behavior: logged, checkpoints
289-
// disabled, and the save resolves undefined. Journal/card work below runs
290-
// only for a real commit and its failures propagate to the caller
291-
// instead of flowing through this handler.
292-
const result = await service
293-
.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage })
294-
.catch((err) => {
287+
// Save failures keep the historical behavior for non-write calls:
288+
// logged, checkpoints disabled, and the save resolves undefined. A
289+
// write-metadata save must not swallow a failed commit: the file write
290+
// already happened, so the caller must see an explicit failure instead
291+
// of a success whose rollback metadata does not exist. Journal/card
292+
// work below runs only for a real commit, and its failures propagate to
293+
// the caller instead of flowing through this handler.
294+
const savePromise = service.saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, {
295+
allowEmpty: force,
296+
suppressMessage,
297+
})
298+
// `void` keeps the historical union member of the awaited legacy
299+
// catch path (and of this function's return type) unchanged.
300+
let result: Awaited<typeof savePromise> | void
301+
if (hasWriteMetadata) {
302+
try {
303+
result = await savePromise
304+
} catch (err) {
305+
console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err)
306+
task.enableCheckpoints = false
307+
throw new Error(
308+
`Checkpoint save failed after a file write; the write has no rollback metadata: ${err instanceof Error ? err.message : String(err)}`,
309+
{ cause: err },
310+
)
311+
}
312+
} else {
313+
result = await savePromise.catch((err) => {
295314
console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err)
296315
task.enableCheckpoints = false
297316
})
317+
}
298318
// B2: record successful file writes in the per-task change journal.
299319
// Only a real commit produces an entry (an empty or failed save
300320
// resolves to undefined / rejects), and non-write checkpoint calls

‎src/core/task/Task.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1684,7 +1684,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
16841684
this.emit(RooCodeEventName.Message, { action: "created", message })
16851685
await this.saveClineMessages()
16861686

1687-
const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
1687+
// Change cards embed raw unified diffs of approved writes (full
1688+
// detail mode): keep them local to the webview so task sync never
1689+
// uploads the content of secret-bearing files (.env, PII) to the
1690+
// cloud endpoint.
1691+
const shouldCaptureMessage =
1692+
message.partial !== true && CloudService.isEnabled() && message.say !== "change_card"
16881693

16891694
if (shouldCaptureMessage) {
16901695
CloudService.instance.captureEvent({
@@ -1734,8 +1739,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
17341739
await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message })
17351740
this.emit(RooCodeEventName.Message, { action: "updated", message })
17361741

1737-
// Check if we should sync to cloud and haven't already synced this message
1738-
const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled()
1742+
// Check if we should sync to cloud and haven't already synced this
1743+
// message. Change cards stay out of cloud capture (full diffs embed
1744+
// file content; see addToClineMessages) - the guard is repeated here
1745+
// because a card message is never tracked as synced.
1746+
const shouldCaptureMessage =
1747+
message.partial !== true && CloudService.isEnabled() && message.say !== "change_card"
17391748
const hasNotBeenSynced = !this.cloudSyncedMessageTimestamps.has(message.ts)
17401749

17411750
if (shouldCaptureMessage && hasNotBeenSynced) {

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7514,6 +7514,90 @@ describe("Cline", () => {
75147514
)
75157515
})
75167516
})
7517+
7518+
// Change cards embed raw unified diffs of approved writes (full detail
7519+
// mode): task sync must not upload their file content to the cloud.
7520+
describe("cloud capture of change cards", () => {
7521+
const flushMicrotasks = () => new Promise<void>((resolve) => setImmediate(resolve))
7522+
7523+
it("keeps change_card messages out of cloud task-message capture", async () => {
7524+
const { CloudService } = await import("@roo-code/cloud")
7525+
const enabledSpy = vi.spyOn(CloudService, "isEnabled").mockReturnValue(true)
7526+
const captureSpy = vi.fn()
7527+
// Minimal double for the singleton getter: the capture path only
7528+
// calls captureEvent on the instance, and the real singleton is
7529+
// not initialized in this harness (the getter would throw).
7530+
const cloudDouble = { captureEvent: captureSpy } as unknown as import("@roo-code/cloud").CloudService
7531+
const instanceSpy = vi.spyOn(CloudService, "instance", "get").mockReturnValue(cloudDouble)
7532+
7533+
const task = new Task({
7534+
provider: mockProvider,
7535+
apiConfiguration: mockApiConfig,
7536+
task: "test task",
7537+
startTask: false,
7538+
})
7539+
await flushMicrotasks()
7540+
captureSpy.mockClear()
7541+
7542+
const cardPayload = JSON.stringify({
7543+
checkpointId: "abc123",
7544+
files: [{ path: ".env", additions: 1, deletions: 0, diff: "+SECRET_KEY=hunter2" }],
7545+
})
7546+
await task.say("change_card", cardPayload, undefined, undefined, undefined, undefined, {
7547+
isNonInteractive: true,
7548+
})
7549+
await flushMicrotasks()
7550+
7551+
const cardCaptures = captureSpy.mock.calls.filter(
7552+
(call) =>
7553+
(call[0] as { properties?: { message?: { say?: string } } }).properties?.message?.say ===
7554+
"change_card",
7555+
)
7556+
expect(cardCaptures).toHaveLength(0)
7557+
7558+
// Control: an ordinary non-partial say still syncs while task
7559+
// capture is enabled, so the exclusion is change_card-specific.
7560+
await task.say("text", "ordinary message")
7561+
await flushMicrotasks()
7562+
const textCaptures = captureSpy.mock.calls.filter(
7563+
(call) =>
7564+
(call[0] as { properties?: { message?: { say?: string } } }).properties?.message?.say === "text",
7565+
)
7566+
expect(textCaptures.length).toBeGreaterThan(0)
7567+
7568+
enabledSpy.mockRestore()
7569+
instanceSpy.mockRestore()
7570+
})
7571+
7572+
it("keeps change_card messages out of the updateClineMessage capture path", async () => {
7573+
const { CloudService } = await import("@roo-code/cloud")
7574+
const enabledSpy = vi.spyOn(CloudService, "isEnabled").mockReturnValue(true)
7575+
const captureSpy = vi.fn()
7576+
const cloudDouble = { captureEvent: captureSpy } as unknown as import("@roo-code/cloud").CloudService
7577+
const instanceSpy = vi.spyOn(CloudService, "instance", "get").mockReturnValue(cloudDouble)
7578+
7579+
const task = new Task({
7580+
provider: mockProvider,
7581+
apiConfiguration: mockApiConfig,
7582+
task: "test task",
7583+
startTask: false,
7584+
})
7585+
await flushMicrotasks()
7586+
captureSpy.mockClear()
7587+
7588+
const cardMessage = {
7589+
ts: Date.now(),
7590+
type: "say" as const,
7591+
say: "change_card" as const,
7592+
text: JSON.stringify({ checkpointId: "abc", files: [{ path: ".env", diff: "+SECRET=x" }] }),
7593+
}
7594+
await task["updateClineMessage"](cardMessage)
7595+
expect(captureSpy).not.toHaveBeenCalled()
7596+
7597+
enabledSpy.mockRestore()
7598+
instanceSpy.mockRestore()
7599+
})
7600+
})
75177601
})
75187602

75197603
describe("Queued message processing after condense", () => {

0 commit comments

Comments
 (0)