Compare commits

...

8 Commits

Author SHA1 Message Date
celestial-vault 560b75f386 merge conflicts 2025-07-31 14:20:07 -07:00
celestial-vault 3067b54752 remove clearCache; make dispose function private; remove vscode api dependency; call reInitialize in reset functions instead of dispose/initialize 2025-07-30 12:18:54 -07:00
celestial-vault 64a4abb521 fix global state reset 2025-07-29 18:29:30 -07:00
celestial-vault 3259a23be5 fix types after merge conflicts 2025-07-29 18:09:13 -07:00
celestial-vault 4f69cf2b41 merge conflicts 2025-07-29 18:07:36 -07:00
celestial-vault b83b8a8814 add state persistence debounced, batch state updates, make setters synchronous 2025-07-28 23:22:52 -07:00
celestial-vault cb0ffb75ce use cache for apiCongfiguration state 2025-07-27 21:06:44 -07:00
celestial-vault 9443ae1a35 remove chatSettings object 2025-07-26 09:58:41 -07:00
14 changed files with 1095 additions and 348 deletions
+65 -46
View File
@@ -30,6 +30,7 @@ import * as path from "path"
import * as vscode from "vscode"
import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk"
import { getAllExtensionState, getGlobalState, getWorkspaceState, storeSecret, updateGlobalState } from "../storage/state"
import { CacheService, PersistenceErrorEvent } from "../storage/CacheService"
import { Task } from "../task"
import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler"
import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog"
@@ -54,16 +55,38 @@ export class Controller {
mcpHub: McpHub
accountService: ClineAccountService
authService: AuthService
readonly cacheService: CacheService
constructor(
readonly context: vscode.ExtensionContext,
postMessage: (message: ExtensionMessage) => Thenable<boolean> | undefined,
id: string,
cacheService: CacheService,
) {
this.id = id
HostProvider.get().logToChannel("ClineProvider instantiated")
this.postMessage = postMessage
this.cacheService = cacheService
// Set up persistence error recovery
this.cacheService.onPersistenceError = async ({ error }: PersistenceErrorEvent) => {
console.error("Cache persistence failed, recovering:", error)
try {
await this.cacheService.reInitialize()
await this.postStateToWebview()
HostProvider.window.showMessage({
type: ShowMessageType.WARNING,
message: "Saving settings to storage failed.",
})
} catch (recoveryError) {
console.error("Cache recovery failed:", recoveryError)
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
message: "Failed to save settings. Please restart the extension.",
})
}
}
this.workspaceTracker = new WorkspaceTracker()
this.mcpHub = new McpHub(
@@ -111,10 +134,16 @@ export class Controller {
// TODO: update to clineAccountId and then move clineApiKey to a clear function.
await storeSecret(this.context, "clineAccountId", undefined)
await updateGlobalState(this.context, "userInfo", undefined)
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", "openrouter"),
updateGlobalState(this.context, "actModeApiProvider", "openrouter"),
])
// Update API providers through cache service
const apiConfiguration = this.cacheService.getApiConfiguration()
const updatedConfig = {
...apiConfiguration,
planModeApiProvider: "openrouter" as ApiProvider,
actModeApiProvider: "openrouter" as ApiProvider,
}
this.cacheService.setApiConfiguration(updatedConfig)
await this.postStateToWebview()
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
@@ -134,8 +163,11 @@ export class Controller {
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 {
apiConfiguration,
autoApprovalSettings,
browserSettings,
preferredLanguage,
@@ -185,6 +217,7 @@ export class Controller {
defaultTerminalProfile ?? "default",
enableCheckpointsSetting ?? true,
await getCwd(getDesktopDir()),
this.cacheService,
task,
images,
files,
@@ -252,7 +285,7 @@ export class Controller {
// Update API handler with new mode (buildApiHandler now selects provider based on mode)
if (this.task) {
const { apiConfiguration } = await getAllExtensionState(this.context)
const apiConfiguration = this.cacheService.getApiConfiguration()
this.task.api = buildApiHandler({ ...apiConfiguration, taskId: this.task.taskId }, modeToSwitchTo)
}
@@ -319,27 +352,26 @@ export class Controller {
const { planActSeparateModelsSetting } = await getAllExtensionState(this.context)
const currentMode = await this.getCurrentMode()
// Get current API configuration from cache
const currentApiConfiguration = this.cacheService.getApiConfiguration()
let updatedConfig = { ...currentApiConfiguration }
if (planActSeparateModelsSetting) {
// Only update the current mode's provider
if (currentMode === "plan") {
await updateGlobalState(this.context, "planModeApiProvider", clineProvider)
updatedConfig.planModeApiProvider = clineProvider
} else {
await updateGlobalState(this.context, "actModeApiProvider", clineProvider)
updatedConfig.actModeApiProvider = clineProvider
}
} else {
// Update both modes to keep them in sync
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", clineProvider),
updateGlobalState(this.context, "actModeApiProvider", clineProvider),
])
updatedConfig.planModeApiProvider = clineProvider
updatedConfig.actModeApiProvider = clineProvider
}
// Get the updated API configuration (now includes the updated providers)
const { apiConfiguration } = await getAllExtensionState(this.context)
const updatedConfig = {
...apiConfiguration,
apiProvider: clineProvider,
}
// Update the API configuration through cache service
this.cacheService.setApiConfiguration(updatedConfig)
// Mark welcome view as completed since user has successfully logged in
await updateGlobalState(this.context, "welcomeViewCompleted", true)
@@ -501,21 +533,20 @@ export class Controller {
const openrouter: ApiProvider = "openrouter"
const currentMode = await this.getCurrentMode()
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", openrouter),
updateGlobalState(this.context, "actModeApiProvider", openrouter),
])
await storeSecret(this.context, "openRouterApiKey", apiKey)
// Update API configuration through cache service
const currentApiConfiguration = this.cacheService.getApiConfiguration()
const updatedConfig = {
...currentApiConfiguration,
planModeApiProvider: openrouter,
actModeApiProvider: openrouter,
openRouterApiKey: apiKey,
}
this.cacheService.setApiConfiguration(updatedConfig)
await this.postStateToWebview()
if (this.task) {
// Get the updated API configuration (now includes the updated providers)
const { apiConfiguration } = await getAllExtensionState(this.context)
const updatedConfig = {
...apiConfiguration,
openRouterApiKey: apiKey,
taskId: this.task.taskId,
}
this.task.api = buildApiHandler(updatedConfig, currentMode)
this.task.api = buildApiHandler({ ...updatedConfig, taskId: this.task.taskId }, currentMode)
}
// await this.postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) // bad ux if user is on welcome
}
@@ -689,8 +720,10 @@ export class Controller {
}
async getStateToPostToWebview(): Promise<ExtensionState> {
// Get API configuration from cache for immediate access
const apiConfiguration = this.cacheService.getApiConfiguration()
const {
apiConfiguration,
lastShownAnnouncementId,
taskHistory,
autoApprovalSettings,
@@ -831,18 +864,4 @@ export class Controller {
await updateGlobalState(this.context, "taskHistory", history)
return history
}
// private async clearState() {
// this.context.workspaceState.keys().forEach((key) => {
// this.context.workspaceState.update(key, undefined)
// })
// this.context.globalState.keys().forEach((key) => {
// this.context.globalState.update(key, undefined)
// })
// this.context.secrets.delete("apiKey")
// }
// secrets
// dev
}
@@ -1,7 +1,6 @@
import type { Controller } from "../index"
import { Empty } from "@shared/proto/cline/common"
import { UpdateApiConfigurationRequest } from "@shared/proto/cline/models"
import { updateApiConfiguration } from "../../storage/state"
import { buildApiHandler } from "@api/index"
import { convertProtoToApiConfiguration } from "@shared/proto-conversions/models/api-configuration-conversion"
@@ -25,7 +24,7 @@ export async function updateApiConfigurationProto(
const appApiConfiguration = convertProtoToApiConfiguration(request.apiConfiguration)
// Update the API configuration in storage
await updateApiConfiguration(controller.context, appApiConfiguration)
controller.cacheService.setApiConfiguration(appApiConfiguration)
// Update the task's API handler if there's an active task
if (controller.task) {
+2 -2
View File
@@ -19,13 +19,13 @@ export async function resetState(controller: Controller, request: ResetStateRequ
type: ShowMessageType.INFORMATION,
message: "Resetting global state...",
})
await resetGlobalState(controller.context)
await resetGlobalState(controller)
} else {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Resetting workspace state...",
})
await resetWorkspaceState(controller.context)
await resetWorkspaceState(controller)
}
if (controller.task) {
@@ -16,11 +16,7 @@ export async function toggleFavoriteModel(controller: Controller, request: Strin
}
const modelId = request.value
const { apiConfiguration } = await controller.getStateToPostToWebview()
if (!apiConfiguration) {
throw new Error("API configuration not found")
}
const apiConfiguration = controller.cacheService.getApiConfiguration()
const favoritedModelIds = apiConfiguration.favoritedModelIds || []
@@ -29,7 +25,12 @@ export async function toggleFavoriteModel(controller: Controller, request: Strin
? favoritedModelIds.filter((id) => id !== modelId)
: [...favoritedModelIds, modelId]
await updateGlobalState(controller.context, "favoritedModelIds", updatedFavorites)
// Update the complete API configuration through cache service
const updatedApiConfiguration = {
...apiConfiguration,
favoritedModelIds: updatedFavorites,
}
controller.cacheService.setApiConfiguration(updatedApiConfiguration)
// Capture telemetry for model favorite toggle
const isFavorited = !favoritedModelIds.includes(modelId)
+4 -5
View File
@@ -1,11 +1,10 @@
import { Controller } from ".."
import { Empty } from "@shared/proto/cline/common"
import { PlanActMode, UpdateSettingsRequest } from "@shared/proto/cline/state"
import { updateApiConfiguration } from "../../storage/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 { convertProtoApiConfigurationToApiConfiguration } from "../../../shared/proto-conversions/state/settings-conversion"
import { TelemetrySetting } from "@/shared/TelemetrySetting"
import { OpenaiReasoningEffort } from "@/shared/storage/types"
/**
* Updates multiple extension settings in a single request
@@ -18,7 +17,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett
// Update API configuration
if (request.apiConfiguration) {
const apiConfiguration = convertProtoApiConfigurationToApiConfiguration(request.apiConfiguration)
await updateApiConfiguration(controller.context, apiConfiguration)
controller.cacheService.setApiConfiguration(apiConfiguration)
if (controller.task) {
const currentMode = await controller.getCurrentMode()
+22 -8
View File
@@ -32,7 +32,8 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
refreshOpenRouterModels(controller, EmptyRequest.create()).then(async (response) => {
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, planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const apiConfiguration = controller.cacheService.getApiConfiguration()
const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const currentMode = await controller.getCurrentMode()
if (planActSeparateModelsSetting) {
@@ -42,26 +43,32 @@ 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])
const updatedConfig = {
...apiConfiguration,
[modelInfoField]: response.models[modelId],
}
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
} else {
// Shared models: update both plan and act modes
const planModelId = apiConfiguration.planModeOpenRouterModelId
const actModelId = apiConfiguration.actModeOpenRouterModelId
let updatedConfig = { ...apiConfiguration }
// Update plan mode model info if we have a model ID
if (planModelId && response.models[planModelId]) {
await updateGlobalState(controller.context, "planModeOpenRouterModelInfo", response.models[planModelId])
updatedConfig.planModeOpenRouterModelInfo = response.models[planModelId]
}
// Update act mode model info if we have a model ID
if (actModelId && response.models[actModelId]) {
await updateGlobalState(controller.context, "actModeOpenRouterModelInfo", response.models[actModelId])
updatedConfig.actModeOpenRouterModelInfo = response.models[actModelId]
}
// Post state update if we updated any model info
if ((planModelId && response.models[planModelId]) || (actModelId && response.models[actModelId])) {
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
}
@@ -71,7 +78,8 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
refreshGroqModels(controller, EmptyRequest.create()).then(async (response) => {
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, planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const apiConfiguration = controller.cacheService.getApiConfiguration()
const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const currentMode = await controller.getCurrentMode()
if (planActSeparateModelsSetting) {
@@ -81,26 +89,32 @@ 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])
const updatedConfig = {
...apiConfiguration,
[modelInfoField]: response.models[modelId],
}
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
} else {
// Shared models: update both plan and act modes
const planModelId = apiConfiguration.planModeGroqModelId
const actModelId = apiConfiguration.actModeGroqModelId
let updatedConfig = { ...apiConfiguration }
// Update plan mode model info if we have a model ID
if (planModelId && response.models[planModelId]) {
await updateGlobalState(controller.context, "planModeGroqModelInfo", response.models[planModelId])
updatedConfig.planModeGroqModelInfo = response.models[planModelId]
}
// Update act mode model info if we have a model ID
if (actModelId && response.models[actModelId]) {
await updateGlobalState(controller.context, "actModeGroqModelInfo", response.models[actModelId])
updatedConfig.actModeGroqModelInfo = response.models[actModelId]
}
// Post state update if we updated any model info
if ((planModelId && response.models[planModelId]) || (actModelId && response.models[actModelId])) {
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
}
+935
View File
@@ -0,0 +1,935 @@
import { ApiConfiguration } from "@shared/api"
import { updateGlobalState, updateWorkspaceState, getAllExtensionState, storeSecret } from "./state"
import { SecretKey, GlobalStateKey, LocalStateKey } from "./state-keys"
import { CACHE_SERVICE_NOT_INITIALIZED } from "./error-messages"
import type { ExtensionContext } from "vscode"
/**
* Interface for persistence error event data
*/
export interface PersistenceErrorEvent {
error: Error
}
/**
* In-memory cache service for fast state access
* Provides immediate reads/writes with async disk persistence
*/
export class CacheService {
private globalStateCache: Map<GlobalStateKey, any> = new Map()
private secretsCache: Map<SecretKey, string | undefined> = new Map()
private workspaceStateCache: Map<LocalStateKey, any> = new Map()
private context: ExtensionContext
private isInitialized = false
// Debounced persistence state
private pendingGlobalState = new Set<GlobalStateKey>()
private pendingSecrets = new Set<SecretKey>()
private pendingWorkspaceState = new Set<LocalStateKey>()
private persistenceTimeout: NodeJS.Timeout | null = null
private readonly PERSISTENCE_DELAY_MS = 500
// Callback for persistence errors
onPersistenceError?: (event: PersistenceErrorEvent) => void
constructor(context: ExtensionContext) {
this.context = context
}
/**
* Initialize the cache by loading data from disk
*/
async initialize(): Promise<void> {
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
// Use populate method to avoid triggering persistence during initialization
this.populateApiConfigurationCache(apiConfiguration)
}
this.isInitialized = true
console.log("CacheService initialized successfully")
} catch (error) {
console.error("Failed to initialize CacheService:", error)
throw error
}
}
/**
* Set method for global state keys - updates cache immediately and schedules debounced persistence
*/
setGlobalState<T>(key: GlobalStateKey, value: T): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.globalStateCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingGlobalState.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for global state keys - updates cache immediately and schedules debounced persistence
*/
setGlobalStateBatch(updates: Partial<Record<GlobalStateKey, any>>): 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)
this.pendingGlobalState.add(key as GlobalStateKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Set method for secret keys - updates cache immediately and schedules debounced persistence
*/
setSecret(key: SecretKey, value: string | undefined): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.secretsCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingSecrets.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for secret keys - updates cache immediately and schedules debounced persistence
*/
setSecretsBatch(updates: Partial<Record<SecretKey, string | undefined>>): 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.pendingSecrets.add(key as SecretKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Set method for workspace state keys - updates cache immediately and schedules debounced persistence
*/
setWorkspaceState<T>(key: LocalStateKey, value: T): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.workspaceStateCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingWorkspaceState.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for workspace state keys - updates cache immediately and schedules debounced persistence
*/
setWorkspaceStateBatch(updates: Partial<Record<LocalStateKey, any>>): 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.pendingWorkspaceState.add(key as LocalStateKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Convenience method for getting API configuration
* Ensures cache is initialized if not already done
*/
getApiConfiguration(): ApiConfiguration {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Construct API configuration from cached component keys
return this.constructApiConfigurationFromCache()
}
/**
* Convenience method for setting API configuration
*/
setApiConfiguration(apiConfiguration: ApiConfiguration): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
huggingFaceApiKey,
requestTimeoutMs,
// 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,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// 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,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
} = apiConfiguration
// Batch update global state keys
this.setGlobalStateBatch({
// Plan mode configuration updates
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configuration updates
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
// Global state updates
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
})
// Batch update secrets
this.setSecretsBatch({
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
huggingFaceApiKey,
})
}
/**
* Get method for global state keys - reads from in-memory cache
*/
getGlobalStateKey<T>(key: GlobalStateKey): T | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.globalStateCache.get(key) as T | undefined
}
/**
* Get method for secret keys - reads from in-memory cache
*/
getSecretKey(key: SecretKey): string | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.secretsCache.get(key)
}
/**
* Get method for workspace state keys - reads from in-memory cache
*/
getWorkspaceStateKey<T>(key: LocalStateKey): T | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.workspaceStateCache.get(key) as T | undefined
}
/**
* Reinitialize the cache service by clearing all state and reloading from disk
* Used for error recovery when write operations fail
*/
async reInitialize(): Promise<void> {
// Clear all cached data and pending state
this.dispose()
// Reinitialize from disk
await this.initialize()
}
/**
* Dispose of the cache service
*/
private dispose(): void {
if (this.persistenceTimeout) {
clearTimeout(this.persistenceTimeout)
this.persistenceTimeout = null
}
this.pendingGlobalState.clear()
this.pendingSecrets.clear()
this.pendingWorkspaceState.clear()
this.globalStateCache.clear()
this.secretsCache.clear()
this.workspaceStateCache.clear()
this.isInitialized = false
}
/**
* Schedule debounced persistence - simple timeout-based persistence
*/
private scheduleDebouncedPersistence(): void {
// Clear existing timeout if one is pending
if (this.persistenceTimeout) {
clearTimeout(this.persistenceTimeout)
}
// Schedule a new timeout to persist pending changes
this.persistenceTimeout = setTimeout(async () => {
try {
await Promise.all([
this.persistGlobalStateBatch(this.pendingGlobalState),
this.persistSecretsBatch(this.pendingSecrets),
this.persistWorkspaceStateBatch(this.pendingWorkspaceState),
])
// Clear pending sets on successful persistence
this.pendingGlobalState.clear()
this.pendingSecrets.clear()
this.pendingWorkspaceState.clear()
this.persistenceTimeout = null
} catch (error) {
console.error("Failed to persist pending changes:", error)
this.persistenceTimeout = null
// Call persistence error callback for error recovery
this.onPersistenceError?.({ error: error as Error })
}
}, this.PERSISTENCE_DELAY_MS)
}
/**
* Private method to batch persist global state keys with Promise.all
*/
private async persistGlobalStateBatch(keys: Set<GlobalStateKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.globalStateCache.get(key)
return this.context.globalState.update(key, value)
}),
)
} catch (error) {
console.error("Failed to persist global state batch:", error)
throw error
}
}
/**
* Private method to batch persist secrets with Promise.all
*/
private async persistSecretsBatch(keys: Set<SecretKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.secretsCache.get(key)
if (value) {
return this.context.secrets.store(key, value)
} else {
return this.context.secrets.delete(key)
}
}),
)
} catch (error) {
console.error("Failed to persist secrets batch:", error)
throw error
}
}
/**
* Private method to batch persist workspace state keys with Promise.all
*/
private async persistWorkspaceStateBatch(keys: Set<LocalStateKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.workspaceStateCache.get(key)
return this.context.workspaceState.update(key, value)
}),
)
} catch (error) {
console.error("Failed to persist workspace state batch:", error)
throw error
}
}
/**
* Private method to populate API configuration cache without triggering persistence
* Used during initialization
*/
private populateApiConfigurationCache(apiConfiguration: ApiConfiguration): void {
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
huggingFaceApiKey,
requestTimeoutMs,
// 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,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// 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,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
} = apiConfiguration
// Directly populate global state cache without triggering persistence
const globalStateUpdates = {
// Plan mode configuration updates
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configuration updates
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
// Global state updates
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
}
// Populate global state cache directly
Object.entries(globalStateUpdates).forEach(([key, value]) => {
this.globalStateCache.set(key as GlobalStateKey, value)
})
// Directly populate secrets cache without triggering persistence
const secretsUpdates = {
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
huggingFaceApiKey,
}
// Populate secrets cache directly
Object.entries(secretsUpdates).forEach(([key, value]) => {
this.secretsCache.set(key as SecretKey, value)
})
}
/**
* Construct API configuration from cached component keys
*/
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"),
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"),
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"),
// 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"),
// 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"),
planModeHuggingFaceModelId: this.globalStateCache.get("planModeHuggingFaceModelId"),
planModeHuggingFaceModelInfo: this.globalStateCache.get("planModeHuggingFaceModelInfo"),
// 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"),
actModeHuggingFaceModelId: this.globalStateCache.get("actModeHuggingFaceModelId"),
actModeHuggingFaceModelInfo: this.globalStateCache.get("actModeHuggingFaceModelInfo"),
} as ApiConfiguration
}
}
+1
View File
@@ -0,0 +1 @@
export const CACHE_SERVICE_NOT_INITIALIZED = "CacheService must be initialized before attempting to access state."
+11 -256
View File
@@ -12,6 +12,7 @@ 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
@@ -578,263 +579,18 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
}
}
export async function updateApiConfiguration(context: vscode.ExtensionContext, apiConfiguration: ApiConfiguration) {
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
huggingFaceApiKey,
huaweiCloudMaasApiKey,
// 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,
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,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
actModeHuaweiCloudMaasModelId,
actModeHuaweiCloudMaasModelInfo,
} = apiConfiguration
export async function resetWorkspaceState(controller: Controller) {
const context = controller.context
await Promise.all(context.workspaceState.keys().map((key) => controller.context.workspaceState.update(key, undefined)))
// OPTIMIZED: Batch all global state updates into 2 operations instead of 47
const batchedGlobalUpdates = {
// Plan mode configuration updates
planModeApiProvider,
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,
// Act mode configuration updates
actModeApiProvider,
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,
// Global state updates (27 keys)
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders: openAiHeaders || {},
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs: apiConfiguration.requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
}
// OPTIMIZED: Batch all secret updates into 1 operation instead of 23
const batchedSecretUpdates = {
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
huggingFaceApiKey,
huaweiCloudMaasApiKey,
}
// Execute batched operations in parallel for maximum performance
await Promise.all([updateGlobalStateBatch(context, batchedGlobalUpdates), updateSecretsBatch(context, batchedSecretUpdates)])
await controller.cacheService.reInitialize()
}
export async function resetWorkspaceState(context: vscode.ExtensionContext) {
for (const key of context.workspaceState.keys()) {
await context.workspaceState.update(key, undefined)
}
}
export async function resetGlobalState(context: vscode.ExtensionContext) {
export async function resetGlobalState(controller: Controller) {
// TODO: Reset all workspace states?
for (const key of context.globalState.keys()) {
await context.globalState.update(key, undefined)
}
const context = controller.context
await Promise.all(context.globalState.keys().map((key) => context.globalState.update(key, undefined)))
const secretKeys: SecretKey[] = [
"apiKey",
"openRouterApiKey",
@@ -864,7 +620,6 @@ export async function resetGlobalState(context: vscode.ExtensionContext) {
"huggingFaceApiKey",
"huaweiCloudMaasApiKey",
]
for (const key of secretKeys) {
await storeSecret(context, key, undefined)
}
await Promise.all(secretKeys.map((key) => storeSecret(context, key, undefined)))
await controller.cacheService.reInitialize()
}
+4 -5
View File
@@ -50,7 +50,7 @@ import { ContextManager } from "../context/context-management/ContextManager"
import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation"
import { formatResponse } from "../prompts/responses"
import { ensureTaskDirectoryExists } from "../storage/disk"
import { getGlobalState, getWorkspaceState } from "../storage/state"
import { CacheService } from "../storage/CacheService"
import { TaskState } from "./TaskState"
import { MessageStateHandler } from "./message-state"
import { AutoApprove } from "./tools/autoApprove"
@@ -86,6 +86,7 @@ export class ToolExecutor {
private clineIgnoreController: ClineIgnoreController,
private workspaceTracker: WorkspaceTracker,
private contextManager: ContextManager,
private cacheService: CacheService,
// Configuration & Settings
private autoApprovalSettings: AutoApprovalSettings,
@@ -1927,10 +1928,8 @@ export class ToolExecutor {
vscode.extensions.getExtension("saoudrizwan.claude-dev")?.packageJSON.version || "Unknown"
const systemInfo = `VSCode: ${vscode.version}, Node.js: ${process.version}, Architecture: ${os.arch()}`
const currentMode = this.mode
const apiProvider =
currentMode === "plan"
? await getGlobalState(this.context, "planModeApiProvider")
: await getGlobalState(this.context, "actModeApiProvider")
const apiConfig = this.cacheService.getApiConfiguration()
const apiProvider = currentMode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider
const providerAndModel = `${apiProvider} / ${this.api.getModel().id}`
// Ask user for confirmation
+9 -4
View File
@@ -85,6 +85,7 @@ import { MessageStateHandler } from "./message-state"
import { TaskState } from "./TaskState"
import { ToolExecutor } from "./ToolExecutor"
import { updateApiReqMsg } from "./utils"
import { CacheService } from "../storage/CacheService"
import { Mode, OpenaiReasoningEffort } from "@shared/storage/types"
import { ShowMessageType } from "@/shared/proto/index.host"
@@ -130,6 +131,9 @@ export class Task {
private reinitExistingTaskFromId: (taskId: string) => Promise<void>
private cancelTask: () => Promise<void>
// Cache service
private cacheService: CacheService
// User chat state
autoApprovalSettings: AutoApprovalSettings
browserSettings: BrowserSettings
@@ -159,6 +163,7 @@ export class Task {
defaultTerminalProfile: string,
enableCheckpointsSetting: boolean,
cwd: string,
cacheService: CacheService,
task?: string,
images?: string[],
files?: string[],
@@ -202,6 +207,7 @@ export class Task {
this.mode = mode
this.enableCheckpoints = enableCheckpointsSetting
this.cwd = cwd
this.cacheService = cacheService
// Set up MCP notification callback for real-time notifications
this.mcpHub.setNotificationCallback(async (serverName: string, level: string, message: string) => {
@@ -318,6 +324,7 @@ export class Task {
this.clineIgnoreController,
this.workspaceTracker,
this.contextManager,
this.cacheService,
this.autoApprovalSettings,
this.browserSettings,
cwd,
@@ -1661,10 +1668,8 @@ export class Task {
private async getCurrentProviderInfo(): Promise<{ modelId: string; providerId: string }> {
const modelId = this.api.getModel()?.id
const providerId =
this.mode === "plan"
? ((await getGlobalState(this.getContext(), "planModeApiProvider")) as string)
: ((await getGlobalState(this.getContext(), "actModeApiProvider")) as string)
const apiConfig = this.cacheService.getApiConfiguration()
const providerId = (this.mode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider) as string
return { modelId, providerId }
}
+18 -1
View File
@@ -4,6 +4,7 @@ import { getNonce } from "./getNonce"
import { WebviewProviderType } from "@/shared/webview/types"
import { Controller } from "@core/controller/index"
import { CacheService } from "@core/storage/CacheService"
import { findLast } from "@shared/array"
import { readFile } from "fs/promises"
import path from "node:path"
@@ -21,6 +22,7 @@ export abstract class WebviewProvider {
protected disposables: vscode.Disposable[] = []
controller: Controller
private clientId: string
private cacheService: CacheService
constructor(
readonly context: vscode.ExtensionContext,
@@ -30,7 +32,22 @@ export abstract class WebviewProvider {
WebviewProvider.activeInstances.add(this)
this.clientId = uuidv4()
WebviewProvider.clientIdMap.set(this, this.clientId)
this.controller = new Controller(context, (message) => this.postMessageToWebview(message), this.clientId)
// Create and initialize cache service
this.cacheService = new CacheService(context)
// Create controller with cache service
this.controller = new Controller(
context,
(message) => this.postMessageToWebview(message),
this.clientId,
this.cacheService,
)
// Initialize cache service asynchronously - critical for extension functionality
this.cacheService.initialize().catch((error) => {
console.error("CRITICAL: Failed to initialize CacheService - extension may not function properly:", error)
})
}
// Add a method to get the client ID
+9 -12
View File
@@ -7,13 +7,7 @@ import { WebviewProvider } from "@core/webview"
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
import { TaskServiceClient } from "webview-ui/src/services/grpc-client"
import { validateWorkspacePath, initializeGitRepository, getFileChanges, calculateToolSuccessRate } from "./GitHelper"
import {
updateGlobalState,
getAllExtensionState,
updateApiConfiguration,
storeSecret,
updateWorkspaceState,
} from "@core/storage/state"
import { updateGlobalState, getAllExtensionState, storeSecret } from "@core/storage/state"
import { ClineAsk, ExtensionMessage } from "@shared/ExtensionMessage"
import { ApiProvider } from "@shared/api"
import { HistoryItem } from "@shared/HistoryItem"
@@ -270,12 +264,15 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server
// Store the API key securely
await storeSecret(visibleWebview.controller.context, "clineAccountId", apiKey)
// Update the API configuration
await updateApiConfiguration(visibleWebview.controller.context, updatedConfig)
visibleWebview.controller.cacheService.setApiConfiguration(updatedConfig)
// Update global state to use cline provider
await updateGlobalState(visibleWebview.controller.context, "planModeApiProvider", "cline")
await updateGlobalState(visibleWebview.controller.context, "actModeApiProvider", "cline")
// Update cache service to use cline provider
const currentConfig = visibleWebview.controller.cacheService.getApiConfiguration()
visibleWebview.controller.cacheService.setApiConfiguration({
...currentConfig,
planModeApiProvider: "cline",
actModeApiProvider: "cline",
})
// Post state to webview to reflect changes
await visibleWebview.controller.postStateToWebview()
+7 -1
View File
@@ -1,5 +1,6 @@
import { activate } from "@/extension"
import { Controller } from "@core/controller"
import { CacheService } from "@core/storage/CacheService"
import { ExternalDiffViewProvider } from "@hosts/external/ExternalDiffviewProvider"
import { ExternalWebviewProvider } from "@hosts/external/ExternalWebviewProvider"
import { ExternalHostBridgeClientManager } from "@hosts/external/host-bridge-client-manager"
@@ -21,7 +22,12 @@ async function main() {
setupGlobalErrorHandlers()
activate(extensionContext)
const controller = new Controller(extensionContext, postMessage, uuidv4())
// Create and initialize cache service
const cacheService = new CacheService(extensionContext)
await cacheService.initialize()
// Create controller with cache service
const controller = new Controller(extensionContext, postMessage, uuidv4(), cacheService)
startProtobusService(controller)
}