Repository navigation
Expand file tree
/
Copy pathClineProvider.ts
More file actions
5594 lines (4999 loc) · 209 KB
/
Copy pathClineProvider.ts
File metadata and controls
5594 lines (4999 loc) · 209 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os from "os"
import * as path from "path"
import fs from "fs/promises"
import EventEmitter from "events"
import crypto from "crypto"
import { Anthropic } from "@anthropic-ai/sdk"
import delay from "delay"
import axios from "axios"
import debounce from "lodash.debounce"
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import {
WEBVIEW_RECOVERY_LIMITS,
preservesRecoveryIncident,
resolutionFailureAction,
canCommitRecovery,
nextRecoveryAttempt,
releaseRecoveryOwner,
pendingSidebarAfterCommandFailure,
recordRecoveryFailure,
recoveryHealth,
recoveryWarningAction,
isRecoveryGenerationCurrent,
beginExplicitRecovery,
} from "./webviewRecoveryPolicy"
import {
type TaskProviderLike,
type TaskProviderEvents,
type GlobalState,
type ProviderName,
type ProviderSettings,
type RooCodeSettings,
type ProviderSettingsEntry,
type StaticAppProperties,
type DynamicAppProperties,
type CloudAppProperties,
type TaskProperties,
type GitProperties,
type TelemetryProperties,
type TelemetryPropertiesProvider,
type CodeActionId,
type CodeActionName,
type TerminalActionId,
type TerminalActionPromptType,
type HistoryItem,
type PendingTaskAction,
type CloudUserInfo,
type CloudOrganizationMembership,
type CreateTaskOptions,
type TokenUsage,
type ToolUsage,
type ExtensionMessage,
type ExtensionState,
type WebviewThemeFixture,
type WebviewDiagnosticsSnapshot,
type MarketplaceInstalledMetadata,
RooCodeEventName,
requestyDefaultModelId,
openRouterDefaultModelId,
DEFAULT_WRITE_DELAY_MS,
DEFAULT_DIFF_FUZZY_THRESHOLD,
DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED,
DEFAULT_ALWAYS_DENY_UNAPPROVED_COMMANDS,
DEFAULT_COLLAPSE_COMMAND_OUTPUT_BY_DEFAULT,
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
DEFAULT_TASK_TITLE_GENERATION_ENABLED,
ORGANIZATION_ALLOW_ALL,
DEFAULT_MODES,
DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
getModelId,
isRetiredProvider,
modelIdKeys,
providerIdentifiers,
} from "@roo-code/types"
import { RateLimitClock, createRateLimitClock } from "../task/RateLimitClock"
import { TaskRegistry } from "../task/TaskRegistry"
import { TaskScheduler } from "../task/TaskScheduler"
import {
getEffectiveTaskApiConfiguration,
selectHandoffExecutionContext,
type TaskExecutionContext,
} from "../task/providerHandoff"
import { aggregateTaskCostsRecursive, type AggregatedCosts } from "./aggregateTaskCosts"
import { TelemetryService } from "@roo-code/telemetry"
import { CloudService, getRooCodeApiUrl } from "@roo-code/cloud"
import { Package } from "../../shared/package"
import { findLast } from "../../shared/array"
import { supportPrompt } from "../../shared/support-prompt"
import { GlobalFileNames } from "../../shared/globalFileNames"
import { Mode, defaultModeSlug, getModeBySlug } from "../../shared/modes"
import { experimentDefault } from "../../shared/experiments"
import { formatLanguage } from "../../shared/language"
import { WebviewMessage } from "../../shared/WebviewMessage"
import { EMBEDDING_MODEL_PROFILES } from "../../shared/embeddingModels"
import { ProfileValidator } from "../../shared/ProfileValidator"
import { Terminal } from "../../integrations/terminal/Terminal"
import { downloadTask, getTaskFileName } from "../../integrations/misc/export-markdown"
import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export"
import { getTheme } from "../../integrations/theme/getTheme"
import WorkspaceTracker from "../../integrations/workspace/WorkspaceTracker"
import { McpHub } from "../../services/mcp/McpHub"
import { McpServerManager } from "../../services/mcp/McpServerManager"
import { MarketplaceManager } from "../../services/marketplace"
import { ShadowCheckpointService } from "../../services/checkpoints/ShadowCheckpointService"
import { CodeIndexManagerRegistry } from "../../services/code-index/code-index-manager-registry"
import type { CodeIndexWorkspaceScope } from "../../services/code-index/code-index-workspace-scope"
import { MdmService } from "../../services/mdm/MdmService"
import { SkillsManager } from "../../services/skills/SkillsManager"
import {
DiagnosticsRecorder,
DiagnosticsRequestBroker,
type DiagnosticsProviderSourceSnapshot,
} from "../../services/diagnostics"
import { setTtsEnabled, setTtsSpeed } from "../../utils/tts"
import { getWorkspaceGitInfo } from "../../utils/git"
import { getWorkspacePath } from "../../utils/path"
import { OrganizationAllowListViolationError } from "../../utils/errors"
import { getPanel, setPanel } from "../../activate/registerCommands"
import { t } from "../../i18n"
import { buildApiHandler } from "../../api"
import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../api/providers/fetchers/lmstudio"
import { ContextProxy } from "../config/ContextProxy"
import { withoutInvalidDisplaySettings } from "../config/displaySettings"
import { ProviderSettingsManager } from "../config/ProviderSettingsManager"
import { CustomModesManager } from "../config/CustomModesManager"
import { PendingActionSettlementError, Task } from "../task/Task"
import { webviewMessageHandler } from "./webviewMessageHandler"
import type { WebviewFocusTracker } from "./WebviewFocusTracker"
import type { ClineMessage, TodoItem } from "@roo-code/types"
import {
type ApiMessage,
readApiMessages,
saveApiMessages,
saveTaskMessages,
TaskHistoryStore,
abandonDelegatedChild,
completeDelegatedChild,
delegateTaskToChild,
interruptDelegatedChild,
LifecycleTransitionError,
} from "../task-persistence"
import { readTaskMessages } from "../task-persistence/taskMessages"
import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry"
import { TaskTitleService } from "../task-title/TaskTitleService"
import { getNonce } from "./getNonce"
import { getUri } from "./getUri"
import { omitOriginalContentFromExtensionMessage } from "./stripOriginalContent"
import { REQUESTY_BASE_URL } from "../../shared/utils/requesty"
import { validateAndFixToolResultIds } from "../task/validateToolResultIds"
import { PendingEditOperationStore, type PendingEditOperationInput } from "./PendingEditOperationStore"
/**
* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
* https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts
*/
type DelegatedChildContext = TaskExecutionContext
function runDelegationTransition<T>(
locks: Map<string, Promise<void>>,
parentTaskId: string,
fn: () => Promise<T>,
): Promise<T> {
const previous = locks.get(parentTaskId) ?? Promise.resolve()
// Fail-forward: run fn even if the previous transition rejected. A failed
// cancelTask must not permanently block a subsequent reopenParentFromDelegation.
// The cancelledDelegationChildIds guard inside each fn is the safety net.
const current = previous.then(fn, fn)
const tail = current.then(
() => {},
() => {},
)
locks.set(parentTaskId, tail)
void tail.finally(() => {
if (locks.get(parentTaskId) === tail) {
locks.delete(parentTaskId)
}
})
return current
}
function scheduleTask(
scheduler: TaskScheduler,
task: Task,
source: string,
run: () => Promise<void> = () => task.run(),
onError?: (error: unknown) => void | Promise<void>,
): void {
void scheduler.schedule(task, run).catch(async (error) => {
console.error(`[${source}] taskScheduler.schedule failed:`, error)
try {
await onError?.(error)
} catch (cleanupError) {
console.error(`[${source}] task failure cleanup failed:`, cleanupError)
}
})
}
// Keys a model-selector patch may touch: model IDs plus settings reset on model change.
const PROFILE_MODEL_ID_PATCH_KEYS: ReadonlySet<string> = new Set(modelIdKeys)
const BEDROCK_CUSTOM_ARN_MODEL_ID = "custom-arn"
// These keys can only be cleared. Setting `awsCustomArn` would let a patch invoke a Bedrock
// resource that the organization allow-list never checked, because the allow-list sees `apiModelId`.
const PROFILE_MODEL_RESET_ONLY_KEYS: ReadonlySet<string> = new Set([
"reasoningEffort",
"modelMaxTokens",
"modelMaxThinkingTokens",
"awsCustomArn",
"awsCustomArnBaseModelId",
"awsModelContextWindow",
])
type GetStateOptions = {
includeTaskHistory?: boolean
}
function removeTaskEventListeners(listeners: WeakMap<Task, Array<() => void>>, task: Task): void {
const cleanupFunctions = listeners.get(task)
if (cleanupFunctions) {
cleanupFunctions.forEach((cleanup) => cleanup())
listeners.delete(task)
}
}
export class ClineProvider
extends EventEmitter<TaskProviderEvents>
implements vscode.WebviewViewProvider, TelemetryPropertiesProvider, TaskProviderLike
{
// Used in package.json as the view's id. This value cannot be changed due
// to how VSCode caches views based on their id, and updating the id would
// break existing instances of the extension.
public static readonly sideBarId = `${Package.name}.SidebarProvider`
public static readonly tabPanelId = `${Package.name}.TabPanelProvider`
private static activeInstances: Set<ClineProvider> = new Set()
private webviewDisposables: vscode.Disposable[] = []
private pendingThemeFixtureProbes = new Map<
string,
{
resolve: (fixture: WebviewThemeFixture) => void
reject: (error: Error) => void
timeout: ReturnType<typeof setTimeout>
}
>()
private nextThemeFixtureProbeId = 0
private view?: vscode.WebviewView | vscode.WebviewPanel
private taskRegistry = new TaskRegistry()
private taskScheduler = new TaskScheduler()
private static readonly delegationTransitionLocks = new Map<string, Promise<void>>()
private cancelledDelegationChildIds = new Set<string>()
private _workspaceTracker?: WorkspaceTracker // workSpaceTracker read-only for access outside this class
protected mcpHub?: McpHub // Change from private to protected
protected skillsManager?: SkillsManager
private marketplaceManager: MarketplaceManager
private mdmService?: MdmService
private taskCreationCallback: (task: Task) => void
private taskEventListeners: WeakMap<Task, Array<() => void>> = new WeakMap()
private currentWorkspacePath: string | undefined
private _disposed = false
private lastWebviewHeartbeatAt = 0
// Bumped on every heartbeat or grace reset, including events in the same
// millisecond; pending recovery must yield to either sign of renewed grace.
private webviewHeartbeatRevision = 0
private webviewRecoveryAttempts = 0
private webviewRecoveryConfirmation: ReturnType<typeof setTimeout> | undefined
private webviewHostRecoveryInProgress = false
// VS Code may resolve the focused sidebar after our bounded wait expires.
// Keep that repair distinct from a user-opened view until it arrives.
private pendingSidebarRecovery = false
private webviewRecoveryFailureReported = false
private webviewRecoveryStopLogged = false
private lastReceivedWebviewHeartbeatAt: number | undefined
private webviewHeartbeatCount = 0
private webviewHealthySince: number | undefined
private static readonly WEBVIEW_RECOVERY_CONFIRM_MS = 10_000
private static readonly WEBVIEW_RECOVERY_ATTEMPT_LIMIT = WEBVIEW_RECOVERY_LIMITS.attempts
private webviewWatchdogInterval: ReturnType<typeof setInterval> | null = null
// Bumped to invalidate an in-flight recovery reload when the provider or
// the watched view is disposed; the reload must not reassign webview.html
// afterwards.
private webviewRecoveryEpoch = 0
private webviewRecoveryRequestGeneration = 0
// Epoch that owns an in-flight recovery reload, if any. Only a recovery
// from the same epoch is blocked, so disposing/replacing the view (which
// bumps webviewRecoveryEpoch) never makes the replacement wait on the
// stale recovery's completion.
private webviewRecoveryInFlightEpoch: number | undefined = undefined
// Wall-clock reading of the previous watchdog tick; a tick arriving far
// later than scheduled means the host slept, so the grace window restarts
// instead of counting the suspended interval against a live renderer.
private lastWebviewWatchdogTickAt = 0
private static readonly WEBVIEW_WATCHDOG_TICK_MS = 60_000
private static readonly WEBVIEW_HEARTBEAT_STALE_MS = WEBVIEW_RECOVERY_LIMITS.staleMs
private readonly _postStateToWebviewThrottled = debounce(
async () => {
try {
await this.postStateToWebviewWithoutTaskHistory()
} catch (error) {
this.log(
`[ClineProvider#postStateToWebviewThrottled] Failed to post state: ${
error instanceof Error ? error.message : String(error)
}`,
)
}
},
500,
{ leading: true, trailing: true, maxWait: 1000 },
)
private readonly diagnosticsRecorder = new DiagnosticsRecorder(200)
private readonly diagnosticsRequestBroker = new DiagnosticsRequestBroker()
private readonly rateLimitClock: RateLimitClock = createRateLimitClock()
private recentTasksCache?: string[]
public readonly taskHistoryStore: TaskHistoryStore
private readonly taskTitleService: TaskTitleService
private taskHistoryStoreInitialized = false
public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds
private providerProfileMutationQueue = Promise.resolve()
private historyTaskCreationQueue = Promise.resolve()
private runDelegationTransition<T>(parentTaskId: string, fn: () => Promise<T>): Promise<T> {
return runDelegationTransition(ClineProvider.delegationTransitionLocks, parentTaskId, fn)
}
/**
* With `runToCompletion`, a timeout only rejects the caller: the mutation is not aborted and the
* queue advances once it settles. Use it for multi-write mutations that must not stop halfway
* (storage saved but not activated) or overlap with the next mutation.
*/
private enqueueProviderProfileMutation<T>(
fn: (signal: AbortSignal) => Promise<T>,
options: { runToCompletion?: boolean } = {},
): Promise<T> {
const controller = new AbortController()
// Run fn after either outcome so a rejected mutation never poisons the queue.
const run = this.providerProfileMutationQueue.then(
() => fn(controller.signal),
() => fn(controller.signal),
)
const callerResult = this.withProviderProfileMutationTimeout(run, () => {
if (options.runToCompletion) {
this.log("Provider profile mutation timed out; waiting for it to finish before the next mutation")
return
}
controller.abort()
this.log("Provider profile mutation timed out; aborting in-flight mutation")
})
void run.then(
() => {
if (controller.signal.aborted) {
this.log("Provider profile mutation completed after cancellation")
}
},
(error) => {
if (controller.signal.aborted) {
this.log(
`Provider profile mutation errored after cancellation: ${
error instanceof Error ? error.message : String(error)
}`,
)
}
},
)
// Advance from the timeout-bounded result. Each fn checks its AbortSignal before
// writing state, so advancing the queue on timeout cannot produce stale overwrites.
this.providerProfileMutationQueue = (options.runToCompletion ? run : callerResult).then(
() => undefined,
() => undefined,
)
return callerResult
}
private withProviderProfileMutationTimeout<T>(operation: Promise<T>, onTimeout: () => void): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
onTimeout()
reject(new Error("Provider profile mutation timed out"))
}, ClineProvider.PENDING_OPERATION_TIMEOUT_MS)
})
return Promise.race([operation, timeout]).finally(() => {
if (timeoutId) {
clearTimeout(timeoutId)
}
})
}
private readonly pendingEditOperations: PendingEditOperationStore
private cloudOrganizationsCache: CloudOrganizationMembership[] | null = null
private cloudOrganizationsCacheTimestamp: number | null = null
private static readonly CLOUD_ORGANIZATIONS_CACHE_DURATION_MS = 5 * 1000 // 5 seconds
/**
* Monotonically increasing sequence number for clineMessages state pushes.
* Used by the frontend to reject stale state that arrives out-of-order.
*/
private clineMessagesSeq = 0
public isViewLaunched = false
public settingsImportedAt?: number
public readonly latestAnnouncementId = "nov-2026-v3.98.0-titles-models-reliability" // v3.98.0 task titles, model support, and reliability
public readonly providerSettingsManager: ProviderSettingsManager
public readonly customModesManager: CustomModesManager
/**
* Mode -> profile id choices made by this window. The persisted mode map in
* `providerSettingsManager` is shared by every VS Code window, so reading it
* alone lets another window's profile selection leak into this window's tasks.
*/
private readonly localModeConfigIds = new Map<string, string>()
/**
* The shared mode map as it was when this window opened. Modes this window has not changed
* resolve against it, so another window's later selection cannot reach this window's tasks
* (including delegated subtasks).
*/
private initialModeConfigIds: Promise<Record<string, string>> = Promise.resolve({})
constructor(
readonly context: vscode.ExtensionContext,
private readonly outputChannel: vscode.OutputChannel,
private readonly renderContext: "sidebar" | "editor" = "sidebar",
public readonly contextProxy: ContextProxy,
public readonly webviewFocusTracker: WebviewFocusTracker,
mdmService?: MdmService,
) {
super()
this.currentWorkspacePath = getWorkspacePath()
this.pendingEditOperations = new PendingEditOperationStore(
ClineProvider.PENDING_OPERATION_TIMEOUT_MS,
(message) => this.log(message),
)
ClineProvider.activeInstances.add(this)
this.diagnosticsRecorder.record({ boundary: "provider", phase: "success", type: "created" })
this.mdmService = mdmService
void this.updateGlobalState("codebaseIndexModels", EMBEDDING_MODEL_PROFILES)
// Initialize the authoritative per-task file-based history store.
this.taskHistoryStore = new TaskHistoryStore(this.contextProxy.globalStorageUri.fsPath)
this.initializeTaskHistoryStore().catch((error) => {
this.log(`Failed to initialize TaskHistoryStore: ${error}`)
})
this.taskTitleService = new TaskTitleService({
getHistoryItem: (taskId) => this.taskHistoryStore.get(taskId),
setAutoTitle: (taskId, autoTitle) => this.setAutoTitle(taskId, autoTitle),
getSettings: async () => {
const { taskTitleGenerationEnabled, taskTitleApiConfigId, customSupportPrompts } = await this.getState({
includeTaskHistory: false,
})
return {
enabled: taskTitleGenerationEnabled ?? DEFAULT_TASK_TITLE_GENERATION_ENABLED,
apiConfigId: taskTitleApiConfigId,
customSupportPrompts,
}
},
resolveProfile: async (apiConfigId) => {
const { listApiConfigMeta = [] } = await this.getState({ includeTaskHistory: false })
if (!listApiConfigMeta.some(({ id }) => id === apiConfigId)) {
return undefined
}
const { name: _name, ...profile } = await this.providerSettingsManager.getProfile({ id: apiConfigId })
return profile.apiProvider ? profile : undefined
},
isProfileAllowed: async (profile) => {
const { organizationAllowList } = await this.getState({ includeTaskHistory: false })
return ProfileValidator.isProfileAllowed(profile, organizationAllowList)
},
log: (message) => this.log(message),
})
// Start configuration loading (which might trigger indexing) in the background.
// Don't await, allowing activation to continue immediately.
// Register this provider with the telemetry service to enable it to add
// properties like mode and provider.
TelemetryService.instance.setProvider(this)
this._workspaceTracker = new WorkspaceTracker(this)
this.providerSettingsManager = new ProviderSettingsManager(this.context, (modeConfigIds) => {
// Manual and automatic imports replace this provider's previous mode choices.
this.localModeConfigIds.clear()
this.initialModeConfigIds = Promise.resolve(modeConfigIds)
})
this.captureInitialModeConfigIds()
this.customModesManager = new CustomModesManager(this.context, async () => {
await this.postStateToWebviewWithoutClineMessages()
})
// Initialize MCP Hub through the singleton manager
McpServerManager.getInstance(this.context, this)
.then((hub) => {
this.mcpHub = hub
this.mcpHub.registerClient()
})
.catch((error) => {
this.log(`Failed to initialize MCP Hub: ${error}`)
})
// Initialize Skills Manager for skill discovery
this.skillsManager = new SkillsManager(this)
this.skillsManager.initialize().catch((error) => {
this.log(`Failed to initialize Skills Manager: ${error}`)
})
this.marketplaceManager = new MarketplaceManager(this.context, this.customModesManager)
// Forward <most> task events to the provider.
// We do something fairly similar for the IPC-based API.
this.taskCreationCallback = (instance: Task) => {
this.emit(RooCodeEventName.TaskCreated, instance)
this.taskTitleService.onTaskCreated(instance)
// Create named listener functions so we can remove them later.
const onTaskStarted = () => this.emit(RooCodeEventName.TaskStarted, instance.taskId)
const onTaskCompleted = async (taskId: string, tokenUsage: TokenUsage, toolUsage: ToolUsage) => {
// Explicitly transition the task to "completed" so that any prior terminal
// status (e.g. "interrupted" from a previous cancel) is correctly overwritten.
// saveClineMessages() omits the status field for top-level tasks, which causes
// the store's merge to preserve a stale "interrupted" status after completion.
// interrupted → completed is a valid VALID_TRANSITIONS path.
try {
const existing = this.taskHistoryStore.get(taskId)
if (existing && existing.status !== "completed") {
await this.updateTaskHistory({ ...existing, status: "completed" })
}
} catch (err) {
this.log(
`[onTaskCompleted] Failed to write completed status for ${taskId}: ${err instanceof Error ? err.message : String(err)}`,
)
}
this.emit(RooCodeEventName.TaskCompleted, taskId, tokenUsage, toolUsage)
}
const onTaskAborted = () => {
if (instance.abortReason === "user_cancelled") {
this.taskTitleService.cancel(instance.taskId, "user")
}
this.emit(RooCodeEventName.TaskAborted, instance.taskId)
}
const onTaskFocused = () => this.emit(RooCodeEventName.TaskFocused, instance.taskId)
const onTaskUnfocused = () => this.emit(RooCodeEventName.TaskUnfocused, instance.taskId)
const onTaskActive = (taskId: string) => this.emit(RooCodeEventName.TaskActive, taskId)
const onTaskInteractive = (taskId: string) => this.emit(RooCodeEventName.TaskInteractive, taskId)
const onTaskResumable = (taskId: string) => this.emit(RooCodeEventName.TaskResumable, taskId)
const onTaskIdle = (taskId: string) => this.emit(RooCodeEventName.TaskIdle, taskId)
const onTaskPaused = (taskId: string) => this.emit(RooCodeEventName.TaskPaused, taskId)
const onTaskUnpaused = (taskId: string) => this.emit(RooCodeEventName.TaskUnpaused, taskId)
const onTaskSpawned = (taskId: string) => this.emit(RooCodeEventName.TaskSpawned, taskId)
const onTaskUserMessage = (taskId: string) => this.emit(RooCodeEventName.TaskUserMessage, taskId)
const onTaskTokenUsageUpdated = (taskId: string, tokenUsage: TokenUsage, toolUsage: ToolUsage) => {
this.taskTitleService.onTokenUsageUpdated(taskId, tokenUsage)
this.emit(RooCodeEventName.TaskTokenUsageUpdated, taskId, tokenUsage, toolUsage)
}
// Attach the listeners.
instance.on(RooCodeEventName.TaskStarted, onTaskStarted)
instance.on(RooCodeEventName.TaskCompleted, onTaskCompleted)
instance.on(RooCodeEventName.TaskAborted, onTaskAborted)
instance.on(RooCodeEventName.TaskFocused, onTaskFocused)
instance.on(RooCodeEventName.TaskUnfocused, onTaskUnfocused)
instance.on(RooCodeEventName.TaskActive, onTaskActive)
instance.on(RooCodeEventName.TaskInteractive, onTaskInteractive)
instance.on(RooCodeEventName.TaskResumable, onTaskResumable)
instance.on(RooCodeEventName.TaskIdle, onTaskIdle)
instance.on(RooCodeEventName.TaskPaused, onTaskPaused)
instance.on(RooCodeEventName.TaskUnpaused, onTaskUnpaused)
instance.on(RooCodeEventName.TaskSpawned, onTaskSpawned)
instance.on(RooCodeEventName.TaskUserMessage, onTaskUserMessage)
instance.on(RooCodeEventName.TaskTokenUsageUpdated, onTaskTokenUsageUpdated)
// Store the cleanup functions for later removal.
this.taskEventListeners.set(instance, [
() => instance.off(RooCodeEventName.TaskStarted, onTaskStarted),
() => instance.off(RooCodeEventName.TaskCompleted, onTaskCompleted),
() => instance.off(RooCodeEventName.TaskAborted, onTaskAborted),
() => instance.off(RooCodeEventName.TaskFocused, onTaskFocused),
() => instance.off(RooCodeEventName.TaskUnfocused, onTaskUnfocused),
() => instance.off(RooCodeEventName.TaskActive, onTaskActive),
() => instance.off(RooCodeEventName.TaskInteractive, onTaskInteractive),
() => instance.off(RooCodeEventName.TaskResumable, onTaskResumable),
() => instance.off(RooCodeEventName.TaskIdle, onTaskIdle),
() => instance.off(RooCodeEventName.TaskUserMessage, onTaskUserMessage),
() => instance.off(RooCodeEventName.TaskPaused, onTaskPaused),
() => instance.off(RooCodeEventName.TaskUnpaused, onTaskUnpaused),
() => instance.off(RooCodeEventName.TaskSpawned, onTaskSpawned),
() => instance.off(RooCodeEventName.TaskTokenUsageUpdated, onTaskTokenUsageUpdated),
() => this.taskTitleService.forget(instance.taskId),
])
}
}
/**
* Initialize the TaskHistoryStore and migrate from globalState if needed.
*/
private async initializeTaskHistoryStore(): Promise<void> {
const startedAt = Date.now()
this.diagnosticsRecorder.record({ boundary: "task-history", phase: "start", type: "initialize" })
try {
await this.taskHistoryStore.initialize()
// Migration: backfill per-task files from globalState on first run
const migrationKey = "taskHistoryMigratedToFiles"
const alreadyMigrated = this.context.globalState.get<boolean>(migrationKey)
if (!alreadyMigrated) {
const legacyHistory = this.context.globalState.get<HistoryItem[]>("taskHistory") ?? []
if (legacyHistory.length > 0) {
this.log(`[initializeTaskHistoryStore] Migrating ${legacyHistory.length} entries from globalState`)
await this.taskHistoryStore.migrateFromGlobalState(legacyHistory)
}
await this.context.globalState.update(migrationKey, true)
this.log("[initializeTaskHistoryStore] Migration complete")
}
this.taskHistoryStoreInitialized = true
this.diagnosticsRecorder.record({
boundary: "task-history",
phase: "success",
type: "initialize",
elapsedMs: Date.now() - startedAt,
})
} catch (error) {
this.diagnosticsRecorder.record({
boundary: "task-history",
phase: "failure",
type: "initialize",
elapsedMs: Date.now() - startedAt,
})
this.log(`[initializeTaskHistoryStore] Error: ${error instanceof Error ? error.message : String(error)}`)
}
}
/**
* Override EventEmitter's on method to match TaskProviderLike interface
*/
override on<K extends keyof TaskProviderEvents>(
event: K,
listener: (...args: TaskProviderEvents[K]) => void | Promise<void>,
): this {
return super.on(event, listener as any)
}
/**
* Override EventEmitter's off method to match TaskProviderLike interface
*/
override off<K extends keyof TaskProviderEvents>(
event: K,
listener: (...args: TaskProviderEvents[K]) => void | Promise<void>,
): this {
return super.off(event, listener as any)
}
/**
* Handle cloud settings updates
*/
private handleCloudSettingsUpdate = async () => {
this.log("Ignoring cloud settings update because cloud profile synchronization is disabled")
}
/**
* Initialize cloud profile synchronization when CloudService is ready
* This method is called externally after CloudService has been initialized
*/
public async initializeCloudProfileSyncWhenReady(): Promise<void> {
this.log("Cloud profile synchronization is disabled in compatibility mode")
}
// Adds a new Task instance to the registry, marking the start of a new task.
// The instance is pushed to the top of the stack (LIFO order).
// When the task is completed, the top instance is removed, reactivating the
// previous task.
async addClineToStack(task: Task) {
// Add this cline instance into the stack that represents the order of
// all the called tasks.
this.taskRegistry.push(task)
task.emit(RooCodeEventName.TaskFocused)
// Perform special setup provider specific tasks.
await this.performPreparationTasks(task)
// Ensure getState() resolves correctly.
const state = await this.getState()
if (!state || typeof state.mode !== "string") {
throw new Error(t("common:errors.retrieve_current_mode"))
}
}
async performPreparationTasks(cline: Task) {
// LMStudio: We need to force model loading in order to read its context
// size; we do it now since we're starting a task with that model selected.
if (cline.apiConfiguration && cline.apiConfiguration.apiProvider === providerIdentifiers.lmstudio) {
try {
if (!hasLoadedFullDetails(cline.apiConfiguration.lmStudioModelId!)) {
await forceFullModelDetailsLoad(
cline.apiConfiguration.lmStudioBaseUrl ?? "http://localhost:1234",
cline.apiConfiguration.lmStudioModelId!,
buildApiHandler({ ...cline.apiConfiguration, apiProvider: providerIdentifiers.lmstudio }),
)
}
} catch (error) {
this.log(`Failed to load full model details for LM Studio: ${error}`)
vscode.window.showErrorMessage(error.message)
}
}
}
// Removes and destroys the top Cline instance (the current finished task),
// activating the previous one (resuming the parent task).
async removeClineFromStack() {
if (this.taskRegistry.length === 0) {
return
}
// Remove the focused Cline instance from the stack.
let task = this.taskRegistry.current
if (task) {
task = this.taskRegistry.remove(task.taskId)
}
if (task) {
task.emit(RooCodeEventName.TaskUnfocused)
try {
// Abort the running task and set isAbandoned to true so
// all running promises will exit as well.
await task.abortTask(true)
} catch (e) {
this.log(
`[ClineProvider#removeClineFromStack] abortTask() failed ${task.taskId}.${task.instanceId}: ${e.message}`,
)
}
// Remove event listeners before clearing the reference.
const cleanupFunctions = this.taskEventListeners.get(task)
if (cleanupFunctions) {
cleanupFunctions.forEach((cleanup) => cleanup())
this.taskEventListeners.delete(task)
}
// Make sure no reference kept, once promises end it will be
// garbage collected.
task = undefined
}
}
private async cleanupFailedHistoryTask(task: Task, error: unknown): Promise<void> {
if (!(error instanceof PendingActionSettlementError)) {
return
}
if (this.taskRegistry.getById(task.taskId) !== task) {
return
}
this.taskRegistry.remove(task.taskId)
task.emit(RooCodeEventName.TaskUnfocused)
removeTaskEventListeners(this.taskEventListeners, task)
try {
await task.dispose()
} catch (error) {
this.log(
`[cleanupFailedHistoryTask] dispose() failed for ${task.taskId}.${task.instanceId}: ${error instanceof Error ? error.message : String(error)}`,
)
}
}
/**
* Evicts the current task from the stack and, if it was an active delegated child,
* marks it interrupted so the parent stays delegated (rather than silently losing the link).
*
* Use this in place of bare removeClineFromStack() at any call site that is not itself
* part of a delegation transition (i.e. everywhere except delegateParentAndOpenChild,
* createTask with a parentTask, and reopenParentFromDelegation).
*/
public async evictCurrentTask(): Promise<void> {
const current = this.getCurrentTask()
const storedHistory = current ? this.taskHistoryStore.get(current.taskId) : undefined
await this.removeClineFromStack()
if (storedHistory?.status === "active" && storedHistory.parentTaskId) {
await this.markDelegatedChildInterrupted({
childTaskId: storedHistory.id,
parentTaskId: storedHistory.parentTaskId,
})
}
}
/**
* Marks a live delegated child as "interrupted" when it is evicted without completing
* (e.g. user hits + for a new task, or navigates away while the child is still active).
*
* This preserves the delegation link — the parent stays "delegated" with awaitingChildId
* intact — so the user can later resume or abandon the interrupted child. It is the live-
* eviction counterpart to cancelTask()'s interruption path and to reopenParentFromDelegation()
* (which handles normal child completion).
*
* Must be called AFTER removeClineFromStack() so the live Task's final saveClineMessages()
* does not reattach the child's parentTaskId/rootTaskId over the interrupted status.
*/
private async markDelegatedChildInterrupted({
childTaskId,
parentTaskId,
}: {
childTaskId: string
parentTaskId: string
}): Promise<void> {
// Fast path: already interrupted (cancelTask beat us to it), nothing to do.
if (this.taskHistoryStore.get(childTaskId)?.status === "interrupted") {
this.log(`[markDelegatedChildInterrupted] Child ${childTaskId} already interrupted — skipping`)
return
}
try {
await this.runDelegationTransition(parentTaskId, async () => {
const { historyItem: parentHistory } = await this.getTaskWithId(parentTaskId)
if (parentHistory?.status !== "delegated" || parentHistory?.awaitingChildId !== childTaskId) {
this.log(
`[markDelegatedChildInterrupted] Parent ${parentTaskId} no longer delegated to child ${childTaskId} — skipping`,
)
return
}
// Prefer the in-memory store entry: it is written by delegateParentAndOpenChild
// with the correct parentTaskId before the child saves its first message.
// getTaskWithId reads from disk and may return an incomplete record (missing
// parentTaskId) if the child was evicted before its first saveClineMessages().
const childHistory =
this.taskHistoryStore.get(childTaskId) ?? (await this.getTaskWithId(childTaskId)).historyItem
// Re-check inside the lock to close the TOCTOU window with cancelTask() or
// a concurrent completion. Only proceed when the child is still "active";
// any other terminal status (interrupted, completed) must not be overwritten.
if (childHistory?.status !== "active") {
this.log(
`[markDelegatedChildInterrupted] Child ${childTaskId} is no longer active (status=${childHistory?.status}) — skipping`,
)
return
}
const interruptedChild = interruptDelegatedChild(parentHistory, childHistory)
await this.updateTaskHistory(interruptedChild)
await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: interruptedChild })
await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: parentHistory })
this.log(
`[markDelegatedChildInterrupted] Marked child ${childTaskId} interrupted; parent ${parentTaskId} stays delegated`,
)
})
} catch (err) {
this.log(
`[markDelegatedChildInterrupted] Failed for child ${childTaskId}: ${err instanceof Error ? err.message : String(err)}`,
)
}
}
getTaskStackSize(): number {
return this.taskRegistry.length
}
public getCurrentTaskStack(): string[] {
return this.taskRegistry.taskIds
}
public async setPendingTaskAction(taskId: string, pendingAction: PendingTaskAction): Promise<void> {
await this.taskHistoryStore.atomicReadAndUpdate(taskId, (historyItem) => ({
...historyItem,
pendingAction,
}))
this.recentTasksCache = undefined
}
public async clearPendingTaskAction(taskId: string, actionId: string): Promise<boolean> {
let cleared = false
try {
await this.taskHistoryStore.atomicReadAndUpdate(taskId, (historyItem) => {
if (historyItem.pendingAction?.actionId !== actionId) {
return historyItem
}
cleared = true
return { ...historyItem, pendingAction: undefined }
})
} catch (error) {
if (
error instanceof Error &&
error.message === `[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache`
) {
return false
}
throw error
}
if (cleared) {
this.recentTasksCache = undefined
}
return cleared
}
// Pending Edit Operations Management
/**
* Sets a pending edit operation with automatic timeout cleanup
*/
public setPendingEditOperation(operationId: string, editData: PendingEditOperationInput): object {
return this.pendingEditOperations.set(operationId, editData)
}
/**
* Gets a pending edit operation by ID
*/
private getPendingEditOperation(operationId: string) {
return this.pendingEditOperations.get(operationId)
}
/**
* Clears a specific pending edit operation
*/
public clearPendingEditOperation(operationId: string, owner?: object): boolean {
return this.pendingEditOperations.clear(operationId, owner)
}
/**
* Clears all pending edit operations
*/
private clearAllPendingEditOperations(): void {
this.pendingEditOperations.clearAll()
}
/*
VSCode extensions use the disposable pattern to clean up resources when the sidebar/editor tab is closed by the user or system. This applies to event listening, commands, interacting with the UI, etc.
- https://vscode-docs.readthedocs.io/en/stable/extensions/patterns-and-principles/
- https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
*/
private clearWebviewResources() {
this.rejectPendingThemeFixtureProbes(new Error("Webview was disposed before the theme fixture probe completed"))
this.stopWebviewWatchdog()
// Invalidate any recovery reload still awaiting its HTML so it cannot
// reassign webview.html on the disposed view.
this.webviewRecoveryEpoch++
// User-opened replacements get a fresh budget; recreating a failed host
// must preserve its incident budget so crash loops remain bounded.
if (!preservesRecoveryIncident(this.webviewHostRecoveryInProgress, this.pendingSidebarRecovery)) {
this.webviewRecoveryAttempts = 0
this.webviewRecoveryFailureReported = false
this.webviewRecoveryStopLogged = false
}
this.lastReceivedWebviewHeartbeatAt = undefined
this.webviewHealthySince = undefined
while (this.webviewDisposables.length) {
const x = this.webviewDisposables.pop()
if (x) {
x.dispose()
}
}
}
/**
* True when an in-flight resolve no longer belongs to the provider's current
* view because the view was disposed or replaced (or the provider itself was
* disposed) while the resolve was awaiting HTML or state hydration.
*/
private isStaleViewResolve(webviewView: vscode.WebviewView | vscode.WebviewPanel, epoch: number): boolean {
return this._disposed || this.view !== webviewView || epoch !== this.webviewRecoveryEpoch
}
/** Drain one task's memoized cleanup without preventing the remaining provider shutdown work. */
private async drainTaskDisposal(task: Task): Promise<void> {
try {
await task.dispose()
} catch (error) {