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 deepEqual from "fast-deep-equal" 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 ProviderSettingsWithId, 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, PROVIDER_SETTINGS_KEYS, viewStateSchema, } 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, hashDistinctId } 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 { generatedSegments, joinSegments } from "../../shared/mentionSegments" 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, ProviderSettingsNotFoundError } 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, MentionSegment, 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" type PersistedViewState = NonNullable[string] /** * What a failed profile deletion still owes on a view pin a newer deletion is holding: the value * the earlier deletion read before it re-pointed the entry, the claim that value belonged to, and * the token of the deletion whose claim is blocking the unwind. */ type DeferredViewPinRollback = { awaitingOwner: symbol entry: PersistedViewState hadPriorClaim: boolean priorClaim: symbol | undefined } /** * A deferred pin rollback a blocking deletion discharged: the view it applies to and the claim its * restored value belonged to before the first deletion moved the pin. */ type DischargedViewPinRollback = { viewId: string hadPriorClaim: boolean priorClaim: symbol | undefined } /** * Values that can be held in a view-local state buffer (in-memory) and, for the * non-secret subset, persisted durably per stable view id. */ type ViewLocalStateValues = Partial & Partial /** * 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( locks: Map>, parentTaskId: string, fn: () => Promise, ): Promise { 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 = () => task.run(), onError?: (error: unknown) => void | Promise, ): 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 = 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 = new Set([ "reasoningEffort", "modelMaxTokens", "modelMaxThinkingTokens", "awsCustomArn", "awsCustomArnBaseModelId", "awsModelContextWindow", ]) type GetStateOptions = { includeTaskHistory?: boolean } /** * What one `ClineProvider.setValues` call found in each persistence layer at its own write * group: `shared` is what the shared store held and `view` is what this view's record held, * both over exactly the keys that call wrote. The two layers can hold different values, so a * caller that compensates a later failure restores each layer from its own report. */ export type SettingsWriteOutcome = { shared: RooCodeSettings view: RooCodeSettings } /** * What one sibling re-pin moved inside that view's own live state, captured by the re-pin itself * after the queued name check and immediately before it wrote. The deletion compensation replays * exactly these values when a sibling failure rolls the deletion back, so a view whose callback had * already started writing when the mutation timed out is restored from what it itself read, and a * view that changed its own state between the deletion reading the pins and this re-pin committing * is restored from what was there when the re-pin ran rather than from the earlier snapshot. * A view whose live pin is no longer the one this deletion wrote is left alone: that view chose a * profile of its own after the re-pin, and the newer choice wins. */ type SiblingProfileRePinLiveChange = { instance: ClineProvider /** The profile this view pinned before the re-pin; undefined when it followed the shared selection. */ previousPin: string | undefined /** This view's own settings overlay before the re-pin, undefined when it had none. */ previousSettings: ProviderSettings | undefined /** The replacement name the re-pin wrote: the replay applies only while the view still holds it. */ appliedPin: string /** Set only when the re-pin also re-pointed a task that ran under the deleted profile. */ task: | { taskId: string; previousName: string; appliedName: string; previousSettings: ProviderSettings | undefined } | undefined } function removeTaskEventListeners(listeners: WeakMap void>>, task: Task): void { const cleanupFunctions = listeners.get(task) if (cleanupFunctions) { cleanupFunctions.forEach((cleanup) => cleanup()) listeners.delete(task) } } export class ClineProvider extends EventEmitter 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 = new Set() private static nextViewId = 0 private static readonly MAX_PERSISTED_VIEW_STATES = 50 private static readonly MAX_VIEW_STATE_ID_LENGTH = 64 /** * Pin-write claims keyed by the persisted view id, mirroring durableViewPinWriteOwner below. * The per-instance field dies with the view while the durable entry it stakes does not: a * profile-deletion rollback that runs after that view closed has nothing else to consult, and * matching on the stored profile name then matches the name that deletion itself wrote into the * entry. Only the write path that commits a write naming a profile records here, so a pin this * deletion moved for a view that was already gone stays unrecorded and the profile-name rule * still decides it: a closed view that never selected a profile of its own can still be rolled * back. Undefined is a recorded value, not the absence of one - a view that selected for itself * cleared its claim, and that has to stay readable after the view goes away. */ private static readonly durableViewPinWriteOwnersByViewId = new Map() /** * Rollback obligations an earlier profile deletion left on a pin a newer deletion still holds. * A rollback that finds its own re-pointed name gone cannot undo that pin yet - a newer deletion * moved it on - but the pin must not stay on that newer replacement once the newer deletion rolls * back either: a failed deletion has to leave a pin at the value it held before the first deletion * moved it. The obligation records what the earlier deletion still owes, keyed by the persisted * view id the same way the write claims are, and the deletion the claim names discharges it inside * its own restore write, so overlapping failed deletions unwind a pin one step per failed deletion * instead of stopping at the last replacement. A claim a user wrote is not a blocking deletion: a * newer selection owns that pin for good, so nothing is owed for it, and an obligation already * waiting on a view is dropped the moment a different writer claims it - the writer it waited on no * longer controls the pin. */ private static readonly deferredViewPinRollbacksByViewId = new Map() private static persistedViewStateWriteQueue: Promise = Promise.resolve() private disposables: vscode.Disposable[] = [] private webviewDisposables: vscode.Disposable[] = [] private pendingThemeFixtureProbes = new Map< string, { resolve: (fixture: WebviewThemeFixture) => void reject: (error: Error) => void timeout: ReturnType } >() private nextThemeFixtureProbeId = 0 private view?: vscode.WebviewView | vscode.WebviewPanel private taskRegistry = new TaskRegistry() private taskScheduler = new TaskScheduler() private static readonly delegationTransitionLocks = new Map>() private cancelledDelegationChildIds = new Set() 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 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 | 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 | 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(parentTaskId: string, fn: () => Promise): Promise { 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. * * Without it a timeout CANCELS the mutation: a callback that had not started yet never starts, and * one that had already started is aborted through the signal. `settled` resolves once this mutation * can no longer write - after its run settles, or at once when the callback was cancelled before * it started, so a caller waiting behind another mutation is not held up by it. A caller whose * compensation a still-pending write can overwrite awaits it first: runToCompletion and the queue * advance bound the caller, not the write. */ private enqueueProviderProfileMutationTracked( fn: (signal: AbortSignal) => Promise, options: { runToCompletion?: boolean } = {}, ): { result: Promise; settled: Promise } { const controller = new AbortController() let started = false let resolveCancelledStart: (value: undefined) => void = () => {} // Resolves in place of running fn when the caller timed out before the callback started: // the mutation is cancelled, so whoever waits on it must not be held behind the mutation // that blocked this one. const cancelledBeforeStart = new Promise((resolve) => { resolveCancelledStart = resolve }) const startQueuedMutation = (): Promise => { // The caller already timed out without asking for run-to-completion, so this callback is // cancelled: starting it afterwards would write state the caller has already compensated. if (!options.runToCompletion && controller.signal.aborted) { return Promise.reject(new Error("Provider profile mutation cancelled before it started")) } started = true return fn(controller.signal) } // Run fn after either outcome so a rejected mutation never poisons the queue. const run = this.providerProfileMutationQueue.then(startQueuedMutation, startQueuedMutation) 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() if (!started) { resolveCancelledStart(undefined) } 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; a // callback cancelled before it started settles at once instead of holding the queue. this.providerProfileMutationQueue = (options.runToCompletion ? run : callerResult).then( () => undefined, () => undefined, ) return { result: callerResult, settled: Promise.race([run, cancelledBeforeStart]).then( () => undefined, () => undefined, ), } } /** * Queue a provider-profile mutation without holding a handle on its run. See * enqueueProviderProfileMutationTracked for what a timeout does to the callback. */ private enqueueProviderProfileMutation( fn: (signal: AbortSignal) => Promise, options: { runToCompletion?: boolean } = {}, ): Promise { return this.enqueueProviderProfileMutationTracked(fn, options).result } /** * Deletes a custom mode through the provider-profile mutation queue. Without it a queued * mode switch can read the mode list, wait while this deletion removes the slug, and then * persist it - deletion would bypass the queue that orders exactly those two mutations. * The switch's own re-checks cover the reverse order (a deletion that lands while the * switch is executing). */ public async deleteCustomMode(slug: string): Promise { return this.enqueueProviderProfileMutation( async () => this.customModesManager.deleteCustomMode(slug), // The deletion must run to completion: a timeout that advanced the queue while the // mode files were being rewritten would let the next switch read a partial list. { runToCompletion: true }, ) } /** * Resolves once the currently queued provider-profile mutation (and everything queued * before it) has settled. A caller that timed out on a run-to-completion mutation waits * on this before acting on state that mutation can still change. */ public awaitProfileMutationSettled(): Promise { return this.providerProfileMutationQueue.then( () => undefined, () => undefined, ) } /** * Whether a mode slug still resolves, as read inside a queued mutation. Built-in slugs are * answered without a store read: they cannot be deleted, so a queued callback does not need * to re-read the custom-mode list for them (a custom mode shadowing a built-in keeps * resolving to the built-in once the custom definition is gone). */ private async modeSlugResolves(slug: Mode): Promise { if (getModeBySlug(slug)) { return true } return !!getModeBySlug(slug, await this.customModesManager.getCustomModes()) } private withProviderProfileMutationTimeout(operation: Promise, onTimeout: () => void): Promise { let timeoutId: ReturnType | undefined const timeout = new Promise((_, 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 /** * Unique identifier for this provider instance's view. * Based on renderContext and a monotonically increasing counter to ensure uniqueness across multiple instances. */ public readonly viewId: string /** * Stable identifier for persisted per-view state keys. * Defaults to viewId until the webview reports its VS Code-persisted id. */ private viewStateId: string /** * Whether this instance wrote an entry under its own session-local temporary id. * Temporary ids restart from 0 on every extension host start, so an entry under the * same name can belong to a different session. Only re-key entries this instance wrote. */ // #1562 seam: `loadViewState(): Promise` and its `return true` sites are this // unit's delivery signal - true means the load ran or had nothing to load, false means // the read failed and the caller must roll the registered id back so a retry can run. // `wroteUnderTemporaryViewStateId` is main's authorship flag, rehydrated at the top of // disposeInternal() below: a view that persisted state under its temporary id and then // disposed before registering a stable id still has to load that entry, and #1562's // early-return-true guard is what lets that load run instead of skipping it. private wroteUnderTemporaryViewStateId = false /** * The mutation that last committed a write naming a profile into this view durable pin, held as * an opaque token rather than as the name it wrote. A view commits its own selections with no * token, which clears the record: from then on the view owns its own pin. Only a profile deletion * carries one, stamped when that deletion re-points the entry, and its compensation puts a pin * back only while its own token is still on it. The stored profile name cannot carry this claim: * the replacement name is one a sibling can select itself, so a matching name says nothing about * who wrote it. */ private durableViewPinWriteOwner: symbol | undefined /** * Local state buffer for this specific view instance. * Used to isolate mode, apiConfiguration, and other fields from the shared ContextProxy singleton * when running in parallel (multi-tab) mode. */ private viewLocalState: Partial = {} /** * Fields mutated after loadViewState cleared the set: a completed mutation (including a * clear) wins over the persisted values an in-flight load read, so a stale load can never * re-apply a value the user changed while the load was in flight. */ private viewLocalStateMutatedFields = new Set<"mode" | "currentApiConfigName" | "apiConfiguration">() /** * Bumped whenever durable and in-memory view state are cleared as a unit (reset and * import broadcasts clear every live buffer through _clearViewLocalState). An * in-flight loadViewState captures it and abandons its assignment when the value has * moved, so a load that read pre-reset persisted entries cannot resurrect selections * a reset already cleared - the field-mutation tracking only covers field writes. */ private viewStateLoadGeneration = 0 /** * This view's pinned profile name from the view-local buffer. Exposed for * sibling-instance inspection (getAllInstances() filtering): `viewLocalState` * is private and must not be reached through bracket access. */ get pinnedProfileName(): string | undefined { return this.viewLocalState.currentApiConfigName } /** * This view's pinned mode slug from the view-local buffer, or undefined when the view * follows the shared selection. Exposed so a custom-mode deletion can key the reset * onto the view it actually applies to instead of moving every view's pin. */ get pinnedModeName(): string | undefined { return this.viewLocalState.mode } public isViewLaunched = false public settingsImportedAt?: number public readonly latestAnnouncementId = "nov-2026-v3.98.2-pass-gemini-responses-fixes" // v3.98.2 Zoo Pass, Gemini models, Responses API, and provider fixes 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() /** * 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> = 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() // Initialize viewId based on renderContext and monotonically increasing instance identifier for uniqueness. // activeInstances is used for visibility/iteration checks, so we keep tracking instances separately. this.viewId = `${renderContext}-${ClineProvider.nextViewId++}` this.viewStateId = this.viewId ClineProvider.activeInstances.add(this) 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() }) // Load initial state from global state into viewLocalState buffer after dependencies used by getState are ready. void this.loadViewState() // 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 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 { 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(migrationKey) if (!alreadyMigrated) { const legacyHistory = this.context.globalState.get("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)}`) } } /** * Reads the registered viewStates map, returning a defensive copy. * When fresh is set, the map is read directly from globalState (bypassing the * ContextProxy cache) so serialized writes never observe a stale in-memory value. */ private getPersistedViewStates(options: { fresh?: boolean } = {}): Record { const viewStates = options.fresh ? this.context.globalState.get("viewStates") : this.contextProxy.getValue("viewStates") if (!viewStates || typeof viewStates !== "object" || Array.isArray(viewStates)) { return Object.create(null) } // Copy onto a null prototype while dropping invalid entries: a view id that names an // Object.prototype key ("constructor", "toString", "valueOf", ...) must not resolve // through the prototype chain and be mistaken for a persisted entry, and corrupt // entries must be reported so a rejecting write is never silently poisoned. const states: Record = Object.create(null) let dropped = 0 for (const [viewId, entry] of Object.entries(viewStates)) { // Validate the fields, not only the shape: an entry such as { currentApiConfigName: 42 } is an // object, so an object check let it through hydration and getState then reported 42 as a // profile name. viewStateSchema is the same schema the settings schema applies to // viewStates, so an entry hydration cannot use is dropped and counted here instead of // being reported after hydration. const parsed = viewStateSchema.safeParse(entry) if (parsed.success) { states[viewId] = parsed.data } else { dropped++ } } if (dropped > 0) { this.log( `[getPersistedViewStates] dropped ${dropped} invalid viewStates ${dropped === 1 ? "entry" : "entries"}`, ) } return states } /** * Persists this view's non-secret selections through the serialized write queue. * The write re-reads the map fresh and merges into the existing entry, removing the * entry entirely when nothing persistable remains, so concurrent views cannot clobber it. * The entry is keyed by the view id active when the change was made. Writes captured * while the provider still holds its temporary (pre-launch) id persist under that id * and are re-keyed to the stable view id when the webview registers one, so a change * that lands before the launch message stays durable instead of being lost. */ private async savePersistedViewState( values: Partial, options: { pinWriteOwner?: symbol } = {}, ): Promise { // Capture the id at change time: a write belongs to the view that was active // when the change was made, even if a newer id is registered while it is queued. const viewStateId = this.viewStateId const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { const states = this.getPersistedViewStates({ fresh: true }) // The first write to an unowned temporary id claims the slot instead of merging // into it: temporary names restart from 0 on every host start, so an entry under // this name can be a leftover from an earlier session, and merging would adopt its // fields and later re-key them under the stable id. Entries under a stable id, or // under the temporary id this instance already authored, keep the merge semantics. const ownsTargetEntry = viewStateId !== this.viewId || this.wroteUnderTemporaryViewStateId const current = ownsTargetEntry ? (states[viewStateId] ?? {}) : {} const next: PersistedViewState = { ...current } if ("mode" in values) { if (values.mode === undefined || values.mode === null) { delete next.mode } else { next.mode = values.mode } } if ("currentApiConfigName" in values) { if (values.currentApiConfigName === undefined || values.currentApiConfigName === null) { delete next.currentApiConfigName } else { next.currentApiConfigName = values.currentApiConfigName } } let wroteEntry = false if (!next.mode && !next.currentApiConfigName) { delete states[viewStateId] } else { next.updatedAt = values.updatedAt ?? Date.now() states[viewStateId] = next wroteEntry = true } try { await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) } catch (error) { // updateGlobalState applies the new map to the in-memory cache before // the durable write, so a rejected write leaves the cache claiming an // entry that never reached disk. Restore the cache to the value durable // storage actually holds (undefined when the key was never written); the // cache update lands even if this compensating write also fails, so // readers cannot observe the lost entry either way. try { await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) } catch { // The cache is updated before the durable attempt: it matches the // durable value regardless of whether this restore write landed. } throw error } // Authorship is recorded only after the durable write lands: a failed persistence // must not mark the temporary id as owned, or a later load would adopt an entry // that was never actually stored. if (wroteEntry && viewStateId === this.viewId) { this.wroteUnderTemporaryViewStateId = true } // A write that names a profile is this view staking a claim on its own pin, so only such a write // moves the claim: a mode-only write names no profile and is not a selection. The writer identity // moves it, not the value it wrote - a view that selects the very profile a profile deletion had // just written into that entry owns the entry from then on, and that deletion has nothing left to // roll back. The token rides on the write that names the profile: the profile deletion passes one // on the activation it runs on its own view, and every other writer - a settings save from this // view webview included - passes none, so a selection the user completes while the deletion still // awaits a sibling re-pin clears the claim and the rollback leaves that newer choice alone. if ("currentApiConfigName" in values) { this.durableViewPinWriteOwner = options.pinWriteOwner this._rememberDurableViewPinWriteOwner(viewStateId, options.pinWriteOwner) } }) ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) await write } /** * Removes the given view's entry from the registered viewStates map. * Runs through the serialized write queue to avoid racing concurrent view-state writes. */ private async clearPersistedViewState(viewStateId = this.viewStateId): Promise { const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { const states = this.getPersistedViewStates({ fresh: true }) delete states[viewStateId] try { await this.contextProxy.setValue("viewStates", states) } catch (error) { // updateGlobalState applies the new map to the in-memory cache before // the durable write, so a rejected write leaves the cache missing an // entry that durable storage still holds. Restore the cache to the // value storage actually holds (undefined when the key was never // written); the cache update lands even if this compensating write // also fails, so readers cannot observe the loss either way. try { await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) } catch { // The cache is updated before the durable attempt: it matches the // durable value regardless of whether this restore write landed. } throw error } }) ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) await write } /** * Re-points persisted view pins that reference a removed profile so views do not * rehydrate a missing profile name after a reload. Runs through the serialized * write queue like every other viewStates mutation. */ /** /** * Hands every durable pin a whole-map write just re-pointed to the writer that committed it, so a * rollback in flight can tell its own write from a newer one. A live view also carries the record * in its own field; the record keyed by the persisted view id is written for every view the write * touched, closed ones included, because it is that record - not the field - the durable merge * leg reads when the view it re-pointed is no longer alive. */ private _recordDurableViewPinWriteOwners(viewStateIds: readonly string[], owner: symbol | undefined): void { if (viewStateIds.length === 0) { return } const instances = ClineProvider.getAllInstances() for (const viewStateId of viewStateIds) { const holder = instances.find((instance) => instance.viewStateId === viewStateId) if (holder) { holder.durableViewPinWriteOwner = owner } // An entry this write re-pointed while its view was closed has no field to hold the // claim, so the only writer left recorded on it is the claim its own last write left // behind. The rollback then reads a pin this deletion moved as somebody else own and // never rolls it back. this._rememberDurableViewPinWriteOwner(viewStateId, owner) } } /** * Records a pin-write claim under the persisted view id it applies to, so the record of who * wrote a view pin survives the view. Undefined is a recorded value, not the absence of one: * an ordinary selection clears the claim, and the record has to say so. Past the same bound * the durable viewStates map is kept to (MAX_PERSISTED_VIEW_STATES) the claims whose durable * entry is gone go first: a claim that describes no stored pin describes nothing a reload can * read, while a claim whose entry is still stored still describes the view a reload will * open. Only when every claim still has a stored entry does the bound fall on the oldest * claim, and that claim then falls back to the profile-name rule at the merge leg. */ private _rememberDurableViewPinWriteOwner(viewStateId: string, owner: symbol | undefined): void { // A claim this write replaces supersedes anything an earlier deletion was still owed on this pin: // the writer that obligation waited on no longer controls it, and letting a later rollback rewrite // a pin its user moved would undo a newer choice for an older failure. const waitingRollback = ClineProvider.deferredViewPinRollbacksByViewId.get(viewStateId) if (waitingRollback && waitingRollback.awaitingOwner !== owner) { ClineProvider.deferredViewPinRollbacksByViewId.delete(viewStateId) } ClineProvider.durableViewPinWriteOwnersByViewId.set(viewStateId, owner) if (ClineProvider.durableViewPinWriteOwnersByViewId.size <= ClineProvider.MAX_PERSISTED_VIEW_STATES) { return } const storedViewIds = new Set(Object.keys(this.getPersistedViewStates({ fresh: true }))) for (const trackedViewId of ClineProvider.durableViewPinWriteOwnersByViewId.keys()) { if (storedViewIds.has(trackedViewId)) { continue } ClineProvider.durableViewPinWriteOwnersByViewId.delete(trackedViewId) if (ClineProvider.durableViewPinWriteOwnersByViewId.size <= ClineProvider.MAX_PERSISTED_VIEW_STATES) { return } } for (const trackedViewId of ClineProvider.durableViewPinWriteOwnersByViewId.keys()) { if (ClineProvider.durableViewPinWriteOwnersByViewId.size <= ClineProvider.MAX_PERSISTED_VIEW_STATES) { break } ClineProvider.durableViewPinWriteOwnersByViewId.delete(trackedViewId) } } /** * Records what this deletion still owes on a pin a newer deletion is holding, so the rollback that * unblocks it can finish the unwind. Called from the restore merge leg when an entry this deletion * had re-pointed no longer names that replacement: the move past this deletion own replacement was * another deletion own doing, so the pin waits for the writer the id-keyed claim names, and what it * comes back to is the value this deletion read before it changed anything. Only a defined claim * qualifies - a claim a user wrote, or no claim at all, means a newer selection owns the pin and * nothing is owed for it. A deeper overlap updates the writer being waited on but keeps the value * already owed, so stacked deletions unwind to the first value rather than to a middle one. Past * the bound the durable claim record is kept to the obligation is not recorded, and the recovery * stays reported as incomplete the way it was. */ private _deferViewPinRollbackToClaimHolder( viewStateId: string, entry: PersistedViewState, blockedByOwner: symbol, priorPinWriteOwners: Map | undefined, ): void { const claims = ClineProvider.durableViewPinWriteOwnersByViewId const holder = claims.get(viewStateId) if (!claims.has(viewStateId) || holder === undefined || holder === blockedByOwner) { return } const owed = ClineProvider.deferredViewPinRollbacksByViewId.get(viewStateId) if (owed) { owed.awaitingOwner = holder return } if (ClineProvider.deferredViewPinRollbacksByViewId.size >= ClineProvider.MAX_PERSISTED_VIEW_STATES) { return } const hadPriorClaim = priorPinWriteOwners?.has(viewStateId) === true ClineProvider.deferredViewPinRollbacksByViewId.set(viewStateId, { awaitingOwner: holder, entry, hadPriorClaim, priorClaim: hadPriorClaim ? priorPinWriteOwners?.get(viewStateId) : undefined, }) } private async repointPersistedViewStates( removedProfileName: string, replacementProfileName: string, options: { pinWriteOwner?: symbol } = {}, ): Promise> { const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { const states = this.getPersistedViewStates({ fresh: true }) let changed = false // Snapshot the claims this write is about to overwrite, per view, while still // inside the queued write and before the record below: key presence means a claim // was recorded for that view (an undefined value is a recorded value, the same rule // the claim map documents above), and a view with no key here had none. A deletion // that re-points twice needs the claim its own re-point replaced, not the one a // later deletion left behind. const recordedOwners = ClineProvider.durableViewPinWriteOwnersByViewId const priorPinWriteOwners = new Map() const rePointedViewIds: string[] = [] for (const [viewId, entry] of Object.entries(states)) { if (entry?.currentApiConfigName !== removedProfileName) { continue } changed = true if (recordedOwners.has(viewId)) { priorPinWriteOwners.set(viewId, recordedOwners.get(viewId)) } rePointedViewIds.push(viewId) const { currentApiConfigName: _removed, ...rest } = entry if (rest.mode) { states[viewId] = { ...rest, currentApiConfigName: replacementProfileName, updatedAt: Date.now() } } else { states[viewId] = { currentApiConfigName: replacementProfileName, updatedAt: Date.now() } } } if (changed) { try { await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) } catch (error) { // updateGlobalState applies the new map to the in-memory cache // before the durable write: restore the cache to the value durable // storage actually holds so closed-view pins cannot serve re-pointed // names that never reached disk, then let the caller compensate. try { await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) } catch { // The cache is updated before the durable attempt: it matches the // durable value regardless of whether this restore write landed. } throw error } // Recorded only after the write landed: a re-point that never reached storage claimed no pin. this._recordDurableViewPinWriteOwners(rePointedViewIds, options.pinWriteOwner) } return priorPinWriteOwners }) ClineProvider.persistedViewStateWriteQueue = write.then(() => {}).catch(() => {}) return await write } /** * Keeps only the most recently updated entries of the persisted view states map, * bounded by MAX_PERSISTED_VIEW_STATES so the global key cannot grow unboundedly. */ private prunePersistedViewStates(states: Record): Record { return Object.fromEntries( Object.entries(states) .filter(([, entry]) => !!entry && typeof entry === "object") .sort(([, a], [, b]) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)) .slice(0, ClineProvider.MAX_PERSISTED_VIEW_STATES), ) } /** * Re-keys this provider's temporary pre-launch viewStates entry to the newly * registered stable id so pre-launch writes become durable under the stable key * instead of orphaning under a session-local temporary id. Only the provider's own * temporary id is eligible: an entry under a previously registered stable id belongs * to that webview's storage and is left alone. When the stable entry already exists * it wins and the temporary entry is dropped, because temporary ids are session * counters that can collide across window reloads. Runs through the serialized write * queue like every other viewStates mutation. */ private async rekeyPersistedViewStateEntry(nextViewStateId: string): Promise { const previousViewStateId = this.viewId const write = ClineProvider.persistedViewStateWriteQueue.then(async () => { // An entry under this name can belong to a different session, because temporary // ids restart from 0 on every extension host start. Only re-key entries this // instance wrote, otherwise a stale entry from another session is adopted. if (!this.wroteUnderTemporaryViewStateId) { return } const states = this.getPersistedViewStates({ fresh: true }) const previous = states[previousViewStateId] if (!previous) { return } delete states[previousViewStateId] if (!states[nextViewStateId]) { states[nextViewStateId] = previous } try { await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states)) } catch (error) { // updateGlobalState applies the new map to the in-memory cache before // the durable write, so a rejected re-key would leave the cache serving // the stable entry while durable storage still holds the temporary one. // Restore the cache to the value durable storage actually holds (the same // rollback savePersistedViewState applies), so a later load or a retry of // the registration sees the pre-rekey entry. try { await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates")) } catch { // The cache is updated before the durable attempt: it matches the // durable value regardless of whether this restore write landed. } throw error } // Only a successful write clears authorship: a failed attempt leaves the entry // under the temporary name, and a retry must still be able to re-key it. this.wroteUnderTemporaryViewStateId = false }) ClineProvider.persistedViewStateWriteQueue = write.catch(() => {}) await write } /** * Resolves once this view's stable state id has been registered (setViewStateId) and * its persisted view state loaded, or when the provider disposes. API-driven task * creation awaits this (bounded by a timeout) so a task cannot consume shared * default mode/profile state before the view's own persisted selections are loaded. */ private viewStateReadinessResolve!: () => void // Created eagerly in the field initializer rather than lazily in a getter: the // resolver is consumed by the first setViewStateId registration or by dispose, // so a promise created after that point would never settle and startNewTask's // readiness race would fall through to its timeout every time. public readonly viewStateReadiness: Promise = new Promise((resolve) => { this.viewStateReadinessResolve = resolve }) /** * True once dispose has started. Dispose resolves viewStateReadiness to release * waiters, so API-driven flows awaiting readiness must consult this flag to tell a real * readiness apart from a teardown: a disposed provider must never create a task. */ public get isDisposed(): boolean { return this._disposed } /** * Registers this provider's stable view identifier and loads any persisted selections it owns. * The identifier is sanitized so it remains a safe object key in the shared viewStates map. */ public async setViewStateId(viewStateId: string | undefined): Promise { // The webview generates this id on purpose - it has to survive a webview reload, // which recreates the view on both sides - so the host cannot mint it instead. // What the host owns is which view may hold a given persisted key, so everything // below validates the supplied value before it becomes one. if (typeof viewStateId !== "string") { // A crafted postMessage can carry any JSON value here even though the message // type declares a string; the persisted key must stay a string. this.log(`[setViewStateId] Ignoring a non-string viewStateId for view ${this.viewId}.`) // The view falls back to shared state; do not leave API-driven task creation // waiting on a registration that will not happen. this.viewStateReadinessResolve() return } const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_") if ( !normalizedViewStateId || normalizedViewStateId === this.viewStateId || // Reject "__proto__": writing states["__proto__"] would go through the // Object.prototype setter and be silently dropped by the later spread. normalizedViewStateId === "__proto__" ) { // No stable id will be registered for this view (no usable id in the launch // message, or this exact id was already registered): the view falls back to // shared state, and API-driven task creation must not time out waiting on a // view state that never registers. Resolve now; the promise is idempotent. this.viewStateReadinessResolve() return } // Bound the key: the webview generates a UUID, so a much longer value is not a // view id, and an unbounded key is unbounded growth in the shared viewStates map. if (normalizedViewStateId.length > ClineProvider.MAX_VIEW_STATE_ID_LENGTH) { this.log( `[setViewStateId] Ignoring an oversized viewStateId (${normalizedViewStateId.length} chars) for view ${this.viewId}.`, ) // The view falls back to shared state; do not leave API-driven task creation // waiting on a registration that will not happen. this.viewStateReadinessResolve() return } const claimant = ClineProvider.getAllInstances().find( (instance) => instance !== this && instance.viewStateId === normalizedViewStateId, ) if (claimant) { // Ownership check: a key another live view holds must not be adopted. Doing so // would load that view's pinned profile, nested overlay, and mode into this // provider, and this webview could then overwrite that view's persisted entry. // Staying on the temporary id keeps this view working against the shared state. this.log( `[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: already claimed by live view ${claimant.viewId}.`, ) // The view falls back to shared state; do not leave API-driven task creation // waiting on a registration that will not happen. this.viewStateReadinessResolve() return } const previousViewStateId = this.viewStateId this.viewStateId = normalizedViewStateId try { // Re-key any durable entry written under the temporary pre-launch id before // loading, so the load sees the view's own pre-registration selections. await this.rekeyPersistedViewStateEntry(this.viewStateId) // loadViewState logs and swallows its own read failures, so a false return is the // only signal that the load did not happen: roll the id back here too, or a retry // with the same id would early-return on the guard above and the view would never // reload its pinned mode/profile. if (!(await this.loadViewState())) { this.viewStateId = previousViewStateId } } catch (error) { // A persistence failure must not leave the provider holding an id that was // never registered: restore the previous id so a later launch retries the // registration and the load instead of the guard above early-returning for // the failed id. this.viewStateId = previousViewStateId throw error } finally { // The stable id is now registered (or restored): API-driven task creation // can proceed against this view's loaded state. this.viewStateReadinessResolve() } } /** * Loads non-secret persisted selections from the registered viewStates map. * Missing entries are intentionally left unset so getState() falls back to shared ContextProxy values. * Fields mutated while the async profile lookup is in flight are reapplied on top of the * loaded state, field by field, so in-flight user selections are not clobbered by the load. * @returns true when the load ran or had nothing to load, false when a read failed and the * persistence error was swallowed here (the caller must then roll back the id it registered). */ private async loadViewState(): Promise { // Capture the id this load is for: a newer id registered while an async // profile lookup is in flight must not be overwritten by this stale load. // #1562 seam: loadViewState returns whether the load delivered - true when it ran // or had nothing to load, false only when the read failed and swallowed the error, so // a false return is the caller-only signal that the registered id must roll back. const loadedForViewId = this.viewStateId // Capture the clear generation too: a reset/import that clears view state as a // unit does not change the id and is not a field mutation, so only the // generation reveals that this load's reads are already stale. const loadedForGeneration = this.viewStateLoadGeneration // While the stable id has not been registered yet, the key is this instance's // session-local name. Temporary names restart from 0 on every host start, so an // entry under the same name can belong to a different session. Load only entries // this instance authored. if (loadedForViewId === this.viewId && !this.wroteUnderTemporaryViewStateId) { return true } try { const persisted = this.getPersistedViewStates()[loadedForViewId] const loadedState: Partial = {} // Snapshot the in-memory buffer before the async profile lookup. The // mutation paths update viewLocalState in place, so a shallow copy is // what makes fields mutated during the load window observable below. const preLoadBuffer = { ...this.viewLocalState } // Clear the mutation marker before the async section: only mutations that // complete while this load is in flight may supersede the values it read. this.viewLocalStateMutatedFields.clear() if (persisted?.mode) { // A persisted mode may reference a custom mode that was deleted after it was // pinned: restore it only when the slug still resolves, so a stale slug cannot // shadow the shared mode from getState(). const customModes = await this.customModesManager.getCustomModes() if (getModeBySlug(persisted.mode, customModes)) { loadedState.mode = persisted.mode as Mode } else { this.log(`[loadViewState] Ignoring unknown persisted mode "${persisted.mode}"`) } } if (persisted?.currentApiConfigName) { loadedState.currentApiConfigName = persisted.currentApiConfigName try { const { name: _name, ...apiConfiguration } = await this.providerSettingsManager.getProfile({ name: persisted.currentApiConfigName, }) loadedState.apiConfiguration = apiConfiguration as ProviderSettings } catch (error) { this.log( `[loadViewState] Unable to resolve API profile '${persisted.currentApiConfigName}' for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, ) } } if (this.viewStateId !== loadedForViewId || this.viewStateLoadGeneration !== loadedForGeneration) { // A newer id owns this provider now: the load was superseded, not failed, so the // caller must keep the id the newer registration set. this.log(`[loadViewState] Discarding stale state for superseded view id ${loadedForViewId}`) return true } // #1562 seam: superseded is not failed. A newer registration owns the id now, so // this load counts as delivered and the caller keeps the id that newer call set. // Reapply the buffer fields that changed while the load was in flight, // tracking the change instead of testing against undefined: a field cleared // during the load window must stay cleared (the loaded value must not // resurrect it), and a field written to a new value must win over it. // Untouched fields keep the persisted values authoritative, and the // pre-load buffer is never merged wholesale so stale temporary-id state // cannot override the stable persisted state. const postLoadBuffer = this.viewLocalState const mergedState: Partial = { ...loadedState } if (!Object.is(preLoadBuffer.mode, postLoadBuffer.mode)) { if (postLoadBuffer.mode === undefined) { delete mergedState.mode } else { mergedState.mode = postLoadBuffer.mode } } if (!Object.is(preLoadBuffer.currentApiConfigName, postLoadBuffer.currentApiConfigName)) { if (postLoadBuffer.currentApiConfigName === undefined) { delete mergedState.currentApiConfigName } else { mergedState.currentApiConfigName = postLoadBuffer.currentApiConfigName } } if (!Object.is(preLoadBuffer.apiConfiguration, postLoadBuffer.apiConfiguration)) { if (postLoadBuffer.apiConfiguration === undefined) { delete mergedState.apiConfiguration } else { mergedState.apiConfiguration = postLoadBuffer.apiConfiguration } } // A mutation recorded inside the load window that left the buffer holding the value // it already held - a clear of an unset field, or a write of the same value - is // invisible to the buffer comparison above, yet it is still a completed mutation // and outranks the persisted values this read. Drop the loaded field in that case. if (this.viewLocalStateMutatedFields.has("mode") && postLoadBuffer.mode === undefined) { delete mergedState.mode } if ( this.viewLocalStateMutatedFields.has("currentApiConfigName") && postLoadBuffer.currentApiConfigName === undefined ) { delete mergedState.currentApiConfigName } if ( this.viewLocalStateMutatedFields.has("apiConfiguration") && postLoadBuffer.apiConfiguration === undefined ) { delete mergedState.apiConfiguration } // The profile name can move during the load window: the settings above were resolved for the // name the persisted record pinned, so when a different name was reapplied mid-load (a // profile switch while this view was starting) they must be re-resolved for the name the // view actually holds - getState() pairs the two and createTask hands that pair to the new // task, which also records the name. Dropping the settings instead is not safe: the view // would fall back to shared settings that can belong to another profile. // Only a name that moved inside the load window needs a re-resolve: a pin that already // held this value before the load started is stale and the persisted record stays // authoritative for both the name and its settings. const reappliedProfileName = !Object.is(preLoadBuffer.currentApiConfigName, postLoadBuffer.currentApiConfigName) && typeof postLoadBuffer.currentApiConfigName === "string" && postLoadBuffer.currentApiConfigName !== persisted?.currentApiConfigName && Object.is(preLoadBuffer.apiConfiguration, postLoadBuffer.apiConfiguration) ? postLoadBuffer.currentApiConfigName : undefined if (reappliedProfileName) { try { const { name: _name, ...reappliedSettings } = await this.providerSettingsManager.getProfile({ name: reappliedProfileName, }) mergedState.apiConfiguration = reappliedSettings as ProviderSettings } catch (error) { // The reapplied name no longer resolves: keep the name and let the view fall back to // the shared store rather than pairing it with a different profile's settings. this.log( `[loadViewState] Unable to resolve API profile '${reappliedProfileName}' reapplied during the load for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, ) delete mergedState.apiConfiguration } if (this.viewStateId !== loadedForViewId) { this.log(`[loadViewState] Discarding stale state for superseded view id ${loadedForViewId}`) return true } } this.viewLocalState = mergedState this.log(`[loadViewState] Loaded state for viewId ${this.viewId}`) return true } catch (error) { this.log( `[loadViewState] Error loading state for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`, ) return false } } /** * Saves a single view-local state value. The in-memory buffer is always updated; the * non-secret subset (mode, currentApiConfigName) is persisted durably under the view * id active when the change was made, re-keyed to the stable id on registration. */ public async saveViewState( key: K, value: ViewLocalStateValues[K] | undefined, ): Promise { await this._saveViewLocalStateFromMutation({ [key]: value } as ViewLocalStateValues) // The saved value is rendered only up to a bound: view-local values span user-authored // settings, and this diagnosability line must never dump arbitrary-length state. this.log( `[saveViewState] Saved ${String(key)}=${typeof value === "string" ? `${value.slice(0, 40)}${value.length > 40 ? "..." : ""}` : value === undefined ? "unset" : typeof value} for viewId ${this.viewId}`, ) } /** * Override EventEmitter's on method to match TaskProviderLike interface */ override on( event: K, listener: (...args: TaskProviderEvents[K]) => void | Promise, ): this { return super.on(event, listener as any) } /** * Override EventEmitter's off method to match TaskProviderLike interface */ override off( event: K, listener: (...args: TaskProviderEvents[K]) => void | Promise, ): 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 { 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 { 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 { 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 { // 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 { await this.taskHistoryStore.atomicReadAndUpdate(taskId, (historyItem) => ({ ...historyItem, pendingAction, })) this.recentTasksCache = undefined } public async clearPendingTaskAction(taskId: string, actionId: string): Promise { 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 { try { await task.dispose() } catch (error) { this.log( `[ClineProvider#dispose] Task cleanup failed for ${task.taskId}.${task.instanceId}: ${error instanceof Error ? error.message : String(error)}`, ) } } async dispose() { if (this._disposed) { return } // Set before the first await: every re-entrant call, guard and delivery check must // see the provider as closing for the whole teardown window. this._disposed = true try { await this.disposeInternal() } finally { // Released here rather than in the teardown body: a pending webview diagnostics // request holds a resolver and a timeout that close over this provider, so a view that // goes away mid-request must release them even when an earlier cleanup step threw. this.diagnosticsRequestBroker.dispose() // Deregistration must not depend on the teardown completing: a failing task // eviction, a throwing disposable or a rejecting MCP client would otherwise // leave this provider registered while _disposed is already set, and the early // return above means no later dispose() could repair the registry. ClineProvider.activeInstances.delete(this) // Clean up any event listeners attached to this provider this.removeAllListeners() McpServerManager.unregisterProvider(this) } } /** * Teardown body for {@link dispose}. Kept separate so every step here - task eviction * included - runs under the caller's finally, which owns the deregistration. */ private async disposeInternal(): Promise { this._postStateToWebviewThrottled.cancel() this.stopWebviewWatchdog() this.diagnosticsRecorder.record({ boundary: "provider", phase: "start", type: "dispose" }) this.log("Disposing ClineProvider...") // A disposed provider will never register a stable view state id: release // any API-driven task creation that is awaiting viewStateReadiness. this.viewStateReadinessResolve() // Reject any tasks still waiting for a scheduler permit so they don't // hold the event loop after the provider is torn down. this.taskScheduler.cancelQueued() // Cleanup steps (task eviction, MCP/skills/marketplace teardown) can // reject. _disposed is already set, so no caller can retry disposal: // each step runs independently so one failure cannot skip the later // release steps, the first error is preserved, and it is reported once // every step has run. let cleanupError: unknown const cleanupStep = async (label: string, fn: () => unknown | Promise) => { // #1562 seam: the constructor's `void this.loadViewState()` (construction-time hydrate) // is the other #1562 consumer of the delivery signal; it has no caller to report to, so // a false return there is intentionally dropped. Disposal does not re-hydrate: there is // no live view left to deliver to, and a load started here would mutate the view-local // state while the teardown is already running. try { await fn() } catch (error) { if (cleanupError === undefined) { cleanupError = error } this.log( `Provider cleanup step '${label}' failed: ${error instanceof Error ? error.message : String(error)}`, ) } } // Clear all tasks from the stack. The first pop goes through evictCurrentTask() // so an active delegated child is marked interrupted before the extension shuts down, // rather than being left persisted as "active" across the reload. await cleanupStep("tasks", async () => { if (this.taskRegistry.length > 0) { const task = this.taskRegistry.current! await this.evictCurrentTask() await this.drainTaskDisposal(task) } while (this.taskRegistry.length > 0) { const task = this.taskRegistry.current! await this.removeClineFromStack() await this.drainTaskDisposal(task) } this.log("Cleared all tasks") }) // Clear all pending edit operations to prevent memory leaks await cleanupStep("pendingEdits", () => { this.clearAllPendingEditOperations() this.log("Cleared pending operations") }) await cleanupStep("view", () => { if (this.view && "dispose" in this.view) { this.view.dispose() this.log("Disposed webview") } }) await cleanupStep("webviewResources", () => this.clearWebviewResources()) await cleanupStep("cloudService", () => { // Clean up cloud service event listener if (CloudService.hasInstance()) { CloudService.instance.off("settings-updated", this.handleCloudSettingsUpdate) } }) await cleanupStep("disposables", () => { while (this.disposables.length) { const x = this.disposables.pop() if (x) { // Isolate individual disposables: one throwing disposable must not // strand the rest of the list. try { x.dispose() } catch (error) { if (cleanupError === undefined) { cleanupError = error } this.log( `Provider cleanup step 'disposable' failed: ${error instanceof Error ? error.message : String(error)}`, ) } } } }) await cleanupStep("workspaceTracker", () => { this._workspaceTracker?.dispose() this._workspaceTracker = undefined }) await cleanupStep("mcpHub", async () => { await this.mcpHub?.unregisterClient() this.mcpHub = undefined }) await cleanupStep("skillsManager", async () => { await this.skillsManager?.dispose() this.skillsManager = undefined }) await cleanupStep("marketplace", () => this.marketplaceManager?.cleanup()) await cleanupStep("customModesManager", () => this.customModesManager?.dispose()) await cleanupStep("taskHistoryStore", () => this.taskHistoryStore.dispose()) await cleanupStep("taskTitleService", () => this.taskTitleService.dispose()) this.log("Disposed all disposables") // The releases themselves live in dispose's finally, not here: the body used to duplicate // all four after this log, so every dispose ran the broker release, the listener removal // and the MCP unregistration twice. if (cleanupError !== undefined) { throw cleanupError } } public get isViewVisible(): boolean { return this.view?.visible === true } public static getVisibleInstance(): ClineProvider | undefined { return findLast(Array.from(this.activeInstances), (instance) => instance.isViewVisible) } public static getAllInstances(): ClineProvider[] { return Array.from(this.activeInstances) } /** * Returns the live instance whose current view is the given view or panel, * if any. Title-bar commands on a specific surface use this to target the * instance that owns that surface rather than the visible-instance * heuristic (which picks whichever surface the user last focused). */ public static getInstanceForView(view: vscode.WebviewView | vscode.WebviewPanel): ClineProvider | undefined { // A provider that is already disposing must not be handed out: dispose() sets // _disposed before it awaits task cleanup, and during that window the view is still // registered while every postMessageToWebview on it is dropped. A caller that // reveals the view and posts didBecomeVisible would therefore have no visible // effect, and the user's next click would open a second tab. return Array.from(this.activeInstances).find((instance) => instance.view === view && !instance._disposed) } public static async getInstance(): Promise { let visibleProvider = ClineProvider.getVisibleInstance() // If no visible provider, try to show the sidebar view if (!visibleProvider) { await vscode.commands.executeCommand(`${Package.name}.SidebarProvider.focus`) // Wait briefly for the view to become visible await delay(100) visibleProvider = ClineProvider.getVisibleInstance() } // If still no visible provider, return if (!visibleProvider) { return } return visibleProvider } public static async isActiveTask(): Promise { const visibleProvider = await ClineProvider.getInstance() if (!visibleProvider) { return false } // Check if there is a cline instance in the stack (if this provider has an active task) if (visibleProvider.getCurrentTask()) { return true } return false } public async handleCodeAction( command: CodeActionId, promptType: CodeActionName, params: Record, ): Promise { // Capture telemetry for code action usage TelemetryService.instance.captureCodeActionUsed(promptType) const { customSupportPrompts } = await this.getState() // TODO: Improve type safety for promptType. // Only the typed input is a user segment. The template and its other params are generated. const segments = supportPrompt.createSegments(promptType, params, customSupportPrompts) const prompt = joinSegments(segments) if (command === "addToContext") { await this.postMessageToWebview({ type: "invoke", invoke: "setChatBoxMessage", text: `${prompt}\n\n`, segments: [...segments, ...generatedSegments("\n\n")], }) await this.postMessageToWebview({ type: "action", action: "focusInput" }) return } await this.createTask(prompt, undefined, undefined, { segments }) } public static async handleTerminalAction( command: TerminalActionId, promptType: TerminalActionPromptType, params: Record, ): Promise { TelemetryService.instance.captureCodeActionUsed(promptType) const visibleProvider = await ClineProvider.getInstance() if (!visibleProvider) { return } const { customSupportPrompts } = await visibleProvider.getState() const segments = supportPrompt.createSegments(promptType, params, customSupportPrompts) const prompt = joinSegments(segments) if (command === "terminalAddToContext") { await visibleProvider.postMessageToWebview({ type: "invoke", invoke: "setChatBoxMessage", text: `${prompt}\n\n`, segments: [...segments, ...generatedSegments("\n\n")], }) await visibleProvider.postMessageToWebview({ type: "action", action: "focusInput" }) return } try { await visibleProvider.createTask(prompt, undefined, undefined, { segments }) } catch (error) { if (error instanceof OrganizationAllowListViolationError) { // Errors from terminal commands seem to get swallowed / ignored. vscode.window.showErrorMessage(error.message) } throw error } } async resolveWebviewView(webviewView: vscode.WebviewView | vscode.WebviewPanel) { const generation = this.webviewRecoveryRequestGeneration // Capture intent before yielding: host recovery can time out while this // resolve is still generating HTML or hydrating state. const recoveringHost = preservesRecoveryIncident( this.webviewHostRecoveryInProgress, this.pendingSidebarRecovery, ) try { await this.initializeWebviewView(webviewView, recoveringHost) } catch (error) { if (!isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return const action = resolutionFailureAction({ recoveringHost, disposed: this._disposed, isCurrent: this.view === webviewView, }) if (action === "propagate") throw error if (action === "ignore") return // VS Code invokes sidebar resolution itself, outside the focus command's // promise. Handle both host types here so failed initialization retains // its task, disposal subscription, and remaining recovery attempts. const host = "onDidChangeViewState" in webviewView ? "tab" : "sidebar" this.reportWebviewRecoveryFailure(`Failed to initialize replacement ${host}: ${String(error)}`, false) this.startWebviewWatchdog() } } private async initializeWebviewView( webviewView: vscode.WebviewView | vscode.WebviewPanel, recoveringHost: boolean, ): Promise { // A different view replaces the current one: dispose its subscriptions so // the replaced view can no longer dispatch messages or refresh provider state. if (this.view !== webviewView) { this.clearWebviewResources() } const epoch = this.webviewRecoveryEpoch this.pendingSidebarRecovery = false this.view = webviewView const inTabMode = "onDidChangeViewState" in webviewView this.diagnosticsRecorder.record({ boundary: "provider", phase: "success", type: "view-resolved", }) // Register disposal before awaiting HTML or state so closing the view during // either load invalidates this resolve and prevents later listener installation. webviewView.onDidDispose( async () => { // A view that is no longer current must not clear the current // view's resources or dispose the provider. if (webviewView !== this.view) { return } if (inTabMode) { if (getPanel() === webviewView) setPanel(undefined, "tab") this.log("Disposing ClineProvider instance for tab view") await this.dispose() } else { this.log("Clearing webview resources for sidebar view") this.view = undefined this.clearWebviewResources() } }, null, // View-scoped, like the other view subscriptions: disposed both when // the view is disposed and when a different view replaces it. this.webviewDisposables, ) if (inTabMode) { setPanel(webviewView, "tab") } else if ("onDidChangeVisibility" in webviewView) { setPanel(webviewView, "sidebar") } // Set up webview options with proper resource roots const resourceRoots = [this.contextProxy.extensionUri] // Add workspace folders to allow access to workspace files if (vscode.workspace.workspaceFolders) { resourceRoots.push(...vscode.workspace.workspaceFolders.map((folder) => folder.uri)) } webviewView.webview.options = { enableScripts: true, localResourceRoots: resourceRoots, } const html = await this.getWebviewHtml(webviewView.webview) // The HTML load above can finish after the view was disposed or replaced. // A stale resolve must not assign HTML to a view the provider no longer owns. if (this.isStaleViewResolve(webviewView, epoch)) { return } // Initialize out-of-scope variables that need to receive persistent // global state values. await this.getState().then( ({ terminalShellIntegrationTimeout = Terminal.defaultShellIntegrationTimeout, terminalShellIntegrationDisabled = false, terminalCommandDelay = 0, terminalZshClearEolMark = true, terminalZshOhMy = false, terminalZshP10k = false, terminalPowershellCounter = false, terminalZdotdir = false, terminalProfile, ttsEnabled, ttsSpeed, }) => { if (this.isStaleViewResolve(webviewView, epoch)) return Terminal.setShellIntegrationTimeout(terminalShellIntegrationTimeout) Terminal.setShellIntegrationDisabled(terminalShellIntegrationDisabled) Terminal.setCommandDelay(terminalCommandDelay) Terminal.setTerminalZshClearEolMark(terminalZshClearEolMark) Terminal.setTerminalZshOhMy(terminalZshOhMy) Terminal.setTerminalZshP10k(terminalZshP10k) Terminal.setPowershellCounter(terminalPowershellCounter) Terminal.setTerminalZdotdir(terminalZdotdir) Terminal.setTerminalProfile(terminalProfile) setTtsEnabled(ttsEnabled ?? false) setTtsSpeed(ttsSpeed ?? 1) }, ) // State hydration can also finish after the view was disposed or replaced. // A stale resolve must not assign HTML or install listeners on a view the // provider no longer owns. if (this.isStaleViewResolve(webviewView, epoch)) { return } // Listen before assigning HTML: the webview posts webviewDidLaunch as soon as // it mounts, and VS Code drops messages that arrive before a listener exists. // Assigning HTML only after hydration also keeps webview messages from racing // the settings snapshot applied above. this.setWebviewMessageListener(webviewView) webviewView.webview.html = html this.webviewDisposables.push(this.webviewFocusTracker.init(this, webviewView)) // Detect a dead webview renderer process (gray screen) via heartbeat timeout. this.startWebviewWatchdog() // Listen for when the panel becomes visible. // https://github.com/microsoft/vscode-discussions/discussions/840 if ("onDidChangeViewState" in webviewView) { // WebviewView and WebviewPanel have all the same properties except // for this visibility listener panel. const viewStateDisposable = webviewView.onDidChangeViewState(() => { // Ignore events from a view that is no longer the current view. if (webviewView !== this.view) { return } this.diagnosticsRecorder.record({ boundary: "provider", phase: "success", type: this.view?.visible ? "view-visible" : "view-hidden", }) if (this.view?.visible) { // Hidden webviews throttle timers, so grant a fresh grace // window instead of counting throttled heartbeats as a crash. this.resetWebviewHeartbeatGrace() void this.postMessageToWebview({ type: "action", action: "didBecomeVisible" }) } else { this.logWebviewHiddenDiagnostics() } }) this.webviewDisposables.push(viewStateDisposable) } else if ("onDidChangeVisibility" in webviewView) { // sidebar const visibilityDisposable = webviewView.onDidChangeVisibility(() => { // Ignore events from a view that is no longer the current view. if (webviewView !== this.view) { return } this.diagnosticsRecorder.record({ boundary: "provider", phase: "success", type: this.view?.visible ? "view-visible" : "view-hidden", }) if (this.view?.visible) { // Hidden webviews throttle timers, so grant a fresh grace // window instead of counting throttled heartbeats as a crash. this.resetWebviewHeartbeatGrace() void this.postMessageToWebview({ type: "action", action: "didBecomeVisible" }) } else { this.logWebviewHiddenDiagnostics() } }) this.webviewDisposables.push(visibilityDisposable) } // Listen for when color changes const configDisposable = vscode.workspace.onDidChangeConfiguration(async (e) => { // Ignore configuration refreshes scoped to a view that is no longer current. if (webviewView !== this.view) { return } if (e && e.affectsConfiguration("workbench.colorTheme")) { // Sends latest theme name to webview await this.postMessageToWebview({ type: "theme", text: JSON.stringify(await getTheme()) }) } }) this.webviewDisposables.push(configDisposable) // If the extension is starting a new session, clear previous task state. // But don't clear if there's already an active task (e.g., resumed via IPC/bridge). const currentTask = this.getCurrentTask() // Host recreation is a UI repair, including when the displayed task is // interrupted. It must not evict or resume that task as a side effect. if (!recoveringHost && (!currentTask || currentTask.abandoned || currentTask.abort)) { await this.removeClineFromStack() } // Ensure zoo-gateway profile is seeded for users who signed in before this feature existed. // Without this, users with a valid cached token but no zoo-gateway profile would need to // re-authenticate to use Zoo Gateway. Fire-and-forget to avoid blocking webview init. void this.ensureZooGatewayProfileSeeded().catch((err) => { this.log(`[ensureZooGatewayProfileSeeded] Error: ${err instanceof Error ? err.message : String(err)}`) }) } /** * Seeds the zoo-gateway provider profile for users who have a cached auth token * but no profile (e.g., users who signed in before Zoo Gateway was added), or * who have an empty/imported profile without a token. * Called once per webview init; handleZooCodeCallback is idempotent so repeated calls are safe. */ private async ensureZooGatewayProfileSeeded(): Promise { const { getCachedZooCodeToken, getZooCodeBaseUrl } = await import("../../services/zoo-code-auth") const token = getCachedZooCodeToken() if (!token) return const expectedGatewayBaseUrl = `${getZooCodeBaseUrl()}/api/gateway/v1` // Check ALL zoo-gateway profiles — only skip seeding if every profile has the current token. // Using .find() would miss stale tokens in duplicate/renamed profiles since handleZooCodeCallback // uses .filter() and updates all of them — the early-return guard must match. const allProfiles = await this.providerSettingsManager.listConfig() const zooGatewayProfiles = allProfiles.filter((p) => p.apiProvider === providerIdentifiers.zooGateway) if (zooGatewayProfiles.length === 0) { this.log("[ensureZooGatewayProfileSeeded] No zoo-gateway profile found, creating one") } else { let allUpToDate = true for (const entry of zooGatewayProfiles) { try { const fullProfile = await this.providerSettingsManager.getProfile({ name: entry.name }) if ( fullProfile.zooSessionToken !== token || fullProfile.zooGatewayBaseUrl !== expectedGatewayBaseUrl ) { allUpToDate = false this.log("[ensureZooGatewayProfileSeeded] Existing zoo-gateway profile is stale, updating") break } } catch { allUpToDate = false this.log("[ensureZooGatewayProfileSeeded] Failed to read existing profile, will re-seed") break } } if (allUpToDate) { const { postZooGatewayCredentialsReady } = await import("../../services/zoo-gateway-credentials-sync") postZooGatewayCredentialsReady((message) => this.postMessageToWebview(message)) return } } // User has token but either no profile, some profiles without token, or stale tokens — seed all await this.handleZooCodeCallback(token) } public createTaskWithHistoryItem( historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task }, options?: { startTask?: boolean }, ): Promise { // History navigation can arrive concurrently (for example, two rapid // showTaskWithId messages). Serialize the full eviction/installation // transition so both callers cannot observe the same previous registry // state and schedule distinct Task instances for one history item. // Fail forward so one rejected restoration does not poison the queue. return ClineProvider.prototype.enqueueHistoryTaskTransition.call< ClineProvider, [() => Promise], Promise >(this, () => ClineProvider.prototype.createTaskWithHistoryItemUnlocked.call(this, historyItem, options)) } /** * Rehydrates `task` from history only if it is still current when the queued * step runs, so a navigation queued earlier is never evicted. */ public restartTaskIfCurrent(task: Task): Promise { return ClineProvider.prototype.enqueueHistoryTaskTransition.call< ClineProvider, [() => Promise], Promise >(this, async () => { if (this.getCurrentTask() !== task) { return false } const { historyItem } = await this.getTaskWithId(task.taskId) if (this.getCurrentTask() !== task) { return false } await ClineProvider.prototype.createTaskWithHistoryItemUnlocked.call(this, historyItem) return true }) } private enqueueHistoryTaskTransition(transition: () => Promise): Promise { const previous = this.historyTaskCreationQueue ?? Promise.resolve() const run = previous.then(transition, transition) this.historyTaskCreationQueue = run.then( () => {}, () => {}, ) return run } private async createTaskWithHistoryItemUnlocked( historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task }, options?: { startTask?: boolean }, ): Promise { const isCliRuntime = process.env.ROO_CLI_RUNTIME === "1" // CLI injects runtime provider settings from command flags/env at startup. // Restoring provider profiles from task history can overwrite those // runtime settings with stale/incomplete persisted profiles. const skipProfileRestoreFromHistory = isCliRuntime // Check if we're rehydrating the current task to avoid flicker const currentTask = this.getCurrentTask() const isRehydratingCurrentTask = currentTask && currentTask.taskId === historyItem.id if (!isRehydratingCurrentTask) { await this.evictCurrentTask() } // If the history item has a saved mode, restore it and its associated API configuration. if (historyItem.mode) { // Validate that the mode still exists const customModes = await this.customModesManager.getCustomModes() const modeExists = getModeBySlug(historyItem.mode, customModes) !== undefined if (!modeExists) { // Mode no longer exists, fall back to default mode. this.log( `Mode '${historyItem.mode}' from history no longer exists. Falling back to default mode '${defaultModeSlug}'.`, ) historyItem.mode = defaultModeSlug } // Persist the restored mode through this view's per-view pin rather than the // shared global: a global write would leak the restored mode into other views // in parallel mode, and a buffer-only write would be lost after a reload. await this.saveViewState("mode", historyItem.mode) // Load the saved API config for the restored mode if it exists. // Skip mode-based profile activation if historyItem.apiConfigName exists, // since the task's specific provider profile will override it anyway. const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false) if (!historyItem.apiConfigName && !lockApiConfigAcrossModes && !skipProfileRestoreFromHistory) { const savedConfigId = await this.getModeConfigId(historyItem.mode) const listApiConfig = await this.providerSettingsManager.listConfig() // Update listApiConfigMeta first to ensure UI has latest data. await this.updateGlobalState("listApiConfigMeta", listApiConfig) // If this mode has a saved config, use it. if (savedConfigId) { const profile = listApiConfig.find(({ id }) => id === savedConfigId) if (profile?.name) { try { // Check if the profile has actual API configuration (not just an id). // In CLI mode, the ProviderSettingsManager may return empty default profiles // that only contain 'id' and 'name' fields. Activating such a profile would // overwrite the CLI's working API configuration with empty settings. const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name }) const hasActualSettings = !!fullProfile.apiProvider if (hasActualSettings) { await this.activateProviderProfile( { name: profile.name }, { persistModeConfig: false, expectedCurrentTaskId: historyItem.id }, ) } else { // The task will continue with the current/default configuration. } } catch (error) { // Log the error but continue with task restoration. this.log( `Failed to restore API configuration for mode '${historyItem.mode}': ${ error instanceof Error ? error.message : String(error) }. Continuing with default configuration.`, ) // The task will continue with the current/default configuration. } } } } } // If the history item has a saved API config name (provider profile), restore it. // This overrides any mode-based config restoration above, because the task's // specific provider profile takes precedence over mode defaults. if (historyItem.apiConfigName && !skipProfileRestoreFromHistory) { const listApiConfig = await this.providerSettingsManager.listConfig() // Keep global state/UI in sync with latest profiles for parity with mode restoration above. await this.updateGlobalState("listApiConfigMeta", listApiConfig) const profile = listApiConfig.find(({ name }) => name === historyItem.apiConfigName) if (profile?.name) { try { if (profile.apiProvider) { await this.activateProviderProfile( { name: profile.name }, { persistModeConfig: false, persistTaskHistory: false, expectedCurrentTaskId: historyItem.id, }, ) } } catch (error) { // Log the error but continue with task restoration. this.log( `Failed to restore API configuration '${historyItem.apiConfigName}' for task: ${ error instanceof Error ? error.message : String(error) }. Continuing with current configuration.`, ) } } else { // Profile no longer exists, log warning but continue this.log( `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, ) } } else if (historyItem.apiConfigName && skipProfileRestoreFromHistory) { this.log( `Skipping restore of provider profile '${historyItem.apiConfigName}' for task ${historyItem.id} in CLI runtime.`, ) } const { apiConfiguration, enableCheckpoints, checkpointTimeout, experiments, diffFuzzyThreshold } = await this.getState() const task = new Task({ provider: this, apiConfiguration, enableCheckpoints, checkpointTimeout, consecutiveMistakeLimit: apiConfiguration.consecutiveMistakeLimit, toolRepetitionSoftLimit: apiConfiguration.toolRepetitionSoftLimit, historyItem, experiments, rootTask: historyItem.rootTask, parentTask: historyItem.parentTask, taskNumber: historyItem.number, workspacePath: historyItem.workspace, onCreated: this.taskCreationCallback, startTask: false, // Preserve the status from the history item to avoid overwriting it when the task saves messages initialStatus: historyItem.status, rateLimitClock: this.rateLimitClock, diffFuzzyThreshold, }) if (isRehydratingCurrentTask) { // Replace the current task in-place to avoid UI flicker const oldTask = this.taskRegistry.current // The current task may have changed or been removed during the awaits above; never touch it. if (oldTask !== currentTask) { removeTaskEventListeners(this.taskEventListeners, task) await task.abortTask(true).catch(() => {}) return task } if (oldTask) { // Abort the old task to stop running processes and mark as abandoned try { await oldTask.abortTask(true) } catch (e) { this.log( `[createTaskWithHistoryItem] abortTask() failed for old task ${oldTask.taskId}.${oldTask.instanceId}: ${e.message}`, ) } removeTaskEventListeners(this.taskEventListeners, oldTask) // Replace in-place: preserves stack index and current pointer this.taskRegistry.replace(oldTask.taskId, task) } task.emit(RooCodeEventName.TaskFocused) // Perform preparation tasks and set up event listeners await this.performPreparationTasks(task) this.log( `[createTaskWithHistoryItem] rehydrated task ${task.taskId}.${task.instanceId} in-place (flicker-free)`, ) if (options?.startTask !== false) { scheduleTask(this.taskScheduler, task, "createTaskWithHistoryItem", undefined, (error) => this.cleanupFailedHistoryTask(task, error), ) } } else { await this.addClineToStack(task) this.log( `[createTaskWithHistoryItem] ${task.parentTask ? "child" : "parent"} task ${task.taskId}.${task.instanceId} instantiated`, ) if (options?.startTask !== false) { scheduleTask(this.taskScheduler, task, "createTaskWithHistoryItem", undefined, (error) => this.cleanupFailedHistoryTask(task, error), ) } } // Check if there's a pending edit after checkpoint restoration const operationId = `task-${task.taskId}` const pendingEdit = this.getPendingEditOperation(operationId) if (pendingEdit) { this.clearPendingEditOperation(operationId) // Clear the pending edit this.log(`[createTaskWithHistoryItem] Processing pending edit after checkpoint restoration`) // Process the pending edit after a short delay to ensure the task is fully initialized setTimeout(async () => { try { // Find the message index in the restored state const { messageIndex, apiConversationHistoryIndex } = (() => { const messageIndex = task.clineMessages.findIndex((msg) => msg.ts === pendingEdit.messageTs) const apiConversationHistoryIndex = task.apiConversationHistory.findIndex( (msg) => msg.ts === pendingEdit.messageTs, ) return { messageIndex, apiConversationHistoryIndex } })() if (messageIndex !== -1) { // Remove the target message and all subsequent messages await task.overwriteClineMessages(task.clineMessages.slice(0, messageIndex)) if (apiConversationHistoryIndex !== -1) { await task.overwriteApiConversationHistory( task.apiConversationHistory.slice(0, apiConversationHistoryIndex), ) } // Process the edited message await task.handleWebviewAskResponse( "messageResponse", pendingEdit.editedContent, pendingEdit.images, ) } } catch (error) { this.log(`[createTaskWithHistoryItem] Error processing pending edit: ${error}`) } }, 100) // Small delay to ensure task is fully ready } return task } public async postMessageToWebview(message: ExtensionMessage) { const startedAt = Date.now() const taskId = this.getCurrentTask()?.taskId this.diagnosticsRecorder.record({ boundary: "webview-out", phase: "start", type: message.type, action: message.action, stateSequence: message.type === "state" ? message.state?.clineMessagesSeq : undefined, taskId, }) if (this._disposed) { this.diagnosticsRecorder.record({ boundary: "webview-out", phase: "failure", type: message.type, action: message.action, elapsedMs: Date.now() - startedAt, taskId, }) return } const webview = this.view?.webview if (!webview) { return } // Dispatch without awaiting the renderer ack: VS Code settles postMessage only when the // webview page acknowledges the message, and a page reload or view dispose in flight // orphans that promise forever. Awaiting it could wedge every caller on the task critical // path (e.g. the trailing postStateToWebview in handleModeSwitchUnlocked gates the next // turn after a mode switch). Message ordering is enforced by the message seq, not the ack. // Promise.resolve() normalizes non-promise returns (e.g. test doubles) before the catch. void Promise.resolve(webview.postMessage(omitOriginalContentFromExtensionMessage(message))) .then((delivered) => { // VS Code resolves `false` when the message was not delivered (the page was // torn down or never finished loading). That is a drop just like a rejection, // so it is logged too instead of losing state updates silently. if (delivered === false) { this.log(`[postMessageToWebview] undelivered message type=${message.type}`) } }) .catch((error) => { // Swallow: postMessage rejects when the webview is disposed in flight. // Log the dropped message type so a wedged webview channel is diagnosable // instead of silently losing state updates. this.log( `[postMessageToWebview] dropped message type=${message.type}: ${error instanceof Error ? error.message : String(error)}`, ) }) } public requestWebviewThemeFixture(timeoutMs = 5_000): Promise { if (process.env.ROO_CODE_THEME_FIXTURE_PROBE !== "1") { return Promise.reject(new Error("Theme fixture probing is disabled")) } const requestId = `theme-fixture-${++this.nextThemeFixtureProbeId}` return new Promise((resolve, reject) => { const timeout = setTimeout(() => { this.pendingThemeFixtureProbes.delete(requestId) reject(new Error(`Theme fixture probe timed out after ${timeoutMs}ms`)) }, timeoutMs) this.pendingThemeFixtureProbes.set(requestId, { resolve, reject, timeout }) void this.postMessageToWebview({ type: "themeFixtureProbeRequest", requestId }) }) } public resolveWebviewThemeFixtureProbe(requestId: string, fixture: WebviewThemeFixture): void { const pending = this.pendingThemeFixtureProbes.get(requestId) if (!pending) { return } clearTimeout(pending.timeout) this.pendingThemeFixtureProbes.delete(requestId) pending.resolve(fixture) } private rejectPendingThemeFixtureProbes(error: Error): void { for (const pending of this.pendingThemeFixtureProbes.values()) { clearTimeout(pending.timeout) pending.reject(error) } this.pendingThemeFixtureProbes.clear() } public getDiagnosticsSnapshot(): DiagnosticsProviderSourceSnapshot { const currentTask = this.getCurrentTask() const events = this.diagnosticsRecorder.snapshot(100) return { renderContext: this.renderContext, disposed: this._disposed, viewPresent: Boolean(this.view), visible: this.view?.visible === true, launched: this.isViewLaunched, taskHistoryInitialized: this.taskHistoryStoreInitialized, taskCount: this.taskRegistry.length, currentTaskId: currentTask?.taskId, currentMessageCount: currentTask?.clineMessages.length ?? 0, currentTodoCount: currentTask?.todoList?.length ?? 0, history: this.taskHistoryStore.getAll(), events: events.events, eventsTruncated: events.truncated, } } public requestWebviewDiagnostics(timeoutMs = 1_000): Promise { if (this._disposed || !this.view) return Promise.resolve(undefined) return this.diagnosticsRequestBroker.request( (requestId) => this.postMessageToWebview({ type: "diagnosticsRequest", requestId }), timeoutMs, ) } private async getHMRHtmlContent(webview: vscode.Webview): Promise { let localPort = "5173" try { const fs = require("fs") const path = require("path") const portFilePath = path.resolve(__dirname, "../../.vite-port") if (fs.existsSync(portFilePath)) { localPort = fs.readFileSync(portFilePath, "utf8").trim() console.log(`[ClineProvider:Vite] Using Vite server port from ${portFilePath}: ${localPort}`) } else { console.log( `[ClineProvider:Vite] Port file not found at ${portFilePath}, using default port: ${localPort}`, ) } } catch (err) { console.error("[ClineProvider:Vite] Failed to read Vite port file:", err) } const localServerUrl = `127.0.0.1:${localPort}` // Check if local dev server is running. try { await axios.get(`http://${localServerUrl}`, { timeout: 5_000 }) } catch (error) { const timedOut = axios.isAxiosError(error) && (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") void vscode.window.showErrorMessage( t(timedOut ? "common:errors.hmr_probe_timeout" : "common:errors.hmr_not_running"), ) return this.getHtmlContent(webview) } const nonce = getNonce() const stylesUri = getUri(webview, this.contextProxy.extensionUri, [ "webview-ui", "build", "assets", "index.css", ]) const codiconsUri = getUri(webview, this.contextProxy.extensionUri, ["assets", "codicons", "codicon.css"]) const materialIconsUri = getUri(webview, this.contextProxy.extensionUri, [ "assets", "vscode-material-icons", "icons", ]) const imagesUri = getUri(webview, this.contextProxy.extensionUri, ["assets", "images"]) const audioUri = getUri(webview, this.contextProxy.extensionUri, ["webview-ui", "audio"]) const file = "src/index.tsx" const scriptUri = `http://${localServerUrl}/${file}` const reactRefresh = /*html*/ ` ` const csp = [ "default-src 'none'", `font-src ${webview.cspSource} data:`, `style-src ${webview.cspSource} 'unsafe-inline' https://* http://${localServerUrl} http://0.0.0.0:${localPort}`, `img-src ${webview.cspSource} https://storage.googleapis.com https://img.clerk.com https://avatars.githubusercontent.com https://lh3.googleusercontent.com data:`, `media-src ${webview.cspSource}`, `script-src 'unsafe-eval' ${webview.cspSource} https://*.posthog.com http://${localServerUrl} http://0.0.0.0:${localPort} 'nonce-${nonce}'`, `connect-src ${webview.cspSource} https://* https://*.posthog.com ws://${localServerUrl} ws://0.0.0.0:${localPort} http://${localServerUrl} http://0.0.0.0:${localPort}`, ] return /*html*/ ` Zoo Code
${reactRefresh} ` } /** * Defines and returns the HTML that should be rendered within the webview panel. * * @remarks This is also the place where references to the React webview build files * are created and inserted into the webview HTML. * * @param webview A reference to the extension webview * @param extensionUri The URI of the directory containing the extension * @returns A template string literal containing the HTML that should be * rendered within the webview panel */ private async getHtmlContent(webview: vscode.Webview): Promise { // Get the local path to main script run in the webview, // then convert it to a uri we can use in the webview. // The CSS file from the React build output const stylesUri = getUri(webview, this.contextProxy.extensionUri, [ "webview-ui", "build", "assets", "index.css", ]) const scriptUri = getUri(webview, this.contextProxy.extensionUri, ["webview-ui", "build", "assets", "index.js"]) const codiconsUri = getUri(webview, this.contextProxy.extensionUri, ["assets", "codicons", "codicon.css"]) const materialIconsUri = getUri(webview, this.contextProxy.extensionUri, [ "assets", "vscode-material-icons", "icons", ]) const imagesUri = getUri(webview, this.contextProxy.extensionUri, ["assets", "images"]) const audioUri = getUri(webview, this.contextProxy.extensionUri, ["webview-ui", "audio"]) // Use a nonce to only allow a specific script to be run. /* content security policy of your webview to only allow scripts that have a specific nonce create a content security policy meta tag so that only loading scripts with a nonce is allowed As your extension grows you will likely want to add custom styles, fonts, and/or images to your webview. If you do, you will need to update the content security policy meta tag to explicitly allow for these resources. E.g. - 'unsafe-inline' is required for styles due to vscode-webview-toolkit's dynamic style injection - since we pass base64 images to the webview, we need to specify img-src ${webview.cspSource} data:; in meta tag we add nonce attribute: A cryptographic nonce (only used once) to allow scripts. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. */ const nonce = getNonce() // Tip: Install the es6-string-html VS Code extension to enable code highlighting below return /*html*/ ` Zoo Code
` } /** * Sets up an event listener to listen for messages passed from the webview context and * executes code based on the message that is received. * * @param webviewView The view whose webview messages are listened to */ private setWebviewMessageListener(webviewView: vscode.WebviewView | vscode.WebviewPanel) { const onReceiveMessage = async (message: WebviewMessage) => { // Ignore messages from a view that is no longer the current view. if (webviewView !== this.view) { return } const startedAt = Date.now() this.diagnosticsRecorder.record({ boundary: "webview-in", phase: "start", type: message.type }) try { if (message.type === "diagnosticsResponse" && message.requestId) { this.diagnosticsRequestBroker.resolve(message.requestId, message.diagnostics) } else { await webviewMessageHandler(this, message, this.marketplaceManager) } this.diagnosticsRecorder.record({ boundary: "webview-in", phase: "success", type: message.type, elapsedMs: Date.now() - startedAt, }) } catch (error) { this.diagnosticsRecorder.record({ boundary: "webview-in", phase: "failure", type: message.type, elapsedMs: Date.now() - startedAt, }) throw error } } const messageDisposable = webviewView.webview.onDidReceiveMessage(onReceiveMessage) this.webviewDisposables.push(messageDisposable) } /** * Handle switching to a new mode, including updating the associated API configuration * @param newMode The mode to switch to * @param targetTask The task whose in-memory mode should be updated. Defaults to the * current task. Pass null to apply only global mode/profile effects for a pending child. * A task that is not this view's focused task only receives the task-scoped effects * (history entry + in-memory mode): the view's durable mode, the ModeChanged * broadcast, and profile activation keep applying to the focused task's selection. * Unknown mode slugs are ignored (logged + no-op) so unvalidated callers (the webview * "mode" message sends message.text as Mode) cannot persist invalid modes. */ public async handleModeSwitch(newMode: Mode, targetTask: Task | null | undefined = this.getCurrentTask()) { return this.enqueueProviderProfileMutation( async (signal) => { // The existence check runs inside the queued callback, not before the switch joins // the queue: a custom mode can be deleted while this switch waits its turn, and a // pre-queue check would then pin a slug that no longer resolves to the view, the // shared mode and the task history. if (!(await this.modeSlugResolves(newMode))) { this.log(`[ClineProvider#handleModeSwitch] ignoring unknown mode "${newMode}"`) return } return this.handleModeSwitchUnlocked(newMode, targetTask, signal) }, // The switch and its nested activation must own the queue until every // write - including compensation - settles: a timeout must not let the // next queued mutation overlap writes that are still in flight. { runToCompletion: true }, ) } private async handleModeSwitchUnlocked( newMode: Mode, targetTask: Task | null | undefined, signal?: AbortSignal, ): Promise { const task = targetTask // Captured for the pin-write rollback below: the mode this task held before // the switch (bracket access: _taskMode is private to Task). const previousTaskMode = task ? task["_taskMode"] : undefined let rollbackTaskWrites: (() => Promise) | undefined // A cancelled or timed-out switch must not be partially applied: bail out // before the task history / _taskMode writes as well as the durable mode // write below. Aborts that land while the history write is in flight are // handled in flight (the landed write is rolled back); the pre-write check // further down still covers the remaining gap before the durable write. if (signal?.aborted) { return } if (task) { TelemetryService.instance.captureModeSwitch(task.taskId, newMode) // Captured above the try so the catch below can undo a history write that already landed. // The emit on the persisted new mode runs after that write, and a listener that throws there // must not leave task history on the new mode while _taskMode and the view's durable pin // still hold the old one. let undoHistoryWrite: (() => Promise) | undefined try { // Update the task history with the new mode first. const taskHistoryItem = this.getTaskHistoryItem(task.taskId) if (taskHistoryItem) { await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) undoHistoryWrite = async () => { // Restore only the field this switch changed, re-reading the item so fields the running // task persisted during the pending window survive the restore. const latest = this.getTaskHistoryItem(task.taskId) ?? taskHistoryItem await this.updateTaskHistory({ ...latest, mode: taskHistoryItem.mode }) } // An abort that lands while the history write is in flight has // already persisted the new mode: restore the pre-switch item and // bail before the in-memory task write and the emit, so task // history, task state, and provider mode cannot diverge. A failed // rollback must not surface as the persistence error of the // cancelled switch: log it and keep the cancellation result. if (signal?.aborted) { try { // Restore only the field this switch changed: re-read the item so // fields the running task persisted during the pending window // (tokens, cost, status, apiConfigName) survive the rollback. const latest = this.getTaskHistoryItem(task.taskId) ?? taskHistoryItem await this.updateTaskHistory({ ...latest, mode: taskHistoryItem.mode }) } catch (rollbackError) { this.log(`Failed to roll back mode switch ${task.taskId}: ${String(rollbackError)}`) } return } } else if (signal?.aborted) { return } task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, newMode) // Only update the task's mode after successful persistence. ;(task as any)._taskMode = newMode // If the view's durable mode pin below fails after these task-side writes // landed, restore them: the caller delivers the message on the caught // error, and the new task mode must not run against the view's unchanged // mode and mode-linked API configuration. const historyItemBefore = taskHistoryItem rollbackTaskWrites = async () => { task["_taskMode"] = previousTaskMode // Listeners were told about the new mode before the failure landed: re-emit // with the restored mode so API/IPC consumers track the rollback. if (previousTaskMode) { task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, previousTaskMode) } if (historyItemBefore) { // Restore only the field this switch changed: re-read the item so // fields the running task persisted during the write survive. const latest = this.getTaskHistoryItem(task.taskId) ?? historyItemBefore await this.updateTaskHistory({ ...latest, mode: historyItemBefore.mode }) } } } catch (error) { // If persistence fails, log the error but don't update the in-memory state. this.log( `Failed to persist mode switch for task ${task.taskId}: ${error instanceof Error ? error.message : String(error)}`, ) // The history write landed before this failure - the emit above is the reachable // thrower now that the history write runs first - so undo it: without the undo, the // persisted item keeps a mode the task, its view pin and its profile never took on. // A failed undo is logged; the original failure is what the caller sees. if (undoHistoryWrite) { try { await undoHistoryWrite() } catch (rollbackError) { this.log( `Failed to roll back the task history entry after a failed mode switch: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } // Optionally, we could emit an event to notify about the failure. // This ensures the in-memory state remains consistent with persisted state. throw error } } // A cancelled or timed-out switch must not write the mode or emit // ModeChanged: check the mutation signal right before the durable write. if (signal?.aborted) { return } // The task writes above await (the history write first), so a custom mode can be deleted // inside that window even while this switch owns the queue. Re-check before the first // durable write so a slug that no longer resolves is never pinned to the view or written // to the shared mode, and undo the task-side writes that already landed. The re-check reads // custom modes through the manager itself, so it can reject after the built-in lookup has // already approved the slug: the task-side writes have landed by then too, and letting the // rejection escape without the undo leaves the task on a mode its view pin and profile // never took. Roll back the task-side writes on a failed lookup and rethrow the original // error; the deleted-mode path below keeps returning without throwing. let slugResolves: boolean try { slugResolves = await this.modeSlugResolves(newMode) } catch (lookupError) { if (rollbackTaskWrites) { try { await rollbackTaskWrites() } catch (rollbackError) { this.log( `[handleModeSwitch] Failed to roll back task mode writes after the mode lookup failed: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } throw lookupError } if (!slugResolves) { this.log(`[ClineProvider#handleModeSwitch] ignoring mode "${newMode}" deleted while the switch was pending`) if (rollbackTaskWrites) { try { await rollbackTaskWrites() } catch (rollbackError) { this.log( `[handleModeSwitch] Failed to roll back task mode writes after the mode was deleted: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } return } // A mode switch requested for a task that is not this view's focused task applies // only to that task (history entry + in-memory mode): pinning the view's durable // mode, broadcasting ModeChanged, or activating a profile on behalf of a // background task would clobber the focused task's selection. const viewScopedSwitch = task === undefined || task === null || this.getCurrentTask() === task // Captured for the reconcile below: the view's pre-switch durable mode pin // (undefined means the view never pinned a mode) and the pre-switch shared // mode. The pin write only touches the view buffer and the per-view store, so // reading the shared value here is unaffected by it. const previousViewMode = this.viewLocalState.mode const previousMode = this.getValue("mode") let pinLanded = false let sharedAttempted = false // Explicit partial-failure behavior: every failure after the task-mode write // rolls back all writes this switch owns - shared mode, view pin, task mode, // and the task-history entry - so the caller (Task#submitUserMessage) delivers // the submitted message on the pre-switch mode and profile instead of a // half-applied switch that runs the new mode against the unchanged profile. // Each restore is awaited on its own and logged on failure, never swallowed. const reconcileSwitchWrites = async () => { if (sharedAttempted) { // The shared write may have landed before its promise rejected: restore // it unconditionally so getValues() cannot mix a fresh shared mode with // the rolled-back view state. try { await this.contextProxy.setValue("mode", previousMode) } catch (rollbackError) { this.log( `[handleModeSwitch] Failed to roll back shared mode after persistence failure: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } if (pinLanded) { try { await this.saveViewState("mode", previousViewMode) } catch (rollbackError) { this.log( `[handleModeSwitch] Failed to roll back the view mode pin after persistence failure: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } if (rollbackTaskWrites) { try { await rollbackTaskWrites() } catch (rollbackError) { this.log( `[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${ rollbackError instanceof Error ? rollbackError.message : String(rollbackError) }`, ) } } } // Once the mode-linked activation below has started writing shared state, a // mode-only rollback would pair the old mode with the new profile: the catch must // then keep the switch instead of reconciling. let activationStarted = false try { if (viewScopedSwitch) { // Pin the view's durable per-view mode first: the pin is this view's own // selection. If any write below fails, the reconcile above restores every // write that landed, including this pin, so a delivered message never runs // the new task mode against an unchanged view mode or mode-linked profile. await this.saveViewState("mode", newMode) pinLanded = true // setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState // buffer stays in sync with the durable global write: getValues() merges // viewLocalState on top of the ContextProxy values, so an unsynced stale // restored mode would otherwise shadow the fresh switch for consumers. // Mark the shared write as attempted only once it resolved: a rejection // is already compensated inside setValue (which restores the prior // shared value before rethrowing), and reconciling again here would // replay the same restore. A resolved write, by contrast, must be // restored by the reconcile when a later write fails. await this.setValue("mode", newMode) sharedAttempted = true } // If workspace lock is on, keep the current API config: the mode-linked // activation below is skipped, and the committed switch falls through to the // emit/post tail outside the reconciled region. const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false) if (!lockApiConfigAcrossModes) { // A background-task switch applies to the task only: no view pin, no // ModeChanged, and no mode-linked activation on its behalf. if (!viewScopedSwitch) { return } // Load the saved API config for the new mode if it exists. // Resolve the mode profile through getModeConfigId: the persisted mode map is // shared by every window, so a bare manager read would let another window's // profile selection drive this view's mode switch (#2110). const savedConfigId = await this.getModeConfigId(newMode) const listApiConfig = await this.providerSettingsManager.listConfig() // The pin and shared mode writes above have committed the mode: an abort // here skips the remaining activation work but falls through to the // emit/post tail so listeners and the webview learn the committed mode. if (!signal?.aborted) { await this.updateGlobalState("listApiConfigMeta", listApiConfig) // If this mode has a saved config, use it. if (savedConfigId) { const profile = listApiConfig.find(({ id }) => id === savedConfigId) if (profile?.name) { // Check if the profile has actual API configuration (not just an id). // In CLI mode, the ProviderSettingsManager may return empty default profiles // that only contain 'id' and 'name' fields. Activating such a profile would // overwrite the CLI's working API configuration with empty settings. // Skip activation if the profile has no apiProvider set - this indicates // an unconfigured/empty profile. const fullProfile = await this.providerSettingsManager.getProfile({ name: profile.name }) const hasActualSettings = !!fullProfile.apiProvider if (hasActualSettings) { // The committed-switch guard flips only when the activation has // actually written the activated profile: a lookup failure (e.g. a // deleted profile) throws before any write and must still reconcile. await this.activateProviderProfileUnlocked( { name: profile.name }, { // A mode switch must not rewrite the shared mode map (#2110): the mapping this // activation would persist is this mode's own saved choice, and writing it out // here would publish this view's profile to the other windows. persistModeConfig: false, ...(targetTask === null ? { skipCurrentTaskRebuild: true } : {}), onSharedWriteStart: () => { activationStarted = true }, }, signal, ) } else { // The task will continue with the current/default configuration. } } else { // The task will continue with the current/default configuration. } } else { // If no saved config for this mode, record this window's current profile as // that mode's choice in the window-local map instead of the shared // modeApiConfigs store: the shared write would publish this view's profile to // every other window (#2110). The recorded profile is still this view's // effective one, so a sibling view holding the shared pin cannot leak its // profile into this one. const currentApiConfigNameAfter = this.getValues().currentApiConfigName if (currentApiConfigNameAfter) { const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter) if (config?.id) { this.localModeConfigIds.set(newMode, config.id) } } } } } } catch (error) { // Two reasons to keep the switch instead of reconciling: once the mode-linked // activation has started writing shared state, a mode-only rollback would pair // the old mode with the new profile; and after a timeout abort the queue has // advanced, so a newer mutation may own these fields and replaying the // pre-switch values would clobber it. if (!activationStarted && !signal?.aborted) { await reconcileSwitchWrites() } else if (signal?.aborted) { // After an abort the mutation queue has advanced: a newer mutation may // already own the mode fields, so emitting here could announce a mode the // newer mutation replaced - listeners are intentionally not notified on // this path. this.log(`[handleModeSwitch] Skipping rollback for aborted switch to "${newMode}"`) } else { // The activation had already written the activated profile: the switch is // kept. Listeners must still learn the committed mode before the rethrow, // and the webview must refresh in case the activation failed before its // own state post. if (viewScopedSwitch) { this.emit(RooCodeEventName.ModeChanged, newMode) } if (targetTask !== null) { try { await this.postStateToWebview() } catch (postError: unknown) { this.log( `[handleModeSwitch] Mode switch to "${newMode}" kept but the state post failed: ${ postError instanceof Error ? postError.message : String(postError) }`, ) } } } this.log( `[handleModeSwitch] Failed to persist mode "${newMode}": ${error instanceof Error ? error.message : String(error)}`, ) throw error } // The switch has committed: notify listeners only now, so a reconciled failure // never leaves listeners tracking a mode the stores rolled back from. After an // abort the mutation queue has advanced: announce only while this switch's // committed mode is still current - a superseded commit stays silent because // the newer mutation already announced its own mode. if (signal?.aborted && this.getValues().mode !== newMode) { return } if (viewScopedSwitch) { this.emit(RooCodeEventName.ModeChanged, newMode) } // The switch has committed: a UI-refresh failure must not roll it back, so the // trailing post runs outside the reconciled region and its failure is only logged. if (targetTask !== null) { try { await this.postStateToWebview() } catch (postError: unknown) { this.log( `[handleModeSwitch] Mode switch to "${newMode}" committed but the state post failed: ${ postError instanceof Error ? postError.message : String(postError) }`, ) } } } // Provider Profile Management private captureInitialModeConfigIds(): void { this.initialModeConfigIds = this.providerSettingsManager.getModeConfigIds().catch((error) => { this.log(`Failed to snapshot mode profile choices: ${error instanceof Error ? error.message : error}`) return {} }) } private async getModeConfigId(mode: Mode): Promise { const cachedId = this.localModeConfigIds.get(mode) ?? (await this.initialModeConfigIds)[mode] // An unmapped mode keeps this provider's current profile, even if another window maps it later. if (!cachedId) return undefined if ((await this.providerSettingsManager.listConfig()).some(({ id }) => id === cachedId)) { return cachedId } return this.providerSettingsManager.getModeConfigId(mode) } public async setModeConfig(mode: Mode, id: string): Promise { await this.providerSettingsManager.setModeConfig(mode, id) this.localModeConfigIds.set(mode, id) } /** * The window-local entry for a mode, without consulting the shared mapping that * `getModeConfigId` falls back to. Callers that write through `setModeConfig` * snapshot this before the write so a compensation can undo both layers. */ public getLocalModeConfigId(mode: Mode): string | undefined { return this.localModeConfigIds.get(mode) } /** * Compensation seam for `setModeConfig`: put this window's entry back exactly as * it was. An undefined `localId` means the window had no entry, and deleting is * what restores `getModeConfigId`'s fallback to the opening snapshot - leaving a * stale entry here would out-rank the shared mapping the caller restores with. */ public restoreLocalModeConfig(mode: Mode, localId: string | undefined): void { if (localId === undefined) { this.localModeConfigIds.delete(mode) } else { this.localModeConfigIds.set(mode, localId) } } /** * Updates the current task's API handler. * Rebuilds when: * - provider or model changes, OR * - explicitly forced (e.g., user-initiated profile switch/save to apply changed settings like headers/baseUrl/tier). * Always synchronizes task.apiConfiguration with latest provider settings. * @param providerSettings The new provider settings to apply * @param options.forceRebuild Force rebuilding the API handler regardless of provider/model equality */ private updateTaskApiHandlerIfNeeded( providerSettings: ProviderSettings, options: { forceRebuild?: boolean; skipCurrentTaskRebuild?: boolean; expectedCurrentTaskId?: string } = {}, ): void { if (options.skipCurrentTaskRebuild) return const task = this.getCurrentTask() if (!task || (options.expectedCurrentTaskId && task.taskId !== options.expectedCurrentTaskId)) return const { forceRebuild = false } = options // Determine if we need to rebuild using the previous configuration snapshot const prevConfig = task.apiConfiguration const prevProvider = prevConfig?.apiProvider const prevModelId = prevConfig ? getModelId(prevConfig) : undefined const newProvider = providerSettings.apiProvider const newModelId = getModelId(providerSettings) const needsRebuild = forceRebuild || prevProvider !== newProvider || prevModelId !== newModelId if (needsRebuild) { // Use updateApiConfiguration which handles both API handler rebuild and parser sync. // Note: updateApiConfiguration is declared async but has no actual async operations, // so we can safely call it without awaiting. task.updateApiConfiguration(providerSettings) } else { // No rebuild needed, just sync apiConfiguration ;(task as any).apiConfiguration = providerSettings } } getProviderProfileEntries(): ProviderSettingsEntry[] { return this.contextProxy.getValues().listApiConfigMeta || [] } getProviderProfileEntry(name: string): ProviderSettingsEntry | undefined { return this.getProviderProfileEntries().find((profile) => profile.name === name) } public hasProviderProfileEntry(name: string): boolean { return !!this.getProviderProfileEntry(name) } async upsertProviderProfile( name: string, providerSettings: ProviderSettings, activate: boolean = true, ): Promise { try { return await this.enqueueProviderProfileMutation( (signal) => this.persistProviderProfile(name, providerSettings, activate, signal), { runToCompletion: true }, ) } catch (error) { this.log( `Error create new api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) vscode.window.showErrorMessage(t("common:errors.create_api_config")) return undefined } } /** * Applies a model change to the latest stored profile inside the mutation queue, * so a stale webview snapshot cannot overwrite newer profile settings. * A `null` patch value clears the key. */ async updateProfileModel(name: string, expectedProvider: string, patch: Record): Promise { let partialState = false try { await this.enqueueProviderProfileMutation( async (signal) => { const { name: _name, ...stored } = await this.providerSettingsManager.getProfile({ name }) // Unset provider (e.g. the seeded default profile) resolves to anthropic, matching getState(). const storedProvider = stored.apiProvider ?? providerIdentifiers.anthropic if (storedProvider !== expectedProvider) { throw new Error( `Profile "${name}" provider changed from "${expectedProvider}" to "${storedProvider}"`, ) } const merged: Record = { ...stored, apiProvider: storedProvider } for (const [key, value] of Object.entries(patch)) { if (PROFILE_MODEL_ID_PATCH_KEYS.has(key)) { if (typeof value !== "string" || value.length === 0) { throw new Error(`Key "${key}" must be a non-empty string in a model patch`) } merged[key] = value } else if (PROFILE_MODEL_RESET_ONLY_KEYS.has(key)) { if (value !== null && value !== undefined) { throw new Error(`Key "${key}" can only be cleared in a model patch`) } delete merged[key] } else { throw new Error(`Key "${key}" is not allowed in a model patch`) } } if (storedProvider === providerIdentifiers.bedrock) { if (merged.apiModelId === BEDROCK_CUSTOM_ARN_MODEL_ID) { // The allow-list only sees apiModelId, so a patch must not select an ARN it cannot supply. if (!merged.awsCustomArn) { throw new Error( `Model "${BEDROCK_CUSTOM_ARN_MODEL_ID}" requires an existing custom ARN`, ) } } else { // A retained ARN would override the allow-listed model, so drop it with its context fields. for (const key of PROFILE_MODEL_RESET_ONLY_KEYS) { if (key.startsWith("aws")) delete merged[key] } } } const { organizationAllowList } = await this.getState() if (!ProfileValidator.isProfileAllowed(merged as ProviderSettings, organizationAllowList)) { throw new OrganizationAllowListViolationError( t("common:errors.violated_organization_allowlist"), ) } if (signal.aborted) return try { await this.persistProviderProfile(name, merged as ProviderSettings, true, signal) } catch (persistError) { // Saving and activating are separate writes. Put the previous profile back so // storage, context settings, and the task do not disagree about the model. try { await this.persistProviderProfile(name, stored as ProviderSettings, true, signal) } catch (restoreError) { partialState = true this.log( `Error restoring profile after failed model update: ${JSON.stringify(restoreError, Object.getOwnPropertyNames(restoreError), 2)}`, ) } throw persistError } }, { runToCompletion: true }, ) } catch (error) { this.log(`Error update profile model: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`) vscode.window.showErrorMessage( partialState ? t("common:errors.update_profile_model_partial") : error instanceof OrganizationAllowListViolationError ? error.message : t("common:errors.create_api_config"), ) } } private async persistProviderProfile( name: string, providerSettings: ProviderSettings, activate: boolean, signal: AbortSignal, ): Promise { // TODO: Do we need to be calling `activateProfile`? It's not // clear to me what the source of truth should be; in some cases // we rely on the `ContextProxy`'s data store and in other cases // we rely on the `ProviderSettingsManager`'s data store. It might // be simpler to unify these two. // Snapshot the prior manager record before the save so a failed post-save // read-back can compensate the landed write instead of leaving the record // changed while the shared store was not. let previousRecord: Awaited> | undefined try { previousRecord = await this.providerSettingsManager.getProfile({ name }) } catch (error) { // getProfile wraps a missing record and a storage read failure in the same plain // Error, so absence is classified with hasConfig instead of by message text. A read // failure that is not absence must not be mistaken for a create: the compensation // below would then deleteConfig a profile that exists and take its credentials with // it. Fail closed before saveConfig runs; a failing hasConfig fails closed too. if (await this.providerSettingsManager.hasConfig(name)) { throw error } } // TODO: Do we need to be calling `activateProfile`? It's not // clear to me what the source of truth should be; in some cases // we rely on the `ContextProxy`'s data store and in other cases // we rely on the `ProviderSettingsManager`'s data store. It might // be simpler to unify these two. // The profile rename holds the manager's cross-instance critical section across its // name check, its save, and its compensation delete. Only the per-instance mutation // queue orders this view's writes, so a same-name save from another view can land // between that rename's check and its save and then be deleted by its compensation. // Joining the section here puts both writers behind one lock; only the store write // is wrapped, so the shared lock is never held across the activation work below. const id = await this.providerSettingsManager.runExclusiveAcrossInstances(() => this.providerSettingsManager.saveConfig(name, providerSettings), ) if (signal.aborted) return id // saveConfig normalizes the record (schema parse, legacy downgrades): // read the stored copy back and use it for every activation write, // sibling refresh, overlay, and task-handler update below, so raw // webview fields the profile schema strips cannot enter the shared // store, sibling view state, or task configuration. Fail closed when // the read-back fails: the raw caller payload must never stand in for // the validated record, so the landed save is compensated and the // mutation group fails instead of propagating unvalidated settings. let normalizedSettings: ProviderSettings try { const { name: _savedName, id: _savedId, ...storedRecord } = await this.providerSettingsManager.getProfile({ name }) normalizedSettings = storedRecord as ProviderSettings } catch (error) { // Fail closed: compensate the landed save (restore the prior record, // or delete a landed create) and fail the group so the raw caller // payload never stands in for the validated stored record. try { if (previousRecord) { const { name: _previousName, id: _previousId, ...previousSettings } = previousRecord await this.providerSettingsManager.saveConfig(name, previousSettings) } else { await this.providerSettingsManager.deleteConfig(name) } } catch (restoreError) { this.log( `[persistProviderProfile] failed to compensate the landed save of '${name}': ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } throw new Error( `Provider profile '${name}' could not be read back after save: ${error instanceof Error ? error.message : String(error)}`, ) } if (activate) { const { mode } = await this.getState() // These promises do the following: // 1. Adds or updates the list of provider profiles. // 2. Sets the current provider profile. // 3. Sets the current mode's provider profile. // 4. Copies the provider settings to the context. // // Note: 1, 2, and 4 can be done in one `ContextProxy` call: // this.contextProxy.setValues({ ...providerSettings, listApiConfigMeta: ..., currentApiConfigName: ... }) // We should probably switch to that and verify that it works. // I left the original implementation in just to be safe. const listApiConfigMeta = await this.providerSettingsManager.listConfig() // Same sibling protection as the activation path: the shared write // below replaces the shared store, so pin other profiles' settings // into the views that reference them first. // The save above has already landed, so a rejected snapshot must not leave it // standing alone: a sibling would keep reporting a pin whose record this call // could not read, while the profile on disk already holds the new settings. Roll // the landed write back with the same restore-or-delete decision the read-back // failure above uses - a landed create is deleted rather than restored to a // record that never existed - and rethrow the original error unchanged, so the // caller sees the failure that happened rather than the compensation's. The // compensation below repeats the shape above on purpose: the two failure routes // stay readable at their own call sites instead of sharing a helper that neither // one could change without moving the other. try { await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(name) } catch (error) { try { if (previousRecord) { const { name: _previousName, id: _previousId, ...previousSettings } = previousRecord await this.providerSettingsManager.saveConfig(name, previousSettings) } else { await this.providerSettingsManager.deleteConfig(name) } } catch (restoreError) { this.log( `[persistProviderProfile] failed to compensate the landed save of '${name}': ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } throw error } // `allSettled` so the caller's error path never races a write still in flight. const activationResults = await Promise.allSettled([ this.updateGlobalState("listApiConfigMeta", listApiConfigMeta), // Route through setValue so the in-memory viewLocalState buffer tracks the // activated profile: a plain global write would leave a stale loaded // currentApiConfigName shadowing the new value in getValues(). this.setValue("currentApiConfigName", name), this.setModeConfig(mode, id), this.contextProxy.setProviderSettings(normalizedSettings), // setProviderSettings writes the shared store directly, bypassing the // view-local mutation path: clear this view's buffered apiConfiguration // overlay (if any) so a stale loaded profile cannot keep shadowing the // new settings in getState(). this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), ]) const failedActivation = activationResults.find( (result): result is PromiseRejectedResult => result.status === "rejected", ) if (failedActivation) throw failedActivation.reason // Other live views may have buffered this profile's settings earlier; // refresh them so their getState() cannot report the updated profile's // name with stale settings. await this.refreshViewLocalStateForUpdatedProfile(name, normalizedSettings) // Change the provider for the current task. // TODO: We should rename `buildApiHandler` for clarity (e.g. `getProviderClient`). this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) // Keep the current task's sticky provider profile in sync with the newly-activated profile. await this.persistStickyProviderProfileToCurrentTask(name) } else { const listApiConfigMeta = await this.providerSettingsManager.listConfig() await this.updateGlobalState("listApiConfigMeta", listApiConfigMeta) this._updateViewLocalStateFromMutation({ listApiConfigMeta }) // A save that does not activate still changes the profile's settings, and // every view pinned to it buffers a full copy of them. Refresh those views // (and this one when it is the pinned view) or their getState() keeps // serving the settings captured before the save under the same name. if (this.pinnedProfileName === name) { await this._saveViewLocalStateFromMutation({ apiConfiguration: normalizedSettings }) // Only rebuild when the task actually runs under the saved profile: a // view pinned to this profile can hold a task that follows a different // sticky profile, and the forced rebuild would silently switch that // conversation to the saved profile's settings. if (this.getCurrentTask()?.taskApiConfigName === name) { this.updateTaskApiHandlerIfNeeded(normalizedSettings, { forceRebuild: true }) } } await this.refreshViewLocalStateForUpdatedProfile(name, normalizedSettings) } await this.postStateToWebview() return id } async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { const globalSettings = this.contextProxy.getValues() let profileToActivate: string | undefined = globalSettings.currentApiConfigName if (profileToDelete.name === profileToActivate) { profileToActivate = this.getProviderProfileEntries().find(({ name }) => name !== profileToDelete.name)?.name } if (!profileToActivate) { throw new Error("You cannot delete the last profile") } // Snapshot the manager record and every persistence surface this // deletion rewrites BEFORE the manager delete commits, so a failure // inside the write group below can be compensated instead of leaving // the secrets-backed record gone while metadata and view pins still // reference it. let previousRecord: Awaited> | undefined // The pin-write claims this deletion own re-point is about to overwrite, view by // view. Held as a local rather than a field: two overlapping deletions must not share // one snapshot, or the second re-point would overwrite the first capture - the very // failure this restores. let priorPinWriteOwners: Map | undefined try { previousRecord = await this.providerSettingsManager.getProfile({ name: profileToDelete.name }) } catch (error) { // Absence is classified with hasConfig, not by message text: getProfile wraps both // a missing record and a storage read failure in one plain Error. Only an absent // record may proceed name-only - the idempotent not-found path below still prunes // the stale list entry, and compensation skips the record restore. Continuing past // a read failure would delete the secrets-backed record and then skip its restore. if (await this.providerSettingsManager.hasConfig(profileToDelete.name)) { throw error } } const previousEntries = this.getProviderProfileEntries() const previousSelection = globalSettings.currentApiConfigName const previousSharedSettings = this.contextProxy.getProviderSettings() const previousViewStates = this.getPersistedViewStates({ fresh: true }) // The manager owns a gate of its own - the profile its store selects and the mode -> // profile mapping - and activating the replacement below rewrites both. It lives in the // secrets-backed profiles file behind the manager lock, so none of the context-gate // restores in the catch below can reach it: snapshot it here, before the delete commits, // through the manager’s own read (a copy of the map, not the live object). const previousManagerGate = await this.providerSettingsManager.getSelectionAndModeConfigs() // What the activation below writes into that gate: the replacement’s name, and its id as // the profile list records it (the mode mapping is keyed by id). The restore legs compare // the manager’s current report against these, and only roll back while they still match. const activatedManagerGateName = profileToActivate const activatedManagerGateId = previousEntries.find((entry) => entry.name === profileToActivate)?.id // What each sibling re-pin below moves in that view's own live state, filled by the re-pin as it // goes. The catch below can only restore what actually changed, and a callback whose write had // already started when the mutation timed out changes live state that no earlier snapshot names, // so the record has to come from the re-pin itself. const rePinLiveChanges: SiblingProfileRePinLiveChange[] = [] // One opaque token for this deletion. Every durable pin this deletion re-points is stamped with // it, and both rollback legs put a pin back only while that stamp is still there: the name this // deletion writes is a name a sibling can write too, so only the writer identity tells this // deletion own write from a newer selection of the same profile. const pinWriteOwner = Symbol("deleteProviderProfile durable view pin writes") // Remove the profile from the settings store (context.secrets) so it cannot be // resurrected by a later listApiConfigMeta sync. A not-found rejection means // the secret was already gone (e.g. pruned by an earlier run): branch on the // typed ProviderSettingsNotFoundError so the stale list entry below is still // pruned as an idempotent success, while any other failure (e.g. refusing to // delete the last remaining configuration) propagates. Matching message text // instead would let a profile whose name contains "not found" swallow an // unrelated failure. try { // The delete below is a whole-profiles-file write built from a map this call loads. // Join the critical section every other view already joins for its own save, rename and // webview delete: without it a save through another manager instance - the sidebar and // each editor tab construct their own over the same secrets - lands between this load // and this store, and the map written here simply lacks that profile. await this.providerSettingsManager.runExclusiveAcrossInstances(async () => { await this.providerSettingsManager.deleteConfig(profileToDelete.name) }) } catch (error) { if (!(error instanceof ProviderSettingsNotFoundError)) { throw error } this.log( `deleteProviderProfile: settings for '${profileToDelete.name}' were not found; pruning the stale list entry only`, ) } try { // Ownership travels on the writes themselves: the re-point below carries the token, and so does // the activation of this view own pin further down. Any other write this view makes while this // deletion runs - a settings save from its webview, say - carries none, and the rollback then // leaves that newer choice alone. // Re-point any persisted view pin that referenced the deleted profile so views // do not rehydrate a missing profile name after a reload. priorPinWriteOwners = await this.repointPersistedViewStates(profileToDelete.name, profileToActivate, { pinWriteOwner, }) // Whether this deletion has to re-anchor this view onto the replacement. The second leg // is a view whose own pin names the deleted profile. The first leg is narrower than it // reads: a view with no pin of its own does not resolve to the deleted profile, it // follows the shared selection, and the deletion hands that selection to it through // activation regardless of which profile was removed - the same hand-off the manager // gate and the current task handler depend on. Measured both deletions: with the shared // selection pointing at a survivor, deleting an unrelated profile still activates the // selection for this view and leaves it pinned to it; deleting the profile the selection // names activates the replacement. Either way what the view serves afterwards is the // profile the shared store holds. const viewFollowsDeletedProfile = this.viewLocalState.currentApiConfigName === undefined || this.viewLocalState.currentApiConfigName === profileToDelete.name if (viewFollowsDeletedProfile) { // Apply the replacement through the activation path so this view's // viewLocalState.apiConfiguration and the current task's api handler are // refreshed; a name-only update would leave the deleted profile's settings // behind in both. // The activation writes this view own pin through this view view-local save, exactly as a // selection would: hand that write the deletion token so the claim lands on the deletion. // The replay leg in the catch below unwinds the live views the sibling re-pin recorded, // and that re-pin filters this view out on purpose. The activation two lines down moves // this view own buffer and the task it runs, so this view is recorded into the same list. const ownPinRestorable = previousViewStates[this.viewStateId]?.currentApiConfigName === profileToDelete.name const ownPin = this.pinnedProfileName const ownSettings = this.viewLocalState.apiConfiguration const ownTask = this.getCurrentTask() const ownTaskSettings = ownTask?.apiConfiguration // read before the activation rebuilds that handler const ownTaskPin = ownTask?.taskApiConfigName === profileToDelete.name ? ownTask.taskApiConfigName : undefined const ownLiveChange: SiblingProfileRePinLiveChange = { instance: this, previousPin: ownPin, previousSettings: ownSettings, appliedPin: profileToActivate, task: undefined, } if (ownPinRestorable) { rePinLiveChanges.push(ownLiveChange) } await this.activateProviderProfile({ name: profileToActivate }, { pinWriteOwner }) // The record is taken before the queue runs, unlike a sibling record taken inside it: // activation is a shared path, and the replay leg owns the precision - it applies only // while this view still sits on the applied name and this deletion still holds the claim. const ownTaskAfter = this.getCurrentTask() if (ownTaskPin && ownTaskAfter && ownTaskAfter.taskId === ownTask?.taskId) { ownLiveChange.task = { taskId: ownTaskAfter.taskId, previousName: ownTaskPin, appliedName: profileToActivate, previousSettings: ownTaskSettings, } } // The return below would otherwise skip the sibling re-pin further down: // the activation's pinned-name refresh only selects siblings pinned to // the replacement, so live views still buffered on the deleted profile // must be re-pointed here as well, with the replacement's settings when // they can be resolved (a name-only re-pin is still better than leaving // the deleted name behind). let replacementSettings: ProviderSettings | undefined try { const { name: _replacementName, ...settings } = await this.providerSettingsManager.getProfile({ name: profileToActivate, }) replacementSettings = settings as ProviderSettings } catch (error) { this.log( `[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${ error instanceof Error ? error.message : String(error) }`, ) } // The live-change records are handed to the re-pin so the compensation in the catch below // can replay them even when this call rejects. await this.rePinViewLocalStateForDeletedProfile( profileToDelete.name, profileToActivate, replacementSettings, rePinLiveChanges, pinWriteOwner, ) return } // This view pins an unrelated profile, which must survive the deletion: sync the // shared profile list and post the updated state only. The buffer already holds // the surviving pin, so the current-profile slot is left untouched here: a // setValue would only trigger a viewStates prune write and could clobber the pin // with the shared slot's value. const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name) // Write only the profile list back: replaying the full settings snapshot // captured above would also rewrite unrelated keys (including viewStates, // which ClineProvider mutates directly in storage for concurrent views) // with this view's stale cached copy. await this.contextProxy.setValue("listApiConfigMeta", entries) // Resolve the surviving profile's settings so the shared provider keys // and any other live view still pinned to the deleted profile can be // updated with a matching configuration. let survivingSettings: ProviderSettings | undefined try { const { name: _survivingName, ...settings } = await this.providerSettingsManager.getProfile({ name: profileToActivate, }) survivingSettings = settings as ProviderSettings } catch (error) { this.log( `[deleteProviderProfile] Unable to resolve API profile '${profileToActivate}': ${ error instanceof Error ? error.message : String(error) }`, ) } // This view's own pin names a surviving profile at this point: a view pinned // to the deleted profile (or with no pin of its own) took the activation // path above and returned, so only the shared selection can need re-pointing // here, and this view's own overlay can be left alone. const deletedWasGlobal = profileToDelete.name === globalSettings.currentApiConfigName // The selection and provider-key writes below move shared state onto the surviving // profile. A live sibling pinned to a profile that is neither the deleted one nor the // replacement, and which has no API overlay of its own, would then report its own pin // name together with the replacement's settings, because getState() merges the shared // provider keys under the pin: a task created from that view would run against the // wrong provider, model and credentials. Capture each such sibling's own profile // settings into its overlay first, exactly as activation and upsert do before their // shared writes. if (deletedWasGlobal) { // This view is part of its own snapshot here: its pin can name a third surviving // profile and carry no overlay of its own, and the shared writes below would then // serve this view the replacement's settings under its own pin name - exactly the // failure the helper guards for siblings. The helper excludes the calling view by // default because activation and upsert own their own overlay handling; a deletion // moves the shared store under an unrelated pin, so it opts this view in. await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(profileToActivate, { includeSelf: true }) // The shared selection changed, but this view's own pin still names a // surviving profile: update the shared store only, leaving the // view-local pin untouched. await this.contextProxy.setValue("currentApiConfigName", profileToActivate) } if (deletedWasGlobal && survivingSettings) { // The deleted profile was the globally active one, so the shared provider // keys still carry its settings; replace them so getState() reports the // surviving profile's configuration. await this.contextProxy.setProviderSettings(survivingSettings) } // Re-pin other live views still buffered on the deleted profile: their // buffer and durable viewStates entry would otherwise keep serving the // deleted profile's name and configuration. // The live-change records are handed to the re-pin so the compensation in the catch below // can replay them even when this call rejects. await this.rePinViewLocalStateForDeletedProfile( profileToDelete.name, profileToActivate, survivingSettings, rePinLiveChanges, pinWriteOwner, ) // Everything this deletion can still put back is behind this line: the manager record, the // shared surfaces, the durable pins and the sibling buffers. What follows only tells this // view webview what the committed deletion changed, so its failure is reported rather than // compensated - a state refresh that throws must not undo writes this deletion no longer // owns. The re-pin above stays inside the compensated region: it is the last write this // deletion can still roll back, and its failure still rejects the deletion. try { await this.postStateToWebview() } catch (refreshError) { this.log( `[deleteProviderProfile] deleted the profile but the final state refresh failed: ${refreshError instanceof Error ? refreshError.message : String(refreshError)}`, ) } } catch (error) { // The manager delete committed but a later write failed: restore the // deleted record first, then the shared metadata, selection, and shared // settings the deletion had rewritten, then the manager gate, and finally the // view pins in both layers they live in. Every leg follows one reconciliation // rule: undo only the value this deletion still owns. A leg that finds a // surface another mutation had already moved leaves it to that owner, and the // live replay runs only on the views the durable pin restore actually rewrote, // so no leg puts storage back while the layer above it stays on the // replacement. // Each restore is independent and logged; the original // failure is what the caller sees. if (previousRecord) { try { // Restore with the record's original id: the record is absent at this point (the // delete committed), so saveConfig would otherwise mint a new one while the // mode mappings and task pins still name the original. Only the name is dropped. const { name: _previousName, ...previousSettings } = previousRecord // Restore only what this deletion still owns: inside the very section this undoes the // delete, ask the store whether the name came back since the snapshot. A newer writer // that re-created it owns that record, and replaying this pre-delete copy over it // would put back a record nobody wrote. const recordRestored = await this.providerSettingsManager.runExclusiveAcrossInstances(async () => { if (await this.providerSettingsManager.hasConfig(profileToDelete.name)) { return false } await this.providerSettingsManager.saveConfig(profileToDelete.name, previousSettings) return true }) if (!recordRestored) { this.log( `[deleteProviderProfile] left the manager record of ${profileToDelete.name} to a newer writer`, ) } } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the manager record '${profileToDelete.name}': ${ restoreError instanceof Error ? restoreError.message : String(restoreError) }`, ) } } try { // Merge rather than clobber: another instance may have added // profiles between the snapshot and the compensation. const currentEntries = this.getProviderProfileEntries() const deletedEntry = previousEntries.find((entry) => entry.name === profileToDelete.name) if (deletedEntry && !currentEntries.some((entry) => entry.name === profileToDelete.name)) { await this.contextProxy.setValue("listApiConfigMeta", [...currentEntries, deletedEntry]) } } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the profile list: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } // The manager gate the activation moved onto the replacement. Restored through the same // write paths the activation used - activateProfile for the selection, setModeConfig for // each mapping - and only while the manager still reports what this deletion wrote: a // concurrent activation or a later mutation may own the gate by now, and replaying the // pre-delete values over it would undo that work. The record and list restores above run // first so the name and ids being restored still exist. try { const currentManagerGate = await this.providerSettingsManager.getSelectionAndModeConfigs() if ( previousManagerGate.currentApiConfigName !== activatedManagerGateName && currentManagerGate.currentApiConfigName === activatedManagerGateName ) { await this.providerSettingsManager.activateProfile({ name: previousManagerGate.currentApiConfigName, }) } const previousModeConfigs = previousManagerGate.modeApiConfigs ?? {} const currentModeConfigs = currentManagerGate.modeApiConfigs ?? {} for (const mode of new Set([...Object.keys(previousModeConfigs), ...Object.keys(currentModeConfigs)])) { const previousModeConfigId = previousModeConfigs[mode] const currentModeConfigId = currentModeConfigs[mode] if ( activatedManagerGateId !== undefined && currentModeConfigId === activatedManagerGateId && previousModeConfigId !== currentModeConfigId ) { await this.providerSettingsManager.setModeConfig(mode as Mode, previousModeConfigId) } } } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the manager selection and mode configs: ${ restoreError instanceof Error ? restoreError.message : String(restoreError) }`, ) } try { await this.contextProxy.setValue("currentApiConfigName", previousSelection) } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the shared selection: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } try { await this.contextProxy.setProviderSettings(previousSharedSettings) } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the shared provider settings: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } // Both pin legs below act on the same set of views, so the durable leg reports // which views it actually rewrote and the live leg replays exactly those. The // name a rolled-back entry has to still carry is the one // repointPersistedViewStates wrote into every entry that named the deleted // profile. const rolledBackViewIds = new Set() const rePointedProfileName = profileToActivate try { const restore = ClineProvider.persistedViewStateWriteQueue.then(async () => { const current = this.getPersistedViewStates({ fresh: true }) const merged = { ...current } const restoredViewIds: string[] = [] for (const [viewId, entry] of Object.entries(previousViewStates)) { if (entry?.currentApiConfigName !== profileToDelete.name) { continue } // Only an entry that still holds the name this deletion re-pointed it to is // this deletion own to undo: an entry a sibling moved since the snapshot - // its own selection of the replacement or of another profile - or one a // concurrent write dropped altogether, belongs to whoever moved it, and // rewriting it here would undo that newer state instead of undoing this // deletion. if (current[viewId]?.currentApiConfigName !== rePointedProfileName) { // The entry moved past this deletion own replacement, so the pin is not its own to undo // yet: the writer the id-keyed claim names is still holding it. What this deletion read // before it changed anything stays owed to it, and the deletion holding the claim unwinds // it when its own rollback hands the claim back. this._deferViewPinRollbackToClaimHolder(viewId, entry, pinWriteOwner, priorPinWriteOwners) continue } // The name match above is not ownership. A sibling that selected the replacement itself wrote // this very name into its own entry, and its own re-pin was declined at the queued name check // because the name already matched, so no live change was recorded for it either. Restoring // that entry here undoes the choice the user made while the live view stays on the profile they // chose, and a reload then undoes it a second time. Ownership is the writer named by the claim // keyed by the persisted view id: the write paths stamp that record themselves, a rollback that // hands a claim back updates it, and it outlives both the view whose field it mirrors and the // deletion whose token it carries. The live field is not consulted here. A view that closes // while this deletion awaits a sibling takes its field with it, and a deletion that already // rolled back left its own token on that field while the record said the pin had gone back to // an earlier writer, so a merge leg that asked the field would skip a pin the record calls its // own. Replaying a pin into an open view is the other leg and keeps its own current-owner // guard there, so a newer live choice is still never overwritten. An entry no write of this // session ever claimed - one this deletion re-pointed while its view was already gone, or one // an earlier session left under a name that happens to match - has no record to contradict the // name rule, and only there does this deletion fall back to the field of the live view holding // the id, so a view whose entry was re-keyed out from under its own claim is still asked who // wrote it. const durableClaims = ClineProvider.durableViewPinWriteOwnersByViewId const holder = durableClaims.has(viewId) ? undefined : ClineProvider.getAllInstances().find((instance) => instance.viewStateId === viewId) const claimedByAnotherWriter = holder ? holder.durableViewPinWriteOwner !== pinWriteOwner : durableClaims.has(viewId) && durableClaims.get(viewId) !== pinWriteOwner if (claimedByAnotherWriter) { continue } merged[viewId] = entry restoredViewIds.push(viewId) } // A pin an earlier rollback owed and this deletion now hands back unwinds in this same write: // the earlier deletion read a value this deletion never touched, and stopping at this deletion // own replacement would leave the pin on a middle profile although both deletions failed. The // claim bookkeeping below puts the record under the writer that value really belonged to. const dischargedRollbacks: DischargedViewPinRollback[] = [] for (const [owedViewId, obligation] of ClineProvider.deferredViewPinRollbacksByViewId) { if (obligation.awaitingOwner !== pinWriteOwner || !restoredViewIds.includes(owedViewId)) { continue } merged[owedViewId] = obligation.entry dischargedRollbacks.push({ viewId: owedViewId, hadPriorClaim: obligation.hadPriorClaim, priorClaim: obligation.priorClaim, }) } if (restoredViewIds.length > 0) { await this.contextProxy.setValue("viewStates", merged) // Recorded only after the write landed: a restore whose write threw // restored no view, and one signal for both legs then means the live // leg replays nobody. for (const viewId of restoredViewIds) { rolledBackViewIds.add(viewId) } // The restore is itself a name-carrying write, so it claims the pins it put back on the // live record: the live replay leg below then replays only views nobody selected after // this line. this._recordDurableViewPinWriteOwners(restoredViewIds, pinWriteOwner) // Then put back the claims this deletion own re-point replaced, on the id-keyed record // only: an entry re-pointed while its view was closed has no field to hold the claim, // so that record is the only one its rollback can read, and leaving the re-point token // on it is what makes an earlier deletion skip a pin the later deletion never owned. // Absence and a recorded undefined are two different states, and the captured map keeps // them apart the way the record does - a key present with an undefined value was // recorded, no key was not - so a recorded undefined is written back as one and a view // with no captured key loses the key again. Every view this loop restores named the // deleted profile in this deletion own snapshot, so no captured key here means this // deletion found no claim to capture. The live holder field is left to the claim the // restore itself wrote, so a newer live choice is never claimed away. for (const viewId of restoredViewIds) { if (priorPinWriteOwners?.has(viewId) === true) { this["_rememberDurableViewPinWriteOwner"](viewId, priorPinWriteOwners.get(viewId)) continue } ClineProvider.durableViewPinWriteOwnersByViewId.delete(viewId) } // The value that came back belonged to the writer the earlier deletion captured, not to this // deletion: the record goes under that writer - a recorded undefined is written back as one, // a view with no captured claim loses the key again - and the obligation this write // discharged is dropped. for (const discharged of dischargedRollbacks) { if (discharged.hadPriorClaim) { this["_rememberDurableViewPinWriteOwner"](discharged.viewId, discharged.priorClaim) } else { ClineProvider.durableViewPinWriteOwnersByViewId.delete(discharged.viewId) } ClineProvider.deferredViewPinRollbacksByViewId.delete(discharged.viewId) } } }) ClineProvider.persistedViewStateWriteQueue = restore.catch(() => {}) await restore } catch (restoreError) { this.log( `[deleteProviderProfile] failed to restore the persisted view pins: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, ) } try { // The durable merge above rolls the pins back in storage; this leg rolls back what the same // re-pin moved in each view's own buffer and in the task that view runs. Durable state, // buffered state and a running conversation name three different profiles until both legs // agree, so this leg replays only the views that durable leg rewrote: replaying a // buffer back while its own storage still holds the replacement would replace one // three-way divergence with another. A view left on the replacement because its durable // restore did not land is reported as an incomplete recovery instead. const unreconciled = await this.restoreSiblingLiveStateAfterRolledBackProfileRePin( rePinLiveChanges, rolledBackViewIds, pinWriteOwner, ) if (unreconciled.length > 0) { this.log( `[deleteProviderProfile] incomplete view-pin rollback, live state left on the replacement for views: ${unreconciled.join(" , ")}`, ) } } catch { // A repair that only refreshes state adds nothing to report here, and a throw from // it means the rollback itself broke halfway: the restored buffer is observable // through the state of the view itself, and swallowing keeps the original deletion // failure - not a repair error - what the caller sees. } throw error } } /** * Replay the live changes a rolled-back profile deletion made in the sibling views it * re-pinned, for the views whose durable pin the same rollback actually rewrote. The * other compensation legs restore the manager record, the shared surfaces and the * durable view pins, which leaves a view whose re-pin had already committed holding the * replacement in its own buffer, and a task that ran under the deleted profile running * with the replacement's handler and sticky profile name. Both return to the values the * re-pin recorded, and only while this deletion still owns them: a view that selected * another profile in the meantime owns its own pin now, and a view whose durable * restore this deletion could not land stays on what its own storage says - replaying * onto it would put the buffer and the durable entry on two different profiles, which * is the divergence this leg exists to remove. The caller passes the view ids the * durable leg rewrote, and gets back the ids it left on the replacement so the caller * can report an incomplete recovery. Nothing is posted here. * A view that committed a selection of its own after the durable restore is left alone as well: * its buffer already names the profile its storage now holds, and only the durable write claim * tells that view from one this deletion still owns, because the selection re-selected the very * name the re-pin had applied. */ private async restoreSiblingLiveStateAfterRolledBackProfileRePin( liveChanges: readonly SiblingProfileRePinLiveChange[], rolledBackViewIds: ReadonlySet, pinWriteOwner: symbol, ): Promise { const unreconciled: string[] = [] for (const change of liveChanges) { const { instance } = change // Whether this deletion own durable restore brought the view back is the question that // decides what to report, so it is asked first: a view whose stored pin still holds the // replacement is an incomplete recovery whatever its buffer does, because moving the // buffer alone would break the agreement the rollback exists to restore. Asking the // live-pin question first skipped exactly the views whose two layers disagree, and the // report stayed silent about them. // The view that ran the deletion is not a reportable divergence here: if its own pin came // back the replay below returns it, and if it did not, either a newer writer owns that // entry or both of its layers still name the replacement, which agrees with itself. if (instance !== this && !rolledBackViewIds.has(instance.viewStateId)) { unreconciled.push(instance.viewStateId) continue } if (instance.pinnedProfileName !== change.appliedPin) { // Somebody moved this view off the applied name after the re-pin; the replay below is // written for a view still sitting on that name. continue } // What is left asks who wrote the pin the durable leg brought back. Neither check can // see a view that saved a selection of its own after that restore: such a view pins the // very name this deletion had applied, and its id is recorded because the durable leg // did roll it back. Its own write took the durable claim with it, and its buffer already // agrees with the profile its entry now holds, so replaying the previous pin here would // put the buffer under a name its own storage no longer carries. if (instance.durableViewPinWriteOwner !== pinWriteOwner) { continue } // Buffer only: the merge leg above already rolled this view's durable entry back, so the // replayed buffer agrees with storage, and no new durable write is queued behind it. instance._updateViewLocalStateFromMutation({ currentApiConfigName: change.previousPin, apiConfiguration: change.previousSettings, }) const task = change.task ? instance.getCurrentTask() : undefined if ( !change.task || task?.taskId !== change.task.taskId || task?.taskApiConfigName !== change.task.appliedName ) { continue } if (change.task.previousSettings) { instance.updateTaskApiHandlerIfNeeded(change.task.previousSettings, { forceRebuild: true }) } await instance.persistStickyProviderProfileToCurrentTask(change.task.previousName) } return unreconciled } private async persistStickyProviderProfileToCurrentTask( apiConfigName: string, options: { skipCurrentTaskRebuild?: boolean; expectedCurrentTaskId?: string } = {}, ): Promise { if (options.skipCurrentTaskRebuild) return const task = this.getCurrentTask() if (!task || (options.expectedCurrentTaskId && task.taskId !== options.expectedCurrentTaskId)) { return } try { // Update in-memory state immediately so sticky behavior works even before the task has // been persisted into taskHistory (it will be captured on the next save). task.setTaskApiConfigName(apiConfigName) const taskHistoryItem = this.getTaskHistoryItem(task.taskId) if (taskHistoryItem) { await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) } } catch (error) { // If persistence fails, log the error but don't fail the profile switch. this.log( `Failed to persist provider profile switch for task ${task.taskId}: ${ error instanceof Error ? error.message : String(error) }`, ) } } /** * Snapshot the settings of sibling views pinned to a different profile into * their view-local overlays before an activation or upsert overwrites the * shared provider-settings store. `getState()` merges the overlay over the * shared store, so a sibling pinned to another profile with no overlay would * otherwise start reporting its pin's name together with the newly activated * profile's settings - and a task created from that view would run against * the wrong provider, model, and credentials. Siblings pinned to the * activated profile are refreshed by `refreshViewLocalStateForUpdatedProfile`; * unpinned siblings follow the shared slot, where name and settings move * together. * * A pin that cannot be READ fails the whole snapshot so the caller does not write the * shared store: that sibling would otherwise report its pin's name with the activated * profile's settings and start tasks on them. Siblings already snapshotted keep an overlay * equal to their own pin's settings, which is what they reported before the aborted write. * * The one tolerated failure is a pin naming a profile the store no longer has * (`ProviderSettingsNotFoundError`): the deletion path re-points those views itself * (`rePinViewLocalStateForDeletedProfile`), and aborting here would let one stale view * block every later activation in the host. Same discrimination `deleteProviderProfile` * applies to its own missing-profile read. * * includeSelf opts the CALLING view into the same snapshot. A deletion moves the shared store * under this view's own pin when that pin names neither the deleted profile nor the * replacement, and the helper excludes the caller by default because activation and upsert * handle their own overlays. A caller that opts in must not be holding this view's mutation * queue - the self commit below writes through the same view-local save the queue commit * uses, without re-entering it. */ private async snapshotSiblingOverlaysBeforeSharedSettingsWrite( activatedProfileName: string | undefined, options: { includeSelf?: boolean } = {}, ): Promise { const includeSelf = options.includeSelf === true const affected = ClineProvider.getAllInstances().filter( (instance) => (instance !== this || includeSelf) && instance.pinnedProfileName !== undefined && instance.pinnedProfileName !== activatedProfileName && instance.viewLocalState.apiConfiguration === undefined, ) const unresolvedPins: Array<{ pinName: string; error: unknown }> = [] await Promise.all( affected.map(async (instance) => { const pinName = instance.pinnedProfileName // The guard below is a safety net only: the filter predicate above guarantees a // defined pin for every instance reaching this callback, and the filter-to-guard // chain is synchronous (no await), so no reachable state trips it. if (pinName === undefined) { return } try { const { name: _siblingPinName, ...settings } = await this.providerSettingsManager.getProfile({ name: pinName, }) // Commit through the sibling's own mutation queue with a pin re-check at // commit time: the sibling may have activated a different profile (or // gained a newer overlay) while this snapshot was in flight, and the // captured settings must never land on top of a newer pin. Direct // private access: compile-time safe across sibling instances. // This view's own pin (includeSelf) commits through the same view-local save the queue // commit below uses, without re-entering this view's mutation queue - a caller that // already holds it would deadlock - and its caller posts state when it is done. if (instance === this) { if (this.pinnedProfileName === pinName && this.viewLocalState.apiConfiguration === undefined) { await this._saveViewLocalStateFromMutation({ apiConfiguration: settings as ProviderSettings, }) } return } await instance["enqueueProviderProfileMutation"](async () => { if ( instance.pinnedProfileName !== pinName || instance.viewLocalState.apiConfiguration !== undefined ) { return } await instance._saveViewLocalStateFromMutation({ apiConfiguration: settings as ProviderSettings, }) await instance.postStateToWebview() }) } catch (error) { // A pin naming a deleted profile is tolerated: the deletion path re-points that // view itself, and one stale view must not block every later activation. Any // other read failure leaves the sibling's settings unknown, and unknown settings // must not be silently replaced by the profile this call is about to activate - // so that case fails the mutation before the shared write. const deletedPin = error instanceof ProviderSettingsNotFoundError // An unreadable pin is fatal for a sibling - unknown settings must not be replaced by // the profile the caller is about to activate - but not for this view's own pin: // leaving the overlay untouched keeps it reporting what it reported before, and a // mutation aborted by this read alone would have had to compensate anyway. if (!deletedPin && instance !== this) { unresolvedPins.push({ pinName, error }) } this.log( `[snapshotSiblingOverlaysBeforeSharedSettingsWrite] Unable to resolve profile '${pinName}': ${ error instanceof Error ? error.message : String(error) }${deletedPin ? " (deleted; the deletion path re-points this view)" : ""}`, ) } }), ) if (unresolvedPins.length > 0) { const firstError = unresolvedPins[0].error throw new Error( `Refusing to overwrite the shared provider settings while pinned profile(s) could not be resolved: ${[ ...new Set(unresolvedPins.map(({ pinName }) => pinName)), ].join(", ")} (${firstError instanceof Error ? firstError.message : String(firstError)})`, ) } } async activateProviderProfile( args: { name: string } | { id: string }, options?: { persistModeConfig?: boolean persistTaskHistory?: boolean skipCurrentTaskRebuild?: boolean preserveForeignTask?: boolean /** Rebuild and sticky-write only when this task is still current. */ expectedCurrentTaskId?: string /** Writer token for the durable view pin this activation writes (profile deletion only). */ pinWriteOwner?: symbol }, ) { return this.enqueueProviderProfileMutation((signal) => this.activateProviderProfileUnlocked(args, options, signal), ) } private async activateProviderProfileUnlocked( args: { name: string } | { id: string }, options?: { persistModeConfig?: boolean persistTaskHistory?: boolean skipCurrentTaskRebuild?: boolean preserveForeignTask?: boolean // Fires once the activation has written the activated profile to shared // state, so callers can mark the switch committed at the true point of no // return (a profile lookup failure must stay reconcilable). onSharedWriteStart?: () => void expectedCurrentTaskId?: string /** Writer token for the durable view pin this activation writes (profile deletion only). */ pinWriteOwner?: symbol }, signal?: AbortSignal, ): Promise { const persistModeConfig = options?.persistModeConfig ?? true const persistTaskHistory = options?.persistTaskHistory ?? true const skipCurrentTaskRebuild = options?.skipCurrentTaskRebuild ?? false // The profile listing that the write group below persists is read together with the sibling // snapshot, before the manager commits the activation, so that a fallible read does not // land in the window after the switch is committed. let listApiConfigMeta: ProviderSettingsEntry[] | undefined if (!skipCurrentTaskRebuild) { // Siblings pinned to other profiles must keep their own settings: the shared // write below replaces the shared store, so pin their profile's settings into // their overlays first. This runs before the manager writes the activated // profile on purpose: a pin whose record cannot be read aborts the write, and // aborting after activateProfile would leave the store on the new profile while // a mode switch that already passed onSharedWriteStart keeps the new mode // instead of restoring the pair, so mode and provider would disagree. // For an activation by id the resolved name comes from the manager's own // listing, which the shared write below reads as well. let activatedProfileName: string if ("name" in args) { activatedProfileName = args.name } else { const listedProfiles = await this.providerSettingsManager.listConfig() activatedProfileName = listedProfiles.find((entry) => entry.id === args.id)?.name ?? args.id listApiConfigMeta = listedProfiles } // The listing the write group below persists is read here rather than after the manager // commit: activateProfile only rewrites the shared selection, so the listing is the same // either way, and a read that rejects after onSharedWriteStart would strand the switch - // handleModeSwitch keeps the new mode once the manager has committed, and nothing around // this read recovered the mode, the profile settings and the task handler together. if (listApiConfigMeta === undefined) { listApiConfigMeta = await this.providerSettingsManager.listConfig() } await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(activatedProfileName) } const { name, id, ...providerSettings } = await this.providerSettingsManager.activateProfile(args) // The manager has now written the activated profile: from here on a failure // must keep the switch rather than roll the mode back onto the old profile. options?.onSharedWriteStart?.() if (signal?.aborted) return // A launch-time pin repair (preserveForeignTask) must not switch a task that follows a // different sticky profile: the repair deliberately leaves the task's sticky profile // untouched, so its handler and credentials must stay on that profile too. Computed // before the writes below - alongside expectedCurrentTaskId, which is captured at the // same point - so the failure path below makes the same decision as the success path. const foreignTaskFollowed = options?.preserveForeignTask === true && this.getCurrentTask()?.taskApiConfigName !== undefined && this.getCurrentTask()?.taskApiConfigName !== name // Once the manager has committed the profile, a failure keeps the switch, so before the error // leaves this function the task is moved onto the profile that now stands; otherwise a pending // message goes out on the handler of the profile the task started on. Both post-commit failure // sites below use this, so the compensation is stated once. A launch-time pin repair is the // exception - rebuilding there would move a foreign task's provider and credentials onto the // activated profile while its sticky pin stays elsewhere - and so is a caller that asked for no // task rebuild at all, which is the same decision the success path makes from the same flag. const restoreHandlerToActivatedProfile = () => { if (skipCurrentTaskRebuild || foreignTaskFollowed) { return } this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true, expectedCurrentTaskId: options?.expectedCurrentTaskId, }) } if (!skipCurrentTaskRebuild) { // See `upsertProviderProfile` for a description of what this is doing. // Safety net only: the listing is read in the pre-commit block above under the same gate, // so this branch is unreachable while both blocks share skipCurrentTaskRebuild. if (listApiConfigMeta === undefined) { listApiConfigMeta = await this.providerSettingsManager.listConfig() } try { // Settle every branch instead of awaiting Promise.all: Promise.all rejects on the first // failure while another branch is still in flight, so the caller would release the // mutation queue and run the compensation below while a write that started here could // still land afterwards on top of a later activation's state. const activationWrites = await Promise.allSettled([ this.contextProxy.setValue("listApiConfigMeta", listApiConfigMeta), // Route through setValue so the in-memory viewLocalState buffer tracks the // activated profile: a plain ContextProxy write would leave a stale loaded // currentApiConfigName shadowing the new value in getValues(). // The pin write goes out through setValue with the caller token: a profile deletion owns // the activation write of its own view, and no other caller supplies one. this.setValue("currentApiConfigName", name, { pinWriteOwner: options?.pinWriteOwner }), this.contextProxy.setProviderSettings(providerSettings), // setProviderSettings writes the shared store directly, bypassing the // view-local mutation path: clear this view's buffered apiConfiguration // overlay (if any) so a stale loaded profile cannot keep shadowing the // new settings in getState(). this._saveViewLocalStateFromMutation({ apiConfiguration: undefined }), ]) const failedWrite = activationWrites.find((result) => result.status === "rejected") if (failedWrite && failedWrite.status === "rejected") { // Every branch has settled: nothing started here is still writing when the // compensation below runs or when the caller's own activation follows. throw failedWrite.reason } } catch (error) { // The manager has already written the activated profile, so the caller keeps the // switch and delivers its pending message now: the shared compensation above moves // the task onto this profile's handler before the failure leaves. restoreHandlerToActivatedProfile() throw error } // Other live views may have buffered this profile's settings earlier; // refresh them so their getState() cannot report the activated profile's // name with stale settings. await this.refreshViewLocalStateForUpdatedProfile(name, providerSettings) } // The state read feeds the per-mode default and is that read's only consumer, so it runs // only when a mode default is actually going to be written. It is post-commit work like // the writes above: a failure here keeps the switch, so it goes through the same // compensation before rethrowing - otherwise the profile stays switched while the task // still runs the handler of the profile it started on - and the mode it reports is the one // that stands after those writes settled, which is what the per-mode default must record. if (id && persistModeConfig) { try { const { mode } = await this.getState() await this.setModeConfig(mode, id) } catch (error) { restoreHandlerToActivatedProfile() throw error } } // Change the provider for the current task. The pin-repair guard // (foreignTaskFollowed) is computed above, before the shared writes, so the failure path // above and this call make the same decision from the same captured state. const expectedCurrentTaskId = options?.expectedCurrentTaskId this.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true, skipCurrentTaskRebuild: skipCurrentTaskRebuild || foreignTaskFollowed, expectedCurrentTaskId, }) // Update the current task's sticky provider profile, unless this activation is // being used purely as a non-persisting restoration (e.g., reopening a task from history). if (persistTaskHistory) { // The same foreign-task guard the handler update above uses. A launch-time pin repair // deliberately leaves the task on the sticky profile it already follows, so writing this // activation's name here would rename the very pin the repair preserves and leave the task // running the other profile's handler under this profile's name. await this.persistStickyProviderProfileToCurrentTask(name, { skipCurrentTaskRebuild: skipCurrentTaskRebuild || foreignTaskFollowed, expectedCurrentTaskId, }) } if (!skipCurrentTaskRebuild) { await this.postStateToWebview() } if (providerSettings.apiProvider && !skipCurrentTaskRebuild) { this.emit(RooCodeEventName.ProviderProfileChanged, { name, provider: providerSettings.apiProvider }) } } /** * Bring the other live views up to date after the profile named here was rewritten in the * shared store and the store-backed manager. Two things follow a profile name, and each is * refreshed on its own axis: a view's buffered apiConfiguration follows the pin it loaded, * while that view's running task follows the profile the task was launched onto, so a view * pinned elsewhere that is running a conversation on this profile gets its handler rebuilt * and nothing else. The originating view refreshes itself at the mutation site. */ async refreshViewLocalStateForUpdatedProfile(name: string, providerSettings: ProviderSettings): Promise { // Two things follow a profile name: a view's own buffer follows the pin it loaded, and the // view's running task follows the profile that task was launched onto. A view pinned to B // can be running a conversation that follows A, so saving A's settings has to reach that // conversation even though the view itself must keep showing B. An instance is in scope when // either one follows the saved profile; each update below is then picked against the truth it // belongs to, so a view that only follows through its task never has its own buffer rewritten. const affected = ClineProvider.getAllInstances().filter( (instance) => instance !== this && (instance.pinnedProfileName === name || instance.getCurrentTask()?.taskApiConfigName === name), ) if (affected.length === 0) { return } await Promise.all( affected.map(async (instance) => { // Read the task once: the selection above and the two updates below must be decided against // the same task, not against two reads that a task switch could separate mid-refresh. const task = instance.getCurrentTask() const viewFollowsProfile = instance.pinnedProfileName === name const taskFollowsProfile = task?.taskApiConfigName === name if (viewFollowsProfile) { // Direct private access: compile-time safe across sibling instances. await instance._saveViewLocalStateFromMutation({ apiConfiguration: providerSettings }) } // The active task holds its own API handler built from the profile's settings: rebuild it // with the saved settings or the running conversation keeps sending the old token even // though some view's buffer has caught up. Only rebuild when the task actually runs // under the saved profile: a task that follows a different sticky profile must keep // its own settings. Direct private access across sibling instances of the same class // is compile-time safe. if (taskFollowsProfile) { instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true }) } // A sibling's UI refresh must not reject an already-applied profile mutation or // trigger its rollback: log the failure and let the remaining siblings refresh. // The UI refresh follows the view, not the task: a view that only follows through its task keeps // its pin and its buffer, so this save does not change the state it posts, and pushing it again // would re-send state the webview already shows. if (viewFollowsProfile) { try { await instance.postStateToWebview() } catch (error) { this.log( `[refreshViewLocalStateForUpdatedProfile] failed to post state to sibling view ${instance.viewId}: ${ error instanceof Error ? error.message : String(error) }`, ) } } }), ) } /** * Re-pin the other live views whose buffer still names a deleted profile: * without this their in-memory buffer and durable viewStates entry keep * serving the deleted profile's name and configuration on top of the * surviving shared state. Each affected view's durable entry is re-pinned * through the serialized write queue, so the rename survives reloads. */ private async rePinViewLocalStateForDeletedProfile( deletedProfileName: string, replacementName: string, replacementSettings: ProviderSettings | undefined, liveChanges: SiblingProfileRePinLiveChange[], pinWriteOwner: symbol, ): Promise { const affected = ClineProvider.getAllInstances().filter( (instance) => instance !== this && instance.pinnedProfileName === deletedProfileName, ) if (affected.length === 0) { return } if (!replacementSettings) { // Renaming the pin without the replacement's settings would leave every affected view // and running task holding the deleted profile's apiConfiguration under the // replacement's name: the UI would show one profile while requests went out with // another profile's provider, model and credentials - the deleted profile's secret // keeps being used after the profile is gone. There is no safe partial repair here // (the manager delete already committed), so fail closed and let deleteProviderProfile // compensate the record and the shared surfaces it rewrote. throw new Error( `Unable to resolve API profile '${replacementName}' to re-point ${affected.length} live view(s) after deleting '${deletedProfileName}'`, ) } // Every sibling's outcome is collected, and every sibling queue settles, before the first // failure is reported: Promise.all would start the deletion's compensation on the first // timeout while another view's callback was still writing. const outcomes = await Promise.allSettled( affected.map(async (instance) => { const values: Partial & Partial = { currentApiConfigName: replacementName, } if (replacementSettings) { values.apiConfiguration = replacementSettings } // Commit through the sibling's own mutation queue, with the pin re-checked at commit // time: the sibling may have queued a selection of another profile between the // filter above and this write, and completing that selection must not end up // underneath the replacement - the user chose it after this deletion read the // live pins. Direct private access: compile-time safe across sibling instances. const repin = instance["enqueueProviderProfileMutationTracked"](async () => { if (instance.pinnedProfileName !== deletedProfileName) { return false } // Recorded here, after the queued name check and immediately before the write, because this is // the state the compensation must return this view to. A mutation the view queued ahead of this // re-pin - a concurrent activation's overlay snapshot commits through this same queue - can fill // an empty overlay without moving the pin, and a record taken before the queue would hand the // rollback the earlier undefined overlay: the view keeps the deleted profile's name while its // settings fall back to the shared store, which now carries the replacement. // No check, no record: a re-pin that wrote nothing has nothing for the replay to undo, so a // selection this view made of its own is not reverted by a record of a change it never made. const liveChange: SiblingProfileRePinLiveChange = { instance, previousPin: instance.pinnedProfileName, previousSettings: instance.viewLocalState.apiConfiguration, appliedPin: replacementName, task: undefined, } liveChanges.push(liveChange) // Direct private access: compile-time safe across sibling instances. // The token rides on this write: this re-pin is the deletion writing the view pin, not the // view choosing it, so the claim on the entry stays with the deletion. await instance._saveViewLocalStateFromMutation(values, { pinWriteOwner }) // The active task of a view pinned to the deleted profile holds its own API // handler and sticky profile name built from the deleted profile: rebuild // the handler with the replacement's settings and re-point the sticky name, // or the running conversation keeps sending the deleted profile's // configuration even though the view's buffer was re-pointed (the posted // state prefers the task's own apiConfiguration). Only re-point when the // task actually runs under the deleted profile: a view pinned to it can // hold a task that follows a different sticky profile, and forcing the // replacement would silently switch that conversation and rewrite its // persisted profile name without the user asking. const task = instance.getCurrentTask() if (task?.taskApiConfigName === deletedProfileName) { // The task change is recorded inside the branch that makes it: only a task this re-pin // itself re-pointed is re-pointed back. liveChange.task = { taskId: task.taskId, previousName: task.taskApiConfigName, appliedName: replacementName, previousSettings: task.apiConfiguration, } if (replacementSettings) { instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true }) } await instance.persistStickyProviderProfileToCurrentTask(replacementName) } return true }) let repinned: boolean try { repinned = await repin.result } catch (error) { // A callback that was already writing when this timed out cannot be cancelled, and the // deletion compensates the affected pins right after this failure: wait for that write // to settle so the compensation merges a pin the write already moved instead of // restoring a pin the write then lands on top of. A callback cancelled before it // started settles at once, so this never holds the deletion behind work that will // not run. await repin.settled throw error } // The outcome is the re-pin itself, not the UI refresh that follows it: this callback returns // before touching a webview, so another view's failure cannot make the deletion's compensation // wait for this view's state post (postStateToWebview reads the custom modes, so it can // outlast the write that committed the re-pin). return { instance, repinned } }), ) const failure = outcomes.find((outcome): outcome is PromiseRejectedResult => outcome.status === "rejected") if (failure) { // The state post is bound to every re-pin succeeding: a view whose re-pin committed does not // post on this path, so a slow custom-mode read inside one view's refresh cannot keep the // deleted profile out of the record while the deletion's compensation waits for that // refresh. The live changes this callback made are not left behind either: the records // filled above let the deletion replay them, so the view's buffer and the task it runs // return to the deleted profile together with the durable pin. A view that selected // another profile in the meantime keeps that selection - the replay skips it. throw failure.reason } // Every re-pin settled and none failed: post the committed state to the views that moved it. // A sibling's UI refresh must not reject an already-applied mutation or trigger the // deletion's rollback: log the failure and let the remaining views post. await Promise.all( outcomes.map(async (outcome) => { if (outcome.status !== "fulfilled" || !outcome.value.repinned) { return } try { await outcome.value.instance.postStateToWebview() } catch (error) { this.log( `[rePinViewLocalStateForDeletedProfile] failed to post state to sibling view ${outcome.value.instance.viewId}: ${ error instanceof Error ? error.message : String(error) }`, ) } }), ) } /** * Re-point live views still pinned to a profile that is being renamed onto * the new name. A rename keeps the profile id, so a view pinned to the old * name should follow the record instead of falling back to the shared * selection: without this, the pin dangles at a name that no longer * resolves and the buffered overlay keeps serving the pre-rename copy. * Must run before the old name is deleted. */ public async repointViewLocalStateAfterProfileRename( oldName: string, newName: string, renamedSettings: ProviderSettingsWithId | undefined, ): Promise { // Closed views keep their pin only in the persisted map: re-point those entries // first so a view that launches after an intervening activation still follows the // renamed profile instead of dangling at the deleted name. await this.repointPersistedViewStates(oldName, newName) const affected = ClineProvider.getAllInstances().filter((instance) => instance.pinnedProfileName === oldName) if (affected.length === 0) { return } await Promise.all( affected.map(async (instance) => { // Assigning the settings (even undefined) is what replaces or clears the // overlay: the renamed record's current settings are the only correct // overlay for a pin that now names the new profile. await instance._saveViewLocalStateFromMutation({ currentApiConfigName: newName, apiConfiguration: renamedSettings, }) // A task running under the old name holds its own API handler and sticky // profile name: re-point both, or the conversation keeps sending the // pre-rename configuration under a name that no longer resolves. if (instance.getCurrentTask()?.taskApiConfigName === oldName) { if (renamedSettings) { instance.updateTaskApiHandlerIfNeeded(renamedSettings, { forceRebuild: true }) } await instance.persistStickyProviderProfileToCurrentTask(newName) } try { await instance.postStateToWebview() } catch (error) { this.log( `[repointViewLocalStateAfterProfileRename] failed to post state to sibling view ${instance.viewId}: ${ error instanceof Error ? error.message : String(error) }`, ) } }), ) } async updateCustomInstructions(instructions?: string) { // User may be clearing the field. await this.updateGlobalState("customInstructions", instructions || undefined) await this.postStateToWebview() } // MCP async ensureMcpServersDirectoryExists(): Promise { // Get platform-specific application data directory let mcpServersDir: string if (process.platform === "win32") { // Windows: %APPDATA%\Roo-Code\MCP mcpServersDir = path.join(os.homedir(), "AppData", "Roaming", "Roo-Code", "MCP") } else if (process.platform === "darwin") { // macOS: ~/Documents/Cline/MCP mcpServersDir = path.join(os.homedir(), "Documents", "Cline", "MCP") } else { // Linux: ~/.local/share/Cline/MCP mcpServersDir = path.join(os.homedir(), ".local", "share", "Roo-Code", "MCP") } try { await fs.mkdir(mcpServersDir, { recursive: true }) } catch { // Fallback to a relative path if directory creation fails return path.join(os.homedir(), ".roo-code", "mcp") } return mcpServersDir } async ensureSettingsDirectoryExists(): Promise { const { getSettingsDirectoryPath } = await import("../../utils/storage") const globalStoragePath = this.contextProxy.globalStorageUri.fsPath return getSettingsDirectoryPath(globalStoragePath) } // OpenRouter async handleOpenRouterCallback(code: string) { const { apiConfiguration, currentApiConfigName = "default" } = await this.getState() let apiKey: string try { const baseUrl = apiConfiguration.openRouterBaseUrl || "https://openrouter.ai/api/v1" // Extract the base domain for the auth endpoint. const baseUrlDomain = baseUrl.match(/^(https?:\/\/[^/]+)/)?.[1] || "https://openrouter.ai" const response = await axios.post(`${baseUrlDomain}/api/v1/auth/keys`, { code }) if (response.data && response.data.key) { apiKey = response.data.key } else { throw new Error("Invalid response from OpenRouter API") } } catch (error) { this.log( `Error exchanging code for API key: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`, ) throw error } const newConfiguration: ProviderSettings = { ...apiConfiguration, apiProvider: providerIdentifiers.openrouter, openRouterApiKey: apiKey, openRouterModelId: apiConfiguration?.openRouterModelId || openRouterDefaultModelId, } await this.upsertProviderProfile(currentApiConfigName, newConfiguration) } // Zoo Code Auth async handleZooCodeCallback(token: string) { // Auth mutation (token storage, subscription check, success toast) was already // performed by handleAuthCallback() in handleUri.ts before this method was called. // Save the zoo-gateway provider profile with the session token so that // ZooGatewayHandler can authenticate without any manual user input. // // activate: true ONLY if Zoo Gateway is already the active profile — this pushes // the new token to the in-memory handler so the current task picks it up immediately. // Otherwise activate: false — do NOT switch providers mid-conversation. The user // must explicitly select Zoo Gateway in settings if they want to use it. try { const { apiConfiguration } = await this.getState() const currentSettings = this.contextProxy.getProviderSettings() const currentApiConfigName = this.contextProxy.getValues().currentApiConfigName // Derive the gateway base URL from ZOO_CODE_BASE_URL so that non-prod environments // (staging, local dev) route completions to the correct backend instead of always // hard-coding production. An already-set value in the profile is NOT preserved here — // it must always align with the auth server the user just authenticated against. const { getZooCodeBaseUrl } = await import("../../services/zoo-code-auth") const derivedGatewayBaseUrl = `${getZooCodeBaseUrl()}/api/gateway/v1` // Check if Zoo Gateway is the currently active profile by apiProvider identity, // not by profile name (profile names are user-renameable). const isZooGatewayActive = currentSettings.apiProvider === providerIdentifiers.zooGateway // Always scan ALL profiles and update every zoo-gateway profile with the new token. // This ensures renamed profiles, duplicate profiles, and inactive profiles all stay // in sync. The model lookup in requestRouterModels uses .find() which returns the // first zoo-gateway profile it finds — if that profile has a stale token, requests fail. const allProfiles = await this.providerSettingsManager.listConfig() const zooProfiles = allProfiles.filter((p) => p.apiProvider === providerIdentifiers.zooGateway) if (zooProfiles.length === 0) { // No existing zoo-gateway profile — create the canonical default. const newConfiguration: ProviderSettings = { apiProvider: providerIdentifiers.zooGateway, zooSessionToken: token, zooGatewayModelId: apiConfiguration.zooGatewayModelId, zooGatewayBaseUrl: derivedGatewayBaseUrl, } // Activate only if zoo-gateway was the active provider (shouldn't happen if // no profiles exist, but defensive). await this.upsertProviderProfile("Zoo Gateway", newConfiguration, isZooGatewayActive) } else { // Update every existing zoo-gateway profile with the new token and the // derived base URL so that environment-specific routing stays consistent. for (const entry of zooProfiles) { const isActiveProfile = isZooGatewayActive && entry.name === currentApiConfigName const existing = await this.providerSettingsManager.getProfile({ name: entry.name }) const updated: ProviderSettings = { ...existing, zooSessionToken: token, zooGatewayBaseUrl: derivedGatewayBaseUrl, } if (isActiveProfile) { // Use upsertProviderProfile with activate: true so the in-memory handler // picks up the new token immediately for the current task. await this.upsertProviderProfile(entry.name, updated, true) } else { // Non-active profiles need the token saved to disk and the views pinned // to them refreshed: a direct saveConfig leaves a pinned view serving the // old token until it reloads. await this.upsertProviderProfile(entry.name, updated, false) } } } } catch (error) { this.log( `[handleZooCodeCallback] Failed to save zoo-gateway profile: ${ error instanceof Error ? error.message : String(error) }`, ) } await this.postStateToWebview() const { postZooGatewayCredentialsReady } = await import("../../services/zoo-gateway-credentials-sync") postZooGatewayCredentialsReady((message) => this.postMessageToWebview(message)) } // Requesty async handleRequestyCallback(code: string, baseUrl: string | null) { const { apiConfiguration } = await this.getState() const newConfiguration: ProviderSettings = { ...apiConfiguration, apiProvider: providerIdentifiers.requesty, requestyApiKey: code, requestyModelId: apiConfiguration?.requestyModelId || requestyDefaultModelId, } // set baseUrl as undefined if we don't provide one // or if it is the default requesty url if (!baseUrl || baseUrl === REQUESTY_BASE_URL) { newConfiguration.requestyBaseUrl = undefined } else { newConfiguration.requestyBaseUrl = baseUrl } const profileName = `Requesty (${new Date().toLocaleString()})` await this.upsertProviderProfile(profileName, newConfiguration) } // Task history private getTaskHistoryItem(id: string): HistoryItem | undefined { const historyItem = this.taskHistoryStore.get(id) // Once initialization and migration succeed, the file-backed store is authoritative. // Legacy global state is only a fallback while startup is incomplete or has failed. if (historyItem || this.taskHistoryStoreInitialized) { return historyItem } return (this.getGlobalState("taskHistory") ?? []).find((item) => item.id === id) } async getTaskWithId(id: string): Promise<{ historyItem: HistoryItem taskDirPath: string apiConversationHistoryFilePath: string uiMessagesFilePath: string apiConversationHistory: Anthropic.MessageParam[] }> { const historyItem = this.getTaskHistoryItem(id) if (!historyItem) { throw new Error("Task not found") } const { getTaskDirectoryPath } = await import("../../utils/storage") const globalStoragePath = this.contextProxy.globalStorageUri.fsPath const taskDirPath = await getTaskDirectoryPath(globalStoragePath, id) const apiConversationHistoryFilePath = path.join(taskDirPath, GlobalFileNames.apiConversationHistory) const uiMessagesFilePath = path.join(taskDirPath, GlobalFileNames.uiMessages) let apiConversationHistory: Anthropic.MessageParam[] = [] try { apiConversationHistory = JSON.parse(await readFileWithMissingRetry(apiConversationHistoryFilePath)) } catch (error) { console.warn( `[getTaskWithId] Could not read API conversation history for task ${id}, returning empty history: ${error instanceof Error ? error.message : String(error)}`, ) } return { historyItem, taskDirPath, apiConversationHistoryFilePath, uiMessagesFilePath, apiConversationHistory, } } async getTaskWithAggregatedCosts(taskId: string): Promise<{ historyItem: HistoryItem aggregatedCosts: AggregatedCosts }> { const historyItem = this.getTaskHistoryItem(taskId) if (!historyItem) throw new Error("Task not found") const aggregatedCosts = await aggregateTaskCostsRecursive(taskId, async (id: string) => { const item = this.getTaskHistoryItem(id) if (!item) throw new Error("Task not found") return item }) return { historyItem, aggregatedCosts } } async showTaskWithId(id: string) { const startedAt = Date.now() this.diagnosticsRecorder.record({ boundary: "task-navigation", phase: "start", type: "show-task", taskId: id, }) try { if (id !== this.getCurrentTask()?.taskId) { // Non-current task. const { historyItem } = await this.getTaskWithId(id) await this.createTaskWithHistoryItem(historyItem) // Clears existing task. } await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) this.diagnosticsRecorder.record({ boundary: "task-navigation", phase: "success", type: "show-task", taskId: id, elapsedMs: Date.now() - startedAt, messageCount: this.getCurrentTask()?.clineMessages.length ?? 0, }) } catch (error) { this.diagnosticsRecorder.record({ boundary: "task-navigation", phase: "failure", type: "show-task", taskId: id, elapsedMs: Date.now() - startedAt, }) throw error } } async exportTaskWithId(id: string) { const { historyItem, apiConversationHistory } = await this.getTaskWithId(id) const fileName = getTaskFileName(historyItem.ts) const defaultUri = await resolveDefaultSaveUri(this.contextProxy, "lastTaskExportPath", fileName, { useWorkspace: false, fallbackDir: path.join(os.homedir(), "Downloads"), }) const saveUri = await downloadTask(apiConversationHistory, defaultUri) if (saveUri) { await saveLastExportPath(this.contextProxy, "lastTaskExportPath", saveUri) } } /* * Sets a user-assigned display title for a history item. A blank title * clears it so the history falls back to the original prompt. */ async renameTaskWithId(id: string, title: string | undefined) { if (!this.taskHistoryStore.get(id)) { this.log(`[renameTaskWithId] task ${id} not found in history`) return } // Read and write under the store lock so a queued task save or delegation // transition cannot be overwritten by a stale snapshot of the item. const trimmed = title?.trim() await this.taskHistoryStore.atomicReadAndUpdate(id, (historyItem) => ({ ...historyItem, title: trimmed ? trimmed : undefined, })) this.recentTasksCache = undefined if (this.isViewLaunched) { const updatedItem = this.taskHistoryStore.get(id) if (updatedItem) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem }) } } } /* * Records a generated title unless the task already has one. The store decides under its lock * against the persisted record, so a deleted or already-titled task is left untouched. */ async setAutoTitle(id: string, autoTitle: string) { const { item } = await this.taskHistoryStore.setAutoTitleIfAbsent(id, autoTitle) this.recentTasksCache = undefined if (item && this.isViewLaunched) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: item }) } } /** * Condenses a task's message history and always posts a terminal response for `taskId`. * * 1. Unknown task: show `condense_task_unavailable`; no Task exists to say on. * 2. Expected rejection or provider failure: the task already said `condense_context_error`. * 3. Cancellation: a throw on an aborted or abandoned task is not reported as a failure. * 4. Unexpected throw: show `condense_failed_with_reason`. * * Never rejects, so the webview handler needs no try. */ async condenseTaskContext(taskId: string): Promise { const task = this.taskRegistry.getById(taskId) try { if (!task) { void vscode.window.showErrorMessage(t("common:errors.condense_task_unavailable")) return } await task.condenseContext() } catch (error) { this.log(`Failed to condense task ${taskId}: ${String(error)}`) if (!task?.abort && !task?.abandoned) { const reason = error instanceof Error ? error.message : String(error) void vscode.window.showErrorMessage(t("common:errors.condense_failed_with_reason", { reason })) } } finally { try { await this.postMessageToWebview({ type: "condenseTaskContextResponse", text: taskId }) } catch (postError) { this.log(`Failed to post condense response for task ${taskId}: ${String(postError)}`) } } } // this function deletes a task from task history, and deletes its checkpoints and delete the task folder // If the task has subtasks (childIds), they will also be deleted recursively async deleteTaskWithId(id: string, cascadeSubtasks: boolean = true) { try { await this.getTaskWithId(id) // Collect all task IDs to delete (parent + all subtasks) const allIdsToDelete: string[] = [id] if (cascadeSubtasks) { // Recursively collect all child IDs const collectChildIds = async (taskId: string): Promise => { try { const { historyItem: item } = await this.getTaskWithId(taskId) if (item.childIds && item.childIds.length > 0) { for (const childId of item.childIds) { allIdsToDelete.push(childId) await collectChildIds(childId) } } } catch { // Child task may already be deleted or not found, continue console.log(`[deleteTaskWithId] child task ${taskId} not found, skipping`) } } await collectChildIds(id) } // Remove from stack if any of the tasks to delete are in the current task stack for (const taskId of allIdsToDelete) { if (taskId === this.getCurrentTask()?.taskId) { // Close the current task instance; delegation flows will be handled via metadata if applicable. await this.removeClineFromStack() break } } for (const taskId of allIdsToDelete) { this.taskTitleService.cancel(taskId, "deleted") } // Delete all tasks from state in one batch await this.taskHistoryStore.deleteMany(allIdsToDelete) this.recentTasksCache = undefined // Delete associated shadow repositories or branches and task directories const globalStorageDir = this.contextProxy.globalStorageUri.fsPath const workspaceDir = this.cwd const { getTaskDirectoryPath } = await import("../../utils/storage") const globalStoragePath = this.contextProxy.globalStorageUri.fsPath for (const taskId of allIdsToDelete) { try { await ShadowCheckpointService.deleteTask({ taskId, globalStorageDir, workspaceDir }) } catch (error) { console.error( `[deleteTaskWithId${taskId}] failed to delete associated shadow repository or branch: ${error instanceof Error ? error.message : String(error)}`, ) } // Delete the task directory try { const dirPath = await getTaskDirectoryPath(globalStoragePath, taskId) await fs.rm(dirPath, { recursive: true, force: true }) console.log(`[deleteTaskWithId${taskId}] removed task directory`) } catch (error) { console.error( `[deleteTaskWithId${taskId}] failed to remove task directory: ${error instanceof Error ? error.message : String(error)}`, ) } } await this.postStateToWebview() } catch (error) { // If task is not found, just remove it from state if (error instanceof Error && error.message === "Task not found") { await this.deleteTaskFromState(id) return } throw error } } async deleteTaskFromState(id: string) { this.taskTitleService.cancel(id, "deleted") await this.taskHistoryStore.delete(id) this.recentTasksCache = undefined await this.postStateToWebview() } async refreshWorkspace() { this.currentWorkspacePath = getWorkspacePath() await this.postStateToWebview() } async postStateToWebview() { const clineMessagesSeq = ++this.clineMessagesSeq const state = await this.getStateToPostToWebview() state.clineMessagesSeq = clineMessagesSeq await this.postMessageToWebview({ type: "state", state }) } /** * Like postStateToWebview but intentionally omits taskHistory. * * Rationale: * - taskHistory can be large and was being resent on every chat message update. * - The webview maintains taskHistory in-memory and receives updates via * `taskHistoryUpdated` / `taskHistoryItemUpdated`. */ async postStateToWebviewWithoutTaskHistory(): Promise { const clineMessagesSeq = ++this.clineMessagesSeq const state = await this.getStateToPostToWebview({ includeTaskHistory: false }) state.clineMessagesSeq = clineMessagesSeq const { taskHistory: _omit, ...rest } = state await this.postMessageToWebview({ type: "state", state: rest }) } /** * Schedules a debounced state-post attempt. A call made while the debounce timer is active returns * the result of the most recent invocation, so awaiting this method does not wait for the trailing * invocation scheduled by that call. Use `flushPostStateToWebviewThrottled()` to force and await any * pending trailing invocation before continuing. */ async postStateToWebviewThrottled(): Promise { if (this._disposed) { return } await this._postStateToWebviewThrottled() } async flushPostStateToWebviewThrottled(): Promise { if (this._disposed) { return } await this._postStateToWebviewThrottled.flush() } /** * Like postStateToWebview but intentionally omits both clineMessages and taskHistory. * * Rationale: * - Cloud event handlers (auth, settings, user-info) and mode changes trigger state pushes * that have nothing to do with chat messages. Including clineMessages in these pushes * creates race conditions where a stale snapshot of clineMessages (captured during async * getStateToPostToWebview) overwrites newer messages the task has streamed in the meantime. * - This method ensures cloud/mode events only push the state fields they actually affect * (cloud auth, org settings, profiles, etc.) without interfering with task message streaming. */ async postStateToWebviewWithoutClineMessages(): Promise { const state = await this.getStateToPostToWebview({ includeTaskHistory: false }) const { clineMessages: _omitMessages, taskHistory: _omitHistory, ...rest } = state await this.postMessageToWebview({ type: "state", state: rest }) } /** * Fetches marketplace data on demand to avoid blocking main state updates */ async fetchMarketplaceData() { try { const [marketplaceResult, marketplaceInstalledMetadata] = await Promise.all([ this.marketplaceManager.getMarketplaceItems().catch((error) => { console.error("Failed to fetch marketplace items:", error) return { organizationMcps: [], marketplaceItems: [], errors: [error.message] } }), this.marketplaceManager.getInstallationMetadata().catch((error) => { console.error("Failed to fetch installation metadata:", error) return { project: {}, global: {} } as MarketplaceInstalledMetadata }), ]) // Send marketplace data separately await this.postMessageToWebview({ type: "marketplaceData", organizationMcps: marketplaceResult.organizationMcps || [], marketplaceItems: marketplaceResult.marketplaceItems || [], marketplaceInstalledMetadata: marketplaceInstalledMetadata || { project: {}, global: {} }, errors: marketplaceResult.errors, }) } catch (error) { console.error("Failed to fetch marketplace data:", error) // Send empty data on error to prevent UI from hanging await this.postMessageToWebview({ type: "marketplaceData", organizationMcps: [], marketplaceItems: [], marketplaceInstalledMetadata: { project: {}, global: {} }, errors: [error instanceof Error ? error.message : String(error)], }) // Show user-friendly error notification for network issues if (error instanceof Error && error.message.includes("timeout")) { vscode.window.showWarningMessage( "Marketplace data could not be loaded due to network restrictions. Core functionality remains available.", ) } } } /** * Merges allowed commands from global state and workspace configuration * with proper validation and deduplication */ private mergeAllowedCommands(globalStateCommands?: string[]): string[] { return this.mergeCommandLists("allowedCommands", "allowed", globalStateCommands) } /** * Merges denied commands from global state and workspace configuration * with proper validation and deduplication */ private mergeDeniedCommands(globalStateCommands?: string[]): string[] { return this.mergeCommandLists("deniedCommands", "denied", globalStateCommands) } /** * Common utility for merging command lists from global state and workspace configuration. * Implements the Command Denylist feature's merging strategy with proper validation. * * @param configKey - VSCode workspace configuration key * @param commandType - Type of commands for error logging * @param globalStateCommands - Commands from global state * @returns Merged and deduplicated command list */ private mergeCommandLists( configKey: "allowedCommands" | "deniedCommands", commandType: "allowed" | "denied", globalStateCommands?: string[], ): string[] { try { // Validate and sanitize global state commands const validGlobalCommands = Array.isArray(globalStateCommands) ? globalStateCommands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) : [] // Get workspace configuration commands const workspaceCommands = vscode.workspace.getConfiguration(Package.name).get(configKey) || [] // Validate and sanitize workspace commands const validWorkspaceCommands = Array.isArray(workspaceCommands) ? workspaceCommands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) : [] // Combine and deduplicate commands // Global state takes precedence over workspace configuration const mergedCommands = [...new Set([...validGlobalCommands, ...validWorkspaceCommands])] return mergedCommands } catch (error) { console.error(`Error merging ${commandType} commands:`, error) // Return empty array as fallback to prevent crashes return [] } } async getStateToPostToWebview({ includeTaskHistory = true }: GetStateOptions = {}): Promise { // Ensure the store is initialized before reading task history await this.taskHistoryStore.initialized const { apiConfiguration, lastShownAnnouncementId, customInstructions, alwaysAllowReadOnly, alwaysAllowReadOnlyOutsideWorkspace, allowedReadFiles, alwaysAllowWrite, alwaysAllowWriteOutsideWorkspace, alwaysAllowWriteProtected, allowedWriteFiles, alwaysAllowExecute, destructiveCommandGuardEnabled, alwaysDenyUnapprovedCommands, allowedCommands, deniedCommands, alwaysAllowMcp, alwaysAllowModeSwitch, alwaysAllowSubtasks, allowedMaxRequests, allowedMaxCost, autoCondenseContext, autoCondenseContextPercent, soundEnabled, ttsEnabled, ttsSpeed, enableCheckpoints, checkpointTimeout, soundVolume, writeDelayMs, diffFuzzyThreshold, terminalShellIntegrationTimeout, terminalShellIntegrationDisabled, collapseCommandOutputByDefault, terminalCommandDelay, terminalPowershellCounter, terminalZshClearEolMark, terminalZshOhMy, terminalZshP10k, terminalZdotdir, terminalProfile, mcpEnabled, currentApiConfigName, listApiConfigMeta, pinnedApiConfigs, mode, customModePrompts, customSupportPrompts, enhancementApiConfigId, autoApprovalEnabled, customModes, experiments, maxOpenTabsContext, maxWorkspaceFiles, disabledTools, telemetrySetting, showRooIgnoredFiles, enableSubfolderRules, language, maxImageFileSize, maxTotalImageSize, historyPreviewCollapsed, reasoningBlockCollapsed, chatFontSize, timeFormat, dateFormat, showRelativeTimes, enterBehavior, cloudUserInfo, cloudIsAuthenticated, sharingEnabled, publicSharingEnabled, organizationAllowList, organizationSettingsVersion, customCondensingPrompt, codebaseIndexConfig, codebaseIndexModels, profileThresholds, alwaysAllowFollowupQuestions, followupAutoApproveTimeoutMs, includeDiagnosticMessages, maxDiagnosticMessages, includeTaskHistoryInEnhance, taskTitleGenerationEnabled, taskTitleApiConfigId, includeCurrentTime, includeCurrentCost, maxGitStatusFiles, taskSyncEnabled, imageGenerationProvider, openRouterImageApiKey, openRouterImageGenerationSelectedModel, lockApiConfigAcrossModes, autoCloseZooOpenedFiles, autoCloseZooOpenedFilesAfterUserEdited, autoCloseZooOpenedNewFiles, } = await this.getState({ includeTaskHistory: false }) let cloudOrganizations: CloudOrganizationMembership[] = [] try { if (!CloudService.instance.isCloudAgent) { const now = Date.now() if ( this.cloudOrganizationsCache !== null && this.cloudOrganizationsCacheTimestamp !== null && now - this.cloudOrganizationsCacheTimestamp < ClineProvider.CLOUD_ORGANIZATIONS_CACHE_DURATION_MS ) { cloudOrganizations = this.cloudOrganizationsCache! } else { cloudOrganizations = await CloudService.instance.getOrganizationMemberships() this.cloudOrganizationsCache = cloudOrganizations this.cloudOrganizationsCacheTimestamp = now } } } catch { // Ignore this error. } const telemetryKey = process.env.POSTHOG_API_KEY // The webview uses this value as its PostHog distinct ID, so it must be the // salted hash: the raw machine ID never crosses the webview boundary (issue #830). const machineId = hashDistinctId(vscode.env.machineId) const vscodeTelemetryEnabled = vscode.env.isTelemetryEnabled const mergedAllowedCommands = this.mergeAllowedCommands(allowedCommands) const mergedDeniedCommands = this.mergeDeniedCommands(deniedCommands) const cwd = this.cwd const currentTask = this.getCurrentTask() let currentTaskMode: string | undefined try { currentTaskMode = currentTask?.taskMode } catch { // A just-created task may still be initializing its mode; retain the persisted projection for this post. } const currentTaskApiConfigName = currentTask?.taskApiConfigName const currentTaskApiConfiguration = currentTask?.apiConfiguration let zooCodeState: { zooCodeIsAuthenticated: boolean zooCodeUserName: string | undefined zooCodeUserEmail: string | undefined zooCodeUserImage: string | undefined zooCodeBaseUrl: string deviceName: string } = { zooCodeIsAuthenticated: false, zooCodeUserName: undefined, zooCodeUserEmail: undefined, zooCodeUserImage: undefined, zooCodeBaseUrl: "https://www.zoocode.dev", deviceName: os.hostname(), } try { const { isZooCodeAuthenticated, getCachedZooCodeUserInfo, getZooCodeBaseUrl } = await import("../../services/zoo-code-auth") const userInfo = getCachedZooCodeUserInfo() zooCodeState = { zooCodeIsAuthenticated: await isZooCodeAuthenticated(), zooCodeUserName: userInfo.name, zooCodeUserEmail: userInfo.email, zooCodeUserImage: userInfo.image, zooCodeBaseUrl: getZooCodeBaseUrl(), deviceName: os.hostname(), } } catch { // Keep the default unauthenticated state if the optional Zoo Code auth service is unavailable. } return { version: this.context.extension?.packageJSON?.version ?? "", apiConfiguration: currentTaskApiConfiguration ?? apiConfiguration, customInstructions, alwaysAllowReadOnly: alwaysAllowReadOnly ?? false, alwaysAllowReadOnlyOutsideWorkspace: alwaysAllowReadOnlyOutsideWorkspace ?? false, allowedReadFiles: allowedReadFiles ?? [], alwaysAllowWrite: alwaysAllowWrite ?? false, alwaysAllowWriteOutsideWorkspace: alwaysAllowWriteOutsideWorkspace ?? false, alwaysAllowWriteProtected: alwaysAllowWriteProtected ?? false, allowedWriteFiles: allowedWriteFiles ?? [], alwaysAllowExecute: alwaysAllowExecute ?? false, destructiveCommandGuardEnabled, alwaysDenyUnapprovedCommands: alwaysDenyUnapprovedCommands ?? false, alwaysAllowMcp: alwaysAllowMcp ?? false, alwaysAllowModeSwitch: alwaysAllowModeSwitch ?? false, alwaysAllowSubtasks: alwaysAllowSubtasks ?? false, allowedMaxRequests, allowedMaxCost, autoCondenseContext: autoCondenseContext ?? true, autoCondenseContextPercent: autoCondenseContextPercent ?? 100, uriScheme: vscode.env.uriScheme, currentTaskId: currentTask?.taskId, currentTaskItem: currentTask?.taskId ? this.taskHistoryStore.get(currentTask.taskId) : undefined, clineMessages: currentTask?.clineMessages || [], currentTaskTodos: currentTask?.todoList || [], messageQueue: currentTask?.messageQueueService?.messages, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll().filter((item: HistoryItem) => item.ts && item.task) : [], soundEnabled: soundEnabled ?? false, ttsEnabled: ttsEnabled ?? false, ttsSpeed: ttsSpeed ?? 1.0, enableCheckpoints: enableCheckpoints ?? true, checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, allowedCommands: mergedAllowedCommands, deniedCommands: mergedDeniedCommands, soundVolume: soundVolume ?? 0.5, writeDelayMs: writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diffFuzzyThreshold: diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, terminalShellIntegrationTimeout: terminalShellIntegrationTimeout ?? Terminal.defaultShellIntegrationTimeout, terminalShellIntegrationDisabled: terminalShellIntegrationDisabled ?? true, collapseCommandOutputByDefault: collapseCommandOutputByDefault ?? DEFAULT_COLLAPSE_COMMAND_OUTPUT_BY_DEFAULT, terminalCommandDelay: terminalCommandDelay ?? 0, terminalPowershellCounter: terminalPowershellCounter ?? false, terminalZshClearEolMark: terminalZshClearEolMark ?? true, terminalZshOhMy: terminalZshOhMy ?? false, terminalZshP10k: terminalZshP10k ?? false, terminalZdotdir: terminalZdotdir ?? false, terminalProfile, mcpEnabled: mcpEnabled ?? true, currentApiConfigName: currentTask ? currentTaskApiConfigName : currentApiConfigName, listApiConfigMeta: listApiConfigMeta ?? [], pinnedApiConfigs: pinnedApiConfigs ?? {}, mode: currentTaskMode ?? mode ?? defaultModeSlug, customModePrompts: customModePrompts ?? {}, customSupportPrompts: customSupportPrompts ?? {}, enhancementApiConfigId, autoApprovalEnabled: autoApprovalEnabled ?? false, customModes, experiments: experiments ?? experimentDefault, mcpServers: this.mcpHub?.getAllServers() ?? [], maxOpenTabsContext: maxOpenTabsContext ?? 20, maxWorkspaceFiles: maxWorkspaceFiles ?? 200, cwd, disabledTools, telemetrySetting, telemetryKey, machineId, vscodeTelemetryEnabled, showRooIgnoredFiles: showRooIgnoredFiles ?? false, enableSubfolderRules: enableSubfolderRules ?? false, language: language ?? formatLanguage(vscode.env.language), renderContext: this.renderContext, maxImageFileSize: maxImageFileSize ?? 5, maxTotalImageSize: maxTotalImageSize ?? 20, settingsImportedAt: this.settingsImportedAt, historyPreviewCollapsed: historyPreviewCollapsed ?? false, reasoningBlockCollapsed: reasoningBlockCollapsed ?? true, chatFontSize, timeFormat: timeFormat ?? "auto", dateFormat: dateFormat ?? "auto", showRelativeTimes: showRelativeTimes ?? true, enterBehavior: enterBehavior ?? "send", cloudUserInfo, cloudIsAuthenticated: cloudIsAuthenticated ?? false, cloudAuthSkipModel: this.context.globalState.get("roo-auth-skip-model") ?? false, cloudOrganizations, sharingEnabled: sharingEnabled ?? false, publicSharingEnabled: publicSharingEnabled ?? false, organizationAllowList, organizationSettingsVersion, customCondensingPrompt, codebaseIndexModels: codebaseIndexModels ?? EMBEDDING_MODEL_PROFILES, codebaseIndexConfig: { codebaseIndexEnabled: codebaseIndexConfig?.codebaseIndexEnabled ?? false, codebaseIndexQdrantUrl: codebaseIndexConfig?.codebaseIndexQdrantUrl ?? "http://localhost:6333", codebaseIndexEmbedderProvider: codebaseIndexConfig?.codebaseIndexEmbedderProvider ?? providerIdentifiers.openai, codebaseIndexEmbedderBaseUrl: codebaseIndexConfig?.codebaseIndexEmbedderBaseUrl ?? "", codebaseIndexEmbedderModelId: codebaseIndexConfig?.codebaseIndexEmbedderModelId ?? "", codebaseIndexEmbedderModelDimension: codebaseIndexConfig?.codebaseIndexEmbedderModelDimension ?? 1536, codebaseIndexOpenAiCompatibleBaseUrl: codebaseIndexConfig?.codebaseIndexOpenAiCompatibleBaseUrl, codebaseIndexSearchMaxResults: codebaseIndexConfig?.codebaseIndexSearchMaxResults, codebaseIndexSearchMinScore: codebaseIndexConfig?.codebaseIndexSearchMinScore, codebaseIndexBedrockRegion: codebaseIndexConfig?.codebaseIndexBedrockRegion, codebaseIndexBedrockProfile: codebaseIndexConfig?.codebaseIndexBedrockProfile, codebaseIndexOpenRouterSpecificProvider: codebaseIndexConfig?.codebaseIndexOpenRouterSpecificProvider, }, // Phase 1 cloud removal: do not let Cloud-auth MDM enforcement force login-only UI flows. mdmCompliant: undefined, profileThresholds: profileThresholds ?? {}, cloudApiUrl: getRooCodeApiUrl(), hasOpenedModeSelector: this.getGlobalState("hasOpenedModeSelector") ?? false, lockApiConfigAcrossModes: lockApiConfigAcrossModes ?? false, alwaysAllowFollowupQuestions: alwaysAllowFollowupQuestions ?? false, followupAutoApproveTimeoutMs: followupAutoApproveTimeoutMs ?? 60000, includeDiagnosticMessages: includeDiagnosticMessages ?? true, maxDiagnosticMessages: maxDiagnosticMessages ?? 50, includeTaskHistoryInEnhance: includeTaskHistoryInEnhance ?? true, taskTitleGenerationEnabled: taskTitleGenerationEnabled ?? DEFAULT_TASK_TITLE_GENERATION_ENABLED, taskTitleApiConfigId, includeCurrentTime: includeCurrentTime ?? true, includeCurrentCost: includeCurrentCost ?? true, maxGitStatusFiles: maxGitStatusFiles ?? 0, taskSyncEnabled, imageGenerationProvider, openRouterImageApiKey, openRouterImageGenerationSelectedModel, autoCloseZooOpenedFiles: autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES, autoCloseZooOpenedFilesAfterUserEdited: autoCloseZooOpenedFilesAfterUserEdited ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED, autoCloseZooOpenedNewFiles: autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES, openAiCodexIsAuthenticated: await (async () => { try { const { openAiCodexOAuthManager } = await import("../../integrations/openai-codex/oauth") return await openAiCodexOAuthManager.isAuthenticated() } catch { return false } })(), kimiCodeIsAuthenticated: await (async () => { try { const { kimiCodeOAuthManager } = await import("../../integrations/kimi-code/oauth") return await kimiCodeOAuthManager.isAuthenticated() } catch { return false } })(), kimiCodeOAuthState: await (async () => { try { const { kimiCodeOAuthManager } = await import("../../integrations/kimi-code/oauth") return kimiCodeOAuthManager.getState() } catch { return undefined } })(), ...zooCodeState, platform: process.platform, arch: process.arch, debug: vscode.workspace.getConfiguration(Package.name).get("debug", false), } } /** * Storage * https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco * https://www.eliostruyf.com/devhack-code-extension-storage-options/ */ async getState({ includeTaskHistory = true }: GetStateOptions = {}): Promise< Omit< ExtensionState, "clineMessages" | "renderContext" | "hasOpenedModeSelector" | "version" | "shouldShowAnnouncement" > > { const stateValues = this.contextProxy.getValues() // Merge viewLocalState on top of global state so a provider can serve // state values scoped to its own view while preserving ContextProxy defaults. const mergedStateValues = { ...stateValues, ...this.viewLocalState } const customModes = await this.customModesManager.getCustomModes() // Determine apiProvider with the same logic as before, while filtering retired providers. // Use mergedStateValues to prioritize viewLocalState for parallel mode support const apiProvider: ProviderName = mergedStateValues.apiProvider && !isRetiredProvider(mergedStateValues.apiProvider) ? mergedStateValues.apiProvider : providerIdentifiers.anthropic // Build the apiConfiguration object combining state values and secrets. const providerSettings = this.contextProxy.getProviderSettings() // Ensure apiProvider is set properly if not already in state if (!providerSettings.apiProvider) { providerSettings.apiProvider = apiProvider } let organizationAllowList = ORGANIZATION_ALLOW_ALL try { organizationAllowList = await CloudService.instance.getAllowList() } catch (error) { console.error( `[getState] failed to get organization allow list: ${error instanceof Error ? error.message : String(error)}`, ) } let cloudUserInfo: CloudUserInfo | null = null try { cloudUserInfo = CloudService.instance.getUserInfo() } catch (error) { console.error( `[getState] failed to get cloud user info: ${error instanceof Error ? error.message : String(error)}`, ) } let cloudIsAuthenticated: boolean = false try { cloudIsAuthenticated = CloudService.instance.isAuthenticated() } catch (error) { console.error( `[getState] failed to get cloud authentication state: ${error instanceof Error ? error.message : String(error)}`, ) } const sharingEnabled: boolean = false const publicSharingEnabled: boolean = false let organizationSettingsVersion: number = -1 try { if (CloudService.hasInstance()) { const settings = CloudService.instance.getOrganizationSettings() organizationSettingsVersion = settings?.version ?? -1 } } catch (error) { console.error( `[getState] failed to get organization settings version: ${error instanceof Error ? error.message : String(error)}`, ) } const taskSyncEnabled: boolean = false // Return the same structure as before. // A view-local profile is a complete snapshot, not a patch over the shared store. // Spreading it on top of providerSettings would let a key the profile never defined // leak in from another profile, which ContextProxy.setProviderSettings deliberately // prevents by clearing omitted keys. Use the view's own settings in place and take // only apiProvider from the shared state when the profile does not carry one. // The overlay is read from the buffer itself: the raw apiConfiguration state key // is a partial patch from shared-store paths, not a view snapshot. const viewApiConfiguration = this.viewLocalState.apiConfiguration const resolvedApiConfiguration = viewApiConfiguration ? { ...viewApiConfiguration, apiProvider: viewApiConfiguration.apiProvider ?? providerSettings.apiProvider, } : providerSettings return { apiConfiguration: resolvedApiConfiguration, lastShownAnnouncementId: mergedStateValues.lastShownAnnouncementId, customInstructions: mergedStateValues.customInstructions, apiModelId: mergedStateValues.apiModelId, alwaysAllowReadOnly: mergedStateValues.alwaysAllowReadOnly ?? false, alwaysAllowReadOnlyOutsideWorkspace: mergedStateValues.alwaysAllowReadOnlyOutsideWorkspace ?? false, allowedReadFiles: mergedStateValues.allowedReadFiles ?? [], alwaysAllowWrite: mergedStateValues.alwaysAllowWrite ?? false, alwaysAllowWriteOutsideWorkspace: mergedStateValues.alwaysAllowWriteOutsideWorkspace ?? false, alwaysAllowWriteProtected: mergedStateValues.alwaysAllowWriteProtected ?? false, allowedWriteFiles: mergedStateValues.allowedWriteFiles ?? [], alwaysAllowExecute: mergedStateValues.alwaysAllowExecute ?? false, destructiveCommandGuardEnabled: mergedStateValues.destructiveCommandGuardEnabled ?? DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED, alwaysDenyUnapprovedCommands: mergedStateValues.alwaysDenyUnapprovedCommands ?? DEFAULT_ALWAYS_DENY_UNAPPROVED_COMMANDS, alwaysAllowMcp: mergedStateValues.alwaysAllowMcp ?? false, alwaysAllowModeSwitch: mergedStateValues.alwaysAllowModeSwitch ?? false, alwaysAllowSubtasks: mergedStateValues.alwaysAllowSubtasks ?? false, alwaysAllowFollowupQuestions: mergedStateValues.alwaysAllowFollowupQuestions ?? false, followupAutoApproveTimeoutMs: mergedStateValues.followupAutoApproveTimeoutMs ?? 60000, diagnosticsEnabled: mergedStateValues.diagnosticsEnabled ?? true, allowedMaxRequests: mergedStateValues.allowedMaxRequests, allowedMaxCost: mergedStateValues.allowedMaxCost, autoCondenseContext: mergedStateValues.autoCondenseContext ?? true, autoCondenseContextPercent: mergedStateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], allowedCommands: mergedStateValues.allowedCommands, deniedCommands: mergedStateValues.deniedCommands, soundEnabled: mergedStateValues.soundEnabled ?? false, ttsEnabled: mergedStateValues.ttsEnabled ?? false, ttsSpeed: mergedStateValues.ttsSpeed ?? 1.0, enableCheckpoints: mergedStateValues.enableCheckpoints ?? true, checkpointTimeout: mergedStateValues.checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, soundVolume: mergedStateValues.soundVolume, writeDelayMs: mergedStateValues.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diffFuzzyThreshold: mergedStateValues.diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, terminalShellIntegrationTimeout: mergedStateValues.terminalShellIntegrationTimeout ?? Terminal.defaultShellIntegrationTimeout, terminalShellIntegrationDisabled: mergedStateValues.terminalShellIntegrationDisabled ?? true, collapseCommandOutputByDefault: mergedStateValues.collapseCommandOutputByDefault ?? DEFAULT_COLLAPSE_COMMAND_OUTPUT_BY_DEFAULT, terminalCommandDelay: mergedStateValues.terminalCommandDelay ?? 0, terminalPowershellCounter: mergedStateValues.terminalPowershellCounter ?? false, terminalZshClearEolMark: mergedStateValues.terminalZshClearEolMark ?? true, terminalZshOhMy: mergedStateValues.terminalZshOhMy ?? false, terminalZshP10k: mergedStateValues.terminalZshP10k ?? false, terminalZdotdir: mergedStateValues.terminalZdotdir ?? false, terminalProfile: mergedStateValues.terminalProfile, mode: (mergedStateValues.mode as Mode) ?? defaultModeSlug, language: mergedStateValues.language ?? formatLanguage(vscode.env.language), mcpEnabled: mergedStateValues.mcpEnabled ?? true, mcpServers: this.mcpHub?.getAllServers() ?? [], currentApiConfigName: mergedStateValues.currentApiConfigName ?? "default", listApiConfigMeta: mergedStateValues.listApiConfigMeta ?? [], pinnedApiConfigs: mergedStateValues.pinnedApiConfigs ?? {}, modeApiConfigs: (mergedStateValues.modeApiConfigs as Record) ?? ({} as Record), customModePrompts: mergedStateValues.customModePrompts ?? {}, customSupportPrompts: mergedStateValues.customSupportPrompts ?? {}, enhancementApiConfigId: mergedStateValues.enhancementApiConfigId, experiments: mergedStateValues.experiments ?? experimentDefault, autoApprovalEnabled: mergedStateValues.autoApprovalEnabled ?? false, customModes, maxOpenTabsContext: mergedStateValues.maxOpenTabsContext ?? 20, maxWorkspaceFiles: mergedStateValues.maxWorkspaceFiles ?? 200, disabledTools: mergedStateValues.disabledTools, telemetrySetting: mergedStateValues.telemetrySetting || "unset", showRooIgnoredFiles: mergedStateValues.showRooIgnoredFiles ?? false, enableSubfolderRules: mergedStateValues.enableSubfolderRules ?? false, maxImageFileSize: mergedStateValues.maxImageFileSize ?? 5, maxTotalImageSize: mergedStateValues.maxTotalImageSize ?? 20, historyPreviewCollapsed: mergedStateValues.historyPreviewCollapsed ?? false, reasoningBlockCollapsed: mergedStateValues.reasoningBlockCollapsed ?? true, chatFontSize: mergedStateValues.chatFontSize, timeFormat: mergedStateValues.timeFormat ?? "auto", dateFormat: mergedStateValues.dateFormat ?? "auto", showRelativeTimes: mergedStateValues.showRelativeTimes ?? true, enterBehavior: mergedStateValues.enterBehavior ?? "send", cloudUserInfo, cloudIsAuthenticated, sharingEnabled, publicSharingEnabled, organizationAllowList, organizationSettingsVersion, customCondensingPrompt: mergedStateValues.customCondensingPrompt, codebaseIndexModels: mergedStateValues.codebaseIndexModels ?? EMBEDDING_MODEL_PROFILES, codebaseIndexConfig: { codebaseIndexEnabled: mergedStateValues.codebaseIndexConfig?.codebaseIndexEnabled ?? false, codebaseIndexQdrantUrl: mergedStateValues.codebaseIndexConfig?.codebaseIndexQdrantUrl ?? "http://localhost:6333", codebaseIndexEmbedderProvider: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderProvider ?? providerIdentifiers.openai, codebaseIndexEmbedderBaseUrl: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderBaseUrl ?? "", codebaseIndexEmbedderModelId: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelId ?? "", codebaseIndexEmbedderModelDimension: mergedStateValues.codebaseIndexConfig?.codebaseIndexEmbedderModelDimension, codebaseIndexOpenAiCompatibleBaseUrl: mergedStateValues.codebaseIndexConfig?.codebaseIndexOpenAiCompatibleBaseUrl, codebaseIndexSearchMaxResults: mergedStateValues.codebaseIndexConfig?.codebaseIndexSearchMaxResults, codebaseIndexSearchMinScore: mergedStateValues.codebaseIndexConfig?.codebaseIndexSearchMinScore, codebaseIndexBedrockRegion: mergedStateValues.codebaseIndexConfig?.codebaseIndexBedrockRegion, codebaseIndexBedrockProfile: mergedStateValues.codebaseIndexConfig?.codebaseIndexBedrockProfile, codebaseIndexOpenRouterSpecificProvider: mergedStateValues.codebaseIndexConfig?.codebaseIndexOpenRouterSpecificProvider, }, profileThresholds: mergedStateValues.profileThresholds ?? {}, lockApiConfigAcrossModes: this.context.workspaceState.get("lockApiConfigAcrossModes", false), includeDiagnosticMessages: mergedStateValues.includeDiagnosticMessages ?? true, maxDiagnosticMessages: mergedStateValues.maxDiagnosticMessages ?? 50, includeTaskHistoryInEnhance: mergedStateValues.includeTaskHistoryInEnhance ?? true, taskTitleGenerationEnabled: mergedStateValues.taskTitleGenerationEnabled ?? DEFAULT_TASK_TITLE_GENERATION_ENABLED, taskTitleApiConfigId: mergedStateValues.taskTitleApiConfigId, includeCurrentTime: mergedStateValues.includeCurrentTime ?? true, includeCurrentCost: mergedStateValues.includeCurrentCost ?? true, maxGitStatusFiles: mergedStateValues.maxGitStatusFiles ?? 0, taskSyncEnabled, imageGenerationProvider: mergedStateValues.imageGenerationProvider, openRouterImageApiKey: mergedStateValues.openRouterImageApiKey, openRouterImageGenerationSelectedModel: mergedStateValues.openRouterImageGenerationSelectedModel, autoCloseZooOpenedFiles: mergedStateValues.autoCloseZooOpenedFiles, autoCloseZooOpenedFilesAfterUserEdited: mergedStateValues.autoCloseZooOpenedFilesAfterUserEdited, autoCloseZooOpenedNewFiles: mergedStateValues.autoCloseZooOpenedNewFiles, } } /** * Updates a task in the task history and optionally broadcasts the updated history to the webview. * Now delegates to TaskHistoryStore for per-task file persistence. * * This writer never owns the `title` or `autoTitle` fields: `title` is written only by the rename * path (`renameTaskWithId` via `taskHistoryStore.atomicReadAndUpdate`) and `autoTitle` only by * `setAutoTitle`. Callers here build items from snapshots read before taking the store lock, * so any title they carry can be stale. * * @param item The history item to update or add * @param options.broadcast Whether to broadcast the updated history to the webview (default: true) * @returns The updated task history array */ async updateTaskHistory(item: HistoryItem, options: { broadcast?: boolean } = {}): Promise { const { broadcast = true } = options // Drop the snapshot's titles so upsertCore preserves the values held under the store lock // instead of treating a stale title as a changed field and reverting a concurrent write. const { title: _title, autoTitle: _autoTitle, ...itemWithoutTitle } = item const history = await this.taskHistoryStore.upsert(itemWithoutTitle) this.recentTasksCache = undefined // Broadcast the updated history to the webview if requested. // Prefer per-item updates to avoid repeatedly cloning/sending the full history. if (broadcast && this.isViewLaunched) { const updatedItem = this.taskHistoryStore.get(item.id) ?? itemWithoutTitle await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem }) } return history } /** * Broadcasts a task history update to the webview. * This sends a lightweight message with just the task history, rather than the full state. * @param history The task history to broadcast (if not provided, reads from the store) */ public async broadcastTaskHistoryUpdate(history?: HistoryItem[]): Promise { if (!this.isViewLaunched) { return } const taskHistory = history ?? this.taskHistoryStore.getAll() // Sort and filter the history the same way as getStateToPostToWebview const sortedHistory = taskHistory .filter((item: HistoryItem) => item.ts && item.task) .sort((a: HistoryItem, b: HistoryItem) => b.ts - a.ts) await this.postMessageToWebview({ type: "taskHistoryUpdated", taskHistory: sortedHistory, }) } // ContextProxy // @deprecated - Use `ContextProxy#setValue` instead. private async updateGlobalState(key: K, value: GlobalState[K]) { await this.contextProxy.setValue(key, value) } // @deprecated - Use `ContextProxy#getValue` instead. private getGlobalState(key: K) { return this.contextProxy.getValue(key) } public async setValue( key: K, value: RooCodeSettings[K], options: { pinWriteOwner?: symbol } = {}, ) { if (key === "mode" && value !== undefined) { // The generic signature keeps the nominal RooCodeSettings[K] even after K is // narrowed to "mode" (runtime type string | undefined); one assertion to the // narrowed shape lets the shared guard type-check, mirroring setValues. const modeValue = value as string | undefined if ( typeof modeValue !== "string" || !getModeBySlug(modeValue, await this.customModesManager.getCustomModes()) ) { this.log(`[ClineProvider#setValue] Ignoring invalid mode "${String(value)}"`) return } } const writtenSharedValues = { [key]: value } as RooCodeSettings // A provider-key write replaces the shared store that a sibling view's pin falls back onto, // so pin that sibling's own profile settings into its overlay first - the protection // setValues takes before a multi-key provider write and the activation paths take before // their shared write. This write is not tied to a saved profile, so no pin is exempt from // the snapshot. Unrelated single-key writes do not touch the shared store and skip it. if (PROVIDER_SETTINGS_KEYS.some((providerKey) => providerKey in writtenSharedValues)) { await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(undefined) } // The value the rollback below restores is read after that snapshot awaits, immediately before // this call writes: another view can complete a write to the same key while this one is inside // the snapshot, and restoring what was current before the wait would undo that write. setValues // takes the same position, capturing before its own write group rather than before the pins. const previousSharedValues = { [key]: this.contextProxy.getValue(key) } as RooCodeSettings try { await this.contextProxy.setValue(key, value) } catch (error) { // The shared write is inside the rollback scope too: ContextProxy persists // keys one at a time, so a rejected initial write must not leave a durable // subset behind without the compensating restore below. await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues, writtenSharedValues) throw error } try { await this._saveViewLocalStateFromMutation({ [key]: value }, options) } catch (error) { // The per-view record did not land: restore the prior shared value so the two // persistence layers cannot diverge, then surface the original failure. await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues, writtenSharedValues) throw error } } /** * Restore shared values captured before a setter wrote them, used when the paired * per-view persistence failed so the shared store cannot move ahead of the per-view * record. Only keys that still hold the value this call wrote are replayed: the shared * store is host-wide, so a sibling view can write the same key while this call awaits, * and replaying this call's snapshot over the newer value would silently undo the * sibling's write. A failed rollback is logged; the original failure is what callers * see. */ private async _restoreSharedValuesAfterFailedViewWrite( previous: RooCodeSettings, written: RooCodeSettings, ): Promise { const current = this.contextProxy.getValues() const restore = Object.fromEntries( Object.entries(previous).filter(([key]) => deepEqual(current[key as keyof RooCodeSettings], written[key as keyof RooCodeSettings]), ), ) as RooCodeSettings if (Object.keys(restore).length === 0) { return } try { await this.contextProxy.setValues(restore) } catch (rollbackError) { this.log( `[ClineProvider] Shared-state rollback after failed per-view write failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, ) } } public getValue(key: K) { return this.contextProxy.getValue(key) } public getValues() { return { ...this.contextProxy.getValues(), ...this.viewLocalState } } /** * Write a group of settings through the shared store and this view's record, rolling both * halves back when either one fails. Returns what each layer held immediately before this * call's own write group: another view - or this view's own user - can move either layer * while this call awaits the custom-mode validation below, so a later compensation must * restore these snapshots rather than anything read before the wait. */ public async setValues( values: RooCodeSettings, options?: { savedProfileName?: string }, ): Promise { const sanitizedValues = withoutInvalidDisplaySettings(values, (key) => this.log(`[setValues] Ignored an invalid value for ${key}`), ) if (sanitizedValues.mode !== undefined) { // An unknown or non-string mode (e.g. from an API payload) must not be persisted: // a new Task would read it from getState() and persist it into task history. // A payload that carries its own customModes (createTask and setConfiguration // call setValues before registering them) validates against those too, so a // brand-new custom mode in the same payload is not silently dropped. if ( typeof sanitizedValues.mode !== "string" || !getModeBySlug(sanitizedValues.mode, [ ...(await this.customModesManager.getCustomModes()), ...(sanitizedValues.customModes ?? []), ]) ) { this.log(`[ClineProvider#setValues] Ignoring invalid mode "${String(sanitizedValues.mode)}"`) delete sanitizedValues.mode } } // A flat provider write replaces the shared store: a sibling pinned to a // profile whose settings are not part of this payload would serve the // caller's provider, model, or credentials on its next task, so pin its // overlay before the shared write (the protection the activation paths // take). When the caller saves a profile with this payload, siblings // pinned to that profile must not be pinned to the pre-save snapshot: // the write carries their profile's new settings, and their overlays are // refreshed from the payload after the write instead. const touchesProviderKeys = PROVIDER_SETTINGS_KEYS.some((key) => key in sanitizedValues) if (touchesProviderKeys) { await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(options?.savedProfileName) } const previousSharedValues = Object.fromEntries( Object.keys(sanitizedValues).map((key) => [key, this.contextProxy.getValue(key as keyof RooCodeSettings)]), ) as RooCodeSettings // The same instant for this view's record, over the same keys: the per-view layer can hold // a different value from the shared store, and it is captured here rather than earlier so // a pin acquired while validation awaited is part of what this write group replaced. The // buffer is typed as the view-local value shape its writers use (see ViewLocalStateValues), // which is what the keys of this write group index into. const viewLocalValues = this.viewLocalState as ViewLocalStateValues const previousViewValues = Object.fromEntries( Object.keys(sanitizedValues).map((key) => [key, viewLocalValues[key as keyof ViewLocalStateValues]]), ) as RooCodeSettings try { await this.contextProxy.setValues(sanitizedValues) } catch (error) { // Same scope rule as setValue: a multi-key write that fails partway has // already persisted a durable subset, so the restore must cover the // initial shared write, not only the per-view persistence below. await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues, sanitizedValues) throw error } try { await this._saveViewLocalStateFromMutation(sanitizedValues) } catch (error) { // The per-view record did not land: restore the prior shared values so the two // persistence layers cannot diverge, then surface the original failure. await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues, sanitizedValues) throw error } if (touchesProviderKeys && options?.savedProfileName !== undefined) { // Siblings pinned to the profile this payload saves: the shared store now // carries the saved settings; refresh their overlays so they serve the // fresh copy instead of a pre-save snapshot. const savedSettings = Object.fromEntries( PROVIDER_SETTINGS_KEYS.map((key) => [key, sanitizedValues[key]]).filter( ([, value]) => value !== undefined, ), ) as ProviderSettings await this.refreshViewLocalStateForUpdatedProfile(options.savedProfileName, savedSettings) } return { shared: previousSharedValues, view: previousViewValues } } /** * Persists the view-local subset of a ContextProxy mutation, then updates the in-memory * viewLocalState buffer. Persistence is awaited first so a failed durable write cannot * leave the local cache ahead of the persisted state. */ private async _saveViewLocalStateFromMutation( values: Partial & Partial, options: { pinWriteOwner?: symbol } = {}, ): Promise { await this._persistViewLocalStateFromMutation(values, options) this._updateViewLocalStateFromMutation(values) } /** * Update or invalidate viewLocalState when ContextProxy is mutated via setValues, setValue, * profile upsert/activation/deletion, or resetState. This ensures the local cache stays in * sync with global state changes that would otherwise be invisible behind mergedStateValues. */ private _updateViewLocalStateFromMutation(values: Partial & Partial): void { if ("mode" in values) { this.viewLocalStateMutatedFields.add("mode") const val = values.mode if (val === undefined || val === null) { delete this.viewLocalState.mode } else { this.viewLocalState.mode = val } } if ("currentApiConfigName" in values) { this.viewLocalStateMutatedFields.add("currentApiConfigName") const val = values.currentApiConfigName if (val === undefined || val === null) { delete this.viewLocalState.currentApiConfigName } else { this.viewLocalState.currentApiConfigName = val } } if ("apiConfiguration" in values) { this.viewLocalStateMutatedFields.add("apiConfiguration") const val = values.apiConfiguration if (val === undefined || val === null) { delete this.viewLocalState.apiConfiguration } else { this.viewLocalState.apiConfiguration = val } } // Flat provider-settings keys (PROVIDER_SETTINGS_KEYS) are shared settings: // they are written through the ContextProxy above and must NOT be merged // into viewLocalState.apiConfiguration, which would turn them into a // per-view override masking later shared updates from other views. If the // mutation carries such a key, drop this view's overlay instead so it cannot // mask the just-written shared values in getState() (the overlay, seeded by // a persisted pin or a sibling refresh, is older than this shared write). if (PROVIDER_SETTINGS_KEYS.some((key) => key in values)) { delete this.viewLocalState.apiConfiguration } } /** * Writes the durably persisted subset of a mutation (mode and currentApiConfigName) * into the registered viewStates map for this view. */ private async _persistViewLocalStateFromMutation( values: Partial & Partial, options: { pinWriteOwner?: symbol } = {}, ): Promise { const persistedValues: Partial = {} if ("mode" in values) { persistedValues.mode = values.mode as PersistedViewState["mode"] } if ("currentApiConfigName" in values) { persistedValues.currentApiConfigName = values.currentApiConfigName } if ("mode" in persistedValues || "currentApiConfigName" in persistedValues) { await this.savePersistedViewState(persistedValues, options) } } /** * Clear view-local state cache so that getState() falls back to ContextProxy defaults. */ private _clearViewLocalState(): void { // A clear is not a field mutation, so the loadViewState field tracking cannot see // it: bump the generation the load captured instead (see the field comment). this.viewStateLoadGeneration += 1 this.viewLocalState = {} } /** * Broadcast a reset/import invalidation to all live ClineProvider instances, clearing * both in-memory view-local caches and durable per-view selections so stale view state * cannot mask imported/reset shared state after reload. */ async broadcastResetToAllInstances(): Promise { const allInstances = ClineProvider.getAllInstances() // The durable per-view selections live in one shared global-state slot, so // the reset needs exactly one durable clear. Route it through the persisted // write queue (and run it before the in-memory clears): a per-instance clear // outside the queue could interleave with a queued view-state write and // either clobber that write or leave a re-created entry behind. const clearWrite = ClineProvider.persistedViewStateWriteQueue.then(async () => { await this.contextProxy.setValue("viewStates", undefined) }) ClineProvider.persistedViewStateWriteQueue = clearWrite.catch(() => {}) // Durable invalidation must not gate live invalidation: when the durable // clear rejects, every live buffer still has to be cleared and every // sibling still has to be posted, or the reset leaves views serving stale // selections behind a failed shared slot. The error is re-thrown after the // loop so callers still see the durable failure. let durableClearError: unknown try { await clearWrite } catch (error) { durableClearError = error this.log( `[broadcastResetToAllInstances] durable viewStates clear failed; live state is still invalidated: ${ error instanceof Error ? error.message : String(error) }`, ) } for (const instance of allInstances) { instance._clearViewLocalState() if (instance !== this) { // A sibling's post can throw mid-reset (state generation reaches the // settings file through customModesManager.getCustomModes): the failure // must not stop the reset from reaching the remaining instances, whose // buffers are already cleared above. The originator is deliberately not // posted here: resetState posts its own state immediately after the // broadcast, and a second post would refresh its webview twice. try { await instance.postStateToWebview() } catch (error) { this.log( `[broadcastResetToAllInstances] failed to post reset state to a sibling view: ${ error instanceof Error ? error.message : String(error) }`, ) } } } if (durableClearError) { throw durableClearError } } // dev async resetState() { const answer = await vscode.window.showInformationMessage( t("common:confirmation.reset_state"), { modal: true }, t("common:answers.yes"), ) if (answer !== t("common:answers.yes")) { return } // Log out from cloud if authenticated if (CloudService.hasInstance()) { try { await CloudService.instance.logout() } catch (error) { this.log( `Failed to logout from cloud during reset: ${error instanceof Error ? error.message : String(error)}`, ) // Continue with reset even if logout fails } } await this.contextProxy.resetAllState() // Per-view state (this view's buffer and durable entry) is cleared by the // broadcast below: it clears the durable map once through the serialized // write queue and every live buffer, and only rethrows after that work, so // a per-view clear here would only add a failure point that can strand the // reset between the shared and provider resets. await this.providerSettingsManager.resetAllConfigs() // Cached choices point at profiles that no longer exist; re-read the reset mapping. this.localModeConfigIds.clear() this.captureInitialModeConfigIds() await this.customModesManager.resetCustomModes() await this.removeClineFromStack() // Clear durable and in-memory per-view state across live instances so parallel tabs don't keep stale state. await this.broadcastResetToAllInstances() await this.postStateToWebview() await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" }) } // logging public log(message: string) { this.outputChannel.appendLine(message) console.log(message) } // getters public get workspaceTracker(): WorkspaceTracker | undefined { return this._workspaceTracker } get viewLaunched() { return this.isViewLaunched } get messages() { return this.getCurrentTask()?.clineMessages || [] } public getMcpHub(): McpHub | undefined { return this.mcpHub } public getSkillsManager(): SkillsManager | undefined { return this.skillsManager } /** * Check if the current state is compliant with MDM policy * @returns true if compliant or no MDM policy exists, false if MDM policy exists and user is non-compliant */ public checkMdmCompliance(): boolean { if (!this.mdmService) { return true // No MDM service, allow operation } const compliance = this.mdmService.isCompliant() if (!compliance.compliant) { return false } return true } public getCurrentWorkspaceCodeIndexScope(): CodeIndexWorkspaceScope | undefined { return CodeIndexManagerRegistry.getOrCreateScope(this.context) } /** * TaskProviderLike, TelemetryPropertiesProvider */ public getCurrentTask(): Task | undefined { return this.taskRegistry.current } private logWebviewHiddenDiagnostics(): void { const task = this.getCurrentTask() if (!task || task.abort || task.abandoned) { return } this.log( `[Zoo Code] Webview hidden during active task.\n` + ` taskId: ${task.taskId}\n` + ` messageCount: ${task.clineMessages.length}\n` + ` stackDepth: ${this.taskRegistry.length}\n` + ` timestamp: ${new Date().toISOString()}\n` + `If the panel appears gray after this, share this log with support@zoocode.dev`, ) } /** A heartbeat confirms liveness; only sustained health replenishes recovery attempts. */ public updateWebviewHeartbeat(): void { const now = Date.now() const health = recoveryHealth( { attempts: this.webviewRecoveryAttempts, lastHeartbeatAt: this.lastReceivedWebviewHeartbeatAt, healthySince: this.webviewHealthySince, }, now, ) this.webviewHealthySince = health.healthySince this.lastReceivedWebviewHeartbeatAt = now this.webviewHeartbeatCount++ // A new heartbeat invalidates the old warning action. Allow a fresh warning // if this renderer stalls again, without replenishing its retry budget. this.webviewRecoveryFailureReported = false this.webviewRecoveryStopLogged = false if (this.webviewRecoveryConfirmation) { this.log("[Zoo Code] Webview heartbeat returned after recovery") } this.resetWebviewHeartbeatGrace() if (health.attempts === 0 && this.webviewRecoveryAttempts > 0) { this.log("[Zoo Code] Webview recovery confirmed by sustained heartbeats") } this.webviewRecoveryAttempts = health.attempts } /** Restarts the grace window and invalidates pending recovery without recording a heartbeat. */ private resetWebviewHeartbeatGrace(): void { this.clearWebviewRecoveryConfirmation() this.lastWebviewHeartbeatAt = Date.now() this.webviewHeartbeatRevision++ } /** * Starts (or restarts) the watchdog that detects a dead webview renderer * process. Hidden webviews throttle timers, so becoming visible resets the * grace window instead of counting throttled heartbeats as a crash. */ private startWebviewWatchdog(): void { this.resetWebviewHeartbeatGrace() this.lastWebviewWatchdogTickAt = Date.now() if (this.webviewWatchdogInterval) { clearInterval(this.webviewWatchdogInterval) } this.webviewWatchdogInterval = setInterval(() => { const now = Date.now() const tickGap = now - this.lastWebviewWatchdogTickAt this.lastWebviewWatchdogTickAt = now // A tick far later than scheduled means the host was suspended or // blocked; the wall clock jumped while both timers were paused. // Grant a fresh grace window instead of reloading a live renderer. if (tickGap > ClineProvider.WEBVIEW_WATCHDOG_TICK_MS * 1.5) { this.resetWebviewHeartbeatGrace() return } if (this.view?.visible !== true) { return } if (now - this.lastWebviewHeartbeatAt <= ClineProvider.WEBVIEW_HEARTBEAT_STALE_MS) return if (this.webviewRecoveryAttempts >= ClineProvider.WEBVIEW_RECOVERY_ATTEMPT_LIMIT) { // Let the final attempt finish generating HTML before declaring recovery stopped. if (this.webviewRecoveryInFlightEpoch !== this.webviewRecoveryEpoch) { this.reportWebviewRecoveryFailure("Recovery attempt limit reached without sustained heartbeats") } return } this.log("[Zoo Code] Webview heartbeat stale while visible; attempting recovery") void this.reloadWebviewForRecovery() }, ClineProvider.WEBVIEW_WATCHDOG_TICK_MS) } /** Stops the renderer heartbeat watchdog; the webview it watches is gone. */ private stopWebviewWatchdog(): void { this.clearWebviewRecoveryConfirmation() if (this.webviewWatchdogInterval) { clearInterval(this.webviewWatchdogInterval) this.webviewWatchdogInterval = null } } /** * First attempt: regenerate this view's HTML. A missing heartbeat escalates * to host recreation because HTML delivery cannot restart a dead renderer. */ private async reloadWebviewForRecovery(): Promise { const view = this.view if (!view?.webview || this.webviewRecoveryAttempts >= ClineProvider.WEBVIEW_RECOVERY_ATTEMPT_LIMIT) { return } // Capture the epoch so a disposal or view replacement can invalidate // this operation while the HTML is being generated. const epoch = this.webviewRecoveryEpoch // A recovery already awaiting its HTML generation owns this view; a // second one would only pile another forced reload onto it. Ownership // is scoped to the epoch so a stale recovery (its view disposed or // replaced, epoch bumped) never blocks the replacement view's recovery. const attempt = nextRecoveryAttempt(this.webviewRecoveryAttempts, this.webviewRecoveryInFlightEpoch === epoch) if (attempt === undefined) return this.webviewRecoveryInFlightEpoch = epoch // Count the whole attempt, including HTML-generation failures. this.webviewRecoveryAttempts = attempt this.lastReceivedWebviewHeartbeatAt = undefined this.webviewHealthySince = undefined // A heartbeat that arrives while the HTML is being generated means the // renderer is alive again; comparing revisions (not timestamps) lets the // post-await check catch heartbeats that land in the same millisecond. const heartbeatRevision = this.webviewHeartbeatRevision try { const html = await this.getWebviewHtml(view.webview) // The await yields; assigning html now that the provider is disposed, // the watched view was disposed/replaced, the renderer heartbeat // recovered, or the view hid again would either touch a dead or // unrelated webview or reload one that no longer needs recovery. if ( !canCommitRecovery({ disposed: this._disposed, isCurrent: this.view === view, epochMatches: this.webviewRecoveryEpoch === epoch, heartbeatMatches: this.webviewHeartbeatRevision === heartbeatRevision, visible: view.visible === true, }) ) { return } view.webview.html = html this.resetWebviewHeartbeatGrace() const revision = this.webviewHeartbeatRevision const requestedAt = Date.now() this.webviewRecoveryConfirmation = setTimeout(() => { this.webviewRecoveryConfirmation = undefined // A late confirmation timer can be a host suspend, just like a // late watchdog tick. Let renderer timers resume before escalating. if (Date.now() - requestedAt > ClineProvider.WEBVIEW_RECOVERY_CONFIRM_MS * 1.5) { this.resetWebviewHeartbeatGrace() return } if ( this._disposed || this.view !== view || this.webviewRecoveryEpoch !== epoch || this.webviewHeartbeatRevision !== revision || !view.visible ) return void this.recreateWebviewHostForRecovery(view).catch((error: unknown) => { this.reportWebviewRecoveryFailure( `Host recreation failed: ${error instanceof Error ? error.message : String(error)}`, ) }) }, ClineProvider.WEBVIEW_RECOVERY_CONFIRM_MS) } catch (error) { this.log(`[Zoo Code] Failed to reload webview: ${error instanceof Error ? error.message : String(error)}`) } finally { // Clear ownership only while this completion still holds it; a // stale recovery must not release the replacement's in-flight state. this.webviewRecoveryInFlightEpoch = releaseRecoveryOwner(this.webviewRecoveryInFlightEpoch, epoch) } } private clearWebviewRecoveryConfirmation(): void { if (this.webviewRecoveryConfirmation) clearTimeout(this.webviewRecoveryConfirmation) this.webviewRecoveryConfirmation = undefined } /** Recreate the host/transport: sending more HTML cannot revive its dead renderer. */ private async recreateWebviewHostForRecovery(view: vscode.WebviewView | vscode.WebviewPanel): Promise { if (this.webviewHostRecoveryInProgress || this._disposed || this.view !== view || !view.visible) return const revision = this.webviewHeartbeatRevision const generation = this.webviewRecoveryRequestGeneration let started = false let sidebarFocused = false try { let commands: string[] | undefined if (!("onDidChangeViewState" in view)) { // Generated VS Code view commands are not an extension API contract. // Check availability and cover them against the pinned real host in E2E. commands = await vscode.commands.getCommands(true) } if ( !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration) || this.webviewHostRecoveryInProgress || this._disposed || this.view !== view || !view.visible || this.webviewHeartbeatRevision !== revision ) return if ( commands && (!commands.includes(`${ClineProvider.sideBarId}.removeView`) || !commands.includes(`${ClineProvider.sideBarId}.focus`)) ) { throw new Error("VS Code does not provide the scoped sidebar recreation commands") } this.webviewHostRecoveryInProgress = true started = true this.log("[Zoo Code] No heartbeat after HTML reload; recreating this webview host") if ("onDidChangeViewState" in view) { const replacement = vscode.window.createWebviewPanel( ClineProvider.tabPanelId, view.title, { viewColumn: view.viewColumn ?? vscode.ViewColumn.Active, preserveFocus: true }, { ...view.options, ...view.webview.options }, ) replacement.iconPath = view.iconPath // Resolve publishes the replacement before yielding. The old view's // disposal must see it no longer owns this provider and its tasks. const resolved = this.resolveWebviewView(replacement) if (this.view === replacement) view.dispose() else replacement.dispose() await resolved } else { this.pendingSidebarRecovery = true await vscode.commands.executeCommand(`${ClineProvider.sideBarId}.removeView`) if (this._disposed || !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return await vscode.commands.executeCommand(`${ClineProvider.sideBarId}.focus`, { preserveFocus: true }) sidebarFocused = true if (!isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return await this.waitForRecoveryView(view, generation) } } catch (error) { if (!isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return // Only a successful focus can leave a delayed replacement pending. // Command failures must not mark a later manual open as recovery. this.pendingSidebarRecovery = pendingSidebarAfterCommandFailure({ started, focusSucceeded: sidebarFocused, pending: this.pendingSidebarRecovery, }) // A late discovery failure must not stop a recovered/replaced view. // Once recreation starts, disposal of the old view is expected. if ( this._disposed || (!started && (this.view !== view || this.webviewHeartbeatRevision !== revision || !view.visible)) ) return if (started && this.lastReceivedWebviewHeartbeatAt !== undefined) return // A published replacement may still be initializing after the wait // expires. Its resolver will restore the watchdog on failure; keep the // remaining attempts available instead of turning this into a dead end. const replacementPublished = this.view !== undefined && this.view !== view this.reportWebviewRecoveryFailure( `Host recreation failed: ${error instanceof Error ? error.message : String(error)}`, !replacementPublished, ) } finally { if (started && isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) this.webviewHostRecoveryInProgress = false } } private async waitForRecoveryView( previous: vscode.WebviewView | vscode.WebviewPanel | undefined, generation: number, ): Promise { await pWaitFor( () => this._disposed || !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration) || (this.view !== undefined && this.view !== previous && this.webviewWatchdogInterval !== null), { interval: 50, timeout: 10_000 }, ) } /** An explicit user action, unlike an ambiguous VS Code resolve callback. */ public async retryWebviewRecovery(expectedGeneration = this.webviewRecoveryRequestGeneration): Promise { if (this._disposed || !isRecoveryGenerationCurrent(expectedGeneration, this.webviewRecoveryRequestGeneration)) return const fresh = beginExplicitRecovery(this.webviewRecoveryRequestGeneration) const generation = fresh.generation this.webviewRecoveryRequestGeneration = generation const view = this.view if (!view || !("onDidChangeViewState" in view)) this.pendingSidebarRecovery = true this.webviewRecoveryEpoch++ this.webviewRecoveryInFlightEpoch = undefined this.webviewHostRecoveryInProgress = false // Count this user-requested attempt in its fresh, bounded incident. this.webviewRecoveryAttempts = fresh.attempts this.webviewRecoveryFailureReported = fresh.reported this.webviewRecoveryStopLogged = fresh.stopLogged this.lastReceivedWebviewHeartbeatAt = undefined this.webviewHealthySince = undefined this.resetWebviewHeartbeatGrace() let focused = false try { if (view) { if ("onDidChangeViewState" in view) view.reveal(view.viewColumn ?? vscode.ViewColumn.Active, true) else view.show(true) await pWaitFor( () => this._disposed || !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration) || this.view !== view || view.visible, { interval: 50, timeout: 10_000 }, ) if ( this._disposed || !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration) || this.view !== view ) return await this.recreateWebviewHostForRecovery(view) } else { // The earlier timeout may have removed the only sidebar. The next // resolve, whatever triggered it, repairs this explicitly renewed incident. this.pendingSidebarRecovery = true this.webviewHostRecoveryInProgress = true await vscode.commands.executeCommand(`${ClineProvider.sideBarId}.focus`, { preserveFocus: true }) focused = true if (!isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return await this.waitForRecoveryView(undefined, generation) } } catch (error) { if (this._disposed || !isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) return this.pendingSidebarRecovery = pendingSidebarAfterCommandFailure({ started: true, focusSucceeded: focused, pending: this.pendingSidebarRecovery, }) const replacementPublished = this.view !== undefined && this.view !== view this.reportWebviewRecoveryFailure( `Explicit interface recovery failed: ${String(error)}`, !replacementPublished, ) } finally { if (isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration)) this.webviewHostRecoveryInProgress = false } } private reportWebviewRecoveryFailure(reason: string, stopRecovery = true): void { if (this._disposed) return // A terminal failure still stops retries if an earlier retryable failure // already showed the notification for this incident. const failure = recordRecoveryFailure( { attempts: this.webviewRecoveryAttempts, reported: this.webviewRecoveryFailureReported, stopLogged: this.webviewRecoveryStopLogged, }, stopRecovery, ) this.webviewRecoveryAttempts = failure.attempts this.webviewRecoveryFailureReported = failure.reported this.webviewRecoveryStopLogged = failure.stopLogged if (failure.log) this.log(`[Zoo Code] Webview recovery ${stopRecovery ? "stopped" : "will retry"}: ${reason}`) if (!failure.notify) return const heartbeatCount = this.webviewHeartbeatCount const generation = this.webviewRecoveryRequestGeneration void Promise.resolve( vscode.window.showWarningMessage( "Zoo Code's interface is not responding. Retry interface recovery without restarting running tasks. Reloading the VS Code window will restart extensions and may interrupt running tasks.", "Retry Interface Recovery", "Reload Window", "Show Logs", ), ) .then(async (choice) => { const action = recoveryWarningAction( choice, this._disposed, this.webviewHeartbeatCount === heartbeatCount, isRecoveryGenerationCurrent(generation, this.webviewRecoveryRequestGeneration), ) if (action === "retry") await this.retryWebviewRecovery(generation) if (action === "reload") { await vscode.commands.executeCommand("workbench.action.reloadWindow") } if (action === "logs") this.outputChannel.show() }) .then(undefined, (error: unknown) => { this.log(`[Zoo Code] Recovery notification failed: ${String(error)}`) }) } /** Builds the webview HTML using the same path as resolveWebviewView (HMR in development). */ private async getWebviewHtml(webview: vscode.Webview): Promise { return this.contextProxy.extensionMode === vscode.ExtensionMode.Development && process.env.ROO_CODE_THEME_FIXTURE_PROBE !== "1" ? await this.getHMRHtmlContent(webview) : await this.getHtmlContent(webview) } public getRecentTasks(): string[] { if (this.recentTasksCache) { return this.recentTasksCache } const history = this.taskHistoryStore.getAll() const workspaceTasks: HistoryItem[] = [] for (const item of history) { if (!item.ts || !item.task || item.workspace !== this.cwd) { continue } workspaceTasks.push(item) } if (workspaceTasks.length === 0) { this.recentTasksCache = [] return this.recentTasksCache } workspaceTasks.sort((a, b) => b.ts - a.ts) let recentTaskIds: string[] = [] if (workspaceTasks.length >= 100) { // If we have at least 100 tasks, return tasks from the last 7 days. const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000 for (const item of workspaceTasks) { // Stop when we hit tasks older than 7 days. if (item.ts < sevenDaysAgo) { break } recentTaskIds.push(item.id) } } else { // Otherwise, return the most recent 100 tasks (or all if less than 100). recentTaskIds = workspaceTasks.slice(0, Math.min(100, workspaceTasks.length)).map((item) => item.id) } this.recentTasksCache = recentTaskIds return this.recentTasksCache } // When initializing a new task, (not from history but from a tool command // new_task) there is no need to remove the previous task since the new // task is a subtask of the previous one, and when it finishes it is removed // from the stack and the caller is resumed in this way we can have a chain // of tasks, each one being a sub task of the previous one until the main // task is finished. public async createTask( text?: string, images?: string[], parentTask?: Task, options: CreateTaskOptions & { handoffExecutionContext?: DelegatedChildContext segments?: MentionSegment[] } = {}, configuration: RooCodeSettings = {}, ): Promise { if (configuration) { // Whether the payload carried a mode of its own, and that value: the rollback // below owns the mode layers only for a payload that wrote them, and only while // they still hold this call's value. const modeWasProvided = Object.prototype.hasOwnProperty.call(configuration, "mode") const requestedMode = configuration.mode // What each layer held at setValues' own write group, which that call reports // itself. Take both from there rather than reading either layer before the call: // another view - or this view's own user - can move either one while setValues // awaits mode validation, and restoring a pre-validation read would undo that. // A report that carries no mode key means this payload wrote no mode at all // (validation dropped an unknown slug), so there is nothing here for this call // to restore in that layer. const valuesBeforeWrite = await this.setValues(configuration) if (configuration.allowedCommands) { await vscode.workspace .getConfiguration(Package.name) .update("allowedCommands", configuration.allowedCommands, vscode.ConfigurationTarget.Global) } if (configuration.deniedCommands) { await vscode.workspace .getConfiguration(Package.name) .update("deniedCommands", configuration.deniedCommands, vscode.ConfigurationTarget.Global) } if (configuration.commandExecutionTimeout !== undefined) { await vscode.workspace .getConfiguration(Package.name) .update( "commandExecutionTimeout", configuration.commandExecutionTimeout, vscode.ConfigurationTarget.Global, ) } if (configuration.currentApiConfigName) { await this.setProviderProfile(configuration.currentApiConfigName) } // Register custom modes so the CustomModesManager knows about them. // setValues writes to global state, but the manager overwrites that // when it merges .roomodes + global settings on refresh. Persisting // via updateCustomMode ensures modes survive the merge cycle. if (configuration.customModes?.length) { try { for (const mode of configuration.customModes) { await this.customModesManager.updateCustomMode(mode.slug, mode) } } catch (error) { // setValues already persisted the payload's mode to shared and per-view // state; if registration fails the mode is not actually usable, so each // layer rolls back to its own prior value (an unset pin stays unset) // before the failure surfaces. Each restore is awaited on its own and // logged on failure, never swallowed; the original failure is what // callers see. try { // Restore a layer only when this write group actually carried a mode into it and // it still holds the value this call wrote: updateCustomMode awaits queued file // I/O, so another view may have moved the layer in the meantime, a payload that // omitted mode never wrote one, and a payload whose slug validation dropped // wrote none either - in that case whatever the layers hold now is somebody // else's selection and must survive. if ( modeWasProvided && Object.prototype.hasOwnProperty.call(valuesBeforeWrite.shared, "mode") && this.contextProxy.getValue("mode") === requestedMode ) { await this.contextProxy.setValue("mode", valuesBeforeWrite.shared.mode) } } catch (rollbackError) { this.log( `[ClineProvider#createTask] Failed to restore the shared mode after custom-mode registration failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, ) } try { if ( modeWasProvided && Object.prototype.hasOwnProperty.call(valuesBeforeWrite.view, "mode") && this.viewLocalState?.mode === requestedMode ) { await this.saveViewState("mode", valuesBeforeWrite.view.mode) } } catch (rollbackError) { this.log( `[ClineProvider#createTask] Failed to restore the view mode pin after custom-mode registration failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, ) } throw error } } } const { apiConfiguration, enableCheckpoints, checkpointTimeout, experiments, organizationAllowList, diffFuzzyThreshold, } = await this.getState() const effectiveApiConfiguration = getEffectiveTaskApiConfiguration( apiConfiguration, options.handoffExecutionContext, ) // Single-open-task invariant: always enforce for user-initiated top-level tasks. if (!parentTask) { await this.evictCurrentTask().catch(() => { // Non-fatal }) } if (!ProfileValidator.isProfileAllowed(effectiveApiConfiguration, organizationAllowList)) { throw new OrganizationAllowListViolationError(t("common:errors.violated_organization_allowlist")) } const task = new Task({ provider: this, apiConfiguration, enableCheckpoints, checkpointTimeout, consecutiveMistakeLimit: effectiveApiConfiguration.consecutiveMistakeLimit, toolRepetitionSoftLimit: effectiveApiConfiguration.toolRepetitionSoftLimit, task: text, images, experiments, rootTask: this.taskRegistry.getAll()[0], parentTask, taskNumber: this.taskRegistry.length + 1, onCreated: this.taskCreationCallback, initialTodos: options.initialTodos, // Ensure this task is present in the registry before startTask() emits // its initial state update, so state.currentTaskId is available ASAP. startTask: false, diffFuzzyThreshold, ...options, rateLimitClock: this.rateLimitClock, }) await this.addClineToStack(task) if (options.startTask !== false) { scheduleTask(this.taskScheduler, task, "createTask") } this.log( `[createTask] ${task.parentTask ? "child" : "parent"} task ${task.taskId}.${task.instanceId} instantiated`, ) return task } public async cancelTask(): Promise { const task = this.getCurrentTask() if (!task) { return } console.log(`[cancelTask] cancelling task ${task.taskId}.${task.instanceId}`) await this.cancelTaskInternal(task) } private async cancelTaskInternal(task: Task): Promise { let historyItem: HistoryItem | undefined try { const history = await this.getTaskWithId(task.taskId) historyItem = history.historyItem } catch (error) { // During task startup there is a short window where currentTask exists // but task history has not been persisted yet. Cancelling should still // abort safely; we just skip post-cancel rehydration in that case. if (error instanceof Error && error.message === "Task not found") { this.log(`[cancelTask] task history missing for ${task.taskId}; skipping rehydrate`) } else { throw error } } // Preserve parent and root task information for history item. let rootTask = task.rootTask let parentTask = task.parentTask // Mark this as a user-initiated cancellation so provider-only rehydration can occur task.setAbortReason("user_cancelled") // Capture the current instance to detect if rehydrate already occurred elsewhere const originalInstanceId = task.instanceId // Immediately cancel the underlying HTTP request if one is in progress // This ensures the stream fails quickly rather than waiting for network timeout task.cancelCurrentRequest() // Kick off abort (sets abort flag synchronously; stream exit and final saveClineMessages // happen asynchronously). We capture the promise so we can await its completion below — // this ensures task.initialStatus ("active") cannot overwrite "interrupted" after we // persist it (issue #560). const abortPromise = task.abortTask() // Immediately mark the original instance as abandoned to prevent any residual activity task.requestAbandon() await pWaitFor( () => this.getCurrentTask()! === undefined || this.getCurrentTask()!.isStreaming === false || this.getCurrentTask()!.didFinishAbortingStream || // If only the first chunk is processed, then there's no // need to wait for graceful abort (closes edits, browser, // etc). this.getCurrentTask()!.isWaitingForFirstChunk, { timeout: 3_000, }, ).catch(() => { console.error("Failed to abort task") }) // Wait for abortTask to fully settle (including its final saveClineMessages write) // before we persist "interrupted", so our write is always the last one. await abortPromise.catch(() => {}) // Defensive safeguard: if current instance already changed, skip rehydrate const current = this.getCurrentTask() if (current && current.instanceId !== originalInstanceId) { this.log( `[cancelTask] Skipping rehydrate: current instance ${current.instanceId} != original ${originalInstanceId}`, ) return } // Final race check before rehydrate to avoid duplicate rehydration { const currentAfterCheck = this.getCurrentTask() if (currentAfterCheck && currentAfterCheck.instanceId !== originalInstanceId) { this.log( `[cancelTask] Skipping rehydrate after final check: current instance ${currentAfterCheck.instanceId} != original ${originalInstanceId}`, ) return } } if (!historyItem) { return } if (task.parentTaskId) { try { await this.runDelegationTransition(task.parentTaskId, async () => { const { historyItem: parentHistory } = await this.getTaskWithId(task.parentTaskId!) if (parentHistory?.status === "delegated" && parentHistory?.awaitingChildId === task.taskId) { // Refresh the child after acquiring the parent transition lock. The pre-abort // history snapshot can be stale if another serialized path interrupted it. historyItem = this.taskHistoryStore.get(task.taskId) ?? (await this.getTaskWithId(task.taskId)).historyItem // Mark the child interrupted and leave parent delegated with awaitingChildId // intact — the user can resume this child later and it will report back. // A previous cancellation may already have persisted the interrupted status // before its caller lost the response. Treat that replay as success without // weakening the lifecycle state machine's self-loop rejection. if (historyItem!.status !== "interrupted") { historyItem = interruptDelegatedChild(parentHistory, historyItem!) await this.updateTaskHistory(historyItem) this.log( `[cancelTask] Marked child ${task.taskId} interrupted; parent ${task.parentTaskId} stays delegated`, ) } else { this.log( `[cancelTask] Child ${task.taskId} is already interrupted; parent ${task.parentTaskId} stays delegated`, ) } // Clear any stale fail-closed entry from a prior failed cancel attempt so // reopenParentFromDelegation is not incorrectly blocked on resume. this.cancelledDelegationChildIds.delete(task.taskId) } }) } catch (error) { // Fail closed: if we cannot persist the interrupted status, sever the link // so later completions don't reopen a stale delegated parent. parentTask = undefined rootTask = undefined this.cancelledDelegationChildIds.add(task.taskId) historyItem = { ...historyItem, parentTaskId: undefined, rootTaskId: undefined, } try { await this.updateTaskHistory(historyItem) } catch (historyError) { this.log( `[cancelTask] Failed to persist interrupted child state for ${task.taskId}: ${ historyError instanceof Error ? historyError.message : String(historyError) }`, ) throw historyError } this.log( `[cancelTask] Failed to mark child interrupted for ${task.taskId}: ${ error instanceof Error ? error.message : String(error) }`, ) } } // Clears task again, so we need to abortTask manually above. await this.createTaskWithHistoryItem({ ...historyItem, rootTask, parentTask }) } // Clear the current task without treating it as a subtask. // This is used when the user cancels a task that is not a subtask. public async clearTask(): Promise { const task = this.taskRegistry.current if (task) { console.log(`[clearTask] clearing task ${task.taskId}.${task.instanceId}`) await this.removeClineFromStack() } } public resumeTask(taskId: string): void { // Use the existing showTaskWithId method which handles both current and // historical tasks. this.showTaskWithId(taskId).catch((error) => { this.log(`Failed to resume task ${taskId}: ${error.message}`) }) } // Modes public async getModes(): Promise<{ slug: string; name: string }[]> { try { const customModes = await this.customModesManager.getCustomModes() return [...DEFAULT_MODES, ...customModes].map(({ slug, name }) => ({ slug, name })) } catch { return DEFAULT_MODES.map(({ slug, name }) => ({ slug, name })) } } public async getMode(): Promise { const { mode } = await this.getState() return mode } public async setMode(mode: string): Promise { await this.setValues({ mode }) } // Provider Profiles public async getProviderProfiles(): Promise<{ name: string; provider?: string }[]> { const { listApiConfigMeta = [] } = await this.getState() return listApiConfigMeta.map((profile) => ({ name: profile.name, provider: profile.apiProvider })) } public async getProviderProfile(): Promise { const { currentApiConfigName = "default" } = await this.getState() return currentApiConfigName } public async setProviderProfile(name: string): Promise { await this.activateProviderProfile({ name }) } // Telemetry private _appProperties?: StaticAppProperties private _gitProperties?: GitProperties private getAppProperties(): StaticAppProperties { if (!this._appProperties) { const packageJSON = this.context.extension?.packageJSON this._appProperties = { appName: packageJSON?.name ?? Package.name, appVersion: packageJSON?.version ?? Package.version, releaseChannel: Package.releaseChannel, vscodeVersion: vscode.version, platform: process.platform, editorName: vscode.env.appName, } } return this._appProperties } public get appProperties(): StaticAppProperties { return this._appProperties ?? this.getAppProperties() } private getCloudProperties(): CloudAppProperties { let cloudIsAuthenticated: boolean | undefined try { if (CloudService.hasInstance()) { cloudIsAuthenticated = CloudService.instance.isAuthenticated() } } catch (error) { // Silently handle errors to avoid breaking telemetry collection. this.log(`[getTelemetryProperties] Failed to get cloud auth state: ${error}`) } return { cloudIsAuthenticated, } } private async getTaskProperties(): Promise { const { language = "en", mode, apiConfiguration } = await this.getState() const task = this.getCurrentTask() const todoList = task?.todoList let todos: { total: number; completed: number; inProgress: number; pending: number } | undefined if (todoList && todoList.length > 0) { todos = { total: todoList.length, completed: todoList.filter((todo) => todo.status === "completed").length, inProgress: todoList.filter((todo) => todo.status === "in_progress").length, pending: todoList.filter((todo) => todo.status === "pending").length, } } const apiProvider = apiConfiguration?.apiProvider return { language, mode, taskId: task?.taskId, parentTaskId: task?.parentTaskId, apiProvider: apiProvider && !isRetiredProvider(apiProvider) ? apiProvider : undefined, modelId: task?.api?.getModel().id, diffStrategy: task?.diffStrategy?.getName(), isSubtask: task ? !!task.parentTaskId : undefined, ...(todos && { todos }), } } private async getGitProperties(): Promise { if (!this._gitProperties) { this._gitProperties = await getWorkspaceGitInfo() } return this._gitProperties } public get gitProperties(): GitProperties | undefined { return this._gitProperties } public async getTelemetryProperties(): Promise { return { ...this.getAppProperties(), ...this.getCloudProperties(), ...(await this.getTaskProperties()), ...(await this.getGitProperties()), } } /** Workspace explicitly associated with this provider, without an active-editor fallback. */ public get workspacePath(): string | undefined { return this.currentWorkspacePath } public get cwd() { return this.currentWorkspacePath || getWorkspacePath() } /** * Delegate parent task and open child task. * * - Enforce single-open invariant * - Persist parent delegation metadata * - Emit TaskDelegated (task-level; API forwards to provider/bridge) * - Create child as sole active and switch mode to child's mode */ public async delegateParentAndOpenChild(params: { parentTaskId: string message: string initialTodos: TodoItem[] mode: string pendingActionId?: string }): Promise { return runDelegationTransition(ClineProvider.delegationTransitionLocks, params.parentTaskId, () => ClineProvider.prototype.delegateParentAndOpenChildUnlocked.call(this, params), ) } private async delegateParentAndOpenChildUnlocked(params: { parentTaskId: string message: string initialTodos: TodoItem[] mode: string pendingActionId?: string }): Promise { const { parentTaskId, message, initialTodos, mode, pendingActionId } = params // Metadata-driven delegation is always enabled // 1) Get parent (must be current task) const parent = this.getCurrentTask() if (!parent) { throw new Error("[delegateParentAndOpenChild] No current task") } if (parent.taskId !== parentTaskId) { throw new Error( `[delegateParentAndOpenChild] Parent mismatch: expected ${parentTaskId}, current ${parent.taskId}`, ) } // A different provider may have delegated this parent while this call // waited on the shared lock. Refresh before mutating either task stack. await this.taskHistoryStore.invalidate(parentTaskId) const authoritativeParent = this.taskHistoryStore.get(parentTaskId) if (authoritativeParent?.status === "delegated") { const awaitedChildId = authoritativeParent.awaitingChildId if (!awaitedChildId) throw new Error("Cannot re-delegate a parent with no awaited child") await this.taskHistoryStore.invalidate(awaitedChildId) if (this.taskHistoryStore.get(awaitedChildId)?.status !== "interrupted") { throw new Error("Cannot re-delegate while the awaited child is not interrupted") } } if (pendingActionId) { const parentHistory = this.taskHistoryStore.get(parentTaskId) if (parentHistory?.pendingAction?.actionId !== pendingActionId) { throw new Error( `[delegateParentAndOpenChild] Pending action mismatch for parent ${parentTaskId}: expected ${pendingActionId}, found ${parentHistory?.pendingAction?.actionId}`, ) } } const parentExecutionContext: DelegatedChildContext = { mode, apiConfigName: await parent.getTaskApiConfigName(), apiConfiguration: structuredClone(parent.apiConfiguration), } const parentMode = await parent.getTaskMode() const lockApiConfigAcrossModes = mode !== parentMode && this.context.workspaceState.get("lockApiConfigAcrossModes", false) let savedModeProfile: { name?: string; apiConfiguration: ProviderSettings } | undefined if (mode !== parentMode && !lockApiConfigAcrossModes) { const savedConfigId = await this.getModeConfigId(mode as Mode) if (savedConfigId) { try { const { name, id: _id, ...savedConfiguration } = await this.providerSettingsManager.getProfile({ id: savedConfigId, }) savedModeProfile = { name, apiConfiguration: savedConfiguration } } catch (error) { this.log( `[delegateParentAndOpenChild] Saved profile ${savedConfigId} for mode '${mode}' could not be loaded for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}. Using the parent task configuration.`, ) } } } const handoffExecutionContext = selectHandoffExecutionContext( parentExecutionContext, mode, parentMode, lockApiConfigAcrossModes, savedModeProfile, ) // 2) Flush pending tool results to API history BEFORE disposing the parent. // This is critical: when tools are called before new_task, // their tool_result blocks are in userMessageContent but not yet saved to API history. // If we don't flush them, the parent's API conversation will be incomplete and // cause 400 errors when resumed (missing tool_result for tool_use blocks). // // NOTE: We do NOT pass the assistant message here because the assistant message // is already added to apiConversationHistory by the normal flow in // recursivelyMakeClineRequests BEFORE tools start executing. We only need to // flush the pending user message with tool_results. try { const flushSuccess = await parent.flushPendingToolResultsToHistory() if (!flushSuccess) { console.warn(`[delegateParentAndOpenChild] Flush failed for parent ${parentTaskId}, retrying...`) const retrySuccess = await parent.retrySaveApiConversationHistory() if (!retrySuccess) { console.error( `[delegateParentAndOpenChild] CRITICAL: Parent ${parentTaskId} API history not persisted to disk. Child return may produce stale state.`, ) vscode.window.showWarningMessage( "Warning: Parent task state could not be saved. The parent task may lose recent context when resumed.", ) } } } catch (error) { this.log( `[delegateParentAndOpenChild] Error flushing pending tool results (non-fatal): ${ error instanceof Error ? error.message : String(error) }`, ) } // 3) Enforce single-open invariant by closing/disposing the parent first // This ensures we never have >1 tasks open at any time during delegation. // Await abort completion to ensure clean disposal and prevent unhandled rejections. try { await this.removeClineFromStack() } catch (error) { this.log( `[delegateParentAndOpenChild] Error during parent disposal (non-fatal): ${ error instanceof Error ? error.message : String(error) }`, ) // Non-fatal: proceed with child creation even if parent cleanup had issues } // 4) Bind the child directly to the delegating task's local provider // context. Delegation never mutates shared profile/global state. // Create child as sole active (parent reference preserved for lineage) // Pass initialStatus: "active" to ensure the child task's historyItem is created // with status from the start, avoiding race conditions where the task might // call attempt_completion before status is persisted separately. // // Pass startTask: false to prevent the child from beginning its task loop // (and writing to globalState via saveClineMessages → updateTaskHistory) // before we persist the parent's delegation metadata in step 5. // Without this, the child's fire-and-forget startTask() races with step 5, // and the last writer to globalState overwrites the other's changes— // causing the parent's delegation fields to be lost. const child = await this.createTask(message, undefined, parent as any, { initialTodos, initialStatus: "active", startTask: false, handoffExecutionContext, }) // 5) Persist parent delegation metadata BEFORE the child starts writing. // atomicReadAndUpdate reads from the in-memory cache and writes back within a // single lock acquisition — no concurrent writer can slip between the read and // write, and the pure updater cannot re-enter the lock (no deadlock). // Broadcast and cache invalidation happen outside the lock after it releases. // // If the parent is already "delegated" to a previous interrupted child (the user // navigated back to the parent and continued working), we implicitly sever the old // link here (delegated → active → delegated) so no explicit Abandon step is needed. // The old awaited child's status is re-read INSIDE the updater (which runs // synchronously under the store lock) so a concurrent abandon or completion cannot // slip between the status snapshot and the write. An active child must never be // silently detached. try { await this.taskHistoryStore.atomicReadAndUpdate(parentTaskId, (historyItem) => { if (pendingActionId && historyItem.pendingAction?.actionId !== pendingActionId) { throw new Error( `[delegateParentAndOpenChild] Pending action mismatch for parent ${parentTaskId}: expected ${pendingActionId}, found ${historyItem.pendingAction?.actionId}`, ) } const awaitedChildStatus = historyItem.awaitingChildId ? this.taskHistoryStore.get(historyItem.awaitingChildId)?.status : undefined const delegated = delegateTaskToChild(historyItem, child.taskId, awaitedChildStatus) return { ...delegated, pendingAction: delegated.pendingAction?.actionId === pendingActionId ? undefined : delegated.pendingAction, } }) this.recentTasksCache = undefined if (this.isViewLaunched) { const updatedItem = this.taskHistoryStore.get(parentTaskId) if (updatedItem) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem }) } } } catch (err) { this.log( `[delegateParentAndOpenChild] Failed to persist parent metadata for ${parentTaskId} -> ${child.taskId}: ${ (err as Error)?.message ?? String(err) }`, ) // The authoritative parent record rejected this delegation (#1714). // Settle the matching pending create_subtask action durably through // the disk-authoritative compare-and-clear so a retry cannot replay // a rejected action and a replacement action from another host is // never cleared, then propagate the original error. let settlementFailed = false if (pendingActionId && err instanceof LifecycleTransitionError) { try { const authoritative = await this.taskHistoryStore.clearPendingActionIfMatching( parentTaskId, pendingActionId, ) settlementFailed = authoritative.pendingAction?.kind === "create_subtask" && authoritative.pendingAction.actionId === pendingActionId this.recentTasksCache = undefined } catch (settlementError) { settlementFailed = true this.log( `[delegateParentAndOpenChild] Failed to settle pending action ${pendingActionId} for parent ${parentTaskId}: ${ (settlementError as Error)?.message ?? String(settlementError) }`, ) } } try { // Only pop the stack if the child we just created is still on top. // A concurrent delegation could have pushed another child since we created ours. if (this.getCurrentTask()?.taskId === child.taskId) { await this.removeClineFromStack() } } catch (cleanupError) { this.log( `[delegateParentAndOpenChild] Failed to close paused child ${child.taskId} during rollback: ${ (cleanupError as Error)?.message ?? String(cleanupError) }`, ) } try { await this.deleteTaskWithId(child.taskId, false) } catch (cleanupError) { this.log( `[delegateParentAndOpenChild] Failed to delete paused child ${child.taskId} during rollback: ${ (cleanupError as Error)?.message ?? String(cleanupError) }`, ) } try { // A failed settlement write leaves the rejected pending action in // durable storage. Restoring the stored parent would replay it in // this process, so leave the parent unrestored. Restart recovery also // settles interrupted create-subtask actions before allowing replay. if (!settlementFailed) { const { historyItem: parentHistory } = await this.getTaskWithId(parentTaskId) await this.createTaskWithHistoryItem(parentHistory) } } catch (rollbackError) { this.log( `[delegateParentAndOpenChild] Failed to restore parent ${parentTaskId} during rollback: ${ (rollbackError as Error)?.message ?? String(rollbackError) }`, ) } throw err } // Stamp only committed delegations; rejected ones must not link to a rolled-back child. try { const globalStoragePath = this.contextProxy.globalStorageUri.fsPath const parentMessages = await readTaskMessages({ taskId: parentTaskId, globalStoragePath }) for (let messageIndex = parentMessages.length - 1; messageIndex >= 0; messageIndex--) { const candidate = parentMessages[messageIndex] if (candidate.ask !== "tool" || !candidate.text) continue let tool: { tool?: unknown; content?: unknown } | null try { tool = JSON.parse(candidate.text) as { tool?: unknown; content?: unknown } | null } catch { continue } if (tool?.tool !== "newTask") continue // Never walk past the newest delegation and stamp an earlier rejected ask. // startSubtask delegates without an ask, so the newest ask may belong to another delegation. // NewTaskTool shows the raw content but delegates with one level of "\\@" unescaped. const matchesDelegation = typeof tool.content === "string" && tool.content.replace(/\\\\@/g, "\\@") === message if (matchesDelegation && !candidate.childTaskId) { candidate.childTaskId = child.taskId await saveTaskMessages({ messages: parentMessages, taskId: parentTaskId, globalStoragePath, merge: true, }) } break } } catch (error) { this.log( `[delegateParentAndOpenChild] Failed to save child link for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}`, ) } // 6) Start the child task now that parent metadata is safely persisted. scheduleTask(this.taskScheduler, child, "delegateParentAndOpenChild") // 7) Emit TaskDelegated (provider-level) try { this.emit(RooCodeEventName.TaskDelegated, parentTaskId, child.taskId) } catch { // non-fatal } return child } /** * Reopen parent task from delegation with write-back and events. */ public async reopenParentFromDelegation(params: { parentTaskId: string childTaskId: string completionResultSummary: string pendingActionId?: string }): Promise { const { parentTaskId, childTaskId, completionResultSummary, pendingActionId } = params return this.runDelegationTransition(parentTaskId, async () => { const globalStoragePath = this.contextProxy.globalStorageUri.fsPath // 1) Load parent from history and current persisted messages const { historyItem } = await this.getTaskWithId(parentTaskId) const childHistory = this.taskHistoryStore.get(childTaskId) if (pendingActionId && childHistory?.pendingAction?.actionId !== pendingActionId) { this.log( `[reopenParentFromDelegation] Aborting: child ${childTaskId} pending action does not match ${pendingActionId}`, ) return false } // Guard: re-validate delegation state after the async approval gap. // cancelTask() or removeClineFromStack() may have already detached the parent // (setting status → "active", awaitingChildId → undefined) while the user was // approving the subtask finish. If the parent no longer awaits this child, // routing output back would corrupt an unrelated task. if ( this.cancelledDelegationChildIds.has(childTaskId) || (historyItem.status !== "delegated" && historyItem.status !== "active") || historyItem.awaitingChildId !== childTaskId ) { this.log( `[reopenParentFromDelegation] Aborting: parent ${parentTaskId} is no longer delegated to child ${childTaskId} ` + `(status=${historyItem.status}, awaitingChildId=${historyItem.awaitingChildId})`, ) return false } let parentClineMessages: ClineMessage[] = [] try { parentClineMessages = await readTaskMessages({ taskId: parentTaskId, globalStoragePath, }) } catch (error) { this.log( `[reopenParentFromDelegation] Failed to read messages for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}`, ) return false } let parentApiMessages: ApiMessage[] = [] try { parentApiMessages = await readApiMessages({ taskId: parentTaskId, globalStoragePath, }) } catch (error) { this.log( `[reopenParentFromDelegation] Failed to read API messages for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}`, ) return false } // 2) Inject synthetic records: UI subtask_result and update API tool_result const ts = Date.now() // Defensive: ensure arrays if (!Array.isArray(parentClineMessages)) parentClineMessages = [] if (!Array.isArray(parentApiMessages)) parentApiMessages = [] const subtaskUiMessage: ClineMessage = { messageId: crypto.randomUUID(), type: "say", say: "subtask_result", text: completionResultSummary, ts, childTaskId, } const lastParentClineMessage = parentClineMessages.at(-1) if ( lastParentClineMessage?.type !== "say" || lastParentClineMessage.say !== "subtask_result" || lastParentClineMessage.text !== completionResultSummary || (lastParentClineMessage.childTaskId !== undefined && lastParentClineMessage.childTaskId !== childTaskId) ) { parentClineMessages.push(subtaskUiMessage) } else { lastParentClineMessage.childTaskId = childTaskId } parentClineMessages = await saveTaskMessages({ messages: parentClineMessages, taskId: parentTaskId, globalStoragePath, merge: true, }) // Find the tool_use_id from the last assistant message's new_task tool_use let toolUseId: string | undefined for (let i = parentApiMessages.length - 1; i >= 0; i--) { const msg = parentApiMessages[i] if (msg.role === "assistant" && Array.isArray(msg.content)) { for (const block of msg.content) { if (block.type === "tool_use" && block.name === "new_task") { toolUseId = block.id break } } if (toolUseId) break } } // Preferred: if the parent history contains the native tool_use for new_task, // inject a matching tool_result for the Anthropic message contract: // user → assistant (tool_use) → user (tool_result) if (toolUseId) { // Check if the last message is already a user message with a tool_result for this tool_use_id // (in case this is a retry or the history was already updated) const lastMsg = parentApiMessages[parentApiMessages.length - 1] let alreadyHasToolResult = false if (lastMsg?.role === "user" && Array.isArray(lastMsg.content)) { for (const block of lastMsg.content) { if (block.type === "tool_result" && block.tool_use_id === toolUseId) { // Update the existing tool_result content block.content = `Subtask ${childTaskId} completed.\n\nResult:\n${completionResultSummary}` alreadyHasToolResult = true break } } } // If no existing tool_result found, create a NEW user message with the tool_result if (!alreadyHasToolResult) { parentApiMessages.push({ messageId: crypto.randomUUID(), role: "user", content: [ { type: "tool_result" as const, tool_use_id: toolUseId, content: `Subtask ${childTaskId} completed.\n\nResult:\n${completionResultSummary}`, }, ], ts, }) } // Validate the newly injected tool_result against the preceding assistant message. // This ensures the tool_result's tool_use_id matches a tool_use in the immediately // preceding assistant message (Anthropic API requirement). const lastMessage = parentApiMessages[parentApiMessages.length - 1] if (lastMessage?.role === "user") { const validatedMessage = validateAndFixToolResultIds(lastMessage, parentApiMessages.slice(0, -1)) parentApiMessages[parentApiMessages.length - 1] = validatedMessage } } else { // If there is no corresponding tool_use in the parent API history, we cannot emit a // tool_result. Fall back to a plain user text note so the parent can still resume. const fallbackText = `Subtask ${childTaskId} completed.\n\nResult:\n${completionResultSummary}` const lastParentApiMessage = parentApiMessages.at(-1) const alreadyHasFallback = lastParentApiMessage?.role === "user" && Array.isArray(lastParentApiMessage.content) && lastParentApiMessage.content.some( (block: { type?: string; text?: string }) => block.type === "text" && block.text === fallbackText, ) if (!alreadyHasFallback) { parentApiMessages.push({ messageId: crypto.randomUUID(), role: "user", content: [ { type: "text" as const, text: fallbackText, }, ], ts, }) } } parentApiMessages = await saveApiMessages({ messages: parentApiMessages, taskId: parentTaskId, globalStoragePath, merge: true, }) // 4) Close child instance if still open (single-open-task invariant). // This MUST happen BEFORE marking the child "completed" because // removeClineFromStack() → abortTask(true) → saveClineMessages() writes // the historyItem with initialStatus (typically "active"), which would // overwrite a "completed" status set later. const current = this.getCurrentTask() if (current?.taskId === childTaskId) { await this.removeClineFromStack() } // 3+5) Atomically mark child completed and parent active in one lock acquisition. // No intermediate state is ever persisted — no sentinel needed. // Build the parent update inside the updater from the locked snapshot so // any concurrent write that landed between step 1 and the lock acquisition // is preserved rather than silently overwritten. let updatedHistory!: typeof historyItem let completingChild!: HistoryItem await this.taskHistoryStore.atomicUpdatePair( childTaskId, parentTaskId, (child) => { if (pendingActionId && child.pendingAction?.actionId !== pendingActionId) { throw new Error(`[reopenParentFromDelegation] Pending action mismatch for child ${childTaskId}`) } completingChild = { ...child } const lifecycleUpdate = completeDelegatedChild(historyItem, child, completionResultSummary) return { ...lifecycleUpdate.child, pendingAction: child.pendingAction?.actionId === pendingActionId ? undefined : child.pendingAction, } }, (parent) => { const lifecycleUpdate = completeDelegatedChild(parent, completingChild, completionResultSummary) updatedHistory = lifecycleUpdate.parent return updatedHistory }, ) this.recentTasksCache = undefined // Notify the webview of both updated items so its in-memory history stays current. if (this.isViewLaunched) { const updatedChild = this.taskHistoryStore.get(childTaskId) const updatedParent = this.taskHistoryStore.get(parentTaskId) if (updatedChild) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedChild }) } if (updatedParent) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedParent }) } } // 6) Emit TaskDelegationCompleted (provider-level) try { this.emit(RooCodeEventName.TaskDelegationCompleted, parentTaskId, childTaskId, completionResultSummary) } catch { // non-fatal } // 7) Reopen the parent from history as the sole active task (restores saved mode) // IMPORTANT: startTask=false to suppress resume-from-history ask scheduling const parentInstance = await this.createTaskWithHistoryItem(updatedHistory, { startTask: false }) // 8) Inject restored histories into the in-memory instance before resuming if (parentInstance) { try { await parentInstance.overwriteClineMessages(parentClineMessages, false) } catch { // non-fatal } try { await parentInstance.overwriteApiConversationHistory(parentApiMessages, false) } catch { // non-fatal } let admitContinuation!: () => void const continuationAdmitted = new Promise((resolve) => { admitContinuation = resolve }) let schedulerAdmitted = false // Reserve the continuation's place in the shared parent queue before this // completion transition releases. Its body waits until scheduler admission, // so the completing child can release its permit without deadlocking. const continuation = this.runDelegationTransition(parentTaskId, async () => { await continuationAdmitted if (!schedulerAdmitted) return {} await this.taskHistoryStore.invalidate(parentTaskId) const persistedParent = this.taskHistoryStore.get(parentTaskId) const currentTask = this.getCurrentTask() if ( this.cancelledDelegationChildIds.has(childTaskId) || parentInstance.abort || parentInstance.abandoned || currentTask !== parentInstance || persistedParent?.status !== "active" || persistedParent.completedByChildId !== childTaskId || persistedParent.awaitingChildId !== undefined || persistedParent.delegatedToId !== undefined ) { this.log( `[reopenParentFromDelegation] Skipping stale parent continuation for ${parentTaskId} after child ${childTaskId}`, ) return {} } // Keep the run promise inside an object so the transition queue does not // assimilate it and retain the parent key for the full resumed task loop. return { runPromise: parentInstance.resumeAfterDelegation() } }) void this.taskScheduler .schedule(parentInstance, async () => { schedulerAdmitted = true admitContinuation() const { runPromise } = await continuation if (!runPromise) return try { await runPromise try { this.emit(RooCodeEventName.TaskDelegationResumed, parentTaskId, childTaskId) } catch { // non-fatal } } catch (error) { const message = `Failed to resume parent task ${parentTaskId} after subtask ${childTaskId}: ${error instanceof Error ? error.message : String(error)}` this.log(`[reopenParentFromDelegation] ${message}`) await vscode.window.showErrorMessage(`${message}. Open the task from history to retry.`) throw error } }) .then(admitContinuation, (error) => { admitContinuation() console.error( `[${ClineProvider.prototype.reopenParentFromDelegation.name}] taskScheduler.schedule failed:`, error, ) }) } this.cancelledDelegationChildIds.delete(childTaskId) return true }) } /** Emits completion after delegated child disposal through the provider-owned event channel. */ public emitDelegatedTaskCompleted(taskId: string, tokenUsage: TokenUsage, toolUsage: ToolUsage): void { this.emit(RooCodeEventName.TaskCompleted, taskId, tokenUsage, toolUsage) } /** * Explicitly sever a delegated parent-child link, e.g. when the user gives up on * an "interrupted" subtask instead of resuming it. Unlike removeClineFromStack()'s * automatic repair, this is user-initiated and works even while the child is * "interrupted" (which removeClineFromStack intentionally leaves alone so the child * can still resume and report back). Only interrupted children can be abandoned — a * still-running child must be cancelled first, so its link is never severed mid-stream. * * Parent transitions delegated → active (its normal "no longer awaiting a child" * state). The child's own status is left untouched (interrupted stays interrupted; * VALID_TRANSITIONS only allows interrupted → completed) — only its parent/root * links are cleared so a later resume-and-complete cannot reattach it. */ public async abandonSubtask(childTaskId: string): Promise { const { historyItem: childHistory } = await this.getTaskWithId(childTaskId) const parentTaskId = childHistory.parentTaskId if (!parentTaskId) { return false } // Only an interrupted (cancelled, not running) child may be abandoned. A still-running // child must be cancelled first — severing the link out from under a live stream would // orphan it silently instead of giving the user the normal cancel/resume flow. if (childHistory.status !== "interrupted") { this.log( `[abandonSubtask] Aborting: child ${childTaskId} is not interrupted (status=${childHistory.status})`, ) return false } return this.runDelegationTransition(parentTaskId, async () => { const { historyItem: parentHistory } = await this.getTaskWithId(parentTaskId) if (parentHistory?.status !== "delegated" || parentHistory?.awaitingChildId !== childTaskId) { this.log( `[abandonSubtask] Aborting: parent ${parentTaskId} is no longer delegated to child ${childTaskId} ` + `(status=${parentHistory?.status}, awaitingChildId=${parentHistory?.awaitingChildId})`, ) return false } // Re-check inside the lock: the child may have been resumed (and be streaming again, // or have completed) between the check above and acquiring the delegation transition lock. const freshChild = this.taskHistoryStore.get(childTaskId) if (freshChild?.status !== "interrupted") { this.log( `[abandonSubtask] Aborting: child ${childTaskId} is no longer interrupted (status=${freshChild?.status})`, ) return false } // Close the live child instance (if it's still the open task — the common case, // since an interrupted child is rehydrated onto the stack after cancelTask) BEFORE // clearing its persisted links. Task#saveClineMessages() rebuilds parentTaskId/ // rootTaskId from the live (readonly) Task fields on every save, so any save that // happens after we clear the persisted links — including abortTask's own final // save — would silently reattach the child to its old parent. const current = this.getCurrentTask() if (current?.taskId === childTaskId) { await this.removeClineFromStack() } await this.taskHistoryStore.atomicUpdatePair( childTaskId, parentTaskId, (child) => abandonDelegatedChild(parentHistory, child).child, (parent) => abandonDelegatedChild(parent, freshChild).parent, ) this.recentTasksCache = undefined // Guard against a stale in-flight resume/completion (e.g. a resume that was already // in progress when abandon was clicked) reattaching the child after the link above // was cleared. AttemptCompletionTool re-reads parent status from the persisted store, // not the live task's readonly parentTaskId field, so this is the authoritative gate. this.cancelledDelegationChildIds.add(childTaskId) if (this.isViewLaunched) { const updatedChild = this.taskHistoryStore.get(childTaskId) const updatedParent = this.taskHistoryStore.get(parentTaskId) if (updatedChild) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedChild }) } if (updatedParent) { await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedParent }) } } this.log(`[abandonSubtask] Severed link between parent ${parentTaskId} and child ${childTaskId}`) return true }) } /** * Convert a file path to a webview-accessible URI * This method safely converts file paths to URIs that can be loaded in the webview * * @param filePath - The absolute file path to convert * @returns The webview URI string, or the original file URI if conversion fails * @throws {Error} When webview is not available * @throws {TypeError} When file path is invalid */ public convertToWebviewUri(filePath: string): string { try { const fileUri = vscode.Uri.file(filePath) // Check if we have a webview available if (this.view?.webview) { const webviewUri = this.view.webview.asWebviewUri(fileUri) return webviewUri.toString() } // Specific error for no webview available const error = new Error("No webview available for URI conversion") console.error(error.message) // Fallback to file URI if no webview available return fileUri.toString() } catch (error) { // More specific error handling if (error instanceof TypeError) { console.error("Invalid file path provided for URI conversion:", error) } else { console.error("Failed to convert to webview URI:", error) } // Return file URI as fallback return vscode.Uri.file(filePath).toString() } } }