Skip to content

Commit 7e5449b

Browse files
fix: no restart from a partly rewound conversation; a read after a write cannot join the batch ahead of it; hold the request's own placeholder; finite token counts; unused catch binding
1 parent fa4b931 commit 7e5449b

13 files changed

Lines changed: 194 additions & 32 deletions

File tree

‎src/core/checkpoints/ConversationRewindError.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@ export class ConversationRewindError extends Error {
2020
}
2121
}
2222

23+
/**
24+
* The messages were cut and could not be put back after the API history failed to follow: the two sides of the
25+
* conversation are not the same, and a task that is started from them would give the model turns that the user cannot
26+
* see. The task is not started again; the caller hands the edit back, and the user decides.
27+
*/
28+
export class ConversationPartlyRewoundError extends Error {
29+
constructor(message: string) {
30+
super(message)
31+
this.name = "ConversationPartlyRewoundError"
32+
}
33+
}
34+
2335
/**
2436
* The files were restored and the conversation was rewound, but the task could not be started again (or was not
2537
* rehydrated). Nothing will take a pending edit, so the caller clears it and hands it back to the user.

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -607,11 +607,18 @@ describe("Checkpoint functionality", () => {
607607
operation: "delete",
608608
})
609609

610-
await expect(restoring).rejects.toMatchObject({ name: "ConversationRewindError" })
610+
await expect(restoring).rejects.toMatchObject({
611+
name: "ConversationRewindError",
612+
restarted: false, // the edit is handed back, and the user decides
613+
restartFailure: {
614+
error: expect.objectContaining({ message: expect.stringContaining("partly rewound") }),
615+
},
616+
})
611617
await expect(restoring).rejects.toThrow(
612618
/could not be saved, and the messages could not be put back \(disk full\).*only partly rewound/,
613619
)
614-
expect(mockProvider.cancelTask).toHaveBeenCalledTimes(1)
620+
// Not started again from two sides that are not the same conversation.
621+
expect(mockProvider.cancelTask).not.toHaveBeenCalled()
615622
})
616623

617624
it("tells a failure that is not an Error as text, in the message about a conversation that is only partly rewound", async () => {
@@ -633,6 +640,7 @@ describe("Checkpoint functionality", () => {
633640
).rejects.toThrow(
634641
"disk gone, and the messages could not be put back (no space): the conversation is only partly rewound",
635642
)
643+
expect(mockProvider.cancelTask).not.toHaveBeenCalled()
636644
})
637645

638646
it("puts nothing back when the messages were not cut", async () => {

‎src/core/checkpoints/index.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ import { DIFF_VIEW_URI_SCHEME } from "../../integrations/editor/DiffViewProvider
1717
import { CheckpointServiceOptions, RepoPerTaskCheckpointService } from "../../services/checkpoints"
1818

1919
import { assertRecordedCheckpoint } from "./recordedCheckpoint"
20-
import { ConversationRewindError, TaskNotRestartedError } from "./ConversationRewindError"
20+
import {
21+
ConversationPartlyRewoundError,
22+
ConversationRewindError,
23+
TaskNotRestartedError,
24+
} from "./ConversationRewindError"
2125

2226
const WARNING_THRESHOLD_MS = 5000
2327

@@ -271,6 +275,15 @@ export async function checkpointRestore(
271275
try {
272276
deletedRequests = await rewindConversation(task, ts, index, operation)
273277
} catch (error) {
278+
// A conversation whose two sides are not the same is not started again: the model would be given turns that
279+
// the user cannot see. It is reported as a restart that did not happen, so the edit is handed back.
280+
if (error instanceof ConversationPartlyRewoundError) {
281+
throw new ConversationRewindError(error, {
282+
error: new Error(
283+
"the task was not started again, because its conversation is only partly rewound",
284+
),
285+
})
286+
}
274287
// The workspace is already restored: the task still has to be started again, as after a rewind that worked.
275288
// A restart that fails is not hidden by the rewind failure, nor does it hide it: both are told.
276289
throw new ConversationRewindError(error, await startTaskAgain(provider, task))
@@ -381,7 +394,7 @@ async function rewindConversation(
381394
} catch (restoreError) {
382395
const reason = failure instanceof Error ? failure.message : String(failure)
383396
const restoreReason = restoreError instanceof Error ? restoreError.message : String(restoreError)
384-
throw new Error(
397+
throw new ConversationPartlyRewoundError(
385398
`${reason}, and the messages could not be put back (${restoreReason}): the conversation is only partly rewound`,
386399
)
387400
}

‎src/core/config/ProviderSettingsManager.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ export class ProviderSettingsManager {
105105
// Synchronize readConfig/writeConfig operations to avoid data loss.
106106
private _lock = Promise.resolve()
107107
private lock<T>(cb: () => Promise<T>) {
108+
// Reads that come after this operation are behind it: they cannot join a batch that is queued ahead of it.
109+
this.readBatch = undefined
108110
const next = this._lock.then(cb)
109111
this._lock = next.catch(() => {}) as Promise<void>
110112
return next

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,33 @@ describe("ProviderSettingsManager", () => {
788788
loadSpy.mockRestore()
789789
})
790790

791+
it("does not let a read that comes after a write join the batch that is queued ahead of that write", async () => {
792+
mockSecrets.get.mockClear()
793+
let finishFirst: (value: string) => void = () => undefined
794+
let current = text()
795+
mockSecrets.get
796+
.mockImplementationOnce(() => new Promise<string>((resolve) => (finishFirst = resolve)))
797+
.mockImplementation(async () => current)
798+
mockSecrets.store.mockImplementation(async (_key: string, value: string) => {
799+
current = value
800+
})
801+
802+
const first = providerSettingsManager.listConfig() // holds the line, so everything after it waits
803+
await vi.waitFor(() => expect(mockSecrets.get).toHaveBeenCalledTimes(1))
804+
const before = providerSettingsManager.getAllProfiles({ signal: new AbortController().signal }) // a batch
805+
const write = providerSettingsManager.saveConfig("added", {
806+
id: "added-id",
807+
apiProvider: providerIdentifiers.anthropic,
808+
})
809+
const after = providerSettingsManager.getAllProfiles({ signal: new AbortController().signal }) // behind the write
810+
finishFirst(text())
811+
812+
await first
813+
await write
814+
expect((await before).map((p) => p.name)).toEqual(["default", "other"]) // as before the write
815+
expect((await after).map((p) => p.name)).toContain("added") // and this one sees what the write stored
816+
})
817+
791818
it("answers every caller of one batch with one load of the storage", async () => {
792819
mockSecrets.get.mockClear()
793820
mockSecrets.get.mockResolvedValue(text())

‎src/core/task/Task.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4106,10 +4106,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
41064106
)
41074107
// The placeholder that the say above added, kept from here: it is this request's, whatever is deleted, rewound
41084108
// or added during the waits below, and no lookup later can select an older request's instead.
4109-
const requestMessage =
4110-
this.clineMessages.slice(messageCountBefore).find((message) => message.say === "api_req_started") ??
4111-
// A task whose `say` added nothing (a test double): the last request message, taken in the same step.
4112-
findLast(this.clineMessages, (message) => message.say === "api_req_started")
4109+
// Only what the say above added: if that was deleted while it waited, there is none, and an older request's is
4110+
// not taken in its place (its usage would be erased, and the deleted turn would still be sent).
4111+
const requestMessage = this.clineMessages
4112+
.slice(messageCountBefore)
4113+
.find((message) => message.say === "api_req_started")
41134114

41144115
const provider = this.providerRef.deref()
41154116
const state = provider ? await provider.getState() : undefined

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

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3905,11 +3905,18 @@ describe("Cline", () => {
39053905
})
39063906

39073907
const payloads: string[] = []
3908+
// As the real say does, the message is added to the conversation: the request keeps hold of that one.
39083909
vi.spyOn(task, "say").mockImplementation(async (type, text) => {
39093910
if (type === "api_req_started") payloads.push(String(text))
3911+
task.clineMessages.push({
3912+
ts: Date.now(),
3913+
type: "say",
3914+
say: type as "api_req_started",
3915+
text: String(text),
3916+
})
39103917
return undefined as never
39113918
})
3912-
task.clineMessages = [{ ts: Date.now(), type: "say", say: "api_req_started", text: "{}" }]
3919+
task.clineMessages = [{ ts: Date.now() - 1, type: "say", say: "api_req_started", text: "{}" }]
39133920

39143921
// Only the stop that the test asks for is expected: any other failure is a failure of the test.
39153922
await task.recursivelyMakeClineRequests([{ type: "text", text: "hello" }]).catch((error: unknown) => {
@@ -3992,6 +3999,47 @@ describe("Cline", () => {
39923999
expect(older.text).toBe('{"apiProvider":"older"}') // not relabelled in its place
39934000
expect(attempt).not.toHaveBeenCalled() // and nothing was sent
39944001
})
4002+
4003+
it("stops, and takes no older request in its place, when the placeholder is deleted while it is being written", async () => {
4004+
const task = new Task({
4005+
provider: mockProvider,
4006+
apiConfiguration: {
4007+
apiProvider: providerIdentifiers.anthropic,
4008+
apiKey: "k",
4009+
apiModelId: "claude-sonnet-5",
4010+
},
4011+
task: "test task",
4012+
startTask: false,
4013+
})
4014+
Object.assign(task.api, { ensureModelFetched: vi.fn().mockResolvedValue(undefined) })
4015+
vi.mocked(processUserContentMentions).mockResolvedValueOnce({
4016+
content: [{ type: "text", text: "hello" }],
4017+
mode: undefined,
4018+
})
4019+
vi.spyOn(getTaskTestAccess(task), "saveClineMessages").mockResolvedValue(true)
4020+
vi.spyOn(getTaskTestAccess(task), "addToApiConversationHistory").mockResolvedValue(undefined)
4021+
const attempt = vi.spyOn(task, "attemptApiRequest")
4022+
// An older request, and the placeholder that this request adds.
4023+
const older = {
4024+
ts: 1,
4025+
type: "say" as const,
4026+
say: "api_req_started" as const,
4027+
text: '{"apiProvider":"older"}',
4028+
}
4029+
task.clineMessages = [older]
4030+
// A delete that is confirmed while the say waits: the placeholder is gone when it returns.
4031+
vi.spyOn(task, "say").mockImplementation(async () => undefined as never)
4032+
// A deletion that is confirmed while the request is being prepared removes its placeholder.
4033+
vi.mocked(getEnvironmentDetails).mockClear()
4034+
4035+
// The loop ends the request there, as it does for an abort.
4036+
await expect(task.recursivelyMakeClineRequests([{ type: "text", text: "hello" }])).rejects.toThrow(
4037+
"request was removed from the conversation",
4038+
)
4039+
4040+
expect(older.text).toBe('{"apiProvider":"older"}') // not relabelled in its place
4041+
expect(attempt).not.toHaveBeenCalled() // and nothing was sent
4042+
})
39954043
})
39964044

39974045
describe("Subtask Rate Limiting", () => {

‎src/core/task/__tests__/ask-auto-deny.spec.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,11 @@ function attachTurnHarness(task: Task) {
8282
Object.defineProperty(task, "streamingToolCallIndices", { value: new Map() })
8383
Object.defineProperty(task, "activeToolContexts", { value: new Map() })
8484
task["saveApiConversationHistory"] = vi.fn(async () => true)
85-
task["say"] = vi.fn(async () => undefined)
86-
// The loop rewrites the newest api_req_started row with cost data; the
87-
// no-op `say` stub above never adds one itself.
88-
task["clineMessages"].push({ type: "say", say: "api_req_started", text: "{}", ts: Date.now() })
85+
// The loop rewrites the request's own api_req_started row with cost data, as the real `say` adds it.
86+
task["say"] = vi.fn(async (type: string, text?: string) => {
87+
task["clineMessages"].push({ type: "say", say: type as ClineMessage["say"], text, ts: Date.now() })
88+
return undefined
89+
})
8990
task["attemptApiRequest"] = vi.fn().mockImplementation(() =>
9091
(async function* () {
9192
yield { type: "text" as const, text: "next turn reply" }

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1675,7 +1675,7 @@ export const webviewMessageHandler = async (
16751675
signal: controller.signal,
16761676
activeProfileId,
16771677
})
1678-
} catch (error) {
1678+
} catch {
16791679
providerQuotasFailed = true
16801680
if (!controller.signal.aborted) {
16811681
// A fixed text: what failed may be the saved profiles, and a message about them (a parse error of the stored

‎src/i18n/locales/zh-TW/common.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)