From 2158165fc4a72e2279a8ff7f1e4d655c8d9d2050 Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Fri, 6 Jun 2025 12:43:03 -0700 Subject: [PATCH] [PROTOBUS] updateSettings & didUpdateSettings (#4073) * updateSettings proto mvp * changeset --- .changeset/blue-cobras-allow.md | 5 + proto/state.proto | 124 +++++++++ src/core/controller/index.ts | 55 ---- src/core/controller/state/updateSettings.ts | 85 ++++++ src/shared/ExtensionMessage.ts | 1 - src/shared/WebviewMessage.ts | 1 - .../state/settings-conversion.ts | 263 ++++++++++++++++++ .../src/components/settings/SettingsView.tsx | 140 +++++----- .../src/context/ExtensionStateContext.tsx | 41 ++- 9 files changed, 579 insertions(+), 136 deletions(-) create mode 100644 .changeset/blue-cobras-allow.md create mode 100644 src/core/controller/state/updateSettings.ts create mode 100644 src/shared/proto-conversions/state/settings-conversion.ts diff --git a/.changeset/blue-cobras-allow.md b/.changeset/blue-cobras-allow.md new file mode 100644 index 00000000..acd0c6a3 --- /dev/null +++ b/.changeset/blue-cobras-allow.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Migrated updateSettings to protos, removed didUpdateSettings, altered Plan/Act toggling in settings menu diff --git a/proto/state.proto b/proto/state.proto index 22006b3c..486efb7e 100644 --- a/proto/state.proto +++ b/proto/state.proto @@ -13,6 +13,7 @@ service StateService { rpc togglePlanActMode(TogglePlanActModeRequest) returns (Empty); rpc updateTerminalConnectionTimeout(Int64Request) returns (Int64); rpc updateAutoApprovalSettings(AutoApprovalSettingsRequest) returns (Empty); + rpc updateSettings(UpdateSettingsRequest) returns (Empty); } message State { @@ -64,3 +65,126 @@ message AutoApprovalSettingsRequest { bool enable_notifications = 6; repeated string favorites = 7; } + +// Message for updating settings +message UpdateSettingsRequest { + Metadata metadata = 1; + optional ApiConfiguration api_configuration = 2; + optional string custom_instructions_setting = 3; + optional string telemetry_setting = 4; + optional bool plan_act_separate_models_setting = 5; + optional bool enable_checkpoints_setting = 6; + optional bool mcp_marketplace_enabled = 7; + optional ChatSettings chat_settings = 8; + optional int64 shell_integration_timeout = 9; + optional bool terminal_reuse_enabled = 10; + optional bool mcp_responses_collapsed = 11; +} + +// Complete API Configuration message +message ApiConfiguration { + // Core API fields + optional string api_provider = 1; + optional string api_model_id = 2; + optional string api_key = 3; // anthropic + optional string api_base_url = 4; + + // Provider-specific API keys + optional string cline_api_key = 5; + optional string openrouter_api_key = 6; + optional string anthropic_base_url = 7; + optional string openai_api_key = 8; + optional string openai_native_api_key = 9; + optional string gemini_api_key = 10; + optional string deepseek_api_key = 11; + optional string requesty_api_key = 12; + optional string together_api_key = 13; + optional string fireworks_api_key = 14; + optional string qwen_api_key = 15; + optional string doubao_api_key = 16; + optional string mistral_api_key = 17; + optional string nebius_api_key = 18; + optional string asksage_api_key = 19; + optional string xai_api_key = 20; + optional string sambanova_api_key = 21; + optional string cerebras_api_key = 22; + + // Model IDs + optional string openrouter_model_id = 23; + optional string openai_model_id = 24; + optional string anthropic_model_id = 25; + optional string bedrock_model_id = 26; + optional string vertex_model_id = 27; + optional string gemini_model_id = 28; + optional string ollama_model_id = 29; + optional string lm_studio_model_id = 30; + optional string litellm_model_id = 31; + optional string requesty_model_id = 32; + optional string together_model_id = 33; + optional string fireworks_model_id = 34; + + // AWS Bedrock fields + optional bool aws_bedrock_custom_selected = 35; + optional string aws_bedrock_custom_model_base_id = 36; + optional string aws_access_key = 37; + optional string aws_secret_key = 38; + optional string aws_session_token = 39; + optional string aws_region = 40; + optional bool aws_use_cross_region_inference = 41; + optional bool aws_bedrock_use_prompt_cache = 42; + optional bool aws_use_profile = 43; + optional string aws_profile = 44; + optional string aws_bedrock_endpoint = 45; + + // Vertex AI fields + optional string vertex_project_id = 46; + optional string vertex_region = 47; + + // Base URLs and endpoints + optional string openai_base_url = 48; + optional string ollama_base_url = 49; + optional string lm_studio_base_url = 50; + optional string gemini_base_url = 51; + optional string litellm_base_url = 52; + optional string asksage_api_url = 53; + + // LiteLLM specific fields + optional string litellm_api_key = 54; + optional bool litellm_use_prompt_cache = 55; + + // Model configuration + optional int64 thinking_budget_tokens = 56; + optional string reasoning_effort = 57; + optional int64 request_timeout_ms = 58; + + // Fireworks specific + optional int64 fireworks_model_max_completion_tokens = 59; + optional int64 fireworks_model_max_tokens = 60; + + // Azure specific + optional string azure_api_version = 61; + + // Ollama specific + optional string ollama_api_options_ctx_num = 62; + + // Qwen specific + optional string qwen_api_line = 63; + + // OpenRouter specific + optional string openrouter_provider_sorting = 64; + + // VSCode LM (stored as JSON string due to complex type) + optional string vscode_lm_model_selector = 65; + + // Model info objects (stored as JSON strings) + optional string openrouter_model_info = 66; + optional string openai_model_info = 67; + optional string requesty_model_info = 68; + optional string litellm_model_info = 69; + + // OpenAI headers (stored as JSON string) + optional string openai_headers = 70; + + // Favorited model IDs + repeated string favorited_model_ids = 71; +} diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index f800ad74..2db549bb 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -285,61 +285,6 @@ export class Controller { await this.postStateToWebview() break } - case "updateSettings": { - // api config - if (message.apiConfiguration) { - await updateApiConfiguration(this.context, message.apiConfiguration) - if (this.task) { - this.task.api = buildApiHandler(message.apiConfiguration) - } - } - - // custom instructions - await this.updateCustomInstructions(message.customInstructionsSetting) - - // telemetry setting - if (message.telemetrySetting) { - await this.updateTelemetrySetting(message.telemetrySetting) - } - - // plan act setting - await updateGlobalState(this.context, "planActSeparateModelsSetting", message.planActSeparateModelsSetting) - - if (typeof message.enableCheckpointsSetting === "boolean") { - await updateGlobalState(this.context, "enableCheckpointsSetting", message.enableCheckpointsSetting) - } - - if (typeof message.mcpMarketplaceEnabled === "boolean") { - await updateGlobalState(this.context, "mcpMarketplaceEnabled", message.mcpMarketplaceEnabled) - } - - if (typeof message.mcpResponsesCollapsed === "boolean") { - await updateGlobalState(this.context, "mcpResponsesCollapsed", message.mcpResponsesCollapsed) - } - - // chat settings (including preferredLanguage and openAIReasoningEffort) - if (message.chatSettings) { - await updateGlobalState(this.context, "chatSettings", message.chatSettings) - if (this.task) { - this.task.chatSettings = message.chatSettings - } - } - - // terminal settings - if (typeof message.shellIntegrationTimeout === "number") { - await updateGlobalState(this.context, "shellIntegrationTimeout", message.shellIntegrationTimeout) - } - - if (typeof message.terminalReuseEnabled === "boolean") { - await updateGlobalState(this.context, "terminalReuseEnabled", message.terminalReuseEnabled) - } - - // after settings are updated, post state to webview - await this.postStateToWebview() - - await this.postMessageToWebview({ type: "didUpdateSettings" }) - break - } case "clearAllTaskHistory": { const answer = await vscode.window.showWarningMessage( "What would you like to delete?", diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts new file mode 100644 index 00000000..5ebb666b --- /dev/null +++ b/src/core/controller/state/updateSettings.ts @@ -0,0 +1,85 @@ +import { Controller } from ".." +import { Empty } from "../../../shared/proto/common" +import { UpdateSettingsRequest } from "../../../shared/proto/state" +import { updateApiConfiguration } from "../../storage/state" +import { buildApiHandler } from "../../../api" +import { convertProtoApiConfigurationToApiConfiguration } from "../../../shared/proto-conversions/state/settings-conversion" +import { convertProtoChatSettingsToChatSettings } from "../../../shared/proto-conversions/state/chat-settings-conversion" +import { TelemetrySetting } from "@/shared/TelemetrySetting" + +/** + * Updates multiple extension settings in a single request + * @param controller The controller instance + * @param request The request containing the settings to update + * @returns An empty response + */ +export async function updateSettings(controller: Controller, request: UpdateSettingsRequest): Promise { + try { + // Update API configuration + if (request.apiConfiguration) { + const apiConfiguration = convertProtoApiConfigurationToApiConfiguration(request.apiConfiguration) + await updateApiConfiguration(controller.context, apiConfiguration) + + if (controller.task) { + controller.task.api = buildApiHandler(apiConfiguration) + } + } + + // Update custom instructions + if (request.customInstructionsSetting !== undefined) { + await controller.updateCustomInstructions(request.customInstructionsSetting) + } + + // Update telemetry setting + if (request.telemetrySetting) { + await controller.updateTelemetrySetting(request.telemetrySetting as TelemetrySetting) + } + + // Update plan/act separate models setting + if (request.planActSeparateModelsSetting !== undefined) { + await controller.context.globalState.update("planActSeparateModelsSetting", request.planActSeparateModelsSetting) + } + + // Update checkpoints setting + if (request.enableCheckpointsSetting !== undefined) { + await controller.context.globalState.update("enableCheckpointsSetting", request.enableCheckpointsSetting) + } + + // Update MCP marketplace setting + if (request.mcpMarketplaceEnabled !== undefined) { + await controller.context.globalState.update("mcpMarketplaceEnabled", request.mcpMarketplaceEnabled) + } + + // Update MCP responses collapsed setting + if (request.mcpResponsesCollapsed !== undefined) { + await controller.context.globalState.update("mcpResponsesCollapsed", request.mcpResponsesCollapsed) + } + + // Update chat settings + if (request.chatSettings) { + const chatSettings = convertProtoChatSettingsToChatSettings(request.chatSettings) + await controller.context.globalState.update("chatSettings", chatSettings) + if (controller.task) { + controller.task.chatSettings = chatSettings + } + } + + // Update terminal timeout setting + if (request.shellIntegrationTimeout !== undefined) { + await controller.context.globalState.update("shellIntegrationTimeout", Number(request.shellIntegrationTimeout)) + } + + // Update terminal reuse setting + if (request.terminalReuseEnabled !== undefined) { + await controller.context.globalState.update("terminalReuseEnabled", request.terminalReuseEnabled) + } + + // Post updated state to webview + await controller.postStateToWebview() + + return Empty.create() + } catch (error) { + console.error("Failed to update settings:", error) + throw error + } +} diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 483f75b7..998b5f7b 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -22,7 +22,6 @@ export interface ExtensionMessage { | "mcpServers" | "relinquishControl" | "mcpDownloadDetails" - | "didUpdateSettings" | "userCreditsBalance" | "userCreditsUsage" | "userCreditsPayments" diff --git a/src/shared/WebviewMessage.ts b/src/shared/WebviewMessage.ts index 4c9a9561..9198544c 100644 --- a/src/shared/WebviewMessage.ts +++ b/src/shared/WebviewMessage.ts @@ -17,7 +17,6 @@ export interface WebviewMessage { | "searchCommits" | "fetchLatestMcpServersFromHub" | "telemetrySetting" - | "updateSettings" | "clearAllTaskHistory" | "fetchUserCreditsData" | "grpc_request" diff --git a/src/shared/proto-conversions/state/settings-conversion.ts b/src/shared/proto-conversions/state/settings-conversion.ts new file mode 100644 index 00000000..41d17be2 --- /dev/null +++ b/src/shared/proto-conversions/state/settings-conversion.ts @@ -0,0 +1,263 @@ +import { ApiConfiguration } from "@shared/api" +import { ChatSettings } from "@shared/ChatSettings" +import { + ApiConfiguration as ProtoApiConfiguration, + ChatSettings as ProtoChatSettings, + PlanActMode, +} from "../../../shared/proto/state" + +/** + * Converts domain ApiConfiguration objects to proto ApiConfiguration objects + */ +export function convertApiConfigurationToProtoApiConfiguration(config: ApiConfiguration): ProtoApiConfiguration { + return ProtoApiConfiguration.create({ + // Core API fields + apiProvider: config.apiProvider, + apiModelId: config.apiModelId, + apiKey: config.apiKey, + + // Provider-specific API keys + clineApiKey: config.clineApiKey, + openrouterApiKey: config.openRouterApiKey, + anthropicBaseUrl: config.anthropicBaseUrl, + openaiApiKey: config.openAiApiKey, + openaiNativeApiKey: config.openAiNativeApiKey, + geminiApiKey: config.geminiApiKey, + deepseekApiKey: config.deepSeekApiKey, + requestyApiKey: config.requestyApiKey, + togetherApiKey: config.togetherApiKey, + fireworksApiKey: config.fireworksApiKey, + qwenApiKey: config.qwenApiKey, + doubaoApiKey: config.doubaoApiKey, + mistralApiKey: config.mistralApiKey, + nebiusApiKey: config.nebiusApiKey, + asksageApiKey: config.asksageApiKey, + xaiApiKey: config.xaiApiKey, + sambanovaApiKey: config.sambanovaApiKey, + cerebrasApiKey: config.cerebrasApiKey, + + // Model IDs - each provider has its own field + openrouterModelId: config.openRouterModelId, + openaiModelId: config.openAiModelId, + anthropicModelId: config.apiModelId, + bedrockModelId: config.apiModelId, + vertexModelId: config.apiModelId, + geminiModelId: config.apiModelId, + ollamaModelId: config.ollamaModelId, + lmStudioModelId: config.lmStudioModelId, + litellmModelId: config.liteLlmModelId, + requestyModelId: config.requestyModelId, + togetherModelId: config.togetherModelId, + fireworksModelId: config.fireworksModelId, + + // AWS Bedrock fields + awsBedrockCustomSelected: config.awsBedrockCustomSelected, + awsBedrockCustomModelBaseId: config.awsBedrockCustomModelBaseId, + awsAccessKey: config.awsAccessKey, + awsSecretKey: config.awsSecretKey, + awsSessionToken: config.awsSessionToken, + awsRegion: config.awsRegion, + awsUseCrossRegionInference: config.awsUseCrossRegionInference, + awsBedrockUsePromptCache: config.awsBedrockUsePromptCache, + awsUseProfile: config.awsUseProfile, + awsProfile: config.awsProfile, + awsBedrockEndpoint: config.awsBedrockEndpoint, + + // Vertex AI fields + vertexProjectId: config.vertexProjectId, + vertexRegion: config.vertexRegion, + + // Base URLs and endpoints + openaiBaseUrl: config.openAiBaseUrl, + ollamaBaseUrl: config.ollamaBaseUrl, + lmStudioBaseUrl: config.lmStudioBaseUrl, + geminiBaseUrl: config.geminiBaseUrl, + litellmBaseUrl: config.liteLlmBaseUrl, + asksageApiUrl: config.asksageApiUrl, + + // LiteLLM specific fields + litellmApiKey: config.liteLlmApiKey, + litellmUsePromptCache: config.liteLlmUsePromptCache, + + // Model configuration + thinkingBudgetTokens: config.thinkingBudgetTokens ? Number(config.thinkingBudgetTokens) : undefined, + reasoningEffort: config.reasoningEffort, + requestTimeoutMs: config.requestTimeoutMs ? Number(config.requestTimeoutMs) : undefined, + + // Fireworks specific + fireworksModelMaxCompletionTokens: config.fireworksModelMaxCompletionTokens + ? Number(config.fireworksModelMaxCompletionTokens) + : undefined, + fireworksModelMaxTokens: config.fireworksModelMaxTokens ? Number(config.fireworksModelMaxTokens) : undefined, + + // Azure specific + azureApiVersion: config.azureApiVersion, + + // Ollama specific + ollamaApiOptionsCtxNum: config.ollamaApiOptionsCtxNum, + + // Qwen specific + qwenApiLine: config.qwenApiLine, + + // OpenRouter specific + openrouterProviderSorting: config.openRouterProviderSorting, + + // Complex objects stored as JSON strings + vscodeLmModelSelector: config.vsCodeLmModelSelector ? JSON.stringify(config.vsCodeLmModelSelector) : undefined, + openrouterModelInfo: config.openRouterModelInfo ? JSON.stringify(config.openRouterModelInfo) : undefined, + openaiModelInfo: config.openAiModelInfo ? JSON.stringify(config.openAiModelInfo) : undefined, + requestyModelInfo: config.requestyModelInfo ? JSON.stringify(config.requestyModelInfo) : undefined, + litellmModelInfo: config.liteLlmModelInfo ? JSON.stringify(config.liteLlmModelInfo) : undefined, + openaiHeaders: config.openAiHeaders ? JSON.stringify(config.openAiHeaders) : undefined, + + // Arrays + favoritedModelIds: config.favoritedModelIds || [], + }) +} + +/** + * Converts proto ApiConfiguration objects to domain ApiConfiguration objects + */ +export function convertProtoApiConfigurationToApiConfiguration(protoConfig: ProtoApiConfiguration): ApiConfiguration { + // eslint-disable-next-line eslint-rules/no-protobuf-object-literals + const config: ApiConfiguration = { + // Core API fields + apiProvider: protoConfig.apiProvider as any, + apiModelId: protoConfig.apiModelId, + apiKey: protoConfig.apiKey, + + // Provider-specific API keys + clineApiKey: protoConfig.clineApiKey, + openRouterApiKey: protoConfig.openrouterApiKey, + anthropicBaseUrl: protoConfig.anthropicBaseUrl, + openAiApiKey: protoConfig.openaiApiKey, + openAiNativeApiKey: protoConfig.openaiNativeApiKey, + geminiApiKey: protoConfig.geminiApiKey, + deepSeekApiKey: protoConfig.deepseekApiKey, + requestyApiKey: protoConfig.requestyApiKey, + togetherApiKey: protoConfig.togetherApiKey, + fireworksApiKey: protoConfig.fireworksApiKey, + qwenApiKey: protoConfig.qwenApiKey, + doubaoApiKey: protoConfig.doubaoApiKey, + mistralApiKey: protoConfig.mistralApiKey, + nebiusApiKey: protoConfig.nebiusApiKey, + asksageApiKey: protoConfig.asksageApiKey, + xaiApiKey: protoConfig.xaiApiKey, + sambanovaApiKey: protoConfig.sambanovaApiKey, + cerebrasApiKey: protoConfig.cerebrasApiKey, + + // Model IDs + openRouterModelId: protoConfig.openrouterModelId, + openAiModelId: protoConfig.openaiModelId, + ollamaModelId: protoConfig.ollamaModelId, + lmStudioModelId: protoConfig.lmStudioModelId, + liteLlmModelId: protoConfig.litellmModelId, + requestyModelId: protoConfig.requestyModelId, + togetherModelId: protoConfig.togetherModelId, + fireworksModelId: protoConfig.fireworksModelId, + + // AWS Bedrock fields + awsBedrockCustomSelected: protoConfig.awsBedrockCustomSelected, + awsBedrockCustomModelBaseId: protoConfig.awsBedrockCustomModelBaseId as any, + awsAccessKey: protoConfig.awsAccessKey, + awsSecretKey: protoConfig.awsSecretKey, + awsSessionToken: protoConfig.awsSessionToken, + awsRegion: protoConfig.awsRegion, + awsUseCrossRegionInference: protoConfig.awsUseCrossRegionInference, + awsBedrockUsePromptCache: protoConfig.awsBedrockUsePromptCache, + awsUseProfile: protoConfig.awsUseProfile, + awsProfile: protoConfig.awsProfile, + awsBedrockEndpoint: protoConfig.awsBedrockEndpoint, + + // Vertex AI fields + vertexProjectId: protoConfig.vertexProjectId, + vertexRegion: protoConfig.vertexRegion, + + // Base URLs and endpoints + openAiBaseUrl: protoConfig.openaiBaseUrl, + ollamaBaseUrl: protoConfig.ollamaBaseUrl, + lmStudioBaseUrl: protoConfig.lmStudioBaseUrl, + geminiBaseUrl: protoConfig.geminiBaseUrl, + liteLlmBaseUrl: protoConfig.litellmBaseUrl, + asksageApiUrl: protoConfig.asksageApiUrl, + + // LiteLLM specific fields + liteLlmApiKey: protoConfig.litellmApiKey, + liteLlmUsePromptCache: protoConfig.litellmUsePromptCache, + + // Model configuration + thinkingBudgetTokens: protoConfig.thinkingBudgetTokens ? Number(protoConfig.thinkingBudgetTokens) : undefined, + reasoningEffort: protoConfig.reasoningEffort, + requestTimeoutMs: protoConfig.requestTimeoutMs ? Number(protoConfig.requestTimeoutMs) : undefined, + + // Fireworks specific + fireworksModelMaxCompletionTokens: protoConfig.fireworksModelMaxCompletionTokens + ? Number(protoConfig.fireworksModelMaxCompletionTokens) + : undefined, + fireworksModelMaxTokens: protoConfig.fireworksModelMaxTokens ? Number(protoConfig.fireworksModelMaxTokens) : undefined, + + // Azure specific + azureApiVersion: protoConfig.azureApiVersion, + + // Ollama specific + ollamaApiOptionsCtxNum: protoConfig.ollamaApiOptionsCtxNum, + + // Qwen specific + qwenApiLine: protoConfig.qwenApiLine, + + // OpenRouter specific + openRouterProviderSorting: protoConfig.openrouterProviderSorting, + + // Arrays + favoritedModelIds: protoConfig.favoritedModelIds || [], + } + + // Handle complex JSON objects + try { + if (protoConfig.vscodeLmModelSelector) { + config.vsCodeLmModelSelector = JSON.parse(protoConfig.vscodeLmModelSelector) + } + if (protoConfig.openrouterModelInfo) { + config.openRouterModelInfo = JSON.parse(protoConfig.openrouterModelInfo) + } + if (protoConfig.openaiModelInfo) { + config.openAiModelInfo = JSON.parse(protoConfig.openaiModelInfo) + } + if (protoConfig.requestyModelInfo) { + config.requestyModelInfo = JSON.parse(protoConfig.requestyModelInfo) + } + if (protoConfig.litellmModelInfo) { + config.liteLlmModelInfo = JSON.parse(protoConfig.litellmModelInfo) + } + if (protoConfig.openaiHeaders) { + config.openAiHeaders = JSON.parse(protoConfig.openaiHeaders) + } + } catch (error) { + console.error("Failed to parse complex JSON objects in API configuration:", error) + } + + return config +} + +/** + * Converts domain ChatSettings objects to proto ChatSettings objects + */ +export function convertChatSettingsToProtoChatSettings(chatSettings: ChatSettings): ProtoChatSettings { + return ProtoChatSettings.create({ + mode: chatSettings.mode === "plan" ? PlanActMode.PLAN : PlanActMode.ACT, + preferredLanguage: chatSettings.preferredLanguage, + openAiReasoningEffort: chatSettings.openAIReasoningEffort, + }) +} + +/** + * Converts proto ChatSettings objects to domain ChatSettings objects + */ +export function convertProtoChatSettingsToChatSettings(protoChatSettings: ProtoChatSettings): ChatSettings { + // eslint-disable-next-line eslint-rules/no-protobuf-object-literals + return { + mode: protoChatSettings.mode === PlanActMode.PLAN ? "plan" : "act", + preferredLanguage: protoChatSettings.preferredLanguage, + openAIReasoningEffort: protoChatSettings.openAiReasoningEffort as "low" | "medium" | "high" | undefined, + } +} diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 556b6dbd..5bb4f837 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -7,7 +7,7 @@ import { validateApiConfiguration, validateModelId } from "@/utils/validate" import { vscode } from "@/utils/vscode" import { ExtensionMessage } from "@shared/ExtensionMessage" import { EmptyRequest } from "@shared/proto/common" -import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/state" +import { PlanActMode, TogglePlanActModeRequest, UpdateSettingsRequest } from "@shared/proto/state" import { VSCodeButton, VSCodeCheckbox, VSCodeLink, VSCodeTextArea } from "@vscode/webview-ui-toolkit/react" import { CheckCheck, FlaskConical, Info, LucideIcon, Settings, SquareMousePointer, SquareTerminal, Webhook } from "lucide-react" import { memo, useCallback, useEffect, useRef, useState } from "react" @@ -21,6 +21,8 @@ import PreferredLanguageSetting from "./PreferredLanguageSetting" // Added impor import Section from "./Section" import SectionHeader from "./SectionHeader" import TerminalSettingsSection from "./TerminalSettingsSection" +import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" +import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" const { IS_DEV } = process.env // Styles for the tab system @@ -150,9 +152,7 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { }) const [apiErrorMessage, setApiErrorMessage] = useState(undefined) const [modelIdErrorMessage, setModelIdErrorMessage] = useState(undefined) - const [pendingTabChange, setPendingTabChange] = useState<"plan" | "act" | null>(null) - - const handleSubmit = (withoutDone: boolean = false) => { + const handleSubmit = async (withoutDone: boolean = false) => { const apiValidationResult = validateApiConfiguration(apiConfiguration) const modelIdValidationResult = validateModelId(apiConfiguration, openRouterModels) @@ -180,18 +180,26 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { apiConfigurationToSubmit = undefined } - vscode.postMessage({ - type: "updateSettings", - planActSeparateModelsSetting, - customInstructionsSetting: customInstructions, - telemetrySetting, - enableCheckpointsSetting, - mcpMarketplaceEnabled, - shellIntegrationTimeout, - terminalReuseEnabled, - mcpResponsesCollapsed, - apiConfiguration: apiConfigurationToSubmit, - }) + try { + await StateServiceClient.updateSettings( + UpdateSettingsRequest.create({ + planActSeparateModelsSetting, + customInstructionsSetting: customInstructions, + telemetrySetting, + enableCheckpointsSetting, + mcpMarketplaceEnabled, + shellIntegrationTimeout, + terminalReuseEnabled, + mcpResponsesCollapsed, + apiConfiguration: apiConfigurationToSubmit + ? convertApiConfigurationToProtoApiConfiguration(apiConfigurationToSubmit) + : undefined, + chatSettings: chatSettings ? convertChatSettingsToProtoChatSettings(chatSettings) : undefined, + }), + ) + } catch (error) { + console.error("Failed to update settings:", error) + } if (!withoutDone) { onDone() @@ -316,59 +324,42 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { If we only want to run code once on mount we can use react-use's useEffectOnce or useMount */ - const handleMessage = useCallback( - (event: MessageEvent) => { - const message: ExtensionMessage = event.data - switch (message.type) { - case "didUpdateSettings": - if (pendingTabChange) { - StateServiceClient.togglePlanActMode( - TogglePlanActModeRequest.create({ - chatSettings: { - mode: pendingTabChange === "plan" ? PlanActMode.PLAN : PlanActMode.ACT, - preferredLanguage: chatSettings.preferredLanguage, - openAiReasoningEffort: chatSettings.openAIReasoningEffort, - }, - }), - ) - setPendingTabChange(null) - } - break - // Handle tab navigation through targetSection prop instead - case "grpc_response": - if (message.grpc_response?.message?.action === "scrollToSettings") { - const tabId = message.grpc_response?.message?.value - if (tabId) { - console.log("Opening settings tab from GRPC response:", tabId) - // Check if the value corresponds to a valid tab ID - const isValidTabId = SETTINGS_TABS.some((tab) => tab.id === tabId) + const handleMessage = useCallback((event: MessageEvent) => { + const message: ExtensionMessage = event.data + switch (message.type) { + // Handle tab navigation through targetSection prop instead + case "grpc_response": + if (message.grpc_response?.message?.action === "scrollToSettings") { + const tabId = message.grpc_response?.message?.value + if (tabId) { + console.log("Opening settings tab from GRPC response:", tabId) + // Check if the value corresponds to a valid tab ID + const isValidTabId = SETTINGS_TABS.some((tab) => tab.id === tabId) - if (isValidTabId) { - // Set the active tab directly - setActiveTab(tabId) - } else { - // Fall back to the old behavior of scrolling to an element - setTimeout(() => { - const element = document.getElementById(tabId) - if (element) { - element.scrollIntoView({ behavior: "smooth" }) + if (isValidTabId) { + // Set the active tab directly + setActiveTab(tabId) + } else { + // Fall back to the old behavior of scrolling to an element + setTimeout(() => { + const element = document.getElementById(tabId) + if (element) { + element.scrollIntoView({ behavior: "smooth" }) - element.style.transition = "background-color 0.5s ease" - element.style.backgroundColor = "var(--vscode-textPreformat-background)" + element.style.transition = "background-color 0.5s ease" + element.style.backgroundColor = "var(--vscode-textPreformat-background)" - setTimeout(() => { - element.style.backgroundColor = "transparent" - }, 1200) - } - }, 300) - } + setTimeout(() => { + element.style.backgroundColor = "transparent" + }, 1200) + } + }, 300) } } - break - } - }, - [pendingTabChange], - ) + } + break + } + }, []) useEvent("message", handleMessage) @@ -380,12 +371,27 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { } } - const handlePlanActModeChange = (tab: "plan" | "act") => { + const handlePlanActModeChange = async (tab: "plan" | "act") => { if (tab === chatSettings.mode) { return } - setPendingTabChange(tab) - handleSubmit(true) + + // Update settings first to ensure any changes to the current tab are saved + await handleSubmit(true) + + try { + await StateServiceClient.togglePlanActMode( + TogglePlanActModeRequest.create({ + chatSettings: { + mode: tab === "plan" ? PlanActMode.PLAN : PlanActMode.ACT, + preferredLanguage: chatSettings.preferredLanguage, + openAiReasoningEffort: chatSettings.openAIReasoningEffort, + }, + }), + ) + } catch (error) { + console.error("Failed to toggle Plan/Act mode:", error) + } } // Track active tab diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 105a7e28..570b7a00 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -1,6 +1,7 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react" import { useEvent } from "react-use" import { EmptyRequest } from "@shared/proto/common" +import { UpdateSettingsRequest } from "@shared/proto/state" import { WebviewProviderType as WebviewProviderTypeEnum, WebviewProviderTypeRequest } from "@shared/proto/ui" import { convertProtoToClineMessage } from "@shared/proto-conversions/cline-message" import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" @@ -650,22 +651,38 @@ export const ExtensionStateContextProvider: React.FC<{ setMcpMarketplaceCatalog: (catalog: McpMarketplaceCatalog) => setMcpMarketplaceCatalog(catalog), setShowMcp, closeMcpView, - setChatSettings: (value) => { + setChatSettings: async (value) => { setState((prevState) => ({ ...prevState, chatSettings: value, })) - vscode.postMessage({ - type: "updateSettings", - chatSettings: value, - apiConfiguration: state.apiConfiguration, - customInstructionsSetting: state.customInstructions, - telemetrySetting: state.telemetrySetting, - planActSeparateModelsSetting: state.planActSeparateModelsSetting, - enableCheckpointsSetting: state.enableCheckpointsSetting, - mcpMarketplaceEnabled: state.mcpMarketplaceEnabled, - mcpResponsesCollapsed: state.mcpResponsesCollapsed, - }) + + try { + // Import the conversion functions + const { convertApiConfigurationToProtoApiConfiguration } = await import( + "@shared/proto-conversions/state/settings-conversion" + ) + const { convertChatSettingsToProtoChatSettings } = await import( + "@shared/proto-conversions/state/chat-settings-conversion" + ) + + await StateServiceClient.updateSettings( + UpdateSettingsRequest.create({ + chatSettings: convertChatSettingsToProtoChatSettings(value), + apiConfiguration: state.apiConfiguration + ? convertApiConfigurationToProtoApiConfiguration(state.apiConfiguration) + : undefined, + customInstructionsSetting: state.customInstructions, + telemetrySetting: state.telemetrySetting, + planActSeparateModelsSetting: state.planActSeparateModelsSetting, + enableCheckpointsSetting: state.enableCheckpointsSetting, + mcpMarketplaceEnabled: state.mcpMarketplaceEnabled, + mcpResponsesCollapsed: state.mcpResponsesCollapsed, + }), + ) + } catch (error) { + console.error("Failed to update chat settings:", error) + } }, setGlobalClineRulesToggles: (toggles) => setState((prevState) => ({