import pWaitFor from "p-wait-for" import * as vscode from "vscode" import type { ClineApiReqInfo } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { Task } from "../task/Task" import { getWorkspacePath } from "../../utils/path" import { checkGitInstalled } from "../../utils/git" import { t } from "../../i18n" import { getApiMetrics } from "../../shared/getApiMetrics" import { DIFF_VIEW_URI_SCHEME } from "../../integrations/editor/DiffViewProvider" import { CheckpointServiceOptions, RepoPerTaskCheckpointService } from "../../services/checkpoints" import { assertRecordedCheckpoint } from "./recordedCheckpoint" import { ConversationPartlyRewoundError, ConversationRewindError, TaskNotRestartedError, } from "./ConversationRewindError" const WARNING_THRESHOLD_MS = 5000 function sendCheckpointInitWarn(task: Task, type?: "WAIT_TIMEOUT" | "INIT_TIMEOUT", timeout?: number) { task.providerRef.deref()?.postMessageToWebview({ type: "checkpointInitWarning", checkpointWarning: type && timeout ? { type, timeout } : undefined, }) } export async function getCheckpointService(task: Task, { interval = 250 }: { interval?: number } = {}) { if (!task.enableCheckpoints) { return undefined } if (task.checkpointService) { return task.checkpointService } const provider = task.providerRef.deref() // Get checkpoint timeout from task settings (converted to milliseconds) const checkpointTimeoutMs = task.checkpointTimeout * 1000 const log = (message: string) => { console.log(message) try { provider?.log(message) } catch { // NO-OP } } console.log("[Task#getCheckpointService] initializing checkpoints service") try { const workspaceDir = task.cwd || getWorkspacePath() if (!workspaceDir) { log("[Task#getCheckpointService] workspace folder not found, disabling checkpoints") task.enableCheckpoints = false return undefined } const globalStorageDir = provider?.context.globalStorageUri.fsPath if (!globalStorageDir) { log("[Task#getCheckpointService] globalStorageDir not found, disabling checkpoints") task.enableCheckpoints = false return undefined } const options: CheckpointServiceOptions = { taskId: task.taskId, workspaceDir, shadowDir: globalStorageDir, log, } if (task.checkpointServiceInitializing) { const checkpointInitStartTime = Date.now() let warningShown = false await pWaitFor( () => { const elapsed = Date.now() - checkpointInitStartTime // Show warning if we're past the threshold and haven't shown it yet if (!warningShown && elapsed >= WARNING_THRESHOLD_MS) { warningShown = true sendCheckpointInitWarn(task, "WAIT_TIMEOUT", WARNING_THRESHOLD_MS / 1000) } console.log( `[Task#getCheckpointService] waiting for service to initialize (${Math.round(elapsed / 1000)}s)`, ) return !!task.checkpointService && !!task?.checkpointService?.isInitialized }, { interval, timeout: checkpointTimeoutMs }, ) if (!task?.checkpointService) { sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout) task.enableCheckpoints = false return undefined } else { sendCheckpointInitWarn(task) } return task.checkpointService } if (!task.enableCheckpoints) { return undefined } const service = RepoPerTaskCheckpointService.create(options) task.checkpointServiceInitializing = true await checkGitInstallation(task, service, log, provider) task.checkpointService = service if (task.enableCheckpoints) { sendCheckpointInitWarn(task) } return service } catch (err) { if (err.name === "TimeoutError" && task.enableCheckpoints) { sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout) } log(`[Task#getCheckpointService] ${err.message}`) task.enableCheckpoints = false task.checkpointServiceInitializing = false return undefined } } async function checkGitInstallation( task: Task, service: RepoPerTaskCheckpointService, log: (message: string) => void, provider: any, ) { try { const gitInstalled = await checkGitInstalled() if (!gitInstalled) { log("[Task#getCheckpointService] Git is not installed, disabling checkpoints") task.enableCheckpoints = false task.checkpointServiceInitializing = false // Show user-friendly notification const selection = await vscode.window.showWarningMessage( t("common:errors.git_not_installed"), t("common:buttons.learn_more"), ) if (selection === t("common:buttons.learn_more")) { await vscode.env.openExternal(vscode.Uri.parse("https://git-scm.com/downloads")) } return } // Git is installed, proceed with initialization service.on("initialize", () => { log("[Task#getCheckpointService] service initialized") task.checkpointServiceInitializing = false }) service.on("checkpoint", ({ fromHash: from, toHash: to, suppressMessage }) => { try { sendCheckpointInitWarn(task) // Always update the current checkpoint hash in the webview, including the suppress flag provider?.postMessageToWebview({ type: "currentCheckpointUpdated", text: to, suppressMessage: !!suppressMessage, }) // Always create the chat message but include the suppress flag in the payload // so the chatview can choose not to render it while keeping it in history. task.say( "checkpoint_saved", to, undefined, undefined, { from, to, suppressMessage: !!suppressMessage }, undefined, { isNonInteractive: true }, ).catch((err) => { log("[Task#getCheckpointService] caught unexpected error in say('checkpoint_saved')") console.error(err) }) } catch (err) { log("[Task#getCheckpointService] caught unexpected error in on('checkpoint'), disabling checkpoints") console.error(err) task.enableCheckpoints = false } }) log("[Task#getCheckpointService] initializing shadow git") try { await service.initShadowGit() } catch (err) { log(`[Task#getCheckpointService] initShadowGit -> ${err.message}`) task.enableCheckpoints = false } } catch (err) { log(`[Task#getCheckpointService] Unexpected error during Git check: ${err.message}`) console.error("Git check error:", err) task.enableCheckpoints = false task.checkpointServiceInitializing = false } } export async function checkpointSave(task: Task, force = false, suppressMessage = false) { const service = await getCheckpointService(task) if (!service) { return } TelemetryService.instance.captureCheckpointCreated(task.taskId) // Start the checkpoint process in the background. return service .saveCheckpoint(`Task: ${task.taskId}, Time: ${Date.now()}`, { allowEmpty: force, suppressMessage }) .catch((err) => { console.error("[Task#checkpointSave] caught unexpected error, disabling checkpoints", err) task.enableCheckpoints = false }) } export type CheckpointRestoreOptions = { ts: number commitHash: string mode: "preview" | "restore" operation?: "delete" | "edit" // Optional to maintain backward compatibility } export async function checkpointRestore( task: Task, { ts, commitHash, mode, operation = "delete" }: CheckpointRestoreOptions, ) { assertRecordedCheckpoint(task, commitHash) const service = await getCheckpointService(task) if (!service) { // A restore that did nothing is not a restore that worked: the caller has stopped the task for it, and has to be // told so that it can offer to start the task again. A preview has nothing to report. if (mode === "restore") throw new Error("Checkpoints are not available for this task") return } const index = task.clineMessages.findIndex((m) => m.ts === ts) if (index === -1) { if (mode === "restore") throw new Error("The message to restore to is no longer in the conversation") return } const provider = task.providerRef.deref() try { await service.restoreCheckpoint(commitHash) TelemetryService.instance.captureCheckpointRestored(task.taskId) await provider?.postMessageToWebview({ type: "currentCheckpointUpdated", text: commitHash }) if (mode === "restore") { let deletedRequests: ClineApiReqInfo try { deletedRequests = await rewindConversation(task, ts, index, operation) } catch (error) { // A conversation whose two sides are not the same is not started again: the model would be given turns that // the user cannot see. It is reported as a restart that did not happen, so the edit is handed back. if (error instanceof ConversationPartlyRewoundError) { throw new ConversationRewindError(error, { error: new Error( "the task was not started again, because its conversation is only partly rewound", ), }) } // The workspace is already restored: the task still has to be started again, as after a rewind that worked. // A restart that fails is not hidden by the rewind failure, nor does it hide it: both are told. throw new ConversationRewindError(error, await startTaskAgain(provider, task)) } // The rewind is saved. The row that reports the deleted requests is only a note: a task that cannot say it // (it was aborted, as a delete does) has been rewound all the same, so this is not a failed rewind, and the // task is started again, and a pending edit applied, as after any rewind that worked. try { await task.say("api_req_deleted", JSON.stringify(deletedRequests)) } catch (error) { provider?.log( `[checkpointRestore] the conversation was rewound, but the deleted requests could not be noted: ${ error instanceof Error ? error.message : String(error) }`, ) } } // The task is already cancelled by the provider beforehand, but we // need to re-init to get the updated messages. // // This was taken from Cline's implementation of the checkpoints // feature. The task instance will hang if we don't cancel twice, // so this is currently necessary, but it seems like a complicated // and hacky solution to a problem that I don't fully understand. // I'd like to revisit this in the future and try to improve the // task flow and the communication between the webview and the // `Task` instance. // The restart is awaited and checked: a task that was not rehydrated is reported, and a pending edit is not left // for a task that will not come. const restart = await startTaskAgain(provider, task) if (restart) throw new TaskNotRestartedError(restart.error) } catch (error) { provider?.log("[checkpointRestore] failed to restore checkpoint") throw error } } /** * Starts the task again (the provider cancels it, and rehydrates it) and checks that it was: `cancelTask` returns * without a word when there is no current task, or no history to rehydrate from. Resolves to what failed, if the restart * did. */ async function startTaskAgain( provider: ReturnType, task: Task, ): Promise<{ error: unknown } | undefined> { try { // Only the task that was restored is started again: if the user moved to another one while the rewind was being // written, cancelling would interrupt that one instead. if (provider && provider.getCurrentTask()?.taskId !== task.taskId) { throw new Error("the task is no longer the current one") } await provider?.cancelTask() const current = provider?.getCurrentTask() if (provider && (!current || current.taskId !== task.taskId || current.instanceId === task.instanceId)) { throw new Error("the task was not rehydrated") } return undefined } catch (error) { provider?.log( `[checkpointRestore] the task could not be started again: ${error instanceof Error ? error.message : String(error)}`, ) return { error } } } /** Rewinds the conversation to the checkpoint, and gives the usage of the requests that it deleted. */ async function rewindConversation( task: Task, ts: number, index: number, operation: "delete" | "edit", ): Promise { // Calculate metrics from messages that will be deleted (must be done before rewind) const deletedMessages = task.clineMessages.slice(index + 1) const { totalTokensIn, totalTokensOut, totalCacheWrites, totalCacheReads, totalCost } = getApiMetrics( task.combineMessages(deletedMessages), ) const messagesBefore = [...task.clineMessages] let failure: unknown try { // Use MessageManager to properly handle context-management events // This ensures orphaned Summary messages and truncation markers are cleaned up await task.messageManager.rewindToTimestamp(ts, { includeTargetMessage: operation === "edit", }) // 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 // retried, and a cut that cannot be stored is a failed rewind, not one that the restart would then undo silently. if (!(await task.ensureApiConversationHistoryStored())) { throw new Error("The API conversation history could not be saved") } } catch (error) { failure = error } if (failure !== undefined) { // The messages were cut first: when the API history could not follow, the two are not the same conversation, and the // task that is started again would show a conversation shorter than the one the model is given. The messages are put // back, so that both are what they were before the rewind. if (task.clineMessages.length !== messagesBefore.length) { try { await task.overwriteClineMessages(messagesBefore) } catch (restoreError) { const reason = failure instanceof Error ? failure.message : String(failure) const restoreReason = restoreError instanceof Error ? restoreError.message : String(restoreError) throw new ConversationPartlyRewoundError( `${reason}, and the messages could not be put back (${restoreReason}): the conversation is only partly rewound`, ) } } throw failure } return { tokensIn: totalTokensIn, tokensOut: totalTokensOut, cacheWrites: totalCacheWrites, cacheReads: totalCacheReads, cost: totalCost, } satisfies ClineApiReqInfo } export type CheckpointDiffOptions = { ts?: number previousCommitHash?: string commitHash: string /** * from-init: Compare from the first checkpoint to the selected checkpoint. * checkpoint: Compare the selected checkpoint to the next checkpoint. * to-current: Compare the selected checkpoint to the current workspace. * full: Compare from the first checkpoint to the current workspace. */ mode: "from-init" | "checkpoint" | "to-current" | "full" } export async function checkpointDiff(task: Task, { commitHash, mode }: CheckpointDiffOptions) { try { assertRecordedCheckpoint(task, commitHash) } catch (error) { void vscode.window.showErrorMessage(error instanceof Error ? error.message : String(error)) return } const service = await getCheckpointService(task) if (!service) { return } TelemetryService.instance.captureCheckpointDiffed(task.taskId) let fromHash: string | undefined let toHash: string | undefined let title: string const checkpoints = task.clineMessages.filter(({ say }) => say === "checkpoint_saved").map(({ text }) => text!) if (["from-init", "full"].includes(mode) && checkpoints.length < 1) { vscode.window.showInformationMessage(t("common:errors.checkpoint_no_first")) return } const idx = checkpoints.indexOf(commitHash) switch (mode) { case "checkpoint": fromHash = commitHash toHash = idx !== -1 && idx < checkpoints.length - 1 ? checkpoints[idx + 1] : undefined title = t("common:errors.checkpoint_diff_with_next") break case "from-init": fromHash = checkpoints[0] toHash = commitHash title = t("common:errors.checkpoint_diff_since_first") break case "to-current": fromHash = commitHash toHash = undefined title = t("common:errors.checkpoint_diff_to_current") break case "full": fromHash = checkpoints[0] toHash = undefined title = t("common:errors.checkpoint_diff_since_first") break } if (!fromHash) { vscode.window.showInformationMessage(t("common:errors.checkpoint_no_previous")) return } try { const changes = await service.getDiff({ from: fromHash, to: toHash }) if (!changes?.length) { vscode.window.showInformationMessage(t("common:errors.checkpoint_no_changes")) return } await vscode.commands.executeCommand( "vscode.changes", title, changes.map((change) => [ vscode.Uri.file(change.paths.absolute), vscode.Uri.parse(`${DIFF_VIEW_URI_SCHEME}:${change.paths.relative}`).with({ query: Buffer.from(change.content.before ?? "").toString("base64"), }), vscode.Uri.parse(`${DIFF_VIEW_URI_SCHEME}:${change.paths.relative}`).with({ query: Buffer.from(change.content.after ?? "").toString("base64"), }), ]), ) } catch { const provider = task.providerRef.deref() provider?.log("[checkpointDiff] disabling checkpoints for this task") task.enableCheckpoints = false } }