From 669e018b85e617754bbcc9d7fd481c2850b3cde3 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Mon, 11 Aug 2025 14:46:39 -0700 Subject: [PATCH] Move rest of state to cache (#5404) * move rest of state to cacheService * finish moving state to cache * remove console logs * fix types * don't type cast * add eslint rule banning use of direct storage apis * fix types * move vscode state eslint rule to separate rule since it's error and the others aren't * fix eslint rules parsing --- .eslintrc.json | 3 +- .../no-direct-vscode-state-api.test.ts | 171 +++++ eslint-rules/index.js | 3 + eslint-rules/no-direct-vscode-state-api.js | 144 ++++ proto/cline/state.proto | 16 +- .../FileContextTracker.test.ts | 11 +- .../context-tracking/FileContextTracker.ts | 27 +- .../user-instructions/cline-rules.ts | 13 +- .../user-instructions/external-rules.ts | 13 +- .../user-instructions/rule-helpers.ts | 29 +- .../user-instructions/workflows.ts | 13 +- .../controller/account/authStateChanged.ts | 3 +- .../controller/browser/discoverBrowser.ts | 3 +- .../browser/getBrowserConnectionInfo.ts | 3 +- .../browser/getDetectedChromePath.ts | 3 +- .../browser/testBrowserConnection.ts | 3 +- .../browser/updateBrowserSettings.ts | 5 +- src/core/controller/file/createRuleFile.ts | 4 +- src/core/controller/file/deleteRuleFile.ts | 2 +- src/core/controller/file/refreshRules.ts | 6 +- src/core/controller/file/toggleClineRule.ts | 13 +- src/core/controller/file/toggleCursorRule.ts | 7 +- .../controller/file/toggleWindsurfRule.ts | 5 +- src/core/controller/file/toggleWorkflow.ts | 10 +- src/core/controller/index.ts | 147 ++-- .../controller/models/refreshBasetenModels.ts | 4 +- .../controller/models/refreshGroqModels.ts | 5 +- .../models/refreshRequestyModels.ts | 3 +- src/core/controller/state/resetState.ts | 4 +- .../state/setWelcomeViewCompleted.ts | 3 +- .../controller/state/toggleFavoriteModel.ts | 1 - .../state/updateAutoApprovalSettings.ts | 3 +- .../state/updateDefaultTerminalProfile.ts | 5 +- src/core/controller/state/updateSettings.ts | 68 +- .../state/updateTerminalConnectionTimeout.ts | 3 +- .../state/updateTerminalReuseEnabled.ts | 3 +- .../controller/task/deleteAllTaskHistory.ts | 8 +- src/core/controller/task/getTaskHistory.ts | 4 +- src/core/controller/task/showTaskWithId.ts | 3 +- .../controller/task/toggleTaskFavorite.ts | 5 +- src/core/controller/ui/initializeWebview.ts | 27 +- .../controller/ui/onDidShowAnnouncement.ts | 3 +- src/core/storage/CacheService.ts | 386 ++++++----- src/core/storage/state-keys.ts | 171 +++++ src/core/storage/state-migrations.ts | 8 +- src/core/storage/state.ts | 648 ------------------ src/core/storage/utils/state-helpers.ts | 442 ++++++++++++ src/core/task/index.ts | 44 +- .../git/commit-message-generator.ts | 4 +- src/services/test/TestServer.ts | 11 +- src/test/cline-api.test.ts | 5 - .../settings/utils/settingsHandlers.ts | 40 +- 52 files changed, 1472 insertions(+), 1096 deletions(-) create mode 100644 eslint-rules/__tests__/no-direct-vscode-state-api.test.ts create mode 100644 eslint-rules/no-direct-vscode-state-api.js delete mode 100644 src/core/storage/state.ts create mode 100644 src/core/storage/utils/state-helpers.ts diff --git a/.eslintrc.json b/.eslintrc.json index cf366abd..80a1861a 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -21,6 +21,7 @@ "semi": "off", "react-hooks/exhaustive-deps": "off", "eslint-rules/no-direct-vscode-api": "warn", + "eslint-rules/no-direct-vscode-state-api": "error", "no-restricted-syntax": [ "error", { @@ -29,5 +30,5 @@ } ] }, - "ignorePatterns": ["out", "dist", "**/*.d.ts"] + "ignorePatterns": ["out", "dist", "dist-standalone", "**/*.d.ts", "node_modules"] } diff --git a/eslint-rules/__tests__/no-direct-vscode-state-api.test.ts b/eslint-rules/__tests__/no-direct-vscode-state-api.test.ts new file mode 100644 index 00000000..0e882859 --- /dev/null +++ b/eslint-rules/__tests__/no-direct-vscode-state-api.test.ts @@ -0,0 +1,171 @@ +const { RuleTester: StateApiRuleTester } = require("eslint") +const noDirectVscodeStateApiRule = require("../no-direct-vscode-state-api") + +const stateApiRuleTester = new StateApiRuleTester({ + parser: require.resolve("@typescript-eslint/parser"), + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + ecmaFeatures: { + jsx: true, + }, + }, +}) + +stateApiRuleTester.run("no-direct-vscode-state-api", noDirectVscodeStateApiRule, { + valid: [ + // Should allow state APIs in CacheService.ts + { + code: `await context.globalState.update("myKey", value);`, + filename: "CacheService.ts", + }, + { + code: `const value = context.globalState.get("myKey");`, + filename: "/src/core/storage/CacheService.ts", + }, + { + code: `await context.secrets.store("apiKey", value);`, + filename: "CacheService.ts", + }, + // Should allow state APIs in state-helpers.ts + { + code: `const value = context.globalState.get("myKey");`, + filename: "state-helpers.ts", + }, + { + code: `await context.secrets.get("apiKey");`, + filename: "/src/core/storage/utils/state-helpers.ts", + }, + // Should allow state APIs in state-migrations.ts + { + code: `await context.globalState.update("myKey", value);`, + filename: "state-migrations.ts", + }, + { + code: `const value = context.workspaceState.get("myKey");`, + filename: "/src/core/storage/state-migrations.ts", + }, + // Should allow state APIs in extension.ts + { + code: `const distinctId = context.globalState.get("cline.distinctId");`, + filename: "extension.ts", + }, + { + code: `await context.globalState.update("clineVersion", currentVersion);`, + filename: "/src/extension.ts", + }, + { + code: `const secret = await context.secrets.get("clineAccountId");`, + filename: "extension.ts", + }, + // Should allow state APIs in test files + { + code: `context.globalState.get("testKey")`, + filename: "/foo/bar.test.ts", + }, + // Should allow non-state API calls + { + code: `const value = someOtherObject.globalState.get("myKey");`, + filename: "some-file.ts", + }, + { + code: `await myContext.secrets.store("key", "value");`, + filename: "some-file.ts", + }, + ], + invalid: [ + // Should disallow context.globalState.get + { + code: `const value = context.globalState.get("myKey");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceGlobalGet", + }, + ], + }, + // Should disallow context.globalState.update + { + code: `await context.globalState.update("myKey", "myValue");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceGlobalSet", + }, + ], + }, + // Should disallow context.workspaceState.get + { + code: `const value = context.workspaceState.get("myKey");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceWorkspaceGet", + }, + ], + }, + // Should disallow context.workspaceState.update + { + code: `await context.workspaceState.update("myKey", "myValue");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceWorkspaceSet", + }, + ], + }, + // Should disallow context.secrets.get + { + code: `const secret = await context.secrets.get("apiKey");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceSecretsGet", + }, + ], + }, + // Should disallow context.secrets.store + { + code: `await context.secrets.store("apiKey", "secret-value");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceSecretsSet", + }, + ], + }, + // Should disallow context.secrets.delete + { + code: `await context.secrets.delete("apiKey");`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceSecretsSet", + }, + ], + }, + // Should disallow chained state API calls + { + code: `const value = await context.globalState.get("key") || "default";`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceGlobalGet", + }, + ], + }, + // Should disallow state API calls in Promise.all + { + code: `await Promise.all([context.secrets.get("key1"), context.secrets.get("key2")]);`, + filename: "some-file.ts", + errors: [ + { + messageId: "useCacheServiceSecretsGet", + }, + { + messageId: "useCacheServiceSecretsGet", + }, + ], + }, + ], +}) diff --git a/eslint-rules/index.js b/eslint-rules/index.js index e3d184e5..e3e43d39 100644 --- a/eslint-rules/index.js +++ b/eslint-rules/index.js @@ -1,15 +1,18 @@ // eslint-rules/index.js const noDirectVscodeApi = require("./no-direct-vscode-api") +const noDirectVscodeStateApi = require("./no-direct-vscode-state-api") module.exports = { rules: { "no-direct-vscode-api": noDirectVscodeApi, + "no-direct-vscode-state-api": noDirectVscodeStateApi, }, configs: { recommended: { plugins: ["local"], rules: { "local/no-direct-vscode-api": "warn", + "local/no-direct-vscode-state-api": "error", }, }, }, diff --git a/eslint-rules/no-direct-vscode-state-api.js b/eslint-rules/no-direct-vscode-state-api.js new file mode 100644 index 00000000..14c599d5 --- /dev/null +++ b/eslint-rules/no-direct-vscode-state-api.js @@ -0,0 +1,144 @@ +const { ESLintUtils } = require("@typescript-eslint/utils") +const path = require("path") + +const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`) + +// Configuration for context-based state APIs +const disallowedContextApis = { + "globalState.get": { + messageId: "useCacheServiceGlobalGet", + }, + "globalState.update": { + messageId: "useCacheServiceGlobalSet", + }, + "workspaceState.get": { + messageId: "useCacheServiceWorkspaceGet", + }, + "workspaceState.update": { + messageId: "useCacheServiceWorkspaceSet", + }, + "secrets.get": { + messageId: "useCacheServiceSecretsGet", + }, + "secrets.store": { + messageId: "useCacheServiceSecretsSet", + }, + "secrets.delete": { + messageId: "useCacheServiceSecretsSet", + }, +} + +module.exports = createRule({ + name: "no-direct-vscode-state-api", + meta: { + type: "problem", + docs: { + description: + "Disallow direct VSCode state API usage (context.globalState, context.workspaceState, context.secrets) in favor of CacheService", + recommended: "error", + }, + messages: { + useCacheServiceGlobalGet: + "Use CacheService.getGlobalStateKey() instead of context.globalState.get().\n" + + "The CacheService provides fast in-memory access with automatic persistence.\n" + + "Example: cacheService.getGlobalStateKey('myKey') instead of context.globalState.get('myKey').\n" + + "Found: {{code}}", + useCacheServiceGlobalSet: + "Use CacheService.setGlobalState() instead of context.globalState.update().\n" + + "The CacheService provides immediate updates with debounced persistence.\n" + + "Example: cacheService.setGlobalState('myKey', value) instead of context.globalState.update('myKey', value).\n" + + "Found: {{code}}", + useCacheServiceWorkspaceGet: + "Use CacheService.getWorkspaceStateKey() instead of context.workspaceState.get().\n" + + "The CacheService provides fast in-memory access with automatic persistence.\n" + + "Example: cacheService.getWorkspaceStateKey('myKey') instead of context.workspaceState.get('myKey').\n" + + "Found: {{code}}", + useCacheServiceWorkspaceSet: + "Use CacheService.setWorkspaceState() instead of context.workspaceState.update().\n" + + "The CacheService provides immediate updates with debounced persistence.\n" + + "Example: cacheService.setWorkspaceState('myKey', value) instead of context.workspaceState.update('myKey', value).\n" + + "Found: {{code}}", + useCacheServiceSecretsGet: + "Use CacheService.getSecretKey() instead of context.secrets.get().\n" + + "The CacheService provides fast in-memory access with automatic persistence.\n" + + "Example: cacheService.getSecretKey('mySecret') instead of context.secrets.get('mySecret').\n" + + "Found: {{code}}", + useCacheServiceSecretsSet: + "Use CacheService.setSecret() instead of context.secrets.store() or context.secrets.delete().\n" + + "The CacheService provides immediate updates with debounced persistence.\n" + + "Example: cacheService.setSecret('mySecret', value) instead of context.secrets.store('mySecret', value).\n" + + "For deletion, use: cacheService.setSecret('mySecret', undefined).\n" + + "Found: {{code}}", + }, + schema: [], + }, + defaultOptions: [], + + create(context) { + function isExcluded(filename) { + // Skip checking test files + if (filename.endsWith(".test.ts")) { + return true + } + // Skip checking specific state-related files that need direct access + const basename = path.basename(filename) + if ( + basename === "CacheService.ts" || + basename === "state-helpers.ts" || + basename === "state-migrations.ts" || + basename === "extension.ts" || + basename === "common.ts" // CI might report errors from this virtual file + ) { + return true + } + return false + } + + // Check for context-based state API calls + function checkContextStateApi(node) { + if (isExcluded(context.filename)) { + return + } + + // Check if this is a member expression like context.globalState.get + if ( + node.type === "MemberExpression" && + node.object && + node.object.type === "MemberExpression" && + node.object.object && + node.object.object.type === "Identifier" && + node.object.object.name === "context" + ) { + const stateType = node.object.property.name // e.g., "globalState", "workspaceState", "secrets" + const method = node.property.name // e.g., "get", "update", "store", "delete" + const apiPath = `${stateType}.${method}` + + if (disallowedContextApis[apiPath]) { + // For method calls, get the whole call expression + let reportNode = node + let parentNode = context.sourceCode.getAncestors(node).pop() + if (parentNode && parentNode.type === "CallExpression" && parentNode.callee === node) { + reportNode = parentNode + } + + const callText = context.sourceCode.getText(reportNode).trim() + + context.report({ + node: reportNode, + messageId: disallowedContextApis[apiPath].messageId, + data: { + code: callText, + }, + }) + } + } + } + + return { + // Detect member expressions (e.g., context.globalState.get) + MemberExpression(node) { + checkContextStateApi(node) + }, + } + }, +}) diff --git a/proto/cline/state.proto b/proto/cline/state.proto index 77451274..b2b56a77 100644 --- a/proto/cline/state.proto +++ b/proto/cline/state.proto @@ -52,6 +52,18 @@ enum PlanActMode { ACT = 1; } +enum OpenaiReasoningEffort { + LOW = 0; + MEDIUM = 1; + HIGH = 2; +} + +enum McpDisplayMode { + RICH = 0; + PLAIN = 1; + MARKDOWN = 2; +} + message ChatContent { optional string message = 1; repeated string images = 2; @@ -105,11 +117,11 @@ message UpdateSettingsRequest { optional int32 shell_integration_timeout = 8; optional bool terminal_reuse_enabled = 9; optional bool mcp_responses_collapsed = 10; - optional string mcp_display_mode = 11; + optional McpDisplayMode mcp_display_mode = 11; optional int32 terminal_output_line_limit = 12; optional PlanActMode mode = 13; optional string preferred_language = 14; - optional string openai_reasoning_effort = 15; + optional OpenaiReasoningEffort openai_reasoning_effort = 15; optional bool strict_plan_mode_enabled = 16; } diff --git a/src/core/context/context-tracking/FileContextTracker.test.ts b/src/core/context/context-tracking/FileContextTracker.test.ts index 6028c3a1..30506fe1 100644 --- a/src/core/context/context-tracking/FileContextTracker.test.ts +++ b/src/core/context/context-tracking/FileContextTracker.test.ts @@ -8,10 +8,11 @@ import * as sinon from "sinon" import * as vscode from "vscode" import type { FileMetadataEntry, TaskMetadata } from "./ContextTrackerTypes" import { FileContextTracker } from "./FileContextTracker" +import { Controller } from "@/core/controller" describe("FileContextTracker", () => { let sandbox: sinon.SinonSandbox - let mockContext: vscode.ExtensionContext + let mockController: Controller let mockWorkspace: sinon.SinonStub let mockFileSystemWatcher: any let tracker: FileContextTracker @@ -44,9 +45,9 @@ describe("FileContextTracker", () => { } // Mock controller and context - mockContext = { - globalStorageUri: { fsPath: "/mock/storage" }, - } as unknown as vscode.ExtensionContext + mockController = { + context: { globalStorageUri: { fsPath: "/mock/storage" } } as vscode.ExtensionContext, + } as unknown as Controller // Mock disk module functions mockTaskMetadata = { files_in_context: [], model_usage: [] } @@ -57,7 +58,7 @@ describe("FileContextTracker", () => { // Create tracker instance taskId = "test-task-id" - tracker = new FileContextTracker(mockContext, taskId) + tracker = new FileContextTracker(mockController, taskId) }) afterEach(() => { diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index e84d12bf..8065ebba 100644 --- a/src/core/context/context-tracking/FileContextTracker.ts +++ b/src/core/context/context-tracking/FileContextTracker.ts @@ -1,12 +1,11 @@ import * as path from "path" import * as vscode from "vscode" import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk" -import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state" -import { getGlobalState } from "@core/storage/state" import type { FileMetadataEntry } from "./ContextTrackerTypes" import type { ClineMessage } from "@shared/ExtensionMessage" -import { HostProvider } from "@/hosts/host-provider" import { getCwd } from "@/utils/path" +import { HistoryItem } from "@/shared/HistoryItem" +import { Controller } from "@/core/controller" // This class is responsible for tracking file operations that may result in stale context. // If a user modifies a file outside of Cline, the context may become stale and need to be updated. @@ -23,7 +22,7 @@ If a file is modified outside of Cline, we detect and track this change to preve This is used when restoring a task (non-git "checkpoint" restore), and mid-task. */ export class FileContextTracker { - private context: vscode.ExtensionContext + private controller: Controller readonly taskId: string // File tracking and watching @@ -31,8 +30,8 @@ export class FileContextTracker { private recentlyModifiedFiles = new Set() private recentlyEditedByCline = new Set() - constructor(context: vscode.ExtensionContext, taskId: string) { - this.context = context + constructor(controller: Controller, taskId: string) { + this.controller = controller this.taskId = taskId } @@ -84,7 +83,7 @@ export class FileContextTracker { } // Add file to metadata - await this.addFileToFileContextTracker(this.context, this.taskId, filePath, operation) + await this.addFileToFileContextTracker(this.controller.context, this.taskId, filePath, operation) // Set up file watcher for this file await this.setupFileWatcher(filePath) @@ -195,7 +194,7 @@ export class FileContextTracker { try { // Check task metadata for files that were edited by Cline or users after the message timestamp - const taskMetadata = await getTaskMetadata(this.context, this.taskId) + const taskMetadata = await getTaskMetadata(this.controller.context, this.taskId) if (taskMetadata?.files_in_context) { for (const fileEntry of taskMetadata.files_in_context) { @@ -237,7 +236,7 @@ export class FileContextTracker { const key = `pendingFileContextWarning_${this.taskId}` // NOTE: Using 'as any' because dynamic keys like pendingFileContextWarning_${taskId} // are legitimate workspace state keys but don't fit the strict LocalStateKey type system - await updateWorkspaceState(this.context, key as any, files) + this.controller.cacheService.setWorkspaceState(key as any, files) } catch (error) { console.error("Error storing pending file context warning:", error) } @@ -249,7 +248,7 @@ export class FileContextTracker { async retrievePendingFileContextWarning(): Promise { try { const key = `pendingFileContextWarning_${this.taskId}` - const files = (await getWorkspaceState(this.context, key as any)) as string[] + const files = this.controller.cacheService.getWorkspaceStateKey(key as any) as string[] return files } catch (error) { console.error("Error retrieving pending file context warning:", error) @@ -264,7 +263,7 @@ export class FileContextTracker { try { const files = await this.retrievePendingFileContextWarning() if (files) { - await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}` as any, undefined) + this.controller.cacheService.setWorkspaceState(`pendingFileContextWarning_${this.taskId}` as any, undefined) return files } } catch (error) { @@ -280,7 +279,8 @@ export class FileContextTracker { static async cleanupOrphanedWarnings(context: vscode.ExtensionContext): Promise { const startTime = Date.now() try { - const taskHistory = ((await getGlobalState(context, "taskHistory")) as Array<{ id: string }>) || [] + // eslint-disable-next-line eslint-rules/no-direct-vscode-state-api + const taskHistory = (context.globalState.get("taskHistory") as HistoryItem[]) || [] const existingTaskIds = new Set(taskHistory.map((task) => task.id)) const allStateKeys = context.workspaceState.keys() const pendingWarningKeys = allStateKeys.filter((key) => key.startsWith("pendingFileContextWarning_")) @@ -295,7 +295,8 @@ export class FileContextTracker { if (orphanedPendingContextTasks.length > 0) { for (const key of orphanedPendingContextTasks) { - await updateWorkspaceState(context, key as any, undefined) + // eslint-disable-next-line eslint-rules/no-direct-vscode-state-api + await context.workspaceState.update(key, undefined) } } diff --git a/src/core/context/instructions/user-instructions/cline-rules.ts b/src/core/context/instructions/user-instructions/cline-rules.ts index c6687e7e..17a0652c 100644 --- a/src/core/context/instructions/user-instructions/cline-rules.ts +++ b/src/core/context/instructions/user-instructions/cline-rules.ts @@ -4,9 +4,8 @@ import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" import { formatResponse } from "@core/prompts/responses" import fs from "fs/promises" import { ClineRulesToggles } from "@shared/cline-rules" -import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "@core/storage/state" -import * as vscode from "vscode" import { synchronizeRuleToggles, getRuleFilesTotalContent } from "@core/context/instructions/user-instructions/rule-helpers" +import { Controller } from "@/core/controller" export const getGlobalClineRules = async (globalClineRulesFilePath: string, toggles: ClineRulesToggles) => { if (await fileExistsAtPath(globalClineRulesFilePath)) { @@ -68,25 +67,25 @@ export const getLocalClineRules = async (cwd: string, toggles: ClineRulesToggles } export async function refreshClineRulesToggles( - context: vscode.ExtensionContext, + controller: Controller, workingDirectory: string, ): Promise<{ globalToggles: ClineRulesToggles localToggles: ClineRulesToggles }> { // Global toggles - const globalClineRulesToggles = ((await getGlobalState(context, "globalClineRulesToggles")) as ClineRulesToggles) || {} + const globalClineRulesToggles = controller.cacheService.getGlobalStateKey("globalClineRulesToggles") const globalClineRulesFilePath = await ensureRulesDirectoryExists() const updatedGlobalToggles = await synchronizeRuleToggles(globalClineRulesFilePath, globalClineRulesToggles) - await updateGlobalState(context, "globalClineRulesToggles", updatedGlobalToggles) + controller.cacheService.setGlobalState("globalClineRulesToggles", updatedGlobalToggles) // Local toggles - const localClineRulesToggles = ((await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles) || {} + const localClineRulesToggles = controller.cacheService.getWorkspaceStateKey("localClineRulesToggles") const localClineRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.clineRules) const updatedLocalToggles = await synchronizeRuleToggles(localClineRulesFilePath, localClineRulesToggles, "", [ [".clinerules", "workflows"], ]) - await updateWorkspaceState(context, "localClineRulesToggles", updatedLocalToggles) + controller.cacheService.setWorkspaceState("localClineRulesToggles", updatedLocalToggles) return { globalToggles: updatedGlobalToggles, diff --git a/src/core/context/instructions/user-instructions/external-rules.ts b/src/core/context/instructions/user-instructions/external-rules.ts index 11641717..d71ec3ee 100644 --- a/src/core/context/instructions/user-instructions/external-rules.ts +++ b/src/core/context/instructions/user-instructions/external-rules.ts @@ -3,7 +3,6 @@ import fs from "fs/promises" import { GlobalFileNames } from "@core/storage/disk" import { fileExistsAtPath, isDirectory } from "@utils/fs" import { formatResponse } from "@core/prompts/responses" -import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state" import { synchronizeRuleToggles, combineRuleToggles, @@ -11,26 +10,26 @@ import { readDirectoryRecursive, } from "@core/context/instructions/user-instructions/rule-helpers" import { ClineRulesToggles } from "@shared/cline-rules" -import * as vscode from "vscode" +import { Controller } from "@/core/controller" /** * Refreshes the toggles for windsurf and cursor rules */ export async function refreshExternalRulesToggles( - context: vscode.ExtensionContext, + controller: Controller, workingDirectory: string, ): Promise<{ windsurfLocalToggles: ClineRulesToggles cursorLocalToggles: ClineRulesToggles }> { // local windsurf toggles - const localWindsurfRulesToggles = ((await getWorkspaceState(context, "localWindsurfRulesToggles")) as ClineRulesToggles) || {} + const localWindsurfRulesToggles = controller.cacheService.getWorkspaceStateKey("localWindsurfRulesToggles") const localWindsurfRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.windsurfRules) const updatedLocalWindsurfToggles = await synchronizeRuleToggles(localWindsurfRulesFilePath, localWindsurfRulesToggles) - await updateWorkspaceState(context, "localWindsurfRulesToggles", updatedLocalWindsurfToggles) + controller.cacheService.setWorkspaceState("localWindsurfRulesToggles", updatedLocalWindsurfToggles) // local cursor toggles - const localCursorRulesToggles = ((await getWorkspaceState(context, "localCursorRulesToggles")) as ClineRulesToggles) || {} + const localCursorRulesToggles = controller.cacheService.getWorkspaceStateKey("localCursorRulesToggles") // cursor has two valid locations for rules files, so we need to check both and combine // synchronizeRuleToggles will drop whichever rules files are not in each given path, but combining the results will result in no data loss @@ -41,7 +40,7 @@ export async function refreshExternalRulesToggles( const updatedLocalCursorToggles2 = await synchronizeRuleToggles(localCursorRulesFilePath, localCursorRulesToggles) const updatedLocalCursorToggles = combineRuleToggles(updatedLocalCursorToggles1, updatedLocalCursorToggles2) - await updateWorkspaceState(context, "localCursorRulesToggles", updatedLocalCursorToggles) + controller.cacheService.setWorkspaceState("localCursorRulesToggles", updatedLocalCursorToggles) return { windsurfLocalToggles: updatedLocalWindsurfToggles, diff --git a/src/core/context/instructions/user-instructions/rule-helpers.ts b/src/core/context/instructions/user-instructions/rule-helpers.ts index b02d7de3..10c70435 100644 --- a/src/core/context/instructions/user-instructions/rule-helpers.ts +++ b/src/core/context/instructions/user-instructions/rule-helpers.ts @@ -1,10 +1,9 @@ import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" import { ensureRulesDirectoryExists, ensureWorkflowsDirectoryExists, GlobalFileNames } from "@core/storage/disk" -import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "@core/storage/state" import * as path from "path" import fs from "fs/promises" import { ClineRulesToggles } from "@shared/cline-rules" -import * as vscode from "vscode" +import { Controller } from "@/core/controller" /** * Recursively traverses directory and finds all files, including checking for optional whitelisted file extension @@ -224,7 +223,7 @@ export const createRuleFile = async (isGlobal: boolean, filename: string, cwd: s * Delete a rule file or workflow file */ export async function deleteRuleFile( - context: vscode.ExtensionContext, + controller: Controller, rulePath: string, isGlobal: boolean, type: string, @@ -248,31 +247,31 @@ export async function deleteRuleFile( // Update the appropriate toggles if (isGlobal) { if (type === "workflow") { - const toggles = ((await getGlobalState(context, "globalWorkflowToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getGlobalStateKey("globalWorkflowToggles") delete toggles[rulePath] - await updateGlobalState(context, "globalWorkflowToggles", toggles) + controller.cacheService.setGlobalState("globalWorkflowToggles", toggles) } else { - const toggles = ((await getGlobalState(context, "globalClineRulesToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getGlobalStateKey("globalClineRulesToggles") delete toggles[rulePath] - await updateGlobalState(context, "globalClineRulesToggles", toggles) + controller.cacheService.setGlobalState("globalClineRulesToggles", toggles) } } else { if (type === "workflow") { - const toggles = ((await getWorkspaceState(context, "workflowToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("workflowToggles") delete toggles[rulePath] - await updateWorkspaceState(context, "workflowToggles", toggles) + controller.cacheService.setWorkspaceState("workflowToggles", toggles) } else if (type === "cursor") { - const toggles = ((await getWorkspaceState(context, "localCursorRulesToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localCursorRulesToggles") delete toggles[rulePath] - await updateWorkspaceState(context, "localCursorRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localCursorRulesToggles", toggles) } else if (type === "windsurf") { - const toggles = ((await getWorkspaceState(context, "localWindsurfRulesToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localWindsurfRulesToggles") delete toggles[rulePath] - await updateWorkspaceState(context, "localWindsurfRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localWindsurfRulesToggles", toggles) } else { - const toggles = ((await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localClineRulesToggles") delete toggles[rulePath] - await updateWorkspaceState(context, "localClineRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localClineRulesToggles", toggles) } } diff --git a/src/core/context/instructions/user-instructions/workflows.ts b/src/core/context/instructions/user-instructions/workflows.ts index 268a5dad..33d1b894 100644 --- a/src/core/context/instructions/user-instructions/workflows.ts +++ b/src/core/context/instructions/user-instructions/workflows.ts @@ -1,30 +1,29 @@ import path from "path" import { GlobalFileNames, ensureWorkflowsDirectoryExists } from "@core/storage/disk" import { ClineRulesToggles } from "@shared/cline-rules" -import { getWorkspaceState, updateWorkspaceState, getGlobalState, updateGlobalState } from "@core/storage/state" -import * as vscode from "vscode" import { synchronizeRuleToggles } from "@core/context/instructions/user-instructions/rule-helpers" +import { Controller } from "@/core/controller" /** * Refresh the workflow toggles */ export async function refreshWorkflowToggles( - context: vscode.ExtensionContext, + controller: Controller, workingDirectory: string, ): Promise<{ globalWorkflowToggles: ClineRulesToggles localWorkflowToggles: ClineRulesToggles }> { // Global workflows - const globalWorkflowToggles = ((await getGlobalState(context, "globalWorkflowToggles")) as ClineRulesToggles) || {} + const globalWorkflowToggles = controller.cacheService.getGlobalStateKey("globalWorkflowToggles") const globalClineWorkflowsFilePath = await ensureWorkflowsDirectoryExists() const updatedGlobalWorkflowToggles = await synchronizeRuleToggles(globalClineWorkflowsFilePath, globalWorkflowToggles) - await updateGlobalState(context, "globalWorkflowToggles", updatedGlobalWorkflowToggles) + controller.cacheService.setGlobalState("globalWorkflowToggles", updatedGlobalWorkflowToggles) - const workflowRulesToggles = ((await getWorkspaceState(context, "workflowToggles")) as ClineRulesToggles) || {} + const workflowRulesToggles = controller.cacheService.getWorkspaceStateKey("workflowToggles") const workflowsDirPath = path.resolve(workingDirectory, GlobalFileNames.workflows) const updatedWorkflowToggles = await synchronizeRuleToggles(workflowsDirPath, workflowRulesToggles) - await updateWorkspaceState(context, "workflowToggles", updatedWorkflowToggles) + controller.cacheService.setWorkspaceState("workflowToggles", updatedWorkflowToggles) return { globalWorkflowToggles: updatedGlobalWorkflowToggles, diff --git a/src/core/controller/account/authStateChanged.ts b/src/core/controller/account/authStateChanged.ts index 692795dd..3d518958 100644 --- a/src/core/controller/account/authStateChanged.ts +++ b/src/core/controller/account/authStateChanged.ts @@ -1,6 +1,5 @@ import { AuthStateChangedRequest, AuthState } from "@shared/proto/cline/account" import type { Controller } from "../index" -import { updateGlobalState } from "../../storage/state" /** * Handles authentication state changes from the Firebase context. @@ -12,7 +11,7 @@ import { updateGlobalState } from "../../storage/state" export async function authStateChanged(controller: Controller, request: AuthStateChangedRequest): Promise { try { // Store the user info directly in global state - await updateGlobalState(controller.context, "userInfo", request.user) + controller.cacheService.setGlobalState("userInfo", request.user) // Return the same user info return AuthState.create({ user: request.user }) diff --git a/src/core/controller/browser/discoverBrowser.ts b/src/core/controller/browser/discoverBrowser.ts index 5b16b48a..18e3d64c 100644 --- a/src/core/controller/browser/discoverBrowser.ts +++ b/src/core/controller/browser/discoverBrowser.ts @@ -1,7 +1,6 @@ import { BrowserConnection } from "@shared/proto/cline/browser" import { EmptyRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { getAllExtensionState } from "@core/storage/state" import { BrowserSession } from "@services/browser/BrowserSession" import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" @@ -20,7 +19,7 @@ export async function discoverBrowser(controller: Controller, request: EmptyRequ // This way we don't override the user's preference // Test the connection to get the endpoint - const { browserSettings } = await getAllExtensionState(controller.context) + const browserSettings = controller.cacheService.getGlobalStateKey("browserSettings") const browserSession = new BrowserSession(controller.context, browserSettings) const result = await browserSession.testConnection(discoveredHost) diff --git a/src/core/controller/browser/getBrowserConnectionInfo.ts b/src/core/controller/browser/getBrowserConnectionInfo.ts index 39477b18..8f4737ef 100644 --- a/src/core/controller/browser/getBrowserConnectionInfo.ts +++ b/src/core/controller/browser/getBrowserConnectionInfo.ts @@ -1,7 +1,6 @@ import { BrowserConnectionInfo } from "@shared/proto/cline/browser" import { EmptyRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { getAllExtensionState } from "@core/storage/state" /** * Get information about the current browser connection @@ -12,7 +11,7 @@ import { getAllExtensionState } from "@core/storage/state" export async function getBrowserConnectionInfo(controller: Controller, _: EmptyRequest): Promise { try { // Get browser settings from extension state - const { browserSettings } = await getAllExtensionState(controller.context) + const browserSettings = controller.cacheService.getGlobalStateKey("browserSettings") // Check if there's an active browser session by using the controller's handleWebviewMessage approach // This is similar to what's done in controller/index.ts for the "getBrowserConnectionInfo" message diff --git a/src/core/controller/browser/getDetectedChromePath.ts b/src/core/controller/browser/getDetectedChromePath.ts index 98a9c727..bbc5dc2d 100644 --- a/src/core/controller/browser/getDetectedChromePath.ts +++ b/src/core/controller/browser/getDetectedChromePath.ts @@ -1,7 +1,6 @@ import { ChromePath } from "@shared/proto/cline/browser" import { EmptyRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { getAllExtensionState } from "../../storage/state" import { BrowserSession } from "../../../services/browser/BrowserSession" /** @@ -12,7 +11,7 @@ import { BrowserSession } from "../../../services/browser/BrowserSession" */ export async function getDetectedChromePath(controller: Controller, _: EmptyRequest): Promise { try { - const { browserSettings } = await getAllExtensionState(controller.context) + const browserSettings = controller.cacheService.getGlobalStateKey("browserSettings") const browserSession = new BrowserSession(controller.context, browserSettings) const result = await browserSession.getDetectedChromePath() diff --git a/src/core/controller/browser/testBrowserConnection.ts b/src/core/controller/browser/testBrowserConnection.ts index c2f33552..c82c66ad 100644 --- a/src/core/controller/browser/testBrowserConnection.ts +++ b/src/core/controller/browser/testBrowserConnection.ts @@ -1,7 +1,6 @@ import { BrowserConnection } from "@shared/proto/cline/browser" import { StringRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { getAllExtensionState } from "@core/storage/state" import { BrowserSession } from "@services/browser/BrowserSession" import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" @@ -13,7 +12,7 @@ import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" */ export async function testBrowserConnection(controller: Controller, request: StringRequest): Promise { try { - const { browserSettings } = await getAllExtensionState(controller.context) + const browserSettings = controller.cacheService.getGlobalStateKey("browserSettings") const browserSession = new BrowserSession(controller.context, browserSettings) const text = request.value || "" diff --git a/src/core/controller/browser/updateBrowserSettings.ts b/src/core/controller/browser/updateBrowserSettings.ts index c4c57977..27dcf048 100644 --- a/src/core/controller/browser/updateBrowserSettings.ts +++ b/src/core/controller/browser/updateBrowserSettings.ts @@ -1,7 +1,6 @@ import { UpdateBrowserSettingsRequest } from "@shared/proto/cline/browser" import { Boolean } from "@shared/proto/cline/common" import { Controller } from "../index" -import { updateGlobalState, getGlobalState } from "../../storage/state" import { BrowserSettings as SharedBrowserSettings, DEFAULT_BROWSER_SETTINGS } from "../../../shared/BrowserSettings" /** @@ -13,7 +12,7 @@ import { BrowserSettings as SharedBrowserSettings, DEFAULT_BROWSER_SETTINGS } fr export async function updateBrowserSettings(controller: Controller, request: UpdateBrowserSettingsRequest): Promise { try { // Get current browser settings to preserve fields not in the request - const currentSettings = (await getGlobalState(controller.context, "browserSettings")) as SharedBrowserSettings | undefined + const currentSettings = controller.cacheService.getGlobalStateKey("browserSettings") const mergedWithDefaults = { ...DEFAULT_BROWSER_SETTINGS, ...currentSettings } // Convert from protobuf format to shared format, merging with existing settings @@ -39,7 +38,7 @@ export async function updateBrowserSettings(controller: Controller, request: Upd } // Update global state with new settings - await updateGlobalState(controller.context, "browserSettings", newBrowserSettings) + controller.cacheService.setGlobalState("browserSettings", newBrowserSettings) // Update task browser settings if task exists if (controller.task) { diff --git a/src/core/controller/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 303b9d0b..6147de5d 100644 --- a/src/core/controller/file/createRuleFile.ts +++ b/src/core/controller/file/createRuleFile.ts @@ -51,9 +51,9 @@ export async function createRuleFile(controller: Controller, request: RuleFileRe await openFile(controller, { value: filePath }) } else { if (request.type === "workflow") { - await refreshWorkflowToggles(controller.context, cwd) + await refreshWorkflowToggles(controller, cwd) } else { - await refreshClineRulesToggles(controller.context, cwd) + await refreshClineRulesToggles(controller, cwd) } await controller.postStateToWebview() diff --git a/src/core/controller/file/deleteRuleFile.ts b/src/core/controller/file/deleteRuleFile.ts index 7d382344..f54cdd45 100644 --- a/src/core/controller/file/deleteRuleFile.ts +++ b/src/core/controller/file/deleteRuleFile.ts @@ -28,7 +28,7 @@ export async function deleteRuleFile(controller: Controller, request: RuleFileRe throw new Error("Missing or invalid parameters") } - const result = await deleteRuleFileImpl(controller.context, request.rulePath, request.isGlobal, request.type) + const result = await deleteRuleFileImpl(controller, request.rulePath, request.isGlobal, request.type) if (!result.success) { throw new Error(result.message || "Failed to delete rule file") diff --git a/src/core/controller/file/refreshRules.ts b/src/core/controller/file/refreshRules.ts index 6d64830b..b5f38677 100644 --- a/src/core/controller/file/refreshRules.ts +++ b/src/core/controller/file/refreshRules.ts @@ -15,9 +15,9 @@ import { getCwd, getDesktopDir } from "@/utils/path" export async function refreshRules(controller: Controller, _request: EmptyRequest): Promise { try { const cwd = await getCwd(getDesktopDir()) - const { globalToggles, localToggles } = await refreshClineRulesToggles(controller.context, cwd) - const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller.context, cwd) - const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller.context, cwd) + const { globalToggles, localToggles } = await refreshClineRulesToggles(controller, cwd) + const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller, cwd) + const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller, cwd) return RefreshedRules.create({ globalClineRulesToggles: { toggles: globalToggles }, diff --git a/src/core/controller/file/toggleClineRule.ts b/src/core/controller/file/toggleClineRule.ts index b1df36d8..6e827903 100644 --- a/src/core/controller/file/toggleClineRule.ts +++ b/src/core/controller/file/toggleClineRule.ts @@ -1,7 +1,6 @@ import { ToggleClineRules } from "@shared/proto/cline/file" import type { ToggleClineRuleRequest } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "../../../core/storage/state" import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** @@ -24,18 +23,18 @@ export async function toggleClineRule(controller: Controller, request: ToggleCli // This is the same core logic as in the original handler if (isGlobal) { - const toggles = ((await getGlobalState(controller.context, "globalClineRulesToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getGlobalStateKey("globalClineRulesToggles") toggles[rulePath] = enabled - await updateGlobalState(controller.context, "globalClineRulesToggles", toggles) + controller.cacheService.setGlobalState("globalClineRulesToggles", toggles) } else { - const toggles = ((await getWorkspaceState(controller.context, "localClineRulesToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localClineRulesToggles") toggles[rulePath] = enabled - await updateWorkspaceState(controller.context, "localClineRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localClineRulesToggles", toggles) } // Get the current state to return in the response - const globalToggles = ((await getGlobalState(controller.context, "globalClineRulesToggles")) as AppClineRulesToggles) || {} - const localToggles = ((await getWorkspaceState(controller.context, "localClineRulesToggles")) as AppClineRulesToggles) || {} + const globalToggles = controller.cacheService.getGlobalStateKey("globalClineRulesToggles") + const localToggles = controller.cacheService.getWorkspaceStateKey("localClineRulesToggles") return ToggleClineRules.create({ globalClineRulesToggles: { toggles: globalToggles }, diff --git a/src/core/controller/file/toggleCursorRule.ts b/src/core/controller/file/toggleCursorRule.ts index 91496bc0..99e8ddda 100644 --- a/src/core/controller/file/toggleCursorRule.ts +++ b/src/core/controller/file/toggleCursorRule.ts @@ -1,7 +1,6 @@ import type { ToggleCursorRuleRequest } from "@shared/proto/cline/file" import { ClineRulesToggles } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state" import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** @@ -22,12 +21,12 @@ export async function toggleCursorRule(controller: Controller, request: ToggleCu } // Update the toggles in workspace state - const toggles = ((await getWorkspaceState(controller.context, "localCursorRulesToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localCursorRulesToggles") toggles[rulePath] = enabled - await updateWorkspaceState(controller.context, "localCursorRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localCursorRulesToggles", toggles) // Get the current state to return in the response - const cursorToggles = ((await getWorkspaceState(controller.context, "localCursorRulesToggles")) as AppClineRulesToggles) || {} + const cursorToggles = controller.cacheService.getWorkspaceStateKey("localCursorRulesToggles") return ClineRulesToggles.create({ toggles: cursorToggles, diff --git a/src/core/controller/file/toggleWindsurfRule.ts b/src/core/controller/file/toggleWindsurfRule.ts index e75c3b4b..ff594475 100644 --- a/src/core/controller/file/toggleWindsurfRule.ts +++ b/src/core/controller/file/toggleWindsurfRule.ts @@ -1,7 +1,6 @@ import type { ToggleWindsurfRuleRequest } from "@shared/proto/cline/file" import { ClineRulesToggles } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state" import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** @@ -22,9 +21,9 @@ export async function toggleWindsurfRule(controller: Controller, request: Toggle } // Update the toggles - const toggles = ((await getWorkspaceState(controller.context, "localWindsurfRulesToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("localWindsurfRulesToggles") toggles[rulePath] = enabled - await updateWorkspaceState(controller.context, "localWindsurfRulesToggles", toggles) + controller.cacheService.setWorkspaceState("localWindsurfRulesToggles", toggles) // Return the toggles directly return ClineRulesToggles.create({ toggles: toggles }) diff --git a/src/core/controller/file/toggleWorkflow.ts b/src/core/controller/file/toggleWorkflow.ts index 8c5a6712..d89e406d 100644 --- a/src/core/controller/file/toggleWorkflow.ts +++ b/src/core/controller/file/toggleWorkflow.ts @@ -1,7 +1,5 @@ import { Controller } from ".." -import { Metadata } from "@shared/proto/cline/common" import { ToggleWorkflowRequest, ClineRulesToggles } from "@shared/proto/cline/file" -import { getWorkspaceState, updateWorkspaceState, getGlobalState, updateGlobalState } from "../../../core/storage/state" import { ClineRulesToggles as AppClineRulesToggles } from "../../../shared/cline-rules" /** @@ -24,18 +22,18 @@ export async function toggleWorkflow(controller: Controller, request: ToggleWork // Update the toggles based on isGlobal flag if (isGlobal) { // Global workflows - const toggles = ((await getGlobalState(controller.context, "globalWorkflowToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getGlobalStateKey("globalWorkflowToggles") toggles[workflowPath] = enabled - await updateGlobalState(controller.context, "globalWorkflowToggles", toggles) + controller.cacheService.setGlobalState("globalWorkflowToggles", toggles) await controller.postStateToWebview() // Return the global toggles return ClineRulesToggles.create({ toggles: toggles }) } else { // Workspace workflows - const toggles = ((await getWorkspaceState(controller.context, "workflowToggles")) as AppClineRulesToggles) || {} + const toggles = controller.cacheService.getWorkspaceStateKey("workflowToggles") toggles[workflowPath] = enabled - await updateWorkspaceState(controller.context, "workflowToggles", toggles) + controller.cacheService.setWorkspaceState("workflowToggles", toggles) await controller.postStateToWebview() // Return the workspace toggles diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 4c3439b3..a8d09d22 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -28,7 +28,6 @@ import * as path from "path" import * as vscode from "vscode" import { CacheService, PersistenceErrorEvent } from "../storage/CacheService" import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk" -import { getAllExtensionState, getGlobalState, updateGlobalState } from "../storage/state" import { Task } from "../task" import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" import { sendStateUpdate } from "./state/subscribeToState" @@ -103,7 +102,7 @@ export class Controller { } async getCurrentMode(): Promise { - return ((await getGlobalState(this.context, "mode")) as Mode | undefined) || "act" + return this.cacheService.getGlobalStateKey("mode") } /* @@ -129,7 +128,7 @@ export class Controller { try { // TODO: update to clineAccountId and then move clineApiKey to a clear function. this.cacheService.setSecret("clineAccountId", undefined) - await updateGlobalState(this.context, "userInfo", undefined) + this.cacheService.setGlobalState("userInfo", undefined) // Update API providers through cache service const apiConfiguration = this.cacheService.getApiConfiguration() @@ -154,36 +153,32 @@ export class Controller { } async setUserInfo(info?: UserInfo) { - await updateGlobalState(this.context, "userInfo", info) + this.cacheService.setGlobalState("userInfo", info) } async initTask(task?: string, images?: string[], files?: string[], historyItem?: HistoryItem) { await this.clearTask() // ensures that an existing task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one - // Get API configuration from cache for immediate access const apiConfiguration = this.cacheService.getApiConfiguration() - - const { - autoApprovalSettings, - browserSettings, - preferredLanguage, - openaiReasoningEffort, - mode, - shellIntegrationTimeout, - terminalReuseEnabled, - terminalOutputLineLimit, - defaultTerminalProfile, - enableCheckpointsSetting, - isNewUser, - taskHistory, - strictPlanModeEnabled, - } = await getAllExtensionState(this.context) + const autoApprovalSettings = this.cacheService.getGlobalStateKey("autoApprovalSettings") + const browserSettings = this.cacheService.getGlobalStateKey("browserSettings") + const preferredLanguage = this.cacheService.getGlobalStateKey("preferredLanguage") + const openaiReasoningEffort = this.cacheService.getGlobalStateKey("openaiReasoningEffort") + const mode = this.cacheService.getGlobalStateKey("mode") + const shellIntegrationTimeout = this.cacheService.getGlobalStateKey("shellIntegrationTimeout") + const terminalReuseEnabled = this.cacheService.getGlobalStateKey("terminalReuseEnabled") + const terminalOutputLineLimit = this.cacheService.getGlobalStateKey("terminalOutputLineLimit") + const defaultTerminalProfile = this.cacheService.getGlobalStateKey("defaultTerminalProfile") + const enableCheckpointsSetting = this.cacheService.getGlobalStateKey("enableCheckpointsSetting") + const isNewUser = this.cacheService.getGlobalStateKey("isNewUser") + const taskHistory = this.cacheService.getGlobalStateKey("taskHistory") + const strictPlanModeEnabled = this.cacheService.getGlobalStateKey("strictPlanModeEnabled") const NEW_USER_TASK_COUNT_THRESHOLD = 10 // Check if the user has completed enough tasks to no longer be considered a "new user" if (isNewUser && !historyItem && taskHistory && taskHistory.length >= NEW_USER_TASK_COUNT_THRESHOLD) { - await updateGlobalState(this.context, "isNewUser", false) + this.cacheService.setGlobalState("isNewUser", false) await this.postStateToWebview() } @@ -192,10 +187,10 @@ export class Controller { ...autoApprovalSettings, version: (autoApprovalSettings.version ?? 1) + 1, } - await updateGlobalState(this.context, "autoApprovalSettings", updatedAutoApprovalSettings) + this.cacheService.setGlobalState("autoApprovalSettings", updatedAutoApprovalSettings) } this.task = new Task( - this.context, + this, this.mcpHub, (historyItem) => this.updateTaskHistory(historyItem), () => this.postStateToWebview(), @@ -230,7 +225,7 @@ export class Controller { } async updateTelemetrySetting(telemetrySetting: TelemetrySetting) { - await updateGlobalState(this.context, "telemetrySetting", telemetrySetting) + this.cacheService.setGlobalState("telemetrySetting", telemetrySetting) const isOptedIn = telemetrySetting !== "disabled" telemetryService.updateTelemetryState(isOptedIn) await this.postStateToWebview() @@ -240,7 +235,7 @@ export class Controller { const didSwitchToActMode = modeToSwitchTo === "act" // Store mode to global state - await updateGlobalState(this.context, "mode", modeToSwitchTo) + this.cacheService.setGlobalState("mode", modeToSwitchTo) // Capture mode switch telemetry | Capture regardless of if we know the taskId telemetryService.captureModeSwitch(this.task?.taskId ?? "0", modeToSwitchTo) @@ -312,7 +307,8 @@ export class Controller { const clineProvider: ApiProvider = "cline" // Get current settings to determine how to update providers - const { planActSeparateModelsSetting } = await getAllExtensionState(this.context) + const planActSeparateModelsSetting = this.cacheService.getGlobalStateKey("planActSeparateModelsSetting") + const currentMode = await this.getCurrentMode() // Get current API configuration from cache @@ -337,7 +333,7 @@ export class Controller { this.cacheService.setApiConfiguration(updatedConfig) // Mark welcome view as completed since user has successfully logged in - await updateGlobalState(this.context, "welcomeViewCompleted", true) + this.cacheService.setGlobalState("welcomeViewCompleted", true) if (this.task) { this.task.api = buildApiHandler({ ...updatedConfig, taskId: this.task.taskId }, currentMode) @@ -378,7 +374,7 @@ export class Controller { } // Store in global state - await updateGlobalState(this.context, "mcpMarketplaceCatalog", catalog) + this.cacheService.setGlobalState("mcpMarketplaceCatalog", catalog) return catalog } catch (error) { console.error("Failed to fetch MCP marketplace:", error) @@ -416,7 +412,7 @@ export class Controller { } // Store in global state - await updateGlobalState(this.context, "mcpMarketplaceCatalog", catalog) + this.cacheService.setGlobalState("mcpMarketplaceCatalog", catalog) return catalog } catch (error) { console.error("Failed to fetch MCP marketplace:", error) @@ -598,7 +594,7 @@ export class Controller { taskMetadataFilePath: string apiConversationHistory: Anthropic.MessageParam[] }> { - const history = ((await getGlobalState(this.context, "taskHistory")) as HistoryItem[] | undefined) || [] + const history = this.cacheService.getGlobalStateKey("taskHistory") const historyItem = history.find((item) => item.id === id) if (historyItem) { const taskDirPath = path.join(this.context.globalStorageUri.fsPath, "tasks", id) @@ -633,9 +629,9 @@ export class Controller { async deleteTaskFromState(id: string) { // Remove the task from history - const taskHistory = ((await getGlobalState(this.context, "taskHistory")) as HistoryItem[] | undefined) || [] + const taskHistory = this.cacheService.getGlobalStateKey("taskHistory") const updatedTaskHistory = taskHistory.filter((task) => task.id !== id) - await updateGlobalState(this.context, "taskHistory", updatedTaskHistory) + this.cacheService.setGlobalState("taskHistory", updatedTaskHistory) // Notify the webview that the task has been deleted await this.postStateToWebview() @@ -651,36 +647,33 @@ export class Controller { async getStateToPostToWebview(): Promise { // Get API configuration from cache for immediate access const apiConfiguration = this.cacheService.getApiConfiguration() - - const { - lastShownAnnouncementId, - taskHistory, - autoApprovalSettings, - browserSettings, - preferredLanguage, - openaiReasoningEffort, - mode, - strictPlanModeEnabled, - userInfo, - mcpMarketplaceEnabled, - mcpDisplayMode, - telemetrySetting, - planActSeparateModelsSetting, - enableCheckpointsSetting, - globalClineRulesToggles, - globalWorkflowToggles, - shellIntegrationTimeout, - terminalReuseEnabled, - defaultTerminalProfile, - isNewUser, - welcomeViewCompleted, - mcpResponsesCollapsed, - terminalOutputLineLimit, - localClineRulesToggles, - localWindsurfRulesToggles, - localCursorRulesToggles, - localWorkflowToggles, - } = await getAllExtensionState(this.context) + const lastShownAnnouncementId = this.cacheService.getGlobalStateKey("lastShownAnnouncementId") + const taskHistory = this.cacheService.getGlobalStateKey("taskHistory") + const autoApprovalSettings = this.cacheService.getGlobalStateKey("autoApprovalSettings") + const browserSettings = this.cacheService.getGlobalStateKey("browserSettings") + const preferredLanguage = this.cacheService.getGlobalStateKey("preferredLanguage") + const openaiReasoningEffort = this.cacheService.getGlobalStateKey("openaiReasoningEffort") + const mode = this.cacheService.getGlobalStateKey("mode") + const strictPlanModeEnabled = this.cacheService.getGlobalStateKey("strictPlanModeEnabled") + const userInfo = this.cacheService.getGlobalStateKey("userInfo") + const mcpMarketplaceEnabled = this.cacheService.getGlobalStateKey("mcpMarketplaceEnabled") + const mcpDisplayMode = this.cacheService.getGlobalStateKey("mcpDisplayMode") + const telemetrySetting = this.cacheService.getGlobalStateKey("telemetrySetting") + const planActSeparateModelsSetting = this.cacheService.getGlobalStateKey("planActSeparateModelsSetting") + const enableCheckpointsSetting = this.cacheService.getGlobalStateKey("enableCheckpointsSetting") + const globalClineRulesToggles = this.cacheService.getGlobalStateKey("globalClineRulesToggles") + const globalWorkflowToggles = this.cacheService.getGlobalStateKey("globalWorkflowToggles") + const shellIntegrationTimeout = this.cacheService.getGlobalStateKey("shellIntegrationTimeout") + const terminalReuseEnabled = this.cacheService.getGlobalStateKey("terminalReuseEnabled") + const defaultTerminalProfile = this.cacheService.getGlobalStateKey("defaultTerminalProfile") + const isNewUser = this.cacheService.getGlobalStateKey("isNewUser") + const welcomeViewCompleted = this.cacheService.getGlobalStateKey("welcomeViewCompleted") + const mcpResponsesCollapsed = this.cacheService.getGlobalStateKey("mcpResponsesCollapsed") + const terminalOutputLineLimit = this.cacheService.getGlobalStateKey("terminalOutputLineLimit") + const localClineRulesToggles = this.cacheService.getWorkspaceStateKey("localClineRulesToggles") + const localWindsurfRulesToggles = this.cacheService.getWorkspaceStateKey("localWindsurfRulesToggles") + const localCursorRulesToggles = this.cacheService.getWorkspaceStateKey("localCursorRulesToggles") + const workflowToggles = this.cacheService.getWorkspaceStateKey("workflowToggles") const currentTaskItem = this.task?.taskId ? (taskHistory || []).find((item) => item.id === this.task?.taskId) : undefined const checkpointTrackerErrorMessage = this.task?.taskState.checkpointTrackerErrorMessage @@ -725,7 +718,7 @@ export class Controller { localClineRulesToggles: localClineRulesToggles || {}, localWindsurfRulesToggles: localWindsurfRulesToggles || {}, localCursorRulesToggles: localCursorRulesToggles || {}, - localWorkflowToggles: localWorkflowToggles || {}, + localWorkflowToggles: workflowToggles || {}, globalWorkflowToggles: globalWorkflowToggles || {}, shellIntegrationTimeout, terminalReuseEnabled, @@ -762,37 +755,15 @@ export class Controller { For now we'll store the conversation history in memory, and if we need to store in state directly we'd need to do a manual conversion to ensure proper json stringification. */ - // getApiConversationHistory(): Anthropic.MessageParam[] { - // // const history = (await this.getGlobalState( - // // this.getApiConversationHistoryStateKey() - // // )) as Anthropic.MessageParam[] - // // return history || [] - // return this.apiConversationHistory - // } - - // setApiConversationHistory(history: Anthropic.MessageParam[] | undefined) { - // // await this.updateGlobalState(this.getApiConversationHistoryStateKey(), history) - // this.apiConversationHistory = history || [] - // } - - // addMessageToApiConversationHistory(message: Anthropic.MessageParam): Anthropic.MessageParam[] { - // // const history = await this.getApiConversationHistory() - // // history.push(message) - // // await this.setApiConversationHistory(history) - // // return history - // this.apiConversationHistory.push(message) - // return this.apiConversationHistory - // } - async updateTaskHistory(item: HistoryItem): Promise { - const history = ((await getGlobalState(this.context, "taskHistory")) as HistoryItem[]) || [] + const history = this.cacheService.getGlobalStateKey("taskHistory") const existingItemIndex = history.findIndex((h) => h.id === item.id) if (existingItemIndex !== -1) { history[existingItemIndex] = item } else { history.push(item) } - await updateGlobalState(this.context, "taskHistory", history) + this.cacheService.setGlobalState("taskHistory", history) return history } } diff --git a/src/core/controller/models/refreshBasetenModels.ts b/src/core/controller/models/refreshBasetenModels.ts index b55c90d6..565ffc20 100644 --- a/src/core/controller/models/refreshBasetenModels.ts +++ b/src/core/controller/models/refreshBasetenModels.ts @@ -1,7 +1,6 @@ import { Controller } from ".." import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import { getAllExtensionState } from "../../storage/state" import { basetenModels } from "../../../shared/api" import axios from "axios" import path from "path" @@ -23,8 +22,7 @@ export async function refreshBasetenModels( const basetenModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.basetenModels) // Get the Baseten API key from the controller's state - const { apiConfiguration } = await getAllExtensionState(controller.context) - const basetenApiKey = apiConfiguration?.basetenApiKey + const basetenApiKey = controller.cacheService.getSecretKey("basetenApiKey") let models: Record> = {} try { diff --git a/src/core/controller/models/refreshGroqModels.ts b/src/core/controller/models/refreshGroqModels.ts index 79428e84..ad1649d6 100644 --- a/src/core/controller/models/refreshGroqModels.ts +++ b/src/core/controller/models/refreshGroqModels.ts @@ -1,7 +1,6 @@ import { Controller } from ".." import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import { getAllExtensionState } from "../../storage/state" import { groqModels } from "../../../shared/api" import axios from "axios" import path from "path" @@ -19,9 +18,7 @@ import { telemetryService } from "@/services/posthog/PostHogClientProvider" export async function refreshGroqModels(controller: Controller, request: EmptyRequest): Promise { const groqModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.groqModels) - // Get the Groq API key from the controller's state - const { apiConfiguration } = await getAllExtensionState(controller.context) - const groqApiKey = apiConfiguration?.groqApiKey + const groqApiKey = controller.cacheService.getSecretKey("groqApiKey") let models: Record> = {} try { diff --git a/src/core/controller/models/refreshRequestyModels.ts b/src/core/controller/models/refreshRequestyModels.ts index b4e1e140..3176576a 100644 --- a/src/core/controller/models/refreshRequestyModels.ts +++ b/src/core/controller/models/refreshRequestyModels.ts @@ -2,7 +2,6 @@ import { Controller } from ".." import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" import axios from "axios" -import { getSecret } from "@core/storage/state" /** * Refreshes the Requesty models and returns the updated model list @@ -20,7 +19,7 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ let models: Record = {} try { - const apiKey = await getSecret(controller.context, "requestyApiKey") + const apiKey = controller.cacheService.getSecretKey("requestyApiKey") const headers = { Authorization: `Bearer ${apiKey}`, } diff --git a/src/core/controller/state/resetState.ts b/src/core/controller/state/resetState.ts index 81afd616..fc9bb445 100644 --- a/src/core/controller/state/resetState.ts +++ b/src/core/controller/state/resetState.ts @@ -1,10 +1,10 @@ import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" import { ResetStateRequest } from "@shared/proto/cline/state" -import { resetGlobalState, resetWorkspaceState } from "../../../core/storage/state" import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" -import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { ShowMessageType } from "@/shared/proto/host/window" import { HostProvider } from "@/hosts/host-provider" +import { resetGlobalState, resetWorkspaceState } from "@/core/storage/utils/state-helpers" /** * Resets the extension state to its defaults diff --git a/src/core/controller/state/setWelcomeViewCompleted.ts b/src/core/controller/state/setWelcomeViewCompleted.ts index 7eed95e9..d7b92f24 100644 --- a/src/core/controller/state/setWelcomeViewCompleted.ts +++ b/src/core/controller/state/setWelcomeViewCompleted.ts @@ -1,7 +1,6 @@ import type { BooleanRequest } from "@shared/proto/cline/common" import { Empty } from "@shared/proto/cline/common" import type { Controller } from "../index" -import { updateGlobalState } from "../../storage/state" /** * Sets the welcomeViewCompleted flag to the specified boolean value @@ -12,7 +11,7 @@ import { updateGlobalState } from "../../storage/state" export async function setWelcomeViewCompleted(controller: Controller, request: BooleanRequest): Promise { try { // Update the global state to set welcomeViewCompleted to the requested value - await updateGlobalState(controller.context, "welcomeViewCompleted", request.value) + controller.cacheService.setGlobalState("welcomeViewCompleted", request.value) await controller.postStateToWebview() diff --git a/src/core/controller/state/toggleFavoriteModel.ts b/src/core/controller/state/toggleFavoriteModel.ts index 0279e874..5ca3b09e 100644 --- a/src/core/controller/state/toggleFavoriteModel.ts +++ b/src/core/controller/state/toggleFavoriteModel.ts @@ -1,7 +1,6 @@ import { telemetryService } from "@services/posthog/PostHogClientProvider" import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" -import { updateGlobalState } from "@/core/storage/state" /** * Toggles a model's favorite status diff --git a/src/core/controller/state/updateAutoApprovalSettings.ts b/src/core/controller/state/updateAutoApprovalSettings.ts index 00b24b74..842508ae 100644 --- a/src/core/controller/state/updateAutoApprovalSettings.ts +++ b/src/core/controller/state/updateAutoApprovalSettings.ts @@ -2,7 +2,6 @@ import { Controller } from ".." import { AutoApprovalSettingsRequest } from "@shared/proto/cline/state" import { Empty } from "@shared/proto/cline/common" import { convertProtoToAutoApprovalSettings } from "../../../shared/proto-conversions/models/auto-approval-settings-conversion" -import { updateGlobalState } from "../../../core/storage/state" /** * Updates the auto approval settings @@ -19,7 +18,7 @@ export async function updateAutoApprovalSettings(controller: Controller, request if (incomingVersion > currentVersion) { const settings = convertProtoToAutoApprovalSettings(request) - await updateGlobalState(controller.context, "autoApprovalSettings", settings) + controller.cacheService.setGlobalState("autoApprovalSettings", settings) if (controller.task) { controller.task.updateAutoApprovalSettings(settings) diff --git a/src/core/controller/state/updateDefaultTerminalProfile.ts b/src/core/controller/state/updateDefaultTerminalProfile.ts index fe1f83c0..89da59cd 100644 --- a/src/core/controller/state/updateDefaultTerminalProfile.ts +++ b/src/core/controller/state/updateDefaultTerminalProfile.ts @@ -1,9 +1,8 @@ import { Controller } from "../index" import * as proto from "@/shared/proto" -import { updateGlobalState } from "../../storage/state" import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { ShowMessageType } from "@/shared/proto/host/window" export async function updateDefaultTerminalProfile( controller: Controller, @@ -12,7 +11,7 @@ export async function updateDefaultTerminalProfile( const profileId = request.value // Update the terminal profile in the state - await updateGlobalState(controller.context, "defaultTerminalProfile", profileId) + controller.cacheService.setGlobalState("defaultTerminalProfile", profileId) let closedCount = 0 let busyTerminals: TerminalInfo[] = [] diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index 9b499fdf..3e93d34d 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -1,10 +1,16 @@ import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" -import { PlanActMode, UpdateSettingsRequest } from "@shared/proto/cline/state" +import { + PlanActMode, + UpdateSettingsRequest, + OpenaiReasoningEffort as ProtoOpenaiReasoningEffort, + McpDisplayMode as ProtoMcpDisplayMode, +} from "@shared/proto/cline/state" import { buildApiHandler } from "../../../api" import { convertProtoApiConfigurationToApiConfiguration } from "../../../shared/proto-conversions/state/settings-conversion" import { TelemetrySetting } from "@/shared/TelemetrySetting" import { OpenaiReasoningEffort } from "@/shared/storage/types" +import { McpDisplayMode } from "@/shared/McpDisplayMode" /** * Updates multiple extension settings in a single request @@ -32,27 +38,42 @@ export async function updateSettings(controller: Controller, request: UpdateSett // Update plan/act separate models setting if (request.planActSeparateModelsSetting !== undefined) { - await controller.context.globalState.update("planActSeparateModelsSetting", request.planActSeparateModelsSetting) + controller.cacheService.setGlobalState("planActSeparateModelsSetting", request.planActSeparateModelsSetting) } // Update checkpoints setting if (request.enableCheckpointsSetting !== undefined) { - await controller.context.globalState.update("enableCheckpointsSetting", request.enableCheckpointsSetting) + controller.cacheService.setGlobalState("enableCheckpointsSetting", request.enableCheckpointsSetting) } // Update MCP marketplace setting if (request.mcpMarketplaceEnabled !== undefined) { - await controller.context.globalState.update("mcpMarketplaceEnabled", request.mcpMarketplaceEnabled) + controller.cacheService.setGlobalState("mcpMarketplaceEnabled", request.mcpMarketplaceEnabled) } // Update MCP responses collapsed setting if (request.mcpResponsesCollapsed !== undefined) { - await controller.context.globalState.update("mcpResponsesCollapsed", request.mcpResponsesCollapsed) + controller.cacheService.setGlobalState("mcpResponsesCollapsed", request.mcpResponsesCollapsed) } // Update MCP display mode setting if (request.mcpDisplayMode !== undefined) { - await controller.context.globalState.update("mcpDisplayMode", request.mcpDisplayMode) + // Convert proto enum to string type + let displayMode: McpDisplayMode + switch (request.mcpDisplayMode) { + case ProtoMcpDisplayMode.RICH: + displayMode = "rich" + break + case ProtoMcpDisplayMode.PLAIN: + displayMode = "plain" + break + case ProtoMcpDisplayMode.MARKDOWN: + displayMode = "markdown" + break + default: + throw new Error(`Invalid MCP display mode value: ${request.mcpDisplayMode}`) + } + controller.cacheService.setGlobalState("mcpDisplayMode", displayMode) } if (request.mode !== undefined) { @@ -60,36 +81,53 @@ export async function updateSettings(controller: Controller, request: UpdateSett if (controller.task) { controller.task.updateMode(mode) } - await controller.context.globalState.update("mode", request.mode) + controller.cacheService.setGlobalState("mode", mode) } if (request.openaiReasoningEffort !== undefined) { - if (controller.task) { - controller.task.openaiReasoningEffort = request.openaiReasoningEffort as OpenaiReasoningEffort + // Convert proto enum to string type + let reasoningEffort: OpenaiReasoningEffort + switch (request.openaiReasoningEffort) { + case ProtoOpenaiReasoningEffort.LOW: + reasoningEffort = "low" + break + case ProtoOpenaiReasoningEffort.MEDIUM: + reasoningEffort = "medium" + break + case ProtoOpenaiReasoningEffort.HIGH: + reasoningEffort = "high" + break + default: + throw new Error(`Invalid OpenAI reasoning effort value: ${request.openaiReasoningEffort}`) } - await controller.context.globalState.update("openaiReasoningEffort", request.openaiReasoningEffort) + + if (controller.task) { + controller.task.openaiReasoningEffort = reasoningEffort + } + + controller.cacheService.setGlobalState("openaiReasoningEffort", reasoningEffort) } if (request.preferredLanguage !== undefined) { if (controller.task) { controller.task.preferredLanguage = request.preferredLanguage } - await controller.context.globalState.update("preferredLanguage", request.preferredLanguage) + controller.cacheService.setGlobalState("preferredLanguage", request.preferredLanguage) } // Update terminal timeout setting if (request.shellIntegrationTimeout !== undefined) { - await controller.context.globalState.update("shellIntegrationTimeout", Number(request.shellIntegrationTimeout)) + controller.cacheService.setGlobalState("shellIntegrationTimeout", Number(request.shellIntegrationTimeout)) } // Update terminal reuse setting if (request.terminalReuseEnabled !== undefined) { - await controller.context.globalState.update("terminalReuseEnabled", request.terminalReuseEnabled) + controller.cacheService.setGlobalState("terminalReuseEnabled", request.terminalReuseEnabled) } // Update terminal output line limit if (request.terminalOutputLineLimit !== undefined) { - await controller.context.globalState.update("terminalOutputLineLimit", Number(request.terminalOutputLineLimit)) + controller.cacheService.setGlobalState("terminalOutputLineLimit", Number(request.terminalOutputLineLimit)) } // Update strict plan mode setting @@ -97,7 +135,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett if (controller.task) { controller.task.updateStrictPlanMode(request.strictPlanModeEnabled) } - await controller.context.globalState.update("strictPlanModeEnabled", request.strictPlanModeEnabled) + controller.cacheService.setGlobalState("strictPlanModeEnabled", request.strictPlanModeEnabled) } // Post updated state to webview diff --git a/src/core/controller/state/updateTerminalConnectionTimeout.ts b/src/core/controller/state/updateTerminalConnectionTimeout.ts index 9d91aa0c..9a4eb58e 100644 --- a/src/core/controller/state/updateTerminalConnectionTimeout.ts +++ b/src/core/controller/state/updateTerminalConnectionTimeout.ts @@ -1,6 +1,5 @@ import { Controller } from "../index" import { UpdateTerminalConnectionTimeoutRequest, UpdateTerminalConnectionTimeoutResponse } from "@shared/proto/cline/state" -import { updateGlobalState } from "../../storage/state" export async function updateTerminalConnectionTimeout( controller: Controller, @@ -9,7 +8,7 @@ export async function updateTerminalConnectionTimeout( const timeoutMs = request.timeoutMs // Update the terminal connection timeout setting in the state - await updateGlobalState(controller.context, "shellIntegrationTimeout", timeoutMs) + controller.cacheService.setGlobalState("shellIntegrationTimeout", timeoutMs || 4000) // Broadcast state update to all webviews await controller.postStateToWebview() diff --git a/src/core/controller/state/updateTerminalReuseEnabled.ts b/src/core/controller/state/updateTerminalReuseEnabled.ts index 3934e285..16b9dac9 100644 --- a/src/core/controller/state/updateTerminalReuseEnabled.ts +++ b/src/core/controller/state/updateTerminalReuseEnabled.ts @@ -1,6 +1,5 @@ import { Controller } from "../index" import * as proto from "@/shared/proto" -import { updateGlobalState } from "../../storage/state" export async function updateTerminalReuseEnabled( controller: Controller, @@ -9,7 +8,7 @@ export async function updateTerminalReuseEnabled( const enabled = request.value // Update the terminal reuse setting in the state - await updateGlobalState(controller.context, "terminalReuseEnabled", enabled) + controller.cacheService.setGlobalState("terminalReuseEnabled", enabled) // Broadcast state update to all webviews await controller.postStateToWebview() diff --git a/src/core/controller/task/deleteAllTaskHistory.ts b/src/core/controller/task/deleteAllTaskHistory.ts index c642af57..6267035f 100644 --- a/src/core/controller/task/deleteAllTaskHistory.ts +++ b/src/core/controller/task/deleteAllTaskHistory.ts @@ -2,10 +2,10 @@ import path from "path" import fs from "fs/promises" import { Controller } from ".." import { DeleteAllTaskHistoryCount } from "@shared/proto/cline/task" -import { getGlobalState, updateGlobalState } from "../../storage/state" import { fileExistsAtPath } from "../../../utils/fs" import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" import { HostProvider } from "@/hosts/host-provider" +import { HistoryItem } from "@/shared/HistoryItem" /** * Deletes all task history, with an option to preserve favorites @@ -19,7 +19,7 @@ export async function deleteAllTaskHistory(controller: Controller): Promise 0) { - await updateGlobalState(controller.context, "taskHistory", favoritedTasks) + controller.cacheService.setGlobalState("taskHistory", favoritedTasks) // Delete non-favorited task directories const preserveTaskIds = favoritedTasks.map((task) => task.id) @@ -88,7 +88,7 @@ export async function deleteAllTaskHistory(controller: Controller): Promise item.id === id) // We need to initialize the task before returning data diff --git a/src/core/controller/task/toggleTaskFavorite.ts b/src/core/controller/task/toggleTaskFavorite.ts index c1d761c1..c59385a6 100644 --- a/src/core/controller/task/toggleTaskFavorite.ts +++ b/src/core/controller/task/toggleTaskFavorite.ts @@ -1,3 +1,4 @@ +import { HistoryItem } from "@/shared/HistoryItem" import { Controller } from "../" import { Empty } from "@shared/proto/cline/common" import { TaskFavoriteRequest } from "@shared/proto/cline/task" @@ -12,7 +13,7 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa try { // Update in-memory state only try { - const history = ((await controller.context.globalState.get("taskHistory")) as any[]) || [] + const history = controller.cacheService.getGlobalStateKey("taskHistory") const taskIndex = history.findIndex((item) => item.id === request.taskId) @@ -28,7 +29,7 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa // Update global state and wait for it to complete try { - await controller.context.globalState.update("taskHistory", updatedHistory) + controller.cacheService.setGlobalState("taskHistory", updatedHistory) } catch (stateErr) { console.error("Error updating global state:", stateErr) } diff --git a/src/core/controller/ui/initializeWebview.ts b/src/core/controller/ui/initializeWebview.ts index 8d05f031..93d97de6 100644 --- a/src/core/controller/ui/initializeWebview.ts +++ b/src/core/controller/ui/initializeWebview.ts @@ -1,7 +1,6 @@ import type { Controller } from "../index" import { EmptyRequest, Empty } from "@shared/proto/cline/common" -import { getAllExtensionState, getGlobalState, updateGlobalState } from "../../storage/state" import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels" import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog" import { telemetryService } from "@/services/posthog/PostHogClientProvider" @@ -31,7 +30,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe if (response && response.models) { // Update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there) const apiConfiguration = controller.cacheService.getApiConfiguration() - const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context) + const planActSeparateModelsSetting = controller.cacheService.getGlobalStateKey("planActSeparateModelsSetting") const currentMode = await controller.getCurrentMode() if (planActSeparateModelsSetting) { @@ -77,7 +76,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe if (response && response.models) { // Update model info in state for Groq (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there) const apiConfiguration = controller.cacheService.getApiConfiguration() - const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context) + const planActSeparateModelsSetting = controller.cacheService.getGlobalStateKey("planActSeparateModelsSetting") const currentMode = await controller.getCurrentMode() if (planActSeparateModelsSetting) { @@ -122,7 +121,9 @@ export async function initializeWebview(controller: Controller, request: EmptyRe refreshBasetenModels(controller, EmptyRequest.create()).then(async (response) => { if (response && response.models) { // Update model info in state for Baseten (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there) - const { apiConfiguration, planActSeparateModelsSetting } = await getAllExtensionState(controller.context) + const apiConfiguration = controller.cacheService.getApiConfiguration() + const planActSeparateModelsSetting = controller.cacheService.getGlobalStateKey("planActSeparateModelsSetting") + const currentMode = await controller.getCurrentMode() if (planActSeparateModelsSetting) { @@ -132,7 +133,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe const modelId = apiConfiguration[modelIdField] if (modelId && response.models[modelId]) { - await updateGlobalState(controller.context, modelInfoField, response.models[modelId]) + controller.cacheService.setGlobalState(modelInfoField, response.models[modelId]) await controller.postStateToWebview() } } else { @@ -142,12 +143,12 @@ export async function initializeWebview(controller: Controller, request: EmptyRe // Update plan mode model info if we have a model ID if (planModelId && response.models[planModelId]) { - await updateGlobalState(controller.context, "planModeBasetenModelInfo", response.models[planModelId]) + controller.cacheService.setGlobalState("planModeBasetenModelInfo", response.models[planModelId]) } // Update act mode model info if we have a model ID if (actModelId && response.models[actModelId]) { - await updateGlobalState(controller.context, "actModeBasetenModelInfo", response.models[actModelId]) + controller.cacheService.setGlobalState("actModeBasetenModelInfo", response.models[actModelId]) } // Post state update if we updated any model info @@ -163,12 +164,12 @@ export async function initializeWebview(controller: Controller, request: EmptyRe // (see normalizeApiConfiguration > openrouter) // Prefetch marketplace and OpenRouter models - // Send cached MCP marketplace catalog if available - getGlobalState(controller.context, "mcpMarketplaceCatalog").then((mcpMarketplaceCatalog) => { - if (mcpMarketplaceCatalog) { - sendMcpMarketplaceCatalogEvent(mcpMarketplaceCatalog as McpMarketplaceCatalog) - } - }) + // Send stored MCP marketplace catalog if available + const mcpMarketplaceCatalog = controller.cacheService.getGlobalStateKey("mcpMarketplaceCatalog") + + if (mcpMarketplaceCatalog) { + sendMcpMarketplaceCatalogEvent(mcpMarketplaceCatalog as McpMarketplaceCatalog) + } // Silently refresh MCP marketplace catalog controller.silentlyRefreshMcpMarketplace() diff --git a/src/core/controller/ui/onDidShowAnnouncement.ts b/src/core/controller/ui/onDidShowAnnouncement.ts index dce4d533..de8d2ace 100644 --- a/src/core/controller/ui/onDidShowAnnouncement.ts +++ b/src/core/controller/ui/onDidShowAnnouncement.ts @@ -1,7 +1,6 @@ import type { EmptyRequest } from "@shared/proto/cline/common" import { Boolean } from "@shared/proto/cline/common" import type { Controller } from "../index" -import { updateGlobalState } from "../../storage/state" import { getLatestAnnouncementId } from "@/utils/announcements" /** @@ -15,7 +14,7 @@ export async function onDidShowAnnouncement(controller: Controller, _request: Em try { const latestAnnouncementId = getLatestAnnouncementId(controller.context) // Update the lastShownAnnouncementId to the current latestAnnouncementId - await updateGlobalState(controller.context, "lastShownAnnouncementId", latestAnnouncementId) + controller.cacheService.setGlobalState("lastShownAnnouncementId", latestAnnouncementId) return Boolean.create({ value: false }) } catch (error) { console.error("Failed to acknowledge announcement:", error) diff --git a/src/core/storage/CacheService.ts b/src/core/storage/CacheService.ts index 665f4e97..7094fcaf 100644 --- a/src/core/storage/CacheService.ts +++ b/src/core/storage/CacheService.ts @@ -1,8 +1,9 @@ import { ApiConfiguration } from "@shared/api" -import { updateGlobalState, updateWorkspaceState, getAllExtensionState, storeSecret } from "./state" -import { SecretKey, GlobalStateKey, LocalStateKey } from "./state-keys" +import { SecretKey, GlobalStateKey, LocalStateKey, GlobalState, Secrets, LocalState } from "./state-keys" import { CACHE_SERVICE_NOT_INITIALIZED } from "./error-messages" import type { ExtensionContext } from "vscode" +import { readStateFromDisk } from "./utils/state-helpers" +import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@/shared/AutoApprovalSettings" /** * Interface for persistence error event data @@ -16,9 +17,9 @@ export interface PersistenceErrorEvent { * Provides immediate reads/writes with async disk persistence */ export class CacheService { - private globalStateCache: Map = new Map() - private secretsCache: Map = new Map() - private workspaceStateCache: Map = new Map() + private globalStateCache: GlobalState = {} as GlobalState + private secretsCache: Secrets = {} as Secrets + private workspaceStateCache: LocalState = {} as LocalState private context: ExtensionContext private isInitialized = false @@ -41,16 +42,16 @@ export class CacheService { */ async initialize(): Promise { try { - // Load API configuration and populate cache with component keys - const { apiConfiguration } = await getAllExtensionState(this.context) - if (apiConfiguration) { - // Populate the caches with the API configuration component keys + // Load all extension state from disk + const state = await readStateFromDisk(this.context) + + if (state) { + // Populate the caches with all extension state fields // Use populate method to avoid triggering persistence during initialization - this.populateApiConfigurationCache(apiConfiguration) + this.populateCache(state) } this.isInitialized = true - console.log("CacheService initialized successfully") } catch (error) { console.error("Failed to initialize CacheService:", error) throw error @@ -60,13 +61,13 @@ export class CacheService { /** * Set method for global state keys - updates cache immediately and schedules debounced persistence */ - setGlobalState(key: GlobalStateKey, value: T): void { + setGlobalState(key: K, value: GlobalState[K]): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } // Update cache immediately for instant access - this.globalStateCache.set(key, value) + this.globalStateCache[key] = value // Add to pending persistence set and schedule debounced write this.pendingGlobalState.add(key) @@ -76,14 +77,17 @@ export class CacheService { /** * Batch set method for global state keys - updates cache immediately and schedules debounced persistence */ - setGlobalStateBatch(updates: Partial>): void { + setGlobalStateBatch(updates: Partial): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } - // Update cache immediately for all keys - Object.entries(updates).forEach(([key, value]) => { - this.globalStateCache.set(key as GlobalStateKey, value) + // Update cache in one go + // Using object.assign to because typescript is not able to infer the type of the updates object when using Object.entries + Object.assign(this.globalStateCache, updates) + + // Then track the keys for persistence + Object.keys(updates).forEach((key) => { this.pendingGlobalState.add(key as GlobalStateKey) }) @@ -94,13 +98,13 @@ export class CacheService { /** * Set method for secret keys - updates cache immediately and schedules debounced persistence */ - setSecret(key: SecretKey, value: string | undefined): void { + setSecret(key: K, value: Secrets[K]): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } // Update cache immediately for instant access - this.secretsCache.set(key, value) + this.secretsCache[key] = value // Add to pending persistence set and schedule debounced write this.pendingSecrets.add(key) @@ -110,14 +114,14 @@ export class CacheService { /** * Batch set method for secret keys - updates cache immediately and schedules debounced persistence */ - setSecretsBatch(updates: Partial>): void { + setSecretsBatch(updates: Partial): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } // Update cache immediately for all keys Object.entries(updates).forEach(([key, value]) => { - this.secretsCache.set(key as SecretKey, value) + this.secretsCache[key as keyof Secrets] = value this.pendingSecrets.add(key as SecretKey) }) @@ -128,13 +132,13 @@ export class CacheService { /** * Set method for workspace state keys - updates cache immediately and schedules debounced persistence */ - setWorkspaceState(key: LocalStateKey, value: T): void { + setWorkspaceState(key: K, value: LocalState[K]): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } // Update cache immediately for instant access - this.workspaceStateCache.set(key, value) + this.workspaceStateCache[key] = value // Add to pending persistence set and schedule debounced write this.pendingWorkspaceState.add(key) @@ -144,14 +148,14 @@ export class CacheService { /** * Batch set method for workspace state keys - updates cache immediately and schedules debounced persistence */ - setWorkspaceStateBatch(updates: Partial>): void { + setWorkspaceStateBatch(updates: Partial): void { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } // Update cache immediately for all keys Object.entries(updates).forEach(([key, value]) => { - this.workspaceStateCache.set(key as LocalStateKey, value) + this.workspaceStateCache[key as keyof LocalState] = value this.pendingWorkspaceState.add(key as LocalStateKey) }) @@ -241,6 +245,7 @@ export class CacheService { claudeCodePath, basetenApiKey, huggingFaceApiKey, + huaweiCloudMaasApiKey, requestTimeoutMs, // Plan mode configurations planModeApiProvider, @@ -269,6 +274,8 @@ export class CacheService { planModeBasetenModelInfo, planModeHuggingFaceModelId, planModeHuggingFaceModelInfo, + planModeHuaweiCloudMaasModelId, + planModeHuaweiCloudMaasModelInfo, // Act mode configurations actModeApiProvider, actModeApiModelId, @@ -296,6 +303,8 @@ export class CacheService { actModeBasetenModelInfo, actModeHuggingFaceModelId, actModeHuggingFaceModelInfo, + actModeHuaweiCloudMaasModelId, + actModeHuaweiCloudMaasModelInfo, } = apiConfiguration // Batch update global state keys @@ -327,6 +336,8 @@ export class CacheService { planModeBasetenModelInfo, planModeHuggingFaceModelId, planModeHuggingFaceModelInfo, + planModeHuaweiCloudMaasModelId, + planModeHuaweiCloudMaasModelInfo, // Act mode configuration updates actModeApiProvider, @@ -355,6 +366,8 @@ export class CacheService { actModeBasetenModelInfo, actModeHuggingFaceModelId, actModeHuggingFaceModelInfo, + actModeHuaweiCloudMaasModelId, + actModeHuaweiCloudMaasModelInfo, // Global state updates awsRegion, @@ -422,37 +435,38 @@ export class CacheService { sapAiCoreClientSecret, basetenApiKey, huggingFaceApiKey, + huaweiCloudMaasApiKey, }) } /** * Get method for global state keys - reads from in-memory cache */ - getGlobalStateKey(key: GlobalStateKey): T | undefined { + getGlobalStateKey(key: K): GlobalState[K] { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } - return this.globalStateCache.get(key) as T | undefined + return this.globalStateCache[key] } /** * Get method for secret keys - reads from in-memory cache */ - getSecretKey(key: SecretKey): string | undefined { + getSecretKey(key: K): Secrets[K] { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } - return this.secretsCache.get(key) + return this.secretsCache[key] } /** * Get method for workspace state keys - reads from in-memory cache */ - getWorkspaceStateKey(key: LocalStateKey): T | undefined { + getWorkspaceStateKey(key: K): LocalState[K] { if (!this.isInitialized) { throw new Error(CACHE_SERVICE_NOT_INITIALIZED) } - return this.workspaceStateCache.get(key) as T | undefined + return this.workspaceStateCache[key] } /** @@ -480,9 +494,9 @@ export class CacheService { this.pendingSecrets.clear() this.pendingWorkspaceState.clear() - this.globalStateCache.clear() - this.secretsCache.clear() - this.workspaceStateCache.clear() + this.globalStateCache = {} as GlobalState + this.secretsCache = {} as Secrets + this.workspaceStateCache = {} as LocalState this.isInitialized = false } @@ -527,7 +541,7 @@ export class CacheService { try { await Promise.all( Array.from(keys).map((key) => { - const value = this.globalStateCache.get(key) + const value = this.globalStateCache[key] return this.context.globalState.update(key, value) }), ) @@ -544,7 +558,7 @@ export class CacheService { try { await Promise.all( Array.from(keys).map((key) => { - const value = this.secretsCache.get(key) + const value = this.secretsCache[key] if (value) { return this.context.secrets.store(key, value) } else { @@ -565,7 +579,7 @@ export class CacheService { try { await Promise.all( Array.from(keys).map((key) => { - const value = this.workspaceStateCache.get(key) + const value = this.workspaceStateCache[key] return this.context.workspaceState.update(key, value) }), ) @@ -576,10 +590,11 @@ export class CacheService { } /** - * Private method to populate API configuration cache without triggering persistence + * Private method to populate cache with all extension state without triggering persistence * Used during initialization */ - private populateApiConfigurationCache(apiConfiguration: ApiConfiguration): void { + private populateCache(state: any): void { + // Extract API configuration fields const { apiKey, openRouterApiKey, @@ -641,6 +656,7 @@ export class CacheService { sapAiResourceGroup, claudeCodePath, huggingFaceApiKey, + huaweiCloudMaasApiKey, requestTimeoutMs, // Plan mode configurations planModeApiProvider, @@ -669,6 +685,8 @@ export class CacheService { planModeBasetenModelInfo, planModeHuggingFaceModelId, planModeHuggingFaceModelInfo, + planModeHuaweiCloudMaasModelId, + planModeHuaweiCloudMaasModelInfo, // Act mode configurations actModeApiProvider, actModeApiModelId, @@ -696,10 +714,36 @@ export class CacheService { actModeBasetenModelInfo, actModeHuggingFaceModelId, actModeHuggingFaceModelInfo, - } = apiConfiguration + actModeHuaweiCloudMaasModelId, + actModeHuaweiCloudMaasModelInfo, + } = state.apiConfiguration || {} // Directly populate global state cache without triggering persistence - const globalStateUpdates = { + const globalStateFields = { + // Extension state fields + strictPlanModeEnabled: state.strictPlanModeEnabled, + isNewUser: state.isNewUser, + welcomeViewCompleted: state.welcomeViewCompleted, + autoApprovalSettings: state.autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, + globalClineRulesToggles: state.globalClineRulesToggles, + browserSettings: state.browserSettings, + preferredLanguage: state.preferredLanguage, + openaiReasoningEffort: state.openaiReasoningEffort, + mode: state.mode, + userInfo: state.userInfo, + mcpMarketplaceEnabled: state.mcpMarketplaceEnabled, + mcpDisplayMode: state.mcpDisplayMode, + mcpResponsesCollapsed: state.mcpResponsesCollapsed, + telemetrySetting: state.telemetrySetting, + planActSeparateModelsSetting: state.planActSeparateModelsSetting, + enableCheckpointsSetting: state.enableCheckpointsSetting, + shellIntegrationTimeout: state.shellIntegrationTimeout, + terminalReuseEnabled: state.terminalReuseEnabled, + terminalOutputLineLimit: state.terminalOutputLineLimit, + defaultTerminalProfile: state.defaultTerminalProfile, + globalWorkflowToggles: state.globalWorkflowToggles, + taskHistory: state.taskHistory, + // Plan mode configuration updates planModeApiProvider, planModeApiModelId, @@ -727,6 +771,8 @@ export class CacheService { planModeBasetenModelInfo, planModeHuggingFaceModelId, planModeHuggingFaceModelInfo, + planModeHuaweiCloudMaasModelId, + planModeHuaweiCloudMaasModelInfo, // Act mode configuration updates actModeApiProvider, @@ -755,8 +801,10 @@ export class CacheService { actModeBasetenModelInfo, actModeHuggingFaceModelId, actModeHuggingFaceModelInfo, + actModeHuaweiCloudMaasModelId, + actModeHuaweiCloudMaasModelInfo, - // Global state updates + // API configuration global state updates awsRegion, awsUseCrossRegionInference, awsBedrockUsePromptCache, @@ -791,12 +839,10 @@ export class CacheService { } // Populate global state cache directly - Object.entries(globalStateUpdates).forEach(([key, value]) => { - this.globalStateCache.set(key as GlobalStateKey, value) - }) + Object.assign(this.globalStateCache, globalStateFields) // Directly populate secrets cache without triggering persistence - const secretsUpdates = { + const secretsFields = { apiKey, openRouterApiKey, clineAccountId, @@ -827,12 +873,21 @@ export class CacheService { sapAiCoreClientId, sapAiCoreClientSecret, huggingFaceApiKey, + huaweiCloudMaasApiKey, } // Populate secrets cache directly - Object.entries(secretsUpdates).forEach(([key, value]) => { - this.secretsCache.set(key as SecretKey, value) - }) + Object.assign(this.secretsCache, secretsFields) + + // Populate workspace state cache directly + const workspaceStateFields = { + localClineRulesToggles: state.localClineRulesToggles, + localWindsurfRulesToggles: state.localWindsurfRulesToggles, + localCursorRulesToggles: state.localCursorRulesToggles, + workflowToggles: state.localWorkflowToggles, // Note: key name is "workflowToggles" in LocalStateKey + } + + Object.assign(this.workspaceStateCache, workspaceStateFields) } /** @@ -841,125 +896,130 @@ export class CacheService { private constructApiConfigurationFromCache(): ApiConfiguration { return { // Secrets - apiKey: this.secretsCache.get("apiKey"), - openRouterApiKey: this.secretsCache.get("openRouterApiKey"), - clineAccountId: this.secretsCache.get("clineAccountId"), - awsAccessKey: this.secretsCache.get("awsAccessKey"), - awsSecretKey: this.secretsCache.get("awsSecretKey"), - awsSessionToken: this.secretsCache.get("awsSessionToken"), - awsBedrockApiKey: this.secretsCache.get("awsBedrockApiKey"), - openAiApiKey: this.secretsCache.get("openAiApiKey"), - ollamaApiKey: this.secretsCache.get("ollamaApiKey"), - geminiApiKey: this.secretsCache.get("geminiApiKey"), - openAiNativeApiKey: this.secretsCache.get("openAiNativeApiKey"), - deepSeekApiKey: this.secretsCache.get("deepSeekApiKey"), - requestyApiKey: this.secretsCache.get("requestyApiKey"), - togetherApiKey: this.secretsCache.get("togetherApiKey"), - qwenApiKey: this.secretsCache.get("qwenApiKey"), - doubaoApiKey: this.secretsCache.get("doubaoApiKey"), - mistralApiKey: this.secretsCache.get("mistralApiKey"), - liteLlmApiKey: this.secretsCache.get("liteLlmApiKey"), - fireworksApiKey: this.secretsCache.get("fireworksApiKey"), - asksageApiKey: this.secretsCache.get("asksageApiKey"), - xaiApiKey: this.secretsCache.get("xaiApiKey"), - sambanovaApiKey: this.secretsCache.get("sambanovaApiKey"), - cerebrasApiKey: this.secretsCache.get("cerebrasApiKey"), - groqApiKey: this.secretsCache.get("groqApiKey"), - basetenApiKey: this.secretsCache.get("basetenApiKey"), - moonshotApiKey: this.secretsCache.get("moonshotApiKey"), - nebiusApiKey: this.secretsCache.get("nebiusApiKey"), - sapAiCoreClientId: this.secretsCache.get("sapAiCoreClientId"), - sapAiCoreClientSecret: this.secretsCache.get("sapAiCoreClientSecret"), - huggingFaceApiKey: this.secretsCache.get("huggingFaceApiKey"), + apiKey: this.secretsCache["apiKey"], + openRouterApiKey: this.secretsCache["openRouterApiKey"], + clineAccountId: this.secretsCache["clineAccountId"], + awsAccessKey: this.secretsCache["awsAccessKey"], + awsSecretKey: this.secretsCache["awsSecretKey"], + awsSessionToken: this.secretsCache["awsSessionToken"], + awsBedrockApiKey: this.secretsCache["awsBedrockApiKey"], + openAiApiKey: this.secretsCache["openAiApiKey"], + ollamaApiKey: this.secretsCache["ollamaApiKey"], + geminiApiKey: this.secretsCache["geminiApiKey"], + openAiNativeApiKey: this.secretsCache["openAiNativeApiKey"], + deepSeekApiKey: this.secretsCache["deepSeekApiKey"], + requestyApiKey: this.secretsCache["requestyApiKey"], + togetherApiKey: this.secretsCache["togetherApiKey"], + qwenApiKey: this.secretsCache["qwenApiKey"], + doubaoApiKey: this.secretsCache["doubaoApiKey"], + mistralApiKey: this.secretsCache["mistralApiKey"], + liteLlmApiKey: this.secretsCache["liteLlmApiKey"], + fireworksApiKey: this.secretsCache["fireworksApiKey"], + asksageApiKey: this.secretsCache["asksageApiKey"], + xaiApiKey: this.secretsCache["xaiApiKey"], + sambanovaApiKey: this.secretsCache["sambanovaApiKey"], + cerebrasApiKey: this.secretsCache["cerebrasApiKey"], + groqApiKey: this.secretsCache["groqApiKey"], + basetenApiKey: this.secretsCache["basetenApiKey"], + moonshotApiKey: this.secretsCache["moonshotApiKey"], + nebiusApiKey: this.secretsCache["nebiusApiKey"], + sapAiCoreClientId: this.secretsCache["sapAiCoreClientId"], + sapAiCoreClientSecret: this.secretsCache["sapAiCoreClientSecret"], + huggingFaceApiKey: this.secretsCache["huggingFaceApiKey"], + huaweiCloudMaasApiKey: this.secretsCache["huaweiCloudMaasApiKey"], // Global state - awsRegion: this.globalStateCache.get("awsRegion"), - awsUseCrossRegionInference: this.globalStateCache.get("awsUseCrossRegionInference"), - awsBedrockUsePromptCache: this.globalStateCache.get("awsBedrockUsePromptCache"), - awsBedrockEndpoint: this.globalStateCache.get("awsBedrockEndpoint"), - awsProfile: this.globalStateCache.get("awsProfile"), - awsUseProfile: this.globalStateCache.get("awsUseProfile"), - awsAuthentication: this.globalStateCache.get("awsAuthentication"), - vertexProjectId: this.globalStateCache.get("vertexProjectId"), - vertexRegion: this.globalStateCache.get("vertexRegion"), - openAiBaseUrl: this.globalStateCache.get("openAiBaseUrl"), - openAiHeaders: this.globalStateCache.get("openAiHeaders") || {}, - ollamaBaseUrl: this.globalStateCache.get("ollamaBaseUrl"), - ollamaApiOptionsCtxNum: this.globalStateCache.get("ollamaApiOptionsCtxNum"), - lmStudioBaseUrl: this.globalStateCache.get("lmStudioBaseUrl"), - anthropicBaseUrl: this.globalStateCache.get("anthropicBaseUrl"), - geminiBaseUrl: this.globalStateCache.get("geminiBaseUrl"), - azureApiVersion: this.globalStateCache.get("azureApiVersion"), - openRouterProviderSorting: this.globalStateCache.get("openRouterProviderSorting"), - liteLlmBaseUrl: this.globalStateCache.get("liteLlmBaseUrl"), - liteLlmUsePromptCache: this.globalStateCache.get("liteLlmUsePromptCache"), - qwenApiLine: this.globalStateCache.get("qwenApiLine"), - moonshotApiLine: this.globalStateCache.get("moonshotApiLine"), - asksageApiUrl: this.globalStateCache.get("asksageApiUrl"), - favoritedModelIds: this.globalStateCache.get("favoritedModelIds"), - requestTimeoutMs: this.globalStateCache.get("requestTimeoutMs"), - fireworksModelMaxCompletionTokens: this.globalStateCache.get("fireworksModelMaxCompletionTokens"), - fireworksModelMaxTokens: this.globalStateCache.get("fireworksModelMaxTokens"), - sapAiCoreBaseUrl: this.globalStateCache.get("sapAiCoreBaseUrl"), - sapAiCoreTokenUrl: this.globalStateCache.get("sapAiCoreTokenUrl"), - sapAiResourceGroup: this.globalStateCache.get("sapAiResourceGroup"), - claudeCodePath: this.globalStateCache.get("claudeCodePath"), + awsRegion: this.globalStateCache["awsRegion"], + awsUseCrossRegionInference: this.globalStateCache["awsUseCrossRegionInference"], + awsBedrockUsePromptCache: this.globalStateCache["awsBedrockUsePromptCache"], + awsBedrockEndpoint: this.globalStateCache["awsBedrockEndpoint"], + awsProfile: this.globalStateCache["awsProfile"], + awsUseProfile: this.globalStateCache["awsUseProfile"], + awsAuthentication: this.globalStateCache["awsAuthentication"], + vertexProjectId: this.globalStateCache["vertexProjectId"], + vertexRegion: this.globalStateCache["vertexRegion"], + openAiBaseUrl: this.globalStateCache["openAiBaseUrl"], + openAiHeaders: this.globalStateCache["openAiHeaders"] || {}, + ollamaBaseUrl: this.globalStateCache["ollamaBaseUrl"], + ollamaApiOptionsCtxNum: this.globalStateCache["ollamaApiOptionsCtxNum"], + lmStudioBaseUrl: this.globalStateCache["lmStudioBaseUrl"], + anthropicBaseUrl: this.globalStateCache["anthropicBaseUrl"], + geminiBaseUrl: this.globalStateCache["geminiBaseUrl"], + azureApiVersion: this.globalStateCache["azureApiVersion"], + openRouterProviderSorting: this.globalStateCache["openRouterProviderSorting"], + liteLlmBaseUrl: this.globalStateCache["liteLlmBaseUrl"], + liteLlmUsePromptCache: this.globalStateCache["liteLlmUsePromptCache"], + qwenApiLine: this.globalStateCache["qwenApiLine"], + moonshotApiLine: this.globalStateCache["moonshotApiLine"], + asksageApiUrl: this.globalStateCache["asksageApiUrl"], + favoritedModelIds: this.globalStateCache["favoritedModelIds"], + requestTimeoutMs: this.globalStateCache["requestTimeoutMs"], + fireworksModelMaxCompletionTokens: this.globalStateCache["fireworksModelMaxCompletionTokens"], + fireworksModelMaxTokens: this.globalStateCache["fireworksModelMaxTokens"], + sapAiCoreBaseUrl: this.globalStateCache["sapAiCoreBaseUrl"], + sapAiCoreTokenUrl: this.globalStateCache["sapAiCoreTokenUrl"], + sapAiResourceGroup: this.globalStateCache["sapAiResourceGroup"], + claudeCodePath: this.globalStateCache["claudeCodePath"], // Plan mode configurations - planModeApiProvider: this.globalStateCache.get("planModeApiProvider"), - planModeApiModelId: this.globalStateCache.get("planModeApiModelId"), - planModeThinkingBudgetTokens: this.globalStateCache.get("planModeThinkingBudgetTokens"), - planModeReasoningEffort: this.globalStateCache.get("planModeReasoningEffort"), - planModeVsCodeLmModelSelector: this.globalStateCache.get("planModeVsCodeLmModelSelector"), - planModeAwsBedrockCustomSelected: this.globalStateCache.get("planModeAwsBedrockCustomSelected"), - planModeAwsBedrockCustomModelBaseId: this.globalStateCache.get("planModeAwsBedrockCustomModelBaseId"), - planModeOpenRouterModelId: this.globalStateCache.get("planModeOpenRouterModelId"), - planModeOpenRouterModelInfo: this.globalStateCache.get("planModeOpenRouterModelInfo"), - planModeOpenAiModelId: this.globalStateCache.get("planModeOpenAiModelId"), - planModeOpenAiModelInfo: this.globalStateCache.get("planModeOpenAiModelInfo"), - planModeOllamaModelId: this.globalStateCache.get("planModeOllamaModelId"), - planModeLmStudioModelId: this.globalStateCache.get("planModeLmStudioModelId"), - planModeLiteLlmModelId: this.globalStateCache.get("planModeLiteLlmModelId"), - planModeLiteLlmModelInfo: this.globalStateCache.get("planModeLiteLlmModelInfo"), - planModeRequestyModelId: this.globalStateCache.get("planModeRequestyModelId"), - planModeRequestyModelInfo: this.globalStateCache.get("planModeRequestyModelInfo"), - planModeTogetherModelId: this.globalStateCache.get("planModeTogetherModelId"), - planModeFireworksModelId: this.globalStateCache.get("planModeFireworksModelId"), - planModeSapAiCoreModelId: this.globalStateCache.get("planModeSapAiCoreModelId"), - planModeGroqModelId: this.globalStateCache.get("planModeGroqModelId"), - planModeGroqModelInfo: this.globalStateCache.get("planModeGroqModelInfo"), - planModeBasetenModelId: this.globalStateCache.get("planModeBasetenModelId"), - planModeBasetenModelInfo: this.globalStateCache.get("planModeBasetenModelInfo"), - planModeHuggingFaceModelId: this.globalStateCache.get("planModeHuggingFaceModelId"), - planModeHuggingFaceModelInfo: this.globalStateCache.get("planModeHuggingFaceModelInfo"), + planModeApiProvider: this.globalStateCache["planModeApiProvider"], + planModeApiModelId: this.globalStateCache["planModeApiModelId"], + planModeThinkingBudgetTokens: this.globalStateCache["planModeThinkingBudgetTokens"], + planModeReasoningEffort: this.globalStateCache["planModeReasoningEffort"], + planModeVsCodeLmModelSelector: this.globalStateCache["planModeVsCodeLmModelSelector"], + planModeAwsBedrockCustomSelected: this.globalStateCache["planModeAwsBedrockCustomSelected"], + planModeAwsBedrockCustomModelBaseId: this.globalStateCache["planModeAwsBedrockCustomModelBaseId"], + planModeOpenRouterModelId: this.globalStateCache["planModeOpenRouterModelId"], + planModeOpenRouterModelInfo: this.globalStateCache["planModeOpenRouterModelInfo"], + planModeOpenAiModelId: this.globalStateCache["planModeOpenAiModelId"], + planModeOpenAiModelInfo: this.globalStateCache["planModeOpenAiModelInfo"], + planModeOllamaModelId: this.globalStateCache["planModeOllamaModelId"], + planModeLmStudioModelId: this.globalStateCache["planModeLmStudioModelId"], + planModeLiteLlmModelId: this.globalStateCache["planModeLiteLlmModelId"], + planModeLiteLlmModelInfo: this.globalStateCache["planModeLiteLlmModelInfo"], + planModeRequestyModelId: this.globalStateCache["planModeRequestyModelId"], + planModeRequestyModelInfo: this.globalStateCache["planModeRequestyModelInfo"], + planModeTogetherModelId: this.globalStateCache["planModeTogetherModelId"], + planModeFireworksModelId: this.globalStateCache["planModeFireworksModelId"], + planModeSapAiCoreModelId: this.globalStateCache["planModeSapAiCoreModelId"], + planModeGroqModelId: this.globalStateCache["planModeGroqModelId"], + planModeGroqModelInfo: this.globalStateCache["planModeGroqModelInfo"], + planModeBasetenModelId: this.globalStateCache["planModeBasetenModelId"], + planModeBasetenModelInfo: this.globalStateCache["planModeBasetenModelInfo"], + planModeHuggingFaceModelId: this.globalStateCache["planModeHuggingFaceModelId"], + planModeHuggingFaceModelInfo: this.globalStateCache["planModeHuggingFaceModelInfo"], + planModeHuaweiCloudMaasModelId: this.globalStateCache["planModeHuaweiCloudMaasModelId"], + planModeHuaweiCloudMaasModelInfo: this.globalStateCache["planModeHuaweiCloudMaasModelInfo"], // Act mode configurations - actModeApiProvider: this.globalStateCache.get("actModeApiProvider"), - actModeApiModelId: this.globalStateCache.get("actModeApiModelId"), - actModeThinkingBudgetTokens: this.globalStateCache.get("actModeThinkingBudgetTokens"), - actModeReasoningEffort: this.globalStateCache.get("actModeReasoningEffort"), - actModeVsCodeLmModelSelector: this.globalStateCache.get("actModeVsCodeLmModelSelector"), - actModeAwsBedrockCustomSelected: this.globalStateCache.get("actModeAwsBedrockCustomSelected"), - actModeAwsBedrockCustomModelBaseId: this.globalStateCache.get("actModeAwsBedrockCustomModelBaseId"), - actModeOpenRouterModelId: this.globalStateCache.get("actModeOpenRouterModelId"), - actModeOpenRouterModelInfo: this.globalStateCache.get("actModeOpenRouterModelInfo"), - actModeOpenAiModelId: this.globalStateCache.get("actModeOpenAiModelId"), - actModeOpenAiModelInfo: this.globalStateCache.get("actModeOpenAiModelInfo"), - actModeOllamaModelId: this.globalStateCache.get("actModeOllamaModelId"), - actModeLmStudioModelId: this.globalStateCache.get("actModeLmStudioModelId"), - actModeLiteLlmModelId: this.globalStateCache.get("actModeLiteLlmModelId"), - actModeLiteLlmModelInfo: this.globalStateCache.get("actModeLiteLlmModelInfo"), - actModeRequestyModelId: this.globalStateCache.get("actModeRequestyModelId"), - actModeRequestyModelInfo: this.globalStateCache.get("actModeRequestyModelInfo"), - actModeTogetherModelId: this.globalStateCache.get("actModeTogetherModelId"), - actModeFireworksModelId: this.globalStateCache.get("actModeFireworksModelId"), - actModeSapAiCoreModelId: this.globalStateCache.get("actModeSapAiCoreModelId"), - actModeGroqModelId: this.globalStateCache.get("actModeGroqModelId"), - actModeGroqModelInfo: this.globalStateCache.get("actModeGroqModelInfo"), - actModeBasetenModelId: this.globalStateCache.get("actModeBasetenModelId"), - actModeBasetenModelInfo: this.globalStateCache.get("actModeBasetenModelInfo"), - actModeHuggingFaceModelId: this.globalStateCache.get("actModeHuggingFaceModelId"), - actModeHuggingFaceModelInfo: this.globalStateCache.get("actModeHuggingFaceModelInfo"), - } as ApiConfiguration + actModeApiProvider: this.globalStateCache["actModeApiProvider"], + actModeApiModelId: this.globalStateCache["actModeApiModelId"], + actModeThinkingBudgetTokens: this.globalStateCache["actModeThinkingBudgetTokens"], + actModeReasoningEffort: this.globalStateCache["actModeReasoningEffort"], + actModeVsCodeLmModelSelector: this.globalStateCache["actModeVsCodeLmModelSelector"], + actModeAwsBedrockCustomSelected: this.globalStateCache["actModeAwsBedrockCustomSelected"], + actModeAwsBedrockCustomModelBaseId: this.globalStateCache["actModeAwsBedrockCustomModelBaseId"], + actModeOpenRouterModelId: this.globalStateCache["actModeOpenRouterModelId"], + actModeOpenRouterModelInfo: this.globalStateCache["actModeOpenRouterModelInfo"], + actModeOpenAiModelId: this.globalStateCache["actModeOpenAiModelId"], + actModeOpenAiModelInfo: this.globalStateCache["actModeOpenAiModelInfo"], + actModeOllamaModelId: this.globalStateCache["actModeOllamaModelId"], + actModeLmStudioModelId: this.globalStateCache["actModeLmStudioModelId"], + actModeLiteLlmModelId: this.globalStateCache["actModeLiteLlmModelId"], + actModeLiteLlmModelInfo: this.globalStateCache["actModeLiteLlmModelInfo"], + actModeRequestyModelId: this.globalStateCache["actModeRequestyModelId"], + actModeRequestyModelInfo: this.globalStateCache["actModeRequestyModelInfo"], + actModeTogetherModelId: this.globalStateCache["actModeTogetherModelId"], + actModeFireworksModelId: this.globalStateCache["actModeFireworksModelId"], + actModeSapAiCoreModelId: this.globalStateCache["actModeSapAiCoreModelId"], + actModeGroqModelId: this.globalStateCache["actModeGroqModelId"], + actModeGroqModelInfo: this.globalStateCache["actModeGroqModelInfo"], + actModeBasetenModelId: this.globalStateCache["actModeBasetenModelId"], + actModeBasetenModelInfo: this.globalStateCache["actModeBasetenModelInfo"], + actModeHuggingFaceModelId: this.globalStateCache["actModeHuggingFaceModelId"], + actModeHuggingFaceModelInfo: this.globalStateCache["actModeHuggingFaceModelInfo"], + actModeHuaweiCloudMaasModelId: this.globalStateCache["actModeHuaweiCloudMaasModelId"], + actModeHuaweiCloudMaasModelInfo: this.globalStateCache["actModeHuaweiCloudMaasModelInfo"], + } } } diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index bdf78002..3b4f0540 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -1,3 +1,15 @@ +import { ApiProvider, BedrockModelId, ModelInfo } from "@shared/api" +import { LanguageModelChatSelector } from "vscode" +import { ClineRulesToggles } from "@/shared/cline-rules" +import { McpDisplayMode } from "@/shared/McpDisplayMode" +import { TelemetrySetting } from "@/shared/TelemetrySetting" +import { UserInfo } from "@/shared/UserInfo" +import { BrowserSettings } from "@/shared/BrowserSettings" +import { HistoryItem } from "@/shared/HistoryItem" +import { AutoApprovalSettings } from "@/shared/AutoApprovalSettings" +import { Mode, OpenaiReasoningEffort } from "@/shared/storage/types" +import { McpMarketplaceCatalog } from "@/shared/mcp" + export type SecretKey = | "apiKey" | "clineAccountId" @@ -150,3 +162,162 @@ export type GlobalStateKey = | "actModeHuaweiCloudMaasModelInfo" export type LocalStateKey = "localClineRulesToggles" | "localCursorRulesToggles" | "localWindsurfRulesToggles" | "workflowToggles" + +export interface GlobalState { + awsRegion: string | undefined + awsUseCrossRegionInference: boolean | undefined + awsBedrockUsePromptCache: boolean | undefined + awsBedrockEndpoint: string | undefined + awsProfile: string | undefined + awsBedrockApiKey: string | undefined + awsAuthentication: string | undefined + awsUseProfile: boolean | undefined + vertexProjectId: string | undefined + vertexRegion: string | undefined + lastShownAnnouncementId: string | undefined + taskHistory: HistoryItem[] + openAiBaseUrl: string | undefined + openAiHeaders: Record + ollamaBaseUrl: string | undefined + ollamaApiOptionsCtxNum: string | undefined + lmStudioBaseUrl: string | undefined + anthropicBaseUrl: string | undefined + geminiBaseUrl: string | undefined + azureApiVersion: string | undefined + openRouterProviderSorting: string | undefined + autoApprovalSettings: AutoApprovalSettings + globalClineRulesToggles: ClineRulesToggles + globalWorkflowToggles: ClineRulesToggles + browserSettings: BrowserSettings + userInfo: UserInfo | undefined + liteLlmBaseUrl: string | undefined + liteLlmUsePromptCache: boolean | undefined + fireworksModelMaxCompletionTokens: number | undefined + fireworksModelMaxTokens: number | undefined + qwenApiLine: string | undefined + moonshotApiLine: string | undefined + mcpMarketplaceCatalog: McpMarketplaceCatalog | undefined + telemetrySetting: TelemetrySetting + asksageApiUrl: string | undefined + planActSeparateModelsSetting: boolean + enableCheckpointsSetting: boolean + mcpMarketplaceEnabled: boolean + favoritedModelIds: string[] | undefined + requestTimeoutMs: number | undefined + shellIntegrationTimeout: number + mcpResponsesCollapsed: boolean + terminalReuseEnabled: boolean + defaultTerminalProfile: string + isNewUser: boolean + welcomeViewCompleted: boolean | undefined + terminalOutputLineLimit: number + mcpDisplayMode: McpDisplayMode + sapAiCoreTokenUrl: string | undefined + sapAiCoreBaseUrl: string | undefined + sapAiResourceGroup: string | undefined + claudeCodePath: string | undefined + strictPlanModeEnabled: boolean + preferredLanguage: string + openaiReasoningEffort: OpenaiReasoningEffort + mode: Mode + // Plan mode configurations + planModeApiProvider: ApiProvider + planModeApiModelId: string | undefined + planModeThinkingBudgetTokens: number | undefined + planModeReasoningEffort: string | undefined + planModeVsCodeLmModelSelector: LanguageModelChatSelector | undefined + planModeAwsBedrockCustomSelected: boolean | undefined + planModeAwsBedrockCustomModelBaseId: BedrockModelId | undefined + planModeOpenRouterModelId: string | undefined + planModeOpenRouterModelInfo: ModelInfo | undefined + planModeOpenAiModelId: string | undefined + planModeOpenAiModelInfo: ModelInfo | undefined + planModeOllamaModelId: string | undefined + planModeLmStudioModelId: string | undefined + planModeLiteLlmModelId: string | undefined + planModeLiteLlmModelInfo: ModelInfo | undefined + planModeRequestyModelId: string | undefined + planModeRequestyModelInfo: ModelInfo | undefined + planModeTogetherModelId: string | undefined + planModeFireworksModelId: string | undefined + planModeSapAiCoreModelId: string | undefined + planModeGroqModelId: string | undefined + planModeGroqModelInfo: ModelInfo | undefined + planModeBasetenModelId: string | undefined + planModeBasetenModelInfo: ModelInfo | undefined + planModeHuggingFaceModelId: string | undefined + planModeHuggingFaceModelInfo: ModelInfo | undefined + planModeHuaweiCloudMaasModelId: string | undefined + planModeHuaweiCloudMaasModelInfo: ModelInfo | undefined + // Act mode configurations + actModeApiProvider: ApiProvider + actModeApiModelId: string | undefined + actModeThinkingBudgetTokens: number | undefined + actModeReasoningEffort: string | undefined + actModeVsCodeLmModelSelector: LanguageModelChatSelector | undefined + actModeAwsBedrockCustomSelected: boolean | undefined + actModeAwsBedrockCustomModelBaseId: BedrockModelId | undefined + actModeOpenRouterModelId: string | undefined + actModeOpenRouterModelInfo: ModelInfo | undefined + actModeOpenAiModelId: string | undefined + actModeOpenAiModelInfo: ModelInfo | undefined + actModeOllamaModelId: string | undefined + actModeLmStudioModelId: string | undefined + actModeLiteLlmModelId: string | undefined + actModeLiteLlmModelInfo: ModelInfo | undefined + actModeRequestyModelId: string | undefined + actModeRequestyModelInfo: ModelInfo | undefined + actModeTogetherModelId: string | undefined + actModeFireworksModelId: string | undefined + actModeSapAiCoreModelId: string | undefined + actModeGroqModelId: string | undefined + actModeGroqModelInfo: ModelInfo | undefined + actModeBasetenModelId: string | undefined + actModeBasetenModelInfo: ModelInfo | undefined + actModeHuggingFaceModelId: string | undefined + actModeHuggingFaceModelInfo: ModelInfo | undefined + actModeHuaweiCloudMaasModelId: string | undefined + actModeHuaweiCloudMaasModelInfo: ModelInfo | undefined +} + +export interface Secrets { + apiKey: string | undefined + clineAccountId: string | undefined + openRouterApiKey: string | undefined + awsAccessKey: string | undefined + awsSecretKey: string | undefined + awsSessionToken: string | undefined + awsBedrockApiKey: string | undefined + openAiApiKey: string | undefined + geminiApiKey: string | undefined + openAiNativeApiKey: string | undefined + ollamaApiKey: string | undefined + deepSeekApiKey: string | undefined + requestyApiKey: string | undefined + togetherApiKey: string | undefined + fireworksApiKey: string | undefined + qwenApiKey: string | undefined + doubaoApiKey: string | undefined + mistralApiKey: string | undefined + liteLlmApiKey: string | undefined + authNonce: string | undefined + asksageApiKey: string | undefined + xaiApiKey: string | undefined + moonshotApiKey: string | undefined + huggingFaceApiKey: string | undefined + nebiusApiKey: string | undefined + sambanovaApiKey: string | undefined + cerebrasApiKey: string | undefined + sapAiCoreClientId: string | undefined + sapAiCoreClientSecret: string | undefined + groqApiKey: string | undefined + huaweiCloudMaasApiKey: string | undefined + basetenApiKey: string | undefined +} + +export interface LocalState { + localClineRulesToggles: ClineRulesToggles + localCursorRulesToggles: ClineRulesToggles + localWindsurfRulesToggles: ClineRulesToggles + workflowToggles: ClineRulesToggles +} diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index 0f8419f7..fac378fd 100644 --- a/src/core/storage/state-migrations.ts +++ b/src/core/storage/state-migrations.ts @@ -2,7 +2,7 @@ import * as vscode from "vscode" import { ensureRulesDirectoryExists } from "./disk" import fs from "fs/promises" import path from "path" -import { updateGlobalState, getAllExtensionState, getGlobalState } from "./state" +import { readStateFromDisk } from "./utils/state-helpers" export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionContext) { // Keys to migrate from workspace storage back to global storage @@ -506,13 +506,13 @@ export async function migrateLegacyApiConfigurationToModeSpecific(context: vscod export async function migrateWelcomeViewCompleted(context: vscode.ExtensionContext) { try { // Check if welcomeViewCompleted is already set - const welcomeViewCompleted = await getGlobalState(context, "welcomeViewCompleted") + const welcomeViewCompleted = context.globalState.get("welcomeViewCompleted") if (welcomeViewCompleted === undefined) { console.log("Migrating welcomeViewCompleted setting...") // Get all extension state to check for existing API keys - const extensionState = await getAllExtensionState(context) + const extensionState = await readStateFromDisk(context) const config = extensionState.apiConfiguration // This is the original logic used for checking is the welcome view should be shown @@ -549,7 +549,7 @@ export async function migrateWelcomeViewCompleted(context: vscode.ExtensionConte : false // Set welcomeViewCompleted based on whether user has keys - await updateGlobalState(context, "welcomeViewCompleted", hasKey) + await context.globalState.update("welcomeViewCompleted", hasKey) console.log(`Migration: Set welcomeViewCompleted to ${hasKey} based on existing API keys`) } diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts deleted file mode 100644 index d4f14db3..00000000 --- a/src/core/storage/state.ts +++ /dev/null @@ -1,648 +0,0 @@ -import * as vscode from "vscode" -import { Mode, OpenaiReasoningEffort } from "@shared/storage/types" -import { DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings" -import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" -import { GlobalStateKey, LocalStateKey, SecretKey } from "./state-keys" -import { ApiConfiguration, ApiProvider, BedrockModelId, ModelInfo } from "@shared/api" -import { HistoryItem } from "@shared/HistoryItem" -import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" -import { BrowserSettings } from "@shared/BrowserSettings" -import { TelemetrySetting } from "@shared/TelemetrySetting" -import { UserInfo } from "@shared/UserInfo" -import { ClineRulesToggles } from "@shared/cline-rules" -import { DEFAULT_MCP_DISPLAY_MODE, McpDisplayMode } from "@shared/McpDisplayMode" -import { migrateEnableCheckpointsSetting, migrateMcpMarketplaceEnableSetting } from "./state-migrations" -import { Controller } from "../controller" -/* - Storage - https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco - https://www.eliostruyf.com/devhack-code-extension-storage-options/ - */ - -const isTemporaryProfile = process.env.TEMP_PROFILE === "true" - -// In-memory storage for temporary profiles -const inMemoryGlobalState = new Map() -const inMemoryWorkspaceState = new Map() -const inMemorySecrets = new Map() - -// global -export async function updateGlobalState(context: vscode.ExtensionContext, key: GlobalStateKey, value: any) { - if (isTemporaryProfile) { - inMemoryGlobalState.set(key, value) - return - } - await context.globalState.update(key, value) -} - -export async function getGlobalState(context: vscode.ExtensionContext, key: GlobalStateKey) { - if (isTemporaryProfile) { - return inMemoryGlobalState.get(key) - } - return await context.globalState.get(key) -} - -// Batched operations for performance optimization -export async function updateGlobalStateBatch(context: vscode.ExtensionContext, updates: Record) { - if (isTemporaryProfile) { - Object.entries(updates).forEach(([key, value]) => { - inMemoryGlobalState.set(key, value) - }) - return - } - // Use Promise.all to batch the updates - await Promise.all(Object.entries(updates).map(([key, value]) => context.globalState.update(key as GlobalStateKey, value))) -} - -export async function updateSecretsBatch(context: vscode.ExtensionContext, updates: Record) { - if (isTemporaryProfile) { - Object.entries(updates).forEach(([key, value]) => { - if (value) { - inMemorySecrets.set(key, value) - } else { - inMemorySecrets.delete(key) - } - }) - return - } - // Use Promise.all to batch the secret updates - await Promise.all(Object.entries(updates).map(([key, value]) => storeSecret(context, key as SecretKey, value))) -} - -// secrets -export async function storeSecret(context: vscode.ExtensionContext, key: SecretKey, value?: string) { - if (isTemporaryProfile) { - if (value) { - inMemorySecrets.set(key, value) - } else { - inMemorySecrets.delete(key) - } - return - } - if (value) { - await context.secrets.store(key, value) - } else { - await context.secrets.delete(key) - } -} - -export async function getSecret(context: vscode.ExtensionContext, key: SecretKey) { - if (isTemporaryProfile) { - return inMemorySecrets.get(key) - } - return await context.secrets.get(key) -} - -// workspace -export async function updateWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey, value: any) { - if (isTemporaryProfile) { - inMemoryWorkspaceState.set(key, value) - return - } - await context.workspaceState.update(key, value) -} - -export async function getWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey) { - if (isTemporaryProfile) { - return inMemoryWorkspaceState.get(key) - } - return await context.workspaceState.get(key) -} - -export async function getAllExtensionState(context: vscode.ExtensionContext) { - const [ - isNewUser, - welcomeViewCompleted, - apiKey, - openRouterApiKey, - clineAccountId, - awsAccessKey, - awsSecretKey, - awsSessionToken, - awsRegion, - awsUseCrossRegionInference, - awsBedrockUsePromptCache, - awsBedrockEndpoint, - awsProfile, - awsBedrockApiKey, - awsUseProfile, - awsAuthentication, - vertexProjectId, - vertexRegion, - openAiBaseUrl, - openAiApiKey, - openAiHeaders, - ollamaBaseUrl, - ollamaApiKey, - ollamaApiOptionsCtxNum, - lmStudioBaseUrl, - anthropicBaseUrl, - geminiApiKey, - geminiBaseUrl, - openAiNativeApiKey, - deepSeekApiKey, - requestyApiKey, - togetherApiKey, - qwenApiKey, - doubaoApiKey, - mistralApiKey, - azureApiVersion, - openRouterProviderSorting, - lastShownAnnouncementId, - taskHistory, - autoApprovalSettings, - browserSettings, - liteLlmBaseUrl, - liteLlmUsePromptCache, - fireworksApiKey, - fireworksModelMaxCompletionTokens, - fireworksModelMaxTokens, - userInfo, - qwenApiLine, - moonshotApiLine, - liteLlmApiKey, - telemetrySetting, - asksageApiKey, - asksageApiUrl, - xaiApiKey, - sambanovaApiKey, - cerebrasApiKey, - groqApiKey, - basetenApiKey, - moonshotApiKey, - nebiusApiKey, - huggingFaceApiKey, - planActSeparateModelsSettingRaw, - favoritedModelIds, - globalClineRulesToggles, - requestTimeoutMs, - shellIntegrationTimeout, - enableCheckpointsSettingRaw, - mcpMarketplaceEnabledRaw, - mcpDisplayMode, - mcpResponsesCollapsedRaw, - globalWorkflowToggles, - terminalReuseEnabled, - terminalOutputLineLimit, - defaultTerminalProfile, - sapAiCoreClientId, - sapAiCoreClientSecret, - sapAiCoreBaseUrl, - sapAiCoreTokenUrl, - sapAiResourceGroup, - claudeCodePath, - huaweiCloudMaasApiKey, - ] = await Promise.all([ - getGlobalState(context, "isNewUser") as Promise, - getGlobalState(context, "welcomeViewCompleted") as Promise, - getSecret(context, "apiKey") as Promise, - getSecret(context, "openRouterApiKey") as Promise, - getSecret(context, "clineAccountId") as Promise, - getSecret(context, "awsAccessKey") as Promise, - getSecret(context, "awsSecretKey") as Promise, - getSecret(context, "awsSessionToken") as Promise, - getGlobalState(context, "awsRegion") as Promise, - getGlobalState(context, "awsUseCrossRegionInference") as Promise, - getGlobalState(context, "awsBedrockUsePromptCache") as Promise, - getGlobalState(context, "awsBedrockEndpoint") as Promise, - getGlobalState(context, "awsProfile") as Promise, - getSecret(context, "awsBedrockApiKey") as Promise, - getGlobalState(context, "awsUseProfile") as Promise, - getGlobalState(context, "awsAuthentication") as Promise, - getGlobalState(context, "vertexProjectId") as Promise, - getGlobalState(context, "vertexRegion") as Promise, - getGlobalState(context, "openAiBaseUrl") as Promise, - getSecret(context, "openAiApiKey") as Promise, - getGlobalState(context, "openAiHeaders") as Promise | undefined>, - getGlobalState(context, "ollamaBaseUrl") as Promise, - getSecret(context, "ollamaApiKey") as Promise, - getGlobalState(context, "ollamaApiOptionsCtxNum") as Promise, - getGlobalState(context, "lmStudioBaseUrl") as Promise, - getGlobalState(context, "anthropicBaseUrl") as Promise, - getSecret(context, "geminiApiKey") as Promise, - getGlobalState(context, "geminiBaseUrl") as Promise, - getSecret(context, "openAiNativeApiKey") as Promise, - getSecret(context, "deepSeekApiKey") as Promise, - getSecret(context, "requestyApiKey") as Promise, - getSecret(context, "togetherApiKey") as Promise, - getSecret(context, "qwenApiKey") as Promise, - getSecret(context, "doubaoApiKey") as Promise, - getSecret(context, "mistralApiKey") as Promise, - getGlobalState(context, "azureApiVersion") as Promise, - getGlobalState(context, "openRouterProviderSorting") as Promise, - getGlobalState(context, "lastShownAnnouncementId") as Promise, - getGlobalState(context, "taskHistory") as Promise, - getGlobalState(context, "autoApprovalSettings") as Promise, - getGlobalState(context, "browserSettings") as Promise, - getGlobalState(context, "liteLlmBaseUrl") as Promise, - getGlobalState(context, "liteLlmUsePromptCache") as Promise, - getSecret(context, "fireworksApiKey") as Promise, - getGlobalState(context, "fireworksModelMaxCompletionTokens") as Promise, - getGlobalState(context, "fireworksModelMaxTokens") as Promise, - getGlobalState(context, "userInfo") as Promise, - getGlobalState(context, "qwenApiLine") as Promise, - getGlobalState(context, "moonshotApiLine") as Promise, - getSecret(context, "liteLlmApiKey") as Promise, - getGlobalState(context, "telemetrySetting") as Promise, - getSecret(context, "asksageApiKey") as Promise, - getGlobalState(context, "asksageApiUrl") as Promise, - getSecret(context, "xaiApiKey") as Promise, - getSecret(context, "sambanovaApiKey") as Promise, - getSecret(context, "cerebrasApiKey") as Promise, - getSecret(context, "groqApiKey") as Promise, - getSecret(context, "basetenApiKey") as Promise, - getSecret(context, "moonshotApiKey") as Promise, - getSecret(context, "nebiusApiKey") as Promise, - getSecret(context, "huggingFaceApiKey") as Promise, - getGlobalState(context, "planActSeparateModelsSetting") as Promise, - getGlobalState(context, "favoritedModelIds") as Promise, - getGlobalState(context, "globalClineRulesToggles") as Promise, - getGlobalState(context, "requestTimeoutMs") as Promise, - getGlobalState(context, "shellIntegrationTimeout") as Promise, - getGlobalState(context, "enableCheckpointsSetting") as Promise, - getGlobalState(context, "mcpMarketplaceEnabled") as Promise, - getGlobalState(context, "mcpDisplayMode") as Promise, - getGlobalState(context, "mcpResponsesCollapsed") as Promise, - getGlobalState(context, "globalWorkflowToggles") as Promise, - getGlobalState(context, "terminalReuseEnabled") as Promise, - getGlobalState(context, "terminalOutputLineLimit") as Promise, - getGlobalState(context, "defaultTerminalProfile") as Promise, - getSecret(context, "sapAiCoreClientId") as Promise, - getSecret(context, "sapAiCoreClientSecret") as Promise, - getGlobalState(context, "sapAiCoreBaseUrl") as Promise, - getGlobalState(context, "sapAiCoreTokenUrl") as Promise, - getGlobalState(context, "sapAiResourceGroup") as Promise, - getGlobalState(context, "claudeCodePath") as Promise, - getSecret(context, "huaweiCloudMaasApiKey") as Promise, - ]) - - const [localClineRulesToggles, localWindsurfRulesToggles, localCursorRulesToggles, localWorkflowToggles] = await Promise.all([ - getWorkspaceState(context, "localClineRulesToggles") as Promise, - getWorkspaceState(context, "localWindsurfRulesToggles") as Promise, - getWorkspaceState(context, "localCursorRulesToggles") as Promise, - getWorkspaceState(context, "workflowToggles") as Promise, - ]) - - const [ - preferredLanguage, - openaiReasoningEffort, - mode, - strictPlanModeEnabled, - // Plan mode configurations - planModeApiProvider, - planModeApiModelId, - planModeThinkingBudgetTokens, - planModeReasoningEffort, - planModeVsCodeLmModelSelector, - planModeAwsBedrockCustomSelected, - planModeAwsBedrockCustomModelBaseId, - planModeOpenRouterModelId, - planModeOpenRouterModelInfo, - planModeOpenAiModelId, - planModeOpenAiModelInfo, - planModeOllamaModelId, - planModeLmStudioModelId, - planModeLiteLlmModelId, - planModeLiteLlmModelInfo, - planModeRequestyModelId, - planModeRequestyModelInfo, - planModeTogetherModelId, - planModeFireworksModelId, - planModeSapAiCoreModelId, - planModeGroqModelId, - planModeGroqModelInfo, - planModeBasetenModelId, - planModeBasetenModelInfo, - planModeHuggingFaceModelId, - planModeHuggingFaceModelInfo, - planModeHuaweiCloudMaasModelId, - planModeHuaweiCloudMaasModelInfo, - // Act mode configurations - actModeApiProvider, - actModeApiModelId, - actModeThinkingBudgetTokens, - actModeReasoningEffort, - actModeVsCodeLmModelSelector, - actModeAwsBedrockCustomSelected, - actModeAwsBedrockCustomModelBaseId, - actModeOpenRouterModelId, - actModeOpenRouterModelInfo, - actModeOpenAiModelId, - actModeOpenAiModelInfo, - actModeOllamaModelId, - actModeLmStudioModelId, - actModeLiteLlmModelId, - actModeLiteLlmModelInfo, - actModeRequestyModelId, - actModeRequestyModelInfo, - actModeTogetherModelId, - actModeFireworksModelId, - actModeSapAiCoreModelId, - actModeGroqModelId, - actModeGroqModelInfo, - actModeBasetenModelId, - actModeBasetenModelInfo, - actModeHuggingFaceModelId, - actModeHuggingFaceModelInfo, - actModeHuaweiCloudMaasModelId, - actModeHuaweiCloudMaasModelInfo, - ] = await Promise.all([ - getGlobalState(context, "preferredLanguage") as Promise, - getGlobalState(context, "openaiReasoningEffort") as Promise, - getGlobalState(context, "mode") as Promise, - getGlobalState(context, "strictPlanModeEnabled") as Promise, - // Plan mode configurations - getGlobalState(context, "planModeApiProvider") as Promise, - getGlobalState(context, "planModeApiModelId") as Promise, - getGlobalState(context, "planModeThinkingBudgetTokens") as Promise, - getGlobalState(context, "planModeReasoningEffort") as Promise, - getGlobalState(context, "planModeVsCodeLmModelSelector") as Promise, - getGlobalState(context, "planModeAwsBedrockCustomSelected") as Promise, - getGlobalState(context, "planModeAwsBedrockCustomModelBaseId") as Promise, - getGlobalState(context, "planModeOpenRouterModelId") as Promise, - getGlobalState(context, "planModeOpenRouterModelInfo") as Promise, - getGlobalState(context, "planModeOpenAiModelId") as Promise, - getGlobalState(context, "planModeOpenAiModelInfo") as Promise, - getGlobalState(context, "planModeOllamaModelId") as Promise, - getGlobalState(context, "planModeLmStudioModelId") as Promise, - getGlobalState(context, "planModeLiteLlmModelId") as Promise, - getGlobalState(context, "planModeLiteLlmModelInfo") as Promise, - getGlobalState(context, "planModeRequestyModelId") as Promise, - getGlobalState(context, "planModeRequestyModelInfo") as Promise, - getGlobalState(context, "planModeTogetherModelId") as Promise, - getGlobalState(context, "planModeFireworksModelId") as Promise, - getGlobalState(context, "planModeSapAiCoreModelId") as Promise, - getGlobalState(context, "planModeGroqModelId") as Promise, - getGlobalState(context, "planModeGroqModelInfo") as Promise, - getGlobalState(context, "planModeBasetenModelId") as Promise, - getGlobalState(context, "planModeBasetenModelInfo") as Promise, - getGlobalState(context, "planModeHuggingFaceModelId") as Promise, - getGlobalState(context, "planModeHuggingFaceModelInfo") as Promise, - getGlobalState(context, "planModeHuaweiCloudMaasModelId") as Promise, - getGlobalState(context, "planModeHuaweiCloudMaasModelInfo") as Promise, - // Act mode configurations - getGlobalState(context, "actModeApiProvider") as Promise, - getGlobalState(context, "actModeApiModelId") as Promise, - getGlobalState(context, "actModeThinkingBudgetTokens") as Promise, - getGlobalState(context, "actModeReasoningEffort") as Promise, - getGlobalState(context, "actModeVsCodeLmModelSelector") as Promise, - getGlobalState(context, "actModeAwsBedrockCustomSelected") as Promise, - getGlobalState(context, "actModeAwsBedrockCustomModelBaseId") as Promise, - getGlobalState(context, "actModeOpenRouterModelId") as Promise, - getGlobalState(context, "actModeOpenRouterModelInfo") as Promise, - getGlobalState(context, "actModeOpenAiModelId") as Promise, - getGlobalState(context, "actModeOpenAiModelInfo") as Promise, - getGlobalState(context, "actModeOllamaModelId") as Promise, - getGlobalState(context, "actModeLmStudioModelId") as Promise, - getGlobalState(context, "actModeLiteLlmModelId") as Promise, - getGlobalState(context, "actModeLiteLlmModelInfo") as Promise, - getGlobalState(context, "actModeRequestyModelId") as Promise, - getGlobalState(context, "actModeRequestyModelInfo") as Promise, - getGlobalState(context, "actModeTogetherModelId") as Promise, - getGlobalState(context, "actModeFireworksModelId") as Promise, - getGlobalState(context, "actModeSapAiCoreModelId") as Promise, - getGlobalState(context, "actModeGroqModelId") as Promise, - getGlobalState(context, "actModeGroqModelInfo") as Promise, - getGlobalState(context, "actModeBasetenModelId") as Promise, - getGlobalState(context, "actModeBasetenModelInfo") as Promise, - getGlobalState(context, "actModeHuggingFaceModelId") as Promise, - getGlobalState(context, "actModeHuggingFaceModelInfo") as Promise, - getGlobalState(context, "actModeHuaweiCloudMaasModelId") as Promise, - getGlobalState(context, "actModeHuaweiCloudMaasModelInfo") as Promise, - ]) - - let apiProvider: ApiProvider - if (planModeApiProvider) { - apiProvider = planModeApiProvider - } else { - // Either new user or legacy user that doesn't have the apiProvider stored in state - // (If they're using OpenRouter or Bedrock, then apiProvider state will exist) - if (apiKey) { - apiProvider = "anthropic" - } else { - // New users should default to openrouter, since they've opted to use an API key instead of signing in - apiProvider = "openrouter" - } - } - - const mcpMarketplaceEnabled = await migrateMcpMarketplaceEnableSetting(mcpMarketplaceEnabledRaw) - const enableCheckpointsSetting = await migrateEnableCheckpointsSetting(enableCheckpointsSettingRaw) - 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 = 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 - } - // this is a special case where it's a new state, but we want it to default to different values for existing and new users. - // persist so next time state is retrieved it's set to the correct value. - await updateGlobalState(context, "planActSeparateModelsSetting", planActSeparateModelsSetting) - } - - return { - apiConfiguration: { - apiKey, - openRouterApiKey, - clineAccountId, - claudeCodePath, - awsAccessKey, - awsSecretKey, - awsSessionToken, - awsRegion, - awsUseCrossRegionInference, - awsBedrockUsePromptCache, - awsBedrockEndpoint, - awsProfile, - awsBedrockApiKey, - awsUseProfile, - awsAuthentication, - vertexProjectId, - vertexRegion, - openAiBaseUrl, - openAiApiKey, - openAiHeaders: openAiHeaders || {}, - ollamaBaseUrl, - ollamaApiKey, - ollamaApiOptionsCtxNum, - lmStudioBaseUrl, - anthropicBaseUrl, - geminiApiKey, - geminiBaseUrl, - openAiNativeApiKey, - deepSeekApiKey, - requestyApiKey, - togetherApiKey, - qwenApiKey, - qwenApiLine, - moonshotApiLine, - doubaoApiKey, - mistralApiKey, - azureApiVersion, - openRouterProviderSorting, - liteLlmBaseUrl, - liteLlmApiKey, - liteLlmUsePromptCache, - fireworksApiKey, - fireworksModelMaxCompletionTokens, - fireworksModelMaxTokens, - asksageApiKey, - asksageApiUrl, - xaiApiKey, - sambanovaApiKey, - cerebrasApiKey, - groqApiKey, - basetenApiKey, - moonshotApiKey, - nebiusApiKey, - favoritedModelIds, - requestTimeoutMs, - sapAiCoreClientId, - sapAiCoreClientSecret, - sapAiCoreBaseUrl, - sapAiCoreTokenUrl, - sapAiResourceGroup, - huggingFaceApiKey, - huaweiCloudMaasApiKey, - // 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, - planModeBasetenModelId, - planModeBasetenModelInfo, - planModeHuggingFaceModelId, - planModeHuggingFaceModelInfo, - planModeHuaweiCloudMaasModelId, - planModeHuaweiCloudMaasModelInfo, - // 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, - actModeBasetenModelId, - actModeBasetenModelInfo, - actModeHuggingFaceModelId, - actModeHuggingFaceModelInfo, - actModeHuaweiCloudMaasModelId, - actModeHuaweiCloudMaasModelInfo, - }, - isNewUser: isNewUser ?? true, - welcomeViewCompleted, - lastShownAnnouncementId, - 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", - strictPlanModeEnabled: strictPlanModeEnabled ?? false, - userInfo, - mcpMarketplaceEnabled: mcpMarketplaceEnabled, - mcpDisplayMode: mcpDisplayMode ?? DEFAULT_MCP_DISPLAY_MODE, - mcpResponsesCollapsed: mcpResponsesCollapsed, - telemetrySetting: telemetrySetting || "unset", - planActSeparateModelsSetting, - enableCheckpointsSetting: enableCheckpointsSetting, - shellIntegrationTimeout: shellIntegrationTimeout || 4000, - terminalReuseEnabled: terminalReuseEnabled ?? true, - terminalOutputLineLimit: terminalOutputLineLimit ?? 500, - defaultTerminalProfile: defaultTerminalProfile ?? "default", - globalWorkflowToggles: globalWorkflowToggles || {}, - localClineRulesToggles: localClineRulesToggles || {}, - localWindsurfRulesToggles: localWindsurfRulesToggles || {}, - localCursorRulesToggles: localCursorRulesToggles || {}, - localWorkflowToggles: localWorkflowToggles || {}, - } -} - -export async function resetWorkspaceState(controller: Controller) { - const context = controller.context - await Promise.all(context.workspaceState.keys().map((key) => controller.context.workspaceState.update(key, undefined))) - - await controller.cacheService.reInitialize() -} - -export async function resetGlobalState(controller: Controller) { - // TODO: Reset all workspace states? - const context = controller.context - - await Promise.all(context.globalState.keys().map((key) => context.globalState.update(key, undefined))) - const secretKeys: SecretKey[] = [ - "apiKey", - "openRouterApiKey", - "awsAccessKey", - "awsSecretKey", - "awsSessionToken", - "awsBedrockApiKey", - "openAiApiKey", - "ollamaApiKey", - "geminiApiKey", - "openAiNativeApiKey", - "deepSeekApiKey", - "requestyApiKey", - "togetherApiKey", - "qwenApiKey", - "doubaoApiKey", - "mistralApiKey", - "clineAccountId", - "liteLlmApiKey", - "fireworksApiKey", - "asksageApiKey", - "xaiApiKey", - "sambanovaApiKey", - "cerebrasApiKey", - "groqApiKey", - "basetenApiKey", - "moonshotApiKey", - "nebiusApiKey", - "huggingFaceApiKey", - "huaweiCloudMaasApiKey", - ] - await Promise.all(secretKeys.map((key) => storeSecret(context, key, undefined))) - await controller.cacheService.reInitialize() -} diff --git a/src/core/storage/utils/state-helpers.ts b/src/core/storage/utils/state-helpers.ts new file mode 100644 index 00000000..80806457 --- /dev/null +++ b/src/core/storage/utils/state-helpers.ts @@ -0,0 +1,442 @@ +import { ExtensionContext } from "vscode" +import { ApiProvider, BedrockModelId, ModelInfo } from "@shared/api" +import { LanguageModelChatSelector } from "vscode" +import { ClineRulesToggles } from "@/shared/cline-rules" +import { DEFAULT_MCP_DISPLAY_MODE, McpDisplayMode } from "@/shared/McpDisplayMode" +import { TelemetrySetting } from "@/shared/TelemetrySetting" +import { UserInfo } from "@/shared/UserInfo" +import { BrowserSettings, DEFAULT_BROWSER_SETTINGS } from "@/shared/BrowserSettings" +import { HistoryItem } from "@/shared/HistoryItem" +import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "@/shared/AutoApprovalSettings" +import { Mode, OpenaiReasoningEffort } from "@/shared/storage/types" +import { SecretKey } from "../state-keys" +import { Controller } from "@/core/controller" + +export async function readStateFromDisk(context: ExtensionContext) { + // Get all global state values + const strictPlanModeEnabled = context.globalState.get("strictPlanModeEnabled") 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 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 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 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 openaiReasoningEffort = context.globalState.get("openaiReasoningEffort") as OpenaiReasoningEffort | undefined + const preferredLanguage = context.globalState.get("preferredLanguage") as string | undefined + + // Get all secret values + const [ + apiKey, + openRouterApiKey, + clineAccountId, + awsAccessKey, + awsSecretKey, + awsSessionToken, + awsBedrockApiKey, + openAiApiKey, + geminiApiKey, + openAiNativeApiKey, + deepSeekApiKey, + requestyApiKey, + togetherApiKey, + qwenApiKey, + doubaoApiKey, + mistralApiKey, + fireworksApiKey, + liteLlmApiKey, + asksageApiKey, + xaiApiKey, + sambanovaApiKey, + cerebrasApiKey, + groqApiKey, + moonshotApiKey, + nebiusApiKey, + huggingFaceApiKey, + sapAiCoreClientId, + sapAiCoreClientSecret, + huaweiCloudMaasApiKey, + basetenApiKey, + ollamaApiKey, + ] = await Promise.all([ + context.secrets.get("apiKey") as Promise, + context.secrets.get("openRouterApiKey") as Promise, + context.secrets.get("clineAccountId") as Promise, + context.secrets.get("awsAccessKey") as Promise, + context.secrets.get("awsSecretKey") as Promise, + context.secrets.get("awsSessionToken") as Promise, + context.secrets.get("awsBedrockApiKey") as Promise, + context.secrets.get("openAiApiKey") as Promise, + context.secrets.get("geminiApiKey") as Promise, + context.secrets.get("openAiNativeApiKey") as Promise, + context.secrets.get("deepSeekApiKey") as Promise, + context.secrets.get("requestyApiKey") as Promise, + context.secrets.get("togetherApiKey") as Promise, + context.secrets.get("qwenApiKey") as Promise, + context.secrets.get("doubaoApiKey") as Promise, + context.secrets.get("mistralApiKey") as Promise, + context.secrets.get("fireworksApiKey") as Promise, + context.secrets.get("liteLlmApiKey") as Promise, + context.secrets.get("asksageApiKey") as Promise, + context.secrets.get("xaiApiKey") as Promise, + context.secrets.get("sambanovaApiKey") as Promise, + context.secrets.get("cerebrasApiKey") as Promise, + context.secrets.get("groqApiKey") as Promise, + context.secrets.get("moonshotApiKey") as Promise, + context.secrets.get("nebiusApiKey") as Promise, + context.secrets.get("huggingFaceApiKey") as Promise, + context.secrets.get("sapAiCoreClientId") as Promise, + context.secrets.get("sapAiCoreClientSecret") as Promise, + context.secrets.get("huaweiCloudMaasApiKey") as Promise, + context.secrets.get("basetenApiKey") as Promise, + context.secrets.get("ollamaApiKey") as Promise, + ]) + + const localClineRulesToggles = context.workspaceState.get("localClineRulesToggles") as ClineRulesToggles | undefined + const localWindsurfRulesToggles = context.workspaceState.get("localWindsurfRulesToggles") as ClineRulesToggles | undefined + const localCursorRulesToggles = context.workspaceState.get("localCursorRulesToggles") as ClineRulesToggles | undefined + const localWorkflowToggles = context.workspaceState.get("workflowToggles") as ClineRulesToggles | 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 + // 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 + + let apiProvider: ApiProvider + if (planModeApiProvider) { + apiProvider = planModeApiProvider + } else { + // Either new user or legacy user that doesn't have the apiProvider stored in state + // (If they're using OpenRouter or Bedrock, then apiProvider state will exist) + if (apiKey) { + apiProvider = "anthropic" + } 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 = 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 { + apiConfiguration: { + apiKey, + openRouterApiKey, + clineAccountId, + claudeCodePath, + awsAccessKey, + awsSecretKey, + awsSessionToken, + awsRegion, + awsUseCrossRegionInference, + awsBedrockUsePromptCache, + awsBedrockEndpoint, + awsProfile, + awsBedrockApiKey, + awsUseProfile, + awsAuthentication, + vertexProjectId, + vertexRegion, + openAiBaseUrl, + openAiApiKey, + openAiHeaders: openAiHeaders || {}, + ollamaBaseUrl, + ollamaApiOptionsCtxNum, + lmStudioBaseUrl, + anthropicBaseUrl, + geminiApiKey, + geminiBaseUrl, + openAiNativeApiKey, + deepSeekApiKey, + requestyApiKey, + togetherApiKey, + qwenApiKey, + qwenApiLine, + moonshotApiLine, + doubaoApiKey, + mistralApiKey, + azureApiVersion, + openRouterProviderSorting, + liteLlmBaseUrl, + liteLlmApiKey, + liteLlmUsePromptCache, + fireworksApiKey, + fireworksModelMaxCompletionTokens, + fireworksModelMaxTokens, + asksageApiKey, + asksageApiUrl, + xaiApiKey, + sambanovaApiKey, + cerebrasApiKey, + groqApiKey, + moonshotApiKey, + nebiusApiKey, + favoritedModelIds, + requestTimeoutMs, + sapAiCoreClientId, + sapAiCoreClientSecret, + sapAiCoreBaseUrl, + sapAiCoreTokenUrl, + sapAiResourceGroup, + huggingFaceApiKey, + huaweiCloudMaasApiKey, + basetenApiKey, + ollamaApiKey, + // 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, + // 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, + }, + strictPlanModeEnabled: strictPlanModeEnabled ?? 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 || {}, + localClineRulesToggles: localClineRulesToggles || {}, + localWindsurfRulesToggles: localWindsurfRulesToggles || {}, + localCursorRulesToggles: localCursorRulesToggles || {}, + localWorkflowToggles: localWorkflowToggles || {}, + } +} + +export async function resetWorkspaceState(controller: Controller) { + const context = controller.context + await Promise.all(context.workspaceState.keys().map((key) => controller.context.workspaceState.update(key, undefined))) + + await controller.cacheService.reInitialize() +} + +export async function resetGlobalState(controller: Controller) { + // TODO: Reset all workspace states? + const context = controller.context + + await Promise.all(context.globalState.keys().map((key) => context.globalState.update(key, undefined))) + const secretKeys: SecretKey[] = [ + "apiKey", + "openRouterApiKey", + "awsAccessKey", + "awsSecretKey", + "awsSessionToken", + "awsBedrockApiKey", + "openAiApiKey", + "ollamaApiKey", + "geminiApiKey", + "openAiNativeApiKey", + "deepSeekApiKey", + "requestyApiKey", + "togetherApiKey", + "qwenApiKey", + "doubaoApiKey", + "mistralApiKey", + "clineAccountId", + "liteLlmApiKey", + "fireworksApiKey", + "asksageApiKey", + "xaiApiKey", + "sambanovaApiKey", + "cerebrasApiKey", + "groqApiKey", + "basetenApiKey", + "moonshotApiKey", + "nebiusApiKey", + "huggingFaceApiKey", + "huaweiCloudMaasApiKey", + ] + await Promise.all(secretKeys.map((key) => context.secrets.delete(key))) + await controller.cacheService.reInitialize() +} diff --git a/src/core/task/index.ts b/src/core/task/index.ts index a2c5df56..e37db174 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -73,7 +73,6 @@ import { getSavedClineMessages, GlobalFileNames, } from "@core/storage/disk" -import { getGlobalState } from "@core/storage/state" import { processFilesIntoText } from "@integrations/misc/extract-text" import { McpHub } from "@services/mcp/McpHub" import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message" @@ -88,6 +87,7 @@ import { updateApiReqMsg } from "./utils" import { CacheService } from "../storage/CacheService" import { Mode, OpenaiReasoningEffort } from "@shared/storage/types" import { ShowMessageType } from "@/shared/proto/index.host" +import { Controller } from "../controller" export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false @@ -107,7 +107,7 @@ export class Task { private enableCheckpoints: boolean // Core dependencies - private context: vscode.ExtensionContext + private controller: Controller private mcpHub: McpHub // Service handlers @@ -144,7 +144,7 @@ export class Task { // Message and conversation state messageStateHandler: MessageStateHandler constructor( - context: vscode.ExtensionContext, + controller: Controller, mcpHub: McpHub, updateTaskHistory: (historyItem: HistoryItem) => Promise, postStateToWebview: () => Promise, @@ -170,7 +170,7 @@ export class Task { historyItem?: HistoryItem, ) { this.taskState = new TaskState() - this.context = context + this.controller = controller this.mcpHub = mcpHub this.updateTaskHistory = updateTaskHistory this.postStateToWebview = postStateToWebview @@ -195,8 +195,8 @@ export class Task { this.terminalManager.setTerminalOutputLineLimit(terminalOutputLineLimit) this.terminalManager.setDefaultTerminalProfile(defaultTerminalProfile) - this.urlContentFetcher = new UrlContentFetcher(context) - this.browserSession = new BrowserSession(context, browserSettings) + this.urlContentFetcher = new UrlContentFetcher(controller.context) + this.browserSession = new BrowserSession(controller.context, browserSettings) this.contextManager = new ContextManager() this.diffViewProvider = HostProvider.get().createDiffViewProvider() this.autoApprovalSettings = autoApprovalSettings @@ -231,7 +231,7 @@ export class Task { } this.messageStateHandler = new MessageStateHandler({ - context, + context: controller.context, taskId: this.taskId, ulid: this.ulid, taskState: this.taskState, @@ -240,8 +240,8 @@ export class Task { }) // Initialize file context tracker - this.fileContextTracker = new FileContextTracker(context, this.taskId) - this.modelContextTracker = new ModelContextTracker(context, this.taskId) + this.fileContextTracker = new FileContextTracker(controller, this.taskId) + this.modelContextTracker = new ModelContextTracker(controller.context, this.taskId) // Prepare effective API configuration const effectiveApiConfiguration: ApiConfiguration = { @@ -314,7 +314,7 @@ export class Task { } this.toolExecutor = new ToolExecutor( - this.context, + this.controller.context, this.taskState, this.messageStateHandler, this.api, @@ -355,7 +355,7 @@ export class Task { // While a task is ref'd by a controller, it will always have access to the extension context // This error is thrown if the controller derefs the task after e.g., aborting the task private getContext(): vscode.ExtensionContext { - const context = this.context + const context = this.controller.context if (!context) { throw new Error("Unable to access extension context") } @@ -412,7 +412,7 @@ export class Task { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, - this.context.globalStorageUri.fsPath, + this.controller.context.globalStorageUri.fsPath, this.enableCheckpoints, ) this.messageStateHandler.setCheckpointTracker(this.checkpointTracker) @@ -600,7 +600,7 @@ export class Task { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, - this.context.globalStorageUri.fsPath, + this.controller.context.globalStorageUri.fsPath, this.enableCheckpoints, ) this.messageStateHandler.setCheckpointTracker(this.checkpointTracker) @@ -737,7 +737,7 @@ export class Task { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, - this.context.globalStorageUri.fsPath, + this.controller.context.globalStorageUri.fsPath, this.enableCheckpoints, ) this.messageStateHandler.setCheckpointTracker(this.checkpointTracker) @@ -1326,7 +1326,7 @@ export class Task { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, - this.context.globalStorageUri.fsPath, + this.controller.context.globalStorageUri.fsPath, this.enableCheckpoints, ) } catch (error) { @@ -1370,7 +1370,7 @@ export class Task { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, - this.context.globalStorageUri.fsPath, + this.controller.context.globalStorageUri.fsPath, this.enableCheckpoints, ) this.messageStateHandler.setCheckpointTracker(this.checkpointTracker) @@ -1714,8 +1714,8 @@ export class Task { ? `# Preferred Language\n\nSpeak in ${preferredLanguage}.` : "" - const { globalToggles, localToggles } = await refreshClineRulesToggles(this.getContext(), this.cwd) - const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.getContext(), this.cwd) + const { globalToggles, localToggles } = await refreshClineRulesToggles(this.controller, this.cwd) + const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.controller, this.cwd) const globalClineRulesFilePath = await ensureRulesDirectoryExists() const globalClineRulesFileInstructions = await getGlobalClineRules(globalClineRulesFilePath, globalToggles) @@ -2155,7 +2155,11 @@ export class Task { // Timeout - If checkpoints take too long to initialize, warn user and disable checkpoints for the task this.checkpointTracker = await pTimeout( - CheckpointTracker.create(this.taskId, this.context.globalStorageUri.fsPath, this.enableCheckpoints), + CheckpointTracker.create( + this.taskId, + this.controller.context.globalStorageUri.fsPath, + this.enableCheckpoints, + ), { milliseconds: 15_000, message: @@ -2542,7 +2546,7 @@ export class Task { // Track if we need to check clinerulesFile let needsClinerulesFileCheck = false - const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.getContext(), this.cwd) + const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.controller, this.cwd) const processUserContent = async () => { // This is a temporary solution to dynamically load context mentions from tool results. It checks for the presence of tags that indicate that the tool was rejected and feedback was provided (see formatToolDeniedFeedback, attemptCompletion, executeCommand, and consecutiveMistakeCount >= 3) or "" (see askFollowupQuestion), we place all user generated content in these tags so they can effectively be used as markers for when we should parse mentions). However if we allow multiple tools responses in the future, we will need to parse mentions specifically within the user content tags. diff --git a/src/integrations/git/commit-message-generator.ts b/src/integrations/git/commit-message-generator.ts index 2a620199..6d2f70ad 100644 --- a/src/integrations/git/commit-message-generator.ts +++ b/src/integrations/git/commit-message-generator.ts @@ -3,7 +3,7 @@ import { writeTextToClipboard } from "@utils/env" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType, ShowTextDocumentRequest } from "@/shared/proto/host/window" import { buildApiHandler } from "@/api" -import { getAllExtensionState } from "@/core/storage/state" +import { readStateFromDisk } from "@/core/storage/utils/state-helpers" import { getWorkingState } from "@/utils/git" import { getCwd } from "@/utils/path" @@ -71,7 +71,7 @@ The commit message should: Commit message:` // Get the current API configuration - const { apiConfiguration } = await getAllExtensionState(context) + const { apiConfiguration } = await readStateFromDisk(context) // Set to use Act mode for now by default // TODO: A new mode for commit generation const currentMode = "act" diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index 84089039..8e859835 100644 --- a/src/services/test/TestServer.ts +++ b/src/services/test/TestServer.ts @@ -1,10 +1,9 @@ import { getCwd } from "@/utils/path" import { getSavedApiConversationHistory, getSavedClineMessages } from "@core/storage/disk" -import { getAllExtensionState, updateGlobalState } from "@core/storage/state" import { WebviewProvider } from "@core/webview" import { Logger } from "@services/logging/Logger" import { ApiProvider } from "@shared/api" -import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" +import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" import { HistoryItem } from "@shared/HistoryItem" import { execa } from "execa" import * as http from "http" @@ -49,11 +48,11 @@ let messageCatcherDisposable: vscode.Disposable | undefined */ async function updateAutoApprovalSettings(context: vscode.ExtensionContext, controller?: Controller) { try { - const { autoApprovalSettings } = await getAllExtensionState(context) + const autoApprovalSettings = controller?.cacheService.getGlobalStateKey("autoApprovalSettings") // Enable all actions const updatedSettings: AutoApprovalSettings = { - ...autoApprovalSettings, + ...(autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS), enabled: true, actions: { readFiles: true, @@ -68,7 +67,7 @@ async function updateAutoApprovalSettings(context: vscode.ExtensionContext, cont maxRequests: 10000, // Increase max requests for tests } - await updateGlobalState(context, "autoApprovalSettings", updatedSettings) + controller?.cacheService.setGlobalState("autoApprovalSettings", updatedSettings) Logger.log("Auto approval settings updated for test mode") // Update the webview with the new state @@ -209,7 +208,7 @@ export function createTestServer(controller: Controller): http.Server { Logger.log("API key provided, updating API configuration") // Get current API configuration - const { apiConfiguration } = await getAllExtensionState(visibleWebview.controller.context) + const apiConfiguration = visibleWebview.controller.cacheService.getApiConfiguration() // Update API configuration with API key const updatedConfig = { diff --git a/src/test/cline-api.test.ts b/src/test/cline-api.test.ts index da30d6f1..e38acd0a 100644 --- a/src/test/cline-api.test.ts +++ b/src/test/cline-api.test.ts @@ -1,5 +1,4 @@ import { createClineAPI } from "@/exports" -import * as stateModule from "@core/storage/state" import { afterEach, beforeEach, describe, it } from "mocha" import * as should from "should" import * as sinon from "sinon" @@ -20,10 +19,6 @@ describe("ClineAPI Core Functionality", () => { mockLogToChannel = sandbox.stub<[string], void>() setVscodeHostProviderMock({ logToChannel: mockLogToChannel }) - // Stub the getGlobalState function from the state module - // This is needed because the real createClineAPI uses it for getCustomInstructions - getGlobalStateStub = sandbox.stub(stateModule, "getGlobalState") - // Create a mock controller that matches what the real createClineAPI expects // We don't import the real Controller to avoid the webview dependencies mockController = { diff --git a/webview-ui/src/components/settings/utils/settingsHandlers.ts b/webview-ui/src/components/settings/utils/settingsHandlers.ts index 0a0a00a6..07aad7cc 100644 --- a/webview-ui/src/components/settings/utils/settingsHandlers.ts +++ b/webview-ui/src/components/settings/utils/settingsHandlers.ts @@ -1,7 +1,41 @@ import { StateServiceClient, BrowserServiceClient } from "@/services/grpc-client" -import { UpdateSettingsRequest } from "@shared/proto/cline/state" +import { UpdateSettingsRequest, OpenaiReasoningEffort, McpDisplayMode } from "@shared/proto/cline/state" import { UpdateBrowserSettingsRequest } from "@shared/proto/cline/browser" +/** + * Converts values to their corresponding proto format + * @param field - The field name + * @param value - The value to convert + * @returns The converted value + * @throws Error if the value is invalid for the field + */ +const convertToProtoValue = (field: keyof UpdateSettingsRequest, value: any): any => { + if (field === "openaiReasoningEffort" && typeof value === "string") { + switch (value) { + case "low": + return OpenaiReasoningEffort.LOW + case "medium": + return OpenaiReasoningEffort.MEDIUM + case "high": + return OpenaiReasoningEffort.HIGH + default: + throw new Error(`Invalid OpenAI reasoning effort value: ${value}`) + } + } else if (field === "mcpDisplayMode" && typeof value === "string") { + switch (value) { + case "rich": + return McpDisplayMode.RICH + case "plain": + return McpDisplayMode.PLAIN + case "markdown": + return McpDisplayMode.MARKDOWN + default: + throw new Error(`Invalid MCP display mode value: ${value}`) + } + } + return value +} + /** * Updates a single field in the settings. * @@ -10,7 +44,9 @@ import { UpdateBrowserSettingsRequest } from "@shared/proto/cline/browser" */ export const updateSetting = (field: keyof UpdateSettingsRequest, value: any) => { const updateRequest: Partial = {} - updateRequest[field] = value + + const convertedValue = convertToProtoValue(field, value) + updateRequest[field] = convertedValue StateServiceClient.updateSettings(UpdateSettingsRequest.create(updateRequest)).catch((error) => { console.error(`Failed to update setting ${field}:`, error)