Skip to content

Commit e92bd5a

Browse files
fix(checkpoints): put the messages back when the API history cannot follow the cut, and report a restore that did nothing; tighter assertions
1 parent db67a63 commit e92bd5a

5 files changed

Lines changed: 175 additions & 23 deletions

File tree

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

Lines changed: 118 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -510,16 +510,128 @@ describe("Checkpoint functionality", () => {
510510
expect(mockProvider.cancelTask).toHaveBeenCalled()
511511
})
512512

513-
it("should handle missing message gracefully", async () => {
514-
await checkpointRestore(mockTask, {
515-
ts: 999, // Non-existent timestamp
516-
commitHash: RESTORE_HASH,
517-
mode: "restore",
518-
})
513+
it("reports a restore to a message that is no longer there, and restores nothing", async () => {
514+
await expect(
515+
checkpointRestore(mockTask, {
516+
ts: 999, // Non-existent timestamp
517+
commitHash: RESTORE_HASH,
518+
mode: "restore",
519+
}),
520+
).rejects.toThrow("no longer in the conversation")
519521

520522
expect(mockCheckpointService.restoreCheckpoint).not.toHaveBeenCalled()
521523
})
522524

525+
it("has nothing to report for a preview of a message that is no longer there", async () => {
526+
await expect(
527+
checkpointRestore(mockTask, { ts: 999, commitHash: RESTORE_HASH, mode: "preview" }),
528+
).resolves.toBeUndefined()
529+
530+
expect(mockCheckpointService.restoreCheckpoint).not.toHaveBeenCalled()
531+
})
532+
533+
it.each(["delete", "edit"] as const)(
534+
"reports a restore when checkpoints were disabled after the checkpoint was recorded, instead of returning as if it worked (%s)",
535+
async (operation) => {
536+
mockTask.enableCheckpoints = false
537+
538+
await expect(
539+
checkpointRestore(mockTask, { ts: 2, commitHash: RESTORE_HASH, mode: "restore", operation }),
540+
).rejects.toThrow("Checkpoints are not available for this task")
541+
542+
// Nothing was restored or rewound, and nothing was started: the caller is told, and can offer to start the task.
543+
expect(mockCheckpointService.restoreCheckpoint).not.toHaveBeenCalled()
544+
expect(mockTask.overwriteClineMessages).not.toHaveBeenCalled()
545+
expect(mockProvider.cancelTask).not.toHaveBeenCalled()
546+
},
547+
)
548+
549+
it("has nothing to report for a preview when checkpoints are disabled", async () => {
550+
mockTask.enableCheckpoints = false
551+
552+
await expect(
553+
checkpointRestore(mockTask, { ts: 2, commitHash: RESTORE_HASH, mode: "preview" }),
554+
).resolves.toBeUndefined()
555+
})
556+
557+
describe("when the API history cannot follow the cut of the messages", () => {
558+
const original = () => [
559+
{ ts: 1, say: "user", text: "Message 1" },
560+
{ ts: 2, say: "assistant", text: "Message 2" },
561+
{ ts: 3, say: "user", text: "Message 3" },
562+
{ ts: 4, say: "checkpoint_saved", text: RESTORE_HASH },
563+
]
564+
// The task keeps what it is given, as the real one does.
565+
const keepWhatIsWritten = () =>
566+
mockTask.overwriteClineMessages.mockImplementation(async (messages: unknown[]) => {
567+
mockTask.clineMessages = messages
568+
})
569+
570+
it("puts the messages back, so the task is started again with both histories as they were", async () => {
571+
keepWhatIsWritten()
572+
mockTask.ensureApiConversationHistoryStored.mockResolvedValueOnce(false)
573+
574+
await expect(
575+
checkpointRestore(mockTask, {
576+
ts: 2,
577+
commitHash: RESTORE_HASH,
578+
mode: "restore",
579+
operation: "delete",
580+
}),
581+
).rejects.toMatchObject({
582+
name: "ConversationRewindError",
583+
message: "The API conversation history could not be saved",
584+
restarted: true,
585+
})
586+
587+
// The cut was written, and then the messages that were there before it.
588+
expect(mockTask.overwriteClineMessages).toHaveBeenCalledTimes(2)
589+
expect(mockTask.overwriteClineMessages.mock.calls[0][0]).toHaveLength(1)
590+
expect(mockTask.overwriteClineMessages.mock.calls[1][0]).toEqual(original())
591+
expect(mockProvider.cancelTask).toHaveBeenCalledTimes(1) // restarted, from what is on disk
592+
})
593+
594+
it("says that the conversation is only partly rewound when the messages cannot be put back either", async () => {
595+
keepWhatIsWritten()
596+
mockTask.ensureApiConversationHistoryStored.mockResolvedValueOnce(false)
597+
mockTask.overwriteClineMessages
598+
.mockImplementationOnce(async (messages: unknown[]) => {
599+
mockTask.clineMessages = messages
600+
})
601+
.mockRejectedValueOnce(new Error("disk full"))
602+
603+
const restoring = checkpointRestore(mockTask, {
604+
ts: 2,
605+
commitHash: RESTORE_HASH,
606+
mode: "restore",
607+
operation: "delete",
608+
})
609+
610+
await expect(restoring).rejects.toMatchObject({ name: "ConversationRewindError" })
611+
await expect(restoring).rejects.toThrow(
612+
/could not be saved, and the messages could not be put back \(disk full\).*only partly rewound/,
613+
)
614+
expect(mockProvider.cancelTask).toHaveBeenCalledTimes(1)
615+
})
616+
617+
it("puts nothing back when the messages were not cut", async () => {
618+
keepWhatIsWritten()
619+
mockTask.overwriteClineMessages.mockReset()
620+
mockTask.overwriteClineMessages.mockRejectedValueOnce(new Error("Failed to save the messages"))
621+
622+
await expect(
623+
checkpointRestore(mockTask, {
624+
ts: 2,
625+
commitHash: RESTORE_HASH,
626+
mode: "restore",
627+
operation: "delete",
628+
}),
629+
).rejects.toMatchObject({ name: "ConversationRewindError" })
630+
631+
expect(mockTask.overwriteClineMessages).toHaveBeenCalledTimes(1) // the one that failed, and no put-back
632+
})
633+
})
634+
523635
it.each(["delete", "edit"] as const)(
524636
"propagates restore failures for %s without rewinding",
525637
async (operation) => {

‎src/core/checkpoints/index.ts‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -246,12 +246,16 @@ export async function checkpointRestore(
246246
const service = await getCheckpointService(task)
247247

248248
if (!service) {
249+
// A restore that did nothing is not a restore that worked: the caller has stopped the task for it, and has to be
250+
// told so that it can offer to start the task again. A preview has nothing to report.
251+
if (mode === "restore") throw new Error("Checkpoints are not available for this task")
249252
return
250253
}
251254

252255
const index = task.clineMessages.findIndex((m) => m.ts === ts)
253256

254257
if (index === -1) {
258+
if (mode === "restore") throw new Error("The message to restore to is no longer in the conversation")
255259
return
256260
}
257261

@@ -349,16 +353,40 @@ async function rewindConversation(
349353
task.combineMessages(deletedMessages),
350354
)
351355

352-
// Use MessageManager to properly handle context-management events
353-
// This ensures orphaned Summary messages and truncation markers are cleaned up
354-
await task.messageManager.rewindToTimestamp(ts, {
355-
includeTargetMessage: operation === "edit",
356-
})
356+
const messagesBefore = [...task.clineMessages]
357+
let failure: unknown
358+
try {
359+
// Use MessageManager to properly handle context-management events
360+
// This ensures orphaned Summary messages and truncation markers are cleaned up
361+
await task.messageManager.rewindToTimestamp(ts, {
362+
includeTargetMessage: operation === "edit",
363+
})
357364

358-
// The cut of the API history has to be on disk before the task is started again from it: a write that was lost is
359-
// retried, and a cut that cannot be stored is a failed rewind, not one that the restart would then undo silently.
360-
if (!(await task.ensureApiConversationHistoryStored())) {
361-
throw new Error("The API conversation history could not be saved")
365+
// The cut of the API history has to be on disk before the task is started again from it: a write that was lost is
366+
// retried, and a cut that cannot be stored is a failed rewind, not one that the restart would then undo silently.
367+
if (!(await task.ensureApiConversationHistoryStored())) {
368+
throw new Error("The API conversation history could not be saved")
369+
}
370+
} catch (error) {
371+
failure = error
372+
}
373+
374+
if (failure !== undefined) {
375+
// The messages were cut first: when the API history could not follow, the two are not the same conversation, and the
376+
// task that is started again would show a conversation shorter than the one the model is given. The messages are put
377+
// back, so that both are what they were before the rewind.
378+
if (task.clineMessages.length !== messagesBefore.length) {
379+
try {
380+
await task.overwriteClineMessages(messagesBefore)
381+
} catch (restoreError) {
382+
const reason = failure instanceof Error ? failure.message : String(failure)
383+
const restoreReason = restoreError instanceof Error ? restoreError.message : String(restoreError)
384+
throw new Error(
385+
`${reason}, and the messages could not be put back (${restoreReason}): the conversation is only partly rewound`,
386+
)
387+
}
388+
}
389+
throw failure
362390
}
363391

364392
return {

‎src/core/config/__tests__/ProviderSettingsManager.spec.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -700,12 +700,16 @@ describe("ProviderSettingsManager", () => {
700700

701701
const first = providerSettingsManager.listConfig() // holds the lock, and cannot be cancelled
702702
await vi.waitFor(() => expect(mockSecrets.get).toHaveBeenCalledTimes(1))
703-
const queued = [
704-
providerSettingsManager.listConfig({ signal: controller.signal }),
705-
providerSettingsManager.getAllProfiles({ signal: controller.signal }),
706-
providerSettingsManager.getProfile({ id: "other-id" }, { signal: controller.signal }),
703+
// Each read wraps the cancellation with its own prefix.
704+
const queued: Array<[Promise<unknown>, RegExp]> = [
705+
[providerSettingsManager.listConfig({ signal: controller.signal }), /^Failed to list configs/],
706+
[providerSettingsManager.getAllProfiles({ signal: controller.signal }), /^Failed to get profiles/],
707+
[
708+
providerSettingsManager.getProfile({ id: "other-id" }, { signal: controller.signal }),
709+
/^Failed to get profile: /,
710+
],
707711
]
708-
const failures = queued.map((read) => expect(read).rejects.toBeDefined())
712+
const failures = queued.map(([read, message]) => expect(read).rejects.toThrow(message))
709713
const write = providerSettingsManager.saveConfig("other", {
710714
id: "other-id",
711715
apiProvider: providerIdentifiers.anthropic,
@@ -728,11 +732,16 @@ describe("ProviderSettingsManager", () => {
728732
it("leaves no listener on a signal that is never aborted", async () => {
729733
mockSecrets.get.mockResolvedValue(text())
730734
const controller = new AbortController()
735+
const add = vi.spyOn(controller.signal, "addEventListener")
731736
const remove = vi.spyOn(controller.signal, "removeEventListener")
732737

733738
await providerSettingsManager.getAllProfiles({ signal: controller.signal })
734739

735-
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function))
740+
// The listener that was added is the one that is removed.
741+
const added = add.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener)
742+
const removed = remove.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener)
743+
expect(added).toHaveLength(1)
744+
expect(removed).toEqual(added)
736745
})
737746
})
738747

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3943,6 +3943,7 @@ describe("Cline", () => {
39433943
it("records neither provider nor model when the profile sets no provider", async () => {
39443944
const payload = await firstApiReqPayload({} as ProviderSettings)
39453945
expect(payload.apiProvider).toBeUndefined()
3946+
expect(payload.modelId).toBeUndefined()
39463947
})
39473948

39483949
it("stops, and relabels no other request, when the placeholder of the request is deleted while it is prepared", async () => {

‎src/services/language-models/__tests__/copilotQuota.spec.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,11 +229,13 @@ describe("getGitHubCopilotQuota", () => {
229229
it("fetches again when the session cannot be looked up", async () => {
230230
await getGitHubCopilotQuota({}, vi.fn(async () => json(businessPayload)) as never)
231231

232-
getSession.mockRejectedValue(new Error("auth broken"))
232+
// The lookup that checks the cache fails once; the session is there for the fetch that follows.
233+
getSession.mockRejectedValueOnce(new Error("auth broken")).mockResolvedValue({ accessToken: "gho_token" })
233234
const fetchSpy = vi.fn(async () => json(other))
234235
const result = await getGitHubCopilotQuota({}, fetchSpy as never)
235236

236-
expect(result).not.toMatchObject({ ok: true, quota: { plan: "business" } })
237+
expect(result).toMatchObject({ ok: true, quota: { plan: "individual" } }) // fetched again, not the cached one
238+
expect(fetchSpy).toHaveBeenCalledTimes(1)
237239
})
238240

239241
it("rejects with the cancellation when the caller leaves while the session is looked up", async () => {

0 commit comments

Comments
 (0)