Skip to content

Commit 94711ae

Browse files
author
Bertan Ari
committed
fix: validate restore hash before cancelling task; compare task instance in rehydration guard
1 parent ba408c1 commit 94711ae

6 files changed

Lines changed: 82 additions & 33 deletions

File tree

‎src/core/checkpoints/index.ts‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import { DIFF_VIEW_URI_SCHEME } from "../../integrations/editor/DiffViewProvider
1616

1717
import { CheckpointServiceOptions, RepoPerTaskCheckpointService } from "../../services/checkpoints"
1818

19+
import { assertRecordedCheckpoint } from "./recordedCheckpoint"
20+
1921
const WARNING_THRESHOLD_MS = 5000
2022

2123
function sendCheckpointInitWarn(task: Task, type?: "WAIT_TIMEOUT" | "INIT_TIMEOUT", timeout?: number) {
@@ -227,21 +229,6 @@ export async function checkpointSave(task: Task, force = false, suppressMessage
227229
})
228230
}
229231

230-
// `git init` honours the user's init.defaultObjectFormat, so full hashes are SHA-1 or SHA-256.
231-
const FULL_COMMIT_HASH = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
232-
233-
// The hash arrives from the webview, so it must name a checkpoint this task recorded before reaching Git.
234-
function assertRecordedCheckpoint(task: Task, commitHash: unknown): asserts commitHash is string {
235-
const isRecorded =
236-
typeof commitHash === "string" &&
237-
FULL_COMMIT_HASH.test(commitHash) &&
238-
task.clineMessages.some(({ say, text }) => say === "checkpoint_saved" && text === commitHash)
239-
240-
if (!isRecorded) {
241-
throw new Error(t("common:errors.checkpoint_invalid_hash"))
242-
}
243-
}
244-
245232
export type CheckpointRestoreOptions = {
246233
ts: number
247234
commitHash: string
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import type { Task } from "../task/Task"
2+
import { t } from "../../i18n"
3+
4+
// `git init` honours the user's init.defaultObjectFormat, so full hashes are SHA-1 or SHA-256.
5+
const FULL_COMMIT_HASH = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
6+
7+
// The hash arrives from the webview, so it must name a checkpoint this task recorded before reaching Git.
8+
export function assertRecordedCheckpoint(
9+
task: Pick<Task, "clineMessages">,
10+
commitHash: unknown,
11+
): asserts commitHash is string {
12+
const isRecorded =
13+
typeof commitHash === "string" &&
14+
FULL_COMMIT_HASH.test(commitHash) &&
15+
task.clineMessages.some(({ say, text }) => say === "checkpoint_saved" && text === commitHash)
16+
17+
if (!isRecorded) {
18+
throw new Error(t("common:errors.checkpoint_invalid_hash"))
19+
}
20+
}

‎src/core/webview/ClineProvider.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1458,7 +1458,7 @@ export class ClineProvider
14581458
const oldTask = this.taskRegistry.current
14591459

14601460
// The current task may have changed or been removed during the awaits above; never touch it.
1461-
if (oldTask?.taskId !== task.taskId) {
1461+
if (oldTask !== currentTask) {
14621462
removeTaskEventListeners(this.taskEventListeners, task)
14631463
await task.abortTask(true).catch(() => {})
14641464
return task

‎src/core/webview/__tests__/checkpointRestoreHandler.spec.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,9 +273,13 @@ describe("checkpointRestoreHandler", () => {
273273

274274
it.each([
275275
{ name: "a different task became current", replacement: "newer" },
276+
{ name: "a newer instance with the same id became current", replacement: "sameId" },
276277
{ name: "no task remains current", replacement: "none" },
277278
] as const)("restart skips replacement and scheduling when $name during setup", async ({ replacement }) => {
278-
const newerTask = { taskId: "newer-task", abortTask: vi.fn<Task["abortTask"]>() }
279+
const newerTask = {
280+
taskId: replacement === "sameId" ? fixture.task.taskId : "newer-task",
281+
abortTask: vi.fn<Task["abortTask"]>(),
282+
}
279283
const constructedTask = { taskId: fixture.task.taskId, abortTask: vi.fn<Task["abortTask"]>(async () => {}) }
280284
constructTask.mockReturnValueOnce(constructedTask)
281285
const listenerCleanup = vi.fn()
@@ -285,7 +289,7 @@ describe("checkpointRestoreHandler", () => {
285289
fixture.taskDouble.checkpointRestore.mockRejectedValueOnce(new Error("Missing commit"))
286290
showWarningMessage.mockResolvedValueOnce("common:checkpoints.restart")
287291
fixture.providerDouble.getState.mockImplementationOnce(async () => {
288-
registry.current = replacement === "newer" ? newerTask : undefined
292+
registry.current = replacement === "none" ? undefined : newerTask
289293
return { apiConfiguration: {} }
290294
})
291295
await expect(handleCheckpointRestoreOperation(fixture.config)).rejects.toThrow("Missing commit")

‎src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ vi.mock("../../../i18n", () => ({
3636
),
3737
}))
3838

39+
const LATEST_CHECKPOINT = "b".repeat(40)
40+
3941
function createFixture() {
4042
const taskDouble = {
4143
taskId: "test-task-123",
@@ -45,7 +47,7 @@ function createFixture() {
4547
{ ts: 1, type: "say", say: "text", text: "Initial task" },
4648
{ ts: 2, type: "say", say: "checkpoint_saved", text: "initial-checkpoint" },
4749
{ ts: 3, type: "say", say: "user_feedback", text: "Latest prompt" },
48-
{ ts: 4, type: "say", say: "checkpoint_saved", text: "latest-prompt-checkpoint" },
50+
{ ts: 4, type: "say", say: "checkpoint_saved", text: LATEST_CHECKPOINT },
4951
{ ts: 5, type: "say", say: "completion_result", text: "Task complete" },
5052
{ ts: 6, type: "ask", ask: "completion_result", text: "", partial: false },
5153
] satisfies Task["clineMessages"],
@@ -167,7 +169,7 @@ describe("webviewMessageHandler - checkpoint operations", () => {
167169
expect(taskDouble.abortTask).toHaveBeenCalledOnce()
168170
expect(taskDouble.checkpointRestore).toHaveBeenCalledWith({
169171
ts: 3,
170-
commitHash: "latest-prompt-checkpoint",
172+
commitHash: LATEST_CHECKPOINT,
171173
mode: "restore",
172174
operation: "delete",
173175
})
@@ -227,7 +229,7 @@ describe("webviewMessageHandler - checkpoint operations", () => {
227229

228230
expect(taskDouble.checkpointRestore).toHaveBeenCalledExactlyOnceWith({
229231
ts: 3,
230-
commitHash: "latest-prompt-checkpoint",
232+
commitHash: LATEST_CHECKPOINT,
231233
mode: "restore",
232234
operation: "edit",
233235
})
@@ -290,14 +292,14 @@ describe("webviewMessageHandler - checkpoint operations", () => {
290292
fixture.taskDouble.checkpointRestore.mockRejectedValueOnce(failure)
291293
const message: WebviewMessage =
292294
type === "checkpointRestore"
293-
? { type, payload: { ts: 4, commitHash: "latest-prompt-checkpoint", mode: "restore" } }
295+
? { type, payload: { ts: 4, commitHash: LATEST_CHECKPOINT, mode: "restore" } }
294296
: { type }
295297
await webviewMessageHandler(fixture.provider, message)
296298

297299
expect(fixture.providerDouble.cancelTask).toHaveBeenCalledOnce()
298300
expect(fixture.taskDouble.checkpointRestore).toHaveBeenCalledWith({
299301
ts: 4,
300-
commitHash: "latest-prompt-checkpoint",
302+
commitHash: LATEST_CHECKPOINT,
301303
mode: "restore",
302304
})
303305
expect(console.error).toHaveBeenCalledWith(`[${type}] checkpointRestore failed:`, failure)
@@ -309,12 +311,41 @@ describe("webviewMessageHandler - checkpoint operations", () => {
309311
expectUnchanged(messages, history)
310312
})
311313

314+
it.each([
315+
{ name: "malformed", commitHash: "HEAD~1" },
316+
{ name: "unrecorded", commitHash: "c".repeat(40) },
317+
])("checkpointRestore rejects a $name hash without cancelling the task", async ({ commitHash }) => {
318+
const messages = structuredClone(fixture.task.clineMessages)
319+
const history = structuredClone(fixture.task.apiConversationHistory)
320+
await webviewMessageHandler(fixture.provider, {
321+
type: "checkpointRestore",
322+
payload: { ts: 4, commitHash, mode: "restore" },
323+
})
324+
325+
expect(fixture.providerDouble.cancelTask).not.toHaveBeenCalled()
326+
expect(fixture.taskDouble.checkpointRestore).not.toHaveBeenCalled()
327+
expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(
328+
"common:errors.checkpoint_restore_failed: common:errors.checkpoint_invalid_hash",
329+
)
330+
expectUnchanged(messages, history)
331+
})
332+
333+
it("checkpointRestore cancels before restoring a recorded hash", async () => {
334+
await webviewMessageHandler(fixture.provider, {
335+
type: "checkpointRestore",
336+
payload: { ts: 4, commitHash: LATEST_CHECKPOINT, mode: "restore" },
337+
})
338+
expect(fixture.providerDouble.cancelTask.mock.invocationCallOrder[0]).toBeLessThan(
339+
fixture.taskDouble.checkpointRestore.mock.invocationCallOrder[0],
340+
)
341+
})
342+
312343
describe("completion checkpoint actions", () => {
313344
it("diffs the checkpoint created after the latest prompt", async () => {
314345
await webviewMessageHandler(fixture.provider, { type: "completionCheckpointDiff" })
315346
expect(fixture.taskDouble.checkpointDiff).toHaveBeenCalledWith({
316347
ts: 4,
317-
commitHash: "latest-prompt-checkpoint",
348+
commitHash: LATEST_CHECKPOINT,
318349
mode: "to-current",
319350
})
320351
})
@@ -323,7 +354,7 @@ describe("webviewMessageHandler - checkpoint operations", () => {
323354
await webviewMessageHandler(fixture.provider, { type: "completionCheckpointRestore" })
324355
expect(fixture.taskDouble.checkpointRestore).toHaveBeenCalledWith({
325356
ts: 4,
326-
commitHash: "latest-prompt-checkpoint",
357+
commitHash: LATEST_CHECKPOINT,
327358
mode: "restore",
328359
})
329360
expect(fixture.providerDouble.cancelTask.mock.invocationCallOrder[0]).toBeLessThan(

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import { importRooTaskHistory } from "../task-persistence/importRooTaskHistory"
4242
import { ClineProvider } from "./ClineProvider"
4343
import { findOriginalContent } from "./stripOriginalContent"
4444
import { handleCheckpointRestoreOperation } from "./checkpointRestoreHandler"
45+
import { assertRecordedCheckpoint } from "../checkpoints/recordedCheckpoint"
4546
import { generateErrorDiagnostics } from "./diagnosticsHandler"
4647
import {
4748
handleRequestSkills,
@@ -1784,16 +1785,22 @@ export const webviewMessageHandler = async (
17841785
const result = checkoutRestorePayloadSchema.safeParse(message.payload)
17851786

17861787
if (result.success) {
1787-
await provider.cancelTask()
1788-
17891788
try {
1790-
await pWaitFor(() => provider.getCurrentTask()?.isInitialized === true, { timeout: 3_000 })
1791-
} catch {
1792-
vscode.window.showErrorMessage(t("common:errors.checkpoint_timeout"))
1793-
return
1794-
}
1789+
const taskBeforeCancel = provider.getCurrentTask()
1790+
// Reject a bad hash before cancelling, so the running task survives.
1791+
if (taskBeforeCancel) {
1792+
assertRecordedCheckpoint(taskBeforeCancel, result.data.commitHash)
1793+
}
1794+
1795+
await provider.cancelTask()
1796+
1797+
try {
1798+
await pWaitFor(() => provider.getCurrentTask()?.isInitialized === true, { timeout: 3_000 })
1799+
} catch {
1800+
vscode.window.showErrorMessage(t("common:errors.checkpoint_timeout"))
1801+
return
1802+
}
17951803

1796-
try {
17971804
await provider.getCurrentTask()?.checkpointRestore(result.data)
17981805
} catch (error) {
17991806
console.error("[checkpointRestore] checkpointRestore failed:", error)

0 commit comments

Comments
 (0)