diff --git a/src/common.ts b/src/common.ts index 3f38f01a..15d3f30f 100644 --- a/src/common.ts +++ b/src/common.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode" import { migrateCustomInstructionsToGlobalRules, + migrateTaskHistoryToFile, migrateWelcomeViewCompleted, migrateWorkspaceToGlobalStorage, } from "./core/storage/state-migrations" @@ -40,6 +41,9 @@ export async function initialize(context: vscode.ExtensionContext): Promise { const startTime = Date.now() try { - // eslint-disable-next-line eslint-rules/no-direct-vscode-state-api - const taskHistory = (context.globalState.get("taskHistory") as HistoryItem[]) || [] + const taskHistory = await readTaskHistoryFromState(context) const existingTaskIds = new Set(taskHistory.map((task) => task.id)) const allStateKeys = context.workspaceState.keys() const pendingWarningKeys = allStateKeys.filter((key) => key.startsWith("pendingFileContextWarning_")) @@ -312,7 +311,7 @@ export class FileContextTracker { `FileContextTracker: Processed ${existingTaskIds.size} tasks, found ${pendingWarningKeys.length} pending warnings, ${orphanedPendingContextTasks.length} orphaned, deleted ${orphanedPendingContextTasks.length}, took ${duration}ms`, ) } catch (error) { - console.error("Error cleaning up orphaned file context warnings:", error) + console.error("[FileContextTracker] Error cleaning up orphaned file context warnings:", error) } } } diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index b567e107..b720d444 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -66,12 +66,15 @@ export class Controller { this.authService.restoreRefreshTokenAndRetrieveAuthInfo() }) .catch((error) => { - console.error("CRITICAL: Failed to initialize StateManager - extension may not function properly:", error) + console.error( + "[Controller] CRITICAL: Failed to initialize StateManager - extension may not function properly:", + error, + ) }) // Set up persistence error recovery this.stateManager.onPersistenceError = async ({ error }: PersistenceErrorEvent) => { - console.error("Cache persistence failed, recovering:", error) + console.error("[Controller] Cache persistence failed, recovering:", error) try { await this.stateManager.reInitialize() await this.postStateToWebview() @@ -80,7 +83,7 @@ export class Controller { message: "Saving settings to storage failed.", }) } catch (recoveryError) { - console.error("Cache recovery failed:", recoveryError) + console.error("[Controller] Cache recovery failed:", recoveryError) HostProvider.window.showMessage({ type: ShowMessageType.ERROR, message: "Failed to save settings. Please restart the extension.", diff --git a/src/core/storage/StateManager.ts b/src/core/storage/StateManager.ts index 315f999f..abb63521 100644 --- a/src/core/storage/StateManager.ts +++ b/src/core/storage/StateManager.ts @@ -1,5 +1,6 @@ import { ApiConfiguration, fireworksDefaultModelId } from "@shared/api" import type { ExtensionContext } from "vscode" +import { writeTaskHistoryToState } from "./disk" import { STATE_MANAGER_NOT_INITIALIZED } from "./error-messages" import { GlobalState, GlobalStateKey, LocalState, LocalStateKey, SecretKey, Secrets } from "./state-keys" import { readGlobalStateFromDisk, readSecretsFromDisk, readWorkspaceStateFromDisk } from "./utils/state-helpers" @@ -46,13 +47,13 @@ export class StateManager { const secrets = await readSecretsFromDisk(this.context) const workspaceState = await readWorkspaceStateFromDisk(this.context) - // Populate the caches with all extension state fields + // Populate the cache with all extension state and secrets fields // Use populate method to avoid triggering persistence during initialization this.populateCache(globalState, secrets, workspaceState) this.isInitialized = true } catch (error) { - console.error("Failed to initialize StateManager:", error) + console.error("[StateManager] Failed to initialize:", error) throw error } } @@ -550,11 +551,11 @@ export class StateManager { this.pendingWorkspaceState.clear() this.persistenceTimeout = null } catch (error) { - console.error("Failed to persist pending changes:", error) + console.error("[StateManager] Failed to persist pending changes:", error) this.persistenceTimeout = null // Call persistence error callback for error recovery - this.onPersistenceError?.({ error: error as Error }) + this.onPersistenceError?.({ error: error }) } }, this.PERSISTENCE_DELAY_MS) } @@ -566,12 +567,15 @@ export class StateManager { try { await Promise.all( Array.from(keys).map((key) => { - const value = this.globalStateCache[key] - return this.context.globalState.update(key, value) + if (key === "taskHistory") { + // Route task history persistence to file, not VS Code globalState + return writeTaskHistoryToState(this.context, this.globalStateCache[key]) + } + return this.context.globalState.update(key, this.globalStateCache[key]) }), ) } catch (error) { - console.error("Failed to persist global state batch:", error) + console.error("[StateManager] Failed to persist global state batch:", error) throw error } } diff --git a/src/core/storage/disk.ts b/src/core/storage/disk.ts index 3eb8d873..a40e2eb6 100644 --- a/src/core/storage/disk.ts +++ b/src/core/storage/disk.ts @@ -2,6 +2,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import { TaskMetadata } from "@core/context/context-tracking/ContextTrackerTypes" import { execa } from "@packages/execa" import { ClineMessage } from "@shared/ExtensionMessage" +import { HistoryItem } from "@shared/HistoryItem" import { fileExistsAtPath } from "@utils/fs" import fs from "fs/promises" import os from "os" @@ -180,3 +181,42 @@ export async function saveTaskMetadata(context: vscode.ExtensionContext, taskId: console.error("Failed to save task metadata:", error) } } + +export async function ensureStateDirectoryExists(context: vscode.ExtensionContext): Promise { + const stateDir = path.join(context.globalStorageUri.fsPath, "state") + await fs.mkdir(stateDir, { recursive: true }) + return stateDir +} + +export async function getTaskHistoryStateFilePath(context: vscode.ExtensionContext): Promise { + return path.join(await ensureStateDirectoryExists(context), "taskHistory.json") +} + +export async function taskHistoryStateFileExists(context: vscode.ExtensionContext): Promise { + const filePath = await getTaskHistoryStateFilePath(context) + return fileExistsAtPath(filePath) +} + +export async function readTaskHistoryFromState(context: vscode.ExtensionContext): Promise { + try { + const filePath = await getTaskHistoryStateFilePath(context) + if (await fileExistsAtPath(filePath)) { + return JSON.parse(await fs.readFile(filePath, "utf8")) + } + return [] + } catch (error) { + console.error("[Disk] Failed to read task history:", error) + throw error + } +} + +export async function writeTaskHistoryToState(context: vscode.ExtensionContext, items: HistoryItem[]): Promise { + try { + const filePath = await getTaskHistoryStateFilePath(context) + // Always create the file; if items is empty, write [] to ensure presence on first startup + await fs.writeFile(filePath, JSON.stringify(items)) + } catch (error) { + console.error("[Disk] Failed to write task history:", error) + throw error + } +} diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index 200c2c52..1e118109 100644 --- a/src/core/storage/state-migrations.ts +++ b/src/core/storage/state-migrations.ts @@ -1,7 +1,7 @@ import fs from "fs/promises" import path from "path" import * as vscode from "vscode" -import { ensureRulesDirectoryExists } from "./disk" +import { ensureRulesDirectoryExists, readTaskHistoryFromState, taskHistoryStateFileExists, writeTaskHistoryToState } from "./disk" import { StateManager } from "./StateManager" export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionContext) { @@ -66,6 +66,25 @@ export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionC } } +export async function migrateTaskHistoryToFile(context: vscode.ExtensionContext) { + try { + // If the old taskHistory vs code global state is undefined, do nothing + const vscodeGlobalStateTaskHistory = await context.globalState.get("taskHistory") + if (vscodeGlobalStateTaskHistory === undefined) { + return + } + // Read legacy from VS Code globalState, default to [] + console.log("[Storage Migration] taskHistory from vscode global state: ", vscodeGlobalStateTaskHistory) + // Always create the file, even when empty + await writeTaskHistoryToState(context, Array.isArray(vscodeGlobalStateTaskHistory) ? vscodeGlobalStateTaskHistory : []) + await context.globalState.update("taskHistory", undefined) + console.log("[Storage Migration] taskHistory file in new location: ", await readTaskHistoryFromState(context)) + console.log("[Storage Migration] old vscode global state: ", await context.globalState.get("taskHistory")) + } catch (error) { + console.error("[Storage Migration] Failed to migrate task history to file:", error) + } +} + export async function migrateMcpMarketplaceEnableSetting(mcpMarketplaceEnabledRaw: boolean | undefined): Promise { const config = vscode.workspace.getConfiguration("cline") const mcpMarketplaceEnabled = config.get("mcpMarketplace.enabled") diff --git a/src/core/storage/utils/state-helpers.ts b/src/core/storage/utils/state-helpers.ts index ebb50f7e..ae978c1b 100644 --- a/src/core/storage/utils/state-helpers.ts +++ b/src/core/storage/utils/state-helpers.ts @@ -11,6 +11,7 @@ import { McpMarketplaceCatalog } from "@/shared/mcp" import { Mode, OpenaiReasoningEffort } from "@/shared/storage/types" import { TelemetrySetting } from "@/shared/TelemetrySetting" import { UserInfo } from "@/shared/UserInfo" +import { readTaskHistoryFromState } from "../disk" import { GlobalState, LocalState, SecretKey, Secrets } from "../state-keys" export async function readSecretsFromDisk(context: ExtensionContext): Promise { @@ -142,303 +143,321 @@ export async function readWorkspaceStateFromDisk(context: ExtensionContext): Pro } export async function readGlobalStateFromDisk(context: ExtensionContext): Promise { - // Get all global state values - const strictPlanModeEnabled = context.globalState.get("strictPlanModeEnabled") as boolean | undefined - const useAutoCondense = context.globalState.get("useAutoCondense") as boolean | undefined - const isNewUser = context.globalState.get("isNewUser") as boolean | undefined - const welcomeViewCompleted = context.globalState.get("welcomeViewCompleted") as boolean | undefined - const awsRegion = context.globalState.get("awsRegion") as string | undefined - const awsUseCrossRegionInference = context.globalState.get("awsUseCrossRegionInference") as boolean | undefined - const awsBedrockUsePromptCache = context.globalState.get("awsBedrockUsePromptCache") as boolean | undefined - const awsBedrockEndpoint = context.globalState.get("awsBedrockEndpoint") as string | undefined - const awsProfile = context.globalState.get("awsProfile") as string | undefined - const awsUseProfile = context.globalState.get("awsUseProfile") as boolean | undefined - const awsAuthentication = context.globalState.get("awsAuthentication") as string | undefined - const vertexProjectId = context.globalState.get("vertexProjectId") as string | undefined - const vertexRegion = context.globalState.get("vertexRegion") as string | undefined - const openAiBaseUrl = context.globalState.get("openAiBaseUrl") as string | undefined - const requestyBaseUrl = context.globalState.get("requestyBaseUrl") as string | undefined - const openAiHeaders = context.globalState.get("openAiHeaders") as Record | undefined - const ollamaBaseUrl = context.globalState.get("ollamaBaseUrl") as string | undefined - const ollamaApiOptionsCtxNum = context.globalState.get("ollamaApiOptionsCtxNum") as string | undefined - const lmStudioBaseUrl = context.globalState.get("lmStudioBaseUrl") as string | undefined - const lmStudioMaxTokens = context.globalState.get("lmStudioMaxTokens") as string | undefined - const anthropicBaseUrl = context.globalState.get("anthropicBaseUrl") as string | undefined - const geminiBaseUrl = context.globalState.get("geminiBaseUrl") as string | undefined - const azureApiVersion = context.globalState.get("azureApiVersion") as string | undefined - const openRouterProviderSorting = context.globalState.get("openRouterProviderSorting") as string | undefined - const lastShownAnnouncementId = context.globalState.get("lastShownAnnouncementId") as string | undefined - const taskHistory = context.globalState.get("taskHistory") as HistoryItem[] | undefined - const autoApprovalSettings = context.globalState.get("autoApprovalSettings") as AutoApprovalSettings | undefined - const browserSettings = context.globalState.get("browserSettings") as BrowserSettings | undefined - const liteLlmBaseUrl = context.globalState.get("liteLlmBaseUrl") as string | undefined - const liteLlmUsePromptCache = context.globalState.get("liteLlmUsePromptCache") as boolean | undefined - const fireworksModelMaxCompletionTokens = context.globalState.get("fireworksModelMaxCompletionTokens") as number | undefined - const fireworksModelMaxTokens = context.globalState.get("fireworksModelMaxTokens") as number | undefined - const userInfo = context.globalState.get("userInfo") as UserInfo | undefined - const qwenApiLine = context.globalState.get("qwenApiLine") as string | undefined - const moonshotApiLine = context.globalState.get("moonshotApiLine") as string | undefined - const zaiApiLine = context.globalState.get("zaiApiLine") as string | undefined - const telemetrySetting = context.globalState.get("telemetrySetting") as TelemetrySetting | undefined - const asksageApiUrl = context.globalState.get("asksageApiUrl") as string | undefined - const planActSeparateModelsSettingRaw = context.globalState.get("planActSeparateModelsSetting") as boolean | undefined - const favoritedModelIds = context.globalState.get("favoritedModelIds") as string[] | undefined - const globalClineRulesToggles = context.globalState.get("globalClineRulesToggles") as ClineRulesToggles | undefined - const requestTimeoutMs = context.globalState.get("requestTimeoutMs") as number | undefined - const shellIntegrationTimeout = context.globalState.get("shellIntegrationTimeout") as number | undefined - const enableCheckpointsSettingRaw = context.globalState.get("enableCheckpointsSetting") as boolean | undefined - const mcpMarketplaceEnabledRaw = context.globalState.get("mcpMarketplaceEnabled") as boolean | undefined - const mcpDisplayMode = context.globalState.get("mcpDisplayMode") as McpDisplayMode | undefined - const mcpResponsesCollapsedRaw = context.globalState.get("mcpResponsesCollapsed") as boolean | undefined - const globalWorkflowToggles = context.globalState.get("globalWorkflowToggles") as ClineRulesToggles | undefined - const terminalReuseEnabled = context.globalState.get("terminalReuseEnabled") as boolean | undefined - const terminalOutputLineLimit = context.globalState.get("terminalOutputLineLimit") as number | undefined - const defaultTerminalProfile = context.globalState.get("defaultTerminalProfile") as string | undefined - const sapAiCoreBaseUrl = context.globalState.get("sapAiCoreBaseUrl") as string | undefined - const sapAiCoreTokenUrl = context.globalState.get("sapAiCoreTokenUrl") as string | undefined - const sapAiResourceGroup = context.globalState.get("sapAiResourceGroup") as string | undefined - const claudeCodePath = context.globalState.get("claudeCodePath") as string | undefined - const difyBaseUrl = context.globalState.get("difyBaseUrl") as string | undefined - const openaiReasoningEffort = context.globalState.get("openaiReasoningEffort") as OpenaiReasoningEffort | undefined - const preferredLanguage = context.globalState.get("preferredLanguage") as string | undefined - const focusChainSettings = context.globalState.get("focusChainSettings") as FocusChainSettings | undefined - const focusChainFeatureFlagEnabled = context.globalState.get("focusChainFeatureFlagEnabled") as boolean | undefined + try { + // Get all global state values + const strictPlanModeEnabled = context.globalState.get("strictPlanModeEnabled") as boolean | undefined + const useAutoCondense = context.globalState.get("useAutoCondense") as boolean | undefined + const isNewUser = context.globalState.get("isNewUser") as boolean | undefined + const welcomeViewCompleted = context.globalState.get("welcomeViewCompleted") as boolean | undefined + const awsRegion = context.globalState.get("awsRegion") as string | undefined + const awsUseCrossRegionInference = context.globalState.get("awsUseCrossRegionInference") as boolean | undefined + const awsBedrockUsePromptCache = context.globalState.get("awsBedrockUsePromptCache") as boolean | undefined + const awsBedrockEndpoint = context.globalState.get("awsBedrockEndpoint") as string | undefined + const awsProfile = context.globalState.get("awsProfile") as string | undefined + const awsUseProfile = context.globalState.get("awsUseProfile") as boolean | undefined + const awsAuthentication = context.globalState.get("awsAuthentication") as string | undefined + const vertexProjectId = context.globalState.get("vertexProjectId") as string | undefined + const vertexRegion = context.globalState.get("vertexRegion") as string | undefined + const openAiBaseUrl = context.globalState.get("openAiBaseUrl") as string | undefined + const requestyBaseUrl = context.globalState.get("requestyBaseUrl") as string | undefined + const openAiHeaders = context.globalState.get("openAiHeaders") as Record | undefined + const ollamaBaseUrl = context.globalState.get("ollamaBaseUrl") as string | undefined + const ollamaApiOptionsCtxNum = context.globalState.get("ollamaApiOptionsCtxNum") as string | undefined + const lmStudioBaseUrl = context.globalState.get("lmStudioBaseUrl") as string | undefined + const lmStudioMaxTokens = context.globalState.get("lmStudioMaxTokens") as string | undefined + const anthropicBaseUrl = context.globalState.get("anthropicBaseUrl") as string | undefined + const geminiBaseUrl = context.globalState.get("geminiBaseUrl") as string | undefined + const azureApiVersion = context.globalState.get("azureApiVersion") as string | undefined + const openRouterProviderSorting = context.globalState.get("openRouterProviderSorting") as string | undefined + const lastShownAnnouncementId = context.globalState.get("lastShownAnnouncementId") as string | undefined + const autoApprovalSettings = context.globalState.get("autoApprovalSettings") as AutoApprovalSettings | undefined + const browserSettings = context.globalState.get("browserSettings") as BrowserSettings | undefined + const liteLlmBaseUrl = context.globalState.get("liteLlmBaseUrl") as string | undefined + const liteLlmUsePromptCache = context.globalState.get("liteLlmUsePromptCache") as boolean | undefined + const fireworksModelMaxCompletionTokens = context.globalState.get("fireworksModelMaxCompletionTokens") as + | number + | undefined + const fireworksModelMaxTokens = context.globalState.get("fireworksModelMaxTokens") as number | undefined + const userInfo = context.globalState.get("userInfo") as UserInfo | undefined + const qwenApiLine = context.globalState.get("qwenApiLine") as string | undefined + const moonshotApiLine = context.globalState.get("moonshotApiLine") as string | undefined + const zaiApiLine = context.globalState.get("zaiApiLine") as string | undefined + const telemetrySetting = context.globalState.get("telemetrySetting") as TelemetrySetting | undefined + const asksageApiUrl = context.globalState.get("asksageApiUrl") as string | undefined + const planActSeparateModelsSettingRaw = context.globalState.get("planActSeparateModelsSetting") as boolean | undefined + const favoritedModelIds = context.globalState.get("favoritedModelIds") as string[] | undefined + const globalClineRulesToggles = context.globalState.get("globalClineRulesToggles") as ClineRulesToggles | undefined + const requestTimeoutMs = context.globalState.get("requestTimeoutMs") as number | undefined + const shellIntegrationTimeout = context.globalState.get("shellIntegrationTimeout") as number | undefined + const enableCheckpointsSettingRaw = context.globalState.get("enableCheckpointsSetting") as boolean | undefined + const mcpMarketplaceEnabledRaw = context.globalState.get("mcpMarketplaceEnabled") as boolean | undefined + const mcpDisplayMode = context.globalState.get("mcpDisplayMode") as McpDisplayMode | undefined + const mcpResponsesCollapsedRaw = context.globalState.get("mcpResponsesCollapsed") as boolean | undefined + const globalWorkflowToggles = context.globalState.get("globalWorkflowToggles") as ClineRulesToggles | undefined + const terminalReuseEnabled = context.globalState.get("terminalReuseEnabled") as boolean | undefined + const terminalOutputLineLimit = context.globalState.get("terminalOutputLineLimit") as number | undefined + const defaultTerminalProfile = context.globalState.get("defaultTerminalProfile") as string | undefined + const sapAiCoreBaseUrl = context.globalState.get("sapAiCoreBaseUrl") as string | undefined + const sapAiCoreTokenUrl = context.globalState.get("sapAiCoreTokenUrl") as string | undefined + const sapAiResourceGroup = context.globalState.get("sapAiResourceGroup") as string | undefined + const claudeCodePath = context.globalState.get("claudeCodePath") as string | undefined + const difyBaseUrl = context.globalState.get("difyBaseUrl") as string | undefined + const openaiReasoningEffort = context.globalState.get("openaiReasoningEffort") as OpenaiReasoningEffort | undefined + const preferredLanguage = context.globalState.get("preferredLanguage") as string | undefined + const focusChainSettings = context.globalState.get("focusChainSettings") as FocusChainSettings | undefined + const focusChainFeatureFlagEnabled = context.globalState.get("focusChainFeatureFlagEnabled") as boolean | undefined - const mcpMarketplaceCatalog = context.globalState.get("mcpMarketplaceCatalog") as GlobalState["mcpMarketplaceCatalog"] - const qwenCodeOauthPath = context.globalState.get("qwenCodeOauthPath") as GlobalState["qwenCodeOauthPath"] - const customPrompt = context.globalState.get("customPrompt") as GlobalState["customPrompt"] + const mcpMarketplaceCatalog = context.globalState.get("mcpMarketplaceCatalog") as GlobalState["mcpMarketplaceCatalog"] + const qwenCodeOauthPath = context.globalState.get("qwenCodeOauthPath") as GlobalState["qwenCodeOauthPath"] + const customPrompt = context.globalState.get("customPrompt") as GlobalState["customPrompt"] - // Get mode-related configurations - const mode = context.globalState.get("mode") as Mode | undefined + // Get mode-related configurations + const mode = context.globalState.get("mode") as Mode | undefined - // Plan mode configurations - const planModeApiProvider = context.globalState.get("planModeApiProvider") as ApiProvider | undefined - const planModeApiModelId = context.globalState.get("planModeApiModelId") as string | undefined - const planModeThinkingBudgetTokens = context.globalState.get("planModeThinkingBudgetTokens") as number | undefined - const planModeReasoningEffort = context.globalState.get("planModeReasoningEffort") as string | undefined - const planModeVsCodeLmModelSelector = context.globalState.get("planModeVsCodeLmModelSelector") as - | LanguageModelChatSelector - | undefined - const planModeAwsBedrockCustomSelected = context.globalState.get("planModeAwsBedrockCustomSelected") as boolean | undefined - const planModeAwsBedrockCustomModelBaseId = context.globalState.get("planModeAwsBedrockCustomModelBaseId") as - | BedrockModelId - | undefined - const planModeOpenRouterModelId = context.globalState.get("planModeOpenRouterModelId") as string | undefined - const planModeOpenRouterModelInfo = context.globalState.get("planModeOpenRouterModelInfo") as ModelInfo | undefined - const planModeOpenAiModelId = context.globalState.get("planModeOpenAiModelId") as string | undefined - const planModeOpenAiModelInfo = context.globalState.get("planModeOpenAiModelInfo") as ModelInfo | undefined - const planModeOllamaModelId = context.globalState.get("planModeOllamaModelId") as string | undefined - const planModeLmStudioModelId = context.globalState.get("planModeLmStudioModelId") as string | undefined - const planModeLiteLlmModelId = context.globalState.get("planModeLiteLlmModelId") as string | undefined - const planModeLiteLlmModelInfo = context.globalState.get("planModeLiteLlmModelInfo") as ModelInfo | undefined - const planModeRequestyModelId = context.globalState.get("planModeRequestyModelId") as string | undefined - const planModeRequestyModelInfo = context.globalState.get("planModeRequestyModelInfo") as ModelInfo | undefined - const planModeTogetherModelId = context.globalState.get("planModeTogetherModelId") as string | undefined - const planModeFireworksModelId = context.globalState.get("planModeFireworksModelId") as string | undefined - const planModeSapAiCoreModelId = context.globalState.get("planModeSapAiCoreModelId") as string | undefined - const planModeGroqModelId = context.globalState.get("planModeGroqModelId") as string | undefined - const planModeGroqModelInfo = context.globalState.get("planModeGroqModelInfo") as ModelInfo | undefined - const planModeHuggingFaceModelId = context.globalState.get("planModeHuggingFaceModelId") as string | undefined - const planModeHuggingFaceModelInfo = context.globalState.get("planModeHuggingFaceModelInfo") as ModelInfo | undefined - const planModeHuaweiCloudMaasModelId = context.globalState.get("planModeHuaweiCloudMaasModelId") as string | undefined - const planModeHuaweiCloudMaasModelInfo = context.globalState.get("planModeHuaweiCloudMaasModelInfo") as ModelInfo | undefined - const planModeBasetenModelId = context.globalState.get("planModeBasetenModelId") as string | undefined - const planModeBasetenModelInfo = context.globalState.get("planModeBasetenModelInfo") as ModelInfo | undefined - const planModeVercelAiGatewayModelId = context.globalState.get("planModeVercelAiGatewayModelId") as string | undefined - const planModeVercelAiGatewayModelInfo = context.globalState.get("planModeVercelAiGatewayModelInfo") as ModelInfo | undefined - // Act mode configurations - const actModeApiProvider = context.globalState.get("actModeApiProvider") as ApiProvider | undefined - const actModeApiModelId = context.globalState.get("actModeApiModelId") as string | undefined - const actModeThinkingBudgetTokens = context.globalState.get("actModeThinkingBudgetTokens") as number | undefined - const actModeReasoningEffort = context.globalState.get("actModeReasoningEffort") as string | undefined - const actModeVsCodeLmModelSelector = context.globalState.get("actModeVsCodeLmModelSelector") as - | LanguageModelChatSelector - | undefined - const actModeAwsBedrockCustomSelected = context.globalState.get("actModeAwsBedrockCustomSelected") as boolean | undefined - const actModeAwsBedrockCustomModelBaseId = context.globalState.get("actModeAwsBedrockCustomModelBaseId") as - | BedrockModelId - | undefined - const actModeOpenRouterModelId = context.globalState.get("actModeOpenRouterModelId") as string | undefined - const actModeOpenRouterModelInfo = context.globalState.get("actModeOpenRouterModelInfo") as ModelInfo | undefined - const actModeOpenAiModelId = context.globalState.get("actModeOpenAiModelId") as string | undefined - const actModeOpenAiModelInfo = context.globalState.get("actModeOpenAiModelInfo") as ModelInfo | undefined - const actModeOllamaModelId = context.globalState.get("actModeOllamaModelId") as string | undefined - const actModeLmStudioModelId = context.globalState.get("actModeLmStudioModelId") as string | undefined - const actModeLiteLlmModelId = context.globalState.get("actModeLiteLlmModelId") as string | undefined - const actModeLiteLlmModelInfo = context.globalState.get("actModeLiteLlmModelInfo") as ModelInfo | undefined - const actModeRequestyModelId = context.globalState.get("actModeRequestyModelId") as string | undefined - const actModeRequestyModelInfo = context.globalState.get("actModeRequestyModelInfo") as ModelInfo | undefined - const actModeTogetherModelId = context.globalState.get("actModeTogetherModelId") as string | undefined - const actModeFireworksModelId = context.globalState.get("actModeFireworksModelId") as string | undefined - const actModeSapAiCoreModelId = context.globalState.get("actModeSapAiCoreModelId") as string | undefined - const actModeGroqModelId = context.globalState.get("actModeGroqModelId") as string | undefined - const actModeGroqModelInfo = context.globalState.get("actModeGroqModelInfo") as ModelInfo | undefined - const actModeHuggingFaceModelId = context.globalState.get("actModeHuggingFaceModelId") as string | undefined - const actModeHuggingFaceModelInfo = context.globalState.get("actModeHuggingFaceModelInfo") as ModelInfo | undefined - const actModeHuaweiCloudMaasModelId = context.globalState.get("actModeHuaweiCloudMaasModelId") as string | undefined - const actModeHuaweiCloudMaasModelInfo = context.globalState.get("actModeHuaweiCloudMaasModelInfo") as ModelInfo | undefined - const actModeBasetenModelId = context.globalState.get("actModeBasetenModelId") as string | undefined - const actModeBasetenModelInfo = context.globalState.get("actModeBasetenModelInfo") as ModelInfo | undefined - const actModeVercelAiGatewayModelId = context.globalState.get("actModeVercelAiGatewayModelId") as string | undefined - const actModeVercelAiGatewayModelInfo = context.globalState.get("actModeVercelAiGatewayModelInfo") as ModelInfo | undefined - const sapAiCoreUseOrchestrationMode = context.globalState.get("sapAiCoreUseOrchestrationMode") as boolean | undefined - - let apiProvider: ApiProvider - if (planModeApiProvider) { - apiProvider = planModeApiProvider - } else { - // New users should default to openrouter, since they've opted to use an API key instead of signing in - apiProvider = "openrouter" - } - - const mcpResponsesCollapsed = mcpResponsesCollapsedRaw ?? false - - // Plan/Act separate models setting is a boolean indicating whether the user wants to use different models for plan and act. Existing users expect this to be enabled, while we want new users to opt in to this being disabled by default. - // On win11 state sometimes initializes as empty string instead of undefined - let planActSeparateModelsSetting: boolean | undefined - if (planActSeparateModelsSettingRaw === true || planActSeparateModelsSettingRaw === false) { - planActSeparateModelsSetting = planActSeparateModelsSettingRaw - } else { - // default to true for existing users - if (planModeApiProvider) { - planActSeparateModelsSetting = true - } else { - // default to false for new users - planActSeparateModelsSetting = false - } - } - - return { - // api configuration fields - claudeCodePath, - awsRegion, - awsUseCrossRegionInference, - awsBedrockUsePromptCache, - awsBedrockEndpoint, - awsProfile, - awsUseProfile, - awsAuthentication, - vertexProjectId, - vertexRegion, - openAiBaseUrl, - requestyBaseUrl, - openAiHeaders: openAiHeaders || {}, - ollamaBaseUrl, - ollamaApiOptionsCtxNum, - lmStudioBaseUrl, - lmStudioMaxTokens, - anthropicBaseUrl, - geminiBaseUrl, - qwenApiLine, - moonshotApiLine, - zaiApiLine, - azureApiVersion, - openRouterProviderSorting, - liteLlmBaseUrl, - liteLlmUsePromptCache, - fireworksModelMaxCompletionTokens, - fireworksModelMaxTokens, - asksageApiUrl, - favoritedModelIds, - requestTimeoutMs, - sapAiCoreBaseUrl, - sapAiCoreTokenUrl, - sapAiResourceGroup, - difyBaseUrl, - sapAiCoreUseOrchestrationMode, // Plan mode configurations - planModeApiProvider: planModeApiProvider || apiProvider, - planModeApiModelId, - planModeThinkingBudgetTokens, - planModeReasoningEffort, - planModeVsCodeLmModelSelector, - planModeAwsBedrockCustomSelected, - planModeAwsBedrockCustomModelBaseId, - planModeOpenRouterModelId, - planModeOpenRouterModelInfo, - planModeOpenAiModelId, - planModeOpenAiModelInfo, - planModeOllamaModelId, - planModeLmStudioModelId, - planModeLiteLlmModelId, - planModeLiteLlmModelInfo, - planModeRequestyModelId, - planModeRequestyModelInfo, - planModeTogetherModelId, - planModeFireworksModelId, - planModeSapAiCoreModelId, - planModeGroqModelId, - planModeGroqModelInfo, - planModeHuggingFaceModelId, - planModeHuggingFaceModelInfo, - planModeHuaweiCloudMaasModelId, - planModeHuaweiCloudMaasModelInfo, - planModeBasetenModelId, - planModeBasetenModelInfo, - planModeVercelAiGatewayModelId, - planModeVercelAiGatewayModelInfo, + const planModeApiProvider = context.globalState.get("planModeApiProvider") as ApiProvider | undefined + const planModeApiModelId = context.globalState.get("planModeApiModelId") as string | undefined + const planModeThinkingBudgetTokens = context.globalState.get("planModeThinkingBudgetTokens") as number | undefined + const planModeReasoningEffort = context.globalState.get("planModeReasoningEffort") as string | undefined + const planModeVsCodeLmModelSelector = context.globalState.get("planModeVsCodeLmModelSelector") as + | LanguageModelChatSelector + | undefined + const planModeAwsBedrockCustomSelected = context.globalState.get("planModeAwsBedrockCustomSelected") as + | boolean + | undefined + const planModeAwsBedrockCustomModelBaseId = context.globalState.get("planModeAwsBedrockCustomModelBaseId") as + | BedrockModelId + | undefined + const planModeOpenRouterModelId = context.globalState.get("planModeOpenRouterModelId") as string | undefined + const planModeOpenRouterModelInfo = context.globalState.get("planModeOpenRouterModelInfo") as ModelInfo | undefined + const planModeOpenAiModelId = context.globalState.get("planModeOpenAiModelId") as string | undefined + const planModeOpenAiModelInfo = context.globalState.get("planModeOpenAiModelInfo") as ModelInfo | undefined + const planModeOllamaModelId = context.globalState.get("planModeOllamaModelId") as string | undefined + const planModeLmStudioModelId = context.globalState.get("planModeLmStudioModelId") as string | undefined + const planModeLiteLlmModelId = context.globalState.get("planModeLiteLlmModelId") as string | undefined + const planModeLiteLlmModelInfo = context.globalState.get("planModeLiteLlmModelInfo") as ModelInfo | undefined + const planModeRequestyModelId = context.globalState.get("planModeRequestyModelId") as string | undefined + const planModeRequestyModelInfo = context.globalState.get("planModeRequestyModelInfo") as ModelInfo | undefined + const planModeTogetherModelId = context.globalState.get("planModeTogetherModelId") as string | undefined + const planModeFireworksModelId = context.globalState.get("planModeFireworksModelId") as string | undefined + const planModeSapAiCoreModelId = context.globalState.get("planModeSapAiCoreModelId") as string | undefined + const planModeGroqModelId = context.globalState.get("planModeGroqModelId") as string | undefined + const planModeGroqModelInfo = context.globalState.get("planModeGroqModelInfo") as ModelInfo | undefined + const planModeHuggingFaceModelId = context.globalState.get("planModeHuggingFaceModelId") as string | undefined + const planModeHuggingFaceModelInfo = context.globalState.get("planModeHuggingFaceModelInfo") as ModelInfo | undefined + const planModeHuaweiCloudMaasModelId = context.globalState.get("planModeHuaweiCloudMaasModelId") as string | undefined + const planModeHuaweiCloudMaasModelInfo = context.globalState.get("planModeHuaweiCloudMaasModelInfo") as + | ModelInfo + | undefined + const planModeBasetenModelId = context.globalState.get("planModeBasetenModelId") as string | undefined + const planModeBasetenModelInfo = context.globalState.get("planModeBasetenModelInfo") as ModelInfo | undefined + const planModeVercelAiGatewayModelId = context.globalState.get("planModeVercelAiGatewayModelId") as string | undefined + const planModeVercelAiGatewayModelInfo = context.globalState.get("planModeVercelAiGatewayModelInfo") as + | ModelInfo + | undefined // Act mode configurations - actModeApiProvider: actModeApiProvider || apiProvider, - actModeApiModelId, - actModeThinkingBudgetTokens, - actModeReasoningEffort, - actModeVsCodeLmModelSelector, - actModeAwsBedrockCustomSelected, - actModeAwsBedrockCustomModelBaseId, - actModeOpenRouterModelId, - actModeOpenRouterModelInfo, - actModeOpenAiModelId, - actModeOpenAiModelInfo, - actModeOllamaModelId, - actModeLmStudioModelId, - actModeLiteLlmModelId, - actModeLiteLlmModelInfo, - actModeRequestyModelId, - actModeRequestyModelInfo, - actModeTogetherModelId, - actModeFireworksModelId, - actModeSapAiCoreModelId, - actModeGroqModelId, - actModeGroqModelInfo, - actModeHuggingFaceModelId, - actModeHuggingFaceModelInfo, - actModeHuaweiCloudMaasModelId, - actModeHuaweiCloudMaasModelInfo, - actModeBasetenModelId, - actModeBasetenModelInfo, - actModeVercelAiGatewayModelId, - actModeVercelAiGatewayModelInfo, + const actModeApiProvider = context.globalState.get("actModeApiProvider") as ApiProvider | undefined + const actModeApiModelId = context.globalState.get("actModeApiModelId") as string | undefined + const actModeThinkingBudgetTokens = context.globalState.get("actModeThinkingBudgetTokens") as number | undefined + const actModeReasoningEffort = context.globalState.get("actModeReasoningEffort") as string | undefined + const actModeVsCodeLmModelSelector = context.globalState.get("actModeVsCodeLmModelSelector") as + | LanguageModelChatSelector + | undefined + const actModeAwsBedrockCustomSelected = context.globalState.get("actModeAwsBedrockCustomSelected") as boolean | undefined + const actModeAwsBedrockCustomModelBaseId = context.globalState.get("actModeAwsBedrockCustomModelBaseId") as + | BedrockModelId + | undefined + const actModeOpenRouterModelId = context.globalState.get("actModeOpenRouterModelId") as string | undefined + const actModeOpenRouterModelInfo = context.globalState.get("actModeOpenRouterModelInfo") as ModelInfo | undefined + const actModeOpenAiModelId = context.globalState.get("actModeOpenAiModelId") as string | undefined + const actModeOpenAiModelInfo = context.globalState.get("actModeOpenAiModelInfo") as ModelInfo | undefined + const actModeOllamaModelId = context.globalState.get("actModeOllamaModelId") as string | undefined + const actModeLmStudioModelId = context.globalState.get("actModeLmStudioModelId") as string | undefined + const actModeLiteLlmModelId = context.globalState.get("actModeLiteLlmModelId") as string | undefined + const actModeLiteLlmModelInfo = context.globalState.get("actModeLiteLlmModelInfo") as ModelInfo | undefined + const actModeRequestyModelId = context.globalState.get("actModeRequestyModelId") as string | undefined + const actModeRequestyModelInfo = context.globalState.get("actModeRequestyModelInfo") as ModelInfo | undefined + const actModeTogetherModelId = context.globalState.get("actModeTogetherModelId") as string | undefined + const actModeFireworksModelId = context.globalState.get("actModeFireworksModelId") as string | undefined + const actModeSapAiCoreModelId = context.globalState.get("actModeSapAiCoreModelId") as string | undefined + const actModeGroqModelId = context.globalState.get("actModeGroqModelId") as string | undefined + const actModeGroqModelInfo = context.globalState.get("actModeGroqModelInfo") as ModelInfo | undefined + const actModeHuggingFaceModelId = context.globalState.get("actModeHuggingFaceModelId") as string | undefined + const actModeHuggingFaceModelInfo = context.globalState.get("actModeHuggingFaceModelInfo") as ModelInfo | undefined + const actModeHuaweiCloudMaasModelId = context.globalState.get("actModeHuaweiCloudMaasModelId") as string | undefined + const actModeHuaweiCloudMaasModelInfo = context.globalState.get("actModeHuaweiCloudMaasModelInfo") as + | ModelInfo + | undefined + const actModeBasetenModelId = context.globalState.get("actModeBasetenModelId") as string | undefined + const actModeBasetenModelInfo = context.globalState.get("actModeBasetenModelInfo") as ModelInfo | undefined + const actModeVercelAiGatewayModelId = context.globalState.get("actModeVercelAiGatewayModelId") as string | undefined + const actModeVercelAiGatewayModelInfo = context.globalState.get("actModeVercelAiGatewayModelInfo") as + | ModelInfo + | undefined + const sapAiCoreUseOrchestrationMode = context.globalState.get("sapAiCoreUseOrchestrationMode") as boolean | undefined - // Other global fields - focusChainSettings: focusChainSettings || DEFAULT_FOCUS_CHAIN_SETTINGS, - focusChainFeatureFlagEnabled: focusChainFeatureFlagEnabled ?? false, - strictPlanModeEnabled: strictPlanModeEnabled ?? true, - useAutoCondense: useAutoCondense ?? false, - isNewUser: isNewUser ?? true, - welcomeViewCompleted, - lastShownAnnouncementId, - taskHistory: taskHistory || [], - autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string - globalClineRulesToggles: globalClineRulesToggles || {}, - browserSettings: { ...DEFAULT_BROWSER_SETTINGS, ...browserSettings }, // this will ensure that older versions of browserSettings (e.g. before remoteBrowserEnabled was added) are merged with the default values (false for remoteBrowserEnabled) - preferredLanguage: preferredLanguage || "English", - openaiReasoningEffort: (openaiReasoningEffort as OpenaiReasoningEffort) || "medium", - mode: mode || "act", - userInfo, - mcpMarketplaceEnabled: mcpMarketplaceEnabledRaw ?? true, - mcpDisplayMode: mcpDisplayMode ?? DEFAULT_MCP_DISPLAY_MODE, - mcpResponsesCollapsed: mcpResponsesCollapsed, - telemetrySetting: telemetrySetting || "unset", - planActSeparateModelsSetting, - enableCheckpointsSetting: enableCheckpointsSettingRaw ?? true, - shellIntegrationTimeout: shellIntegrationTimeout || 4000, - terminalReuseEnabled: terminalReuseEnabled ?? true, - terminalOutputLineLimit: terminalOutputLineLimit ?? 500, - defaultTerminalProfile: defaultTerminalProfile ?? "default", - globalWorkflowToggles: globalWorkflowToggles || {}, - mcpMarketplaceCatalog, - qwenCodeOauthPath, - customPrompt, + let apiProvider: ApiProvider + if (planModeApiProvider) { + apiProvider = planModeApiProvider + } else { + // New users should default to openrouter, since they've opted to use an API key instead of signing in + apiProvider = "openrouter" + } + + const mcpResponsesCollapsed = mcpResponsesCollapsedRaw ?? false + + // Plan/Act separate models setting is a boolean indicating whether the user wants to use different models for plan and act. Existing users expect this to be enabled, while we want new users to opt in to this being disabled by default. + // On win11 state sometimes initializes as empty string instead of undefined + let planActSeparateModelsSetting: boolean | undefined + if (planActSeparateModelsSettingRaw === true || planActSeparateModelsSettingRaw === false) { + planActSeparateModelsSetting = planActSeparateModelsSettingRaw + } else { + // default to true for existing users + if (planModeApiProvider) { + planActSeparateModelsSetting = true + } else { + // default to false for new users + planActSeparateModelsSetting = false + } + } + + const taskHistory = await readTaskHistoryFromState(context) + + return { + // api configuration fields + claudeCodePath, + awsRegion, + awsUseCrossRegionInference, + awsBedrockUsePromptCache, + awsBedrockEndpoint, + awsProfile, + awsUseProfile, + awsAuthentication, + vertexProjectId, + vertexRegion, + openAiBaseUrl, + requestyBaseUrl, + openAiHeaders: openAiHeaders || {}, + ollamaBaseUrl, + ollamaApiOptionsCtxNum, + lmStudioBaseUrl, + lmStudioMaxTokens, + anthropicBaseUrl, + geminiBaseUrl, + qwenApiLine, + moonshotApiLine, + zaiApiLine, + azureApiVersion, + openRouterProviderSorting, + liteLlmBaseUrl, + liteLlmUsePromptCache, + fireworksModelMaxCompletionTokens, + fireworksModelMaxTokens, + asksageApiUrl, + favoritedModelIds, + requestTimeoutMs, + sapAiCoreBaseUrl, + sapAiCoreTokenUrl, + sapAiResourceGroup, + difyBaseUrl, + sapAiCoreUseOrchestrationMode, + // Plan mode configurations + planModeApiProvider: planModeApiProvider || apiProvider, + planModeApiModelId, + planModeThinkingBudgetTokens, + planModeReasoningEffort, + planModeVsCodeLmModelSelector, + planModeAwsBedrockCustomSelected, + planModeAwsBedrockCustomModelBaseId, + planModeOpenRouterModelId, + planModeOpenRouterModelInfo, + planModeOpenAiModelId, + planModeOpenAiModelInfo, + planModeOllamaModelId, + planModeLmStudioModelId, + planModeLiteLlmModelId, + planModeLiteLlmModelInfo, + planModeRequestyModelId, + planModeRequestyModelInfo, + planModeTogetherModelId, + planModeFireworksModelId, + planModeSapAiCoreModelId, + planModeGroqModelId, + planModeGroqModelInfo, + planModeHuggingFaceModelId, + planModeHuggingFaceModelInfo, + planModeHuaweiCloudMaasModelId, + planModeHuaweiCloudMaasModelInfo, + planModeBasetenModelId, + planModeBasetenModelInfo, + planModeVercelAiGatewayModelId, + planModeVercelAiGatewayModelInfo, + // Act mode configurations + actModeApiProvider: actModeApiProvider || apiProvider, + actModeApiModelId, + actModeThinkingBudgetTokens, + actModeReasoningEffort, + actModeVsCodeLmModelSelector, + actModeAwsBedrockCustomSelected, + actModeAwsBedrockCustomModelBaseId, + actModeOpenRouterModelId, + actModeOpenRouterModelInfo, + actModeOpenAiModelId, + actModeOpenAiModelInfo, + actModeOllamaModelId, + actModeLmStudioModelId, + actModeLiteLlmModelId, + actModeLiteLlmModelInfo, + actModeRequestyModelId, + actModeRequestyModelInfo, + actModeTogetherModelId, + actModeFireworksModelId, + actModeSapAiCoreModelId, + actModeGroqModelId, + actModeGroqModelInfo, + actModeHuggingFaceModelId, + actModeHuggingFaceModelInfo, + actModeHuaweiCloudMaasModelId, + actModeHuaweiCloudMaasModelInfo, + actModeBasetenModelId, + actModeBasetenModelInfo, + actModeVercelAiGatewayModelId, + actModeVercelAiGatewayModelInfo, + + // Other global fields + focusChainSettings: focusChainSettings || DEFAULT_FOCUS_CHAIN_SETTINGS, + focusChainFeatureFlagEnabled: focusChainFeatureFlagEnabled ?? false, + strictPlanModeEnabled: strictPlanModeEnabled ?? true, + useAutoCondense: useAutoCondense ?? false, + isNewUser: isNewUser ?? true, + welcomeViewCompleted, + lastShownAnnouncementId, + taskHistory: taskHistory || [], + autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string + globalClineRulesToggles: globalClineRulesToggles || {}, + browserSettings: { ...DEFAULT_BROWSER_SETTINGS, ...browserSettings }, // this will ensure that older versions of browserSettings (e.g. before remoteBrowserEnabled was added) are merged with the default values (false for remoteBrowserEnabled) + preferredLanguage: preferredLanguage || "English", + openaiReasoningEffort: (openaiReasoningEffort as OpenaiReasoningEffort) || "medium", + mode: mode || "act", + userInfo, + mcpMarketplaceEnabled: mcpMarketplaceEnabledRaw ?? true, + mcpDisplayMode: mcpDisplayMode ?? DEFAULT_MCP_DISPLAY_MODE, + mcpResponsesCollapsed: mcpResponsesCollapsed, + telemetrySetting: telemetrySetting || "unset", + planActSeparateModelsSetting, + enableCheckpointsSetting: enableCheckpointsSettingRaw ?? true, + shellIntegrationTimeout: shellIntegrationTimeout || 4000, + terminalReuseEnabled: terminalReuseEnabled ?? true, + terminalOutputLineLimit: terminalOutputLineLimit ?? 500, + defaultTerminalProfile: defaultTerminalProfile ?? "default", + globalWorkflowToggles: globalWorkflowToggles || {}, + mcpMarketplaceCatalog, + qwenCodeOauthPath, + customPrompt, + } + } catch (error) { + console.error("[StateHelpers] Failed to read global state:", error) + throw error } }