This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathindex.ts
More file actions
432 lines (360 loc) · 12.8 KB
/
Copy pathindex.ts
File metadata and controls
432 lines (360 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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"
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 (err) {
// 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,
) {
const service = await getCheckpointService(task)
if (!service) {
return
}
const index = task.clineMessages.findIndex((m) => m.ts === ts)
if (index === -1) {
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") {
// 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),
)
// 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",
})
// Report the deleted API request metrics
await task.say(
"api_req_deleted",
JSON.stringify({
tokensIn: totalTokensIn,
tokensOut: totalTokensOut,
cacheWrites: totalCacheWrites,
cacheReads: totalCacheReads,
cost: totalCost,
} satisfies ClineApiReqInfo),
)
}
// 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.
provider?.cancelTask()
} catch (err) {
provider?.log("[checkpointRestore] disabling checkpoints for this task")
task.enableCheckpoints = false
}
}
/**
* Restore the workspace to its initial state (baseHash) - the state when the shadow git repo was initialized.
* This is a simpler version of checkpointRestore that doesn't need to rewind messages since we're
* restoring to the very beginning of the task.
* @returns true if restoration was successful, false otherwise
*/
export async function checkpointRestoreToBase(task: Task): Promise<boolean> {
const service = await getCheckpointService(task)
if (!service) {
return false
}
const baseHash = service.baseHash
if (!baseHash) {
const provider = task.providerRef.deref()
provider?.log("[checkpointRestoreToBase] no baseHash available")
return false
}
const provider = task.providerRef.deref()
try {
await service.restoreCheckpoint(baseHash)
TelemetryService.instance.captureCheckpointRestored(task.taskId)
await provider?.postMessageToWebview({ type: "currentCheckpointUpdated", text: baseHash })
// Cancel the task to reinitialize with the restored state
// This follows the same pattern as checkpointRestore
provider?.cancelTask()
return true
} catch (err) {
provider?.log("[checkpointRestoreToBase] disabling checkpoints for this task")
task.enableCheckpoints = false
return false
}
}
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, { ts, previousCommitHash, commitHash, mode }: CheckpointDiffOptions) {
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 (err) {
const provider = task.providerRef.deref()
provider?.log("[checkpointDiff] disabling checkpoints for this task")
task.enableCheckpoints = false
}
}