From d4d5a49e67ff0eaddb8ed5b1d0bbd716f7f4343c Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Thu, 26 Jun 2025 10:40:37 -0700 Subject: [PATCH 01/60] Refactor autoApprove out of task class (#4233) * Refactor auto approve out of task class * Rebase fixes * cleanup * reorg --- .changeset/young-bulldogs-raise.md | 5 ++ .../state/updateAutoApprovalSettings.ts | 2 +- src/core/task/ToolExecutor.ts | 25 +++++- src/core/task/index.ts | 72 ++-------------- src/core/task/tools/autoApprove.ts | 83 +++++++++++++++++++ 5 files changed, 118 insertions(+), 69 deletions(-) create mode 100644 .changeset/young-bulldogs-raise.md create mode 100644 src/core/task/tools/autoApprove.ts diff --git a/.changeset/young-bulldogs-raise.md b/.changeset/young-bulldogs-raise.md new file mode 100644 index 00000000..bba9851e --- /dev/null +++ b/.changeset/young-bulldogs-raise.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Refactor task class, moving auto approve diff --git a/src/core/controller/state/updateAutoApprovalSettings.ts b/src/core/controller/state/updateAutoApprovalSettings.ts index cc38e230..cab4ca3c 100644 --- a/src/core/controller/state/updateAutoApprovalSettings.ts +++ b/src/core/controller/state/updateAutoApprovalSettings.ts @@ -22,7 +22,7 @@ export async function updateAutoApprovalSettings(controller: Controller, request await updateGlobalState(controller.context, "autoApprovalSettings", settings) if (controller.task) { - controller.task.autoApprovalSettings = settings + controller.task.updateAutoApprovalSettings(settings) } await controller.postStateToWebview() diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index c85059f8..6507b39e 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -11,6 +11,7 @@ import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { ChatSettings } from "@shared/ChatSettings" import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message" +import { AutoApprove } from "./tools/autoApprove" import { BrowserAction, BrowserActionResult, @@ -57,6 +58,17 @@ import { setTimeout as setTimeoutPromise } from "node:timers/promises" import { ChangeLocation, StreamingJsonReplacer } from "../assistant-message/diff-json" export class ToolExecutor { + private autoApprover: AutoApprove + + // Auto-approval methods using the AutoApprove class + private shouldAutoApproveTool(toolName: ToolUseName): boolean | [boolean, boolean] { + return this.autoApprover.shouldAutoApproveTool(toolName) + } + + private shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean { + return this.autoApprover.shouldAutoApproveToolWithPath(blockname, autoApproveActionpath) + } + constructor( // Core Services & Managers private context: vscode.ExtensionContext, @@ -96,13 +108,20 @@ export class ToolExecutor { private saveCheckpoint: (isAttemptCompletionMessage?: boolean) => Promise, private reinitExistingTaskFromId: (taskId: string) => Promise, private cancelTask: () => Promise, - private shouldAutoApproveTool: (toolName: ToolUseName) => boolean | [boolean, boolean], - private shouldAutoApproveToolWithPath: (blockname: ToolUseName, autoApproveActionpath: string | undefined) => boolean, private sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise, private removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise, private executeCommandTool: (command: string) => Promise<[boolean, any]>, private doesLatestTaskCompletionHaveNewChanges: () => Promise, - ) {} + ) { + this.autoApprover = new AutoApprove(autoApprovalSettings) + } + + /** + * Updates the auto approval settings + */ + public updateAutoApprovalSettings(settings: AutoApprovalSettings): void { + this.autoApprover.updateSettings(settings) + } private pushToolResult = (content: ToolResponse, block: ToolUse) => { const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api) diff --git a/src/core/task/index.ts b/src/core/task/index.ts index b2566707..456db6ff 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -314,8 +314,6 @@ export class Task { this.saveCheckpoint.bind(this), this.reinitExistingTaskFromId.bind(this), this.cancelTask.bind(this), - this.shouldAutoApproveTool.bind(this), - this.shouldAutoApproveToolWithPath.bind(this), this.sayAndCreateMissingParamError.bind(this), this.removeLastPartialMessageIfExistsWithType.bind(this), this.executeCommandTool.bind(this), @@ -333,6 +331,13 @@ export class Task { return context } + /** + * Updates the auto approval settings for this task + */ + public updateAutoApprovalSettings(settings: AutoApprovalSettings): void { + this.toolExecutor.updateAutoApprovalSettings(settings) + } + async restoreCheckpoint(messageTs: number, restoreType: ClineCheckpointRestore, offset?: number) { const clineMessages = this.messageStateHandler.getClineMessages() const messageIndex = clineMessages.findIndex((m) => m.ts === messageTs) - (offset || 0) @@ -1554,69 +1559,6 @@ export class Task { } } - // Check if the tool should be auto-approved based on the settings - // Returns bool for most tools, and tuple for tools with nested settings - shouldAutoApproveTool(toolName: ToolUseName): boolean | [boolean, boolean] { - if (this.autoApprovalSettings.enabled) { - switch (toolName) { - case "read_file": - case "list_files": - case "list_code_definition_names": - case "search_files": - return [ - this.autoApprovalSettings.actions.readFiles, - this.autoApprovalSettings.actions.readFilesExternally ?? false, - ] - case "new_rule": - case "write_to_file": - case "replace_in_file": - return [ - this.autoApprovalSettings.actions.editFiles, - this.autoApprovalSettings.actions.editFilesExternally ?? false, - ] - case "execute_command": - return [ - this.autoApprovalSettings.actions.executeSafeCommands ?? false, - this.autoApprovalSettings.actions.executeAllCommands ?? false, - ] - case "browser_action": - return this.autoApprovalSettings.actions.useBrowser - case "web_fetch": - return this.autoApprovalSettings.actions.useBrowser - case "access_mcp_resource": - case "use_mcp_tool": - return this.autoApprovalSettings.actions.useMcp - } - } - return false - } - - // Check if the tool should be auto-approved based on the settings - // and the path of the action. Returns true if the tool should be auto-approved - // based on the user's settings and the path of the action. - shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean { - let isLocalRead: boolean = false - if (autoApproveActionpath) { - const absolutePath = path.resolve(cwd, autoApproveActionpath) - isLocalRead = absolutePath.startsWith(cwd) - } else { - // If we do not get a path for some reason, default to a (safer) false return - isLocalRead = false - } - - // Get auto-approve settings for local and external edits - const autoApproveResult = this.shouldAutoApproveTool(blockname) - const [autoApproveLocal, autoApproveExternal] = Array.isArray(autoApproveResult) - ? autoApproveResult - : [autoApproveResult, false] - - if ((isLocalRead && autoApproveLocal) || (!isLocalRead && autoApproveLocal && autoApproveExternal)) { - return true - } else { - return false - } - } - /** * Migrates the disableBrowserTool setting from VSCode configuration to browserSettings */ diff --git a/src/core/task/tools/autoApprove.ts b/src/core/task/tools/autoApprove.ts new file mode 100644 index 00000000..8411a4ae --- /dev/null +++ b/src/core/task/tools/autoApprove.ts @@ -0,0 +1,83 @@ +import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" +import { ToolUseName } from "@core/assistant-message" +import * as path from "path" +import * as vscode from "vscode" +import os from "os" + +export const cwd = + vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") + +export class AutoApprove { + autoApprovalSettings: AutoApprovalSettings + + constructor(autoApprovalSettings: AutoApprovalSettings) { + this.autoApprovalSettings = autoApprovalSettings + } + + // Check if the tool should be auto-approved based on the settings + // Returns bool for most tools, and tuple for tools with nested settings + shouldAutoApproveTool(toolName: ToolUseName): boolean | [boolean, boolean] { + if (this.autoApprovalSettings.enabled) { + switch (toolName) { + case "read_file": + case "list_files": + case "list_code_definition_names": + case "search_files": + return [ + this.autoApprovalSettings.actions.readFiles, + this.autoApprovalSettings.actions.readFilesExternally ?? false, + ] + case "new_rule": + case "write_to_file": + case "replace_in_file": + return [ + this.autoApprovalSettings.actions.editFiles, + this.autoApprovalSettings.actions.editFilesExternally ?? false, + ] + case "execute_command": + return [ + this.autoApprovalSettings.actions.executeSafeCommands ?? false, + this.autoApprovalSettings.actions.executeAllCommands ?? false, + ] + case "browser_action": + return this.autoApprovalSettings.actions.useBrowser + case "web_fetch": + return this.autoApprovalSettings.actions.useBrowser + case "access_mcp_resource": + case "use_mcp_tool": + return this.autoApprovalSettings.actions.useMcp + } + } + return false + } + + // Check if the tool should be auto-approved based on the settings + // and the path of the action. Returns true if the tool should be auto-approved + // based on the user's settings and the path of the action. + shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean { + let isLocalRead: boolean = false + if (autoApproveActionpath) { + const absolutePath = path.resolve(cwd, autoApproveActionpath) + isLocalRead = absolutePath.startsWith(cwd) + } else { + // If we do not get a path for some reason, default to a (safer) false return + isLocalRead = false + } + + // Get auto-approve settings for local and external edits + const autoApproveResult = this.shouldAutoApproveTool(blockname) + const [autoApproveLocal, autoApproveExternal] = Array.isArray(autoApproveResult) + ? autoApproveResult + : [autoApproveResult, false] + + if ((isLocalRead && autoApproveLocal) || (!isLocalRead && autoApproveLocal && autoApproveExternal)) { + return true + } else { + return false + } + } + + updateSettings(settings: AutoApprovalSettings): void { + this.autoApprovalSettings = settings + } +} From 937cebc7de8895f397fec5bf4ca0d30ac52a670e Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 15:01:31 -0700 Subject: [PATCH 02/60] refactor vertex and doubao provider ui (#4474) * doubao * vertex Co-authored-by: StvLz * ui --------- Co-authored-by: StvLz --- .../src/components/settings/ApiOptions.tsx | 115 +++-------------- .../settings/providers/DoubaoProvider.tsx | 47 +++++++ .../settings/providers/VertexProvider.tsx | 121 ++++++++++++++++++ 3 files changed, 188 insertions(+), 95 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/DoubaoProvider.tsx create mode 100644 webview-ui/src/components/settings/providers/VertexProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 85ef3245..198532e6 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -7,15 +7,12 @@ import { bedrockModels, cerebrasModels, claudeCodeModels, - doubaoModels, geminiModels, internationalQwenModels, liteLlmModelInfoSaneDefaults, mainlandQwenModels, ModelInfo, nebiusModels, - vertexGlobalModels, - vertexModels, xaiModels, sapAiCoreModels, } from "@shared/api" @@ -54,6 +51,8 @@ import { AnthropicProvider } from "./providers/AnthropicProvider" import { AskSageProvider } from "./providers/AskSageProvider" import { OpenAINativeProvider } from "./providers/OpenAINative" import { GeminiProvider } from "./providers/GeminiProvider" +import { DoubaoProvider } from "./providers/DoubaoProvider" +import { VertexProvider } from "./providers/VertexProvider" import GeminiCliProvider from "./providers/GeminiCliProvider" interface ApiOptionsProps { @@ -65,14 +64,6 @@ interface ApiOptionsProps { } const SUPPORTED_THINKING_MODELS: Record = { - vertex: [ - "claude-3-7-sonnet@20250219", - "claude-sonnet-4@20250514", - "claude-opus-4@20250514", - "gemini-2.5-flash-preview-05-20", - "gemini-2.5-flash-preview-04-17", - "gemini-2.5-pro-preview-06-05", - ], qwen: [ "qwen3-235b-a22b", "qwen3-32b", @@ -88,7 +79,7 @@ const SUPPORTED_THINKING_MODELS: Record = { } // This is necessary to ensure dropdown opens downward, important for when this is used in popup -const DROPDOWN_Z_INDEX = OPENROUTER_MODEL_PICKER_Z_INDEX + 2 // Higher than the OpenRouterModelPicker's and ModelSelectorTooltip's z-index +export const DROPDOWN_Z_INDEX = OPENROUTER_MODEL_PICKER_Z_INDEX + 2 // Higher than the OpenRouterModelPicker's and ModelSelectorTooltip's z-index export const DropdownContainer = styled.div<{ zIndex?: number }>` position: relative; @@ -403,35 +394,13 @@ const ApiOptions = ({ )} - {selectedProvider === "doubao" && ( -
- - Doubao API Key - -

- This key is stored locally and only used to make API requests from this extension. - {!apiConfiguration?.doubaoApiKey && ( - - You can get a Doubao API key by signing up here. - - )} -

-
+ {apiConfiguration && selectedProvider === "doubao" && ( + )} {apiConfiguration && selectedProvider === "mistral" && ( @@ -760,57 +729,14 @@ const ApiOptions = ({ )} - {apiConfiguration?.apiProvider === "vertex" && ( -
- - Google Cloud Project ID - - - - - Select a region... - us-east5 - us-central1 - europe-west1 - europe-west4 - asia-southeast1 - global - - -

- To use Google Cloud Vertex AI, you need to - - {"1) create a Google Cloud account › enable the Vertex AI API › enable the desired Claude models,"} - {" "} - - {"2) install the Google Cloud CLI › configure Application Default Credentials."} - -

-
+ {apiConfiguration && selectedProvider === "vertex" && ( + )} {apiConfiguration && selectedProvider === "gemini" && ( @@ -1602,6 +1528,8 @@ const ApiOptions = ({ selectedProvider !== "sambanova" && selectedProvider !== "openai-native" && selectedProvider !== "gemini" && + selectedProvider !== "doubao" && + selectedProvider !== "vertex" && selectedProvider !== "gemini-cli" && showModelOptions && ( <> @@ -1610,13 +1538,10 @@ const ApiOptions = ({ Model {selectedProvider === "claude-code" && createDropdown(claudeCodeModels)} - {selectedProvider === "vertex" && - createDropdown(apiConfiguration?.vertexRegion === "global" ? vertexGlobalModels : vertexModels)} {selectedProvider === "qwen" && createDropdown( apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, )} - {selectedProvider === "doubao" && createDropdown(doubaoModels)} {selectedProvider === "xai" && createDropdown(xaiModels)} {selectedProvider === "cerebras" && createDropdown(cerebrasModels)} {selectedProvider === "nebius" && createDropdown(nebiusModels)} diff --git a/webview-ui/src/components/settings/providers/DoubaoProvider.tsx b/webview-ui/src/components/settings/providers/DoubaoProvider.tsx new file mode 100644 index 00000000..76e3d8a8 --- /dev/null +++ b/webview-ui/src/components/settings/providers/DoubaoProvider.tsx @@ -0,0 +1,47 @@ +import { ApiConfiguration, doubaoModels } from "@shared/api" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelSelector } from "../common/ModelSelector" +import { ModelInfoView } from "../common/ModelInfoView" +import { normalizeApiConfiguration } from "../utils/providerUtils" + +/** + * Props for the DoubaoProvider component + */ +interface DoubaoProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The ByteDance Doubao provider configuration component + */ +export const DoubaoProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: DoubaoProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + return ( +
+ + + {showModelOptions && ( + <> + + + + + )} +
+ ) +} diff --git a/webview-ui/src/components/settings/providers/VertexProvider.tsx b/webview-ui/src/components/settings/providers/VertexProvider.tsx new file mode 100644 index 00000000..8768c840 --- /dev/null +++ b/webview-ui/src/components/settings/providers/VertexProvider.tsx @@ -0,0 +1,121 @@ +import { ApiConfiguration, vertexGlobalModels, vertexModels } from "@shared/api" +import { VSCodeTextField, VSCodeDropdown, VSCodeOption, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { ModelSelector } from "../common/ModelSelector" +import { ModelInfoView } from "../common/ModelInfoView" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { DropdownContainer, DROPDOWN_Z_INDEX } from "../ApiOptions" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" + +/** + * Props for the VertexProvider component + */ +interface VertexProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +// Vertex models that support thinking +const SUPPORTED_THINKING_MODELS = [ + "claude-3-7-sonnet@20250219", + "claude-sonnet-4@20250514", + "claude-opus-4@20250514", + "gemini-2.5-flash", + "gemini-2.5-pro", +] + +/** + * The GCP Vertex AI provider configuration component + */ +export const VertexProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: VertexProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + // Determine which models to use based on region + const modelsToUse = apiConfiguration?.vertexRegion === "global" ? vertexGlobalModels : vertexModels + + return ( +
+ + Google Cloud Project ID + + + + + + Select a region... + us-east5 + us-central1 + europe-west1 + europe-west4 + asia-southeast1 + global + + + +

+ To use Google Cloud Vertex AI, you need to + + {"1) create a Google Cloud account › enable the Vertex AI API › enable the desired Claude models,"} + {" "} + + {"2) install the Google Cloud CLI › configure Application Default Credentials."} + +

+ + {showModelOptions && ( + <> + + + {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( + + )} + + + + )} +
+ ) +} From c8f0324536c2e91bd8a245181ea5313ab9f465ac Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 15:43:24 -0700 Subject: [PATCH 03/60] remove gemini free text for 2.5 models (#4492) * gemini text * remove --- webview-ui/src/components/settings/common/ModelInfoView.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webview-ui/src/components/settings/common/ModelInfoView.tsx b/webview-ui/src/components/settings/common/ModelInfoView.tsx index 258b0486..6118167b 100644 --- a/webview-ui/src/components/settings/common/ModelInfoView.tsx +++ b/webview-ui/src/components/settings/common/ModelInfoView.tsx @@ -196,9 +196,7 @@ export const ModelInfoView = ({ selectedModelId, modelInfo, isPopup }: ModelInfo ), outputPriceElement, // Add the generated output price block isGeminiProvider && ( - - * Free up to {selectedModelId && selectedModelId.includes("flash") ? "15" : "2"} requests per minute. After that, - billing depends on prompt size.{" "} + For more info, see pricing details. From 2709ccefcddc616e89a70962f017bcbbca1f17bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Barreiro?= <52393857+BarreiroT@users.noreply.github.com> Date: Fri, 27 Jun 2025 00:43:58 +0200 Subject: [PATCH 04/60] fix: ENAMETOOLONG on Claude Code - write to stdin instead of including the messages in the prompt (#4494) * Write to stdin instead of including the messages in the prompt * Add changeset --- .changeset/chilled-paws-remain.md | 5 +++++ src/integrations/claude-code/run.ts | 10 +++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 .changeset/chilled-paws-remain.md diff --git a/.changeset/chilled-paws-remain.md b/.changeset/chilled-paws-remain.md new file mode 100644 index 00000000..856222e0 --- /dev/null +++ b/.changeset/chilled-paws-remain.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Fix ENAMETOOLONG when calling Claude Code diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index b97fa93f..94d2766a 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -112,7 +112,6 @@ function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions const args = [ "-p", - JSON.stringify(messages), "--system-prompt", systemPrompt, "--verbose", @@ -129,8 +128,8 @@ function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions args.push("--model", modelId) } - return execa(claudePath, args, { - stdin: "ignore", + const claudeCodeProcess = execa(claudePath, args, { + stdin: "pipe", stdout: "pipe", stderr: "pipe", env: { @@ -142,6 +141,11 @@ function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions maxBuffer: 1024 * 1024 * 1000, timeout: CLAUDE_CODE_TIMEOUT, }) + + claudeCodeProcess.stdin.write(JSON.stringify(messages)) + claudeCodeProcess.stdin.end() + + return claudeCodeProcess } function parseChunk(data: string, processState: ProcessState) { From f00c5f4ecca6b176601f28f2b7cb55fa645d5e4b Mon Sep 17 00:00:00 2001 From: Andrei Eternal Date: Thu, 26 Jun 2025 13:07:21 -1000 Subject: [PATCH 05/60] experimental vscode impls & build-proto cleanup (#4493) * experimental vscode impls * weird errors * add workspace host config * format --------- Co-authored-by: Andrei Eternal --- proto/build-proto-config.js | 29 + proto/build-proto.js | 63 +- .../runtime-files/vscode/enhanced-terminal.js | 514 ++++++++++++ .../runtime-files/vscode/vscode-impls.js | 743 +++++++++++++++++- 4 files changed, 1280 insertions(+), 69 deletions(-) create mode 100644 proto/build-proto-config.js create mode 100644 standalone/runtime-files/vscode/enhanced-terminal.js diff --git a/proto/build-proto-config.js b/proto/build-proto-config.js new file mode 100644 index 00000000..66bfc107 --- /dev/null +++ b/proto/build-proto-config.js @@ -0,0 +1,29 @@ +// Configuration file for protocol buffer build scripts +// Contains service name mappings used by both build-proto.js and build-go-proto.js + +// List of gRPC services +// To add a new service, simply add it to this map and run the build scripts +// The service handler will be automatically discovered and used by grpc-handler.ts +export const serviceNameMap = { + account: "cline.AccountService", + browser: "cline.BrowserService", + checkpoints: "cline.CheckpointsService", + file: "cline.FileService", + mcp: "cline.McpService", + state: "cline.StateService", + task: "cline.TaskService", + web: "cline.WebService", + models: "cline.ModelsService", + slash: "cline.SlashService", + ui: "cline.UiService", + // Add new services here - no other code changes needed! +} + +// List of host gRPC services (IDE API bridge) +// These services are implemented in the IDE extension and called by the standalone Cline Core +export const hostServiceNameMap = { + uri: "host.UriService", + watch: "host.WatchService", + workspace: "host.WorkspaceService", + // Add new host services here +} diff --git a/proto/build-proto.js b/proto/build-proto.js index 04a42928..3416b071 100755 --- a/proto/build-proto.js +++ b/proto/build-proto.js @@ -9,16 +9,18 @@ import chalk from "chalk" import os from "os" import { createRequire } from "module" +import { serviceNameMap, hostServiceNameMap } from "./build-proto-config.js" + const require = createRequire(import.meta.url) const PROTOC = path.join(require.resolve("grpc-tools"), "../bin/protoc") const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url)) const ROOT_DIR = path.resolve(SCRIPT_DIR, "..") -const TS_OUT_DIR = path.join(ROOT_DIR, "src/shared/proto") -const GRPC_JS_OUT_DIR = path.join(ROOT_DIR, "src/generated/grpc-js") -const NICE_JS_OUT_DIR = path.join(ROOT_DIR, "src/generated/nice-grpc") -const DESCRIPTOR_OUT_DIR = path.join(ROOT_DIR, "dist-standalone/proto") +const TS_OUT_DIR = path.join(ROOT_DIR, "src", "shared", "proto") +const GRPC_JS_OUT_DIR = path.join(ROOT_DIR, "src", "generated", "grpc-js") +const NICE_JS_OUT_DIR = path.join(ROOT_DIR, "src", "generated", "nice-grpc") +const DESCRIPTOR_OUT_DIR = path.join(ROOT_DIR, "dist-standalone", "proto") const isWindows = process.platform === "win32" const TS_PROTO_PLUGIN = isWindows @@ -34,34 +36,13 @@ const TS_PROTO_OPTIONS = [ "useDate=false", // Timestamp fields will not be automatically converted to Date. ] -// List of gRPC services -// To add a new service, simply add it to this map and run this script -// The service handler will be automatically discovered and used by grpc-handler.ts -const serviceNameMap = { - account: "cline.AccountService", - browser: "cline.BrowserService", - checkpoints: "cline.CheckpointsService", - file: "cline.FileService", - mcp: "cline.McpService", - state: "cline.StateService", - task: "cline.TaskService", - web: "cline.WebService", - models: "cline.ModelsService", - slash: "cline.SlashService", - ui: "cline.UiService", - // Add new services here - no other code changes needed! -} -const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(ROOT_DIR, "src/core/controller", serviceKey)) +// Service directories derived from imported serviceNameMap +const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(ROOT_DIR, "src", "core", "controller", serviceKey)) -// List of host gRPC services (IDE API bridge) -// These services are implemented in the IDE extension and called by the standalone Cline Core -const hostServiceNameMap = { - uri: "host.UriService", - watch: "host.WatchService", - workspace: "host.WorkspaceService", - // Add new host services here -} -const hostServiceDirs = Object.keys(hostServiceNameMap).map((serviceKey) => path.join(ROOT_DIR, "src/hosts/vscode", serviceKey)) +// Host service directories derived from imported hostServiceNameMap +const hostServiceDirs = Object.keys(hostServiceNameMap).map((serviceKey) => + path.join(ROOT_DIR, "src", "hosts", "vscode", serviceKey), +) async function main() { console.log(chalk.bold.blue("Starting Protocol Buffer code generation...")) @@ -177,7 +158,7 @@ export { ${serviceExports.join(",\n\t")} }` - const filePath = path.join(ROOT_DIR, "webview-ui/src/services/grpc-client.ts") + const filePath = path.join(ROOT_DIR, "webview-ui", "src", "services", "grpc-client.ts") await writeFileWithMkdirs(filePath, content) log_verbose(chalk.green(`Generated gRPC client at ${filePath}`)) } @@ -386,7 +367,7 @@ export interface ServiceHandlerConfig { export const serviceHandlers: Record = {${serviceConfigs.join(",")} };` - const configPath = path.join(ROOT_DIR, "src/core/controller/grpc-service-config.ts") + const configPath = path.join(ROOT_DIR, "src", "core", "controller", "grpc-service-config.ts") await writeFileWithMkdirs(configPath, content) log_verbose(chalk.green(`Generated service configuration at ${configPath}`)) } @@ -602,13 +583,12 @@ async function cleanup() { for (const file of existingFiles) { await fs.unlink(path.join(TS_OUT_DIR, file)) } - await rmdir(path.join(ROOT_DIR, "src/generated")) + await rmdir(path.join(ROOT_DIR, "src", "generated")) // Clean up generated files that were moved. - await fs.rm(path.join(ROOT_DIR, "src/standalone/services/host-grpc-client.ts"), { force: true }) - await rmdir(path.join(ROOT_DIR, "src/standalone/services")) - - await fs.rm(path.join(ROOT_DIR, "hosts/vscode"), { force: true, recursive: true }) + await fs.rm(path.join(ROOT_DIR, "src", "standalone", "services", "host-grpc-client.ts"), { force: true }) + await rmdir(path.join(ROOT_DIR, "src", "standalone", "services")) + await fs.rm(path.join(ROOT_DIR, "hosts", "vscode"), { force: true, recursive: true }) await rmdir(path.join(ROOT_DIR, "hosts")) await fs.rm(path.join(ROOT_DIR, "src/standalone/server-setup.ts"), { force: true }) @@ -636,13 +616,6 @@ async function rmdir(path) { } } -function serviceNameWithoutPackage(fullServiceName) { - return fullServiceName.replace(/.*\./, "") -} -function lowercaseFirstChar(str) { - return str.charAt(0).toLowerCase() + str.slice(1) -} - // Check for Apple Silicon compatibility function checkAppleSiliconCompatibility() { // Only run check on macOS diff --git a/standalone/runtime-files/vscode/enhanced-terminal.js b/standalone/runtime-files/vscode/enhanced-terminal.js new file mode 100644 index 00000000..8dbb89f6 --- /dev/null +++ b/standalone/runtime-files/vscode/enhanced-terminal.js @@ -0,0 +1,514 @@ +const { spawn } = require("child_process") +const { EventEmitter } = require("events") +const path = require("path") +const os = require("os") + +// Enhanced terminal management for standalone Cline +// This replaces VSCode's terminal integration with real subprocess management + +class StandaloneTerminalProcess extends EventEmitter { + constructor() { + super() + this.waitForShellIntegration = false // We don't need to wait since we control the process + this.isListening = true + this.buffer = "" + this.fullOutput = "" + this.lastRetrievedIndex = 0 + this.isHot = false + this.hotTimer = null + this.childProcess = null + this.exitCode = null + this.isCompleted = false + } + + async run(terminal, command) { + console.log(`[StandaloneTerminal] Running command: ${command}`) + + // Get shell and working directory from terminal + const shell = terminal._shellPath || this.getDefaultShell() + const cwd = terminal._cwd || process.cwd() + + // Prepare command for execution + const shellArgs = this.getShellArgs(shell, command) + + try { + // Spawn the process + this.childProcess = spawn(shell, shellArgs, { + cwd: cwd, + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, TERM: "xterm-256color" }, + }) + + // Track process state + let didEmitEmptyLine = false + + // Handle stdout + this.childProcess.stdout.on("data", (data) => { + const output = data.toString() + this.handleOutput(output, didEmitEmptyLine) + if (!didEmitEmptyLine && output) { + this.emit("line", "") // Signal start of output + didEmitEmptyLine = true + } + }) + + // Handle stderr + this.childProcess.stderr.on("data", (data) => { + const output = data.toString() + this.handleOutput(output, didEmitEmptyLine) + if (!didEmitEmptyLine && output) { + this.emit("line", "") + didEmitEmptyLine = true + } + }) + + // Handle process completion + this.childProcess.on("close", (code, signal) => { + console.log(`[StandaloneTerminal] Process closed with code ${code}, signal ${signal}`) + this.exitCode = code + this.isCompleted = true + this.emitRemainingBuffer() + + // Clear hot timer + if (this.hotTimer) { + clearTimeout(this.hotTimer) + this.isHot = false + } + + this.emit("completed") + this.emit("continue") + }) + + // Handle process errors + this.childProcess.on("error", (error) => { + console.error(`[StandaloneTerminal] Process error:`, error) + this.emit("error", error) + }) + + // Update terminal's process reference + terminal._process = this.childProcess + terminal._processId = this.childProcess.pid + } catch (error) { + console.error(`[StandaloneTerminal] Failed to spawn process:`, error) + this.emit("error", error) + } + } + + handleOutput(data, didEmitEmptyLine) { + // Set process as hot (actively outputting) + this.isHot = true + if (this.hotTimer) { + clearTimeout(this.hotTimer) + } + + // Check for compilation markers to adjust hot timeout + const compilingMarkers = ["compiling", "building", "bundling", "transpiling", "generating", "starting"] + const markerNullifiers = [ + "compiled", + "success", + "finish", + "complete", + "succeed", + "done", + "end", + "stop", + "exit", + "terminate", + "error", + "fail", + ] + + const isCompiling = + compilingMarkers.some((marker) => data.toLowerCase().includes(marker.toLowerCase())) && + !markerNullifiers.some((nullifier) => data.toLowerCase().includes(nullifier.toLowerCase())) + + const hotTimeout = isCompiling ? 15000 : 2000 + this.hotTimer = setTimeout(() => { + this.isHot = false + }, hotTimeout) + + // Store full output + this.fullOutput += data + + if (this.isListening) { + this.emitLines(data) + this.lastRetrievedIndex = this.fullOutput.length - this.buffer.length + } + } + + emitLines(chunk) { + this.buffer += chunk + let lineEndIndex + while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) { + let line = this.buffer.slice(0, lineEndIndex).trimEnd() + this.emit("line", line) + this.buffer = this.buffer.slice(lineEndIndex + 1) + } + } + + emitRemainingBuffer() { + if (this.buffer && this.isListening) { + const remainingBuffer = this.removeLastLineArtifacts(this.buffer) + if (remainingBuffer) { + this.emit("line", remainingBuffer) + } + this.buffer = "" + this.lastRetrievedIndex = this.fullOutput.length + } + } + + continue() { + this.emitRemainingBuffer() + this.isListening = false + this.removeAllListeners("line") + this.emit("continue") + } + + getUnretrievedOutput() { + const unretrieved = this.fullOutput.slice(this.lastRetrievedIndex) + this.lastRetrievedIndex = this.fullOutput.length + return this.removeLastLineArtifacts(unretrieved) + } + + removeLastLineArtifacts(output) { + const lines = output.trimEnd().split("\n") + if (lines.length > 0) { + const lastLine = lines[lines.length - 1] + lines[lines.length - 1] = lastLine.replace(/[%$#>]\s*$/, "") + } + return lines.join("\n").trimEnd() + } + + getDefaultShell() { + if (process.platform === "win32") { + return process.env.COMSPEC || "cmd.exe" + } else { + return process.env.SHELL || "/bin/bash" + } + } + + getShellArgs(shell, command) { + if (process.platform === "win32") { + if (shell.toLowerCase().includes("powershell") || shell.toLowerCase().includes("pwsh")) { + return ["-Command", command] + } else { + return ["/c", command] + } + } else { + return ["-c", command] + } + } + + // Terminate the process if it's still running + terminate() { + if (this.childProcess && !this.isCompleted) { + console.log(`[StandaloneTerminal] Terminating process ${this.childProcess.pid}`) + this.childProcess.kill("SIGTERM") + + // Force kill after timeout + setTimeout(() => { + if (!this.isCompleted) { + console.log(`[StandaloneTerminal] Force killing process ${this.childProcess.pid}`) + this.childProcess.kill("SIGKILL") + } + }, 5000) + } + } +} + +class StandaloneTerminal { + constructor(options = {}) { + this.name = options.name || `Terminal ${Math.floor(Math.random() * 10000)}` + this.processId = Promise.resolve(Math.floor(Math.random() * 100000)) + this.creationOptions = options + this.exitStatus = undefined + this.state = { isInteractedWith: false } + this._cwd = options.cwd || process.cwd() + this._shellPath = options.shellPath + this._process = null + this._processId = null + + // Mock shell integration for compatibility + this.shellIntegration = { + cwd: { fsPath: this._cwd }, + executeCommand: (command) => { + // Return a mock execution object that the TerminalProcess expects + return { + read: async function* () { + // This will be handled by our StandaloneTerminalProcess + yield "" + }, + } + }, + } + + console.log(`[StandaloneTerminal] Created terminal: ${this.name} in ${this._cwd}`) + } + + sendText(text, addNewLine = true) { + console.log(`[StandaloneTerminal] sendText: ${text}`) + + // If we have an active process, send input to it + if (this._process && !this._process.killed) { + try { + this._process.stdin.write(text + (addNewLine ? "\n" : "")) + } catch (error) { + console.error(`[StandaloneTerminal] Error sending text to process:`, error) + } + } else { + // For compatibility with old behavior, we could spawn a new process + console.log(`[StandaloneTerminal] No active process to send text to`) + } + } + + show() { + console.log(`[StandaloneTerminal] show: ${this.name}`) + this.state.isInteractedWith = true + } + + hide() { + console.log(`[StandaloneTerminal] hide: ${this.name}`) + } + + dispose() { + console.log(`[StandaloneTerminal] dispose: ${this.name}`) + if (this._process && !this._process.killed) { + this._process.kill("SIGTERM") + } + } +} + +// Terminal registry for tracking terminals +class StandaloneTerminalRegistry { + constructor() { + this.terminals = new Map() + this.nextId = 1 + } + + createTerminal(options = {}) { + const terminal = new StandaloneTerminal(options) + const id = this.nextId++ + + const terminalInfo = { + id: id, + terminal: terminal, + busy: false, + lastCommand: "", + shellPath: options.shellPath, + lastActive: Date.now(), + pendingCwdChange: undefined, + cwdResolved: undefined, + } + + this.terminals.set(id, terminalInfo) + console.log(`[StandaloneTerminalRegistry] Created terminal ${id}`) + return terminalInfo + } + + getTerminal(id) { + return this.terminals.get(id) + } + + getAllTerminals() { + return Array.from(this.terminals.values()) + } + + removeTerminal(id) { + const terminalInfo = this.terminals.get(id) + if (terminalInfo) { + terminalInfo.terminal.dispose() + this.terminals.delete(id) + console.log(`[StandaloneTerminalRegistry] Removed terminal ${id}`) + } + } + + updateTerminal(id, updates) { + const terminalInfo = this.terminals.get(id) + if (terminalInfo) { + Object.assign(terminalInfo, updates) + } + } +} + +// Enhanced terminal manager +class StandaloneTerminalManager { + constructor() { + this.registry = new StandaloneTerminalRegistry() + this.processes = new Map() + this.terminalIds = new Set() + this.shellIntegrationTimeout = 4000 + this.terminalReuseEnabled = true + this.terminalOutputLineLimit = 500 + this.defaultTerminalProfile = "default" + } + + runCommand(terminalInfo, command) { + console.log(`[StandaloneTerminalManager] Running command on terminal ${terminalInfo.id}: ${command}`) + + terminalInfo.busy = true + terminalInfo.lastCommand = command + + const process = new StandaloneTerminalProcess() + this.processes.set(terminalInfo.id, process) + + process.once("completed", () => { + terminalInfo.busy = false + console.log(`[StandaloneTerminalManager] Command completed on terminal ${terminalInfo.id}`) + }) + + process.once("error", (error) => { + terminalInfo.busy = false + console.error(`[StandaloneTerminalManager] Command error on terminal ${terminalInfo.id}:`, error) + }) + + // Create promise for the process + const promise = new Promise((resolve, reject) => { + process.once("continue", () => resolve()) + process.once("error", (error) => reject(error)) + }) + + // Run the command immediately (no shell integration wait needed) + process.run(terminalInfo.terminal, command) + + // Return merged promise/process object + return this.mergePromise(process, promise) + } + + async getOrCreateTerminal(cwd) { + const terminals = this.registry.getAllTerminals() + + // Find available terminal with matching CWD + const matchingTerminal = terminals.find((t) => { + if (t.busy) return false + return t.terminal._cwd === cwd + }) + + if (matchingTerminal) { + this.terminalIds.add(matchingTerminal.id) + console.log(`[StandaloneTerminalManager] Reusing terminal ${matchingTerminal.id}`) + return matchingTerminal + } + + // Find any available terminal if reuse is enabled + if (this.terminalReuseEnabled) { + const availableTerminal = terminals.find((t) => !t.busy) + if (availableTerminal) { + // Change directory + await this.runCommand(availableTerminal, `cd "${cwd}"`) + availableTerminal.terminal._cwd = cwd + availableTerminal.terminal.shellIntegration.cwd.fsPath = cwd + this.terminalIds.add(availableTerminal.id) + console.log(`[StandaloneTerminalManager] Reused terminal ${availableTerminal.id} with cd`) + return availableTerminal + } + } + + // Create new terminal + const newTerminalInfo = this.registry.createTerminal({ + cwd: cwd, + name: `Cline Terminal ${this.registry.nextId}`, + }) + this.terminalIds.add(newTerminalInfo.id) + console.log(`[StandaloneTerminalManager] Created new terminal ${newTerminalInfo.id}`) + return newTerminalInfo + } + + getTerminals(busy) { + return Array.from(this.terminalIds) + .map((id) => this.registry.getTerminal(id)) + .filter((t) => t && t.busy === busy) + .map((t) => ({ id: t.id, lastCommand: t.lastCommand })) + } + + getUnretrievedOutput(terminalId) { + if (!this.terminalIds.has(terminalId)) { + return "" + } + const process = this.processes.get(terminalId) + return process ? process.getUnretrievedOutput() : "" + } + + isProcessHot(terminalId) { + const process = this.processes.get(terminalId) + return process ? process.isHot : false + } + + processOutput(outputLines) { + if (outputLines.length > this.terminalOutputLineLimit) { + const halfLimit = Math.floor(this.terminalOutputLineLimit / 2) + const start = outputLines.slice(0, halfLimit) + const end = outputLines.slice(outputLines.length - halfLimit) + return `${start.join("\n")}\n... (output truncated) ...\n${end.join("\n")}`.trim() + } + return outputLines.join("\n").trim() + } + + disposeAll() { + // Terminate all processes + for (const [terminalId, process] of this.processes) { + if (process && process.terminate) { + process.terminate() + } + } + + // Clear all tracking + this.terminalIds.clear() + this.processes.clear() + + // Dispose all terminals + for (const terminalInfo of this.registry.getAllTerminals()) { + terminalInfo.terminal.dispose() + } + + console.log(`[StandaloneTerminalManager] Disposed all terminals`) + } + + // Set shell integration timeout (compatibility method) + setShellIntegrationTimeout(timeout) { + this.shellIntegrationTimeout = timeout + console.log(`[StandaloneTerminalManager] Set shell integration timeout to ${timeout}ms`) + } + + // Set terminal reuse enabled (compatibility method) + setTerminalReuseEnabled(enabled) { + this.terminalReuseEnabled = enabled + console.log(`[StandaloneTerminalManager] Set terminal reuse enabled to ${enabled}`) + } + + // Set terminal output line limit (compatibility method) + setTerminalOutputLineLimit(limit) { + this.terminalOutputLineLimit = limit + console.log(`[StandaloneTerminalManager] Set terminal output line limit to ${limit}`) + } + + // Set default terminal profile (compatibility method) + setDefaultTerminalProfile(profile) { + this.defaultTerminalProfile = profile + console.log(`[StandaloneTerminalManager] Set default terminal profile to ${profile}`) + } + + // Helper to merge process and promise (similar to execa) + mergePromise(process, promise) { + const nativePromisePrototype = (async () => {})().constructor.prototype + const descriptors = ["then", "catch", "finally"].map((property) => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), + ]) + + for (const [property, descriptor] of descriptors) { + if (descriptor) { + const value = descriptor.value.bind(promise) + Reflect.defineProperty(process, property, { ...descriptor, value }) + } + } + + return process + } +} + +module.exports = { + StandaloneTerminal, + StandaloneTerminalProcess, + StandaloneTerminalRegistry, + StandaloneTerminalManager, +} diff --git a/standalone/runtime-files/vscode/vscode-impls.js b/standalone/runtime-files/vscode/vscode-impls.js index db340d4e..f872c71e 100644 --- a/standalone/runtime-files/vscode/vscode-impls.js +++ b/standalone/runtime-files/vscode/vscode-impls.js @@ -2,8 +2,19 @@ console.log("Loading stub impls...") const { createStub } = require("./stub-utils") const open = require("open").default +const fs = require("fs") +const path = require("path") +const { StandaloneTerminalManager } = require("./enhanced-terminal") +// Import the base vscode object from stubs +const vscode = require("./vscode-stubs.js") + +// Create global terminal manager instance +const globalTerminalManager = new StandaloneTerminalManager() + +// Extend the existing window object from stubs rather than overwriting it vscode.window = { + ...vscode.window, // Keep existing properties from stubs showInformationMessage: (...args) => { console.log("Stubbed showInformationMessage:", ...args) return Promise.resolve(undefined) @@ -28,9 +39,210 @@ vscode.window = { console.log("Stubbed showSaveDialog:", options) return undefined }, - showTextDocument: async (...args) => { - console.log("Stubbed showTextDocument:", ...args) - return {} + showTextDocument: async (uri, options) => { + console.log("Stubbed showTextDocument:", uri, options) + + // Extract file path from URI + let filePath = uri.path || uri.fsPath || uri + if (typeof filePath !== "string") { + filePath = uri.toString() + } + + // Remove file:// prefix if present + if (filePath.startsWith("file://")) { + filePath = filePath.substring(7) + } + + // Create a function that always reads the current file content + const getCurrentFileContent = async () => { + try { + const content = await fs.promises.readFile(filePath, "utf8") + console.log(`getCurrentFileContent: Read file ${filePath} (${content.length} chars)`) + return content + } catch (error) { + console.log(`getCurrentFileContent: Could not read file ${filePath}:`, error.message) + return "" + } + } + + // Try to read the initial file content + let fileContent = await getCurrentFileContent() + let lineCount = fileContent.split("\n").length + + // Check if we already have an active editor for this file path + const existingEditor = vscode.window._documentEditors && vscode.window._documentEditors[filePath] + if (existingEditor) { + console.log(`showTextDocument: Updating existing editor for ${filePath}`) + // Update the existing editor's content + fileContent = await getCurrentFileContent() + lineCount = fileContent.split("\n").length + + // Update the document's getText method to return current content + existingEditor.document.getText = (range) => { + // Always read fresh content for getText calls + const currentContent = require("fs").readFileSync(filePath, "utf8") + if (!range) { + return currentContent + } + // Handle range-based getText with current content + const lines = currentContent.split("\n") + const startLine = Math.max(0, range.start.line) + const endLine = Math.min(lines.length - 1, range.end.line) + + if (startLine === endLine) { + // Single line + const line = lines[startLine] || "" + const startChar = Math.max(0, range.start.character) + const endChar = Math.min(line.length, range.end.character) + return line.substring(startChar, endChar) + } else { + // Multiple lines + const result = [] + for (let i = startLine; i <= endLine; i++) { + const line = lines[i] || "" + if (i === startLine) { + result.push(line.substring(range.start.character)) + } else if (i === endLine) { + result.push(line.substring(0, range.end.character)) + } else { + result.push(line) + } + } + return result.join("\n") + } + } + + // Update other properties + existingEditor.document.lineCount = lineCount + existingEditor.document.fileName = filePath + + // Update the active text editor reference + vscode.window.activeTextEditor = existingEditor + + return existingEditor + } + + // Create a new mock text editor that always reads current file content + const mockEditor = { + document: { + uri: uri, + fileName: filePath, + isDirty: false, + lineCount: lineCount, + getText: (range) => { + // Always read fresh content for getText calls + try { + const currentContent = require("fs").readFileSync(filePath, "utf8") + console.log(`document.getText: Read fresh content (${currentContent.length} chars)`) + if (!range) { + return currentContent + } + // Handle range-based getText with current content + const lines = currentContent.split("\n") + const startLine = Math.max(0, range.start.line) + const endLine = Math.min(lines.length - 1, range.end.line) + + if (startLine === endLine) { + // Single line + const line = lines[startLine] || "" + const startChar = Math.max(0, range.start.character) + const endChar = Math.min(line.length, range.end.character) + return line.substring(startChar, endChar) + } else { + // Multiple lines + const result = [] + for (let i = startLine; i <= endLine; i++) { + const line = lines[i] || "" + if (i === startLine) { + result.push(line.substring(range.start.character)) + } else if (i === endLine) { + result.push(line.substring(0, range.end.character)) + } else { + result.push(line) + } + } + return result.join("\n") + } + } catch (error) { + console.error(`Error reading file in getText: ${error.message}`) + return "" + } + }, + save: async () => { + console.log("Called mock textDocument.save") + return true + }, + positionAt: (offset) => { + try { + const currentContent = require("fs").readFileSync(filePath, "utf8") + const lines = currentContent.split("\n") + let currentOffset = 0 + for (let line = 0; line < lines.length; line++) { + const lineLength = lines[line].length + 1 // +1 for newline + if (currentOffset + lineLength > offset) { + return { line: line, character: offset - currentOffset } + } + currentOffset += lineLength + } + return { line: lines.length - 1, character: lines[lines.length - 1]?.length || 0 } + } catch (error) { + return { line: 0, character: 0 } + } + }, + offsetAt: (position) => { + try { + const currentContent = require("fs").readFileSync(filePath, "utf8") + const lines = currentContent.split("\n") + let offset = 0 + for (let i = 0; i < position.line && i < lines.length; i++) { + offset += lines[i].length + 1 // +1 for newline + } + offset += Math.min(position.character, lines[position.line]?.length || 0) + return offset + } catch (error) { + return 0 + } + }, + }, + selection: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, + selections: [], + visibleRanges: [{ start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }], + options: {}, + viewColumn: 1, + edit: async (callback) => { + console.log("Called mock textEditor.edit") + return true + }, + insertSnippet: async () => true, + setDecorations: () => {}, + revealRange: () => {}, + show: () => {}, + hide: () => {}, + } + + // Store the editor by file path for future reference + if (!vscode.window._documentEditors) { + vscode.window._documentEditors = {} + } + vscode.window._documentEditors[filePath] = mockEditor + + // Update the active text editor + vscode.window.activeTextEditor = mockEditor + + // Trigger onDidChangeActiveTextEditor listeners + if (vscode.window._activeTextEditorListeners) { + setTimeout(() => { + vscode.window._activeTextEditorListeners.forEach((listener) => { + try { + listener(mockEditor) + } catch (error) { + console.error("Error calling onDidChangeActiveTextEditor listener:", error) + } + }) + }, 10) // Small delay to simulate async behavior + } + + return mockEditor }, createOutputChannel: (name) => { console.log("Stubbed createOutputChannel:", name) @@ -41,20 +253,60 @@ vscode.window = { } }, createTerminal: (...args) => { - console.log("Stubbed createTerminal:", ...args) - return { - sendText: console.log, - show: () => {}, - dispose: () => {}, + console.log("Enhanced createTerminal:", ...args) + + // Extract options from arguments + let options = {} + if (args.length > 0) { + if (typeof args[0] === "string") { + // Called with (name, shellPath, shellArgs) + options = { + name: args[0], + shellPath: args[1], + shellArgs: args[2], + } + } else if (typeof args[0] === "object") { + // Called with options object + options = args[0] + } } + + // Use our enhanced terminal manager to create a terminal + const terminalInfo = globalTerminalManager.registry.createTerminal({ + name: options.name || `Terminal ${Date.now()}`, + cwd: options.cwd || process.cwd(), + shellPath: options.shellPath, + }) + + // Store reference for tracking + vscode.window.terminals.push(terminalInfo.terminal) + if (!vscode.window.activeTerminal) { + vscode.window.activeTerminal = terminalInfo.terminal + } + + console.log(`Enhanced terminal created: ${terminalInfo.id}`) + return terminalInfo.terminal }, activeTextEditor: undefined, visibleTextEditors: [], tabGroups: { - all: [], - close: async () => {}, - onDidChangeTabs: createStub("vscode.env.tabGroups.onDidChangeTabs"), - activeTabGroup: { tabs: [] }, + all: [ + { + tabs: [], + isActive: true, + viewColumn: 1, + }, + ], + activeTabGroup: { + tabs: [], + isActive: true, + viewColumn: 1, + }, + close: async (tab) => { + console.log("Stubbed tabGroups.close:", tab) + return true + }, + onDidChangeTabs: createStub("vscode.window.tabGroups.onDidChangeTabs"), }, withProgress: async (_options, task) => { console.log("Stubbed withProgress") @@ -62,14 +314,56 @@ vscode.window = { }, registerUriHandler: () => ({ dispose: () => {} }), registerWebviewViewProvider: () => ({ dispose: () => {} }), - onDidChangeActiveTextEditor: () => ({ dispose: () => {} }), - createTextEditorDecorationType: () => ({ dispose: () => {} }), - createWebviewPanel: (..._args) => { - throw new Error("WebviewPanel is not supported in standalone app.") + onDidChangeActiveTextEditor: (listener) => { + console.log("Called vscode.window.onDidChangeActiveTextEditor") + // Store the listener so we can call it when showTextDocument is called + vscode.window._activeTextEditorListeners = vscode.window._activeTextEditorListeners || [] + vscode.window._activeTextEditorListeners.push(listener) + return { + dispose: () => { + console.log("Disposed onDidChangeActiveTextEditor listener") + const index = vscode.window._activeTextEditorListeners.indexOf(listener) + if (index > -1) { + vscode.window._activeTextEditorListeners.splice(index, 1) + } + }, + } }, + createTextEditorDecorationType: () => ({ dispose: () => {} }), + createWebviewPanel: (...args) => { + console.log("Stubbed createWebviewPanel:", ...args) + return { + webview: {}, + reveal: () => {}, + dispose: () => {}, + } + }, + onDidChangeTerminalState: (listener) => { + console.log("Called vscode.window.onDidChangeTerminalState") + return { + dispose: () => { + console.log("Disposed onDidChangeTerminalState listener") + }, + } + }, + onDidChangeTextEditorVisibleRanges: (listener) => { + console.log("Called vscode.window.onDidChangeTextEditorVisibleRanges") + return { + dispose: () => { + console.log("Disposed onDidChangeTextEditorVisibleRanges listener") + }, + } + }, + terminals: [], + activeTerminal: null, } -vscode.env = { +// Initialize env object if it doesn't exist, then extend it +if (!vscode.env) { + vscode.env = {} +} + +Object.assign(vscode.env, { uriScheme: "vscode", appName: "Visual Studio Code", appRoot: "/tmp/vscode/appRoot", @@ -79,17 +373,26 @@ vscode.env = { sessionId: "stub-session-id", shell: "/bin/bash", + // Add the stub functions that were missing clipboard: createStub("vscode.env.clipboard"), - openExternal: createStub("vscode.env.openExternal"), getQueryParameter: createStub("vscode.env.getQueryParameter"), onDidChangeTelemetryEnabled: createStub("vscode.env.onDidChangeTelemetryEnabled"), isTelemetryEnabled: createStub("vscode.env.isTelemetryEnabled"), telemetryConfiguration: createStub("vscode.env.telemetryConfiguration"), onDidChangeTelemetryConfiguration: createStub("vscode.env.onDidChangeTelemetryConfiguration"), createTelemetryLogger: createStub("vscode.env.createTelemetryLogger"), +}) + +// Override the openExternal function with actual implementation +vscode.env.openExternal = async (uri) => { + const url = typeof uri === "string" ? uri : (uri.toString?.() ?? "") + console.log("Opening browser:", url) + await open(url) + return true } -vscode.Uri = { +// Extend Uri object with improved implementations +Object.assign(vscode.Uri, { parse: (uriString) => { const url = new URL(uriString) return { @@ -134,13 +437,405 @@ vscode.Uri = { const joined = segments.map((s) => (typeof s === "string" ? s : s.path)).join("/") return vscode.Uri.file("/" + joined.replace(/\/+/g, "/")) }, +}) + +// Extend workspace object with file system operations +Object.assign(vscode.workspace, { + fs: { + readFile: async function (uri) { + console.log(`Called vscode.workspace.fs.readFile with uri:`, uri) + try { + // Extract file path from URI + let filePath = uri.path || uri.fsPath || uri + if (typeof filePath !== "string") { + filePath = uri.toString() + } + + // Remove file:// prefix if present + if (filePath.startsWith("file://")) { + filePath = filePath.substring(7) + } + + console.log(`Reading file: ${filePath}`) + const content = await fs.promises.readFile(filePath, "utf8") + console.log( + `File content read (${content.length} chars):`, + content.substring(0, 100) + (content.length > 100 ? "..." : ""), + ) + return new Uint8Array(Buffer.from(content, "utf8")) + } catch (error) { + console.error(`Error reading file:`, error) + throw error + } + }, + + writeFile: async function (uri, content) { + console.log(`Called vscode.workspace.fs.writeFile with uri:`, uri) + try { + // Extract file path from URI + let filePath = uri.path || uri.fsPath || uri + if (typeof filePath !== "string") { + filePath = uri.toString() + } + + // Remove file:// prefix if present + if (filePath.startsWith("file://")) { + filePath = filePath.substring(7) + } + + console.log(`Writing file: ${filePath}`) + + // Ensure directory exists + const dir = path.dirname(filePath) + await fs.promises.mkdir(dir, { recursive: true }) + + // Write the file + await fs.promises.writeFile(filePath, content) + } catch (error) { + console.error(`Error writing file:`, error) + throw error + } + }, + }, + + // Add workspace folder configuration + rootPath: process.cwd(), + workspaceFolders: [ + { + uri: vscode.Uri.file(process.cwd()), + name: path.basename(process.cwd()), + index: 0, + }, + ], + name: path.basename(process.cwd()), + workspaceFile: vscode.Uri.file(path.join(process.cwd(), ".vscode", "workspace.json")), + + // Add other workspace methods as stubs + getConfiguration: () => ({ + get: () => undefined, + update: () => Promise.resolve(), + has: () => false, + }), + getWorkspaceFolder: (uri) => { + console.log("Called vscode.workspace.getWorkspaceFolder with:", uri) + // Return the first workspace folder for any URI in standalone mode + if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { + return vscode.workspace.workspaceFolders[0] + } + return undefined + }, + createFileSystemWatcher: () => ({ + onDidChange: () => ({ dispose: () => {} }), + onDidCreate: () => ({ dispose: () => {} }), + onDidDelete: () => ({ dispose: () => {} }), + dispose: () => {}, + }), + onDidChangeConfiguration: () => ({ dispose: () => {} }), + onDidChangeWorkspaceFolders: () => ({ dispose: () => {} }), + onDidCreateFiles: createStub("vscode.workspace.onDidCreateFiles"), + onDidDeleteFiles: createStub("vscode.workspace.onDidDeleteFiles"), + onDidRenameFiles: createStub("vscode.workspace.onDidRenameFiles"), + onWillCreateFiles: createStub("vscode.workspace.onWillCreateFiles"), + onWillDeleteFiles: createStub("vscode.workspace.onWillDeleteFiles"), + onWillRenameFiles: createStub("vscode.workspace.onWillRenameFiles"), + textDocuments: { + find: (predicate) => { + console.log("Called vscode.workspace.textDocuments.find") + // Return a mock text document that behaves like VSCode expects + return { + uri: { fsPath: "/tmp/mock-document" }, + fileName: "/tmp/mock-document", + isDirty: false, + save: async () => { + console.log("Called mock textDocument.save") + return true + }, + getText: () => "", + lineCount: 0, + } + }, + forEach: (callback) => { + console.log("Called vscode.workspace.textDocuments.forEach") + // No documents to iterate over in standalone mode + }, + length: 0, + [Symbol.iterator]: function* () { + // Empty iterator for standalone mode + }, + }, + + // Add the crucial applyEdit method + applyEdit: async (workspaceEdit) => { + console.log("Called vscode.workspace.applyEdit", workspaceEdit) + + // For standalone mode, we'll simulate applying the edit by actually writing to files + try { + // WorkspaceEdit can contain multiple types of edits + if (workspaceEdit._edits) { + for (const edit of workspaceEdit._edits) { + if (edit._type === 1) { + // TextEdit + const uri = edit._uri + const edits = edit._edits + + let filePath = uri.path || uri.fsPath + if (filePath.startsWith("file://")) { + filePath = filePath.substring(7) + } + + console.log(`Applying text edits to: ${filePath}`) + + // Read current content if file exists + let currentContent = "" + try { + currentContent = await fs.promises.readFile(filePath, "utf8") + } catch (e) { + // File doesn't exist, start with empty content + console.log(`File ${filePath} doesn't exist, starting with empty content`) + } + + // Apply edits in reverse order (from end to beginning) to maintain positions + const sortedEdits = edits.sort((a, b) => { + const aStart = a.range.start.line * 1000000 + a.range.start.character + const bStart = b.range.start.line * 1000000 + b.range.start.character + return bStart - aStart + }) + + let lines = currentContent.split("\n") + + for (const edit of sortedEdits) { + const startLine = edit.range.start.line + const startChar = edit.range.start.character + const endLine = edit.range.end.line + const endChar = edit.range.end.character + const newText = edit.newText + + console.log(`Applying edit: ${startLine}:${startChar} - ${endLine}:${endChar} -> "${newText}"`) + + // Handle the edit + if (startLine === endLine) { + // Single line edit + const line = lines[startLine] || "" + lines[startLine] = line.substring(0, startChar) + newText + line.substring(endChar) + } else { + // Multi-line edit + const firstLine = lines[startLine] || "" + const lastLine = lines[endLine] || "" + const newFirstLine = firstLine.substring(0, startChar) + newText + lastLine.substring(endChar) + + // Replace the range with the new content + lines.splice(startLine, endLine - startLine + 1, newFirstLine) + } + } + + const newContent = lines.join("\n") + + // Ensure directory exists + const dir = path.dirname(filePath) + await fs.promises.mkdir(dir, { recursive: true }) + + // Write the updated content + await fs.promises.writeFile(filePath, newContent, "utf8") + console.log(`Successfully applied edits to: ${filePath}`) + } + } + } + + return true + } catch (error) { + console.error("Error applying workspace edit:", error) + return false + } + }, +}) + +// Fix CodeActionKind to have static properties instead of being a class +vscode.CodeActionKind = { + Empty: "", + QuickFix: "quickfix", + Refactor: "refactor", + RefactorExtract: "refactor.extract", + RefactorInline: "refactor.inline", + RefactorRewrite: "refactor.rewrite", + Source: "source", + SourceOrganizeImports: "source.organizeImports", + SourceFixAll: "source.fixAll", } -vscode.env.openExternal = async (uri) => { - const url = typeof uri === "string" ? uri : (uri.toString?.() ?? "") - console.log("Opening browser:", url) - await open(url) - return true +// Add missing commands implementation +if (!vscode.commands) { + vscode.commands = {} } +Object.assign(vscode.commands, { + executeCommand: async (command, ...args) => { + console.log(`Called vscode.commands.executeCommand: ${command}`, args) + + // Handle the vscode.diff command specifically + if (command === "vscode.diff") { + const [originalUri, modifiedUri, title, options] = args + console.log("Opening diff view:", { originalUri, modifiedUri, title }) + + // For standalone mode, just open the modified file directly + // since we can't show a proper diff view + const editor = await vscode.window.showTextDocument(modifiedUri, { + preserveFocus: options?.preserveFocus || false, + preview: false, + }) + + // Ensure the onDidChangeActiveTextEditor event fires with a slight delay + // This is crucial for DiffViewProvider.openDiffEditor() to work properly + setTimeout(() => { + if (vscode.window._activeTextEditorListeners) { + vscode.window._activeTextEditorListeners.forEach((listener) => { + try { + listener(editor) + } catch (error) { + console.error("Error calling onDidChangeActiveTextEditor listener in vscode.diff:", error) + } + }) + } + }, 50) // Slightly longer delay to ensure proper event ordering + + return editor + } + + // For other commands, just return a resolved promise + return Promise.resolve() + }, + registerCommand: (command, callback) => { + console.log(`Registered command: ${command}`) + return { dispose: () => {} } + }, + getCommands: async () => { + return [] + }, +}) + +// Add missing TabInput classes +vscode.TabInputText = class TabInputText { + constructor(uri) { + this.uri = uri + } +} + +vscode.TabInputTextDiff = class TabInputTextDiff { + constructor(original, modified) { + this.original = original + this.modified = modified + } +} + +// Add missing WorkspaceEdit and related classes +vscode.WorkspaceEdit = class WorkspaceEdit { + constructor() { + this._edits = [] + } + + replace(uri, range, newText) { + console.log("WorkspaceEdit.replace:", uri, range, newText) + this._edits.push({ + _type: 1, // TextEdit + _uri: uri, + _edits: [ + { + range: range, + newText: newText, + }, + ], + }) + } + + insert(uri, position, newText) { + console.log("WorkspaceEdit.insert:", uri, position, newText) + this.replace(uri, new vscode.Range(position, position), newText) + } + + delete(uri, range) { + console.log("WorkspaceEdit.delete:", uri, range) + this.replace(uri, range, "") + } +} + +vscode.Range = class Range { + constructor(startLine, startCharacter, endLine, endCharacter) { + if (typeof startLine === "object") { + // Called with Position objects + this.start = startLine + this.end = startCharacter + } else { + // Called with line/character numbers + this.start = new vscode.Position(startLine, startCharacter) + this.end = new vscode.Position(endLine, endCharacter) + } + } +} + +vscode.Position = class Position { + constructor(line, character) { + this.line = line + this.character = character + } +} + +vscode.Selection = class Selection extends vscode.Range { + constructor(anchorLine, anchorCharacter, activeLine, activeCharacter) { + if (typeof anchorLine === "object") { + // Called with Position objects + super(anchorLine, anchorCharacter) + this.anchor = anchorLine + this.active = anchorCharacter + } else { + // Called with line/character numbers + super(anchorLine, anchorCharacter, activeLine, activeCharacter) + this.anchor = new vscode.Position(anchorLine, anchorCharacter) + this.active = new vscode.Position(activeLine, activeCharacter) + } + } +} + +// Add TextEditorRevealType enum +vscode.TextEditorRevealType = { + Default: 0, + InCenter: 1, + InCenterIfOutsideViewport: 2, + AtTop: 3, +} + +// Add missing languages API +if (!vscode.languages) { + vscode.languages = {} +} + +Object.assign(vscode.languages, { + getDiagnostics: (uri) => { + console.log("Called vscode.languages.getDiagnostics") + // Return empty diagnostics for standalone mode + if (uri) { + return [] + } else { + // Return all diagnostics as empty array + return [] + } + }, + registerCodeActionsProvider: () => ({ dispose: () => {} }), + createDiagnosticCollection: () => ({ + set: () => {}, + delete: () => {}, + clear: () => {}, + dispose: () => {}, + }), +}) + console.log("Finished loading stub impls...") + +// Export the terminal manager globally for Cline core to use +global.standaloneTerminalManager = globalTerminalManager + +// Override the TerminalManager to use our standalone implementation +if (typeof global !== "undefined") { + // Replace the TerminalManager class with our standalone implementation + global.StandaloneTerminalManagerClass = require("./enhanced-terminal").StandaloneTerminalManager +} + +module.exports = vscode From b7b0e96cc7ba17c03d2f7d07c4400ac0752c8522 Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Thu, 26 Jun 2025 16:18:29 -0700 Subject: [PATCH 06/60] Add env host bridge service, migrate clipboard read/write calls (#4496) * host bridge migration - clipboard * changeset * removed dev logging * switched to empty return on clipboard write * Moved new hostServiceNameMap entry to new proto configs --- .changeset/yellow-gifts-explain.md | 5 +++ proto/build-proto-config.js | 1 + proto/host/env.proto | 16 ++++++++++ src/core/controller/file/copyToClipboard.ts | 3 +- src/extension.ts | 9 +++--- src/hosts/host-provider-types.ts | 2 ++ src/hosts/vscode/client/host-grpc-client.ts | 1 + src/hosts/vscode/env/clipboardReadText.ts | 7 ++++ src/hosts/vscode/env/clipboardWriteText.ts | 7 ++++ .../git/commit-message-generator.ts | 3 +- .../terminal/get-latest-output.ts | 7 ++-- src/standalone/host-bridge-client-manager.ts | 4 +++ src/utils/env.ts | 32 +++++++++++++++++++ src/utils/github-url-utils.ts | 5 +-- 14 files changed, 91 insertions(+), 11 deletions(-) create mode 100644 .changeset/yellow-gifts-explain.md create mode 100644 proto/host/env.proto create mode 100644 src/hosts/vscode/env/clipboardReadText.ts create mode 100644 src/hosts/vscode/env/clipboardWriteText.ts create mode 100644 src/utils/env.ts diff --git a/.changeset/yellow-gifts-explain.md b/.changeset/yellow-gifts-explain.md new file mode 100644 index 00000000..2d1efdff --- /dev/null +++ b/.changeset/yellow-gifts-explain.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +host bridge migration - clipboard diff --git a/proto/build-proto-config.js b/proto/build-proto-config.js index 66bfc107..0fee8494 100644 --- a/proto/build-proto-config.js +++ b/proto/build-proto-config.js @@ -25,5 +25,6 @@ export const hostServiceNameMap = { uri: "host.UriService", watch: "host.WatchService", workspace: "host.WorkspaceService", + env: "host.EnvService", // Add new host services here } diff --git a/proto/host/env.proto b/proto/host/env.proto new file mode 100644 index 00000000..9d769c1e --- /dev/null +++ b/proto/host/env.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package host; +option java_package = "bot.cline.host.proto"; +option java_multiple_files = true; + +import "common.proto"; + +// Provides methods for working with the user's environment. +service EnvService { + // Writes text to the system clipboard. + rpc clipboardWriteText(cline.StringRequest) returns (cline.Empty); + + // Reads text from the system clipboard. + rpc clipboardReadText(cline.EmptyRequest) returns (cline.String); +} diff --git a/src/core/controller/file/copyToClipboard.ts b/src/core/controller/file/copyToClipboard.ts index 156fa82c..d825cda4 100644 --- a/src/core/controller/file/copyToClipboard.ts +++ b/src/core/controller/file/copyToClipboard.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode" import { Controller } from ".." import { Empty, StringRequest } from "../../../shared/proto/common" +import { writeTextToClipboard } from "@/utils/env" /** * Copies text to the system clipboard @@ -11,7 +12,7 @@ import { Empty, StringRequest } from "../../../shared/proto/common" export async function copyToClipboard(controller: Controller, request: StringRequest): Promise { try { if (request.value) { - await vscode.env.clipboard.writeText(request.value) + await writeTextToClipboard(request.value) } } catch (error) { console.error("Error copying to clipboard:", error) diff --git a/src/extension.ts b/src/extension.ts index 5465b038..5576f7b8 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -34,6 +34,7 @@ import * as hostProviders from "@hosts/host-providers" import { vscodeHostBridgeClient } from "@/hosts/vscode/client/host-grpc-client" import { VscodeWebviewProvider } from "./core/webview/VscodeWebviewProvider" import { ExtensionContext } from "vscode" +import { writeTextToClipboard, readTextFromClipboard } from "@/utils/env" /* Built using https://github.com/microsoft/vscode-webview-ui-toolkit @@ -369,17 +370,17 @@ export async function activate(context: vscode.ExtensionContext) { } // Save current clipboard content - const tempCopyBuffer = await vscode.env.clipboard.readText() + const tempCopyBuffer = await readTextFromClipboard() try { // Copy the *existing* terminal selection (without selecting all) await vscode.commands.executeCommand("workbench.action.terminal.copySelection") // Get copied content - let terminalContents = (await vscode.env.clipboard.readText()).trim() + let terminalContents = (await readTextFromClipboard()).trim() // Restore original clipboard content - await vscode.env.clipboard.writeText(tempCopyBuffer) + await writeTextToClipboard(tempCopyBuffer) if (!terminalContents) { // No terminal content was copied (either nothing selected or some error) @@ -405,7 +406,7 @@ export async function activate(context: vscode.ExtensionContext) { await visibleWebview?.controller.addSelectedTerminalOutputToChat(terminalContents, terminal.name) } catch (error) { // Ensure clipboard is restored even if an error occurs - await vscode.env.clipboard.writeText(tempCopyBuffer) + await writeTextToClipboard(tempCopyBuffer) console.error("Error getting terminal contents:", error) vscode.window.showErrorMessage("Failed to get terminal contents") } diff --git a/src/hosts/host-provider-types.ts b/src/hosts/host-provider-types.ts index 280709b4..43b5ec44 100644 --- a/src/hosts/host-provider-types.ts +++ b/src/hosts/host-provider-types.ts @@ -2,6 +2,7 @@ import { UriServiceClientInterface, WatchServiceClientInterface, WorkspaceServiceClientInterface, + EnvServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" /** @@ -11,6 +12,7 @@ export interface HostBridgeClientProvider { uriServiceClient: UriServiceClientInterface watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface + envClient: EnvServiceClientInterface } /** diff --git a/src/hosts/vscode/client/host-grpc-client.ts b/src/hosts/vscode/client/host-grpc-client.ts index 230483d3..04b06a54 100644 --- a/src/hosts/vscode/client/host-grpc-client.ts +++ b/src/hosts/vscode/client/host-grpc-client.ts @@ -6,4 +6,5 @@ export const vscodeHostBridgeClient: HostBridgeClientProvider = { uriServiceClient: createGrpcClient(host.UriServiceDefinition), watchServiceClient: createGrpcClient(host.WatchServiceDefinition), workspaceClient: createGrpcClient(host.WorkspaceServiceDefinition), + envClient: createGrpcClient(host.EnvServiceDefinition), } diff --git a/src/hosts/vscode/env/clipboardReadText.ts b/src/hosts/vscode/env/clipboardReadText.ts new file mode 100644 index 00000000..ac210d6d --- /dev/null +++ b/src/hosts/vscode/env/clipboardReadText.ts @@ -0,0 +1,7 @@ +import { EmptyRequest, String } from "@/shared/proto/common" +import * as vscode from "vscode" + +export async function clipboardReadText(_: EmptyRequest): Promise { + const text = await vscode.env.clipboard.readText() + return String.create({ value: text }) +} diff --git a/src/hosts/vscode/env/clipboardWriteText.ts b/src/hosts/vscode/env/clipboardWriteText.ts new file mode 100644 index 00000000..38c08af9 --- /dev/null +++ b/src/hosts/vscode/env/clipboardWriteText.ts @@ -0,0 +1,7 @@ +import { StringRequest, Empty } from "@/shared/proto/common" +import * as vscode from "vscode" + +export async function clipboardWriteText(request: StringRequest): Promise { + await vscode.env.clipboard.writeText(request.value) + return Empty.create({}) +} diff --git a/src/integrations/git/commit-message-generator.ts b/src/integrations/git/commit-message-generator.ts index eb0887b6..72878b28 100644 --- a/src/integrations/git/commit-message-generator.ts +++ b/src/integrations/git/commit-message-generator.ts @@ -1,5 +1,6 @@ import * as vscode from "vscode" import { getWorkingState } from "@utils/git" +import { writeTextToClipboard } from "@utils/env" /** * Formats the git diff into a prompt for the AI @@ -57,7 +58,7 @@ export function extractCommitMessage(aiResponse: string): string { * @param message The commit message to copy */ export async function copyCommitMessageToClipboard(message: string): Promise { - await vscode.env.clipboard.writeText(message) + await writeTextToClipboard(message) vscode.window.showInformationMessage("Commit message copied to clipboard") } diff --git a/src/integrations/terminal/get-latest-output.ts b/src/integrations/terminal/get-latest-output.ts index 0c869e7f..79192ae3 100644 --- a/src/integrations/terminal/get-latest-output.ts +++ b/src/integrations/terminal/get-latest-output.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode" +import { readTextFromClipboard, writeTextToClipboard } from "@utils/env" /** * Gets the contents of the active terminal @@ -6,7 +7,7 @@ import * as vscode from "vscode" */ export async function getLatestTerminalOutput(): Promise { // Store original clipboard content to restore later - const originalClipboard = await vscode.env.clipboard.readText() + const originalClipboard = await readTextFromClipboard() try { // Select terminal content @@ -19,7 +20,7 @@ export async function getLatestTerminalOutput(): Promise { await vscode.commands.executeCommand("workbench.action.terminal.clearSelection") // Get terminal contents from clipboard - let terminalContents = (await vscode.env.clipboard.readText()).trim() + let terminalContents = (await readTextFromClipboard()).trim() // Check if there's actually a terminal open if (terminalContents === originalClipboard) { @@ -40,6 +41,6 @@ export async function getLatestTerminalOutput(): Promise { return terminalContents } finally { // Restore original clipboard content - await vscode.env.clipboard.writeText(originalClipboard) + await writeTextToClipboard(originalClipboard) } } diff --git a/src/standalone/host-bridge-client-manager.ts b/src/standalone/host-bridge-client-manager.ts index 4d02107a..f6bb26e4 100644 --- a/src/standalone/host-bridge-client-manager.ts +++ b/src/standalone/host-bridge-client-manager.ts @@ -3,11 +3,13 @@ import { UriServiceClientImpl, WatchServiceClientImpl, WorkspaceServiceClientImpl, + EnvServiceClientImpl, } from "@generated/standalone/host-bridge-clients" import { UriServiceClientInterface, WatchServiceClientInterface, WorkspaceServiceClientInterface, + EnvServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" import { HostBridgeClientProvider } from "@/hosts/host-provider-types" @@ -20,6 +22,7 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider uriServiceClient: UriServiceClientInterface watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface + envClient: EnvServiceClientInterface constructor() { const address = process.env.HOST_BRIDGE_ADDRESS || "localhost:50052" @@ -28,6 +31,7 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider this.uriServiceClient = new UriServiceClientImpl(this.channel) this.watchServiceClient = new WatchServiceClientImpl(this.channel) this.workspaceClient = new WorkspaceServiceClientImpl(this.channel) + this.envClient = new EnvServiceClientImpl(this.channel) } public close(): void { diff --git a/src/utils/env.ts b/src/utils/env.ts new file mode 100644 index 00000000..832f049b --- /dev/null +++ b/src/utils/env.ts @@ -0,0 +1,32 @@ +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { StringRequest, EmptyRequest } from "@/shared/proto/common" + +/** + * Writes text to the system clipboard + * @param text The text to write to the clipboard + * @returns Promise that resolves when the operation is complete + * @throws Error if the operation fails + */ +export async function writeTextToClipboard(text: string): Promise { + try { + await getHostBridgeProvider().envClient.clipboardWriteText(StringRequest.create({ value: text })) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to write to clipboard: ${errorMessage}`) + } +} + +/** + * Reads text from the system clipboard + * @returns Promise that resolves to the clipboard text + * @throws Error if the operation fails + */ +export async function readTextFromClipboard(): Promise { + try { + const response = await getHostBridgeProvider().envClient.clipboardReadText(EmptyRequest.create({})) + return response.value + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to read from clipboard: ${errorMessage}`) + } +} diff --git a/src/utils/github-url-utils.ts b/src/utils/github-url-utils.ts index 0eb7293b..9ef4a96a 100644 --- a/src/utils/github-url-utils.ts +++ b/src/utils/github-url-utils.ts @@ -17,6 +17,7 @@ import * as vscode from "vscode" import * as cp from "child_process" import * as os from "os" import * as util from "util" +import { writeTextToClipboard } from "@/utils/env" /** * Creates a properly encoded GitHub issue URL. @@ -81,7 +82,7 @@ export async function openUrlInBrowser(url: string): Promise { // Always copy to clipboard as a fallback try { - await vscode.env.clipboard.writeText(url) + await writeTextToClipboard(url) console.log("URL copied to clipboard as backup") } catch (error) { console.error(`Failed to copy URL to clipboard: ${error}`) @@ -159,7 +160,7 @@ export async function openUrlInBrowser(url: string): Promise { ) .then((selection) => { if (selection === "Copy URL Again") { - vscode.env.clipboard.writeText(url) + writeTextToClipboard(url) } }) } From e898bd8825f7b6d423740a4008fb5f3c5a81aa0d Mon Sep 17 00:00:00 2001 From: Daniel Steigman <35793213+NightTrek@users.noreply.github.com> Date: Thu, 26 Jun 2025 16:47:34 -0700 Subject: [PATCH 07/60] Updated best model to be gemini (#4500) --- .../components/settings/OpenRouterModelPicker.tsx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index aae3cd23..cdbf8fc6 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -43,13 +43,13 @@ export interface OpenRouterModelPickerProps { // Featured models for Cline provider const featuredModels = [ { - id: "anthropic/claude-sonnet-4", - description: "Recommended for agentic coding in Cline", + id: "google/gemini-2.5-pro", + description: "Large 1M context window, great value", label: "Best", }, { - id: "google/gemini-2.5-pro", - description: "Large 1M context window, great value", + id: "anthropic/claude-sonnet-4", + description: "Recommended for agentic coding in Cline", label: "Trending", }, { @@ -334,8 +334,8 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } If you're unsure which model to choose, Cline works best with{" "} handleModelChange("anthropic/claude-sonnet-4")}> - anthropic/claude-sonnet-4. + onClick={() => handleModelChange("google/gemini-2.5-pro")}> + google/gemini-2.5-pro. You can also try searching "free" for no-cost options currently available. From 16da0f1e069ed664359cf4097c9def4ff7f8c39a Mon Sep 17 00:00:00 2001 From: kevinneung <94151024+kevinneung@users.noreply.github.com> Date: Thu, 26 Jun 2025 16:54:28 -0700 Subject: [PATCH 08/60] Fix telemetry source code link path (#4476) Update the source code link in telemetry documentation to point to the correct file location: src/services/posthog/telemetry/TelemetryService.ts --- docs/more-info/telemetry.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/more-info/telemetry.mdx b/docs/more-info/telemetry.mdx index 9ff1b7a9..fce237a4 100644 --- a/docs/more-info/telemetry.mdx +++ b/docs/more-info/telemetry.mdx @@ -6,7 +6,7 @@ title: "Telemetry" To help make Cline better for everyone, we collect anonymous usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience. -We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see exactly what we track. +We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/posthog/telemetry/TelemetryService.ts) to see exactly what we track. ### Tracking Policy @@ -22,7 +22,7 @@ We collect basic anonymous usage data including: **System Context:** OS type and VS Code environment details\ **UI Activity:** Navigation patterns and feature usage -For complete transparency, you can inspect our [telemetry implementation](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see the exact events we track. +For complete transparency, you can inspect our [telemetry implementation](https://github.com/cline/cline/blob/main/src/services/posthog/telemetry/TelemetryService.ts) to see the exact events we track. ### How to Opt Out From 68b84f3df487d945930dbb0bba555df0d67cda5d Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Thu, 26 Jun 2025 17:53:44 -0700 Subject: [PATCH 09/60] Fix for delete all bug, refactored deleteAll logic (#4497) --- .changeset/tall-elephants-sort.md | 5 ++ proto/task.proto | 10 +-- .../controller/task/deleteAllTaskHistory.ts | 36 ++++++-- .../task/deleteNonFavoritedTasks.ts | 88 ------------------- .../src/components/history/HistoryView.tsx | 14 +-- 5 files changed, 39 insertions(+), 114 deletions(-) create mode 100644 .changeset/tall-elephants-sort.md delete mode 100644 src/core/controller/task/deleteNonFavoritedTasks.ts diff --git a/.changeset/tall-elephants-sort.md b/.changeset/tall-elephants-sort.md new file mode 100644 index 00000000..17121ee6 --- /dev/null +++ b/.changeset/tall-elephants-sort.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Removed deleteNonFavoritedTasks, moved popup to extension, cleaned up deletion logic diff --git a/proto/task.proto b/proto/task.proto index 0933725b..0949cd17 100644 --- a/proto/task.proto +++ b/proto/task.proto @@ -23,8 +23,6 @@ service TaskService { rpc exportTaskWithId(StringRequest) returns (Empty); // Toggles the favorite status of a task rpc toggleTaskFavorite(TaskFavoriteRequest) returns (Empty); - // Deletes all non-favorited tasks - rpc deleteNonFavoritedTasks(EmptyRequest) returns (DeleteNonFavoritedTasksResults); // Gets filtered task history rpc getTaskHistory(GetTaskHistoryRequest) returns (TaskHistoryArray); // Sends a response to a previous ask operation @@ -36,7 +34,7 @@ service TaskService { // Executes a quick win task with command and title rpc executeQuickWin(ExecuteQuickWinRequest) returns (Empty); // Deletes all task history - rpc deleteAllTaskHistory(BooleanRequest) returns (DeleteAllTaskHistoryCount); + rpc deleteAllTaskHistory(EmptyRequest) returns (DeleteAllTaskHistoryCount); } // Request message for creating a new task @@ -68,12 +66,6 @@ message TaskResponse { int32 cache_reads = 10; } -// Results returned when deleting non-favorited tasks -message DeleteNonFavoritedTasksResults { - int32 tasks_preserved = 1; - int32 tasks_deleted = 2; -} - // Request for getting task history with filtering message GetTaskHistoryRequest { Metadata metadata = 1; diff --git a/src/core/controller/task/deleteAllTaskHistory.ts b/src/core/controller/task/deleteAllTaskHistory.ts index d05996c3..b6491fcf 100644 --- a/src/core/controller/task/deleteAllTaskHistory.ts +++ b/src/core/controller/task/deleteAllTaskHistory.ts @@ -2,7 +2,6 @@ import path from "path" import fs from "fs/promises" import { Controller } from ".." import { DeleteAllTaskHistoryCount } from "../../../shared/proto/task" -import { BooleanRequest } from "../../../shared/proto/common" import { getGlobalState, updateGlobalState } from "../../storage/state" import { fileExistsAtPath } from "../../../utils/fs" import vscode from "vscode" @@ -13,7 +12,7 @@ import vscode from "vscode" * @param request Request with option to preserve favorites * @returns Results with count of deleted tasks */ -export async function deleteAllTaskHistory(controller: Controller, request: BooleanRequest): Promise { +export async function deleteAllTaskHistory(controller: Controller): Promise { try { // Clear current task first await controller.clearTask() @@ -22,8 +21,22 @@ export async function deleteAllTaskHistory(controller: Controller, request: Bool const taskHistory = ((await getGlobalState(controller.context, "taskHistory")) as any[]) || [] const totalTasks = taskHistory.length + const userChoice = await vscode.window.showWarningMessage( + "What would you like to delete?", + { modal: true }, + "Delete All Except Favorites", + "Delete Everything", + ) + + // Default VS Code Cancel button returns `undefined` - don't delete anything + if (userChoice === undefined) { + return DeleteAllTaskHistoryCount.create({ + tasksDeleted: 0, + }) + } + // If preserving favorites, filter out non-favorites - if (request.value) { + if (userChoice === "Delete All Except Favorites") { const favoritedTasks = taskHistory.filter((task) => task.isFavorited === true) // If there are favorited tasks, update state @@ -45,9 +58,20 @@ export async function deleteAllTaskHistory(controller: Controller, request: Bool tasksDeleted: totalTasks - favoritedTasks.length, }) } else { - return DeleteAllTaskHistoryCount.create({ - tasksDeleted: 0, - }) + // No favorited tasks found - show warning and ask user what to do + const answer = await vscode.window.showWarningMessage( + "No favorited tasks found. Would you like to delete all tasks anyway?", + { modal: true }, + "Delete All Tasks", + ) + + // User cancelled - don't delete anything + if (answer === undefined) { + return DeleteAllTaskHistoryCount.create({ + tasksDeleted: 0, + }) + } + // If user chose "Delete All Tasks", fall through to the `delete everything` section below } } diff --git a/src/core/controller/task/deleteNonFavoritedTasks.ts b/src/core/controller/task/deleteNonFavoritedTasks.ts deleted file mode 100644 index 2f7bb92b..00000000 --- a/src/core/controller/task/deleteNonFavoritedTasks.ts +++ /dev/null @@ -1,88 +0,0 @@ -import path from "path" -import fs from "fs/promises" -import { Controller } from ".." -import { EmptyRequest } from "../../../shared/proto/common" -import { DeleteNonFavoritedTasksResults } from "../../../shared/proto/task" -import { getGlobalState, updateGlobalState } from "../../storage/state" -import { fileExistsAtPath } from "../../../utils/fs" - -/** - * Deletes all non-favorited tasks, preserving only favorited ones - * @param controller The controller instance - * @param request Empty request - * @returns DeleteNonFavoritedTasksResults with counts of preserved and deleted tasks - */ -export async function deleteNonFavoritedTasks( - controller: Controller, - _request: EmptyRequest, -): Promise { - try { - // Clear current task first - await controller.clearTask() - - // Get existing task history - const taskHistory = ((await getGlobalState(controller.context, "taskHistory")) as any[]) || [] - - // Filter out non-favorited tasks - const favoritedTasks = taskHistory.filter((task) => task.isFavorited === true) - const deletedCount = taskHistory.length - favoritedTasks.length - - console.log(`[deleteNonFavoritedTasks] Found ${favoritedTasks.length} favorited tasks to preserve`) - - // Update global state - if (favoritedTasks.length > 0) { - await updateGlobalState(controller.context, "taskHistory", favoritedTasks) - } else { - await updateGlobalState(controller.context, "taskHistory", undefined) - } - - // Handle file system cleanup for deleted tasks - const preserveTaskIds = favoritedTasks.map((task) => task.id) - await cleanupTaskFiles(controller, preserveTaskIds) - - // Update webview - try { - await controller.postStateToWebview() - } catch (webviewErr) { - console.error("Error posting to webview:", webviewErr) - } - - return DeleteNonFavoritedTasksResults.create({ - tasksPreserved: favoritedTasks.length, - tasksDeleted: deletedCount, - }) - } catch (error) { - console.error("Error in deleteNonFavoritedTasks:", error) - throw error - } -} - -/** - * Helper function to cleanup task files while preserving specified tasks - */ -async function cleanupTaskFiles(controller: Controller, preserveTaskIds: string[]) { - const taskDirPath = path.join(controller.context.globalStorageUri.fsPath, "tasks") - - try { - if (await fileExistsAtPath(taskDirPath)) { - if (preserveTaskIds.length > 0) { - const taskDirs = await fs.readdir(taskDirPath) - console.debug(`[cleanupTaskFiles] Found ${taskDirs.length} task directories`) - - // Delete only non-preserved task directories - for (const dir of taskDirs) { - if (!preserveTaskIds.includes(dir)) { - await fs.rm(path.join(taskDirPath, dir), { recursive: true, force: true }) - } - } - } else { - // No tasks to preserve, delete everything - await fs.rm(taskDirPath, { recursive: true, force: true }) - } - } - } catch (error) { - console.error("Error cleaning up task files:", error) - } - - return true -} diff --git a/webview-ui/src/components/history/HistoryView.tsx b/webview-ui/src/components/history/HistoryView.tsx index 53e34cda..da3dabfc 100644 --- a/webview-ui/src/components/history/HistoryView.tsx +++ b/webview-ui/src/components/history/HistoryView.tsx @@ -727,17 +727,9 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { disabled={deleteAllDisabled || taskHistory.length === 0} onClick={() => { setDeleteAllDisabled(true) - const confirmDelete = window.confirm("Are you sure you want to delete all task history?") - if (confirmDelete) { - const preserveFavorites = window.confirm( - "Would you like to preserve favorited tasks?\n\nClick 'OK' to preserve favorites, or 'Cancel' to delete everything.", - ) - TaskServiceClient.deleteAllTaskHistory(BooleanRequest.create({ value: preserveFavorites })) - .catch((error) => console.error("Error deleting task history:", error)) - .finally(() => setDeleteAllDisabled(false)) - } else { - setDeleteAllDisabled(false) - } + TaskServiceClient.deleteAllTaskHistory(BooleanRequest.create({})) + .catch((error) => console.error("Error deleting task history:", error)) + .finally(() => setDeleteAllDisabled(false)) }}> Delete All History{totalTasksSize !== null ? ` (${formatSize(totalTasksSize)})` : ""} From ab9f1a07854538a5f75b33f564c4fc34ef00847a Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 20:11:15 -0700 Subject: [PATCH 10/60] refactor request and fireworks provider ui (#4499) * requesty * fireworks --- .../src/components/settings/ApiOptions.tsx | 119 +++--------------- .../settings/providers/FireworksProvider.tsx | 83 ++++++++++++ .../settings/providers/RequestyProvider.tsx | 31 +++++ 3 files changed, 131 insertions(+), 102 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/FireworksProvider.tsx create mode 100644 webview-ui/src/components/settings/providers/RequestyProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 198532e6..b469efb8 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -54,6 +54,8 @@ import { GeminiProvider } from "./providers/GeminiProvider" import { DoubaoProvider } from "./providers/DoubaoProvider" import { VertexProvider } from "./providers/VertexProvider" import GeminiCliProvider from "./providers/GeminiCliProvider" +import { RequestyProvider } from "./providers/RequestyProvider" +import { FireworksProvider } from "./providers/FireworksProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -758,109 +760,22 @@ const ApiOptions = ({ /> )} - {selectedProvider === "requesty" && ( -
- - API Key - - {!apiConfiguration?.requestyApiKey && Get API Key} -
+ {apiConfiguration && selectedProvider === "requesty" && ( + )} - {selectedProvider === "fireworks" && ( -
- - Fireworks API Key - -

- This key is stored locally and only used to make API requests from this extension. - {!apiConfiguration?.fireworksApiKey && ( - - You can get a Fireworks API key by signing up here. - - )} -

- - Model ID - -

- - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) - -

- { - const value = (e.target as HTMLInputElement).value - if (!value) { - return - } - const num = parseInt(value, 10) - if (isNaN(num)) { - return - } - handleInputChange("fireworksModelMaxCompletionTokens")({ - target: { - value: num, - }, - }) - }} - placeholder={"2000"}> - Max Completion Tokens - - { - const value = (e.target as HTMLInputElement).value - if (!value) { - return - } - const num = parseInt(value) - if (isNaN(num)) { - return - } - handleInputChange("fireworksModelMaxTokens")({ - target: { - value: num, - }, - }) - }} - placeholder={"4000"}> - Max Context Tokens - -
+ {apiConfiguration && selectedProvider === "fireworks" && ( + )} {selectedProvider === "vscode-lm" && ( @@ -1531,6 +1446,7 @@ const ApiOptions = ({ selectedProvider !== "doubao" && selectedProvider !== "vertex" && selectedProvider !== "gemini-cli" && + selectedProvider !== "fireworks" && showModelOptions && ( <> @@ -1618,7 +1534,6 @@ const ApiOptions = ({ )} {selectedProvider === "cline" && showModelOptions && } - {selectedProvider === "requesty" && showModelOptions && } {modelIdErrorMessage && (

(event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Fireworks provider configuration component + */ +export const FireworksProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: FireworksProviderProps) => { + // Handler for number input fields with validation + const handleNumberInputChange = (field: keyof ApiConfiguration) => (e: any) => { + const value = (e.target as HTMLInputElement).value + if (!value) { + return + } + const num = parseInt(value, 10) + if (isNaN(num)) { + return + } + handleInputChange(field)({ + target: { + value: num, + }, + }) + } + + return ( +

+ + + {showModelOptions && ( + <> + + Model ID + +

+ + (Note: Cline uses complex prompts and works best with Claude + models. Less capable models may not work as expected.) + +

+ + Max Completion Tokens + + + Max Context Tokens + + + )} +
+ ) +} diff --git a/webview-ui/src/components/settings/providers/RequestyProvider.tsx b/webview-ui/src/components/settings/providers/RequestyProvider.tsx new file mode 100644 index 00000000..72e3998a --- /dev/null +++ b/webview-ui/src/components/settings/providers/RequestyProvider.tsx @@ -0,0 +1,31 @@ +import { ApiConfiguration } from "@shared/api" +import { ApiKeyField } from "../common/ApiKeyField" +import RequestyModelPicker from "../RequestyModelPicker" + +/** + * Props for the RequestyProvider component + */ +interface RequestyProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Requesty provider configuration component + */ +export const RequestyProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: RequestyProviderProps) => { + return ( +
+ + + {showModelOptions && } +
+ ) +} From 7cd4be7a68a11d727731982c60aa06dc79adb21b Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 20:34:34 -0700 Subject: [PATCH 11/60] xai (#4504) --- .../src/components/settings/ApiOptions.tsx | 90 ++----------- .../settings/providers/XaiProvider.tsx | 125 ++++++++++++++++++ 2 files changed, 135 insertions(+), 80 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/XaiProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index b469efb8..a3f2b767 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -56,6 +56,7 @@ import { VertexProvider } from "./providers/VertexProvider" import GeminiCliProvider from "./providers/GeminiCliProvider" import { RequestyProvider } from "./providers/RequestyProvider" import { FireworksProvider } from "./providers/FireworksProvider" +import { XaiProvider } from "./providers/XaiProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -1214,34 +1215,14 @@ const ApiOptions = ({

)} - {selectedProvider === "xai" && ( -
- - X AI API Key - -

- - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) - - This key is stored locally and only used to make API requests from this extension. - {!apiConfiguration?.xaiApiKey && ( - - You can get an X AI API key by signing up here. - - )} -

-
+ {apiConfiguration && selectedProvider === "xai" && ( + )} {selectedProvider === "cerebras" && ( @@ -1447,6 +1428,7 @@ const ApiOptions = ({ selectedProvider !== "vertex" && selectedProvider !== "gemini-cli" && selectedProvider !== "fireworks" && + selectedProvider !== "xai" && showModelOptions && ( <> @@ -1458,7 +1440,6 @@ const ApiOptions = ({ createDropdown( apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, )} - {selectedProvider === "xai" && createDropdown(xaiModels)} {selectedProvider === "cerebras" && createDropdown(cerebrasModels)} {selectedProvider === "nebius" && createDropdown(nebiusModels)} {selectedProvider === "sapaicore" && createDropdown(sapAiCoreModels)} @@ -1472,57 +1453,6 @@ const ApiOptions = ({ /> )} - {selectedProvider === "xai" && selectedModelId.includes("3-mini") && ( - <> - { - const isChecked = e.target.checked === true - setReasoningEffortSelected(isChecked) - if (!isChecked) { - setApiConfiguration({ - ...apiConfiguration, - reasoningEffort: "", - }) - } - }}> - Modify reasoning effort - - - {reasoningEffortSelected && ( -
- - - { - setApiConfiguration({ - ...apiConfiguration, - reasoningEffort: e.target.value, - }) - }}> - low - high - - -

- High effort may produce more thorough analysis but takes longer and uses more tokens. -

-
- )} - - )} (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +/** + * The xAI provider configuration component + */ +export const XaiProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: XaiProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + // Local state for reasoning effort toggle + const [reasoningEffortSelected, setReasoningEffortSelected] = useState(!!apiConfiguration?.reasoningEffort) + + return ( +
+
+ +

+ + (Note: Cline uses complex prompts and works best with Claude + models. Less capable models may not work as expected.) + +

+
+ + {showModelOptions && ( + <> + + + {selectedModelId && selectedModelId.includes("3-mini") && ( + <> + { + const isChecked = e.target.checked === true + setReasoningEffortSelected(isChecked) + if (!isChecked) { + setApiConfiguration({ + ...apiConfiguration, + reasoningEffort: "", + }) + } + }}> + Modify reasoning effort + + + {reasoningEffortSelected && ( +
+ + + { + setApiConfiguration({ + ...apiConfiguration, + reasoningEffort: e.target.value, + }) + }}> + low + high + + +

+ High effort may produce more thorough analysis but takes longer and uses more tokens. +

+
+ )} + + )} + + + + )} +
+ ) +} From 8bfa7daa2832c0ea30e9f437869a6bfd2193f110 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 20:45:30 -0700 Subject: [PATCH 12/60] refactor ollama settings to different component (#4506) --- .../src/components/settings/ApiOptions.tsx | 101 ++---------- .../settings/providers/OllamaProvider.tsx | 147 ++++++++++++++++++ 2 files changed, 156 insertions(+), 92 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/OllamaProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index a3f2b767..9b78f405 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -57,6 +57,7 @@ import GeminiCliProvider from "./providers/GeminiCliProvider" import { RequestyProvider } from "./providers/RequestyProvider" import { FireworksProvider } from "./providers/FireworksProvider" import { XaiProvider } from "./providers/XaiProvider" +import { OllamaProvider } from "./providers/OllamaProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -1100,73 +1101,14 @@ const ApiOptions = ({ )} - {selectedProvider === "ollama" && ( -
- - Base URL (optional) - - - {/* Model selection - use filterable picker */} - - { - setApiConfiguration({ - ...apiConfiguration, - ollamaModelId: modelId, - }) - }} - placeholder={ollamaModels.length > 0 ? "Search and select a model..." : "e.g. llama3.1"} - /> - - {/* Show status message based on model availability */} - {ollamaModels.length === 0 && ( -

- Unable to fetch models from Ollama server. Please ensure Ollama is running and accessible, or enter - the model ID manually above. -

- )} - - - Model Context Window - -

- Ollama allows you to run models locally on your computer. For instructions on how to get started, see - their{" "} - - quickstart guide. - {" "} - - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) - -

-
+ {apiConfiguration && selectedProvider === "ollama" && ( + )} {selectedProvider === "nebius" && ( @@ -1332,31 +1274,6 @@ const ApiOptions = ({

)} - {selectedProvider === "ollama" && showModelOptions && ( - <> - { - const value = e.target.value - // Convert to number, with validation - const numValue = parseInt(value, 10) - if (!isNaN(numValue) && numValue > 0) { - setApiConfiguration({ - ...apiConfiguration, - requestTimeoutMs: numValue, - }) - } - }} - placeholder="Default: 30000 (30 seconds)"> - Request Timeout (ms) - -

- Maximum time in milliseconds to wait for API responses before timing out. -

- - )} - {selectedProvider === "cline" && showModelOptions && ( <> (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +/** + * The Ollama provider configuration component + */ +export const OllamaProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: OllamaProviderProps) => { + const [ollamaModels, setOllamaModels] = useState([]) + + // Poll ollama models + const requestOllamaModels = useCallback(async () => { + try { + const response = await ModelsServiceClient.getOllamaModels( + StringRequest.create({ + value: apiConfiguration?.ollamaBaseUrl || "", + }), + ) + if (response && response.values) { + setOllamaModels(response.values) + } + } catch (error) { + console.error("Failed to fetch Ollama models:", error) + setOllamaModels([]) + } + }, [apiConfiguration?.ollamaBaseUrl]) + + useEffect(() => { + requestOllamaModels() + }, [requestOllamaModels]) + + useInterval(requestOllamaModels, 2000) + + return ( +
+ handleInputChange("ollamaBaseUrl")({ target: { value } })} + placeholder="Default: http://localhost:11434" + label="Use custom base URL" + /> + + {/* Model selection - use filterable picker */} + + { + setApiConfiguration({ + ...apiConfiguration, + ollamaModelId: modelId, + }) + }} + placeholder={ollamaModels.length > 0 ? "Search and select a model..." : "e.g. llama3.1"} + /> + + {/* Show status message based on model availability */} + {ollamaModels.length === 0 && ( +

+ Unable to fetch models from Ollama server. Please ensure Ollama is running and accessible, or enter the model + ID manually above. +

+ )} + + + Model Context Window + + + {showModelOptions && ( + <> + { + const value = e.target.value + // Convert to number, with validation + const numValue = parseInt(value, 10) + if (!isNaN(numValue) && numValue > 0) { + setApiConfiguration({ + ...apiConfiguration, + requestTimeoutMs: numValue, + }) + } + }} + placeholder="Default: 30000 (30 seconds)"> + Request Timeout (ms) + +

+ Maximum time in milliseconds to wait for API responses before timing out. +

+ + )} + +

+ Ollama allows you to run models locally on your computer. For instructions on how to get started, see their{" "} + + quickstart guide. + {" "} + + (Note: Cline uses complex prompts and works best with Claude models. + Less capable models may not work as expected.) + +

+
+ ) +} From 8c3fd8ba5508141188e98853d5ebca46153af25b Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 20:53:58 -0700 Subject: [PATCH 13/60] refactor cerebras provider menu ui (#4507) * xai * base --- .../src/components/settings/ApiOptions.tsx | 42 ++++------------- .../settings/providers/CerebrasProvider.tsx | 47 +++++++++++++++++++ 2 files changed, 56 insertions(+), 33 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/CerebrasProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 9b78f405..32cbaa45 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -5,7 +5,6 @@ import { ApiConfiguration, bedrockDefaultModelId, bedrockModels, - cerebrasModels, claudeCodeModels, geminiModels, internationalQwenModels, @@ -13,7 +12,6 @@ import { mainlandQwenModels, ModelInfo, nebiusModels, - xaiModels, sapAiCoreModels, } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" @@ -36,7 +34,6 @@ import * as vscodemodels from "vscode" import { ClineAccountInfoCard } from "./ClineAccountInfoCard" import OllamaModelPicker from "./OllamaModelPicker" import OpenRouterModelPicker, { ModelDescriptionMarkdown, OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" -import RequestyModelPicker from "./RequestyModelPicker" import ThinkingBudgetSlider from "./ThinkingBudgetSlider" import { formatPrice } from "./utils/pricingUtils" import { normalizeApiConfiguration } from "./utils/providerUtils" @@ -57,6 +54,7 @@ import GeminiCliProvider from "./providers/GeminiCliProvider" import { RequestyProvider } from "./providers/RequestyProvider" import { FireworksProvider } from "./providers/FireworksProvider" import { XaiProvider } from "./providers/XaiProvider" +import { CerebrasProvider } from "./providers/CerebrasProvider" import { OllamaProvider } from "./providers/OllamaProvider" interface ApiOptionsProps { @@ -1167,35 +1165,13 @@ const ApiOptions = ({ /> )} - {selectedProvider === "cerebras" && ( -
- - Cerebras API Key - -

- This key is stored locally and only used to make API requests from this extension. - {!apiConfiguration?.cerebrasApiKey && ( - - You can get a Cerebras API key by signing up here. - - )} -

-
+ {apiConfiguration && selectedProvider === "cerebras" && ( + )} {selectedProvider === "sapaicore" && ( @@ -1346,6 +1322,7 @@ const ApiOptions = ({ selectedProvider !== "gemini-cli" && selectedProvider !== "fireworks" && selectedProvider !== "xai" && + selectedProvider !== "cerebras" && showModelOptions && ( <> @@ -1357,7 +1334,6 @@ const ApiOptions = ({ createDropdown( apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, )} - {selectedProvider === "cerebras" && createDropdown(cerebrasModels)} {selectedProvider === "nebius" && createDropdown(nebiusModels)} {selectedProvider === "sapaicore" && createDropdown(sapAiCoreModels)} diff --git a/webview-ui/src/components/settings/providers/CerebrasProvider.tsx b/webview-ui/src/components/settings/providers/CerebrasProvider.tsx new file mode 100644 index 00000000..c5f07721 --- /dev/null +++ b/webview-ui/src/components/settings/providers/CerebrasProvider.tsx @@ -0,0 +1,47 @@ +import { ApiConfiguration, cerebrasModels } from "@shared/api" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelSelector } from "../common/ModelSelector" +import { ModelInfoView } from "../common/ModelInfoView" +import { normalizeApiConfiguration } from "../utils/providerUtils" + +/** + * Props for the CerebrasProvider component + */ +interface CerebrasProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Cerebras provider configuration component + */ +export const CerebrasProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: CerebrasProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + return ( +
+ + + {showModelOptions && ( + <> + + + + + )} +
+ ) +} From c13e749eed30bab0518438e9ae4a8875379590c7 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:05:29 -0700 Subject: [PATCH 14/60] refactor out sap ai core settings (#4508) --- .../src/components/settings/ApiOptions.tsx | 79 ++----------- .../settings/providers/SapAiCoreProvider.tsx | 105 ++++++++++++++++++ 2 files changed, 116 insertions(+), 68 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 32cbaa45..aff3627d 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -12,13 +12,11 @@ import { mainlandQwenModels, ModelInfo, nebiusModels, - sapAiCoreModels, } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" -import { OpenAiModelsRequest, UpdateApiConfigurationRequest } from "@shared/proto/models" +import { UpdateApiConfigurationRequest } from "@shared/proto/models" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" import { - VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeLink, @@ -27,7 +25,7 @@ import { VSCodeRadioGroup, VSCodeTextField, } from "@vscode/webview-ui-toolkit/react" -import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from "react" +import { Fragment, memo, useCallback, useEffect, useMemo, useState } from "react" import { useInterval } from "react-use" import styled from "styled-components" import * as vscodemodels from "vscode" @@ -56,6 +54,7 @@ import { FireworksProvider } from "./providers/FireworksProvider" import { XaiProvider } from "./providers/XaiProvider" import { CerebrasProvider } from "./providers/CerebrasProvider" import { OllamaProvider } from "./providers/OllamaProvider" +import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -1174,69 +1173,13 @@ const ApiOptions = ({ /> )} - {selectedProvider === "sapaicore" && ( -
- - AI Core Client Id - - {apiConfiguration?.sapAiCoreClientId && ( -

- Client Id is set. To change it, please re-enter the value. -

- )} - - AI Core Client Secret - - {apiConfiguration?.sapAiCoreClientSecret && ( -

- Client Secret is set. To change it, please re-enter the value. -

- )} - - AI Core Base URL - - - AI Core Auth URL - - - AI Core Resource Group - -

- These credentials are stored locally and only used to make API requests from this extension. - - You can find more information about SAP AI Core API access here. - -

-
+ {apiConfiguration && selectedProvider === "sapaicore" && ( + )} {apiErrorMessage && ( @@ -1323,6 +1266,7 @@ const ApiOptions = ({ selectedProvider !== "fireworks" && selectedProvider !== "xai" && selectedProvider !== "cerebras" && + selectedProvider !== "sapaicore" && showModelOptions && ( <> @@ -1335,7 +1279,6 @@ const ApiOptions = ({ apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, )} {selectedProvider === "nebius" && createDropdown(nebiusModels)} - {selectedProvider === "sapaicore" && createDropdown(sapAiCoreModels)} {SUPPORTED_THINKING_MODELS[selectedProvider]?.includes(selectedModelId) && ( diff --git a/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx new file mode 100644 index 00000000..1dd195b9 --- /dev/null +++ b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx @@ -0,0 +1,105 @@ +import { ApiConfiguration, sapAiCoreModels } from "@shared/api" +import { VSCodeTextField, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { ModelSelector } from "../common/ModelSelector" +import { ModelInfoView } from "../common/ModelInfoView" +import { normalizeApiConfiguration } from "../utils/providerUtils" + +/** + * Props for the SapAiCoreProvider component + */ +interface SapAiCoreProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The SAP AI Core provider configuration component + */ +export const SapAiCoreProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: SapAiCoreProviderProps) => { + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + return ( +
+ + AI Core Client Id + + {apiConfiguration?.sapAiCoreClientId && ( +

+ Client Id is set. To change it, please re-enter the value. +

+ )} + + + AI Core Client Secret + + {apiConfiguration?.sapAiCoreClientSecret && ( +

+ Client Secret is set. To change it, please re-enter the value. +

+ )} + + + AI Core Base URL + + + + AI Core Auth URL + + + + AI Core Resource Group + + +

+ These credentials are stored locally and only used to make API requests from this extension. + + You can find more information about SAP AI Core API access here. + +

+ + {showModelOptions && ( + <> + + + + + )} +
+ ) +} From 9563a71c8a402d6299db9fd452b2bfa60d8292d4 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:14:00 -0700 Subject: [PATCH 15/60] base (#4509) --- .../src/components/settings/ApiOptions.tsx | 30 +++------ .../settings/providers/ClaudeCodeProvider.tsx | 63 +++++++++++++++++++ 2 files changed, 72 insertions(+), 21 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index aff3627d..02bdecb6 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -5,7 +5,6 @@ import { ApiConfiguration, bedrockDefaultModelId, bedrockModels, - claudeCodeModels, geminiModels, internationalQwenModels, liteLlmModelInfoSaneDefaults, @@ -54,6 +53,7 @@ import { FireworksProvider } from "./providers/FireworksProvider" import { XaiProvider } from "./providers/XaiProvider" import { CerebrasProvider } from "./providers/CerebrasProvider" import { OllamaProvider } from "./providers/OllamaProvider" +import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" interface ApiOptionsProps { @@ -309,25 +309,13 @@ const ApiOptions = ({ /> )} - {selectedProvider === "claude-code" && ( -
- - -

- Path to the Claude Code CLI. -

-
+ {apiConfiguration && selectedProvider === "claude-code" && ( + )} {apiConfiguration && selectedProvider === "openai-native" && ( @@ -1248,6 +1236,7 @@ const ApiOptions = ({ selectedProvider !== "cline" && selectedProvider !== "anthropic" && selectedProvider !== "asksage" && + selectedProvider !== "claude-code" && selectedProvider !== "openai" && selectedProvider !== "ollama" && selectedProvider !== "lmstudio" && @@ -1273,7 +1262,6 @@ const ApiOptions = ({ - {selectedProvider === "claude-code" && createDropdown(claudeCodeModels)} {selectedProvider === "qwen" && createDropdown( apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, diff --git a/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx new file mode 100644 index 00000000..85b045cb --- /dev/null +++ b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx @@ -0,0 +1,63 @@ +import { ApiConfiguration, claudeCodeModels } from "@shared/api" +import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { ModelSelector } from "../common/ModelSelector" +import { ModelInfoView } from "../common/ModelInfoView" +import { normalizeApiConfiguration } from "../utils/providerUtils" + +/** + * Props for the ClaudeCodeProvider component + */ +interface ClaudeCodeProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Claude Code provider configuration component + */ +export const ClaudeCodeProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, +}: ClaudeCodeProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + return ( +
+ + Claude Code CLI Path + + +

+ Path to the Claude Code CLI. +

+ + {showModelOptions && ( + <> + + + + + )} +
+ ) +} From 40244f09fec5bd9229e353834e85e43a6c132d86 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:23:43 -0700 Subject: [PATCH 16/60] base (#4511) --- .../src/components/settings/ApiOptions.tsx | 95 ++------------- .../settings/providers/QwenProvider.tsx | 108 ++++++++++++++++++ 2 files changed, 118 insertions(+), 85 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/QwenProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 02bdecb6..56c736cf 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -6,9 +6,7 @@ import { bedrockDefaultModelId, bedrockModels, geminiModels, - internationalQwenModels, liteLlmModelInfoSaneDefaults, - mainlandQwenModels, ModelInfo, nebiusModels, } from "@shared/api" @@ -46,6 +44,7 @@ import { AskSageProvider } from "./providers/AskSageProvider" import { OpenAINativeProvider } from "./providers/OpenAINative" import { GeminiProvider } from "./providers/GeminiProvider" import { DoubaoProvider } from "./providers/DoubaoProvider" +import { QwenProvider } from "./providers/QwenProvider" import { VertexProvider } from "./providers/VertexProvider" import GeminiCliProvider from "./providers/GeminiCliProvider" import { RequestyProvider } from "./providers/RequestyProvider" @@ -64,21 +63,6 @@ interface ApiOptionsProps { saveImmediately?: boolean // Add prop to control immediate saving } -const SUPPORTED_THINKING_MODELS: Record = { - qwen: [ - "qwen3-235b-a22b", - "qwen3-32b", - "qwen3-30b-a3b", - "qwen3-14b", - "qwen3-8b", - "qwen3-4b", - "qwen3-1.7b", - "qwen3-0.6b", - "qwen-plus-latest", - "qwen-turbo-latest", - ], -} - // This is necessary to ensure dropdown opens downward, important for when this is used in popup export const DROPDOWN_Z_INDEX = OPENROUTER_MODEL_PICKER_Z_INDEX + 2 // Higher than the OpenRouterModelPicker's and ModelSelectorTooltip's z-index @@ -120,7 +104,6 @@ const ApiOptions = ({ const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) - const [reasoningEffortSelected, setReasoningEffortSelected] = useState(!!apiConfiguration?.reasoningEffort) const handleInputChange = (field: keyof ApiConfiguration) => (event: any) => { const newValue = event.target.value @@ -327,60 +310,14 @@ const ApiOptions = ({ /> )} - {selectedProvider === "qwen" && ( -
- - - - China API - International API - - -

- Please select the appropriate API interface based on your location. If you are in China, choose the China - API interface. Otherwise, choose the International API interface. -

- - Qwen API Key - -

- This key is stored locally and only used to make API requests from this extension. - {!apiConfiguration?.qwenApiKey && ( - - You can get a Qwen API key by signing up here. - - )} -

-
+ {apiConfiguration && selectedProvider === "qwen" && ( + )} {apiConfiguration && selectedProvider === "doubao" && ( @@ -1250,6 +1187,7 @@ const ApiOptions = ({ selectedProvider !== "openai-native" && selectedProvider !== "gemini" && selectedProvider !== "doubao" && + selectedProvider !== "qwen" && selectedProvider !== "vertex" && selectedProvider !== "gemini-cli" && selectedProvider !== "fireworks" && @@ -1262,21 +1200,8 @@ const ApiOptions = ({ - {selectedProvider === "qwen" && - createDropdown( - apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels, - )} {selectedProvider === "nebius" && createDropdown(nebiusModels)}
- - {SUPPORTED_THINKING_MODELS[selectedProvider]?.includes(selectedModelId) && ( - - )} - (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +/** + * The Alibaba Qwen provider configuration component + */ +export const QwenProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: QwenProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + // Determine which models to use based on API line selection + const qwenModels = apiConfiguration?.qwenApiLine === "china" ? mainlandQwenModels : internationalQwenModels + + return ( +
+ + + + China API + International API + + +

+ Please select the appropriate API interface based on your location. If you are in China, choose the China API + interface. Otherwise, choose the International API interface. +

+ + + + {showModelOptions && ( + <> + + + {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( + + )} + + + + )} +
+ ) +} From 6690d392cd52bc09adb3e3cc86e1171c52712010 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:29:27 -0700 Subject: [PATCH 17/60] refactor out bedrock (#4510) --- .../src/components/settings/ApiOptions.tsx | 289 +--------------- .../settings/providers/BedrockProvider.tsx | 311 ++++++++++++++++++ 2 files changed, 321 insertions(+), 279 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/BedrockProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 56c736cf..bc029485 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1,15 +1,7 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelsServiceClient } from "@/services/grpc-client" import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" -import { - ApiConfiguration, - bedrockDefaultModelId, - bedrockModels, - geminiModels, - liteLlmModelInfoSaneDefaults, - ModelInfo, - nebiusModels, -} from "@shared/api" +import { ApiConfiguration, geminiModels, liteLlmModelInfoSaneDefaults, ModelInfo, nebiusModels } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" import { UpdateApiConfigurationRequest } from "@shared/proto/models" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" @@ -54,6 +46,7 @@ import { CerebrasProvider } from "./providers/CerebrasProvider" import { OllamaProvider } from "./providers/OllamaProvider" import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" +import { BedrockProvider } from "./providers/BedrockProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -100,7 +93,6 @@ const ApiOptions = ({ const [ollamaModels, setOllamaModels] = useState([]) const [lmStudioModels, setLmStudioModels] = useState([]) const [vsCodeLmModels, setVsCodeLmModels] = useState([]) - const [awsEndpointSelected, setAwsEndpointSelected] = useState(!!apiConfiguration?.awsBedrockEndpoint) const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) @@ -384,275 +376,14 @@ const ApiOptions = ({ /> )} - {selectedProvider === "bedrock" && ( -
- { - const value = (e.target as HTMLInputElement)?.value - const useProfile = value === "profile" - setApiConfiguration({ - ...apiConfiguration, - awsUseProfile: useProfile, - }) - }}> - AWS Credentials - AWS Profile - - - {apiConfiguration?.awsUseProfile ? ( - - AWS Profile Name - - ) : ( - <> - - AWS Access Key - - - AWS Secret Key - - - AWS Session Token - - - )} - - - - Select a region... - {/* The user will have to choose a region that supports the model they use, but this shouldn't be a problem since they'd have to request access for it in that region in the first place. */} - us-east-1 - us-east-2 - {/* us-west-1 */} - us-west-2 - {/* af-south-1 */} - {/* ap-east-1 */} - ap-south-1 - ap-northeast-1 - ap-northeast-2 - ap-northeast-3 - ap-southeast-1 - ap-southeast-2 - ca-central-1 - eu-central-1 - eu-central-2 - eu-west-1 - eu-west-2 - eu-west-3 - eu-north-1 - eu-south-1 - eu-south-2 - {/* me-south-1 */} - sa-east-1 - us-gov-east-1 - us-gov-west-1 - {/* us-gov-east-1 */} - - - -
- { - const isChecked = e.target.checked === true - setAwsEndpointSelected(isChecked) - if (!isChecked) { - setApiConfiguration({ - ...apiConfiguration, - awsBedrockEndpoint: "", - }) - } - }}> - Use custom VPC endpoint - - - {awsEndpointSelected && ( - - )} - - { - const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - awsUseCrossRegionInference: isChecked, - }) - }}> - Use cross-region inference - - - {selectedModelInfo.supportsPromptCache && ( - <> - { - const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - awsBedrockUsePromptCache: isChecked, - }) - }}> - Use prompt caching - - - )} -
-

- {apiConfiguration?.awsUseProfile ? ( - <> - Using AWS Profile credentials from ~/.aws/credentials. Leave profile name empty to use the default - profile. These credentials are only used locally to make API requests from this extension. - - ) : ( - <> - Authenticate by either providing the keys above or use the default AWS credential providers, i.e. - ~/.aws/credentials or environment variables. These credentials are only used locally to make API - requests from this extension. - - )} -

- - - { - const isCustom = e.target.value === "custom" - setApiConfiguration({ - ...apiConfiguration, - apiModelId: isCustom ? "" : e.target.value, - awsBedrockCustomSelected: isCustom, - awsBedrockCustomModelBaseId: bedrockDefaultModelId, - }) - }} - style={{ width: "100%" }}> - Select a model... - {Object.keys(bedrockModels).map((modelId) => ( - - {modelId} - - ))} - Custom - - - {apiConfiguration?.awsBedrockCustomSelected && ( -
-

- Select "Custom" when using the Application Inference Profile in Bedrock. Enter the Application - Inference Profile ARN in the Model ID field. -

- - - - - - Select a model... - {Object.keys(bedrockModels).map((modelId) => ( - - {modelId} - - ))} - - -
- )} - {(selectedModelId === "anthropic.claude-3-7-sonnet-20250219-v1:0" || - selectedModelId === "anthropic.claude-sonnet-4-20250514-v1:0" || - selectedModelId === "anthropic.claude-opus-4-20250514-v1:0" || - (apiConfiguration?.awsBedrockCustomSelected && - apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-3-7-sonnet-20250219-v1:0") || - (apiConfiguration?.awsBedrockCustomSelected && - apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-sonnet-4-20250514-v1:0") || - (apiConfiguration?.awsBedrockCustomSelected && - apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-opus-4-20250514-v1:0")) && ( - - )} - -
+ {apiConfiguration && selectedProvider === "bedrock" && ( + )} {apiConfiguration && selectedProvider === "vertex" && ( diff --git a/webview-ui/src/components/settings/providers/BedrockProvider.tsx b/webview-ui/src/components/settings/providers/BedrockProvider.tsx new file mode 100644 index 00000000..01c3be6a --- /dev/null +++ b/webview-ui/src/components/settings/providers/BedrockProvider.tsx @@ -0,0 +1,311 @@ +import { ApiConfiguration, bedrockDefaultModelId, bedrockModels } from "@shared/api" +import { + VSCodeCheckbox, + VSCodeDropdown, + VSCodeOption, + VSCodeRadio, + VSCodeRadioGroup, + VSCodeTextField, +} from "@vscode/webview-ui-toolkit/react" +import { useState } from "react" +import { ModelInfoView } from "../common/ModelInfoView" +import { DropdownContainer } from "../common/ModelSelector" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { normalizeApiConfiguration } from "../utils/providerUtils" + +// Z-index constants for proper dropdown layering +const DROPDOWN_Z_INDEX = 1000 + +interface BedrockProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +export const BedrockProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: BedrockProviderProps) => { + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + const [awsEndpointSelected, setAwsEndpointSelected] = useState(!!apiConfiguration?.awsBedrockEndpoint) + + return ( +
+ { + const value = (e.target as HTMLInputElement)?.value + const useProfile = value === "profile" + setApiConfiguration({ + ...apiConfiguration, + awsUseProfile: useProfile, + }) + }}> + AWS Credentials + AWS Profile + + + {apiConfiguration?.awsUseProfile ? ( + + AWS Profile Name + + ) : ( + <> + + AWS Access Key + + + AWS Secret Key + + + AWS Session Token + + + )} + + + + + Select a region... + {/* The user will have to choose a region that supports the model they use, but this shouldn't be a problem since they'd have to request access for it in that region in the first place. */} + us-east-1 + us-east-2 + {/* us-west-1 */} + us-west-2 + {/* af-south-1 */} + {/* ap-east-1 */} + ap-south-1 + ap-northeast-1 + ap-northeast-2 + ap-northeast-3 + ap-southeast-1 + ap-southeast-2 + ca-central-1 + eu-central-1 + eu-central-2 + eu-west-1 + eu-west-2 + eu-west-3 + eu-north-1 + eu-south-1 + eu-south-2 + {/* me-south-1 */} + sa-east-1 + us-gov-east-1 + us-gov-west-1 + {/* us-gov-east-1 */} + + + +
+ { + const isChecked = e.target.checked === true + setAwsEndpointSelected(isChecked) + if (!isChecked) { + setApiConfiguration({ + ...apiConfiguration, + awsBedrockEndpoint: "", + }) + } + }}> + Use custom VPC endpoint + + + {awsEndpointSelected && ( + + )} + + { + const isChecked = e.target.checked === true + setApiConfiguration({ + ...apiConfiguration, + awsUseCrossRegionInference: isChecked, + }) + }}> + Use cross-region inference + + + {selectedModelInfo.supportsPromptCache && ( + <> + { + const isChecked = e.target.checked === true + setApiConfiguration({ + ...apiConfiguration, + awsBedrockUsePromptCache: isChecked, + }) + }}> + Use prompt caching + + + )} +
+ +

+ {apiConfiguration?.awsUseProfile ? ( + <> + Using AWS Profile credentials from ~/.aws/credentials. Leave profile name empty to use the default + profile. These credentials are only used locally to make API requests from this extension. + + ) : ( + <> + Authenticate by either providing the keys above or use the default AWS credential providers, i.e. + ~/.aws/credentials or environment variables. These credentials are only used locally to make API requests + from this extension. + + )} +

+ + {showModelOptions && ( + <> + + + { + const isCustom = e.target.value === "custom" + setApiConfiguration({ + ...apiConfiguration, + apiModelId: isCustom ? "" : e.target.value, + awsBedrockCustomSelected: isCustom, + awsBedrockCustomModelBaseId: bedrockDefaultModelId, + }) + }} + style={{ width: "100%" }}> + Select a model... + {Object.keys(bedrockModels).map((modelId) => ( + + {modelId} + + ))} + Custom + + + + {apiConfiguration?.awsBedrockCustomSelected && ( +
+

+ Select "Custom" when using the Application Inference Profile in Bedrock. Enter the Application + Inference Profile ARN in the Model ID field. +

+ + + + + + Select a model... + {Object.keys(bedrockModels).map((modelId) => ( + + {modelId} + + ))} + + +
+ )} + + {(selectedModelId === "anthropic.claude-3-7-sonnet-20250219-v1:0" || + selectedModelId === "anthropic.claude-sonnet-4-20250514-v1:0" || + selectedModelId === "anthropic.claude-opus-4-20250514-v1:0" || + (apiConfiguration?.awsBedrockCustomSelected && + apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-3-7-sonnet-20250219-v1:0") || + (apiConfiguration?.awsBedrockCustomSelected && + apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-sonnet-4-20250514-v1:0") || + (apiConfiguration?.awsBedrockCustomSelected && + apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-opus-4-20250514-v1:0")) && ( + + )} + + + + )} +
+ ) +} From ca984609caa34dd611d431ee4700b760f4ea3e24 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:41:35 -0700 Subject: [PATCH 18/60] refactor out cline (#4512) --- .../src/components/settings/ApiOptions.tsx | 67 ++------------- .../settings/providers/ClineProvider.tsx | 86 +++++++++++++++++++ 2 files changed, 94 insertions(+), 59 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/ClineProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index bc029485..dbee31de 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -18,13 +18,13 @@ import { Fragment, memo, useCallback, useEffect, useMemo, useState } from "react import { useInterval } from "react-use" import styled from "styled-components" import * as vscodemodels from "vscode" -import { ClineAccountInfoCard } from "./ClineAccountInfoCard" import OllamaModelPicker from "./OllamaModelPicker" import OpenRouterModelPicker, { ModelDescriptionMarkdown, OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" import ThinkingBudgetSlider from "./ThinkingBudgetSlider" import { formatPrice } from "./utils/pricingUtils" import { normalizeApiConfiguration } from "./utils/providerUtils" +import { ClineProvider } from "./providers/ClineProvider" import { OpenRouterProvider } from "./providers/OpenRouterProvider" import { MistralProvider } from "./providers/MistralProvider" import { DeepSeekProvider } from "./providers/DeepSeekProvider" @@ -95,7 +95,6 @@ const ApiOptions = ({ const [vsCodeLmModels, setVsCodeLmModels] = useState([]) const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) - const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) const handleInputChange = (field: keyof ApiConfiguration) => (event: any) => { const newValue = event.target.value @@ -259,10 +258,13 @@ const ApiOptions = ({
- {selectedProvider === "cline" && ( -
- -
+ {apiConfiguration && selectedProvider === "cline" && ( + )} {apiConfiguration && selectedProvider === "asksage" && ( @@ -849,57 +851,6 @@ const ApiOptions = ({

)} - {selectedProvider === "cline" && showModelOptions && ( - <> - { - const isChecked = e.target.checked === true - setProviderSortingSelected(isChecked) - if (!isChecked) { - setApiConfiguration({ - ...apiConfiguration, - openRouterProviderSorting: "", - }) - } - }}> - Sort underlying provider routing - - - {providerSortingSelected && ( -
- - { - setApiConfiguration({ - ...apiConfiguration, - openRouterProviderSorting: e.target.value, - }) - }}> - Default - Price - Throughput - Latency - - -

- {!apiConfiguration?.openRouterProviderSorting && - "Default behavior is to load balance requests across providers (like AWS, Google Vertex, Anthropic), prioritizing price while considering provider uptime"} - {apiConfiguration?.openRouterProviderSorting === "price" && - "Sort providers by price, prioritizing the lowest cost provider"} - {apiConfiguration?.openRouterProviderSorting === "throughput" && - "Sort providers by throughput, prioritizing the provider with the highest throughput (may increase cost)"} - {apiConfiguration?.openRouterProviderSorting === "latency" && - "Sort providers by response time, prioritizing the provider with the lowest latency"} -

-
- )} - - )} - {selectedProvider !== "openrouter" && selectedProvider !== "cline" && selectedProvider !== "anthropic" && @@ -943,8 +894,6 @@ const ApiOptions = ({ )} - {selectedProvider === "cline" && showModelOptions && } - {modelIdErrorMessage && (

(event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Cline provider configuration component + */ +export const ClineProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: ClineProviderProps) => { + const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) + + // Create a wrapper for handling field changes more directly + const handleFieldChange = (field: keyof ApiConfiguration) => (value: any) => { + handleInputChange(field)({ target: { value } }) + } + + return ( +

+ {/* Cline Account Info Card */} +
+ +
+ + {showModelOptions && ( + <> + {/* Provider Sorting Options */} + { + const isChecked = e.target.checked === true + setProviderSortingSelected(isChecked) + if (!isChecked) { + handleFieldChange("openRouterProviderSorting")("") + } + }}> + Sort underlying provider routing + + + {providerSortingSelected && ( +
+ + { + handleFieldChange("openRouterProviderSorting")(e.target.value) + }}> + Default + Price + Throughput + Latency + + +

+ {!apiConfiguration?.openRouterProviderSorting && + "Default behavior is to load balance requests across providers (like AWS, Google Vertex, Anthropic), prioritizing price while considering provider uptime"} + {apiConfiguration?.openRouterProviderSorting === "price" && + "Sort providers by price, prioritizing the lowest cost provider"} + {apiConfiguration?.openRouterProviderSorting === "throughput" && + "Sort providers by throughput, prioritizing the provider with the highest throughput (may increase cost)"} + {apiConfiguration?.openRouterProviderSorting === "latency" && + "Sort providers by response time, prioritizing the provider with the lowest latency"} +

+
+ )} + + {/* OpenRouter Model Picker */} + + + )} +
+ ) +} From abccde0e2a43c815d006d1aba1bf2e160982c9cb Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 21:55:37 -0700 Subject: [PATCH 19/60] refactor out vscode lm (#4513) --- .../src/components/settings/ApiOptions.tsx | 81 +--------------- .../settings/providers/VSCodeLmProvider.tsx | 96 +++++++++++++++++++ 2 files changed, 101 insertions(+), 76 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/VSCodeLmProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index dbee31de..3c675418 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -47,6 +47,7 @@ import { OllamaProvider } from "./providers/OllamaProvider" import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" import { BedrockProvider } from "./providers/BedrockProvider" +import { VSCodeLmProvider } from "./providers/VSCodeLmProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -92,7 +93,6 @@ const ApiOptions = ({ const { apiConfiguration, setApiConfiguration, uriScheme } = extensionState const [ollamaModels, setOllamaModels] = useState([]) const [lmStudioModels, setLmStudioModels] = useState([]) - const [vsCodeLmModels, setVsCodeLmModels] = useState([]) const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) @@ -160,27 +160,14 @@ const ApiOptions = ({ console.error("Failed to fetch LM Studio models:", error) setLmStudioModels([]) } - } else if (selectedProvider === "vscode-lm") { - try { - const response = await ModelsServiceClient.getVsCodeLmModels(EmptyRequest.create({})) - if (response && response.models) { - setVsCodeLmModels(response.models) - } - } catch (error) { - console.error("Failed to fetch VS Code LM models:", error) - setVsCodeLmModels([]) - } } }, [selectedProvider, apiConfiguration?.ollamaBaseUrl, apiConfiguration?.lmStudioBaseUrl]) useEffect(() => { - if (selectedProvider === "ollama" || selectedProvider === "lmstudio" || selectedProvider === "vscode-lm") { + if (selectedProvider === "ollama" || selectedProvider === "lmstudio") { requestLocalModels() } }, [selectedProvider, requestLocalModels]) - useInterval( - requestLocalModels, - selectedProvider === "ollama" || selectedProvider === "lmstudio" || selectedProvider === "vscode-lm" ? 2000 : null, - ) + useInterval(requestLocalModels, selectedProvider === "ollama" || selectedProvider === "lmstudio" ? 2000 : null) /* VSCodeDropdown has an open bug where dynamically rendered options don't auto select the provided value prop. You can see this for yourself by comparing it with normal select/option elements, which work as expected. @@ -435,66 +422,8 @@ const ApiOptions = ({ /> )} - {selectedProvider === "vscode-lm" && ( -
- - - {vsCodeLmModels.length > 0 ? ( - { - const value = (e.target as HTMLInputElement).value - if (!value) { - return - } - const [vendor, family] = value.split("/") - handleInputChange("vsCodeLmModelSelector")({ - target: { - value: { vendor, family }, - }, - }) - }} - style={{ width: "100%" }}> - Select a model... - {vsCodeLmModels.map((model) => ( - - {model.vendor} - {model.family} - - ))} - - ) : ( -

- The VS Code Language Model API allows you to run models provided by other VS Code extensions - (including but not limited to GitHub Copilot). The easiest way to get started is to install the - Copilot extension from the VS Marketplace and enabling Claude 4 Sonnet. -

- )} - -

- Note: This is a very experimental integration and may not work as expected. -

-
-
+ {apiConfiguration && selectedProvider === "vscode-lm" && ( + )} {selectedProvider === "lmstudio" && ( diff --git a/webview-ui/src/components/settings/providers/VSCodeLmProvider.tsx b/webview-ui/src/components/settings/providers/VSCodeLmProvider.tsx new file mode 100644 index 00000000..2daebb55 --- /dev/null +++ b/webview-ui/src/components/settings/providers/VSCodeLmProvider.tsx @@ -0,0 +1,96 @@ +import { ApiConfiguration } from "@shared/api" +import { EmptyRequest } from "@shared/proto/common" +import { ModelsServiceClient } from "@/services/grpc-client" +import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useState, useCallback, useEffect } from "react" +import { useInterval } from "react-use" +import * as vscodemodels from "vscode" +import { DropdownContainer, DROPDOWN_Z_INDEX } from "../ApiOptions" + +interface VSCodeLmProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void +} + +export const VSCodeLmProvider = ({ apiConfiguration, handleInputChange }: VSCodeLmProviderProps) => { + const [vsCodeLmModels, setVsCodeLmModels] = useState([]) + + // Poll VS Code LM models + const requestVsCodeLmModels = useCallback(async () => { + try { + const response = await ModelsServiceClient.getVsCodeLmModels(EmptyRequest.create({})) + if (response && response.models) { + setVsCodeLmModels(response.models) + } + } catch (error) { + console.error("Failed to fetch VS Code LM models:", error) + setVsCodeLmModels([]) + } + }, []) + + useEffect(() => { + requestVsCodeLmModels() + }, [requestVsCodeLmModels]) + + useInterval(requestVsCodeLmModels, 2000) + + return ( +
+ + + {vsCodeLmModels.length > 0 ? ( + { + const value = (e.target as HTMLInputElement).value + if (!value) { + return + } + const [vendor, family] = value.split("/") + handleInputChange("vsCodeLmModelSelector")({ + target: { + value: { vendor, family }, + }, + }) + }} + style={{ width: "100%" }}> + Select a model... + {vsCodeLmModels.map((model) => ( + + {model.vendor} - {model.family} + + ))} + + ) : ( +

+ The VS Code Language Model API allows you to run models provided by other VS Code extensions (including + but not limited to GitHub Copilot). The easiest way to get started is to install the Copilot extension + from the VS Marketplace and enabling Claude 4 Sonnet. +

+ )} + +

+ Note: This is a very experimental integration and may not work as expected. +

+
+
+ ) +} From 985cb51c39f641e917948ea1434dcce7e3bc4efb Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Thu, 26 Jun 2025 22:34:14 -0700 Subject: [PATCH 20/60] refactor lmstudio (#4514) * refactor lmstudio * merge conflict deleted stuff --- .../src/components/settings/ApiOptions.tsx | 99 +++------------- .../settings/providers/LMStudioProvider.tsx | 109 ++++++++++++++++++ 2 files changed, 123 insertions(+), 85 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/LMStudioProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 3c675418..12d75d43 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -48,6 +48,7 @@ import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" import { BedrockProvider } from "./providers/BedrockProvider" import { VSCodeLmProvider } from "./providers/VSCodeLmProvider" +import { LMStudioProvider } from "./providers/LMStudioProvider" interface ApiOptionsProps { showModelOptions: boolean @@ -92,7 +93,6 @@ const ApiOptions = ({ const extensionState = useExtensionState() const { apiConfiguration, setApiConfiguration, uriScheme } = extensionState const [ollamaModels, setOllamaModels] = useState([]) - const [lmStudioModels, setLmStudioModels] = useState([]) const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) @@ -130,7 +130,7 @@ const ApiOptions = ({ return normalizeApiConfiguration(apiConfiguration) }, [apiConfiguration]) - // Poll ollama/lmstudio models + // Poll ollama/vscode-lm models const requestLocalModels = useCallback(async () => { if (selectedProvider === "ollama") { try { @@ -146,28 +146,14 @@ const ApiOptions = ({ console.error("Failed to fetch Ollama models:", error) setOllamaModels([]) } - } else if (selectedProvider === "lmstudio") { - try { - const response = await ModelsServiceClient.getLmStudioModels( - StringRequest.create({ - value: apiConfiguration?.lmStudioBaseUrl || "", - }), - ) - if (response && response.values) { - setLmStudioModels(response.values) - } - } catch (error) { - console.error("Failed to fetch LM Studio models:", error) - setLmStudioModels([]) - } } - }, [selectedProvider, apiConfiguration?.ollamaBaseUrl, apiConfiguration?.lmStudioBaseUrl]) + }, [selectedProvider, apiConfiguration?.ollamaBaseUrl]) useEffect(() => { - if (selectedProvider === "ollama" || selectedProvider === "lmstudio") { + if (selectedProvider === "ollama") { requestLocalModels() } }, [selectedProvider, requestLocalModels]) - useInterval(requestLocalModels, selectedProvider === "ollama" || selectedProvider === "lmstudio" ? 2000 : null) + useInterval(requestLocalModels, selectedProvider === "ollama" ? 2000 : null) /* VSCodeDropdown has an open bug where dynamically rendered options don't auto select the provided value prop. You can see this for yourself by comparing it with normal select/option elements, which work as expected. @@ -426,72 +412,6 @@ const ApiOptions = ({ )} - {selectedProvider === "lmstudio" && ( -
- - Base URL (optional) - - - Model ID - - {lmStudioModels.length > 0 && ( - { - const value = (e.target as HTMLInputElement)?.value - // need to check value first since radio group returns empty string sometimes - if (value) { - handleInputChange("lmStudioModelId")({ - target: { value }, - }) - } - }}> - {lmStudioModels.map((model) => ( - - {model} - - ))} - - )} -

- LM Studio allows you to run models locally on your computer. For instructions on how to get started, see - their - - quickstart guide. - - You will also need to start LM Studio's{" "} - - local server - {" "} - feature to use it with this extension.{" "} - - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) - -

-
- )} - {selectedProvider === "litellm" && (
)} + {apiConfiguration && selectedProvider === "lmstudio" && ( + + )} + {apiConfiguration && selectedProvider === "ollama" && ( (event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The LM Studio provider configuration component + */ +export const LMStudioProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: LMStudioProviderProps) => { + const [lmStudioModels, setLmStudioModels] = useState([]) + + // Poll LM Studio models + const requestLmStudioModels = useCallback(async () => { + try { + const response = await ModelsServiceClient.getLmStudioModels( + StringRequest.create({ + value: apiConfiguration?.lmStudioBaseUrl || "", + }), + ) + if (response && response.values) { + setLmStudioModels(response.values) + } + } catch (error) { + console.error("Failed to fetch LM Studio models:", error) + setLmStudioModels([]) + } + }, [apiConfiguration?.lmStudioBaseUrl]) + + useEffect(() => { + requestLmStudioModels() + }, [requestLmStudioModels]) + + useInterval(requestLmStudioModels, 2000) + + return ( +
+ handleInputChange("lmStudioBaseUrl")({ target: { value } })} + placeholder="Default: http://localhost:1234" + label="Use custom base URL" + /> + + + Model ID + + + {lmStudioModels.length > 0 && ( + { + const value = (e.target as HTMLInputElement)?.value + // need to check value first since radio group returns empty string sometimes + if (value) { + handleInputChange("lmStudioModelId")({ + target: { value }, + }) + } + }}> + {lmStudioModels.map((model) => ( + + {model} + + ))} + + )} + +

+ LM Studio allows you to run models locally on your computer. For instructions on how to get started, see their + + quickstart guide. + + You will also need to start LM Studio's{" "} + + local server + {" "} + feature to use it with this extension.{" "} + + (Note: Cline uses complex prompts and works best with Claude models. + Less capable models may not work as expected.) + +

+
+ ) +} From 0e29f05e289f0d3c2571e7df78cef6f26ee71945 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 22:39:56 -0700 Subject: [PATCH 21/60] refactor nebius and remove unused logic (#4515) * base 2 Co-authored-by: StvLz * base 3 --------- Co-authored-by: StvLz --- .../src/components/settings/ApiOptions.tsx | 304 +----------------- .../settings/OpenRouterModelPicker.tsx | 11 +- .../settings/RequestyModelPicker.tsx | 11 +- .../settings/providers/NebiusProvider.tsx | 48 +++ 4 files changed, 61 insertions(+), 313 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/NebiusProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 12d75d43..80d0caed 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1,7 +1,7 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelsServiceClient } from "@/services/grpc-client" import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" -import { ApiConfiguration, geminiModels, liteLlmModelInfoSaneDefaults, ModelInfo, nebiusModels } from "@shared/api" +import { ApiConfiguration, geminiModels, liteLlmModelInfoSaneDefaults, ModelInfo } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" import { UpdateApiConfigurationRequest } from "@shared/proto/models" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" @@ -21,7 +21,6 @@ import * as vscodemodels from "vscode" import OllamaModelPicker from "./OllamaModelPicker" import OpenRouterModelPicker, { ModelDescriptionMarkdown, OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" import ThinkingBudgetSlider from "./ThinkingBudgetSlider" -import { formatPrice } from "./utils/pricingUtils" import { normalizeApiConfiguration } from "./utils/providerUtils" import { ClineProvider } from "./providers/ClineProvider" @@ -47,6 +46,7 @@ import { OllamaProvider } from "./providers/OllamaProvider" import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" import { BedrockProvider } from "./providers/BedrockProvider" +import { NebiusProvider } from "./providers/NebiusProvider" import { VSCodeLmProvider } from "./providers/VSCodeLmProvider" import { LMStudioProvider } from "./providers/LMStudioProvider" @@ -94,7 +94,6 @@ const ApiOptions = ({ const { apiConfiguration, setApiConfiguration, uriScheme } = extensionState const [ollamaModels, setOllamaModels] = useState([]) const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) - const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) const handleInputChange = (field: keyof ApiConfiguration) => (event: any) => { const newValue = event.target.value @@ -624,50 +623,13 @@ const ApiOptions = ({ /> )} - {selectedProvider === "nebius" && ( -
- - Nebius API Key - -

- This key is stored locally and only used to make API requests from this extension.{" "} - {!apiConfiguration?.nebiusApiKey && ( - - You can get a Nebius API key by signing up here.{" "} - - )} - - (Note: Cline uses complex prompts and works best with Claude - models. Less capable models may not work as expected.) - -

-
- )} - - {apiErrorMessage && ( -

- {apiErrorMessage} -

+ {apiConfiguration && selectedProvider === "nebius" && ( + )} {apiConfiguration && selectedProvider === "xai" && ( @@ -708,50 +670,6 @@ const ApiOptions = ({ {apiErrorMessage}

)} - - {selectedProvider !== "openrouter" && - selectedProvider !== "cline" && - selectedProvider !== "anthropic" && - selectedProvider !== "asksage" && - selectedProvider !== "claude-code" && - selectedProvider !== "openai" && - selectedProvider !== "ollama" && - selectedProvider !== "lmstudio" && - selectedProvider !== "vscode-lm" && - selectedProvider !== "litellm" && - selectedProvider !== "requesty" && - selectedProvider !== "bedrock" && - selectedProvider !== "mistral" && - selectedProvider !== "deepseek" && - selectedProvider !== "sambanova" && - selectedProvider !== "openai-native" && - selectedProvider !== "gemini" && - selectedProvider !== "doubao" && - selectedProvider !== "qwen" && - selectedProvider !== "vertex" && - selectedProvider !== "gemini-cli" && - selectedProvider !== "fireworks" && - selectedProvider !== "xai" && - selectedProvider !== "cerebras" && - selectedProvider !== "sapaicore" && - showModelOptions && ( - <> - - - {selectedProvider === "nebius" && createDropdown(nebiusModels)} - - - - )} - {modelIdErrorMessage && (

{ - if (!tiers || tiers.length === 0) { - return [] - } - - return tiers - .map((tier, index, arr) => { - const prevLimit = index > 0 ? arr[index - 1].contextWindow : 0 - const price = tier[priceType] - - if (price === undefined) return null - - return ( - - {formatPrice(price)}/million tokens ( - {tier.contextWindow === Number.POSITIVE_INFINITY ? ( - - {">"} {prevLimit.toLocaleString()} - - ) : ( - - {"<="} {tier.contextWindow.toLocaleString()} - - )} - {" tokens)"} - {index < arr.length - 1 &&
} -
- ) - }) - .filter((element): element is JSX.Element => element !== null) -} - -export const ModelInfoView = ({ - selectedModelId, - modelInfo, - isDescriptionExpanded, - setIsDescriptionExpanded, - isPopup, -}: { - selectedModelId: string - modelInfo: ModelInfo - isDescriptionExpanded: boolean - setIsDescriptionExpanded: (isExpanded: boolean) => void - isPopup?: boolean -}) => { - const isGemini = Object.keys(geminiModels).includes(selectedModelId) - const hasThinkingConfig = !!modelInfo.thinkingConfig - const hasTiers = !!modelInfo.tiers && modelInfo.tiers.length > 0 - - // Create elements for input pricing - const inputPriceElement = hasTiers ? ( - - Input price: -
- {formatTiers(modelInfo.tiers, "inputPrice")} -
- ) : modelInfo.inputPrice !== undefined && modelInfo.inputPrice > 0 ? ( - - Input price: {formatPrice(modelInfo.inputPrice)}/million tokens - - ) : null - - // --- Output Price Logic --- - let outputPriceElement = null - if (hasThinkingConfig && modelInfo.outputPrice !== undefined && modelInfo.thinkingConfig?.outputPrice !== undefined) { - // Display both standard and thinking budget prices - outputPriceElement = ( - - Output price (Standard): {formatPrice(modelInfo.outputPrice)}/million - tokens -
- Output price (Thinking Budget > 0):{" "} - {formatPrice(modelInfo.thinkingConfig.outputPrice)}/million tokens -
- ) - } else if (hasTiers) { - // Display tiered output pricing - outputPriceElement = ( - - Output price: - (based on input tokens) -
- {formatTiers(modelInfo.tiers, "outputPrice")} -
- ) - } else if (modelInfo.outputPrice !== undefined && modelInfo.outputPrice > 0) { - // Display single standard output price - outputPriceElement = ( - - Output price: {formatPrice(modelInfo.outputPrice)}/million tokens - - ) - } - // --- End Output Price Logic --- - - const infoItems = [ - modelInfo.description && ( - - ), - , - , - !isGemini && ( - - ), - modelInfo.maxTokens !== undefined && modelInfo.maxTokens > 0 && ( - - Max output: {modelInfo.maxTokens?.toLocaleString()} tokens - - ), - inputPriceElement, // Add the generated input price block - modelInfo.supportsPromptCache && modelInfo.cacheWritesPrice && ( - - Cache writes price: {formatPrice(modelInfo.cacheWritesPrice || 0)} - /million tokens - - ), - modelInfo.supportsPromptCache && modelInfo.cacheReadsPrice && ( - - Cache reads price: {formatPrice(modelInfo.cacheReadsPrice || 0)}/million - tokens - - ), - outputPriceElement, // Add the generated output price block - isGemini && ( - - * Free up to {selectedModelId && selectedModelId.includes("flash") ? "15" : "2"} requests per minute. After that, - billing depends on prompt size.{" "} - - For more info, see pricing details. - - - ), - ].filter(Boolean) - - return ( -

- {infoItems.map((item, index) => ( - - {item} - {index < infoItems.length - 1 &&
} -
- ))} -

- ) -} - -const ModelInfoSupportsItem = ({ - isSupported, - supportsLabel, - doesNotSupportLabel, -}: { - isSupported: boolean - supportsLabel: string - doesNotSupportLabel: string -}) => ( - - - {isSupported ? supportsLabel : doesNotSupportLabel} - -) - export default memo(ApiOptions) diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index cdbf8fc6..cefebaf1 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -10,7 +10,7 @@ import { useRemark } from "react-remark" import { useMount } from "react-use" import styled from "styled-components" import { highlight } from "../history/HistoryView" -import { ModelInfoView } from "./ApiOptions" +import { ModelInfoView } from "./common/ModelInfoView" import { normalizeApiConfiguration } from "./utils/providerUtils" import FeaturedModelCard from "./FeaturedModelCard" import ThinkingBudgetSlider from "./ThinkingBudgetSlider" @@ -66,7 +66,6 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } const [selectedIndex, setSelectedIndex] = useState(-1) const dropdownRef = useRef(null) const itemRefs = useRef<(HTMLDivElement | null)[]>([]) - const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) const dropdownListRef = useRef(null) const handleModelChange = (newModelId: string) => { @@ -311,13 +310,7 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } )} - + ) : (

= ({ isPopup }) => const [selectedIndex, setSelectedIndex] = useState(-1) const dropdownRef = useRef(null) const itemRefs = useRef<(HTMLDivElement | null)[]>([]) - const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false) const dropdownListRef = useRef(null) const handleModelChange = (newModelId: string) => { @@ -230,13 +229,7 @@ const RequestyModelPicker: React.FC = ({ isPopup }) => {showBudgetSlider && ( )} - + ) : (

(event: any) => void + showModelOptions: boolean + isPopup?: boolean +} + +/** + * The Nebius AI Studio provider configuration component + */ +export const NebiusProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: NebiusProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + return ( +

+ + + {showModelOptions && ( + <> + + + + + )} +
+ ) +} From 656e3276c6131cf4f2907b46ff758687e751ba44 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Thu, 26 Jun 2025 22:51:12 -0700 Subject: [PATCH 22/60] lite llm provider ui (#4517) * base 2 Co-authored-by: StvLz * base 3 * base --------- Co-authored-by: StvLz --- .../src/components/settings/ApiOptions.tsx | 204 +--------------- .../settings/providers/LiteLlmProvider.tsx | 231 ++++++++++++++++++ 2 files changed, 240 insertions(+), 195 deletions(-) create mode 100644 webview-ui/src/components/settings/providers/LiteLlmProvider.tsx diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 80d0caed..44ee49ea 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1,7 +1,5 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelsServiceClient } from "@/services/grpc-client" -import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" -import { ApiConfiguration, geminiModels, liteLlmModelInfoSaneDefaults, ModelInfo } from "@shared/api" import { EmptyRequest, StringRequest } from "@shared/proto/common" import { UpdateApiConfigurationRequest } from "@shared/proto/models" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" @@ -18,9 +16,7 @@ import { Fragment, memo, useCallback, useEffect, useMemo, useState } from "react import { useInterval } from "react-use" import styled from "styled-components" import * as vscodemodels from "vscode" -import OllamaModelPicker from "./OllamaModelPicker" import OpenRouterModelPicker, { ModelDescriptionMarkdown, OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" -import ThinkingBudgetSlider from "./ThinkingBudgetSlider" import { normalizeApiConfiguration } from "./utils/providerUtils" import { ClineProvider } from "./providers/ClineProvider" @@ -47,6 +43,7 @@ import { ClaudeCodeProvider } from "./providers/ClaudeCodeProvider" import { SapAiCoreProvider } from "./providers/SapAiCoreProvider" import { BedrockProvider } from "./providers/BedrockProvider" import { NebiusProvider } from "./providers/NebiusProvider" +import { LiteLlmProvider } from "./providers/LiteLlmProvider" import { VSCodeLmProvider } from "./providers/VSCodeLmProvider" import { LMStudioProvider } from "./providers/LMStudioProvider" @@ -411,197 +408,14 @@ const ApiOptions = ({ )} - {selectedProvider === "litellm" && ( -
- - Base URL (optional) - - - API Key - - - Model ID - - -
- {selectedModelInfo.supportsPromptCache && ( - <> - { - const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - liteLlmUsePromptCache: isChecked, - }) - }} - style={{ fontWeight: 500, color: "var(--vscode-charts-green)" }}> - Use prompt caching (GA) - -

- Prompt caching requires a supported provider and model -

- - )} -
- - <> - -

- Extended thinking is available for models such as Sonnet-4, o3-mini, Deepseek R1, etc. More info on{" "} - - thinking mode configuration - -

- - -
setModelConfigurationSelected((val) => !val)}> - - - Model Configuration - -
- {modelConfigurationSelected && ( - <> - { - const isChecked = e.target.checked === true - const modelInfo = apiConfiguration?.liteLlmModelInfo - ? apiConfiguration.liteLlmModelInfo - : { ...liteLlmModelInfoSaneDefaults } - modelInfo.supportsImages = isChecked - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) - }}> - Supports Images - -
- { - const modelInfo = apiConfiguration?.liteLlmModelInfo - ? apiConfiguration.liteLlmModelInfo - : { ...liteLlmModelInfoSaneDefaults } - modelInfo.contextWindow = Number(input.target.value) - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) - }}> - Context Window Size - - { - const modelInfo = apiConfiguration?.liteLlmModelInfo - ? apiConfiguration.liteLlmModelInfo - : { ...liteLlmModelInfoSaneDefaults } - modelInfo.maxTokens = input.target.value - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) - }}> - Max Output Tokens - -
-
- { - const modelInfo = apiConfiguration?.liteLlmModelInfo - ? apiConfiguration.liteLlmModelInfo - : { ...liteLlmModelInfoSaneDefaults } - - // Check if the input ends with a decimal point or has trailing zeros after decimal - const value = input.target.value - const shouldPreserveFormat = - value.endsWith(".") || (value.includes(".") && value.endsWith("0")) - - modelInfo.temperature = - value === "" - ? liteLlmModelInfoSaneDefaults.temperature - : shouldPreserveFormat - ? value // Keep as string to preserve decimal format - : parseFloat(value) - - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) - }}> - Temperature - -
- - )} -

- LiteLLM provides a unified interface to access various LLM providers' models. See their{" "} - - quickstart guide - {" "} - for more information. -

-
+ {apiConfiguration && selectedProvider === "litellm" && ( + )} {apiConfiguration && selectedProvider === "lmstudio" && ( diff --git a/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx new file mode 100644 index 00000000..bfa1e468 --- /dev/null +++ b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx @@ -0,0 +1,231 @@ +import { useState } from "react" +import { ApiConfiguration, liteLlmModelInfoSaneDefaults } from "@shared/api" +import { VSCodeTextField, VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { ModelInfoView } from "../common/ModelInfoView" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" + +/** + * Props for the LiteLlmProvider component + */ +interface LiteLlmProviderProps { + apiConfiguration: ApiConfiguration + handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void + showModelOptions: boolean + isPopup?: boolean + setApiConfiguration: (config: ApiConfiguration) => void +} + +/** + * The LiteLLM provider configuration component + */ +export const LiteLlmProvider = ({ + apiConfiguration, + handleInputChange, + showModelOptions, + isPopup, + setApiConfiguration, +}: LiteLlmProviderProps) => { + // Get the normalized configuration + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) + + // Local state for collapsible model configuration section + const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) + + return ( +
+ + Base URL (optional) + + + API Key + + + Model ID + + +
+ {selectedModelInfo.supportsPromptCache && ( + <> + { + const isChecked = e.target.checked === true + setApiConfiguration({ + ...apiConfiguration, + liteLlmUsePromptCache: isChecked, + }) + }} + style={{ fontWeight: 500, color: "var(--vscode-charts-green)" }}> + Use prompt caching (GA) + +

+ Prompt caching requires a supported provider and model +

+ + )} +
+ + <> + +

+ Extended thinking is available for models such as Sonnet-4, o3-mini, Deepseek R1, etc. More info on{" "} + + thinking mode configuration + +

+ + +
setModelConfigurationSelected((val) => !val)}> + + + Model Configuration + +
+ {modelConfigurationSelected && ( + <> + { + const isChecked = e.target.checked === true + const modelInfo = apiConfiguration?.liteLlmModelInfo + ? apiConfiguration.liteLlmModelInfo + : { ...liteLlmModelInfoSaneDefaults } + modelInfo.supportsImages = isChecked + setApiConfiguration({ + ...apiConfiguration, + liteLlmModelInfo: modelInfo, + }) + }}> + Supports Images + +
+ { + const modelInfo = apiConfiguration?.liteLlmModelInfo + ? apiConfiguration.liteLlmModelInfo + : { ...liteLlmModelInfoSaneDefaults } + modelInfo.contextWindow = Number(input.target.value) + setApiConfiguration({ + ...apiConfiguration, + liteLlmModelInfo: modelInfo, + }) + }}> + Context Window Size + + { + const modelInfo = apiConfiguration?.liteLlmModelInfo + ? apiConfiguration.liteLlmModelInfo + : { ...liteLlmModelInfoSaneDefaults } + modelInfo.maxTokens = input.target.value + setApiConfiguration({ + ...apiConfiguration, + liteLlmModelInfo: modelInfo, + }) + }}> + Max Output Tokens + +
+
+ { + const modelInfo = apiConfiguration?.liteLlmModelInfo + ? apiConfiguration.liteLlmModelInfo + : { ...liteLlmModelInfoSaneDefaults } + + // Check if the input ends with a decimal point or has trailing zeros after decimal + const value = input.target.value + const shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0")) + + modelInfo.temperature = + value === "" + ? liteLlmModelInfoSaneDefaults.temperature + : shouldPreserveFormat + ? value // Keep as string to preserve decimal format + : parseFloat(value) + + setApiConfiguration({ + ...apiConfiguration, + liteLlmModelInfo: modelInfo, + }) + }}> + Temperature + +
+ + )} +

+ LiteLLM provides a unified interface to access various LLM providers' models. See their{" "} + + quickstart guide + {" "} + for more information. +

+ + {showModelOptions && ( + + )} +
+ ) +} From 247552fcb5440804e759d82022e863608e1d8c81 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 27 Jun 2025 09:35:02 -0700 Subject: [PATCH 23/60] remove unused function (#4518) --- .../src/components/settings/ApiOptions.tsx | 42 +++---------------- .../settings/common/ModelSelector.tsx | 11 +++++ 2 files changed, 17 insertions(+), 36 deletions(-) diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 44ee49ea..995a1877 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1,22 +1,15 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelsServiceClient } from "@/services/grpc-client" -import { EmptyRequest, StringRequest } from "@shared/proto/common" +import { ApiConfiguration } from "@shared/api" +import { StringRequest } from "@shared/proto/common" import { UpdateApiConfigurationRequest } from "@shared/proto/models" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" -import { - VSCodeCheckbox, - VSCodeDropdown, - VSCodeLink, - VSCodeOption, - VSCodeRadio, - VSCodeRadioGroup, - VSCodeTextField, -} from "@vscode/webview-ui-toolkit/react" -import { Fragment, memo, useCallback, useEffect, useMemo, useState } from "react" +import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { memo, useCallback, useEffect, useMemo, useState } from "react" import { useInterval } from "react-use" import styled from "styled-components" -import * as vscodemodels from "vscode" -import OpenRouterModelPicker, { ModelDescriptionMarkdown, OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" +import { OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" + import { normalizeApiConfiguration } from "./utils/providerUtils" import { ClineProvider } from "./providers/ClineProvider" @@ -159,29 +152,6 @@ const ApiOptions = ({ As a workaround, we create separate instances of the dropdown for each provider, and then conditionally render the one that matches the current provider. */ - const createDropdown = (models: Record) => { - return ( - - Select a model... - {Object.keys(models).map((modelId) => ( - - {modelId} - - ))} - - ) - } return (
diff --git a/webview-ui/src/components/settings/common/ModelSelector.tsx b/webview-ui/src/components/settings/common/ModelSelector.tsx index 81d31032..0be3b9a9 100644 --- a/webview-ui/src/components/settings/common/ModelSelector.tsx +++ b/webview-ui/src/components/settings/common/ModelSelector.tsx @@ -32,6 +32,17 @@ interface ModelSelectorProps { label?: string } +/* +OG Saoud Note: + + VSCodeDropdown has an open bug where dynamically rendered options don't auto select the provided value prop. You can see this for yourself by comparing it with normal select/option elements, which work as expected. + https://github.com/microsoft/vscode-webview-ui-toolkit/issues/433 + + In our case, when the user switches between providers, we recalculate the selectedModelId depending on the provider, the default model for that provider, and a modelId that the user may have selected. Unfortunately, the VSCodeDropdown component wouldn't select this calculated value, and would default to the first "Select a model..." option instead, which makes it seem like the model was cleared out when it wasn't. + + As a workaround, we create separate instances of the dropdown for each provider, and then conditionally render the one that matches the current provider. + */ + /** * A reusable component for selecting models from a dropdown */ From efe2388e4a36e743e08f9650036700d93bd4b330 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 27 Jun 2025 10:57:54 -0700 Subject: [PATCH 24/60] refactor out apiconfig section (#4528) --- .../src/components/settings/SettingsView.tsx | 81 +++------------ .../sections/ApiConfigurationSection.tsx | 99 +++++++++++++++++++ 2 files changed, 110 insertions(+), 70 deletions(-) create mode 100644 webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 066bfe08..b559ea1d 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -21,6 +21,7 @@ import PreferredLanguageSetting from "./PreferredLanguageSetting" // Added impor import Section from "./Section" import SectionHeader from "./SectionHeader" import TerminalSettingsSection from "./TerminalSettingsSection" +import ApiConfigurationSection from "./sections/ApiConfigurationSection" import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" const IS_DEV = process.env.IS_DEV @@ -761,76 +762,16 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { {/* API Configuration Tab */} {activeTab === "api-config" && ( -
- {renderSectionHeader("api-config")} -
- {/* Tabs container */} - {planActSeparateModelsSetting ? ( -
-
- handlePlanActModeChange("plan")} - disabled={isSwitchingMode} - style={{ - opacity: isSwitchingMode ? 0.6 : 1, - cursor: isSwitchingMode ? "not-allowed" : "pointer", - }}> - {isSwitchingMode && chatSettings.mode === "act" - ? "Switching..." - : "Plan Mode"} - - handlePlanActModeChange("act")} - disabled={isSwitchingMode} - style={{ - opacity: isSwitchingMode ? 0.6 : 1, - cursor: isSwitchingMode ? "not-allowed" : "pointer", - }}> - {isSwitchingMode && chatSettings.mode === "plan" - ? "Switching..." - : "Act Mode"} - -
- - {/* Content container */} -
- -
-
- ) : ( - - )} - -
- { - const checked = e.target.checked === true - setPlanActSeparateModelsSetting(checked) - }}> - Use different models for Plan and Act modes - -

- Switching between Plan and Act mode will persist the API and model used in the - previous mode. This may be helpful e.g. when using a strong reasoning model to - architect a plan for a cheaper coding model to act on. -

-
-
-
+ )} {/* General Settings Tab */} diff --git a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx new file mode 100644 index 00000000..77c53f63 --- /dev/null +++ b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx @@ -0,0 +1,99 @@ +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" +import { memo } from "react" +import { TabButton } from "../../mcp/configuration/McpConfigurationView" +import ApiOptions from "../ApiOptions" +import Section from "../Section" + +import { ChatSettings } from "@shared/ChatSettings" + +interface ApiConfigurationSectionProps { + planActSeparateModelsSetting: boolean + chatSettings: ChatSettings + isSwitchingMode: boolean + apiErrorMessage?: string + modelIdErrorMessage?: string + handlePlanActModeChange: (mode: "plan" | "act") => Promise + setPlanActSeparateModelsSetting: (value: boolean) => void + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +const ApiConfigurationSection = ({ + planActSeparateModelsSetting, + chatSettings, + isSwitchingMode, + apiErrorMessage, + modelIdErrorMessage, + handlePlanActModeChange, + setPlanActSeparateModelsSetting, + renderSectionHeader, +}: ApiConfigurationSectionProps) => { + return ( +
+ {renderSectionHeader("api-config")} +
+ {/* Tabs container */} + {planActSeparateModelsSetting ? ( +
+
+ handlePlanActModeChange("plan")} + disabled={isSwitchingMode} + style={{ + opacity: isSwitchingMode ? 0.6 : 1, + cursor: isSwitchingMode ? "not-allowed" : "pointer", + }}> + {isSwitchingMode && chatSettings.mode === "act" ? "Switching..." : "Plan Mode"} + + handlePlanActModeChange("act")} + disabled={isSwitchingMode} + style={{ + opacity: isSwitchingMode ? 0.6 : 1, + cursor: isSwitchingMode ? "not-allowed" : "pointer", + }}> + {isSwitchingMode && chatSettings.mode === "plan" ? "Switching..." : "Act Mode"} + +
+ + {/* Content container */} +
+ +
+
+ ) : ( + + )} + +
+ { + const checked = e.target.checked === true + setPlanActSeparateModelsSetting(checked) + }}> + Use different models for Plan and Act modes + +

+ Switching between Plan and Act mode will persist the API and model used in the previous mode. This may be + helpful e.g. when using a strong reasoning model to architect a plan for a cheaper coding model to act on. +

+
+
+
+ ) +} + +export default memo(ApiConfigurationSection) From d2f1e0cde0b968c21e5dd4db96e334c75df90367 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Fri, 27 Jun 2025 11:51:02 -0700 Subject: [PATCH 25/60] Replace vscode.workspace.workspaceFolders with host bridge getWorkspacePaths (#4443) * Use the host bridge in utils/path.ts Update utils/path.ts to use the host bridge to get the workspace folders, instead of the vscode SDK. Update callers to use await as the functions are now async. * Replace vscode workspaceFolders in WorkspaceTracker Make the cwd an instance property because await cannot be used at the top level. * Use the host bridge getWorkspacePaths in FileContextTracker Replace the vscode SDK getWorkspaceFolders with the util function getCwd (this is already switched to the host bridge). * Fix test failure Update the rootDir for the tests to be "." instead of "src". The changes to path.ts pull in new dependencies from the extension, which indirectly include files from the webview-ui. ``` Run npm run pretest > claude-dev@3.18.0 pretest > npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint > claude-dev@3.18.0 compile-tests > node ./scripts/build-tests.js node:child_process:957 throw err; ^ Error: Command failed: tsc -p ./tsconfig.test.json --outDir out at genericNodeError (node:internal/errors:983:15) at wrappedFn (node:internal/errors:537:14) at checkExecSyncError (node:child_process:882:11) at execSync (node:child_process:954:15) at Object. (/home/runner/work/cline/cline/scripts/build-tests.js:55:1) at Module._compile (node:internal/modules/cjs/loader:1730:14) at Object..js (node:internal/modules/cjs/loader:1895:10) at Module.load (node:internal/modules/cjs/loader:1465:32) at Function._load (node:internal/modules/cjs/loader:1282:12) at TracingChannel.traceSync (node:diagnostics_channel:322:14) { status: 2, signal: null, output: [ null, "src/services/test/TestServer.ts(8,35): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" + "webview-ui/src/services/grpc-client-base.ts(1,24): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/utils/vscode.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" + "webview-ui/src/services/grpc-client.ts(4,34): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client-base.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n", '' ], pid: 2496, stdout: "src/services/test/TestServer.ts(8,35): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" + "webview-ui/src/services/grpc-client-base.ts(1,24): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/utils/vscode.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" + "webview-ui/src/services/grpc-client.ts(4,34): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client-base.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n", stderr: '' } ``` * Build the protos before compiling the tests. The tests depend on generated files now, so compile the extension before the tests so that the protos are built. * Set up the host providers in the integration test FileContextTracker.test.ts * Reduce the amount of logging in grpc-service.ts Just log the service registration, instead of every rpc. * In the `clean` build target, also remove the compiled test code. * Correct the alias mapping for the compiled test files. --- package.json | 4 +-- .../FileContextTracker.test.ts | 5 +++- .../context-tracking/FileContextTracker.ts | 10 ++++--- src/core/controller/file/searchCommits.ts | 2 +- src/core/controller/file/searchFiles.ts | 4 +-- src/core/controller/grpc-service.ts | 2 +- src/core/controller/index.ts | 9 ++++--- src/core/controller/task/getTaskHistory.ts | 2 +- src/core/task/ToolExecutor.ts | 20 +++++++------- .../workspace/WorkspaceTracker.ts | 27 +++++++++++-------- src/utils/path.ts | 17 +++++++++--- test-setup.js | 2 +- tsconfig.test.json | 2 +- 13 files changed, 64 insertions(+), 42 deletions(-) diff --git a/package.json b/package.json index ec0c6bbf..6051ad56 100644 --- a/package.json +++ b/package.json @@ -332,14 +332,14 @@ "package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.js --production", "protos": "node proto/build-proto.js && node scripts/generate-server-setup.mjs && node scripts/generate-host-bridge-client.mjs", "postprotos": "prettier src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --write --log-level warn", - "clean": "rimraf dist dist-standalone webview-ui/build src/generated", + "clean": "rimraf dist dist-standalone webview-ui/build src/generated out/", "compile-tests": "node ./scripts/build-tests.js", "watch-tests": "tsc -p . -w --outDir out", - "pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint", "check-types": "npm run protos && tsc --noEmit", "lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && buf lint && cd webview-ui && npm run lint", "format": "prettier . --check", "format:fix": "prettier . --write", + "pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint", "test": "npm-run-all test:unit test:integration", "test:ci": "node scripts/test-ci.js", "test:integration": "vscode-test", diff --git a/src/core/context/context-tracking/FileContextTracker.test.ts b/src/core/context/context-tracking/FileContextTracker.test.ts index f5fe6587..27fea102 100644 --- a/src/core/context/context-tracking/FileContextTracker.test.ts +++ b/src/core/context/context-tracking/FileContextTracker.test.ts @@ -6,6 +6,9 @@ import * as path from "path" import { FileContextTracker } from "./FileContextTracker" import * as diskModule from "@core/storage/disk" import type { TaskMetadata, FileMetadataEntry } from "./ContextTrackerTypes" +import type { WebviewProviderCreator } from "@/hosts/host-providers" +import * as hostProviders from "@hosts/host-providers" +import { vscodeHostBridgeClient } from "@/hosts/vscode/client/host-grpc-client" describe("FileContextTracker", () => { let sandbox: sinon.SinonSandbox @@ -37,7 +40,6 @@ describe("FileContextTracker", () => { } // Use a function replacement instead of a direct stub - const originalCreateFileSystemWatcher = vscode.workspace.createFileSystemWatcher vscode.workspace.createFileSystemWatcher = function () { return mockFileSystemWatcher } @@ -51,6 +53,7 @@ describe("FileContextTracker", () => { mockTaskMetadata = { files_in_context: [], model_usage: [] } getTaskMetadataStub = sandbox.stub(diskModule, "getTaskMetadata").resolves(mockTaskMetadata) saveTaskMetadataStub = sandbox.stub(diskModule, "saveTaskMetadata").resolves() + hostProviders.initializeHostProviders(((_) => {}) as WebviewProviderCreator, vscodeHostBridgeClient) // Create tracker instance taskId = "test-task-id" diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index 26c70b10..14f7d4ce 100644 --- a/src/core/context/context-tracking/FileContextTracker.ts +++ b/src/core/context/context-tracking/FileContextTracker.ts @@ -5,6 +5,8 @@ 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 { getHostBridgeProvider } from "@/hosts/host-providers" +import { getCwd } from "@/utils/path" // 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. @@ -37,8 +39,8 @@ export class FileContextTracker { /** * Gets the current working directory or returns undefined if it cannot be determined */ - private getCwd(): string | undefined { - const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) + private async getCwd(): Promise { + const cwd = await getCwd(undefined) if (!cwd) { console.info("No workspace folder available - cannot determine current working directory") } @@ -54,7 +56,7 @@ export class FileContextTracker { return } - const cwd = this.getCwd() + const cwd = await this.getCwd() if (!cwd) { return } @@ -85,7 +87,7 @@ export class FileContextTracker { */ async trackFileContext(filePath: string, operation: "read_tool" | "user_edited" | "cline_edited" | "file_mentioned") { try { - const cwd = this.getCwd() + const cwd = await this.getCwd() if (!cwd) { return } diff --git a/src/core/controller/file/searchCommits.ts b/src/core/controller/file/searchCommits.ts index 772be381..7665f292 100644 --- a/src/core/controller/file/searchCommits.ts +++ b/src/core/controller/file/searchCommits.ts @@ -13,7 +13,7 @@ import { convertGitCommitsToProtoGitCommits } from "@shared/proto-conversions/fi * @returns GitCommits containing the matching commits */ export const searchCommits: FileMethodHandler = async (controller: Controller, request: StringRequest): Promise => { - const cwd = getWorkspacePath() + const cwd = await getWorkspacePath() if (!cwd) { return GitCommits.create({ commits: [] }) } diff --git a/src/core/controller/file/searchFiles.ts b/src/core/controller/file/searchFiles.ts index f68fb254..fe482e24 100644 --- a/src/core/controller/file/searchFiles.ts +++ b/src/core/controller/file/searchFiles.ts @@ -12,10 +12,10 @@ import { convertSearchResultsToProtoFileInfos } from "@shared/proto-conversions/ * @returns Results containing matching files/folders */ export const searchFiles: FileMethodHandler = async ( - controller: Controller, + _controller: Controller, request: FileSearchRequest, ): Promise => { - const workspacePath = getWorkspacePath() + const workspacePath = await getWorkspacePath() if (!workspacePath) { // Handle case where workspace path is not available diff --git a/src/core/controller/grpc-service.ts b/src/core/controller/grpc-service.ts index 23cb54ba..aa9d4a33 100644 --- a/src/core/controller/grpc-service.ts +++ b/src/core/controller/grpc-service.ts @@ -37,6 +37,7 @@ export class ServiceRegistry { * @param serviceName The name of the service (used for logging) */ constructor(serviceName: string) { + console.log(`Registering Protobus service: ${serviceName}...`) this.serviceName = serviceName } @@ -56,7 +57,6 @@ export class ServiceRegistry { } this.methodMetadata[methodName] = { isStreaming, ...metadata } - console.log(`Registered ${this.serviceName} method: ${methodName}${isStreaming ? " (streaming)" : ""}`) } /** diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index efd25b0b..688c818b 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -46,6 +46,9 @@ import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceC import { sendRelinquishControlEvent } from "./ui/subscribeToRelinquishControl" import { handleTaskServiceRequest } from "./task" import { BooleanRequest } from "@shared/proto/common" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { GetWorkspacePathsRequest } from "@/shared/proto/index.host" +import { getCwd } from "@/utils/path" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts @@ -683,8 +686,8 @@ export class Controller { // Context menus and code actions - getFileMentionFromPath(filePath: string) { - const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) + async getFileMentionFromPath(filePath: string) { + const cwd = await getCwd() if (!cwd) { return "@/" + filePath } @@ -988,7 +991,7 @@ export class Controller { async generateGitCommitMessage() { try { // Check if there's a workspace folder open - const cwd = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath + const cwd = await getCwd() if (!cwd) { vscode.window.showErrorMessage("No workspace folder open") return diff --git a/src/core/controller/task/getTaskHistory.ts b/src/core/controller/task/getTaskHistory.ts index a9c73433..90c0d659 100644 --- a/src/core/controller/task/getTaskHistory.ts +++ b/src/core/controller/task/getTaskHistory.ts @@ -15,7 +15,7 @@ export async function getTaskHistory(controller: Controller, request: GetTaskHis // Get task history from global state const taskHistory = ((await getGlobalState(controller.context, "taskHistory")) as any[]) || [] - const workspacePath = getWorkspacePath() + const workspacePath = await getWorkspacePath() // Apply filters let filteredTasks = taskHistory.filter((item) => { diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 6507b39e..777b7e10 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -574,7 +574,7 @@ export class ToolExecutor { tool: fileExists ? "editedExistingFile" : "newFileCreated", path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relPath)), content: diff || content, - operationIsLocatedInWorkspace: isLocatedInWorkspace(relPath), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), } if (block.partial) { @@ -645,7 +645,7 @@ export class ToolExecutor { const completeMessage = JSON.stringify({ ...sharedMessageProps, content: diff || content, - operationIsLocatedInWorkspace: isLocatedInWorkspace(relPath), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), // ? formatResponse.createPrettyPatch( // relPath, // this.diffViewProvider.originalContent, @@ -788,7 +788,7 @@ export class ToolExecutor { const partialMessage = JSON.stringify({ ...sharedMessageProps, content: undefined, - operationIsLocatedInWorkspace: isLocatedInWorkspace(relPath), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -819,7 +819,7 @@ export class ToolExecutor { const completeMessage = JSON.stringify({ ...sharedMessageProps, content: absolutePath, - operationIsLocatedInWorkspace: isLocatedInWorkspace(relPath), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -870,7 +870,7 @@ export class ToolExecutor { const partialMessage = JSON.stringify({ ...sharedMessageProps, content: "", - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -902,7 +902,7 @@ export class ToolExecutor { const completeMessage = JSON.stringify({ ...sharedMessageProps, content: result, - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -945,7 +945,7 @@ export class ToolExecutor { const partialMessage = JSON.stringify({ ...sharedMessageProps, content: "", - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -974,7 +974,7 @@ export class ToolExecutor { const completeMessage = JSON.stringify({ ...sharedMessageProps, content: result, - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -1021,7 +1021,7 @@ export class ToolExecutor { const partialMessage = JSON.stringify({ ...sharedMessageProps, content: "", - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") @@ -1058,7 +1058,7 @@ export class ToolExecutor { const completeMessage = JSON.stringify({ ...sharedMessageProps, content: results, - operationIsLocatedInWorkspace: isLocatedInWorkspace(block.params.path), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") diff --git a/src/integrations/workspace/WorkspaceTracker.ts b/src/integrations/workspace/WorkspaceTracker.ts index c64ce321..7a589dbc 100644 --- a/src/integrations/workspace/WorkspaceTracker.ts +++ b/src/integrations/workspace/WorkspaceTracker.ts @@ -2,13 +2,22 @@ import * as vscode from "vscode" import * as path from "path" import { listFiles } from "@services/glob/list-files" import { sendWorkspaceUpdateEvent } from "@core/controller/file/subscribeToWorkspaceUpdates" - -const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) +import { getCwd } from "@/utils/path" // Note: this is not a drop-in replacement for listFiles at the start of tasks, since that will be done for Desktops when there is no workspace selected class WorkspaceTracker { private disposables: vscode.Disposable[] = [] private filePaths: Set = new Set() + private cwd: string = "" + + constructor() { + this.initializeCwd() + this.registerListeners() + } + + private async initializeCwd() { + this.cwd = await getCwd() + } private get activeFiles() { return new Set( @@ -18,16 +27,12 @@ class WorkspaceTracker { ) } - constructor() { - this.registerListeners() - } - async populateFilePaths() { // should not auto get filepaths for desktop since it would immediately show permission popup before cline ever creates a file - if (!cwd) { + if (!this.cwd) { return } - const [files, _] = await listFiles(cwd, true, 1_000) + const [files, _] = await listFiles(this.cwd, true, 1_000) files.forEach((file) => this.filePaths.add(this.normalizeFilePath(file))) this.workspaceDidUpdate() } @@ -91,18 +96,18 @@ class WorkspaceTracker { } private async workspaceDidUpdate() { - if (!cwd) { + if (!this.cwd) { return } const filePaths = Array.from(new Set([...this.activeFiles, ...this.filePaths])).map((file) => { - const relativePath = path.relative(cwd, file).toPosix() + const relativePath = path.relative(this.cwd, file).toPosix() return file.endsWith("/") ? relativePath + "/" : relativePath }) await sendWorkspaceUpdateEvent(filePaths) } private normalizeFilePath(filePath: string): string { - const resolvedPath = cwd ? path.resolve(cwd, filePath) : path.resolve(filePath) + const resolvedPath = this.cwd ? path.resolve(this.cwd, filePath) : path.resolve(filePath) return filePath.endsWith("/") ? resolvedPath + "/" : resolvedPath } diff --git a/src/utils/path.ts b/src/utils/path.ts index 4a1aee4c..fd1f85e7 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -1,6 +1,7 @@ import * as path from "path" import os from "os" import * as vscode from "vscode" +import { getHostBridgeProvider } from "@/hosts/host-providers" /* The Node.js 'path' module resolves and normalizes paths differently depending on the platform: @@ -101,9 +102,17 @@ export function getReadablePath(cwd: string, relPath?: string): string { } } -export const getWorkspacePath = (defaultCwdPath = "") => { - const cwdPath = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || defaultCwdPath +// Returns the path of the first workspace directory, or the defaultCwdPath if there is no workspace open. +export const getCwd = async (defaultCwdPath = ""): Promise => { + const workspaceFolders = await getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) + return workspaceFolders.paths.shift() || defaultCwdPath +} + +// Returns the workspace path of the file in the current editor. +// If there is no path, it returns the top level workspace directory. +export const getWorkspacePath = async (defaultCwdPath = "") => { const currentFileUri = vscode.window.activeTextEditor?.document.uri + const cwdPath = await getCwd(defaultCwdPath) if (currentFileUri) { const workspaceFolder = vscode.workspace.getWorkspaceFolder(currentFileUri) return workspaceFolder?.uri.fsPath || cwdPath @@ -111,8 +120,8 @@ export const getWorkspacePath = (defaultCwdPath = "") => { return cwdPath } -export const isLocatedInWorkspace = (pathToCheck: string = ""): boolean => { - const workspacePath = getWorkspacePath() +export const isLocatedInWorkspace = async (pathToCheck: string = ""): Promise => { + const workspacePath = await getWorkspacePath() // Handle long paths in Windows if (pathToCheck.startsWith("\\\\?\\") || workspacePath.startsWith("\\\\?\\")) { diff --git a/test-setup.js b/test-setup.js index a096b737..bdeab16d 100644 --- a/test-setup.js +++ b/test-setup.js @@ -16,7 +16,7 @@ const tsConfig = JSON.parse(fs.readFileSync(path.join(baseUrl, "tsconfig.json"), const outPaths = {} Object.keys(tsConfig.compilerOptions.paths).forEach((key) => { const value = tsConfig.compilerOptions.paths[key] - outPaths[key] = value.map((path) => path.replace("src", "out")) + outPaths[key] = value.map((path) => path.replace("src", "out/src")) }) tsConfigPaths.register({ diff --git a/tsconfig.test.json b/tsconfig.test.json index 4699ca7e..fef4465b 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -11,7 +11,7 @@ "types": ["node", "mocha", "should", "vscode", "chai"], "typeRoots": ["./node_modules/@types", "./src/test/types"], "outDir": "out", - "rootDir": "src" + "rootDir": "." }, "include": ["src/**/*.test.ts"], "exclude": ["src/test/**/*.js", "src/**/__tests__/*"] From 12fbc48629dbed05109d3d735447bace8eee6a8f Mon Sep 17 00:00:00 2001 From: xiongxiong Date: Sat, 28 Jun 2025 04:44:54 +0700 Subject: [PATCH 26/60] feat. support anthropic--claude-4-sonnet in SAP AI Core provider (#4448) --- .changeset/sharp-singers-tie.md | 5 +++++ src/api/providers/sapaicore.ts | 5 +++-- src/shared/api.ts | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 .changeset/sharp-singers-tie.md diff --git a/.changeset/sharp-singers-tie.md b/.changeset/sharp-singers-tie.md new file mode 100644 index 00000000..f22544e2 --- /dev/null +++ b/.changeset/sharp-singers-tie.md @@ -0,0 +1,5 @@ +--- +"claude-dev": minor +--- + +Support Sonnet-4 in SAP AI Core provider diff --git a/src/api/providers/sapaicore.ts b/src/api/providers/sapaicore.ts index e5bcbbac..4101ff0b 100644 --- a/src/api/providers/sapaicore.ts +++ b/src/api/providers/sapaicore.ts @@ -122,6 +122,7 @@ export class SapAiCoreHandler implements ApiHandler { const deploymentId = await this.getDeploymentForModel(model.id) const anthropicModels = [ + "anthropic--claude-4-sonnet", "anthropic--claude-3.7-sonnet", "anthropic--claude-3.5-sonnet", "anthropic--claude-3-sonnet", @@ -136,7 +137,7 @@ export class SapAiCoreHandler implements ApiHandler { if (anthropicModels.includes(model.id)) { url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/invoke-with-response-stream` - if (model.id === "anthropic--claude-3.7-sonnet") { + if (model.id === "anthropic--claude-3.7-sonnet" || model.id === "anthropic--claude-4-sonnet") { url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/converse-stream` payload = { inferenceConfig: { @@ -221,7 +222,7 @@ export class SapAiCoreHandler implements ApiHandler { } } else if (openAIModels.includes(model.id)) { yield* this.streamCompletionGPT(response.data, model) - } else if (model.id === "anthropic--claude-3.7-sonnet") { + } else if (model.id === "anthropic--claude-3.7-sonnet" || model.id === "anthropic--claude-4-sonnet") { yield* this.streamCompletionSonnet37(response.data, model) } else { yield* this.streamCompletion(response.data, model) diff --git a/src/shared/api.ts b/src/shared/api.ts index fcf856a9..8efb13c9 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -2509,6 +2509,14 @@ export const requestyDefaultModelInfo: ModelInfo = { export type SapAiCoreModelId = keyof typeof sapAiCoreModels export const sapAiCoreDefaultModelId: SapAiCoreModelId = "anthropic--claude-3.5-sonnet" export const sapAiCoreModels = { + "anthropic--claude-4-sonnet": { + maxTokens: 8192, + contextWindow: 200_000, + supportsImages: true, + supportsPromptCache: false, + inputPrice: 3.0, + outputPrice: 15.0, + }, "anthropic--claude-3.7-sonnet": { maxTokens: 64_000, contextWindow: 200_000, From b9d3814355a08e6734871dfc8a65e70c6c75177a Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 27 Jun 2025 15:14:12 -0700 Subject: [PATCH 27/60] [SettingsView.tsx] Extract GeneralSettings Section (#4529) * refactor out apiconfig section * add general settings section * duplicate import * add missing type --- .../src/components/settings/SettingsView.tsx | 53 ++++-------------- .../sections/ApiConfigurationSection.tsx | 3 +- .../sections/GeneralSettingsSection.tsx | 56 +++++++++++++++++++ 3 files changed, 67 insertions(+), 45 deletions(-) create mode 100644 webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index b559ea1d..0ffeabbd 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -3,25 +3,22 @@ import HeroTooltip from "@/components/common/HeroTooltip" import { useExtensionState } from "@/context/ExtensionStateContext" import { StateServiceClient } from "@/services/grpc-client" import { validateApiConfiguration, validateModelId } from "@/utils/validate" -import { vscode } from "@/utils/vscode" import { ExtensionMessage } from "@shared/ExtensionMessage" -import { EmptyRequest, StringRequest } from "@shared/proto/common" +import { StringRequest } from "@shared/proto/common" import { PlanActMode, ResetStateRequest, TogglePlanActModeRequest, UpdateSettingsRequest } from "@shared/proto/state" -import { VSCodeButton, VSCodeCheckbox, VSCodeLink, VSCodeTextArea } from "@vscode/webview-ui-toolkit/react" +import { VSCodeButton, VSCodeLink } 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" import { useEvent } from "react-use" import { Tab, TabContent, TabHeader, TabList, TabTrigger } from "../common/Tab" -import { TabButton } from "../mcp/configuration/McpConfigurationView" -import ApiOptions from "./ApiOptions" import BrowserSettingsSection from "./BrowserSettingsSection" import { BrowserSettings } from "@shared/BrowserSettings" import FeatureSettingsSection from "./FeatureSettingsSection" -import PreferredLanguageSetting from "./PreferredLanguageSetting" // Added import import Section from "./Section" import SectionHeader from "./SectionHeader" import TerminalSettingsSection from "./TerminalSettingsSection" import ApiConfigurationSection from "./sections/ApiConfigurationSection" +import GeneralSettingsSection from "./sections/GeneralSettingsSection" import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" const IS_DEV = process.env.IS_DEV @@ -776,43 +773,13 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { {/* General Settings Tab */} {activeTab === "general" && ( -
- {renderSectionHeader("general")} -
- {chatSettings && ( - - )} - -
- { - const checked = e.target.checked === true - setTelemetrySetting(checked ? "enabled" : "disabled") - }}> - Allow anonymous error and usage reporting - -

- Help improve Cline by sending anonymous usage data and error reports. No code, - prompts, or personal information are ever sent. See our{" "} - - telemetry overview - {" "} - and{" "} - - privacy policy - {" "} - for more details. -

-
-
-
+ )} {/* Feature Settings Tab */} diff --git a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx index 77c53f63..7b108c8e 100644 --- a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx +++ b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx @@ -1,5 +1,4 @@ import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" -import { memo } from "react" import { TabButton } from "../../mcp/configuration/McpConfigurationView" import ApiOptions from "../ApiOptions" import Section from "../Section" @@ -96,4 +95,4 @@ const ApiConfigurationSection = ({ ) } -export default memo(ApiConfigurationSection) +export default ApiConfigurationSection diff --git a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx new file mode 100644 index 00000000..61fd6de6 --- /dev/null +++ b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx @@ -0,0 +1,56 @@ +import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { ChatSettings } from "@shared/ChatSettings" +import { TelemetrySetting } from "@shared/TelemetrySetting" +import PreferredLanguageSetting from "../PreferredLanguageSetting" +import Section from "../Section" + +interface GeneralSettingsSectionProps { + chatSettings: ChatSettings + setChatSettings: (settings: ChatSettings) => void + telemetrySetting: TelemetrySetting + setTelemetrySetting: (value: TelemetrySetting) => void + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +const GeneralSettingsSection = ({ + chatSettings, + setChatSettings, + telemetrySetting, + setTelemetrySetting, + renderSectionHeader, +}: GeneralSettingsSectionProps) => { + return ( +
+ {renderSectionHeader("general")} +
+ {chatSettings && } + +
+ { + const checked = e.target.checked === true + setTelemetrySetting(checked ? "enabled" : "disabled") + }}> + Allow anonymous error and usage reporting + +

+ Help improve Cline by sending anonymous usage data and error reports. No code, prompts, or personal + information are ever sent. See our{" "} + + telemetry overview + {" "} + and{" "} + + privacy policy + {" "} + for more details. +

+
+
+
+ ) +} + +export default GeneralSettingsSection From 3d100d835a6725b3634dd856142865c27b2a2555 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 27 Jun 2025 15:44:31 -0700 Subject: [PATCH 28/60] [SettingsView.tsx] Extract Browser, Terminal, and Feature Sections (#4533) * refactor out apiconfig section * add general settings section * duplicate import * move terminal, browser, and feature settings * move files to sections folder --- .../settings/FeatureSettingsSection.tsx | 104 ------ .../src/components/settings/SettingsView.tsx | 39 +-- .../settings/TerminalSettingsSection.tsx | 142 -------- .../{ => sections}/BrowserSettingsSection.tsx | 320 ++++++++++-------- .../sections/FeatureSettingsSection.tsx | 114 +++++++ .../sections/GeneralSettingsSection.tsx | 2 +- .../sections/TerminalSettingsSection.tsx | 156 +++++++++ 7 files changed, 455 insertions(+), 422 deletions(-) delete mode 100644 webview-ui/src/components/settings/FeatureSettingsSection.tsx delete mode 100644 webview-ui/src/components/settings/TerminalSettingsSection.tsx rename webview-ui/src/components/settings/{ => sections}/BrowserSettingsSection.tsx (61%) create mode 100644 webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx create mode 100644 webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx diff --git a/webview-ui/src/components/settings/FeatureSettingsSection.tsx b/webview-ui/src/components/settings/FeatureSettingsSection.tsx deleted file mode 100644 index e4996683..00000000 --- a/webview-ui/src/components/settings/FeatureSettingsSection.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { memo } from "react" -import { OpenAIReasoningEffort } from "@shared/ChatSettings" - -const FeatureSettingsSection = () => { - const { - enableCheckpointsSetting, - setEnableCheckpointsSetting, - mcpMarketplaceEnabled, - setMcpMarketplaceEnabled, - mcpRichDisplayEnabled, - setMcpRichDisplayEnabled, - mcpResponsesCollapsed, - setMcpResponsesCollapsed, - chatSettings, - setChatSettings, - } = useExtensionState() - - return ( -
-
- { - const checked = e.target.checked === true - setEnableCheckpointsSetting(checked) - }}> - Enable Checkpoints - -

- Enables extension to save checkpoints of workspace throughout the task. Uses git under the hood which may not - work well with large workspaces. -

-
-
- { - const checked = e.target.checked === true - setMcpMarketplaceEnabled(checked) - }}> - Enable MCP Marketplace - -

- Enables the MCP Marketplace tab for discovering and installing MCP servers. -

-
-
- { - const checked = e.target.checked === true - setMcpRichDisplayEnabled(checked) - }}> - Enable Rich MCP Display - -

- Enables rich formatting for MCP responses. When disabled, responses will be shown in plain text. -

-
-
- { - const checked = e.target.checked === true - setMcpResponsesCollapsed(checked) - }}> - Collapse MCP Responses - -

- Sets the default display mode for MCP response panels -

-
-
- - { - const newValue = e.target.currentValue as OpenAIReasoningEffort - setChatSettings({ - ...chatSettings, - openAIReasoningEffort: newValue, - }) - }} - className="w-full"> - Low - Medium - High - -

- Reasoning effort for the OpenAI family of models(applies to all OpenAI model providers) -

-
-
- ) -} - -export default memo(FeatureSettingsSection) diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 0ffeabbd..39bcf685 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -11,16 +11,17 @@ import { CheckCheck, FlaskConical, Info, LucideIcon, Settings, SquareMousePointe import { memo, useCallback, useEffect, useRef, useState } from "react" import { useEvent } from "react-use" import { Tab, TabContent, TabHeader, TabList, TabTrigger } from "../common/Tab" -import BrowserSettingsSection from "./BrowserSettingsSection" import { BrowserSettings } from "@shared/BrowserSettings" -import FeatureSettingsSection from "./FeatureSettingsSection" +import FeatureSettingsSection from "./sections/FeatureSettingsSection" import Section from "./Section" import SectionHeader from "./SectionHeader" -import TerminalSettingsSection from "./TerminalSettingsSection" +import TerminalSettingsSection from "./sections/TerminalSettingsSection" import ApiConfigurationSection from "./sections/ApiConfigurationSection" import GeneralSettingsSection from "./sections/GeneralSettingsSection" +import BrowserSettingsSection from "./sections/BrowserSettingsSection" import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" + const IS_DEV = process.env.IS_DEV // Styles for the tab system @@ -783,37 +784,19 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { )} {/* Feature Settings Tab */} - {activeTab === "features" && ( -
- {renderSectionHeader("features")} -
- -
-
- )} + {activeTab === "features" && } {/* Browser Settings Tab */} {activeTab === "browser" && ( -
- {renderSectionHeader("browser")} -
- -
-
+ )} {/* Terminal Settings Tab */} - {activeTab === "terminal" && ( -
- {renderSectionHeader("terminal")} -
- -
-
- )} + {activeTab === "terminal" && } {/* Debug Tab (only in dev mode) */} {IS_DEV && activeTab === "debug" && ( diff --git a/webview-ui/src/components/settings/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/TerminalSettingsSection.tsx deleted file mode 100644 index 2faa3825..00000000 --- a/webview-ui/src/components/settings/TerminalSettingsSection.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import React, { useState, useEffect } from "react" -import { VSCodeTextField, VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" -import { useExtensionState } from "@/context/ExtensionStateContext" -import TerminalOutputLineLimitSlider from "./TerminalOutputLineLimitSlider" -import { StateServiceClient } from "../../services/grpc-client" -import { Int64, Int64Request } from "@shared/proto/common" - -export const TerminalSettingsSection: React.FC = () => { - const { - shellIntegrationTimeout, - setShellIntegrationTimeout, - terminalReuseEnabled, - setTerminalReuseEnabled, - defaultTerminalProfile, - setDefaultTerminalProfile, - availableTerminalProfiles, - platform, - } = useExtensionState() - - const [inputValue, setInputValue] = useState((shellIntegrationTimeout / 1000).toString()) - const [inputError, setInputError] = useState(null) - - const handleTimeoutChange = (event: Event) => { - const target = event.target as HTMLInputElement - const value = target.value - - setInputValue(value) - - const seconds = parseFloat(value) - if (isNaN(seconds) || seconds <= 0) { - setInputError("Please enter a positive number") - return - } - - setInputError(null) - const timeout = Math.round(seconds * 1000) - - setShellIntegrationTimeout(timeout) - - StateServiceClient.updateTerminalConnectionTimeout({ - value: timeout, - } as Int64Request) - .then((response: Int64) => { - setShellIntegrationTimeout(response.value) - setInputValue((response.value / 1000).toString()) - }) - .catch((error) => { - console.error("Failed to update terminal connection timeout:", error) - }) - } - - const handleInputBlur = () => { - if (inputError) { - setInputValue((shellIntegrationTimeout / 1000).toString()) - setInputError(null) - } - } - - const handleTerminalReuseChange = (event: Event) => { - const target = event.target as HTMLInputElement - const checked = target.checked - setTerminalReuseEnabled(checked) - StateServiceClient.updateTerminalReuseEnabled({ value: checked } as any).catch((error) => { - console.error("Failed to update terminal reuse enabled:", error) - }) - } - - // Use any to avoid type conflicts between Event and FormEvent - const handleDefaultTerminalProfileChange = (event: any) => { - const target = event.target as HTMLSelectElement - const profileId = target.value - // Only update the local state, let the Save button handle the backend update - setDefaultTerminalProfile(profileId) - } - - const profilesToShow = availableTerminalProfiles - - return ( -
-
- - - {profilesToShow.map((profile) => ( - - {profile.name} - - ))} - -

- Select the default terminal Cline will use. 'Default' uses your VSCode global setting. -

-
- -
-
- -
- handleTimeoutChange(event as Event)} - onBlur={handleInputBlur} - /> -
- {inputError && ( -
{inputError}
- )} -
-

- Set how long Cline waits for shell integration to activate before executing commands. Increase this value if - you experience terminal connection timeouts. -

-
- -
-
- handleTerminalReuseChange(event as Event)}> - Enable aggressive terminal reuse - -
-

- When enabled, Cline will reuse existing terminal windows that aren't in the current working directory. Disable - this if you experience issues with task lockout after a terminal command. -

-
- -
- ) -} - -export default TerminalSettingsSection diff --git a/webview-ui/src/components/settings/BrowserSettingsSection.tsx b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx similarity index 61% rename from webview-ui/src/components/settings/BrowserSettingsSection.tsx rename to webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx index 2792d20b..8dae8000 100644 --- a/webview-ui/src/components/settings/BrowserSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx @@ -2,15 +2,17 @@ import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextF import debounce from "debounce" import React, { useCallback, useEffect, useState } from "react" import styled from "styled-components" -import { BROWSER_VIEWPORT_PRESETS } from "../../../../src/shared/BrowserSettings" -import { useExtensionState } from "../../context/ExtensionStateContext" -import { BrowserServiceClient } from "../../services/grpc-client" +import { BROWSER_VIEWPORT_PRESETS } from "../../../../../src/shared/BrowserSettings" +import { useExtensionState } from "../../../context/ExtensionStateContext" +import { BrowserServiceClient } from "../../../services/grpc-client" import { EmptyRequest, StringRequest } from "@shared/proto/common" import { BrowserSettings } from "@shared/BrowserSettings" +import Section from "../Section" interface BrowserSettingsSectionProps { localBrowserSettings: BrowserSettings onBrowserSettingsChange: (settings: BrowserSettings) => void + renderSectionHeader: (tabId: string) => JSX.Element | null } const ConnectionStatusIndicator = ({ @@ -59,6 +61,7 @@ const CollapsibleContent = styled.div<{ isOpen: boolean }>` export const BrowserSettingsSection: React.FC = ({ localBrowserSettings, onBrowserSettingsChange, + renderSectionHeader, }) => { const { browserSettings } = useExtensionState() const [localChromePath, setLocalChromePath] = useState(localBrowserSettings.chromeExecutablePath || "") @@ -275,161 +278,184 @@ export const BrowserSettingsSection: React.FC = ({ const isSubSettingsOpen = !(localBrowserSettings.disableToolUse || false) return ( -
- {/* Master Toggle */} -
- updateDisableToolUse((e.target as HTMLInputElement).checked)}> - Disable browser tool usage - -

- Prevent Cline from using browser actions (e.g. launch, click, type). -

-
- - -
-
- - { - const typedSize = size as { width: number; height: number } - return ( - typedSize.width === localBrowserSettings.viewport.width && - typedSize.height === localBrowserSettings.viewport.height - ) - })?.[0] - } - onChange={(event) => handleViewportChange(event as Event)}> - {Object.entries(BROWSER_VIEWPORT_PRESETS).map(([name]) => ( - - {name} - - ))} - -
-

- Set the size of the browser viewport for screenshots and interactions. -

-
- -
- {" "} - {/* This div now contains Remote Connection & Chrome Path */} -
+
+ {renderSectionHeader("browser")} +
+
+ {/* Master Toggle */} +
updateRemoteBrowserEnabled((e.target as HTMLInputElement).checked)}> - Use remote browser connection + checked={localBrowserSettings.disableToolUse || false} + onChange={(e) => updateDisableToolUse((e.target as HTMLInputElement).checked)}> + Disable browser tool usage - +

+ Prevent Cline from using browser actions (e.g. launch, click, type). +

-

- Enable Cline to use your Chrome - {isBundled ? "(not detected on your machine)" : detectedChromePath ? ` (${detectedChromePath})` : ""}. You - can specify a custom path below. Using a remote browser connection requires starting Chrome in debug mode - {localBrowserSettings.remoteBrowserEnabled ? ( - <> - {" "} - manually (--remote-debugging-port=9222) or using the button below. Enter the host - address or leave it blank for automatic discovery. - - ) : ( - "." - )} -

- {/* Moved remote-specific settings to appear directly after enabling remote connection */} - {localBrowserSettings.remoteBrowserEnabled && ( -
- updateRemoteBrowserHost(e.target.value || undefined)} - /> - - {shouldShowRelaunchButton && ( -
- - {debugMode ? "Launching Browser..." : "Launch Browser with Debug Mode"} - -
- )} - - {relaunchResult && ( -
- {relaunchResult.message} -
- )} + +
+
+ + { + const typedSize = size as { width: number; height: number } + return ( + typedSize.width === localBrowserSettings.viewport.width && + typedSize.height === localBrowserSettings.viewport.height + ) + })?.[0] + } + onChange={(event) => handleViewportChange(event as Event)}> + {Object.entries(BROWSER_VIEWPORT_PRESETS).map(([name]) => ( + + {name} + + ))} + +

+ }}> + Set the size of the browser viewport for screenshots and interactions. +

- )} - {/* Chrome Executable Path section now follows remote-specific settings */} -
- - { - const newValue = e.target.value || "" - updateChromeExecutablePath(newValue) - }} - /> -

- Leave blank to auto-detect. -

-
+ +
+ {" "} + {/* This div now contains Remote Connection & Chrome Path */} +
+ updateRemoteBrowserEnabled((e.target as HTMLInputElement).checked)}> + Use remote browser connection + + +
+

+ Enable Cline to use your Chrome + {isBundled + ? "(not detected on your machine)" + : detectedChromePath + ? ` (${detectedChromePath})` + : ""} + . You can specify a custom path below. Using a remote browser connection requires starting Chrome + in debug mode + {localBrowserSettings.remoteBrowserEnabled ? ( + <> + {" "} + manually (--remote-debugging-port=9222) or using the button below. Enter the + host address or leave it blank for automatic discovery. + + ) : ( + "." + )} +

+ {/* Moved remote-specific settings to appear directly after enabling remote connection */} + {localBrowserSettings.remoteBrowserEnabled && ( +
+ updateRemoteBrowserHost(e.target.value || undefined)} + /> + + {shouldShowRelaunchButton && ( +
+ + {debugMode ? "Launching Browser..." : "Launch Browser with Debug Mode"} + +
+ )} + + {relaunchResult && ( +
+ {relaunchResult.message} +
+ )} + +

+
+ )} + {/* Chrome Executable Path section now follows remote-specific settings */} +
+ + { + const newValue = e.target.value || "" + updateChromeExecutablePath(newValue) + }} + /> +

+ Leave blank to auto-detect. +

+
+
+
- +
) } diff --git a/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx new file mode 100644 index 00000000..c5a80242 --- /dev/null +++ b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx @@ -0,0 +1,114 @@ +import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { memo } from "react" +import { OpenAIReasoningEffort } from "@shared/ChatSettings" +import Section from "../Section" + +interface FeatureSettingsSectionProps { + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionProps) => { + const { + enableCheckpointsSetting, + setEnableCheckpointsSetting, + mcpMarketplaceEnabled, + setMcpMarketplaceEnabled, + mcpRichDisplayEnabled, + setMcpRichDisplayEnabled, + mcpResponsesCollapsed, + setMcpResponsesCollapsed, + chatSettings, + setChatSettings, + } = useExtensionState() + + return ( +
+ {renderSectionHeader("features")} +
+
+
+ { + const checked = e.target.checked === true + setEnableCheckpointsSetting(checked) + }}> + Enable Checkpoints + +

+ Enables extension to save checkpoints of workspace throughout the task. Uses git under the hood which + may not work well with large workspaces. +

+
+
+ { + const checked = e.target.checked === true + setMcpMarketplaceEnabled(checked) + }}> + Enable MCP Marketplace + +

+ Enables the MCP Marketplace tab for discovering and installing MCP servers. +

+
+
+ { + const checked = e.target.checked === true + setMcpRichDisplayEnabled(checked) + }}> + Enable Rich MCP Display + +

+ Enables rich formatting for MCP responses. When disabled, responses will be shown in plain text. +

+
+
+ { + const checked = e.target.checked === true + setMcpResponsesCollapsed(checked) + }}> + Collapse MCP Responses + +

+ Sets the default display mode for MCP response panels +

+
+
+ + { + const newValue = e.target.currentValue as OpenAIReasoningEffort + setChatSettings({ + ...chatSettings, + openAIReasoningEffort: newValue, + }) + }} + className="w-full"> + Low + Medium + High + +

+ Reasoning effort for the OpenAI family of models(applies to all OpenAI model providers) +

+
+
+
+
+ ) +} + +export default memo(FeatureSettingsSection) diff --git a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx index 61fd6de6..bd8c90f5 100644 --- a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx @@ -7,7 +7,7 @@ import Section from "../Section" interface GeneralSettingsSectionProps { chatSettings: ChatSettings setChatSettings: (settings: ChatSettings) => void - telemetrySetting: TelemetrySetting + telemetrySetting: string setTelemetrySetting: (value: TelemetrySetting) => void renderSectionHeader: (tabId: string) => JSX.Element | null } diff --git a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx new file mode 100644 index 00000000..7d1878d1 --- /dev/null +++ b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx @@ -0,0 +1,156 @@ +import React, { useState, useEffect } from "react" +import { VSCodeTextField, VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import TerminalOutputLineLimitSlider from "../TerminalOutputLineLimitSlider" +import { StateServiceClient } from "../../../services/grpc-client" +import { Int64, Int64Request } from "@shared/proto/common" +import Section from "../Section" + +interface TerminalSettingsSectionProps { + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +export const TerminalSettingsSection: React.FC = ({ renderSectionHeader }) => { + const { + shellIntegrationTimeout, + setShellIntegrationTimeout, + terminalReuseEnabled, + setTerminalReuseEnabled, + defaultTerminalProfile, + setDefaultTerminalProfile, + availableTerminalProfiles, + platform, + } = useExtensionState() + + const [inputValue, setInputValue] = useState((shellIntegrationTimeout / 1000).toString()) + const [inputError, setInputError] = useState(null) + + const handleTimeoutChange = (event: Event) => { + const target = event.target as HTMLInputElement + const value = target.value + + setInputValue(value) + + const seconds = parseFloat(value) + if (isNaN(seconds) || seconds <= 0) { + setInputError("Please enter a positive number") + return + } + + setInputError(null) + const timeout = Math.round(seconds * 1000) + + setShellIntegrationTimeout(timeout) + + StateServiceClient.updateTerminalConnectionTimeout({ + value: timeout, + } as Int64Request) + .then((response: Int64) => { + setShellIntegrationTimeout(response.value) + setInputValue((response.value / 1000).toString()) + }) + .catch((error) => { + console.error("Failed to update terminal connection timeout:", error) + }) + } + + const handleInputBlur = () => { + if (inputError) { + setInputValue((shellIntegrationTimeout / 1000).toString()) + setInputError(null) + } + } + + const handleTerminalReuseChange = (event: Event) => { + const target = event.target as HTMLInputElement + const checked = target.checked + setTerminalReuseEnabled(checked) + StateServiceClient.updateTerminalReuseEnabled({ value: checked } as any).catch((error) => { + console.error("Failed to update terminal reuse enabled:", error) + }) + } + + // Use any to avoid type conflicts between Event and FormEvent + const handleDefaultTerminalProfileChange = (event: any) => { + const target = event.target as HTMLSelectElement + const profileId = target.value + // Only update the local state, let the Save button handle the backend update + setDefaultTerminalProfile(profileId) + } + + const profilesToShow = availableTerminalProfiles + + return ( +
+ {renderSectionHeader("terminal")} +
+
+
+ + + {profilesToShow.map((profile) => ( + + {profile.name} + + ))} + +

+ Select the default terminal Cline will use. 'Default' uses your VSCode global setting. +

+
+ +
+
+ +
+ handleTimeoutChange(event as Event)} + onBlur={handleInputBlur} + /> +
+ {inputError && ( +
+ {inputError} +
+ )} +
+

+ Set how long Cline waits for shell integration to activate before executing commands. Increase this + value if you experience terminal connection timeouts. +

+
+ +
+
+ handleTerminalReuseChange(event as Event)}> + Enable aggressive terminal reuse + +
+

+ When enabled, Cline will reuse existing terminal windows that aren't in the current working directory. + Disable this if you experience issues with task lockout after a terminal command. +

+
+ +
+
+
+ ) +} + +export default TerminalSettingsSection From e65605535a390d75fc60b2e0191b30acd7755e18 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 27 Jun 2025 16:04:28 -0700 Subject: [PATCH 29/60] [SettingsView.tsx] Extract Debug Section (#4536) * refactor out apiconfig section * add general settings section * duplicate import * move terminal, browser, and feature settings * move files to sections folder * refactor out debug section --- .../src/components/settings/SettingsView.tsx | 22 ++---------- .../settings/sections/DebugSection.tsx | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 20 deletions(-) create mode 100644 webview-ui/src/components/settings/sections/DebugSection.tsx diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 39bcf685..02540f56 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -19,6 +19,7 @@ import TerminalSettingsSection from "./sections/TerminalSettingsSection" import ApiConfigurationSection from "./sections/ApiConfigurationSection" import GeneralSettingsSection from "./sections/GeneralSettingsSection" import BrowserSettingsSection from "./sections/BrowserSettingsSection" +import DebugSection from "./sections/DebugSection" import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" @@ -800,26 +801,7 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { {/* Debug Tab (only in dev mode) */} {IS_DEV && activeTab === "debug" && ( -
- {renderSectionHeader("debug")} -
- handleResetState()} - className="mt-[5px] w-auto" - style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> - Reset Workspace State - - handleResetState(true)} - className="mt-[5px] w-auto" - style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> - Reset Global State - -

- This will reset all global state and secret storage in the extension. -

-
-
+ )} {/* About Tab */} diff --git a/webview-ui/src/components/settings/sections/DebugSection.tsx b/webview-ui/src/components/settings/sections/DebugSection.tsx new file mode 100644 index 00000000..fd8f6e00 --- /dev/null +++ b/webview-ui/src/components/settings/sections/DebugSection.tsx @@ -0,0 +1,34 @@ +import Section from "../Section" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" + +interface DebugSectionProps { + onResetState: (resetGlobalState?: boolean) => Promise + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +const DebugSection = ({ onResetState, renderSectionHeader }: DebugSectionProps) => { + return ( +
+ {renderSectionHeader("debug")} +
+ onResetState()} + className="mt-[5px] w-auto" + style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> + Reset Workspace State + + onResetState(true)} + className="mt-[5px] w-auto" + style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> + Reset Global State + +

+ This will reset all global state and secret storage in the extension. +

+
+
+ ) +} + +export default DebugSection From fe9e5bff74788ac7bb8cc0e6682e0d171a1d50b3 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Sat, 28 Jun 2025 00:27:13 -0700 Subject: [PATCH 30/60] base (#4539) --- webview-ui/src/components/chat/ChatRow.tsx | 2784 ++++++++++--------- webview-ui/src/components/chat/ChatView.tsx | 2 +- 2 files changed, 1409 insertions(+), 1377 deletions(-) diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 3e1e207e..848bb415 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -57,7 +57,7 @@ const ChatRowContainer = styled.div` interface ChatRowProps { message: ClineMessage isExpanded: boolean - onToggleExpand: () => void + onToggleExpand: (ts: number) => void lastModifiedMessage?: ClineMessage isLast: boolean onHeightChange: (isTaller: boolean) => void @@ -105,39 +105,41 @@ const Markdown = memo(({ markdown }: { markdown?: string }) => { ) }) -const RetryMessage = ({ seconds, attempt, retryOperations }: { retryOperations: number; attempt: number; seconds?: number }) => { - const [remainingSeconds, setRemainingSeconds] = useState(seconds || 0) +const RetryMessage = memo( + ({ seconds, attempt, retryOperations }: { retryOperations: number; attempt: number; seconds?: number }) => { + const [remainingSeconds, setRemainingSeconds] = useState(seconds || 0) - useEffect(() => { - if (seconds && seconds > 0) { - setRemainingSeconds(seconds) + useEffect(() => { + if (seconds && seconds > 0) { + setRemainingSeconds(seconds) - const interval = setInterval(() => { - setRemainingSeconds((prev) => { - if (prev <= 1) { - clearInterval(interval) - return 0 - } - return prev - 1 - }) - }, 1000) + const interval = setInterval(() => { + setRemainingSeconds((prev) => { + if (prev <= 1) { + clearInterval(interval) + return 0 + } + return prev - 1 + }) + }, 1000) - return () => clearInterval(interval) - } - }, [seconds]) + return () => clearInterval(interval) + } + }, [seconds]) - return ( - - {`API Request (Retrying failed attempt ${attempt}/${retryOperations}`} - {remainingSeconds > 0 && ` in ${remainingSeconds} seconds`} - )... - - ) -} + return ( + + {`API Request (Retrying failed attempt ${attempt}/${retryOperations}`} + {remainingSeconds > 0 && ` in ${remainingSeconds} seconds`} + )... + + ) + }, +) const ChatRow = memo( (props: ChatRowProps) => { @@ -174,381 +176,530 @@ const ChatRow = memo( export default ChatRow -export const ChatRowContent = ({ - message, - isExpanded, - onToggleExpand, - lastModifiedMessage, - isLast, - inputValue, - sendMessageFromChatRow, - onSetQuote, -}: ChatRowContentProps) => { - const { mcpServers, mcpMarketplaceCatalog, onRelinquishControl, apiConfiguration } = useExtensionState() - const [seeNewChangesDisabled, setSeeNewChangesDisabled] = useState(false) - const [quoteButtonState, setQuoteButtonState] = useState({ - visible: false, - top: 0, - left: 0, - selectedText: "", - }) - const contentRef = useRef(null) - const [cost, apiReqCancelReason, apiReqStreamingFailedMessage, retryStatus] = useMemo(() => { - if (message.text != null && message.say === "api_req_started") { - const info: ClineApiReqInfo = JSON.parse(message.text) - return [info.cost, info.cancelReason, info.streamingFailedMessage, info.retryStatus] - } - return [undefined, undefined, undefined, undefined] - }, [message.text, message.say]) - - // when resuming task last won't be api_req_failed but a resume_task message so api_req_started will show loading spinner. that's why we just remove the last api_req_started that failed without streaming anything - const apiRequestFailedMessage = - isLast && lastModifiedMessage?.ask === "api_req_failed" // if request is retried then the latest message is a api_req_retried - ? lastModifiedMessage?.text - : undefined - - const isCommandExecuting = - isLast && - (lastModifiedMessage?.ask === "command" || lastModifiedMessage?.say === "command") && - lastModifiedMessage?.text?.includes(COMMAND_OUTPUT_STRING) - - const isMcpServerResponding = isLast && lastModifiedMessage?.say === "mcp_server_request_started" - - const type = message.type === "ask" ? message.ask : message.say - - // Use the onRelinquishControl hook instead of message event - useEffect(() => { - return onRelinquishControl(() => { - setSeeNewChangesDisabled(false) +export const ChatRowContent = memo( + ({ + message, + isExpanded, + onToggleExpand, + lastModifiedMessage, + isLast, + inputValue, + sendMessageFromChatRow, + onSetQuote, + }: ChatRowContentProps) => { + const { mcpServers, mcpMarketplaceCatalog, onRelinquishControl, apiConfiguration } = useExtensionState() + const [seeNewChangesDisabled, setSeeNewChangesDisabled] = useState(false) + const [quoteButtonState, setQuoteButtonState] = useState({ + visible: false, + top: 0, + left: 0, + selectedText: "", }) - }, [onRelinquishControl]) + const contentRef = useRef(null) + const [cost, apiReqCancelReason, apiReqStreamingFailedMessage, retryStatus] = useMemo(() => { + if (message.text != null && message.say === "api_req_started") { + const info: ClineApiReqInfo = JSON.parse(message.text) + return [info.cost, info.cancelReason, info.streamingFailedMessage, info.retryStatus] + } + return [undefined, undefined, undefined, undefined] + }, [message.text, message.say]) - // --- Quote Button Logic --- - // MOVE handleQuoteClick INSIDE ChatRowContent - const handleQuoteClick = useCallback(() => { - onSetQuote(quoteButtonState.selectedText) - window.getSelection()?.removeAllRanges() // Clear the browser selection - setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) - }, [onSetQuote, quoteButtonState.selectedText]) // <-- Use onSetQuote from props + // when resuming task last won't be api_req_failed but a resume_task message so api_req_started will show loading spinner. that's why we just remove the last api_req_started that failed without streaming anything + const apiRequestFailedMessage = + isLast && lastModifiedMessage?.ask === "api_req_failed" // if request is retried then the latest message is a api_req_retried + ? lastModifiedMessage?.text + : undefined - const handleMouseUp = useCallback((event: MouseEvent) => { - // Get the target element immediately, before the timeout - const targetElement = event.target as Element - const isClickOnButton = !!targetElement.closest(".quote-button-class") + const isCommandExecuting = + isLast && + (lastModifiedMessage?.ask === "command" || lastModifiedMessage?.say === "command") && + lastModifiedMessage?.text?.includes(COMMAND_OUTPUT_STRING) - // Delay the selection check slightly - setTimeout(() => { - // Now, check the selection state *after* the browser has likely updated it - const selection = window.getSelection() - const selectedText = selection?.toString().trim() ?? "" + const isMcpServerResponding = isLast && lastModifiedMessage?.say === "mcp_server_request_started" - let shouldShowButton = false - let buttonTop = 0 - let buttonLeft = 0 - let textToQuote = "" + const type = message.type === "ask" ? message.ask : message.say - // Condition 1: Check if there's a valid, non-collapsed selection within bounds - // Ensure contentRef.current still exists in case component unmounted during timeout - if (selectedText && contentRef.current && selection && selection.rangeCount > 0 && !selection.isCollapsed) { - const range = selection.getRangeAt(0) - const rangeRect = range.getBoundingClientRect() - // Re-check ref inside timeout and ensure containerRect is valid - const containerRect = contentRef.current?.getBoundingClientRect() + const handleToggle = useCallback(() => { + onToggleExpand(message.ts) + }, [onToggleExpand, message.ts]) - if (containerRect) { - // Check if containerRect was successfully obtained - const tolerance = 5 // Allow for a small pixel overflow (e.g., for margins) - const isSelectionWithin = - rangeRect.top >= containerRect.top && - rangeRect.left >= containerRect.left && - rangeRect.bottom <= containerRect.bottom + tolerance && // Added tolerance - rangeRect.right <= containerRect.right + // Use the onRelinquishControl hook instead of message event + useEffect(() => { + return onRelinquishControl(() => { + setSeeNewChangesDisabled(false) + }) + }, [onRelinquishControl]) - if (isSelectionWithin) { - shouldShowButton = true // Mark that we should show the button - const buttonHeight = 30 - // Calculate the raw top position relative to the container, placing it above the selection - const calculatedTop = rangeRect.top - containerRect.top - buttonHeight - 5 // Subtract button height and a small margin - // Allow the button to potentially have a negative top value - buttonTop = calculatedTop - buttonLeft = Math.max(0, rangeRect.left - containerRect.left) // Still prevent going left of container - textToQuote = selectedText + // --- Quote Button Logic --- + // MOVE handleQuoteClick INSIDE ChatRowContent + const handleQuoteClick = useCallback(() => { + onSetQuote(quoteButtonState.selectedText) + window.getSelection()?.removeAllRanges() // Clear the browser selection + setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) + }, [onSetQuote, quoteButtonState.selectedText]) // <-- Use onSetQuote from props + + const handleMouseUp = useCallback((event: MouseEvent) => { + // Get the target element immediately, before the timeout + const targetElement = event.target as Element + const isClickOnButton = !!targetElement.closest(".quote-button-class") + + // Delay the selection check slightly + setTimeout(() => { + // Now, check the selection state *after* the browser has likely updated it + const selection = window.getSelection() + const selectedText = selection?.toString().trim() ?? "" + + let shouldShowButton = false + let buttonTop = 0 + let buttonLeft = 0 + let textToQuote = "" + + // Condition 1: Check if there's a valid, non-collapsed selection within bounds + // Ensure contentRef.current still exists in case component unmounted during timeout + if (selectedText && contentRef.current && selection && selection.rangeCount > 0 && !selection.isCollapsed) { + const range = selection.getRangeAt(0) + const rangeRect = range.getBoundingClientRect() + // Re-check ref inside timeout and ensure containerRect is valid + const containerRect = contentRef.current?.getBoundingClientRect() + + if (containerRect) { + // Check if containerRect was successfully obtained + const tolerance = 5 // Allow for a small pixel overflow (e.g., for margins) + const isSelectionWithin = + rangeRect.top >= containerRect.top && + rangeRect.left >= containerRect.left && + rangeRect.bottom <= containerRect.bottom + tolerance && // Added tolerance + rangeRect.right <= containerRect.right + + if (isSelectionWithin) { + shouldShowButton = true // Mark that we should show the button + const buttonHeight = 30 + // Calculate the raw top position relative to the container, placing it above the selection + const calculatedTop = rangeRect.top - containerRect.top - buttonHeight - 5 // Subtract button height and a small margin + // Allow the button to potentially have a negative top value + buttonTop = calculatedTop + buttonLeft = Math.max(0, rangeRect.left - containerRect.left) // Still prevent going left of container + textToQuote = selectedText + } } } - } - // Decision: Set the state based on whether we should show or hide - if (shouldShowButton) { - // Scenario A: Valid selection exists -> Show button - setQuoteButtonState({ - visible: true, - top: buttonTop, - left: buttonLeft, - selectedText: textToQuote, - }) - } else if (!isClickOnButton) { - // Scenario B: No valid selection AND click was NOT on button -> Hide button - setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) - } - // Scenario C (Click WAS on button): Do nothing here, handleQuoteClick takes over. - }, 0) // Delay of 0ms pushes execution after current event cycle - }, []) // Dependencies remain empty + // Decision: Set the state based on whether we should show or hide + if (shouldShowButton) { + // Scenario A: Valid selection exists -> Show button + setQuoteButtonState({ + visible: true, + top: buttonTop, + left: buttonLeft, + selectedText: textToQuote, + }) + } else if (!isClickOnButton) { + // Scenario B: No valid selection AND click was NOT on button -> Hide button + setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) + } + // Scenario C (Click WAS on button): Do nothing here, handleQuoteClick takes over. + }, 0) // Delay of 0ms pushes execution after current event cycle + }, []) // Dependencies remain empty - const [icon, title] = useMemo(() => { - switch (type) { - case "error": - return [ - , - Error, - ] - case "mistake_limit_reached": - return [ - , - Cline is having trouble..., - ] - case "auto_approval_max_req_reached": - return [ - , - Maximum Requests Reached, - ] - case "command": - return [ - isCommandExecuting ? ( - - ) : ( + const [icon, title] = useMemo(() => { + switch (type) { + case "error": + return [ - ), - Cline wants to execute this command:, - ] - case "use_mcp_server": - const mcpServerUse = JSON.parse(message.text || "{}") as ClineAskUseMcpServer - return [ - isMcpServerResponding ? ( - - ) : ( + }}>, + Error, + ] + case "mistake_limit_reached": + return [ - ), - - Cline wants to {mcpServerUse.type === "use_mcp_tool" ? "use a tool" : "access a resource"} on the{" "} - - {getMcpServerDisplayName(mcpServerUse.serverName, mcpMarketplaceCatalog)} - {" "} - MCP server: - , - ] - case "completion_result": - return [ - , - Task Completed, - ] - case "api_req_started": - const getIconSpan = (iconName: string, color: string) => ( -
+ }}>, + Cline is having trouble..., + ] + case "auto_approval_max_req_reached": + return [ -
- ) - return [ - apiReqCancelReason != null ? ( - apiReqCancelReason === "user_cancelled" ? ( - getIconSpan("error", cancelledColor) + }}>, + Maximum Requests Reached, + ] + case "command": + return [ + isCommandExecuting ? ( + ) : ( - getIconSpan("error", errorColor) - ) - ) : cost != null ? ( - getIconSpan("check", successColor) - ) : apiRequestFailedMessage ? ( - getIconSpan("error", errorColor) - ) : ( - - ), - (() => { - if (apiReqCancelReason != null) { - return apiReqCancelReason === "user_cancelled" ? ( - API Request Cancelled - ) : ( - API Streaming Failed - ) - } - - if (cost != null) { - return API Request - } - - if (apiRequestFailedMessage) { - return API Request Failed - } - // New: Check for retryStatus to modify the title - if (retryStatus && cost == null && !apiReqCancelReason) { - const retryOperations = retryStatus.maxAttempts > 0 ? retryStatus.maxAttempts - 1 : 0 - return ( - - ) - } - - return API Request... - })(), - ] - case "followup": - return [ - , - Cline has a question:, - ] - default: - return [null, null] - } - }, [type, cost, apiRequestFailedMessage, isCommandExecuting, apiReqCancelReason, isMcpServerResponding, message.text]) - - const headerStyle: React.CSSProperties = { - display: "flex", - alignItems: "center", - gap: "10px", - marginBottom: "12px", - } - - const pStyle: React.CSSProperties = { - margin: 0, - whiteSpace: "pre-wrap", - wordBreak: "break-word", - overflowWrap: "anywhere", - } - - const tool = useMemo(() => { - if (message.ask === "tool" || message.say === "tool") { - return JSON.parse(message.text || "{}") as ClineSayTool - } - return null - }, [message.ask, message.say, message.text]) - - if (tool) { - const colorMap = { - red: "var(--vscode-errorForeground)", - yellow: "var(--vscode-editorWarning-foreground)", - green: "var(--vscode-charts-green)", - } - const toolIcon = (name: string, color?: string, rotation?: number, title?: string) => ( - - ) - - switch (tool.tool) { - case "editedExistingFile": - return ( - <> -
- {toolIcon("edit")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} - Cline wants to edit this file: -
- - - ) - case "newFileCreated": - return ( - <> -
- {toolIcon("new-file")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} - Cline wants to create a new file: -
- - - ) - case "readFile": - return ( - <> -
- {toolIcon("file-code")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} - - {/* {message.type === "ask" ? "" : "Cline read this file:"} */} - Cline wants to read this file: - -
+ + ), + Cline wants to execute this command:, + ] + case "use_mcp_server": + const mcpServerUse = JSON.parse(message.text || "{}") as ClineAskUseMcpServer + return [ + isMcpServerResponding ? ( + + ) : ( + + ), + + Cline wants to {mcpServerUse.type === "use_mcp_tool" ? "use a tool" : "access a resource"} on the{" "} + + {getMcpServerDisplayName(mcpServerUse.serverName, mcpMarketplaceCatalog)} + {" "} + MCP server: + , + ] + case "completion_result": + return [ + , + Task Completed, + ] + case "api_req_started": + const getIconSpan = (iconName: string, color: string) => (
+ +
+ ) + return [ + apiReqCancelReason != null ? ( + apiReqCancelReason === "user_cancelled" ? ( + getIconSpan("error", cancelledColor) + ) : ( + getIconSpan("error", errorColor) + ) + ) : cost != null ? ( + getIconSpan("check", successColor) + ) : apiRequestFailedMessage ? ( + getIconSpan("error", errorColor) + ) : ( + + ), + (() => { + if (apiReqCancelReason != null) { + return apiReqCancelReason === "user_cancelled" ? ( + API Request Cancelled + ) : ( + API Streaming Failed + ) + } + + if (cost != null) { + return API Request + } + + if (apiRequestFailedMessage) { + return API Request Failed + } + // New: Check for retryStatus to modify the title + if (retryStatus && cost == null && !apiReqCancelReason) { + const retryOperations = retryStatus.maxAttempts > 0 ? retryStatus.maxAttempts - 1 : 0 + return ( + + ) + } + + return API Request... + })(), + ] + case "followup": + return [ + , + Cline has a question:, + ] + default: + return [null, null] + } + }, [type, cost, apiRequestFailedMessage, isCommandExecuting, apiReqCancelReason, isMcpServerResponding, message.text]) + + const headerStyle: React.CSSProperties = { + display: "flex", + alignItems: "center", + gap: "10px", + marginBottom: "12px", + } + + const pStyle: React.CSSProperties = { + margin: 0, + whiteSpace: "pre-wrap", + wordBreak: "break-word", + overflowWrap: "anywhere", + } + + const tool = useMemo(() => { + if (message.ask === "tool" || message.say === "tool") { + return JSON.parse(message.text || "{}") as ClineSayTool + } + return null + }, [message.ask, message.say, message.text]) + + if (tool) { + const colorMap = { + red: "var(--vscode-errorForeground)", + yellow: "var(--vscode-editorWarning-foreground)", + green: "var(--vscode-charts-green)", + } + const toolIcon = (name: string, color?: string, rotation?: number, title?: string) => ( + + ) + + switch (tool.tool) { + case "editedExistingFile": + return ( + <> +
+ {toolIcon("edit")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} + Cline wants to edit this file: +
+ + + ) + case "newFileCreated": + return ( + <> +
+ {toolIcon("new-file")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} + Cline wants to create a new file: +
+ + + ) + case "readFile": + return ( + <> +
+ {toolIcon("file-code")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} + + {/* {message.type === "ask" ? "" : "Cline read this file:"} */} + Cline wants to read this file: + +
+
{ + FileServiceClient.openFile(StringRequest.create({ value: tool.content })).catch((err) => + console.error("Failed to open file:", err), + ) + }}> + {tool.path?.startsWith(".") && .} + + {cleanPathPrefix(tool.path ?? "") + "\u200E"} + +
+ +
+
+ + ) + case "listFilesTopLevel": + return ( + <> +
+ {toolIcon("folder-opened")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} + + {message.type === "ask" + ? "Cline wants to view the top level files in this directory:" + : "Cline viewed the top level files in this directory:"} + +
+ + + ) + case "listFilesRecursive": + return ( + <> +
+ {toolIcon("folder-opened")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} + + {message.type === "ask" + ? "Cline wants to recursively view all files in this directory:" + : "Cline recursively viewed all files in this directory:"} + +
+ + + ) + case "listCodeDefinitionNames": + return ( + <> +
+ {toolIcon("file-code")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} + + {message.type === "ask" + ? "Cline wants to view source code definition names used in this directory:" + : "Cline viewed source code definition names used in this directory:"} + +
+ + + ) + case "searchFiles": + return ( + <> +
+ {toolIcon("search")} + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} + + Cline wants to search this directory for {tool.regex}: + +
+ + + ) + case "webFetch": + return ( + <> +
+ + {tool.operationIsLocatedInWorkspace === false && + toolIcon("sign-out", "yellow", -90, "This URL is external")} + + {message.type === "ask" + ? "Cline wants to fetch content from this URL:" + : "Cline fetched content from this URL:"} + +
+
{ - FileServiceClient.openFile(StringRequest.create({ value: tool.content })).catch((err) => - console.error("Failed to open file:", err), - ) + // Open the URL in the default browser using gRPC + if (tool.path) { + UiServiceClient.openUrl(StringRequest.create({ value: tool.path })) + + .catch((err) => { + console.error("Failed to open URL:", err) + }) + } }}> - {tool.path?.startsWith(".") && .} - {cleanPathPrefix(tool.path ?? "") + "\u200E"} + {tool.path + "\u200E"} -
-
-
- - ) - case "listFilesTopLevel": - return ( - <> -
- {toolIcon("folder-opened")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} - - {message.type === "ask" - ? "Cline wants to view the top level files in this directory:" - : "Cline viewed the top level files in this directory:"} - -
- - - ) - case "listFilesRecursive": - return ( - <> -
- {toolIcon("folder-opened")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} - - {message.type === "ask" - ? "Cline wants to recursively view all files in this directory:" - : "Cline recursively viewed all files in this directory:"} - -
- - - ) - case "listCodeDefinitionNames": - return ( - <> -
- {toolIcon("file-code")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} - - {message.type === "ask" - ? "Cline wants to view source code definition names used in this directory:" - : "Cline viewed source code definition names used in this directory:"} - -
- - - ) - case "searchFiles": - return ( - <> -
- {toolIcon("search")} - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} - - Cline wants to search this directory for {tool.regex}: - -
- - - ) - case "webFetch": - return ( - <> -
- - {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This URL is external")} - - {message.type === "ask" - ? "Cline wants to fetch content from this URL:" - : "Cline fetched content from this URL:"} - -
-
{ - // Open the URL in the default browser using gRPC - if (tool.path) { - UiServiceClient.openUrl(StringRequest.create({ value: tool.path })) - - .catch((err) => { - console.error("Failed to open URL:", err) - }) - } - }}> - - {tool.path + "\u200E"} - -
- {/* Displaying the 'content' which now holds "Fetching URL: [URL]" */} - {/*
{tool.content}
*/} - - ) - default: - return null - } - } - - if (message.ask === "command" || message.say === "command") { - const splitMessage = (text: string) => { - const outputIndex = text.indexOf(COMMAND_OUTPUT_STRING) - if (outputIndex === -1) { - return { command: text, output: "" } - } - return { - command: text.slice(0, outputIndex).trim(), - output: text - .slice(outputIndex + COMMAND_OUTPUT_STRING.length) - .trim() - .split("") - .map((char) => { - switch (char) { - case "\t": - return "→ " - case "\b": - return "⌫" - case "\f": - return "⏏" - case "\v": - return "⇳" - default: - return char - } - }) - .join(""), + {/* Displaying the 'content' which now holds "Fetching URL: [URL]" */} + {/*
{tool.content}
*/} + + ) + default: + return null } } - const { command: rawCommand, output } = splitMessage(message.text || "") + if (message.ask === "command" || message.say === "command") { + const splitMessage = (text: string) => { + const outputIndex = text.indexOf(COMMAND_OUTPUT_STRING) + if (outputIndex === -1) { + return { command: text, output: "" } + } + return { + command: text.slice(0, outputIndex).trim(), + output: text + .slice(outputIndex + COMMAND_OUTPUT_STRING.length) + .trim() + .split("") + .map((char) => { + switch (char) { + case "\t": + return "→ " + case "\b": + return "⌫" + case "\f": + return "⏏" + case "\v": + return "⇳" + default: + return char + } + }) + .join(""), + } + } - const requestsApproval = rawCommand.endsWith(COMMAND_REQ_APP_STRING) - const command = requestsApproval ? rawCommand.slice(0, -COMMAND_REQ_APP_STRING.length) : rawCommand + const { command: rawCommand, output } = splitMessage(message.text || "") - return ( - <> -
- {icon} - {title} -
-
- - {output.length > 0 && ( -
-
- - Command Output -
- {isExpanded && } -
- )} -
- {requestsApproval && ( + const requestsApproval = rawCommand.endsWith(COMMAND_REQ_APP_STRING) + const command = requestsApproval ? rawCommand.slice(0, -COMMAND_REQ_APP_STRING.length) : rawCommand + + return ( + <> +
+ {icon} + {title} +
- - The model has determined this command requires explicit approval. -
- )} - - ) - } - - if (message.ask === "use_mcp_server" || message.say === "use_mcp_server") { - const useMcpServer = JSON.parse(message.text || "{}") as ClineAskUseMcpServer - const server = mcpServers.find((server) => server.name === useMcpServer.serverName) - return ( - <> -
- {icon} - {title} -
- -
- {useMcpServer.type === "access_mcp_resource" && ( - - )} - - {useMcpServer.type === "use_mcp_tool" && ( - <> -
e.stopPropagation()}> - tool.name === useMcpServer.toolName)?.description || "", - autoApprove: - server?.tools?.find((tool) => tool.name === useMcpServer.toolName)?.autoApprove || - false, - }} - serverName={useMcpServer.serverName} - /> -
- {useMcpServer.arguments && useMcpServer.arguments !== "{}" && ( -
-
- Arguments -
- -
- )} - - )} -
- - ) - } - - switch (message.type) { - case "say": - switch (message.say) { - case "api_req_started": - return ( - <> -
+ + {output.length > 0 && ( +
- {icon} - {title} - {/* Need to render this every time since it affects height of row by 2px */} - 0 ? 1 : 0, - }}> - ${Number(cost || 0)?.toFixed(4)} - -
- -
- {((cost == null && apiRequestFailedMessage) || apiReqStreamingFailedMessage) && ( - <> - {(() => { - // Try to parse the error message as JSON for credit limit error - const errorData = parseErrorText(apiRequestFailedMessage) - if (errorData) { - if ( - errorData.code === "insufficient_credits" && - typeof errorData.current_balance === "number" && - typeof errorData.total_spent === "number" && - typeof errorData.total_promotions === "number" && - typeof errorData.message === "string" - ) { - return ( - - ) - } - } - - // Check for rate limit errors (status code 429) - const isRateLimitError = - apiRequestFailedMessage?.includes("status code 429") || - apiRequestFailedMessage?.toLowerCase().includes("rate limit") || - apiRequestFailedMessage?.toLowerCase().includes("too many requests") || - apiRequestFailedMessage?.toLowerCase().includes("quota exceeded") || - apiRequestFailedMessage?.toLowerCase().includes("resource exhausted") - - if (isRateLimitError) { - // Check if current provider is Gemini CLI to show specific message - const isGeminiCliProvider = apiConfiguration?.apiProvider === "gemini-cli" - - if (isGeminiCliProvider) { - return ( -
-
- - - Rate Limit Exceeded - -
-

- You've hit the API rate limit. This is likely due to free tier limits. -

-

- You can read about the tier limits{" "} - { - e.preventDefault() - UiServiceClient.openUrl( - StringRequest.create({ - value: "https://codeassist.google/", - }), - ).catch((err) => console.error("Failed to open URL:", err)) - }}> - here - - , or alternatively, you can use the Gemini Flash Model that will give - you better limits. -

-
- ) - } else { - // Generic rate limit error for other providers - return ( -

- {apiRequestFailedMessage || apiReqStreamingFailedMessage} -

- ) - } - } - - // Default error display - return ( -

- {apiRequestFailedMessage || apiReqStreamingFailedMessage} - {apiRequestFailedMessage?.toLowerCase().includes("powershell") && ( - <> -
-
- It seems like you're having Windows PowerShell issues, please see this{" "} - - troubleshooting guide - - . - - )} -

- ) - })()} - - )} - - {isExpanded && ( -
- -
- )} - - ) - case "api_req_finished": - return null // we should never see this message type - case "mcp_server_response": - return - case "mcp_notification": - return ( -
- -
- MCP Notification: - {message.text} -
-
- ) - case "text": - return ( - - - {quoteButtonState.visible && ( - { - handleQuoteClick() - }} - /> - )} - - ) - case "reasoning": - return ( - <> - {message.text && ( -
- {isExpanded ? ( -
- - Thinking - - - {message.text} -
- ) : ( -
- Thinking: - - {message.text + "\u200E"} - - -
- )} + + Command Output
- )} - - ) - case "user_feedback": - return ( - - ) - case "user_feedback_diff": - const tool = JSON.parse(message.text || "{}") as ClineSayTool - return ( -
- -
- ) - case "error": - return ( - <> - {title && ( -
- {icon} - {title} -
- )} -

- {message.text} -

- - ) - case "diff_error": - return ( - <> -
-
- - Diff Edit Mismatch -
-
The model used search patterns that don't match anything in the file. Retrying...
+ {isExpanded && }
- - ) - case "clineignore_error": - return ( - <> -
-
- - - Access Denied - -
-
- Cline tried to access {message.text} which is blocked by the{" "} - .clineignore - file. -
-
- - ) - case "checkpoint_created": - return ( - <> - - - ) - case "load_mcp_documentation": - return ( + )} +
+ {requestsApproval && (
- - Loading MCP documentation + + The model has determined this command requires explicit approval.
- ) - case "completion_result": - const hasChanges = message.text?.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false - const text = hasChanges ? message.text?.slice(0, -COMPLETION_RESULT_CHANGES_FLAG.length) : message.text - return ( - <> + )} + + ) + } + + if (message.ask === "use_mcp_server" || message.say === "use_mcp_server") { + const useMcpServer = JSON.parse(message.text || "{}") as ClineAskUseMcpServer + const server = mcpServers.find((server) => server.name === useMcpServer.serverName) + return ( + <> +
+ {icon} + {title} +
+ +
+ {useMcpServer.type === "access_mcp_resource" && ( + + )} + + {useMcpServer.type === "use_mcp_tool" && ( + <> +
e.stopPropagation()}> + tool.name === useMcpServer.toolName)?.description || + "", + autoApprove: + server?.tools?.find((tool) => tool.name === useMcpServer.toolName)?.autoApprove || + false, + }} + serverName={useMcpServer.serverName} + /> +
+ {useMcpServer.arguments && useMcpServer.arguments !== "{}" && ( +
+
+ Arguments +
+ +
+ )} + + )} +
+ + ) + } + + switch (message.type) { + case "say": + switch (message.say) { + case "api_req_started": + return ( + <> +
+
+ {icon} + {title} + {/* Need to render this every time since it affects height of row by 2px */} + 0 ? 1 : 0, + }}> + ${Number(cost || 0)?.toFixed(4)} + +
+ +
+ {((cost == null && apiRequestFailedMessage) || apiReqStreamingFailedMessage) && ( + <> + {(() => { + // Try to parse the error message as JSON for credit limit error + const errorData = parseErrorText(apiRequestFailedMessage) + if (errorData) { + if ( + errorData.code === "insufficient_credits" && + typeof errorData.current_balance === "number" && + typeof errorData.total_spent === "number" && + typeof errorData.total_promotions === "number" && + typeof errorData.message === "string" + ) { + return ( + + ) + } + } + + // Check for rate limit errors (status code 429) + const isRateLimitError = + apiRequestFailedMessage?.includes("status code 429") || + apiRequestFailedMessage?.toLowerCase().includes("rate limit") || + apiRequestFailedMessage?.toLowerCase().includes("too many requests") || + apiRequestFailedMessage?.toLowerCase().includes("quota exceeded") || + apiRequestFailedMessage?.toLowerCase().includes("resource exhausted") + + if (isRateLimitError) { + // Check if current provider is Gemini CLI to show specific message + const isGeminiCliProvider = apiConfiguration?.apiProvider === "gemini-cli" + + if (isGeminiCliProvider) { + return ( +
+
+ + + Rate Limit Exceeded + +
+

+ You've hit the API rate limit. This is likely due to free tier + limits. +

+

+ You can read about the tier limits{" "} + { + e.preventDefault() + UiServiceClient.openUrl( + StringRequest.create({ + value: "https://codeassist.google/", + }), + ).catch((err) => + console.error("Failed to open URL:", err), + ) + }}> + here + + , or alternatively, you can use the Gemini Flash Model that will + give you better limits. +

+
+ ) + } else { + // Generic rate limit error for other providers + return ( +

+ {apiRequestFailedMessage || apiReqStreamingFailedMessage} +

+ ) + } + } + + // Default error display + return ( +

+ {apiRequestFailedMessage || apiReqStreamingFailedMessage} + {apiRequestFailedMessage?.toLowerCase().includes("powershell") && ( + <> +
+
+ It seems like you're having Windows PowerShell issues, please see this{" "} + + troubleshooting guide + + . + + )} +

+ ) + })()} + + )} + + {isExpanded && ( +
+ +
+ )} + + ) + case "api_req_finished": + return null // we should never see this message type + case "mcp_server_response": + return + case "mcp_notification": + return (
- {icon} - {title} - +
+ MCP Notification: + {message.text} +
+ ) + case "text": + return ( - + textToCopy={message.text} + position="bottom-right"> + {quoteButtonState.visible && ( { + handleQuoteClick() + }} /> )} - {message.partial !== true && hasChanges && ( -
- { - setSeeNewChangesDisabled(true) - TaskServiceClient.taskCompletionViewChanges( - Int64Request.create({ - value: message.ts, - }), - ).catch((err) => console.error("Failed to show task completion view changes:", err)) - }} + ) + case "reasoning": + return ( + <> + {message.text && ( +
- - See new changes - -
- )} - - ) - case "shell_integration_warning": - return ( - <> + {isExpanded ? ( +
+ + Thinking + + + {message.text} +
+ ) : ( +
+ Thinking: + + {message.text + "\u200E"} + + +
+ )} +
+ )} + + ) + case "user_feedback": + return ( + + ) + case "user_feedback_diff": + const tool = JSON.parse(message.text || "{}") as ClineSayTool + return (
+ +
+ ) + case "error": + return ( + <> + {title && ( +
+ {icon} + {title} +
+ )} +

+ {message.text} +

+ + ) + case "diff_error": + return ( + <>
- - - Shell Integration Unavailable - + + Diff Edit Mismatch +
+
The model used search patterns that don't match anything in the file. Retrying...
-
- Cline won't be able to view the command's output. Please update VSCode ( - CMD/CTRL + Shift + P → "Update") and make sure you're using a supported shell: - zsh, bash, fish, or PowerShell (CMD/CTRL + Shift + P → "Terminal: Select Default - Profile").{" "} - - Still having trouble? - -
-
- - ) - default: - return ( - <> - {title && ( -
- {icon} - {title} -
- )} -
- -
- - ) - } - case "ask": - switch (message.ask) { - case "mistake_limit_reached": - return ( - <> -
- {icon} - {title} -
-

- {message.text} -

- - ) - case "auto_approval_max_req_reached": - return ( - <> -
- {icon} - {title} -
-

- {message.text} -

- - ) - case "completion_result": - if (message.text) { - const hasChanges = message.text.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false - const text = hasChanges ? message.text.slice(0, -COMPLETION_RESULT_CHANGES_FLAG.length) : message.text + + ) + case "clineignore_error": return ( -
+ <> +
+
+ + + Access Denied + +
+
+ Cline tried to access {message.text} which is blocked by the{" "} + .clineignore + file. +
+
+ + ) + case "checkpoint_created": + return ( + <> + + + ) + case "load_mcp_documentation": + return ( +
+ + Loading MCP documentation +
+ ) + case "completion_result": + const hasChanges = message.text?.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false + const text = hasChanges ? message.text?.slice(0, -COMPLETION_RESULT_CHANGES_FLAG.length) : message.text + return ( + <>
{message.partial !== true && hasChanges && ( -
+
{ setSeeNewChangesDisabled(true) @@ -1547,56 +1404,313 @@ export const ChatRowContent = ({ ).catch((err) => console.error("Failed to show task completion view changes:", err), ) + }} + style={{ + cursor: seeNewChangesDisabled ? "wait" : "pointer", + width: "100%", }}> - + See new changes
)} -
+ ) - } else { - return null // Don't render anything when we get a completion_result ask without text - } - case "followup": - let question: string | undefined - let options: string[] | undefined - let selected: string | undefined - try { - const parsedMessage = JSON.parse(message.text || "{}") as ClineAskQuestion - question = parsedMessage.question - options = parsedMessage.options - selected = parsedMessage.selected - } catch (e) { - // legacy messages would pass question directly - question = message.text - } - - return ( - <> - {title && ( + case "shell_integration_warning": + return ( + <> +
+
+ + + Shell Integration Unavailable + +
+
+ Cline won't be able to view the command's output. Please update VSCode ( + CMD/CTRL + Shift + P → "Update") and make sure you're using a supported + shell: zsh, bash, fish, or PowerShell (CMD/CTRL + Shift + P → "Terminal: + Select Default Profile").{" "} + + Still having trouble? + +
+
+ + ) + default: + return ( + <> + {title && ( +
+ {icon} + {title} +
+ )} +
+ +
+ + ) + } + case "ask": + switch (message.ask) { + case "mistake_limit_reached": + return ( + <>
{icon} {title}
- )} +

+ {message.text} +

+ + ) + case "auto_approval_max_req_reached": + return ( + <> +
+ {icon} + {title} +
+

+ {message.text} +

+ + ) + case "completion_result": + if (message.text) { + const hasChanges = message.text.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false + const text = hasChanges ? message.text.slice(0, -COMPLETION_RESULT_CHANGES_FLAG.length) : message.text + return ( +
+
+ {icon} + {title} + +
+ + + {quoteButtonState.visible && ( + + )} + + {message.partial !== true && hasChanges && ( +
+ { + setSeeNewChangesDisabled(true) + TaskServiceClient.taskCompletionViewChanges( + Int64Request.create({ + value: message.ts, + }), + ).catch((err) => + console.error("Failed to show task completion view changes:", err), + ) + }}> + + See new changes + +
+ )} +
+ ) + } else { + return null // Don't render anything when we get a completion_result ask without text + } + case "followup": + let question: string | undefined + let options: string[] | undefined + let selected: string | undefined + try { + const parsedMessage = JSON.parse(message.text || "{}") as ClineAskQuestion + question = parsedMessage.question + options = parsedMessage.options + selected = parsedMessage.selected + } catch (e) { + // legacy messages would pass question directly + question = message.text + } + + return ( + <> + {title && ( +
+ {icon} + {title} +
+ )} + + + + {quoteButtonState.visible && ( + { + handleQuoteClick() + }} + /> + )} + + + ) + case "new_task": + return ( + <> +
+ + + Cline wants to start a new task: + +
+ + + ) + case "condense": + return ( + <> +
+ + + Cline wants to condense your conversation: + +
+ + + ) + case "report_bug": + return ( + <> +
+ + + Cline wants to create a Github issue: + +
+ + + ) + case "plan_mode_respond": { + let response: string | undefined + let options: string[] | undefined + let selected: string | undefined + try { + const parsedMessage = JSON.parse(message.text || "{}") as ClinePlanModeResponse + response = parsedMessage.response + options = parsedMessage.options + selected = parsedMessage.selected + } catch (e) { + // legacy messages would pass response directly + response = message.text + } + return ( - + textToCopy={response} + position="bottom-right"> + {quoteButtonState.visible && ( @@ -1609,96 +1723,14 @@ export const ChatRowContent = ({ /> )} - - ) - case "new_task": - return ( - <> -
- - Cline wants to start a new task: -
- - - ) - case "condense": - return ( - <> -
- - - Cline wants to condense your conversation: - -
- - - ) - case "report_bug": - return ( - <> -
- - - Cline wants to create a Github issue: - -
- - - ) - case "plan_mode_respond": { - let response: string | undefined - let options: string[] | undefined - let selected: string | undefined - try { - const parsedMessage = JSON.parse(message.text || "{}") as ClinePlanModeResponse - response = parsedMessage.response - options = parsedMessage.options - selected = parsedMessage.selected - } catch (e) { - // legacy messages would pass response directly - response = message.text + ) } - return ( - - - - {quoteButtonState.visible && ( - { - handleQuoteClick() - }} - /> - )} - - ) + default: + return null } - default: - return null - } - } -} + } + }, +) function parseErrorText(text: string | undefined) { if (!text) { diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index dfbef9c6..2fdc3307 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -1074,7 +1074,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie key={messageOrGroup.ts} message={messageOrGroup} isExpanded={expandedRows[messageOrGroup.ts] || false} - onToggleExpand={() => toggleRowExpansion(messageOrGroup.ts)} + onToggleExpand={toggleRowExpansion} lastModifiedMessage={modifiedMessages.at(-1)} isLast={isLast} onHeightChange={handleRowHeightChange} From 5a777f28b660389e068304d91107a23ab795215d Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Sat, 28 Jun 2025 10:12:51 -0700 Subject: [PATCH 31/60] fix browser row in chat view to prevent constant rerendering (#4542) * base * browser 2 --- .../src/components/chat/BrowserSessionRow.tsx | 142 +++++++++--------- webview-ui/src/components/chat/ChatView.tsx | 9 +- 2 files changed, 77 insertions(+), 74 deletions(-) diff --git a/webview-ui/src/components/chat/BrowserSessionRow.tsx b/webview-ui/src/components/chat/BrowserSessionRow.tsx index a205169e..6943ce03 100644 --- a/webview-ui/src/components/chat/BrowserSessionRow.tsx +++ b/webview-ui/src/components/chat/BrowserSessionRow.tsx @@ -9,13 +9,13 @@ import { BrowserAction, BrowserActionResult, ClineMessage, ClineSayBrowserAction import { StringRequest } from "@shared/proto/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import deepEqual from "fast-deep-equal" -import React, { CSSProperties, memo, useEffect, useMemo, useRef, useState } from "react" +import React, { CSSProperties, memo, useCallback, useEffect, useMemo, useRef, useState } from "react" import { useSize } from "react-use" import styled from "styled-components" interface BrowserSessionRowProps { messages: ClineMessage[] - isExpanded: (messageTs: number) => boolean + expandedRows: Record onToggleExpand: (messageTs: number) => void lastModifiedMessage?: ClineMessage isLast: boolean @@ -294,10 +294,13 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { {currentPage?.nextAction?.messages.map((message) => ( ))} {!isBrowsing && messages.some((m) => m.say === "browser_action_result") && currentPageIndex === 0 && ( @@ -498,73 +501,78 @@ interface BrowserSessionRowContentProps extends Omit void } -const BrowserSessionRowContent = ({ - message, - isExpanded, - onToggleExpand, - lastModifiedMessage, - isLast, - setMaxActionHeight, - onSetQuote, -}: BrowserSessionRowContentProps) => { - if (message.ask === "browser_action_launch" || message.say === "browser_action_launch") { - return ( - <> -
- Browser Session Started -
-
- -
- - ) - } +const BrowserSessionRowContent = memo( + ({ + message, + expandedRows, + onToggleExpand, + lastModifiedMessage, + isLast, + setMaxActionHeight, + onSetQuote, + }: BrowserSessionRowContentProps) => { + const handleToggle = useCallback(() => { + if (message.say === "api_req_started") { + setMaxActionHeight(0) + } + onToggleExpand(message.ts) + }, [onToggleExpand, message.ts, setMaxActionHeight]) - switch (message.type) { - case "say": - switch (message.say) { - case "api_req_started": - case "text": - case "reasoning": - return ( -
- { - if (message.say === "api_req_started") { - setMaxActionHeight(0) - } - onToggleExpand(message.ts) - }} - lastModifiedMessage={lastModifiedMessage} - isLast={isLast} - onSetQuote={onSetQuote} + if (message.ask === "browser_action_launch" || message.say === "browser_action_launch") { + return ( + <> +
+ Browser Session Started +
+
+ +
+ + ) + } + + switch (message.type) { + case "say": + switch (message.say) { + case "api_req_started": + case "text": + case "reasoning": + return ( +
+ +
+ ) + + case "browser_action": + const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction + return ( + -
- ) + ) - case "browser_action": - const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction - return ( - - ) + default: + return null + } - default: - return null - } - - case "ask": - switch (message.ask) { - default: - return null - } - } -} + case "ask": + switch (message.ask) { + default: + return null + } + } + }, + deepEqual, +) const BrowserActionBox = ({ action, coordinate, text }: { action: BrowserAction; coordinate?: string; text?: string }) => { const getBrowserActionText = (action: BrowserAction, coordinate?: string, text?: string) => { diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index 2fdc3307..2e4844e6 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -1048,13 +1048,8 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie lastModifiedMessage={modifiedMessages.at(-1)} onHeightChange={handleRowHeightChange} // Pass handlers for each message in the group - isExpanded={(messageTs: number) => expandedRows[messageTs] ?? false} - onToggleExpand={(messageTs: number) => { - setExpandedRows((prev) => ({ - ...prev, - [messageTs]: !prev[messageTs], - })) - }} + expandedRows={expandedRows} + onToggleExpand={toggleRowExpansion} onSetQuote={setActiveQuote} /> ) From 968b46a1796588ee3d0afdc45dbbcf5a16dedb7e Mon Sep 17 00:00:00 2001 From: Ara Date: Sun, 29 Jun 2025 06:50:32 +0530 Subject: [PATCH 32/60] Revert "Adding Gemini CLI Provider with Oauth support (#4472)" (#4556) * Revert "Adding Gemini CLI Provider with Oauth support (#4472)" This reverts commit 890148407ac658430340a2fd851331bf1eb58365. * revert * revert * revert --------- Co-authored-by: Cline Evaluation --- .changeset/strong-glasses-bathe.md | 5 + package-lock.json | 608 ++---------------- package.json | 1 - proto/models.proto | 41 +- src/api/index.ts | 3 - src/api/providers/gemini-cli.ts | 418 ------------ src/shared/api.ts | 135 ---- .../models/api-configuration-conversion.ts | 8 - webview-ui/src/components/chat/ChatRow.tsx | 88 +-- .../src/components/settings/ApiOptions.tsx | 11 - .../settings/common/ModelInfoView.tsx | 11 +- .../settings/providers/GeminiCliProvider.tsx | 169 ----- .../settings/utils/providerUtils.ts | 4 - 13 files changed, 93 insertions(+), 1409 deletions(-) create mode 100644 .changeset/strong-glasses-bathe.md delete mode 100644 src/api/providers/gemini-cli.ts delete mode 100644 webview-ui/src/components/settings/providers/GeminiCliProvider.tsx diff --git a/.changeset/strong-glasses-bathe.md b/.changeset/strong-glasses-bathe.md new file mode 100644 index 00000000..44de2844 --- /dev/null +++ b/.changeset/strong-glasses-bathe.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Reverting Gemini Cli provider diff --git a/package-lock.json b/package-lock.json index 259568dc..4bc2cfeb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,7 +45,6 @@ "fzf": "^0.5.2", "get-folder-size": "^5.0.0", "globby": "^14.0.2", - "google-auth-library": "^10.1.0", "grpc-health-check": "^2.0.2", "iconv-lite": "^0.6.3", "ignore": "^7.0.3", @@ -202,75 +201,6 @@ "undici-types": "~5.26.4" } }, - "node_modules/@anthropic-ai/vertex-sdk/node_modules/gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "license": "Apache-2.0", - "dependencies": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@anthropic-ai/vertex-sdk/node_modules/gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "license": "Apache-2.0", - "dependencies": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@anthropic-ai/vertex-sdk/node_modules/google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "license": "Apache-2.0", - "dependencies": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@anthropic-ai/vertex-sdk/node_modules/google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@anthropic-ai/vertex-sdk/node_modules/gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "license": "MIT", - "dependencies": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/@asyncapi/parser": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/@asyncapi/parser/-/parser-3.4.0.tgz", @@ -2938,75 +2868,6 @@ "node": ">=18.0.0" } }, - "node_modules/@google-cloud/vertexai/node_modules/gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "license": "Apache-2.0", - "dependencies": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google-cloud/vertexai/node_modules/gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "license": "Apache-2.0", - "dependencies": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google-cloud/vertexai/node_modules/google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "license": "Apache-2.0", - "dependencies": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google-cloud/vertexai/node_modules/google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@google-cloud/vertexai/node_modules/gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "license": "MIT", - "dependencies": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/@google/genai": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.0.0.tgz", @@ -3025,75 +2886,6 @@ "@modelcontextprotocol/sdk": "^1.11.0" } }, - "node_modules/@google/genai/node_modules/gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "license": "Apache-2.0", - "dependencies": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google/genai/node_modules/gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "license": "Apache-2.0", - "dependencies": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google/genai/node_modules/google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "license": "Apache-2.0", - "dependencies": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/@google/genai/node_modules/google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@google/genai/node_modules/gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "license": "MIT", - "dependencies": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/@grpc/grpc-js": { "version": "1.9.15", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.15.tgz", @@ -9810,10 +9602,9 @@ } }, "node_modules/bignumber.js": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.0.tgz", - "integrity": "sha512-EM7aMFTXbptt/wZdMlBv2t8IViwQL+h6SLHosp8Yf0dqJMTnY6iL32opnAB6kAdL0SZPuvcAzFr31o0c/R3/RA==", - "license": "MIT", + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", "engines": { "node": "*" } @@ -9999,8 +9790,7 @@ "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", - "license": "BSD-3-Clause" + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" }, "node_modules/buffer-indexof-polyfill": { "version": "1.0.2", @@ -11658,7 +11448,6 @@ "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", - "license": "Apache-2.0", "dependencies": { "safe-buffer": "^5.0.1" } @@ -13297,29 +13086,6 @@ "pend": "~1.2.0" } }, - "node_modules/fetch-blob": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", - "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" - } - }, "node_modules/figures": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", @@ -13656,18 +13422,6 @@ "node": ">= 14" } }, - "node_modules/formdata-polyfill": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", - "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", - "license": "MIT", - "dependencies": { - "fetch-blob": "^3.1.2" - }, - "engines": { - "node": ">=12.20.0" - } - }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -13934,44 +13688,18 @@ } }, "node_modules/gaxios": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.1.tgz", - "integrity": "sha512-Odju3uBUJyVCkW64nLD4wKLhbh93bh6vIg/ZIXkWiLPBrdgtc65+tls/qml+un3pr6JqYVFDZbbmLDQT68rTOQ==", - "license": "Apache-2.0", + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2" + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" }, "engines": { - "node": ">=18" - } - }, - "node_modules/gaxios/node_modules/data-uri-to-buffer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", - "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/gaxios/node_modules/node-fetch": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", - "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" + "node": ">=14" } }, "node_modules/gcd": { @@ -13981,17 +13709,15 @@ "dev": true }, "node_modules/gcp-metadata": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-7.0.1.tgz", - "integrity": "sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==", - "license": "Apache-2.0", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.0.tgz", + "integrity": "sha512-Jh/AIwwgaxan+7ZUUmRLCjtchyDiqh4KjBJ5tW3plBZb5iL/BPcso8A5DlzeD9qlw0duCamnNdpFjxwaT0KyKg==", "dependencies": { - "gaxios": "^7.0.0", - "google-logging-utils": "^1.0.0", + "gaxios": "^6.0.0", "json-bigint": "^1.0.0" }, "engines": { - "node": ">=18" + "node": ">=14" } }, "node_modules/get-caller-file": { @@ -14264,28 +13990,18 @@ } }, "node_modules/google-auth-library": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.1.0.tgz", - "integrity": "sha512-GspVjZj1RbyRWpQ9FbAXMKjFGzZwDKnUHi66JJ+tcjcu5/xYAP1pdlWotCuIkMwjfVsxxDvsGZXGLzRt72D0sQ==", + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", "license": "Apache-2.0", "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^7.0.0", - "gcp-metadata": "^7.0.0", - "google-logging-utils": "^1.0.0", - "gtoken": "^8.0.0", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", "jws": "^4.0.0" }, - "engines": { - "node": ">=18" - } - }, - "node_modules/google-logging-utils": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.1.tgz", - "integrity": "sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==", - "license": "Apache-2.0", "engines": { "node": ">=14" } @@ -14422,16 +14138,15 @@ } }, "node_modules/gtoken": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-8.0.0.tgz", - "integrity": "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==", - "license": "MIT", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", "dependencies": { - "gaxios": "^7.0.0", + "gaxios": "^6.0.0", "jws": "^4.0.0" }, "engines": { - "node": ">=18" + "node": ">=14.0.0" } }, "node_modules/has-bigints": { @@ -16030,7 +15745,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", - "license": "MIT", "dependencies": { "bignumber.js": "^9.0.0" } @@ -16144,12 +15858,11 @@ "license": "MIT" }, "node_modules/jwa": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", - "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", - "license": "MIT", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", "dependencies": { - "buffer-equal-constant-time": "^1.0.1", + "buffer-equal-constant-time": "1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } @@ -16158,7 +15871,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", - "license": "MIT", "dependencies": { "jwa": "^2.0.0", "safe-buffer": "^5.0.1" @@ -23688,15 +23400,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/web-streams-polyfill": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", - "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, "node_modules/web-tree-sitter": { "version": "0.22.6", "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.22.6.tgz", @@ -24457,55 +24160,6 @@ "requires": { "undici-types": "~5.26.4" } - }, - "gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "requires": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - } - }, - "gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "requires": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - } - }, - "google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "requires": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - } - }, - "google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==" - }, - "gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "requires": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - } } } }, @@ -26762,57 +26416,6 @@ "integrity": "sha512-35o5tIEMLW3JeFJOaaMNR2e5sq+6rpnhrF97PuAxeOm0GlqVTESKhkGj7a5B5mmJSSSU3hUfIhcQCRRsw4Ipzg==", "requires": { "google-auth-library": "^9.1.0" - }, - "dependencies": { - "gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "requires": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - } - }, - "gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "requires": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - } - }, - "google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "requires": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - } - }, - "google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==" - }, - "gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "requires": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - } - } } }, "@google/genai": { @@ -26824,57 +26427,6 @@ "ws": "^8.18.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.4" - }, - "dependencies": { - "gaxios": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", - "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", - "requires": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "is-stream": "^2.0.0", - "node-fetch": "^2.6.9", - "uuid": "^9.0.1" - } - }, - "gcp-metadata": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", - "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", - "requires": { - "gaxios": "^6.1.1", - "google-logging-utils": "^0.0.2", - "json-bigint": "^1.0.0" - } - }, - "google-auth-library": { - "version": "9.15.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", - "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", - "requires": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^6.1.1", - "gcp-metadata": "^6.1.0", - "gtoken": "^7.0.0", - "jws": "^4.0.0" - } - }, - "google-logging-utils": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", - "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==" - }, - "gtoken": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", - "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", - "requires": { - "gaxios": "^6.0.0", - "jws": "^4.0.0" - } - } } }, "@grpc/grpc-js": { @@ -31658,9 +31210,9 @@ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==" }, "bignumber.js": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.0.tgz", - "integrity": "sha512-EM7aMFTXbptt/wZdMlBv2t8IViwQL+h6SLHosp8Yf0dqJMTnY6iL32opnAB6kAdL0SZPuvcAzFr31o0c/R3/RA==" + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==" }, "binary": { "version": "0.3.0", @@ -34012,15 +33564,6 @@ "pend": "~1.2.0" } }, - "fetch-blob": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", - "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", - "requires": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - } - }, "figures": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", @@ -34256,14 +33799,6 @@ } } }, - "formdata-polyfill": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", - "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", - "requires": { - "fetch-blob": "^3.1.2" - } - }, "forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -34449,30 +33984,15 @@ } }, "gaxios": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.1.tgz", - "integrity": "sha512-Odju3uBUJyVCkW64nLD4wKLhbh93bh6vIg/ZIXkWiLPBrdgtc65+tls/qml+un3pr6JqYVFDZbbmLDQT68rTOQ==", + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", "requires": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2" - }, - "dependencies": { - "data-uri-to-buffer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", - "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==" - }, - "node-fetch": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", - "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", - "requires": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - } - } + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" } }, "gcd": { @@ -34482,12 +34002,11 @@ "dev": true }, "gcp-metadata": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-7.0.1.tgz", - "integrity": "sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.0.tgz", + "integrity": "sha512-Jh/AIwwgaxan+7ZUUmRLCjtchyDiqh4KjBJ5tW3plBZb5iL/BPcso8A5DlzeD9qlw0duCamnNdpFjxwaT0KyKg==", "requires": { - "gaxios": "^7.0.0", - "google-logging-utils": "^1.0.0", + "gaxios": "^6.0.0", "json-bigint": "^1.0.0" } }, @@ -34661,24 +34180,18 @@ } }, "google-auth-library": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.1.0.tgz", - "integrity": "sha512-GspVjZj1RbyRWpQ9FbAXMKjFGzZwDKnUHi66JJ+tcjcu5/xYAP1pdlWotCuIkMwjfVsxxDvsGZXGLzRt72D0sQ==", + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", "requires": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^7.0.0", - "gcp-metadata": "^7.0.0", - "google-logging-utils": "^1.0.0", - "gtoken": "^8.0.0", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", "jws": "^4.0.0" } }, - "google-logging-utils": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.1.tgz", - "integrity": "sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==" - }, "gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -34779,11 +34292,11 @@ } }, "gtoken": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-8.0.0.tgz", - "integrity": "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", "requires": { - "gaxios": "^7.0.0", + "gaxios": "^6.0.0", "jws": "^4.0.0" } }, @@ -35923,11 +35436,11 @@ "dev": true }, "jwa": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", - "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", "requires": { - "buffer-equal-constant-time": "^1.0.1", + "buffer-equal-constant-time": "1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } @@ -41118,11 +40631,6 @@ "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==", "dev": true }, - "web-streams-polyfill": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", - "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==" - }, "web-tree-sitter": { "version": "0.22.6", "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.22.6.tgz", diff --git a/package.json b/package.json index 6051ad56..4880ead9 100644 --- a/package.json +++ b/package.json @@ -442,7 +442,6 @@ "fzf": "^0.5.2", "get-folder-size": "^5.0.0", "globby": "^14.0.2", - "google-auth-library": "^10.1.0", "grpc-health-check": "^2.0.2", "iconv-lite": "^0.6.3", "ignore": "^7.0.3", diff --git a/proto/models.proto b/proto/models.proto index 9692a5ea..5f60fdbf 100644 --- a/proto/models.proto +++ b/proto/models.proto @@ -105,25 +105,24 @@ enum ApiProvider { OLLAMA = 5; LMSTUDIO = 6; GEMINI = 7; - GEMINI_CLI = 8; - OPENAI_NATIVE = 9; - REQUESTY = 10; - TOGETHER = 11; - DEEPSEEK = 12; - QWEN = 13; - DOUBAO = 14; - MISTRAL = 15; - VSCODE_LM = 16; - CLINE = 17; - LITELLM = 18; - NEBIUS = 19; - FIREWORKS = 20; - ASKSAGE = 21; - XAI = 22; - SAMBANOVA = 23; - CEREBRAS = 24; - SAPAICORE = 25; - CLAUDE_CODE = 26; + OPENAI_NATIVE = 8; + REQUESTY = 9; + TOGETHER = 10; + DEEPSEEK = 11; + QWEN = 12; + DOUBAO = 13; + MISTRAL = 14; + VSCODE_LM = 15; + CLINE = 16; + LITELLM = 17; + NEBIUS = 18; + FIREWORKS = 19; + ASKSAGE = 20; + XAI = 21; + SAMBANOVA = 22; + CEREBRAS = 23; + SAPAICORE = 24; + CLAUDE_CODE = 25; } // Model info for OpenAI-compatible models @@ -237,6 +236,4 @@ message ModelsApiConfiguration { optional string sap_ai_core_token_url = 71; optional string sap_ai_core_base_url = 72; optional string claude_code_path = 73; - optional string gemini_cli_oauth_path = 74; - optional string gemini_cli_project_id = 75; -} +} \ No newline at end of file diff --git a/src/api/index.ts b/src/api/index.ts index 04d346f3..61e5ba31 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -8,7 +8,6 @@ import { OpenAiHandler } from "./providers/openai" import { OllamaHandler } from "./providers/ollama" import { LmStudioHandler } from "./providers/lmstudio" import { GeminiHandler } from "./providers/gemini" -import { GeminiCliHandler } from "./providers/gemini-cli" import { OpenAiNativeHandler } from "./providers/openai-native" import { ApiStream, ApiStreamUsageChunk } from "./transform/stream" import { DeepSeekHandler } from "./providers/deepseek" @@ -57,8 +56,6 @@ function createHandlerForProvider(apiProvider: string | undefined, options: any) return new LmStudioHandler(options) case "gemini": return new GeminiHandler(options) - case "gemini-cli": - return new GeminiCliHandler(options) case "openai-native": return new OpenAiNativeHandler(options) case "deepseek": diff --git a/src/api/providers/gemini-cli.ts b/src/api/providers/gemini-cli.ts deleted file mode 100644 index 9cedea10..00000000 --- a/src/api/providers/gemini-cli.ts +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Gemini CLI Provider - OAuth-based API Handler - * - * This implementation provides access to Google's Gemini models through OAuth authentication, - * leveraging the same authentication mechanism as the official Gemini CLI tool. - * - * Attribution: This implementation is inspired by and uses concepts from the Google Gemini CLI, - * which is licensed under the Apache License 2.0. - * Original project: https://github.com/google-gemini/gemini-cli - * - * Copyright 2025 Google LLC - * Licensed under the Apache License, Version 2.0 - * - * Key features: - * - OAuth2 authentication (no API keys required) - * - Auto-discovery of Google Cloud project IDs - * - Real-time streaming via Server-Sent Events - * - Free tier access through Google's Code Assist API - * - Compatible with personal Google accounts only - */ - -import type { Anthropic } from "@anthropic-ai/sdk" -import { OAuth2Client } from "google-auth-library" -import fs from "fs/promises" -import path from "path" -import os from "os" -import * as readline from "readline" -import { Readable } from "stream" -import { ApiHandler } from "../" -import { ApiHandlerOptions, GeminiCliModelId, geminiCliModels, ModelInfo, geminiCliDefaultModelId } from "@shared/api" -import { convertAnthropicMessageToGemini } from "../transform/gemini-format" -import { ApiStream } from "../transform/stream" -import { withRetry } from "../retry" - -const CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com" -const CODE_ASSIST_API_VERSION = "v1internal" - -// OAuth configuration -const OAUTH_CLIENT_ID = "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com" -// Change this line in setup.js: -const OAUTH_CLIENT_SECRET = "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" - -const OAUTH_REDIRECT_URI = "http://localhost:45289" - -interface OAuthCredentials { - access_token: string - refresh_token: string - scope: string - token_type: string - expiry_date: number -} - -interface GeminiCliHandlerOptions extends ApiHandlerOptions { - geminiCliOAuthPath?: string - geminiCliProjectId?: string -} - -/** - * Handler for Google's Gemini API via OAuth (Gemini CLI style). - * - * This provider uses OAuth authentication instead of API keys, making it suitable - * for users who have already authenticated with the Gemini CLI tool. - * It automatically discovers project IDs and works with the free tier. - */ -export class GeminiCliHandler implements ApiHandler { - private options: GeminiCliHandlerOptions - private authClient: OAuth2Client - private projectId: string | null = null - private authInitialized: boolean = false - - constructor(options: GeminiCliHandlerOptions) { - this.options = options - this.authClient = new OAuth2Client(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_REDIRECT_URI) - } - - /** - * Load OAuth credentials from the file system - */ - private async loadOAuthCredentials(): Promise { - const credPath = this.options.geminiCliOAuthPath || path.join(os.homedir(), ".gemini", "oauth_creds.json") - try { - const data = await fs.readFile(credPath, "utf8") - return JSON.parse(data) - } catch (err) { - throw new Error(`Failed to load OAuth credentials from ${credPath}. Please authenticate with 'gemini auth' first.`) - } - } - - /** - * Call a Code Assist API endpoint - */ - private async callEndpoint(method: string, body: any, retryAuth: boolean = true): Promise { - console.log(`[GeminiCLI] Calling endpoint: ${method}`) - console.log(`[GeminiCLI] Request body:`, JSON.stringify(body, null, 2)) - - try { - const res = await this.authClient.request({ - url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:${method}`, - method: "POST", - headers: { - "Content-Type": "application/json", - }, - responseType: "json", - body: JSON.stringify(body), - }) - console.log(`[GeminiCLI] Response status:`, res.status) - console.log(`[GeminiCLI] Response data:`, JSON.stringify(res.data, null, 2)) - return res.data - } catch (error: any) { - console.error(`[GeminiCLI] Error calling ${method}:`, error) - console.error(`[GeminiCLI] Error response:`, error.response?.data) - console.error(`[GeminiCLI] Error status:`, error.response?.status) - console.error(`[GeminiCLI] Error message:`, error.message) - - // If we get a 401 and haven't retried yet, try refreshing auth - if (error.response?.status === 401 && retryAuth) { - console.log(`[GeminiCLI] Got 401, attempting to refresh authentication...`) - await this.initializeAuth(true) // Force refresh - return this.callEndpoint(method, body, false) // Retry without further auth retries - } - - throw error - } - } - - /** - * Discover or retrieve the project ID - */ - private async discoverProjectId(): Promise { - // If we already have a project ID, use it - if (this.options.geminiCliProjectId) { - return this.options.geminiCliProjectId - } - - // If we've already discovered it, return it - if (this.projectId) { - return this.projectId - } - - // Start with a default project ID (can be anything for personal OAuth) - const initialProjectId = "default" - - // Prepare client metadata - const clientMetadata = { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - duetProject: initialProjectId, - } - - try { - // Call loadCodeAssist to discover the actual project ID - const loadRequest = { - cloudaicompanionProject: initialProjectId, - metadata: clientMetadata, - } - - const loadResponse = await this.callEndpoint("loadCodeAssist", loadRequest) - - // Check if we already have a project ID from the response - if (loadResponse.cloudaicompanionProject) { - this.projectId = loadResponse.cloudaicompanionProject - return this.projectId as string - } - - // If no existing project, we need to onboard - const defaultTier = loadResponse.allowedTiers?.find((tier: any) => tier.isDefault) - const tierId = defaultTier?.id || "free-tier" - - const onboardRequest = { - tierId: tierId, - cloudaicompanionProject: initialProjectId, - metadata: clientMetadata, - } - - let lroResponse = await this.callEndpoint("onboardUser", onboardRequest) - - // Poll until operation is complete - while (!lroResponse.done) { - await new Promise((resolve) => setTimeout(resolve, 2000)) - lroResponse = await this.callEndpoint("onboardUser", onboardRequest) - } - - const discoveredProjectId = lroResponse.response?.cloudaicompanionProject?.id || initialProjectId - this.projectId = discoveredProjectId - return this.projectId as string - } catch (error: any) { - console.error("Failed to discover project ID:", error.response?.data || error.message) - throw new Error("Could not discover project ID. Make sure you're authenticated with 'gemini auth'.") - } - } - - /** - * Initialize the OAuth client with credentials - */ - private async initializeAuth(forceRefresh: boolean = false): Promise { - // Check if we need to initialize or refresh - if (this.authInitialized && !forceRefresh) { - // Check if token is still valid - const credentials = this.authClient.credentials - if (credentials && credentials.expiry_date && Date.now() < credentials.expiry_date) { - console.log(`[GeminiCLI] Auth already initialized and token still valid`) - return - } - } - - console.log(`[GeminiCLI] Initializing OAuth authentication...`) - const credentials = await this.loadOAuthCredentials() - const isExpired = credentials.expiry_date ? Date.now() > credentials.expiry_date : false - - console.log(`[GeminiCLI] Loaded credentials:`, { - hasAccessToken: !!credentials.access_token, - hasRefreshToken: !!credentials.refresh_token, - tokenType: credentials.token_type, - expiryDate: credentials.expiry_date, - isExpired: isExpired, - }) - - this.authClient.setCredentials(credentials) - - // If token is expired and we have a refresh token, try to refresh - if (isExpired && credentials.refresh_token) { - console.log(`[GeminiCLI] Token expired, attempting to refresh...`) - try { - const { credentials: newCredentials } = await this.authClient.refreshAccessToken() - console.log(`[GeminiCLI] Token refreshed successfully`) - // Note: In a real implementation, you'd want to save the new credentials back to the file - // For now, we'll just use them in memory - } catch (error) { - console.error(`[GeminiCLI] Failed to refresh token:`, error) - // Continue with the expired token - the API might still accept it - } - } - - this.authInitialized = true - console.log(`[GeminiCLI] OAuth client configured`) - } - - /** - * Parse Server-Sent Events from a stream - */ - private async *parseSSEStream(stream: Readable): AsyncGenerator { - const rl = readline.createInterface({ - input: stream, - crlfDelay: Infinity, - }) - - let bufferedLines: string[] = [] - - for await (const line of rl) { - // Blank lines separate JSON objects in the stream - if (line === "") { - if (bufferedLines.length === 0) { - continue - } - - try { - const jsonData = JSON.parse(bufferedLines.join("\n")) - yield jsonData - } catch (parseError) { - console.error("Error parsing JSON chunk:", parseError) - } - - bufferedLines = [] - } else if (line.startsWith("data: ")) { - bufferedLines.push(line.slice(6).trim()) - } - } - - // Process any remaining buffered content - if (bufferedLines.length > 0) { - try { - const jsonData = JSON.parse(bufferedLines.join("\n")) - yield jsonData - } catch (parseError) { - console.error("Error parsing final buffered content:", parseError) - } - } - } - - /** - * Create a message using the Gemini CLI OAuth API - */ - @withRetry({ - maxRetries: 2, - baseDelay: 2000, - maxDelay: 10000, - }) - async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { - // Initialize auth if not already done - await this.initializeAuth() - // Discover project ID if needed - const projectId = await this.discoverProjectId() - - // Convert messages to Gemini format - const contents = messages.map(convertAnthropicMessageToGemini) - - // Get the selected model - const { id: modelId, info: modelInfo } = this.getModel() - - // Build the request - const streamRequest = { - model: modelId, - project: projectId, - request: { - contents: [ - { - role: "user", - parts: [{ text: systemPrompt }], - }, - ...contents, - ], - generationConfig: { - temperature: 0.7, - maxOutputTokens: modelInfo.maxTokens || 8192, - }, - }, - } - - let totalContent = "" - let promptTokens = 0 - let outputTokens = 0 - let lastUsageMetadata: any = null - - try { - // Make the streaming request - const response = await this.authClient.request({ - url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:streamGenerateContent`, - method: "POST", - params: { alt: "sse" }, - headers: { - "Content-Type": "application/json", - }, - responseType: "stream", - body: JSON.stringify(streamRequest), - }) - - // Process the SSE stream - for await (const jsonData of this.parseSSEStream(response.data as Readable)) { - // Extract content from the response - const candidate = jsonData.response?.candidates?.[0] - if (candidate?.content?.parts?.[0]?.text) { - const content = candidate.content.parts[0].text - totalContent += content - - // Yield text chunk - yield { - type: "text", - text: content, - } - } - - // Store usage metadata for final reporting - if (jsonData.response?.usageMetadata) { - lastUsageMetadata = jsonData.response.usageMetadata - promptTokens = lastUsageMetadata.promptTokenCount || promptTokens - outputTokens = lastUsageMetadata.candidatesTokenCount || outputTokens - } - - // Check if this is the final chunk - if (candidate?.finishReason) { - break - } - } - - // Yield usage information - if (lastUsageMetadata) { - yield { - type: "usage", - inputTokens: promptTokens, - outputTokens: outputTokens, - totalCost: 0, // Free tier - } - } - } catch (error) { - // Handle rate limit errors similar to the Gemini provider - if (error instanceof Error) { - // Check for rate limit patterns in the error message - const rateLimitPatterns = [ - /got status: 429/i, - /429 Too Many Requests/i, - /rate limit exceeded/i, - /too many requests/i, - /quota exceeded/i, - /resource exhausted/i, - /code 429/i, - ] - - const isRateLimit = rateLimitPatterns.some((pattern) => pattern.test(error.message)) - - if (isRateLimit) { - const rateLimitError = Object.assign(new Error(error.message), { - ...error, - status: 429, - }) - throw rateLimitError - } - } - - // Re-throw the original error if it's not a rate limit error - throw error - } - } - - /** - * Get the model ID and info - */ - getModel(): { id: GeminiCliModelId; info: ModelInfo } { - const modelId = this.options.apiModelId as GeminiCliModelId - if (modelId && modelId in geminiCliModels) { - return { id: modelId, info: geminiCliModels[modelId] } - } - return { - id: geminiCliDefaultModelId, - info: geminiCliModels[geminiCliDefaultModelId], - } - } -} diff --git a/src/shared/api.ts b/src/shared/api.ts index 8efb13c9..f4f09edc 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -10,7 +10,6 @@ export type ApiProvider = | "ollama" | "lmstudio" | "gemini" - | "gemini-cli" | "openai-native" | "requesty" | "together" @@ -70,8 +69,6 @@ export interface ApiHandlerOptions { lmStudioBaseUrl?: string geminiApiKey?: string geminiBaseUrl?: string - geminiCliOAuthPath?: string - geminiCliProjectId?: string openAiNativeApiKey?: string deepSeekApiKey?: string requestyApiKey?: string @@ -878,138 +875,6 @@ export const geminiModels = { }, } as const satisfies Record -// Gemini CLI (OAuth-based) -export type GeminiCliModelId = keyof typeof geminiCliModels -export const geminiCliDefaultModelId: GeminiCliModelId = "gemini-2.5-flash" -export const geminiCliModels = { - "gemini-2.5-pro": { - maxTokens: 65536, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, // Free tier via OAuth - outputPrice: 0, // Free tier via OAuth - description: "Google's Gemini 2.5 Pro model via OAuth (free tier)", - }, - "gemini-2.5-flash": { - maxTokens: 65536, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, // Free tier via OAuth - outputPrice: 0, // Free tier via OAuth - description: "Google's Gemini 2.5 Flash model via OAuth (free tier)", - }, - "gemini-2.0-flash-001": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, // Free tier via OAuth - outputPrice: 0, // Free tier via OAuth - description: "Google's Gemini 2.0 Flash model via OAuth (free tier)", - }, - "gemini-2.0-flash-lite-preview-02-05": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 2.0 Flash Lite Preview model via OAuth", - }, - "gemini-2.0-pro-exp-02-05": { - maxTokens: 8192, - contextWindow: 2_097_152, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 2.0 Pro Experimental model via OAuth", - }, - "gemini-2.0-flash-thinking-exp-01-21": { - maxTokens: 65_536, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 2.0 Flash Thinking Experimental model via OAuth", - }, - "gemini-2.0-flash-thinking-exp-1219": { - maxTokens: 8192, - contextWindow: 32_767, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 2.0 Flash Thinking Experimental (1219) model via OAuth", - }, - "gemini-2.0-flash-exp": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 2.0 Flash Experimental model via OAuth", - }, - "gemini-1.5-flash-002": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, // Free tier via OAuth - outputPrice: 0, // Free tier via OAuth - description: "Google's Gemini 1.5 Flash 002 model via OAuth (free tier)", - }, - "gemini-1.5-flash-exp-0827": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 1.5 Flash Experimental (0827) model via OAuth", - }, - "gemini-1.5-flash-8b-exp-0827": { - maxTokens: 8192, - contextWindow: 1_048_576, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 1.5 Flash 8B Experimental model via OAuth", - }, - "gemini-1.5-pro-002": { - maxTokens: 8192, - contextWindow: 2_097_152, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 1.5 Pro 002 model via OAuth", - }, - "gemini-1.5-pro-exp-0827": { - maxTokens: 8192, - contextWindow: 2_097_152, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini 1.5 Pro Experimental model via OAuth", - }, - "gemini-exp-1206": { - maxTokens: 8192, - contextWindow: 2_097_152, - supportsImages: true, - supportsPromptCache: false, - inputPrice: 0, - outputPrice: 0, - description: "Google's Gemini Experimental (1206) model via OAuth", - }, -} as const satisfies Record - // OpenAI Native // https://openai.com/api/pricing/ export type OpenAiNativeModelId = keyof typeof openAiNativeModels diff --git a/src/shared/proto-conversions/models/api-configuration-conversion.ts b/src/shared/proto-conversions/models/api-configuration-conversion.ts index 262f5f08..595a983e 100644 --- a/src/shared/proto-conversions/models/api-configuration-conversion.ts +++ b/src/shared/proto-conversions/models/api-configuration-conversion.ts @@ -202,8 +202,6 @@ function convertApiProviderToProto(provider: string | undefined): ProtoApiProvid return ProtoApiProvider.LMSTUDIO case "gemini": return ProtoApiProvider.GEMINI - case "gemini-cli": - return ProtoApiProvider.GEMINI_CLI case "openai-native": return ProtoApiProvider.OPENAI_NATIVE case "requesty": @@ -264,8 +262,6 @@ function convertProtoToApiProvider(provider: ProtoApiProvider): ApiProvider { return "lmstudio" case ProtoApiProvider.GEMINI: return "gemini" - case ProtoApiProvider.GEMINI_CLI: - return "gemini-cli" case ProtoApiProvider.OPENAI_NATIVE: return "openai-native" case ProtoApiProvider.REQUESTY: @@ -383,8 +379,6 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA sapAiCoreTokenUrl: config.sapAiCoreTokenUrl, sapAiCoreBaseUrl: config.sapAiCoreBaseUrl, claudeCodePath: config.claudeCodePath, - geminiCliOauthPath: config.geminiCliOAuthPath, - geminiCliProjectId: config.geminiCliProjectId, } } @@ -464,7 +458,5 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio sapAiCoreTokenUrl: protoConfig.sapAiCoreTokenUrl, sapAiCoreBaseUrl: protoConfig.sapAiCoreBaseUrl, claudeCodePath: protoConfig.claudeCodePath, - geminiCliOAuthPath: protoConfig.geminiCliOauthPath, - geminiCliProjectId: protoConfig.geminiCliProjectId, } } diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 848bb415..d948671c 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -974,85 +974,15 @@ export const ChatRowContent = memo( apiRequestFailedMessage?.toLowerCase().includes("resource exhausted") if (isRateLimitError) { - // Check if current provider is Gemini CLI to show specific message - const isGeminiCliProvider = apiConfiguration?.apiProvider === "gemini-cli" - - if (isGeminiCliProvider) { - return ( -
-
- - - Rate Limit Exceeded - -
-

- You've hit the API rate limit. This is likely due to free tier - limits. -

-

- You can read about the tier limits{" "} - { - e.preventDefault() - UiServiceClient.openUrl( - StringRequest.create({ - value: "https://codeassist.google/", - }), - ).catch((err) => - console.error("Failed to open URL:", err), - ) - }}> - here - - , or alternatively, you can use the Gemini Flash Model that will - give you better limits. -

-
- ) - } else { - // Generic rate limit error for other providers - return ( -

- {apiRequestFailedMessage || apiReqStreamingFailedMessage} -

- ) - } + return ( +

+ {apiRequestFailedMessage || apiReqStreamingFailedMessage} +

+ ) } // Default error display diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 995a1877..661e9222 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -26,7 +26,6 @@ import { GeminiProvider } from "./providers/GeminiProvider" import { DoubaoProvider } from "./providers/DoubaoProvider" import { QwenProvider } from "./providers/QwenProvider" import { VertexProvider } from "./providers/VertexProvider" -import GeminiCliProvider from "./providers/GeminiCliProvider" import { RequestyProvider } from "./providers/RequestyProvider" import { FireworksProvider } from "./providers/FireworksProvider" import { XaiProvider } from "./providers/XaiProvider" @@ -175,7 +174,6 @@ const ApiOptions = ({ OpenAI Compatible GCP Vertex AI Google Gemini - Gemini CLI Provider DeepSeek Mistral OpenAI @@ -347,15 +345,6 @@ const ApiOptions = ({ /> )} - {apiConfiguration && selectedProvider === "gemini-cli" && ( - - )} - {apiConfiguration && selectedProvider === "requesty" && ( 0 @@ -170,7 +170,7 @@ export const ModelInfoView = ({ selectedModelId, modelInfo, isPopup }: ModelInfo supportsLabel="Supports browser use" doesNotSupportLabel="Does not support browser use" />, - !isGeminiProvider && ( + !isGemini && ( ), outputPriceElement, // Add the generated output price block - isGeminiProvider && ( - - - For more info, see pricing details. - - - ), ].filter(Boolean) return ( diff --git a/webview-ui/src/components/settings/providers/GeminiCliProvider.tsx b/webview-ui/src/components/settings/providers/GeminiCliProvider.tsx deleted file mode 100644 index c1346c01..00000000 --- a/webview-ui/src/components/settings/providers/GeminiCliProvider.tsx +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Gemini CLI Provider Component - * - * This component integrates with Google's Gemini CLI tool for OAuth authentication. - * - * Attribution: This implementation is inspired by and uses concepts from the Google Gemini CLI, - * which is licensed under the Apache License 2.0. - * Original project: https://github.com/google-gemini/gemini-cli - * - * Copyright 2025 Google LLC - * Licensed under the Apache License, Version 2.0 - */ - -import { ApiConfiguration, geminiCliModels } from "@shared/api" -import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" -import { memo } from "react" -import { ModelSelector } from "../common/ModelSelector" -import { ModelInfoView } from "../common/ModelInfoView" -import { normalizeApiConfiguration } from "../utils/providerUtils" - -interface GeminiCliProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void - showModelOptions: boolean - isPopup?: boolean -} - -const GeminiCliProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: GeminiCliProviderProps) => { - // Get the normalized configuration - const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) - return ( -
- - OAuth Credentials Path (optional) - -

- Path to the OAuth credentials file. Leave empty to use the default location (~/.gemini/oauth_creds.json). -

- - {apiConfiguration?.geminiCliProjectId && ( - <> - - Discovered Project ID - -

- This project ID was automatically discovered from your OAuth credentials. -

- - )} - -

- This provider uses OAuth authentication from the Gemini CLI tool and does not require API keys. If you haven't - authenticated yet, please run{" "} - - gemini - {" "} - in your terminal first. -
- - Gemini CLI Setup Instructions - -

- - {showModelOptions && ( - <> - - - - - )} - -
-
- - - Important Requirements - -
-

- • First, you need to install the Gemini CLI tool -
• Then, run gemini in your terminal and make sure you{" "} - Log in with Google -
• Only works with personal Google accounts (not Google Workspace accounts) -
- • Does not use API keys - authentication is handled via OAuth -
• Requires the Gemini CLI tool to be installed and authenticated first -

-
- -

- ✓ Free tier access via OAuth authentication -

-
- ) -} - -export default memo(GeminiCliProvider) diff --git a/webview-ui/src/components/settings/utils/providerUtils.ts b/webview-ui/src/components/settings/utils/providerUtils.ts index 154222d8..bcfc9b85 100644 --- a/webview-ui/src/components/settings/utils/providerUtils.ts +++ b/webview-ui/src/components/settings/utils/providerUtils.ts @@ -10,8 +10,6 @@ import { deepSeekModels, geminiDefaultModelId, geminiModels, - geminiCliDefaultModelId, - geminiCliModels, mistralDefaultModelId, mistralModels, openAiModelInfoSaneDefaults, @@ -98,8 +96,6 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration): return getProviderData(vertexModels, vertexDefaultModelId) case "gemini": return getProviderData(geminiModels, geminiDefaultModelId) - case "gemini-cli": - return getProviderData(geminiCliModels, geminiCliDefaultModelId) case "openai-native": return getProviderData(openAiNativeModels, openAiNativeDefaultModelId) case "deepseek": From 037a781a6d3404c84800b9589fe26077dd7242d1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 28 Jun 2025 18:38:32 -0700 Subject: [PATCH 33/60] v3.18.1 Release Notes - Add support for Claude 4 Sonnet in SAP AI Core provider (Thanks @GTxx!) - Fix ENAMETOOLONG error when using Claude Code provider with long conversation histories (Thanks @BarreiroT!) - Remove Gemini CLI provider because Google asked us to - Fix bug with "Delete All Tasks" functionality --- .changeset/chilled-paws-remain.md | 5 ----- .changeset/sharp-singers-tie.md | 5 ----- .changeset/strong-glasses-bathe.md | 5 ----- .changeset/tall-elephants-sort.md | 5 ----- .changeset/yellow-gifts-explain.md | 5 ----- .changeset/young-bulldogs-raise.md | 5 ----- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 9 files changed, 10 insertions(+), 33 deletions(-) delete mode 100644 .changeset/chilled-paws-remain.md delete mode 100644 .changeset/sharp-singers-tie.md delete mode 100644 .changeset/strong-glasses-bathe.md delete mode 100644 .changeset/tall-elephants-sort.md delete mode 100644 .changeset/yellow-gifts-explain.md delete mode 100644 .changeset/young-bulldogs-raise.md diff --git a/.changeset/chilled-paws-remain.md b/.changeset/chilled-paws-remain.md deleted file mode 100644 index 856222e0..00000000 --- a/.changeset/chilled-paws-remain.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Fix ENAMETOOLONG when calling Claude Code diff --git a/.changeset/sharp-singers-tie.md b/.changeset/sharp-singers-tie.md deleted file mode 100644 index f22544e2..00000000 --- a/.changeset/sharp-singers-tie.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": minor ---- - -Support Sonnet-4 in SAP AI Core provider diff --git a/.changeset/strong-glasses-bathe.md b/.changeset/strong-glasses-bathe.md deleted file mode 100644 index 44de2844..00000000 --- a/.changeset/strong-glasses-bathe.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Reverting Gemini Cli provider diff --git a/.changeset/tall-elephants-sort.md b/.changeset/tall-elephants-sort.md deleted file mode 100644 index 17121ee6..00000000 --- a/.changeset/tall-elephants-sort.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Removed deleteNonFavoritedTasks, moved popup to extension, cleaned up deletion logic diff --git a/.changeset/yellow-gifts-explain.md b/.changeset/yellow-gifts-explain.md deleted file mode 100644 index 2d1efdff..00000000 --- a/.changeset/yellow-gifts-explain.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -host bridge migration - clipboard diff --git a/.changeset/young-bulldogs-raise.md b/.changeset/young-bulldogs-raise.md deleted file mode 100644 index bba9851e..00000000 --- a/.changeset/young-bulldogs-raise.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"claude-dev": patch ---- - -Refactor task class, moving auto approve diff --git a/CHANGELOG.md b/CHANGELOG.md index a8936d60..981c16fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [3.18.1] + +- Add support for Claude 4 Sonnet in SAP AI Core provider (Thanks @GTxx!) +- Fix ENAMETOOLONG error when using Claude Code provider with long conversation histories (Thanks @BarreiroT!) +- Remove Gemini CLI provider because Google asked us to +- Fix bug with "Delete All Tasks" functionality + ## [3.18.0] - Optimized Cline to work with the Claude 4 family of models, resulting in improved performance, reliability, and new capabilities diff --git a/package-lock.json b/package-lock.json index 4bc2cfeb..585c7f5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-dev", - "version": "3.18.0", + "version": "3.18.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "claude-dev", - "version": "3.18.0", + "version": "3.18.1", "license": "Apache-2.0", "dependencies": { "@anthropic-ai/sdk": "^0.37.0", diff --git a/package.json b/package.json index 4880ead9..ec77a82a 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "claude-dev", "displayName": "Cline", "description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.", - "version": "3.18.0", + "version": "3.18.1", "icon": "assets/icons/icon.png", "engines": { "vscode": "^1.84.0" From 09c773bd5fd57ef0db8314c1f6588fda535e79fd Mon Sep 17 00:00:00 2001 From: Lize Cai Date: Tue, 1 Jul 2025 01:24:45 +0800 Subject: [PATCH 34/60] Add Claude 4 model to SAP AI Core Provider (#4418) * add claude 4 support to sap aicore Signed-off-by: Lize Cai * add changelog Signed-off-by: Lize Cai * update model-utils to capture other naming for claude 4. Signed-off-by: Lize Cai * add claude 4 opus as well Signed-off-by: Lize Cai --------- Signed-off-by: Lize Cai --- .changeset/lovely-readers-design.md | 5 +++++ src/api/providers/sapaicore.ts | 13 +++++++++++-- src/shared/api.ts | 8 ++++++++ src/utils/model-utils.ts | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 .changeset/lovely-readers-design.md diff --git a/.changeset/lovely-readers-design.md b/.changeset/lovely-readers-design.md new file mode 100644 index 00000000..7e3a6b53 --- /dev/null +++ b/.changeset/lovely-readers-design.md @@ -0,0 +1,5 @@ +--- +"claude-dev": minor +--- + +Add Claude Sonnet 4 and Opus 4 model in SAP AI Core provider. diff --git a/src/api/providers/sapaicore.ts b/src/api/providers/sapaicore.ts index 4101ff0b..93724aa4 100644 --- a/src/api/providers/sapaicore.ts +++ b/src/api/providers/sapaicore.ts @@ -123,6 +123,7 @@ export class SapAiCoreHandler implements ApiHandler { const anthropicModels = [ "anthropic--claude-4-sonnet", + "anthropic--claude-4-opus", "anthropic--claude-3.7-sonnet", "anthropic--claude-3.5-sonnet", "anthropic--claude-3-sonnet", @@ -137,7 +138,11 @@ export class SapAiCoreHandler implements ApiHandler { if (anthropicModels.includes(model.id)) { url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/invoke-with-response-stream` - if (model.id === "anthropic--claude-3.7-sonnet" || model.id === "anthropic--claude-4-sonnet") { + if ( + model.id === "anthropic--claude-4-sonnet" || + model.id === "anthropic--claude-4-opus" || + model.id === "anthropic--claude-3.7-sonnet" + ) { url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/converse-stream` payload = { inferenceConfig: { @@ -222,7 +227,11 @@ export class SapAiCoreHandler implements ApiHandler { } } else if (openAIModels.includes(model.id)) { yield* this.streamCompletionGPT(response.data, model) - } else if (model.id === "anthropic--claude-3.7-sonnet" || model.id === "anthropic--claude-4-sonnet") { + } else if ( + model.id === "anthropic--claude-4-sonnet" || + model.id === "anthropic--claude-4-opus" || + model.id === "anthropic--claude-3.7-sonnet" + ) { yield* this.streamCompletionSonnet37(response.data, model) } else { yield* this.streamCompletion(response.data, model) diff --git a/src/shared/api.ts b/src/shared/api.ts index f4f09edc..3026e3f8 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -2382,6 +2382,14 @@ export const sapAiCoreModels = { inputPrice: 3.0, outputPrice: 15.0, }, + "anthropic--claude-4-opus": { + maxTokens: 8192, + contextWindow: 200_000, + supportsImages: true, + supportsPromptCache: false, + inputPrice: 3.0, + outputPrice: 15.0, + }, "anthropic--claude-3.7-sonnet": { maxTokens: 64_000, contextWindow: 200_000, diff --git a/src/utils/model-utils.ts b/src/utils/model-utils.ts index 014a420a..35c78bb1 100644 --- a/src/utils/model-utils.ts +++ b/src/utils/model-utils.ts @@ -2,7 +2,7 @@ import { ApiHandler } from "@api/index" export function isClaude4ModelFamily(api: ApiHandler): boolean { const model = api.getModel() - const modelId = model.id + const modelId = model.id.toLowerCase() return ( modelId.includes("sonnet-4") || modelId.includes("opus-4") || modelId.includes("4-sonnet") || modelId.includes("4-opus") ) From 27a531c86af8c97e58120860ee80e7028cec1390 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Mon, 30 Jun 2025 10:47:18 -0700 Subject: [PATCH 35/60] [SettingsView.tsx] Extract About Section (#4537) * refactor out apiconfig section * add general settings section * duplicate import * move terminal, browser, and feature settings * move files to sections folder * refactor out debug section * pull out about section --- .../src/components/settings/SettingsView.tsx | 16 ++--------- .../settings/sections/AboutSection.tsx | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 14 deletions(-) create mode 100644 webview-ui/src/components/settings/sections/AboutSection.tsx diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 02540f56..055e1743 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -20,6 +20,7 @@ import ApiConfigurationSection from "./sections/ApiConfigurationSection" import GeneralSettingsSection from "./sections/GeneralSettingsSection" import BrowserSettingsSection from "./sections/BrowserSettingsSection" import DebugSection from "./sections/DebugSection" +import AboutSection from "./sections/AboutSection" import { convertApiConfigurationToProtoApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" @@ -806,20 +807,7 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { {/* About Tab */} {activeTab === "about" && ( -
- {renderSectionHeader("about")} -
-
-

- If you have any questions or feedback, feel free to open an issue at{" "} - - https://github.com/cline/cline - -

-

v{version}

-
-
-
+ )} ) diff --git a/webview-ui/src/components/settings/sections/AboutSection.tsx b/webview-ui/src/components/settings/sections/AboutSection.tsx new file mode 100644 index 00000000..4ea7464c --- /dev/null +++ b/webview-ui/src/components/settings/sections/AboutSection.tsx @@ -0,0 +1,28 @@ +import Section from "../Section" +import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" + +interface AboutSectionProps { + version: string + renderSectionHeader: (tabId: string) => JSX.Element | null +} + +const AboutSection = ({ version, renderSectionHeader }: AboutSectionProps) => { + return ( +
+ {renderSectionHeader("about")} +
+
+

+ If you have any questions or feedback, feel free to open an issue at{" "} + + https://github.com/cline/cline + +

+

v{version}

+
+
+
+ ) +} + +export default AboutSection From e6760ed6cc3e194ccaee515f8a4afee12ba38371 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Mon, 30 Jun 2025 11:33:00 -0700 Subject: [PATCH 36/60] race (#4583) --- src/core/controller/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 688c818b..9d4530e8 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -702,7 +702,7 @@ export class Controller { await setTimeoutPromise(100) // Post message to webview with the selected code - const fileMention = this.getFileMentionFromPath(filePath) + const fileMention = await this.getFileMentionFromPath(filePath) let input = `${fileMention}\n\`\`\`\n${code}\n\`\`\`` if (diagnostics) { @@ -739,7 +739,7 @@ export class Controller { await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus") await setTimeoutPromise(100) - const fileMention = this.getFileMentionFromPath(filePath) + const fileMention = await this.getFileMentionFromPath(filePath) const problemsString = this.convertDiagnosticsToProblemsString(diagnostics) await this.initTask(`Fix the following code in ${fileMention}\n\`\`\`\n${code}\n\`\`\`\n\nProblems:\n${problemsString}`) @@ -918,7 +918,7 @@ export class Controller { if (this.task) { await telemetryService.sendCollectedEvents(this.task.taskId) } - this.task?.abortTask() + await this.task?.abortTask() this.task = undefined // removes reference to it, so once promises end it will be garbage collected } From 9e69576fb0abd4ab312881443496325dcd1b77f4 Mon Sep 17 00:00:00 2001 From: Ara Date: Tue, 1 Jul 2025 02:25:25 +0530 Subject: [PATCH 37/60] Splitting chat view into multiple modular files (#4569) * Splitting chat view into multiple modular files * Adding Comments and removing redundancies --------- Co-authored-by: Cline Evaluation --- .changeset/gold-berries-give.md | 5 + .../src/components/chat/ChatTextArea.tsx | 6 +- webview-ui/src/components/chat/ChatView.tsx | 1114 ++--------------- .../components/layout/ActionButtons.tsx | 100 ++ .../components/layout/ChatLayout.tsx | 26 + .../components/layout/InputSection.tsx | 78 ++ .../components/layout/MessagesArea.tsx | 98 ++ .../components/layout/TaskSection.tsx | 50 + .../components/layout/WelcomeSection.tsx | 43 + .../chat/chat-view/components/layout/index.ts | 10 + .../components/messages/MessageRenderer.tsx | 103 ++ .../messages/StreamingIndicator.tsx | 93 ++ .../chat-view/components/messages/index.ts | 6 + .../components/chat/chat-view/constants.ts | 7 + .../components/chat/chat-view/hooks/index.ts | 8 + .../chat/chat-view/hooks/useButtonState.ts | 160 +++ .../chat/chat-view/hooks/useChatState.ts | 96 ++ .../chat-view/hooks/useMessageHandlers.ts | 270 ++++ .../chat/chat-view/hooks/useScrollBehavior.ts | 232 ++++ .../src/components/chat/chat-view/index.ts | 21 + .../chat/chat-view/types/chatTypes.ts | 172 +++ .../chat/chat-view/utils/markdownUtils.ts | 58 + .../chat/chat-view/utils/messageUtils.ts | 151 +++ .../chat/chat-view/utils/scrollUtils.ts | 60 + 24 files changed, 1954 insertions(+), 1013 deletions(-) create mode 100644 .changeset/gold-berries-give.md create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/ChatLayout.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/layout/index.ts create mode 100644 webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx create mode 100644 webview-ui/src/components/chat/chat-view/components/messages/index.ts create mode 100644 webview-ui/src/components/chat/chat-view/constants.ts create mode 100644 webview-ui/src/components/chat/chat-view/hooks/index.ts create mode 100644 webview-ui/src/components/chat/chat-view/hooks/useButtonState.ts create mode 100644 webview-ui/src/components/chat/chat-view/hooks/useChatState.ts create mode 100644 webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts create mode 100644 webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts create mode 100644 webview-ui/src/components/chat/chat-view/index.ts create mode 100644 webview-ui/src/components/chat/chat-view/types/chatTypes.ts create mode 100644 webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts create mode 100644 webview-ui/src/components/chat/chat-view/utils/messageUtils.ts create mode 100644 webview-ui/src/components/chat/chat-view/utils/scrollUtils.ts diff --git a/.changeset/gold-berries-give.md b/.changeset/gold-berries-give.md new file mode 100644 index 00000000..845c8c72 --- /dev/null +++ b/.changeset/gold-berries-give.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Refactor chat view into multiple modular files diff --git a/webview-ui/src/components/chat/ChatTextArea.tsx b/webview-ui/src/components/chat/ChatTextArea.tsx index 7f52262f..a008aa93 100644 --- a/webview-ui/src/components/chat/ChatTextArea.tsx +++ b/webview-ui/src/components/chat/ChatTextArea.tsx @@ -1,4 +1,6 @@ -import { MAX_IMAGES_AND_FILES_PER_MESSAGE } from "@/components/chat/ChatView" +import { CHAT_CONSTANTS } from "@/components/chat/chat-view/constants" + +const { MAX_IMAGES_AND_FILES_PER_MESSAGE } = CHAT_CONSTANTS import ContextMenu from "@/components/chat/ContextMenu" import SlashCommandMenu from "@/components/chat/SlashCommandMenu" import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" @@ -29,10 +31,8 @@ import { validateSlashCommand, } from "@/utils/slash-commands" import { validateApiConfiguration, validateModelId } from "@/utils/validate" -import { vscode } from "@/utils/vscode" import { ChatSettings } from "@shared/ChatSettings" import { mentionRegex, mentionRegexGlobal } from "@shared/context-mentions" -import { ExtensionMessage } from "@shared/ExtensionMessage" import { EmptyRequest, StringRequest } from "@shared/proto/common" import { FileSearchRequest, RelativePathsRequest } from "@shared/proto/file" import { UpdateApiConfigurationRequest } from "@shared/proto/models" diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index 2e4844e6..734436f5 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -1,42 +1,33 @@ -import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" -import debounce from "debounce" -import { useCallback, useEffect, useMemo, useRef, useState } from "react" -import { useDeepCompareEffect, useEvent, useMount } from "react-use" -import { Virtuoso, type VirtuosoHandle } from "react-virtuoso" -import styled from "styled-components" -import { - ClineApiReqInfo, - ClineAsk, - ClineMessage, - ClineSayBrowserAction, - ClineSayTool, - ExtensionMessage, -} from "@shared/ExtensionMessage" +import { useCallback, useEffect, useMemo } from "react" +import { useMount } from "react-use" +import { ClineApiReqInfo, ClineMessage } from "@shared/ExtensionMessage" import { findLast } from "@shared/array" import { combineApiRequests } from "@shared/combineApiRequests" import { combineCommandSequences } from "@shared/combineCommandSequences" import { getApiMetrics } from "@shared/getApiMetrics" import { useExtensionState } from "@/context/ExtensionStateContext" -import { vscode } from "@/utils/vscode" -import { TaskServiceClient, SlashServiceClient, FileServiceClient, UiServiceClient } from "@/services/grpc-client" -import HistoryPreview from "@/components/history/HistoryPreview" +import { FileServiceClient, UiServiceClient } from "@/services/grpc-client" import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils" -import Announcement from "@/components/chat/Announcement" -import BrowserSessionRow from "@/components/chat/BrowserSessionRow" -import ChatRow from "@/components/chat/ChatRow" -import ChatTextArea from "@/components/chat/ChatTextArea" -import QuotedMessagePreview from "@/components/chat/QuotedMessagePreview" -import TaskHeader from "@/components/chat/task-header/TaskHeader" -import TelemetryBanner from "@/components/common/TelemetryBanner" -import { unified } from "unified" -import remarkStringify from "remark-stringify" -import rehypeRemark from "rehype-remark" -import rehypeParse from "rehype-parse" -import HomeHeader from "../welcome/HomeHeader" -import AutoApproveBar from "./auto-approve-menu/AutoApproveBar" -import { SuggestedTasks } from "../welcome/SuggestedTasks" import { BooleanRequest, EmptyRequest, StringRequest } from "@shared/proto/common" -import { AskResponseRequest, NewTaskRequest } from "@shared/proto/task" + +// Import utilities and hooks from the new structure +import { + convertHtmlToMarkdown, + filterVisibleMessages, + groupMessages, + CHAT_CONSTANTS, + useChatState, + useButtonState, + useScrollBehavior, + useMessageHandlers, + useIsStreaming, + ChatLayout, + WelcomeSection, + TaskSection, + MessagesArea, + ActionButtons, + InputSection, +} from "./chat-view" interface ChatViewProps { isHidden: boolean @@ -45,54 +36,8 @@ interface ChatViewProps { showHistoryView: () => void } -// Function to clean up markdown escape characters -function cleanupMarkdownEscapes(markdown: string): string { - return ( - markdown - // Handle underscores and asterisks (single or multiple) - .replace(/\\([_*]+)/g, "$1") - - // Handle angle brackets (for generics and XML) - .replace(/\\([<>])/g, "$1") - - // Handle backticks (for code) - .replace(/\\(`)/g, "$1") - - // Handle other common markdown special characters - .replace(/\\([[\]()#.!])/g, "$1") - - // Fix multiple consecutive backslashes - .replace(/\\{2,}([_*`<>[\]()#.!])/g, "$1") - ) -} - -async function convertHtmlToMarkdown(html: string) { - // Process the HTML to Markdown - const result = await unified() - .use(rehypeParse as any, { fragment: true }) // Parse HTML fragments - .use(rehypeRemark as any) // Convert HTML to Markdown AST - .use(remarkStringify as any, { - // Convert Markdown AST to text - bullet: "-", // Use - for unordered lists - emphasis: "*", // Use * for emphasis - strong: "_", // Use _ for strong - listItemIndent: "one", // Use one space for list indentation - rule: "-", // Use - for horizontal rules - ruleSpaces: false, // No spaces in horizontal rules - fences: true, - escape: false, - entities: false, - }) - .process(html) - - const md = String(result) - // Apply comprehensive cleanup of escape characters - return cleanupMarkdownEscapes(md) -} - -// Anthropic limits to 20 images, which we use to constrain both images & files for simplicity -export const MAX_IMAGES_AND_FILES_PER_MESSAGE = 20 -const QUICK_WINS_HISTORY_THRESHOLD = 300 +// Use constants from the imported module +const MAX_IMAGES_AND_FILES_PER_MESSAGE = CHAT_CONSTANTS.MAX_IMAGES_AND_FILES_PER_MESSAGE const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryView }: ChatViewProps) => { const { @@ -124,33 +69,29 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie return getTotalTokensFromApiReqMessage(lastApiReqMessage) }, [modifiedMessages]) - const [inputValue, setInputValue] = useState("") - const [activeQuote, setActiveQuote] = useState(null) - const [isTextAreaFocused, setIsTextAreaFocused] = useState(false) - const textAreaRef = useRef(null) - const [sendingDisabled, setSendingDisabled] = useState(false) - const [selectedImages, setSelectedImages] = useState([]) - const [selectedFiles, setSelectedFiles] = useState([]) - - const [enableButtons, setEnableButtons] = useState(false) - const [primaryButtonText, setPrimaryButtonText] = useState("Approve") - const [secondaryButtonText, setSecondaryButtonText] = useState("Reject") - const [didClickCancel, setDidClickCancel] = useState(false) - const virtuosoRef = useRef(null) - const [expandedRows, setExpandedRows] = useState>({}) - const scrollContainerRef = useRef(null) - const disableAutoScrollRef = useRef(false) - const [showScrollToBottom, setShowScrollToBottom] = useState(false) - const [isAtBottom, setIsAtBottom] = useState(false) - const [pendingScrollToMessage, setPendingScrollToMessage] = useState(null) - - // UI layout depends on the last 2 messages - // (since it relies on the content of these messages, we are deep comparing. i.e. the button state after hitting button sets enableButtons to false, and this effect otherwise would have to true again even if messages didn't change - const lastMessage = useMemo(() => messages.at(-1), [messages]) - const secondLastMessage = useMemo(() => messages.at(-2), [messages]) - - // Derive clineAsk directly from lastMessage to avoid race conditions - const clineAsk = useMemo(() => (lastMessage?.type === "ask" ? lastMessage.ask : undefined), [lastMessage]) + // Use custom hooks for state management + const chatState = useChatState(messages) + const { + inputValue, + setInputValue, + activeQuote, + setActiveQuote, + isTextAreaFocused, + selectedImages, + setSelectedImages, + selectedFiles, + setSelectedFiles, + sendingDisabled, + enableButtons, + primaryButtonText, + secondaryButtonText, + didClickCancel, + expandedRows, + setExpandedRows, + textAreaRef, + handleFocusChange, + clineAsk, + } = chatState useEffect(() => { const handleCopy = async (e: ClipboardEvent) => { @@ -238,401 +179,24 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie document.removeEventListener("copy", handleCopy) } }, []) - useDeepCompareEffect(() => { - // if last message is an ask, show user ask UI - // if user finished a task, then start a new task with a new conversation history since in this moment that the extension is waiting for user response, the user could close the extension and the conversation history would be lost. - // basically as long as a task is active, the conversation history will be persisted - if (lastMessage) { - switch (lastMessage.type) { - case "ask": - const isPartial = lastMessage.partial === true - switch (lastMessage.ask) { - case "api_req_failed": - setSendingDisabled(true) - setEnableButtons(true) - setPrimaryButtonText("Retry") - setSecondaryButtonText("Start New Task") - break - case "mistake_limit_reached": - setSendingDisabled(false) - setEnableButtons(true) - setPrimaryButtonText("Proceed Anyways") - setSecondaryButtonText("Start New Task") - break - case "auto_approval_max_req_reached": - setSendingDisabled(true) - setEnableButtons(true) - setPrimaryButtonText("Proceed") - setSecondaryButtonText("Start New Task") - break - case "followup": - setSendingDisabled(isPartial) - setEnableButtons(false) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - break - case "plan_mode_respond": - setSendingDisabled(isPartial) - setEnableButtons(false) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - break - case "tool": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool - switch (tool.tool) { - case "editedExistingFile": - case "newFileCreated": - setPrimaryButtonText("Save") - setSecondaryButtonText("Reject") - break - default: - setPrimaryButtonText("Approve") - setSecondaryButtonText("Reject") - break - } - break - case "browser_action_launch": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Approve") - setSecondaryButtonText("Reject") - break - case "command": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Run Command") - setSecondaryButtonText("Reject") - break - case "command_output": - setSendingDisabled(false) - setEnableButtons(true) - setPrimaryButtonText("Proceed While Running") - setSecondaryButtonText(undefined) - break - case "use_mcp_server": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Approve") - setSecondaryButtonText("Reject") - break - case "completion_result": - // extension waiting for feedback. but we can just present a new task button - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Start New Task") - setSecondaryButtonText(undefined) - break - case "resume_task": - setSendingDisabled(false) - setEnableButtons(true) - setPrimaryButtonText("Resume Task") - setSecondaryButtonText(undefined) - setDidClickCancel(false) // special case where we reset the cancel button state - break - case "resume_completed_task": - setSendingDisabled(false) - setEnableButtons(true) - setPrimaryButtonText("Start New Task") - setSecondaryButtonText(undefined) - setDidClickCancel(false) - break - case "new_task": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Start New Task with Context") - setSecondaryButtonText(undefined) - break - case "condense": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Condense Conversation") - setSecondaryButtonText(undefined) - break - case "report_bug": - setSendingDisabled(isPartial) - setEnableButtons(!isPartial) - setPrimaryButtonText("Report GitHub issue") - setSecondaryButtonText(undefined) - break - } - break - case "say": - // don't want to reset since there could be a "say" after an "ask" while ask is waiting for response - switch (lastMessage.say) { - case "api_req_started": - if (secondLastMessage?.ask === "command_output") { - // if the last ask is a command_output, and we receive an api_req_started, then that means the command has finished and we don't need input from the user anymore (in every other case, the user has to interact with input field or buttons to continue, which does the following automatically) - setInputValue("") - setSendingDisabled(true) - setSelectedImages([]) - setSelectedFiles([]) - setEnableButtons(false) - } - break - case "task": - case "error": - case "api_req_finished": - case "text": - case "browser_action": - case "browser_action_result": - case "browser_action_launch": - case "command": - case "use_mcp_server": - case "command_output": - case "mcp_server_request_started": - case "mcp_server_response": - case "completion_result": - case "tool": - case "load_mcp_documentation": - break - } - break - } - } else { - // this would get called after sending the first message, so we have to watch messages.length instead - // No messages, so user has to submit a task - // setTextAreaDisabled(false) - // setClineAsk(undefined) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - } - }, [lastMessage, secondLastMessage]) - - useEffect(() => { - if (messages.length === 0) { - setSendingDisabled(false) - setEnableButtons(false) - setPrimaryButtonText("Approve") - setSecondaryButtonText("Reject") - } - }, [messages.length]) + // Button state is now managed by useButtonState hook useEffect(() => { setExpandedRows({}) }, [task?.ts]) - const isStreaming = useMemo(() => { - const isLastAsk = !!modifiedMessages.at(-1)?.ask // checking clineAsk isn't enough since messages effect may be called again for a tool for example, set clineAsk to its value, and if the next message is not an ask then it doesn't reset. This is likely due to how much more often we're updating messages as compared to before, and should be resolved with optimizations as it's likely a rendering bug. but as a final guard for now, the cancel button will show if the last message is not an ask - const isToolCurrentlyAsking = isLastAsk && clineAsk !== undefined && enableButtons && primaryButtonText !== undefined - if (isToolCurrentlyAsking) { - return false - } + // Use streaming hook + const isStreaming = useIsStreaming(modifiedMessages, clineAsk, enableButtons, primaryButtonText) - const isLastMessagePartial = modifiedMessages.at(-1)?.partial === true - if (isLastMessagePartial) { - return true - } else { - const lastApiReqStarted = findLast(modifiedMessages, (message) => message.say === "api_req_started") - if (lastApiReqStarted && lastApiReqStarted.text != null && lastApiReqStarted.say === "api_req_started") { - const cost = JSON.parse(lastApiReqStarted.text).cost - if (cost === undefined) { - // api request has not finished yet - return true - } - } - } + // handleFocusChange is already provided by chatState - return false - }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText]) + // Use button state hook + useButtonState(messages, chatState) - const handleSendMessage = useCallback( - async (text: string, images: string[], files: string[]) => { - let messageToSend = text.trim() - const hasContent = messageToSend || images.length > 0 || files.length > 0 - - // Prepend the active quote if it exists - if (activeQuote && hasContent) { - const prefix = "[context] \n> " - const formattedQuote = activeQuote - const suffix = "\n[/context] \n\n" - messageToSend = `${prefix} ${formattedQuote} ${suffix} ${messageToSend}` - } - - if (hasContent) { - console.log("[ChatView] handleSendMessage - Sending message:", messageToSend) - if (messages.length === 0) { - await TaskServiceClient.newTask(NewTaskRequest.create({ text: messageToSend, images, files })) - } else if (clineAsk) { - switch (clineAsk) { - case "followup": - case "plan_mode_respond": - case "tool": - case "browser_action_launch": - case "command": // user can provide feedback to a tool or command use - case "command_output": // user can send input to command stdin - case "use_mcp_server": - case "completion_result": // if this happens then the user has feedback for the completion result - case "resume_task": - case "resume_completed_task": - case "mistake_limit_reached": - case "new_task": // user can provide feedback or reject the new task suggestion - case "condense": - case "report_bug": - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "messageResponse", - text: messageToSend, - images, - files, - }), - ) - break - // there is no other case that a textfield should be enabled - } - } - setInputValue("") - setActiveQuote(null) // Clear quote when sending message - setSendingDisabled(true) - setSelectedImages([]) - setSelectedFiles([]) - setEnableButtons(false) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - disableAutoScrollRef.current = false - } - }, - [messages.length, clineAsk, activeQuote], - ) - - const startNewTask = useCallback(async () => { - setActiveQuote(null) // Clear the active quote state - await TaskServiceClient.clearTask(EmptyRequest.create({})) - }, []) - - /* - This logic depends on the useEffect[messages] above to set clineAsk, after which buttons are shown and we then send an askResponse to the extension. - */ - const handlePrimaryButtonClick = useCallback( - async (text?: string, images?: string[], files?: string[]) => { - const trimmedInput = text?.trim() - switch (clineAsk) { - case "api_req_failed": - case "command": - case "command_output": - case "tool": - case "browser_action_launch": - case "use_mcp_server": - case "resume_task": - case "mistake_limit_reached": - case "auto_approval_max_req_reached": - if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "yesButtonClicked", - text: trimmedInput, - images: images, - files: files, - }), - ) - } else { - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "yesButtonClicked", - }), - ) - } - // Clear input state after sending - setInputValue("") - setActiveQuote(null) // Clear quote when using primary button - setSelectedImages([]) - setSelectedFiles([]) - break - case "completion_result": - case "resume_completed_task": - // extension waiting for feedback. but we can just present a new task button - startNewTask() - break - case "new_task": - console.info("new task button clicked!", { lastMessage, messages, clineAsk, text }) - await TaskServiceClient.newTask( - NewTaskRequest.create({ - text: lastMessage?.text, - images: [], - files: [], - }), - ) - break - case "condense": - await SlashServiceClient.condense(StringRequest.create({ value: lastMessage?.text })).catch((err) => - console.error(err), - ) - break - case "report_bug": - await SlashServiceClient.reportBug(StringRequest.create({ value: lastMessage?.text })).catch((err) => - console.error(err), - ) - break - } - setSendingDisabled(true) - setEnableButtons(false) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - disableAutoScrollRef.current = false - }, - [clineAsk, startNewTask, lastMessage], - ) - - const handleSecondaryButtonClick = useCallback( - async (text?: string, images?: string[], files?: string[]) => { - const trimmedInput = text?.trim() - if (isStreaming) { - await TaskServiceClient.cancelTask(EmptyRequest.create({})) - setDidClickCancel(true) - return - } - - switch (clineAsk) { - case "api_req_failed": - case "mistake_limit_reached": - case "auto_approval_max_req_reached": - startNewTask() - break - case "command": - case "tool": - case "browser_action_launch": - case "use_mcp_server": - if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "noButtonClicked", - text: trimmedInput, - images: images, - files: files, - }), - ) - } else { - // responds to the API with a "This operation failed" and lets it try again - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "noButtonClicked", - }), - ) - } - // Clear input state after sending - setInputValue("") - setActiveQuote(null) // Clear quote when using secondary button - setSelectedImages([]) - setSelectedFiles([]) - break - } - setSendingDisabled(true) - setEnableButtons(false) - // setPrimaryButtonText(undefined) - // setSecondaryButtonText(undefined) - disableAutoScrollRef.current = false - }, - [clineAsk, startNewTask, isStreaming], - ) - - const handleTaskCloseButtonClick = useCallback(() => { - startNewTask() - }, [startNewTask]) - - const handleFocusChange = useCallback((isFocused: boolean) => { - setIsTextAreaFocused(isFocused) - }, []) + // Use message handlers hook + const messageHandlers = useMessageHandlers(messages, chatState, isStreaming) + const { handleSendMessage, handlePrimaryButtonClick, handleSecondaryButtonClick, handleTaskCloseButtonClick } = + messageHandlers const { selectedModelInfo } = useMemo(() => { return normalizeApiConfiguration(apiConfiguration) @@ -739,550 +303,80 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie }, [isHidden, sendingDisabled, enableButtons]) const visibleMessages = useMemo(() => { - return modifiedMessages.filter((message) => { - switch (message.ask) { - case "completion_result": - // don't show a chat row for a completion_result ask without text. This specific type of message only occurs if cline wants to execute a command as part of its completion result, in which case we interject the completion_result tool with the execute_command tool. - if (message.text === "") { - return false - } - break - case "api_req_failed": // this message is used to update the latest api_req_started that the request failed - case "resume_task": - case "resume_completed_task": - return false - } - switch (message.say) { - case "api_req_finished": // combineApiRequests removes this from modifiedMessages anyways - case "api_req_retried": // this message is used to update the latest api_req_started that the request was retried - case "deleted_api_reqs": // aggregated api_req metrics from deleted messages - return false - case "text": - // Sometimes cline returns an empty text message, we don't want to render these. (We also use a say text for user messages, so in case they just sent images we still render that) - if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) { - return false - } - break - case "mcp_server_request_started": - return false - } - return true - }) + return filterVisibleMessages(modifiedMessages) }, [modifiedMessages]) - const isBrowserSessionMessage = (message: ClineMessage): boolean => { - // which of visible messages are browser session messages, see above - - // NOTE: any messages we want to make as part of a browser session should be included here - // There was an issue where we added checkpoints after browser actions, and it resulted in browser sessions being disrupted. - if (message.type === "ask") { - return ["browser_action_launch"].includes(message.ask!) - } - if (message.type === "say") { - return [ - "browser_action_launch", - "api_req_started", - "text", - "browser_action", - "browser_action_result", - "checkpoint_created", - "reasoning", - ].includes(message.say!) - } - return false - } - const groupedMessages = useMemo(() => { - const result: (ClineMessage | ClineMessage[])[] = [] - let currentGroup: ClineMessage[] = [] - let isInBrowserSession = false - - const endBrowserSession = () => { - if (currentGroup.length > 0) { - result.push([...currentGroup]) - currentGroup = [] - isInBrowserSession = false - } - } - - visibleMessages.forEach((message) => { - if (message.ask === "browser_action_launch" || message.say === "browser_action_launch") { - // complete existing browser session if any - endBrowserSession() - // start new - isInBrowserSession = true - currentGroup.push(message) - } else if (isInBrowserSession) { - // end session if api_req_started is cancelled - - if (message.say === "api_req_started") { - // get last api_req_started in currentGroup to check if it's cancelled. If it is then this api req is not part of the current browser session - const lastApiReqStarted = [...currentGroup].reverse().find((m) => m.say === "api_req_started") - if (lastApiReqStarted?.text != null) { - const info = JSON.parse(lastApiReqStarted.text) - const isCancelled = info.cancelReason != null - if (isCancelled) { - endBrowserSession() - result.push(message) - return - } - } - } - - if (isBrowserSessionMessage(message)) { - currentGroup.push(message) - - // Check if this is a close action - if (message.say === "browser_action") { - const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction - if (browserAction.action === "close") { - endBrowserSession() - } - } - } else { - // complete existing browser session if any - endBrowserSession() - result.push(message) - } - } else { - result.push(message) - } - }) - - // Handle case where browser session is the last group - if (currentGroup.length > 0) { - result.push([...currentGroup]) - } - - return result + return groupMessages(visibleMessages) }, [visibleMessages]) - // scrolling - - const scrollToBottomSmooth = useMemo( - () => - debounce( - () => { - virtuosoRef.current?.scrollTo({ - top: Number.MAX_SAFE_INTEGER, - behavior: "smooth", - }) - }, - 10, - { immediate: true }, - ), - [], - ) - - const scrollToBottomAuto = useCallback(() => { - virtuosoRef.current?.scrollTo({ - top: Number.MAX_SAFE_INTEGER, - behavior: "auto", // instant causes crash - }) - }, []) - - const scrollToMessage = useCallback( - (messageIndex: number) => { - setPendingScrollToMessage(messageIndex) - - const targetMessage = messages[messageIndex] - if (!targetMessage) { - setPendingScrollToMessage(null) - return - } - - const visibleIndex = visibleMessages.findIndex((msg) => msg.ts === targetMessage.ts) - if (visibleIndex === -1) { - setPendingScrollToMessage(null) - return - } - - let groupIndex = -1 - let currentVisibleIndex = 0 - - for (let i = 0; i < groupedMessages.length; i++) { - const group = groupedMessages[i] - if (Array.isArray(group)) { - const groupSize = group.length - const messageInGroup = group.some((msg) => msg.ts === targetMessage.ts) - if (messageInGroup) { - groupIndex = i - break - } - currentVisibleIndex += groupSize - } else { - if (group.ts === targetMessage.ts) { - groupIndex = i - break - } - currentVisibleIndex++ - } - } - - if (groupIndex !== -1) { - setPendingScrollToMessage(null) - disableAutoScrollRef.current = true - requestAnimationFrame(() => { - requestAnimationFrame(() => { - virtuosoRef.current?.scrollToIndex({ - index: groupIndex, - align: "start", - behavior: "smooth", - }) - }) - }) - } - }, - [messages, visibleMessages, groupedMessages], - ) - - // scroll when user toggles certain rows - const toggleRowExpansion = useCallback( - (ts: number) => { - const isCollapsing = expandedRows[ts] ?? false - const lastGroup = groupedMessages.at(-1) - const isLast = Array.isArray(lastGroup) ? lastGroup[0].ts === ts : lastGroup?.ts === ts - const secondToLastGroup = groupedMessages.at(-2) - const isSecondToLast = Array.isArray(secondToLastGroup) - ? secondToLastGroup[0].ts === ts - : secondToLastGroup?.ts === ts - - const isLastCollapsedApiReq = - isLast && - !Array.isArray(lastGroup) && // Make sure it's not a browser session group - lastGroup?.say === "api_req_started" && - !expandedRows[lastGroup.ts] - - setExpandedRows((prev) => ({ - ...prev, - [ts]: !prev[ts], - })) - - // disable auto scroll when user expands row - if (!isCollapsing) { - disableAutoScrollRef.current = true - } - - if (isCollapsing && isAtBottom) { - const timer = setTimeout(() => { - scrollToBottomAuto() - }, 0) - return () => clearTimeout(timer) - } else if (isLast || isSecondToLast) { - if (isCollapsing) { - if (isSecondToLast && !isLastCollapsedApiReq) { - return - } - const timer = setTimeout(() => { - scrollToBottomAuto() - }, 0) - return () => clearTimeout(timer) - } else { - const timer = setTimeout(() => { - virtuosoRef.current?.scrollToIndex({ - index: groupedMessages.length - (isLast ? 1 : 2), - align: "start", - }) - }, 0) - return () => clearTimeout(timer) - } - } - }, - [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom], - ) - - const handleRowHeightChange = useCallback( - (isTaller: boolean) => { - if (!disableAutoScrollRef.current) { - if (isTaller) { - scrollToBottomSmooth() - } else { - setTimeout(() => { - scrollToBottomAuto() - }, 0) - } - } - }, - [scrollToBottomSmooth, scrollToBottomAuto], - ) - - useEffect(() => { - if (!disableAutoScrollRef.current) { - setTimeout(() => { - scrollToBottomSmooth() - }, 50) - // return () => clearTimeout(timer) // dont cleanup since if visibleMessages.length changes it cancels. - } - }, [groupedMessages.length, scrollToBottomSmooth]) - - useEffect(() => { - if (pendingScrollToMessage !== null) { - scrollToMessage(pendingScrollToMessage) - } - }, [pendingScrollToMessage, groupedMessages, scrollToMessage]) - - const handleWheel = useCallback((event: Event) => { - const wheelEvent = event as WheelEvent - if (wheelEvent.deltaY && wheelEvent.deltaY < 0) { - if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) { - // user scrolled up - disableAutoScrollRef.current = true - } - } - }, []) - useEvent("wheel", handleWheel, window, { passive: true }) // passive improves scrolling performance + // Use scroll behavior hook + const scrollBehavior = useScrollBehavior(messages, visibleMessages, groupedMessages, expandedRows, setExpandedRows) const placeholderText = useMemo(() => { const text = task ? "Type a message..." : "Type your task here..." return text }, [task]) - const itemContent = useCallback( - (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => { - // browser session group - if (Array.isArray(messageOrGroup)) { - return ( - - ) - } - - // We display certain statuses for the last message only - // If the last message is a checkpoint, we want to show the status of the previous message - const nextMessage = index < groupedMessages.length - 1 && groupedMessages[index + 1] - const isNextCheckpoint = !Array.isArray(nextMessage) && nextMessage && nextMessage?.say === "checkpoint_created" - const isLastMessageGroup = isNextCheckpoint && index === groupedMessages.length - 2 - - const isLast = index === groupedMessages.length - 1 || isLastMessageGroup - - // regular message - return ( - - ) - }, - [ - expandedRows, - modifiedMessages, - groupedMessages.length, - toggleRowExpansion, - handleRowHeightChange, - inputValue, - setActiveQuote, - ], - ) - return ( -
+ {task ? ( - ) : ( -
- {telemetrySetting === "unset" && } - - {showAnnouncement && } - - - {!shouldShowQuickWins && taskHistory.length > 0 && } -
- )} - - {!task && ( - <> - - - + )} {task && ( <> -
-
, // Add empty padding at the bottom - }} - // increasing top by 3_000 to prevent jumping around when user collapses a row - increaseViewportBy={{ - top: 3_000, - bottom: Number.MAX_SAFE_INTEGER, - }} // hack to make sure the last message is always rendered to get truly perfect scroll to bottom animation when new messages are added (Number.MAX_SAFE_INTEGER is safe for arithmetic operations, which is all virtuoso uses this value for in src/sizeRangeSystem.ts) - data={groupedMessages} // messages is the raw format returned by extension, modifiedMessages is the manipulated structure that combines certain messages of related type, and visibleMessages is the filtered structure that removes messages that should not be rendered - itemContent={itemContent} - atBottomStateChange={(isAtBottom) => { - setIsAtBottom(isAtBottom) - if (isAtBottom) { - disableAutoScrollRef.current = false - } - setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom) - }} - atBottomThreshold={10} // anything lower causes issues with followOutput - initialTopMostItemIndex={groupedMessages.length - 1} - /> -
- - {showScrollToBottom ? ( -
- { - scrollToBottomSmooth() - disableAutoScrollRef.current = false - }}> - - -
- ) : ( -
- {primaryButtonText && !isStreaming && ( - handlePrimaryButtonClick(inputValue, selectedImages, selectedFiles)}> - {primaryButtonText} - - )} - {(secondaryButtonText || isStreaming) && ( - handleSecondaryButtonClick(inputValue, selectedImages, selectedFiles)}> - {isStreaming ? "Cancel" : secondaryButtonText} - - )} -
- )} + + )} - {(() => { - return activeQuote ? ( -
- setActiveQuote(null)} - isFocused={isTextAreaFocused} - /> -
- ) : null - })()} - handleSendMessage(inputValue, selectedImages, selectedFiles)} - onSelectFilesAndImages={selectFilesAndImages} shouldDisableFilesAndImages={shouldDisableFilesAndImages} - onHeightChange={() => { - if (isAtBottom) { - scrollToBottomAuto() - } - }} + selectFilesAndImages={selectFilesAndImages} /> -
+
) } -const ScrollToBottomButton = styled.div` - background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 55%, transparent); - border-radius: 3px; - overflow: hidden; - cursor: pointer; - display: flex; - justify-content: center; - align-items: center; - flex: 1; - height: 25px; - - &:hover { - background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 90%, transparent); - } - - &:active { - background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 70%, transparent); - } -` - export default ChatView diff --git a/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx b/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx new file mode 100644 index 00000000..f14d2a6f --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx @@ -0,0 +1,100 @@ +import React from "react" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import styled from "styled-components" +import { ChatState, MessageHandlers } from "../../types/chatTypes" + +interface ActionButtonsProps { + chatState: ChatState + messageHandlers: MessageHandlers + isStreaming: boolean + scrollBehavior: { + scrollToBottomSmooth: () => void + disableAutoScrollRef: React.MutableRefObject + showScrollToBottom: boolean + } +} + +/** + * Action buttons area including scroll-to-bottom and approve/reject buttons + */ +export const ActionButtons: React.FC = ({ chatState, messageHandlers, isStreaming, scrollBehavior }) => { + const { primaryButtonText, secondaryButtonText, enableButtons, didClickCancel, inputValue, selectedImages, selectedFiles } = + chatState + + const { showScrollToBottom, scrollToBottomSmooth, disableAutoScrollRef } = scrollBehavior + + if (showScrollToBottom) { + return ( +
+ { + scrollToBottomSmooth() + disableAutoScrollRef.current = false + }}> + + +
+ ) + } + + const shouldShowButtons = primaryButtonText || secondaryButtonText || isStreaming + const opacity = shouldShowButtons ? (enableButtons || (isStreaming && !didClickCancel) ? 1 : 0.5) : 0 + + return ( +
+ {primaryButtonText && !isStreaming && ( + messageHandlers.handlePrimaryButtonClick(inputValue, selectedImages, selectedFiles)}> + {primaryButtonText} + + )} + {(secondaryButtonText || isStreaming) && ( + messageHandlers.handleSecondaryButtonClick(inputValue, selectedImages, selectedFiles)}> + {isStreaming ? "Cancel" : secondaryButtonText} + + )} +
+ ) +} + +const ScrollToBottomButton = styled.div` + background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 55%, transparent); + border-radius: 3px; + overflow: hidden; + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + flex: 1; + height: 25px; + + &:hover { + background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 90%, transparent); + } + + &:active { + background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 70%, transparent); + } +` diff --git a/webview-ui/src/components/chat/chat-view/components/layout/ChatLayout.tsx b/webview-ui/src/components/chat/chat-view/components/layout/ChatLayout.tsx new file mode 100644 index 00000000..f571efe2 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/ChatLayout.tsx @@ -0,0 +1,26 @@ +import React from "react" +import styled from "styled-components" + +interface ChatLayoutProps { + isHidden: boolean + children: React.ReactNode +} + +/** + * Main layout container for the chat view + * Provides the fixed positioning and flex layout structure + */ +export const ChatLayout: React.FC = ({ isHidden, children }) => { + return {children} +} + +const ChatLayoutContainer = styled.div<{ isHidden: boolean }>` + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + display: ${(props) => (props.isHidden ? "none" : "flex")}; + flex-direction: column; + overflow: hidden; +` diff --git a/webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx b/webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx new file mode 100644 index 00000000..d89bcbe8 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx @@ -0,0 +1,78 @@ +import React from "react" +import QuotedMessagePreview from "@/components/chat/QuotedMessagePreview" +import ChatTextArea from "@/components/chat/ChatTextArea" +import { ChatState, MessageHandlers, ScrollBehavior } from "../../types/chatTypes" + +interface InputSectionProps { + chatState: ChatState + messageHandlers: MessageHandlers + scrollBehavior: ScrollBehavior + placeholderText: string + shouldDisableFilesAndImages: boolean + selectFilesAndImages: () => Promise +} + +/** + * Input section including quoted message preview and chat text area + */ +export const InputSection: React.FC = ({ + chatState, + messageHandlers, + scrollBehavior, + placeholderText, + shouldDisableFilesAndImages, + selectFilesAndImages, +}) => { + const { + activeQuote, + setActiveQuote, + isTextAreaFocused, + inputValue, + setInputValue, + sendingDisabled, + selectedImages, + setSelectedImages, + selectedFiles, + setSelectedFiles, + textAreaRef, + handleFocusChange, + } = chatState + + const { isAtBottom, scrollToBottomAuto } = scrollBehavior + + return ( + <> + {activeQuote && ( +
+ setActiveQuote(null)} + isFocused={isTextAreaFocused} + /> +
+ )} + + messageHandlers.handleSendMessage(inputValue, selectedImages, selectedFiles)} + onSelectFilesAndImages={selectFilesAndImages} + shouldDisableFilesAndImages={shouldDisableFilesAndImages} + onHeightChange={() => { + if (isAtBottom) { + scrollToBottomAuto() + } + }} + /> + + ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx b/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx new file mode 100644 index 00000000..47bd5749 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx @@ -0,0 +1,98 @@ +import React, { useCallback } from "react" +import { Virtuoso } from "react-virtuoso" +import AutoApproveBar from "@/components/chat/auto-approve-menu/AutoApproveBar" +import { ClineMessage } from "@shared/ExtensionMessage" +import { ScrollBehavior, ChatState, MessageHandlers } from "../../types/chatTypes" +import { createMessageRenderer } from "../messages/MessageRenderer" + +interface MessagesAreaProps { + task: ClineMessage + groupedMessages: (ClineMessage | ClineMessage[])[] + modifiedMessages: ClineMessage[] + scrollBehavior: ScrollBehavior + chatState: ChatState + messageHandlers: MessageHandlers +} + +/** + * The scrollable messages area with virtualized list + * Handles rendering of chat rows and browser sessions + */ +export const MessagesArea: React.FC = ({ + task, + groupedMessages, + modifiedMessages, + scrollBehavior, + chatState, + messageHandlers, +}) => { + const { + virtuosoRef, + scrollContainerRef, + toggleRowExpansion, + handleRowHeightChange, + setIsAtBottom, + setShowScrollToBottom, + disableAutoScrollRef, + } = scrollBehavior + + const { expandedRows, inputValue, setActiveQuote } = chatState + + const itemContent = useCallback( + createMessageRenderer( + groupedMessages, + modifiedMessages, + expandedRows, + toggleRowExpansion, + handleRowHeightChange, + setActiveQuote, + inputValue, + messageHandlers, + ), + [ + groupedMessages, + modifiedMessages, + expandedRows, + toggleRowExpansion, + handleRowHeightChange, + setActiveQuote, + inputValue, + messageHandlers, + ], + ) + + return ( + <> +
+
, // Add empty padding at the bottom + }} + increaseViewportBy={{ + top: 3_000, + bottom: Number.MAX_SAFE_INTEGER, + }} + data={groupedMessages} + itemContent={itemContent} + atBottomStateChange={(isAtBottom) => { + setIsAtBottom(isAtBottom) + if (isAtBottom) { + disableAutoScrollRef.current = false + } + setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom) + }} + atBottomThreshold={10} + initialTopMostItemIndex={groupedMessages.length - 1} + /> +
+ + + ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx b/webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx new file mode 100644 index 00000000..14d01961 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx @@ -0,0 +1,50 @@ +import React from "react" +import TaskHeader from "@/components/chat/task-header/TaskHeader" +import { ClineMessage } from "@shared/ExtensionMessage" +import { MessageHandlers, ScrollBehavior } from "../../types/chatTypes" + +interface TaskSectionProps { + task: ClineMessage + apiMetrics: { + totalTokensIn: number + totalTokensOut: number + totalCacheWrites?: number + totalCacheReads?: number + totalCost: number + } + lastApiReqTotalTokens?: number + selectedModelInfo: { + supportsPromptCache: boolean + supportsImages: boolean + } + messageHandlers: MessageHandlers + scrollBehavior: ScrollBehavior +} + +/** + * Task section shown when there's an active task + * Includes the task header and manages task-specific UI + */ +export const TaskSection: React.FC = ({ + task, + apiMetrics, + lastApiReqTotalTokens, + selectedModelInfo, + messageHandlers, + scrollBehavior, +}) => { + return ( + + ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx b/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx new file mode 100644 index 00000000..5cbea3c3 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx @@ -0,0 +1,43 @@ +import React from "react" +import TelemetryBanner from "@/components/common/TelemetryBanner" +import Announcement from "@/components/chat/Announcement" +import HomeHeader from "@/components/welcome/HomeHeader" +import HistoryPreview from "@/components/history/HistoryPreview" +import { SuggestedTasks } from "@/components/welcome/SuggestedTasks" +import AutoApproveBar from "@/components/chat/auto-approve-menu/AutoApproveBar" +import { WelcomeSectionProps } from "../../types/chatTypes" + +/** + * Welcome section shown when there's no active task + * Includes telemetry banner, announcements, home header, and history preview + */ +export const WelcomeSection: React.FC = ({ + showAnnouncement, + hideAnnouncement, + showHistoryView, + telemetrySetting, + version, + taskHistory, + shouldShowQuickWins, +}) => { + return ( + <> +
+ {telemetrySetting === "unset" && } + {showAnnouncement && } + + {!shouldShowQuickWins && taskHistory.length > 0 && } +
+ + + + ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/layout/index.ts b/webview-ui/src/components/chat/chat-view/components/layout/index.ts new file mode 100644 index 00000000..f9404b54 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/layout/index.ts @@ -0,0 +1,10 @@ +/** + * Export all layout components + */ + +export { ChatLayout } from "./ChatLayout" +export { WelcomeSection } from "./WelcomeSection" +export { TaskSection } from "./TaskSection" +export { MessagesArea } from "./MessagesArea" +export { ActionButtons } from "./ActionButtons" +export { InputSection } from "./InputSection" diff --git a/webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx b/webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx new file mode 100644 index 00000000..a4fc393f --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx @@ -0,0 +1,103 @@ +import React, { useCallback } from "react" +import BrowserSessionRow from "@/components/chat/BrowserSessionRow" +import ChatRow from "@/components/chat/ChatRow" +import { ClineMessage } from "@shared/ExtensionMessage" +import { MessageHandlers } from "../../types/chatTypes" + +interface MessageRendererProps { + index: number + messageOrGroup: ClineMessage | ClineMessage[] + groupedMessages: (ClineMessage | ClineMessage[])[] + modifiedMessages: ClineMessage[] + expandedRows: Record + onToggleExpand: (ts: number) => void + onHeightChange: (isTaller: boolean) => void + onSetQuote: (quote: string | null) => void + inputValue: string + messageHandlers: MessageHandlers +} + +/** + * Specialized component for rendering different message types + * Handles browser sessions, regular messages, and checkpoint logic + */ +export const MessageRenderer: React.FC = ({ + index, + messageOrGroup, + groupedMessages, + modifiedMessages, + expandedRows, + onToggleExpand, + onHeightChange, + onSetQuote, + inputValue, + messageHandlers, +}) => { + // Browser session group + if (Array.isArray(messageOrGroup)) { + return ( + + ) + } + + // Determine if this is the last message for status display purposes + const nextMessage = index < groupedMessages.length - 1 && groupedMessages[index + 1] + const isNextCheckpoint = !Array.isArray(nextMessage) && nextMessage && nextMessage?.say === "checkpoint_created" + const isLastMessageGroup = isNextCheckpoint && index === groupedMessages.length - 2 + const isLast = index === groupedMessages.length - 1 || isLastMessageGroup + + // Regular message + return ( + + ) +} + +/** + * Factory function to create the itemContent callback for Virtuoso + * This allows us to encapsulate the rendering logic while maintaining performance + */ +export const createMessageRenderer = ( + groupedMessages: (ClineMessage | ClineMessage[])[], + modifiedMessages: ClineMessage[], + expandedRows: Record, + onToggleExpand: (ts: number) => void, + onHeightChange: (isTaller: boolean) => void, + onSetQuote: (quote: string | null) => void, + inputValue: string, + messageHandlers: MessageHandlers, +) => { + return (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => ( + + ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx b/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx new file mode 100644 index 00000000..b9ed1508 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx @@ -0,0 +1,93 @@ +import React, { useMemo } from "react" +import { ClineMessage } from "@shared/ExtensionMessage" +import { findLast } from "@shared/array" + +/** + * Hook to determine if the chat is currently streaming + * Encapsulates the complex streaming detection logic + */ +export const useIsStreaming = ( + modifiedMessages: ClineMessage[], + clineAsk?: string, + enableButtons?: boolean, + primaryButtonText?: string, +): boolean => { + return useMemo(() => { + // Check if the last message is an ask (tool is waiting for user input) + const isLastAsk = !!modifiedMessages.at(-1)?.ask + const isToolCurrentlyAsking = isLastAsk && clineAsk !== undefined && enableButtons && primaryButtonText !== undefined + if (isToolCurrentlyAsking) { + return false + } + + // Check if the last message is partial (still being streamed) + const isLastMessagePartial = modifiedMessages.at(-1)?.partial === true + if (isLastMessagePartial) { + return true + } + + // Check if there's an ongoing API request + const lastApiReqStarted = findLast(modifiedMessages, (message) => message.say === "api_req_started") + if (lastApiReqStarted && lastApiReqStarted.text != null && lastApiReqStarted.say === "api_req_started") { + const cost = JSON.parse(lastApiReqStarted.text).cost + if (cost === undefined) { + // API request has not finished yet + return true + } + } + + return false + }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText]) +} + +/** + * Component that shows a visual streaming indicator + * Can be used to show loading states, typing indicators, etc. + */ +export const StreamingVisualIndicator: React.FC<{ isStreaming: boolean }> = ({ isStreaming }) => { + if (!isStreaming) return null + + return ( +
+
+ {[0, 1, 2].map((i) => ( +
+ ))} +
+ Cline is thinking... + +
+ ) +} diff --git a/webview-ui/src/components/chat/chat-view/components/messages/index.ts b/webview-ui/src/components/chat/chat-view/components/messages/index.ts new file mode 100644 index 00000000..3d07a53e --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/components/messages/index.ts @@ -0,0 +1,6 @@ +/** + * Export all message-related components + */ + +export { MessageRenderer, createMessageRenderer } from "./MessageRenderer" +export { useIsStreaming, StreamingVisualIndicator } from "./StreamingIndicator" diff --git a/webview-ui/src/components/chat/chat-view/constants.ts b/webview-ui/src/components/chat/chat-view/constants.ts new file mode 100644 index 00000000..dcd3b7fe --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/constants.ts @@ -0,0 +1,7 @@ +/** + * Constants used across the chat view components + */ +export const CHAT_CONSTANTS = { + MAX_IMAGES_AND_FILES_PER_MESSAGE: 20, + QUICK_WINS_HISTORY_THRESHOLD: 300, +} as const diff --git a/webview-ui/src/components/chat/chat-view/hooks/index.ts b/webview-ui/src/components/chat/chat-view/hooks/index.ts new file mode 100644 index 00000000..089fe397 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/hooks/index.ts @@ -0,0 +1,8 @@ +/** + * Export all custom hooks for the chat view + */ + +export { useChatState } from "./useChatState" +export { useButtonState } from "./useButtonState" +export { useScrollBehavior } from "./useScrollBehavior" +export { useMessageHandlers } from "./useMessageHandlers" diff --git a/webview-ui/src/components/chat/chat-view/hooks/useButtonState.ts b/webview-ui/src/components/chat/chat-view/hooks/useButtonState.ts new file mode 100644 index 00000000..ec7cff8d --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/hooks/useButtonState.ts @@ -0,0 +1,160 @@ +import { useEffect } from "react" +import { useDeepCompareEffect } from "react-use" +import { ClineMessage, ClineSayTool } from "@shared/ExtensionMessage" +import { ChatState } from "../types/chatTypes" + +/** + * Custom hook for managing button state based on messages + * Handles button text and enable/disable states based on the current ask type + */ +export function useButtonState(messages: ClineMessage[], chatState: ChatState) { + const { + setSendingDisabled, + setEnableButtons, + setPrimaryButtonText, + setSecondaryButtonText, + setDidClickCancel, + lastMessage, + secondLastMessage, + } = chatState + + // Update button state based on last message + useDeepCompareEffect(() => { + if (lastMessage) { + switch (lastMessage.type) { + case "ask": + const isPartial = lastMessage.partial === true + switch (lastMessage.ask) { + case "api_req_failed": + setSendingDisabled(true) + setEnableButtons(true) + setPrimaryButtonText("Retry") + setSecondaryButtonText("Start New Task") + break + case "mistake_limit_reached": + setSendingDisabled(false) + setEnableButtons(true) + setPrimaryButtonText("Proceed Anyways") + setSecondaryButtonText("Start New Task") + break + case "auto_approval_max_req_reached": + setSendingDisabled(true) + setEnableButtons(true) + setPrimaryButtonText("Proceed") + setSecondaryButtonText("Start New Task") + break + case "followup": + setSendingDisabled(isPartial) + setEnableButtons(false) + break + case "plan_mode_respond": + setSendingDisabled(isPartial) + setEnableButtons(false) + break + case "tool": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool + switch (tool.tool) { + case "editedExistingFile": + case "newFileCreated": + setPrimaryButtonText("Save") + setSecondaryButtonText("Reject") + break + default: + setPrimaryButtonText("Approve") + setSecondaryButtonText("Reject") + break + } + break + case "browser_action_launch": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Approve") + setSecondaryButtonText("Reject") + break + case "command": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Run Command") + setSecondaryButtonText("Reject") + break + case "command_output": + setSendingDisabled(false) + setEnableButtons(true) + setPrimaryButtonText("Proceed While Running") + setSecondaryButtonText(undefined) + break + case "use_mcp_server": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Approve") + setSecondaryButtonText("Reject") + break + case "completion_result": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Start New Task") + setSecondaryButtonText(undefined) + break + case "resume_task": + setSendingDisabled(false) + setEnableButtons(true) + setPrimaryButtonText("Resume Task") + setSecondaryButtonText(undefined) + setDidClickCancel(false) + break + case "resume_completed_task": + setSendingDisabled(false) + setEnableButtons(true) + setPrimaryButtonText("Start New Task") + setSecondaryButtonText(undefined) + setDidClickCancel(false) + break + case "new_task": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Start New Task with Context") + setSecondaryButtonText(undefined) + break + case "condense": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Condense Conversation") + setSecondaryButtonText(undefined) + break + case "report_bug": + setSendingDisabled(isPartial) + setEnableButtons(!isPartial) + setPrimaryButtonText("Report GitHub issue") + setSecondaryButtonText(undefined) + break + } + break + case "say": + switch (lastMessage.say) { + case "api_req_started": + if (secondLastMessage?.ask === "command_output") { + chatState.setInputValue("") + setSendingDisabled(true) + chatState.setSelectedImages([]) + chatState.setSelectedFiles([]) + setEnableButtons(false) + } + break + } + break + } + } + }, [lastMessage, secondLastMessage]) + + // Reset button state when no messages + useEffect(() => { + if (messages.length === 0) { + setSendingDisabled(false) + setEnableButtons(false) + setPrimaryButtonText("Approve") + setSecondaryButtonText("Reject") + } + }, [messages.length, setSendingDisabled, setEnableButtons, setPrimaryButtonText, setSecondaryButtonText]) +} diff --git a/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts b/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts new file mode 100644 index 00000000..879491c4 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts @@ -0,0 +1,96 @@ +import { useState, useMemo, useRef, useCallback } from "react" +import { ClineMessage, ClineAsk } from "@shared/ExtensionMessage" +import { ChatState, MessageHandlers } from "../types/chatTypes" + +/** + * Custom hook for managing chat state + * Handles input values, selection states, and UI state + */ +export function useChatState(messages: ClineMessage[]): ChatState { + // Input and selection state + const [inputValue, setInputValue] = useState("") + const [activeQuote, setActiveQuote] = useState(null) + const [isTextAreaFocused, setIsTextAreaFocused] = useState(false) + const [selectedImages, setSelectedImages] = useState([]) + const [selectedFiles, setSelectedFiles] = useState([]) + + // UI state + const [sendingDisabled, setSendingDisabled] = useState(false) + const [enableButtons, setEnableButtons] = useState(false) + const [primaryButtonText, setPrimaryButtonText] = useState("Approve") + const [secondaryButtonText, setSecondaryButtonText] = useState("Reject") + const [didClickCancel, setDidClickCancel] = useState(false) + const [expandedRows, setExpandedRows] = useState>({}) + + // Refs + const textAreaRef = useRef(null) + + // Derived state + const lastMessage = useMemo(() => messages.at(-1), [messages]) + const secondLastMessage = useMemo(() => messages.at(-2), [messages]) + const clineAsk = useMemo(() => (lastMessage?.type === "ask" ? lastMessage.ask : undefined), [lastMessage]) + + // Clear expanded rows when task changes + const task = useMemo(() => messages.at(0), [messages]) + const clearExpandedRows = useCallback(() => { + setExpandedRows({}) + }, []) + + // Reset state when starting new conversation + const resetState = useCallback(() => { + setInputValue("") + setActiveQuote(null) + setSendingDisabled(false) + setSelectedImages([]) + setSelectedFiles([]) + setEnableButtons(false) + setPrimaryButtonText("Approve") + setSecondaryButtonText("Reject") + setDidClickCancel(false) + }, []) + + // Handle focus change + const handleFocusChange = useCallback((isFocused: boolean) => { + setIsTextAreaFocused(isFocused) + }, []) + + return { + // State values + inputValue, + setInputValue, + activeQuote, + setActiveQuote, + isTextAreaFocused, + setIsTextAreaFocused, + selectedImages, + setSelectedImages, + selectedFiles, + setSelectedFiles, + sendingDisabled, + setSendingDisabled, + enableButtons, + setEnableButtons, + primaryButtonText, + setPrimaryButtonText, + secondaryButtonText, + setSecondaryButtonText, + didClickCancel, + setDidClickCancel, + expandedRows, + setExpandedRows, + + // Refs + textAreaRef, + + // Derived values + lastMessage, + secondLastMessage, + clineAsk, + task, + + // Handlers + handleFocusChange, + clearExpandedRows, + resetState, + } +} diff --git a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts new file mode 100644 index 00000000..82ebc737 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts @@ -0,0 +1,270 @@ +import { useCallback } from "react" +import { ClineMessage, ClineAsk } from "@shared/ExtensionMessage" +import { TaskServiceClient, SlashServiceClient } from "@/services/grpc-client" +import { EmptyRequest, StringRequest } from "@shared/proto/common" +import { AskResponseRequest, NewTaskRequest } from "@shared/proto/task" +import { MessageHandlers, ChatState } from "../types/chatTypes" + +/** + * Custom hook for managing message handlers + * Handles sending messages, button clicks, and task management + */ +export function useMessageHandlers(messages: ClineMessage[], chatState: ChatState, isStreaming: boolean): MessageHandlers { + const { + inputValue, + setInputValue, + activeQuote, + setActiveQuote, + selectedImages, + setSelectedImages, + selectedFiles, + setSelectedFiles, + setSendingDisabled, + setEnableButtons, + setDidClickCancel, + clineAsk, + lastMessage, + } = chatState + + // Handle sending a message + const handleSendMessage = useCallback( + async (text: string, images: string[], files: string[]) => { + let messageToSend = text.trim() + const hasContent = messageToSend || images.length > 0 || files.length > 0 + + // Prepend the active quote if it exists + if (activeQuote && hasContent) { + const prefix = "[context] \n> " + const formattedQuote = activeQuote + const suffix = "\n[/context] \n\n" + messageToSend = `${prefix} ${formattedQuote} ${suffix} ${messageToSend}` + } + + if (hasContent) { + console.log("[ChatView] handleSendMessage - Sending message:", messageToSend) + if (messages.length === 0) { + await TaskServiceClient.newTask(NewTaskRequest.create({ text: messageToSend, images, files })) + } else if (clineAsk) { + switch (clineAsk) { + case "followup": + case "plan_mode_respond": + case "tool": + case "browser_action_launch": + case "command": + case "command_output": + case "use_mcp_server": + case "completion_result": + case "resume_task": + case "resume_completed_task": + case "mistake_limit_reached": + case "new_task": + case "condense": + case "report_bug": + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "messageResponse", + text: messageToSend, + images, + files, + }), + ) + break + } + } + setInputValue("") + setActiveQuote(null) + setSendingDisabled(true) + setSelectedImages([]) + setSelectedFiles([]) + setEnableButtons(false) + + // Reset auto-scroll + if ("disableAutoScrollRef" in chatState) { + ;(chatState as any).disableAutoScrollRef.current = false + } + } + }, + [ + messages.length, + clineAsk, + activeQuote, + setInputValue, + setActiveQuote, + setSendingDisabled, + setSelectedImages, + setSelectedFiles, + setEnableButtons, + chatState, + ], + ) + + // Start a new task + const startNewTask = useCallback(async () => { + setActiveQuote(null) + await TaskServiceClient.clearTask(EmptyRequest.create({})) + }, [setActiveQuote]) + + // Handle primary button click + const handlePrimaryButtonClick = useCallback( + async (text?: string, images?: string[], files?: string[]) => { + const trimmedInput = text?.trim() + switch (clineAsk) { + case "api_req_failed": + case "command": + case "command_output": + case "tool": + case "browser_action_launch": + case "use_mcp_server": + case "resume_task": + case "mistake_limit_reached": + case "auto_approval_max_req_reached": + if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "yesButtonClicked", + text: trimmedInput, + images: images, + files: files, + }), + ) + } else { + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "yesButtonClicked", + }), + ) + } + // Clear input state after sending + setInputValue("") + setActiveQuote(null) + setSelectedImages([]) + setSelectedFiles([]) + break + case "completion_result": + case "resume_completed_task": + startNewTask() + break + case "new_task": + console.info("new task button clicked!", { lastMessage, messages, clineAsk, text }) + await TaskServiceClient.newTask( + NewTaskRequest.create({ + text: lastMessage?.text, + images: [], + files: [], + }), + ) + break + case "condense": + await SlashServiceClient.condense(StringRequest.create({ value: lastMessage?.text })).catch((err) => + console.error(err), + ) + break + case "report_bug": + await SlashServiceClient.reportBug(StringRequest.create({ value: lastMessage?.text })).catch((err) => + console.error(err), + ) + break + } + setSendingDisabled(true) + setEnableButtons(false) + + // Reset auto-scroll + if ("disableAutoScrollRef" in chatState) { + ;(chatState as any).disableAutoScrollRef.current = false + } + }, + [ + clineAsk, + startNewTask, + lastMessage, + messages, + setInputValue, + setActiveQuote, + setSelectedImages, + setSelectedFiles, + setSendingDisabled, + setEnableButtons, + chatState, + ], + ) + + // Handle secondary button click + const handleSecondaryButtonClick = useCallback( + async (text?: string, images?: string[], files?: string[]) => { + const trimmedInput = text?.trim() + + if (isStreaming) { + await TaskServiceClient.cancelTask(EmptyRequest.create({})) + setDidClickCancel(true) + return + } + + switch (clineAsk) { + case "api_req_failed": + case "mistake_limit_reached": + case "auto_approval_max_req_reached": + startNewTask() + break + case "command": + case "tool": + case "browser_action_launch": + case "use_mcp_server": + if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "noButtonClicked", + text: trimmedInput, + images: images, + files: files, + }), + ) + } else { + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "noButtonClicked", + }), + ) + } + // Clear input state after sending + setInputValue("") + setActiveQuote(null) + setSelectedImages([]) + setSelectedFiles([]) + break + } + setSendingDisabled(true) + setEnableButtons(false) + + // Reset auto-scroll + if ("disableAutoScrollRef" in chatState) { + ;(chatState as any).disableAutoScrollRef.current = false + } + }, + [ + isStreaming, + clineAsk, + startNewTask, + setInputValue, + setActiveQuote, + setSelectedImages, + setSelectedFiles, + setSendingDisabled, + setEnableButtons, + setDidClickCancel, + chatState, + ], + ) + + // Handle task close button click + const handleTaskCloseButtonClick = useCallback(() => { + startNewTask() + }, [startNewTask]) + + return { + handleSendMessage, + handlePrimaryButtonClick, + handleSecondaryButtonClick, + handleTaskCloseButtonClick, + startNewTask, + } +} diff --git a/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts b/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts new file mode 100644 index 00000000..5cef086c --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts @@ -0,0 +1,232 @@ +import { useRef, useState, useCallback, useEffect, useMemo } from "react" +import { useEvent } from "react-use" +import debounce from "debounce" +import { VirtuosoHandle } from "react-virtuoso" +import { ClineMessage } from "@shared/ExtensionMessage" +import { ScrollBehavior } from "../types/chatTypes" + +/** + * Custom hook for managing scroll behavior + * Handles auto-scrolling, manual scrolling, and scroll-to-message functionality + */ +export function useScrollBehavior( + messages: ClineMessage[], + visibleMessages: ClineMessage[], + groupedMessages: (ClineMessage | ClineMessage[])[], + expandedRows: Record, + setExpandedRows: React.Dispatch>>, +): ScrollBehavior & { + showScrollToBottom: boolean + setShowScrollToBottom: React.Dispatch> + isAtBottom: boolean + setIsAtBottom: React.Dispatch> + pendingScrollToMessage: number | null + setPendingScrollToMessage: React.Dispatch> +} { + // Refs + const virtuosoRef = useRef(null) + const scrollContainerRef = useRef(null) + const disableAutoScrollRef = useRef(false) + + // State + const [showScrollToBottom, setShowScrollToBottom] = useState(false) + const [isAtBottom, setIsAtBottom] = useState(false) + const [pendingScrollToMessage, setPendingScrollToMessage] = useState(null) + + // Smooth scroll to bottom with debounce + const scrollToBottomSmooth = useMemo( + () => + debounce( + () => { + virtuosoRef.current?.scrollTo({ + top: Number.MAX_SAFE_INTEGER, + behavior: "smooth", + }) + }, + 10, + { immediate: true }, + ), + [], + ) + + // Instant scroll to bottom + const scrollToBottomAuto = useCallback(() => { + virtuosoRef.current?.scrollTo({ + top: Number.MAX_SAFE_INTEGER, + behavior: "auto", // instant causes crash + }) + }, []) + + // Scroll to specific message + const scrollToMessage = useCallback( + (messageIndex: number) => { + setPendingScrollToMessage(messageIndex) + + const targetMessage = messages[messageIndex] + if (!targetMessage) { + setPendingScrollToMessage(null) + return + } + + const visibleIndex = visibleMessages.findIndex((msg) => msg.ts === targetMessage.ts) + if (visibleIndex === -1) { + setPendingScrollToMessage(null) + return + } + + let groupIndex = -1 + let currentVisibleIndex = 0 + + for (let i = 0; i < groupedMessages.length; i++) { + const group = groupedMessages[i] + if (Array.isArray(group)) { + const groupSize = group.length + const messageInGroup = group.some((msg) => msg.ts === targetMessage.ts) + if (messageInGroup) { + groupIndex = i + break + } + currentVisibleIndex += groupSize + } else { + if (group.ts === targetMessage.ts) { + groupIndex = i + break + } + currentVisibleIndex++ + } + } + + if (groupIndex !== -1) { + setPendingScrollToMessage(null) + disableAutoScrollRef.current = true + requestAnimationFrame(() => { + requestAnimationFrame(() => { + virtuosoRef.current?.scrollToIndex({ + index: groupIndex, + align: "start", + behavior: "smooth", + }) + }) + }) + } + }, + [messages, visibleMessages, groupedMessages], + ) + + // Toggle row expansion with scroll handling + const toggleRowExpansion = useCallback( + (ts: number) => { + const isCollapsing = expandedRows[ts] ?? false + const lastGroup = groupedMessages.at(-1) + const isLast = Array.isArray(lastGroup) ? lastGroup[0].ts === ts : lastGroup?.ts === ts + const secondToLastGroup = groupedMessages.at(-2) + const isSecondToLast = Array.isArray(secondToLastGroup) + ? secondToLastGroup[0].ts === ts + : secondToLastGroup?.ts === ts + + const isLastCollapsedApiReq = + isLast && + !Array.isArray(lastGroup) && // Make sure it's not a browser session group + lastGroup?.say === "api_req_started" && + !expandedRows[lastGroup.ts] + + setExpandedRows((prev) => ({ + ...prev, + [ts]: !prev[ts], + })) + + // disable auto scroll when user expands row + if (!isCollapsing) { + disableAutoScrollRef.current = true + } + + if (isCollapsing && isAtBottom) { + const timer = setTimeout(() => { + scrollToBottomAuto() + }, 0) + return () => clearTimeout(timer) + } else if (isLast || isSecondToLast) { + if (isCollapsing) { + if (isSecondToLast && !isLastCollapsedApiReq) { + return + } + const timer = setTimeout(() => { + scrollToBottomAuto() + }, 0) + return () => clearTimeout(timer) + } else { + const timer = setTimeout(() => { + virtuosoRef.current?.scrollToIndex({ + index: groupedMessages.length - (isLast ? 1 : 2), + align: "start", + }) + }, 0) + return () => clearTimeout(timer) + } + } + }, + [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom, setExpandedRows], + ) + + // Handle row height changes + const handleRowHeightChange = useCallback( + (isTaller: boolean) => { + if (!disableAutoScrollRef.current) { + if (isTaller) { + scrollToBottomSmooth() + } else { + setTimeout(() => { + scrollToBottomAuto() + }, 0) + } + } + }, + [scrollToBottomSmooth, scrollToBottomAuto], + ) + + // Auto-scroll when new messages arrive + useEffect(() => { + if (!disableAutoScrollRef.current) { + setTimeout(() => { + scrollToBottomSmooth() + }, 50) + } + }, [groupedMessages.length, scrollToBottomSmooth]) + + // Handle pending scroll to message + useEffect(() => { + if (pendingScrollToMessage !== null) { + scrollToMessage(pendingScrollToMessage) + } + }, [pendingScrollToMessage, groupedMessages, scrollToMessage]) + + // Handle wheel events to detect manual scrolling + const handleWheel = useCallback((event: Event) => { + const wheelEvent = event as WheelEvent + if (wheelEvent.deltaY && wheelEvent.deltaY < 0) { + if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) { + // user scrolled up + disableAutoScrollRef.current = true + } + } + }, []) + + useEvent("wheel", handleWheel, window, { passive: true }) + + return { + virtuosoRef, + scrollContainerRef, + disableAutoScrollRef, + scrollToBottomSmooth, + scrollToBottomAuto, + scrollToMessage, + toggleRowExpansion, + handleRowHeightChange, + showScrollToBottom, + setShowScrollToBottom, + isAtBottom, + setIsAtBottom, + pendingScrollToMessage, + setPendingScrollToMessage, + } +} diff --git a/webview-ui/src/components/chat/chat-view/index.ts b/webview-ui/src/components/chat/chat-view/index.ts new file mode 100644 index 00000000..8c35d10d --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/index.ts @@ -0,0 +1,21 @@ +/** + * Barrel export for chat-view utilities, hooks, components, and types + */ + +// Export utilities +export * from "./utils/markdownUtils" +export * from "./utils/messageUtils" +export * from "./utils/scrollUtils" + +// Export hooks +export * from "./hooks" + +// Export layout components +export * from "./components/layout" + +// Export message components +export * from "./components/messages" + +// Export types and constants +export * from "./types/chatTypes" +export * from "./constants" diff --git a/webview-ui/src/components/chat/chat-view/types/chatTypes.ts b/webview-ui/src/components/chat/chat-view/types/chatTypes.ts new file mode 100644 index 00000000..a039bf18 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/types/chatTypes.ts @@ -0,0 +1,172 @@ +/** + * Shared types and interfaces for the chat view components + */ + +import { ClineMessage, ClineAsk } from "@shared/ExtensionMessage" +import { VirtuosoHandle } from "react-virtuoso" + +/** + * Main ChatView component props + */ +export interface ChatViewProps { + isHidden: boolean + showAnnouncement: boolean + hideAnnouncement: () => void + showHistoryView: () => void +} + +/** + * Chat state interface + */ +export interface ChatState { + // State values + inputValue: string + setInputValue: React.Dispatch> + activeQuote: string | null + setActiveQuote: React.Dispatch> + isTextAreaFocused: boolean + setIsTextAreaFocused: React.Dispatch> + selectedImages: string[] + setSelectedImages: React.Dispatch> + selectedFiles: string[] + setSelectedFiles: React.Dispatch> + sendingDisabled: boolean + setSendingDisabled: React.Dispatch> + enableButtons: boolean + setEnableButtons: React.Dispatch> + primaryButtonText: string | undefined + setPrimaryButtonText: React.Dispatch> + secondaryButtonText: string | undefined + setSecondaryButtonText: React.Dispatch> + didClickCancel: boolean + setDidClickCancel: React.Dispatch> + expandedRows: Record + setExpandedRows: React.Dispatch>> + + // Refs + textAreaRef: React.RefObject + + // Derived values + lastMessage: ClineMessage | undefined + secondLastMessage: ClineMessage | undefined + clineAsk: ClineAsk | undefined + task: ClineMessage | undefined + + // Handlers + handleFocusChange: (isFocused: boolean) => void + clearExpandedRows: () => void + resetState: () => void + + // Scroll-related state (will be moved to scroll hook) + showScrollToBottom?: boolean + isAtBottom?: boolean + pendingScrollToMessage?: number | null +} + +/** + * Message handlers interface + */ +export interface MessageHandlers { + handleSendMessage: (text: string, images: string[], files: string[]) => Promise + handlePrimaryButtonClick: (text?: string, images?: string[], files?: string[]) => Promise + handleSecondaryButtonClick: (text?: string, images?: string[], files?: string[]) => Promise + handleTaskCloseButtonClick: () => void + startNewTask: () => Promise +} + +/** + * Scroll behavior interface + */ +export interface ScrollBehavior { + virtuosoRef: React.RefObject + scrollContainerRef: React.RefObject + disableAutoScrollRef: React.MutableRefObject + scrollToBottomSmooth: () => void + scrollToBottomAuto: () => void + scrollToMessage: (messageIndex: number) => void + toggleRowExpansion: (ts: number) => void + handleRowHeightChange: (isTaller: boolean) => void + showScrollToBottom: boolean + setShowScrollToBottom: React.Dispatch> + isAtBottom: boolean + setIsAtBottom: React.Dispatch> + pendingScrollToMessage: number | null + setPendingScrollToMessage: React.Dispatch> +} + +/** + * Button state interface + */ +export interface ButtonState { + enableButtons: boolean + primaryButtonText: string | undefined + secondaryButtonText: string | undefined +} + +/** + * Input state interface + */ +export interface InputState { + inputValue: string + selectedImages: string[] + selectedFiles: string[] + activeQuote: string | null + isTextAreaFocused: boolean +} + +/** + * Task section props + */ +export interface TaskSectionProps { + task: ClineMessage + messages: ClineMessage[] + scrollBehavior: ScrollBehavior + buttonState: ButtonState + messageHandlers: MessageHandlers + chatState: ChatState + apiMetrics: { + totalTokensIn: number + totalTokensOut: number + totalCacheWrites?: number + totalCacheReads?: number + totalCost: number + } + lastApiReqTotalTokens?: number + selectedModelInfo: { + supportsPromptCache: boolean + supportsImages: boolean + } + isStreaming: boolean + clineAsk?: ClineAsk + modifiedMessages: ClineMessage[] +} + +/** + * Welcome section props + */ +export interface WelcomeSectionProps { + showAnnouncement: boolean + hideAnnouncement: () => void + showHistoryView: () => void + telemetrySetting: string + version: string + taskHistory: any[] + shouldShowQuickWins: boolean +} + +/** + * Input section props + */ +export interface InputSectionProps { + chatState: ChatState + messageHandlers: MessageHandlers + textAreaRef: React.RefObject + onFocusChange: (isFocused: boolean) => void + onInputChange: (value: string) => void + onQuoteChange: (quote: string | null) => void + onImagesChange: (images: string[]) => void + onFilesChange: (files: string[]) => void + placeholderText: string + shouldDisableFilesAndImages: boolean + selectFilesAndImages: () => Promise +} diff --git a/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts b/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts new file mode 100644 index 00000000..fcd079f6 --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts @@ -0,0 +1,58 @@ +/** + * Utility functions for handling markdown conversions and cleanup + */ + +import { unified } from "unified" +import remarkStringify from "remark-stringify" +import rehypeRemark from "rehype-remark" +import rehypeParse from "rehype-parse" + +/** + * Clean up markdown escape characters + */ +export function cleanupMarkdownEscapes(markdown: string): string { + return ( + markdown + // Handle underscores and asterisks (single or multiple) + .replace(/\\([_*]+)/g, "$1") + + // Handle angle brackets (for generics and XML) + .replace(/\\([<>])/g, "$1") + + // Handle backticks (for code) + .replace(/\\(`)/g, "$1") + + // Handle other common markdown special characters + .replace(/\\([[\]()#.!])/g, "$1") + + // Fix multiple consecutive backslashes + .replace(/\\{2,}([_*`<>[\]()#.!])/g, "$1") + ) +} + +/** + * Convert HTML to Markdown + */ +export async function convertHtmlToMarkdown(html: string): Promise { + // Process the HTML to Markdown + const result = await unified() + .use(rehypeParse as any, { fragment: true }) // Parse HTML fragments + .use(rehypeRemark as any) // Convert HTML to Markdown AST + .use(remarkStringify as any, { + // Convert Markdown AST to text + bullet: "-", // Use - for unordered lists + emphasis: "*", // Use * for emphasis + strong: "_", // Use _ for strong + listItemIndent: "one", // Use one space for list indentation + rule: "-", // Use - for horizontal rules + ruleSpaces: false, // No spaces in horizontal rules + fences: true, + escape: false, + entities: false, + }) + .process(html) + + const md = String(result) + // Apply comprehensive cleanup of escape characters + return cleanupMarkdownEscapes(md) +} diff --git a/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts b/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts new file mode 100644 index 00000000..ab5c12ac --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts @@ -0,0 +1,151 @@ +/** + * Utility functions for message filtering, grouping, and manipulation + */ + +import { ClineMessage, ClineSayBrowserAction } from "@shared/ExtensionMessage" +import { combineApiRequests } from "@shared/combineApiRequests" +import { combineCommandSequences } from "@shared/combineCommandSequences" + +/** + * Combine API requests and command sequences in messages + */ +export function processMessages(messages: ClineMessage[]): ClineMessage[] { + return combineApiRequests(combineCommandSequences(messages)) +} + +/** + * Filter messages that should be visible in the chat + */ +export function filterVisibleMessages(messages: ClineMessage[]): ClineMessage[] { + return messages.filter((message) => { + switch (message.ask) { + case "completion_result": + // don't show a chat row for a completion_result ask without text + if (message.text === "") { + return false + } + break + case "api_req_failed": + case "resume_task": + case "resume_completed_task": + return false + } + switch (message.say) { + case "api_req_finished": + case "api_req_retried": + case "deleted_api_reqs": + return false + case "text": + // Sometimes cline returns an empty text message, we don't want to render these + if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) { + return false + } + break + case "mcp_server_request_started": + return false + } + return true + }) +} + +/** + * Check if a message is part of a browser session + */ +export function isBrowserSessionMessage(message: ClineMessage): boolean { + if (message.type === "ask") { + return ["browser_action_launch"].includes(message.ask!) + } + if (message.type === "say") { + return [ + "browser_action_launch", + "api_req_started", + "text", + "browser_action", + "browser_action_result", + "checkpoint_created", + "reasoning", + ].includes(message.say!) + } + return false +} + +/** + * Group messages, combining browser session messages into arrays + */ +export function groupMessages(visibleMessages: ClineMessage[]): (ClineMessage | ClineMessage[])[] { + const result: (ClineMessage | ClineMessage[])[] = [] + let currentGroup: ClineMessage[] = [] + let isInBrowserSession = false + + const endBrowserSession = () => { + if (currentGroup.length > 0) { + result.push([...currentGroup]) + currentGroup = [] + isInBrowserSession = false + } + } + + visibleMessages.forEach((message) => { + if (message.ask === "browser_action_launch" || message.say === "browser_action_launch") { + // complete existing browser session if any + endBrowserSession() + // start new + isInBrowserSession = true + currentGroup.push(message) + } else if (isInBrowserSession) { + // end session if api_req_started is cancelled + if (message.say === "api_req_started") { + // get last api_req_started in currentGroup to check if it's cancelled + const lastApiReqStarted = [...currentGroup].reverse().find((m) => m.say === "api_req_started") + if (lastApiReqStarted?.text != null) { + const info = JSON.parse(lastApiReqStarted.text) + const isCancelled = info.cancelReason != null + if (isCancelled) { + endBrowserSession() + result.push(message) + return + } + } + } + + if (isBrowserSessionMessage(message)) { + currentGroup.push(message) + + // Check if this is a close action + if (message.say === "browser_action") { + const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction + if (browserAction.action === "close") { + endBrowserSession() + } + } + } else { + // complete existing browser session if any + endBrowserSession() + result.push(message) + } + } else { + result.push(message) + } + }) + + // Handle case where browser session is the last group + if (currentGroup.length > 0) { + result.push([...currentGroup]) + } + + return result +} + +/** + * Get the task message from the messages array + */ +export function getTaskMessage(messages: ClineMessage[]): ClineMessage | undefined { + return messages.at(0) +} + +/** + * Check if we should show the scroll to bottom button + */ +export function shouldShowScrollButton(disableAutoScroll: boolean, isAtBottom: boolean): boolean { + return disableAutoScroll && !isAtBottom +} diff --git a/webview-ui/src/components/chat/chat-view/utils/scrollUtils.ts b/webview-ui/src/components/chat/chat-view/utils/scrollUtils.ts new file mode 100644 index 00000000..3ae1237d --- /dev/null +++ b/webview-ui/src/components/chat/chat-view/utils/scrollUtils.ts @@ -0,0 +1,60 @@ +/** + * Utility functions for scroll behavior and management + */ + +import debounce from "debounce" +import { VirtuosoHandle } from "react-virtuoso" + +/** + * Create a debounced smooth scroll function + */ +export function createSmoothScrollToBottom(virtuosoRef: React.RefObject) { + return debounce( + () => { + virtuosoRef.current?.scrollTo({ + top: Number.MAX_SAFE_INTEGER, + behavior: "smooth", + }) + }, + 10, + { immediate: true }, + ) +} + +/** + * Scroll to bottom with auto behavior + */ +export function scrollToBottomAuto(virtuosoRef: React.RefObject) { + virtuosoRef.current?.scrollTo({ + top: Number.MAX_SAFE_INTEGER, + behavior: "auto", // instant causes crash + }) +} + +/** + * Handle wheel events to detect user scroll + */ +export function createWheelHandler( + scrollContainerRef: React.RefObject, + disableAutoScrollRef: React.MutableRefObject, +) { + return (event: Event) => { + const wheelEvent = event as WheelEvent + if (wheelEvent.deltaY && wheelEvent.deltaY < 0) { + if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) { + // user scrolled up + disableAutoScrollRef.current = true + } + } + } +} + +/** + * Constants for scroll behavior + */ +export const SCROLL_CONSTANTS = { + AT_BOTTOM_THRESHOLD: 10, + VIEWPORT_INCREASE_TOP: 3_000, + VIEWPORT_INCREASE_BOTTOM: Number.MAX_SAFE_INTEGER, + FOOTER_HEIGHT: 5, +} as const From c8b05cdf9cc3b12babfc59bf09a82427fa7b298b Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 30 Jun 2025 14:03:41 -0700 Subject: [PATCH 38/60] Remove unused property postMessageToWebview from Task (#4587) Cleanup imports. --- src/core/controller/index.ts | 56 ++++++++++------------ src/core/task/index.ts | 90 +++++++++++++++--------------------- 2 files changed, 61 insertions(+), 85 deletions(-) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 9d4530e8..c4c78126 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -1,31 +1,31 @@ +import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" +import { getCwd } from "@/utils/path" import { Anthropic } from "@anthropic-ai/sdk" +import { buildApiHandler } from "@api/index" +import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration" +import { extractCommitMessage } from "@integrations/git/commit-message-generator" +import { downloadTask } from "@integrations/misc/export-markdown" +import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" +import { ClineAccountService } from "@services/account/ClineAccountService" +import { McpHub } from "@services/mcp/McpHub" +import { ApiProvider, ModelInfo } from "@shared/api" +import { ChatContent } from "@shared/ChatContent" +import { ChatSettings, StoredChatSettings } from "@shared/ChatSettings" +import { ClineRulesToggles } from "@shared/cline-rules" +import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage" +import { HistoryItem } from "@shared/HistoryItem" +import { McpMarketplaceCatalog } from "@shared/mcp" +import { TelemetrySetting } from "@shared/TelemetrySetting" +import { UserInfo } from "@shared/UserInfo" +import { WebviewMessage } from "@shared/WebviewMessage" +import { fileExistsAtPath } from "@utils/fs" +import { getWorkingState } from "@utils/git" import axios from "axios" -import { v4 as uuidv4 } from "uuid" import fs from "fs/promises" import { setTimeout as setTimeoutPromise } from "node:timers/promises" import pWaitFor from "p-wait-for" import * as path from "path" import * as vscode from "vscode" -import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler" -import { buildApiHandler } from "@api/index" -import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration" -import { downloadTask } from "@integrations/misc/export-markdown" -import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" -import { ClineAccountService } from "@services/account/ClineAccountService" -import { McpHub } from "@services/mcp/McpHub" -import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" -import { ApiProvider, ModelInfo } from "@shared/api" -import { ChatContent } from "@shared/ChatContent" -import { ChatSettings, StoredChatSettings } from "@shared/ChatSettings" -import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage" -import { HistoryItem } from "@shared/HistoryItem" -import { McpMarketplaceCatalog } from "@shared/mcp" -import { UserInfo } from "@shared/UserInfo" -import { TelemetrySetting } from "@shared/TelemetrySetting" -import { WebviewMessage } from "@shared/WebviewMessage" -import { fileExistsAtPath } from "@utils/fs" -import { getWorkingState } from "@utils/git" -import { extractCommitMessage } from "@integrations/git/commit-message-generator" import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk" import { getAllExtensionState, @@ -33,22 +33,15 @@ import { getSecret, getWorkspaceState, storeSecret, - updateApiConfiguration, updateGlobalState, updateWorkspaceState, } from "../storage/state" import { Task } from "../task" -import { ClineRulesToggles } from "@shared/cline-rules" +import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback" +import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler" +import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" import { sendStateUpdate } from "./state/subscribeToState" import { sendAddToInputEvent } from "./ui/subscribeToAddToInput" -import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback" -import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" -import { sendRelinquishControlEvent } from "./ui/subscribeToRelinquishControl" -import { handleTaskServiceRequest } from "./task" -import { BooleanRequest } from "@shared/proto/common" -import { getHostBridgeProvider } from "@/hosts/host-providers" -import { GetWorkspacePathsRequest } from "@/shared/proto/index.host" -import { getCwd } from "@/utils/path" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts @@ -178,7 +171,6 @@ export class Controller { this.workspaceTracker, (historyItem) => this.updateTaskHistory(historyItem), () => this.postStateToWebview(), - (message) => this.postMessageToWebview(message), (taskId) => this.reinitExistingTaskFromId(taskId), () => this.cancelTask(), apiConfiguration, diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 456db6ff..a875a4d6 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -1,13 +1,4 @@ import { Anthropic } from "@anthropic-ai/sdk" -import cloneDeep from "clone-deep" -import { execa } from "execa" -import { setTimeout as setTimeoutPromise } from "node:timers/promises" -import os from "os" -import pTimeout from "p-timeout" -import pWaitFor from "p-wait-for" -import * as path from "path" -import * as vscode from "vscode" -import { Logger } from "@services/logging/Logger" import { ApiHandler, buildApiHandler } from "@api/index" import { AnthropicHandler } from "@api/providers/anthropic" import { ClineHandler } from "@api/providers/cline" @@ -21,6 +12,7 @@ import { TerminalManager } from "@integrations/terminal/TerminalManager" import { BrowserSession } from "@services/browser/BrowserSession" import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" import { listFiles } from "@services/glob/list-files" +import { Logger } from "@services/logging/Logger" import { telemetryService } from "@services/posthog/telemetry/TelemetryService" import { ApiConfiguration } from "@shared/api" import { findLast, findLastIndex } from "@shared/array" @@ -29,42 +21,47 @@ import { BrowserSettings } from "@shared/BrowserSettings" import { ChatSettings } from "@shared/ChatSettings" import { combineApiRequests } from "@shared/combineApiRequests" import { combineCommandSequences } from "@shared/combineCommandSequences" -import { - ClineApiReqCancelReason, - ClineApiReqInfo, - ClineAsk, - ClineMessage, - ClineSay, - ExtensionMessage, -} from "@shared/ExtensionMessage" +import { ClineApiReqCancelReason, ClineApiReqInfo, ClineAsk, ClineMessage, ClineSay } from "@shared/ExtensionMessage" import { getApiMetrics } from "@shared/getApiMetrics" import { HistoryItem } from "@shared/HistoryItem" import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages" import { ClineAskResponse, ClineCheckpointRestore } from "@shared/WebviewMessage" import { arePathsEqual } from "@utils/path" +import cloneDeep from "clone-deep" +import { execa } from "execa" +import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import os from "os" +import pTimeout from "p-timeout" +import pWaitFor from "p-wait-for" +import * as path from "path" +import * as vscode from "vscode" -import { - AssistantMessageContent, - parseAssistantMessageV2, - parseAssistantMessageV3, - ToolParamName, - ToolUseName, -} from "@core/assistant-message" -import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" -import { parseMentions } from "@core/mentions" -import { formatResponse } from "@core/prompts/responses" -import { addUserInstructions, SYSTEM_PROMPT } from "@core/prompts/system" -import { sendPartialMessageEvent } from "@core/controller/ui/subscribeToPartialMessage" -import { sendRelinquishControlEvent } from "@core/controller/ui/subscribeToRelinquishControl" -import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message" -import { getContextWindowInfo } from "@core/context/context-management/context-window-utils" -import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" -import { ModelContextTracker } from "@core/context/context-tracking/ModelContextTracker" +import { parseAssistantMessageV2, parseAssistantMessageV3, ToolUseName } from "@core/assistant-message" import { checkIsAnthropicContextWindowError, checkIsOpenRouterContextWindowError, } from "@core/context/context-management/context-error-handling" +import { getContextWindowInfo } from "@core/context/context-management/context-window-utils" import { ContextManager } from "@core/context/context-management/ContextManager" +import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" +import { ModelContextTracker } from "@core/context/context-tracking/ModelContextTracker" +import { + getGlobalClineRules, + getLocalClineRules, + refreshClineRulesToggles, +} from "@core/context/instructions/user-instructions/cline-rules" +import { + getLocalCursorRules, + getLocalWindsurfRules, + refreshExternalRulesToggles, +} from "@core/context/instructions/user-instructions/external-rules" +import { sendPartialMessageEvent } from "@core/controller/ui/subscribeToPartialMessage" +import { sendRelinquishControlEvent } from "@core/controller/ui/subscribeToRelinquishControl" +import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import { parseMentions } from "@core/mentions" +import { formatResponse } from "@core/prompts/responses" +import { addUserInstructions, SYSTEM_PROMPT } from "@core/prompts/system" +import { parseSlashCommands } from "@core/slash-commands" import { ensureRulesDirectoryExists, ensureTaskDirectoryExists, @@ -72,29 +69,19 @@ import { getSavedClineMessages, GlobalFileNames, } from "@core/storage/disk" -import { - getGlobalClineRules, - getLocalClineRules, - refreshClineRulesToggles, -} from "@core/context/instructions/user-instructions/cline-rules" -import { ensureLocalClineDirExists } from "../context/instructions/user-instructions/rule-helpers" -import { - refreshExternalRulesToggles, - getLocalWindsurfRules, - getLocalCursorRules, -} from "@core/context/instructions/user-instructions/external-rules" -import { refreshWorkflowToggles } from "../context/instructions/user-instructions/workflows" import { getWorkspaceState } from "@core/storage/state" -import { parseSlashCommands } from "@core/slash-commands" +import { processFilesIntoText } from "@integrations/misc/extract-text" import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" import { McpHub } from "@services/mcp/McpHub" -import { isInTestMode } from "../../services/test/TestMode" -import { processFilesIntoText } from "@integrations/misc/extract-text" +import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message" import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils" +import { isInTestMode } from "../../services/test/TestMode" +import { ensureLocalClineDirExists } from "../context/instructions/user-instructions/rule-helpers" +import { refreshWorkflowToggles } from "../context/instructions/user-instructions/workflows" import { MessageStateHandler } from "./message-state" -import { formatErrorWithStatusCode, updateApiReqMsg } from "./utils" import { TaskState } from "./TaskState" import { ToolExecutor } from "./ToolExecutor" +import { formatErrorWithStatusCode, updateApiReqMsg } from "./utils" export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false @@ -137,7 +124,6 @@ export class Task { // Callbacks private updateTaskHistory: (historyItem: HistoryItem) => Promise private postStateToWebview: () => Promise - private postMessageToWebview: (message: ExtensionMessage) => Promise private reinitExistingTaskFromId: (taskId: string) => Promise private cancelTask: () => Promise @@ -154,7 +140,6 @@ export class Task { workspaceTracker: WorkspaceTracker, updateTaskHistory: (historyItem: HistoryItem) => Promise, postStateToWebview: () => Promise, - postMessageToWebview: (message: ExtensionMessage) => Promise, reinitExistingTaskFromId: (taskId: string) => Promise, cancelTask: () => Promise, apiConfiguration: ApiConfiguration, @@ -177,7 +162,6 @@ export class Task { this.workspaceTracker = workspaceTracker this.updateTaskHistory = updateTaskHistory this.postStateToWebview = postStateToWebview - this.postMessageToWebview = postMessageToWebview this.reinitExistingTaskFromId = reinitExistingTaskFromId this.cancelTask = cancelTask this.clineIgnoreController = new ClineIgnoreController(cwd) From 4d2fec787ec07934209be57ddd642a9db995602d Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 30 Jun 2025 14:54:36 -0700 Subject: [PATCH 39/60] Replace uses of workspaceFolders from the vscode SDK with the host bridge (#4589) * Switch openMention to use getCwd instead of using the vscode SDK directly. * Use getCwd in services/test/TestServer.ts instead of using the vscode SDK. Don't get the cwd from the controller extension context global state, use the workspace folder as the rest of the codebase is doing. Replace GitHelper.getWorkspacePath with utils.getCwd() * Use host bridge getWorkspacePaths in services/test/TestMode.ts -instead of using the vscode SDK. Remove unsed param `context` * Remove unused file CheckpointTracker-old.ts * Use hostbridge getCwd in CheckpointUtils.ts and message-state.ts --- src/core/controller/file/openMention.ts | 2 +- src/core/mentions/index.ts | 5 +- src/core/task/message-state.ts | 4 +- src/extension.ts | 3 +- .../checkpoints/CheckpointTracker-old.ts | 422 ------------------ .../checkpoints/CheckpointUtils.ts | 3 +- src/services/test/GitHelper.ts | 29 +- src/services/test/TestMode.ts | 15 +- src/services/test/TestServer.ts | 13 +- 9 files changed, 23 insertions(+), 473 deletions(-) delete mode 100644 src/integrations/checkpoints/CheckpointTracker-old.ts diff --git a/src/core/controller/file/openMention.ts b/src/core/controller/file/openMention.ts index ad996e47..8d152419 100644 --- a/src/core/controller/file/openMention.ts +++ b/src/core/controller/file/openMention.ts @@ -8,7 +8,7 @@ import { openMention as coreOpenMention } from "../../mentions" * @param request The string request containing the mention text * @returns Empty response */ -export async function openMention(controller: Controller, request: StringRequest): Promise { +export async function openMention(_controller: Controller, request: StringRequest): Promise { coreOpenMention(request.value) return Empty.create() } diff --git a/src/core/mentions/index.ts b/src/core/mentions/index.ts index 611ed7b6..6a8bbb01 100644 --- a/src/core/mentions/index.ts +++ b/src/core/mentions/index.ts @@ -11,13 +11,14 @@ import { getLatestTerminalOutput } from "@integrations/terminal/get-latest-outpu import { getCommitInfo } from "@utils/git" import { getWorkingState } from "@utils/git" import { FileContextTracker } from "../context/context-tracking/FileContextTracker" +import { getCwd } from "@/utils/path" -export function openMention(mention?: string): void { +export async function openMention(mention?: string): Promise { if (!mention) { return } - const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) + const cwd = await getCwd() if (!cwd) { return } diff --git a/src/core/task/message-state.ts b/src/core/task/message-state.ts index e261d33c..04d794a9 100644 --- a/src/core/task/message-state.ts +++ b/src/core/task/message-state.ts @@ -12,6 +12,7 @@ import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker" import { HistoryItem } from "@/shared/HistoryItem" import Anthropic from "@anthropic-ai/sdk" import { TaskState } from "./TaskState" +import { getCwd } from "@/utils/path" interface MessageStateHandlerParams { context: vscode.ExtensionContext @@ -21,8 +22,6 @@ interface MessageStateHandlerParams { taskState: TaskState } -const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution - export class MessageStateHandler { private apiConversationHistory: Anthropic.MessageParam[] = [] private clineMessages: ClineMessage[] = [] @@ -84,6 +83,7 @@ export class MessageStateHandler { } catch (error) { console.error("Failed to get task directory size:", taskDir, error) } + const cwd = await getCwd(path.join(os.homedir(), "Desktop")) await this.updateTaskHistory({ id: this.taskId, ts: lastRelevantMessage.ts, diff --git a/src/extension.ts b/src/extension.ts index 5576f7b8..dcc570db 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -76,8 +76,9 @@ export async function activate(context: vscode.ExtensionContext) { const previousVersion = context.globalState.get("clineVersion") const sidebarWebview = hostProviders.createWebviewProvider(WebviewProviderType.SIDEBAR) + const testModeWatchers = await initializeTestMode(sidebarWebview) // Initialize test mode and add disposables to context - context.subscriptions.push(...initializeTestMode(context, sidebarWebview)) + context.subscriptions.push(...testModeWatchers) vscode.commands.executeCommand("setContext", "cline.isDevMode", IS_DEV && IS_DEV === "true") diff --git a/src/integrations/checkpoints/CheckpointTracker-old.ts b/src/integrations/checkpoints/CheckpointTracker-old.ts deleted file mode 100644 index cab89b88..00000000 --- a/src/integrations/checkpoints/CheckpointTracker-old.ts +++ /dev/null @@ -1,422 +0,0 @@ -import fs from "fs/promises" -import os from "os" -import * as path from "path" -import simpleGit, { SimpleGit } from "simple-git" -import * as vscode from "vscode" -import { Controller as ClineProvider } from "@core/controller" -import { fileExistsAtPath } from "@utils/fs" -import { globby } from "globby" - -class CheckpointTracker { - private providerRef: WeakRef - private taskId: string - private disposables: vscode.Disposable[] = [] - private cwd: string - private lastRetrievedShadowGitConfigWorkTree?: string - lastCheckpointHash?: string - - private constructor(provider: ClineProvider, taskId: string, cwd: string) { - this.providerRef = new WeakRef(provider) - this.taskId = taskId - this.cwd = cwd - } - - public static async create( - taskId: string, - enableCheckpointsSetting: boolean, - provider?: ClineProvider, - ): Promise { - try { - if (!provider) { - throw new Error("Provider is required to create a checkpoint tracker") - } - - if (!enableCheckpointsSetting) { - return undefined // Don't create tracker when disabled - } - - // Check if git is installed by attempting to get version - try { - await simpleGit().version() - } catch (error) { - throw new Error("Git must be installed to use checkpoints.") // FIXME: must match what we check for in TaskHeader to show link - } - - const cwd = await CheckpointTracker.getWorkingDirectory() - const newTracker = new CheckpointTracker(provider, taskId, cwd) - await newTracker.initShadowGit() - return newTracker - } catch (error) { - console.error("Failed to create CheckpointTracker:", error) - throw error - } - } - - private static async getWorkingDirectory(): Promise { - const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) - if (!cwd) { - throw new Error("No workspace detected. Please open Cline in a workspace to use checkpoints.") - } - const homedir = os.homedir() - const desktopPath = path.join(homedir, "Desktop") - const documentsPath = path.join(homedir, "Documents") - const downloadsPath = path.join(homedir, "Downloads") - - switch (cwd) { - case homedir: - throw new Error("Cannot use checkpoints in home directory") - case desktopPath: - throw new Error("Cannot use checkpoints in Desktop directory") - case documentsPath: - throw new Error("Cannot use checkpoints in Documents directory") - case downloadsPath: - throw new Error("Cannot use checkpoints in Downloads directory") - default: - return cwd - } - } - - private async getShadowGitPath(): Promise { - const globalStoragePath = this.providerRef.deref()?.context.globalStorageUri.fsPath - if (!globalStoragePath) { - throw new Error("Global storage uri is invalid") - } - const checkpointsDir = path.join(globalStoragePath, "tasks", this.taskId, "checkpoints") - await fs.mkdir(checkpointsDir, { recursive: true }) - const gitPath = path.join(checkpointsDir, ".git") - return gitPath - } - - public static async doesShadowGitExist(taskId: string, provider?: ClineProvider): Promise { - const globalStoragePath = provider?.context.globalStorageUri.fsPath - if (!globalStoragePath) { - return false - } - const gitPath = path.join(globalStoragePath, "tasks", taskId, "checkpoints", ".git") - return await fileExistsAtPath(gitPath) - } - - public async initShadowGit(): Promise { - const gitPath = await this.getShadowGitPath() - if (await fileExistsAtPath(gitPath)) { - // Make sure it's the same cwd as the configured worktree - const worktree = await this.getShadowGitConfigWorkTree() - if (worktree !== this.cwd) { - throw new Error("Checkpoints can only be used in the original workspace: " + worktree) - } - - return gitPath - } else { - const checkpointsDir = path.dirname(gitPath) - const git = simpleGit(checkpointsDir) - await git.init() - - await git.addConfig("core.worktree", this.cwd) // sets the working tree to the current workspace - - // Disable commit signing for shadow repo - await git.addConfig("commit.gpgSign", "false") - - // Get LFS patterns from workspace if they exist - let lfsPatterns: string[] = [] - try { - const attributesPath = path.join(this.cwd, ".gitattributes") - if (await fileExistsAtPath(attributesPath)) { - const attributesContent = await fs.readFile(attributesPath, "utf8") - lfsPatterns = attributesContent - .split("\n") - .filter((line) => line.includes("filter=lfs")) - .map((line) => line.split(" ")[0].trim()) - } - } catch (error) { - console.warn("Failed to read .gitattributes:", error) - } - - // Add basic excludes directly in git config, while respecting any .gitignore in the workspace - // .git/info/exclude is local to the shadow git repo, so it's not shared with the main repo - and won't conflict with user's .gitignore - // TODO: let user customize these - const excludesPath = path.join(gitPath, "info", "exclude") - await fs.mkdir(path.join(gitPath, "info"), { recursive: true }) - await fs.writeFile( - excludesPath, - [ - ".git/", // ignore the user's .git - `.git${GIT_DISABLED_SUFFIX}/`, // ignore the disabled nested git repos - ".DS_Store", - "*.log", - "node_modules/", - "__pycache__/", - "env/", - "venv/", - "target/dependency/", - "build/dependencies/", - "dist/", - "out/", - "bundle/", - "vendor/", - "tmp/", - "temp/", - "deps/", - "pkg/", - "Pods/", - // Media files - "*.jpg", - "*.jpeg", - "*.png", - "*.gif", - "*.bmp", - "*.ico", - // "*.svg", - "*.mp3", - "*.mp4", - "*.wav", - "*.avi", - "*.mov", - "*.wmv", - "*.webm", - "*.webp", - "*.m4a", - "*.flac", - // Build and dependency directories - "build/", - "bin/", - "obj/", - ".gradle/", - ".idea/", - ".vscode/", - ".vs/", - "coverage/", - ".next/", - ".nuxt/", - // Cache and temporary files - "*.cache", - "*.tmp", - "*.temp", - "*.swp", - "*.swo", - "*.pyc", - "*.pyo", - ".pytest_cache/", - ".eslintcache", - // Environment and config files - ".env*", - "*.local", - "*.development", - "*.production", - // Large data files - "*.zip", - "*.tar", - "*.gz", - "*.rar", - "*.7z", - "*.iso", - "*.bin", - "*.exe", - "*.dll", - "*.so", - "*.dylib", - // Database files - "*.sqlite", - "*.db", - "*.sql", - // Log files - "*.logs", - "*.error", - "npm-debug.log*", - "yarn-debug.log*", - "yarn-error.log*", - ...lfsPatterns, - ].join("\n"), - ) - - // Set up git identity (git throws an error if user.name or user.email is not set) - await git.addConfig("user.name", "Cline Checkpoint") - await git.addConfig("user.email", "noreply@example.com") - - await this.addAllFiles(git) - // Initial commit (--allow-empty ensures it works even with no files) - await git.commit("initial commit", { "--allow-empty": null }) - - return gitPath - } - } - - public async getShadowGitConfigWorkTree(): Promise { - if (this.lastRetrievedShadowGitConfigWorkTree) { - return this.lastRetrievedShadowGitConfigWorkTree - } - try { - const gitPath = await this.getShadowGitPath() - const git = simpleGit(path.dirname(gitPath)) - const worktree = await git.getConfig("core.worktree") - this.lastRetrievedShadowGitConfigWorkTree = worktree.value || undefined - return this.lastRetrievedShadowGitConfigWorkTree - } catch (error) { - console.error("Failed to get shadow git config worktree:", error) - return undefined - } - } - - public async commit(): Promise { - try { - const gitPath = await this.getShadowGitPath() - const git = simpleGit(path.dirname(gitPath)) - await this.addAllFiles(git) - const result = await git.commit("checkpoint", { - "--allow-empty": null, - }) - const commitHash = result.commit || "" - this.lastCheckpointHash = commitHash - return commitHash - } catch (error) { - console.error("Failed to create checkpoint:", error) - return undefined - } - } - - public async resetHead(commitHash: string): Promise { - const gitPath = await this.getShadowGitPath() - const git = simpleGit(path.dirname(gitPath)) - - // Clean working directory and force reset - // This ensures that the operation will succeed regardless of: - // - Untracked files in the workspace - // - Staged changes - // - Unstaged changes - // - Partial commits - // - Merge conflicts - await git.clean("f", ["-d", "-f"]) // Remove untracked files and directories - await git.reset(["--hard", commitHash]) // Hard reset to target commit - } - - /** - * Return an array describing changed files between one commit and either: - * - another commit, or - * - the current working directory (including uncommitted changes). - * - * If `rhsHash` is omitted, compares `lhsHash` to the working directory. - * If you want truly untracked files to appear, `git add` them first. - * - * @param lhsHash - The commit to compare from (older commit) - * @param rhsHash - The commit to compare to (newer commit). - * If omitted, we compare to the working directory. - * @returns Array of file changes with before/after content - */ - public async getDiffSet( - lhsHash?: string, - rhsHash?: string, - ): Promise< - Array<{ - relativePath: string - absolutePath: string - before: string - after: string - }> - > { - const gitPath = await this.getShadowGitPath() - const git = simpleGit(path.dirname(gitPath)) - - // If lhsHash is missing, use the initial commit of the repo - let baseHash = lhsHash - if (!baseHash) { - const rootCommit = await git.raw(["rev-list", "--max-parents=0", "HEAD"]) - baseHash = rootCommit.trim() - } - - // Stage all changes so that untracked files appear in diff summary - await this.addAllFiles(git) - - const diffSummary = rhsHash ? await git.diffSummary([`${baseHash}..${rhsHash}`]) : await git.diffSummary([baseHash]) - - // For each changed file, gather before/after content - const result = [] - const cwdPath = (await this.getShadowGitConfigWorkTree()) || this.cwd || "" - - for (const file of diffSummary.files) { - const filePath = file.file - const absolutePath = path.join(cwdPath, filePath) - - let beforeContent = "" - try { - beforeContent = await git.show([`${baseHash}:${filePath}`]) - } catch (_) { - // file didn't exist in older commit => remains empty - } - - let afterContent = "" - if (rhsHash) { - // if user provided a newer commit, use git.show at that commit - try { - afterContent = await git.show([`${rhsHash}:${filePath}`]) - } catch (_) { - // file didn't exist in newer commit => remains empty - } - } else { - // otherwise, read from disk (includes uncommitted changes) - try { - afterContent = await fs.readFile(absolutePath, "utf8") - } catch (_) { - // file might be deleted => remains empty - } - } - - result.push({ - relativePath: filePath, - absolutePath, - before: beforeContent, - after: afterContent, - }) - } - - return result - } - - private async addAllFiles(git: SimpleGit) { - await this.renameNestedGitRepos(true) - try { - await git.add(".") - } catch (error) { - console.error("Failed to add files to git:", error) - } finally { - await this.renameNestedGitRepos(false) - } - } - - // Since we use git to track checkpoints, we need to temporarily disable nested git repos to work around git's requirement of using submodules for nested repos. - private async renameNestedGitRepos(disable: boolean) { - // Find all .git directories that are not at the root level - const gitPaths = await globby("**/.git" + (disable ? "" : GIT_DISABLED_SUFFIX), { - cwd: this.cwd, - onlyDirectories: true, - ignore: [".git"], // Ignore root level .git - dot: true, - markDirectories: false, - }) - - // For each nested .git directory, rename it based on operation - for (const gitPath of gitPaths) { - const fullPath = path.join(this.cwd, gitPath) - let newPath: string - if (disable) { - newPath = fullPath + GIT_DISABLED_SUFFIX - } else { - newPath = fullPath.endsWith(GIT_DISABLED_SUFFIX) ? fullPath.slice(0, -GIT_DISABLED_SUFFIX.length) : fullPath - } - - try { - await fs.rename(fullPath, newPath) - console.log(`CheckpointTracker ${disable ? "disabled" : "enabled"} nested git repo ${gitPath}`) - } catch (error) { - console.error(`CheckpointTracker failed to ${disable ? "disable" : "enable"} nested git repo ${gitPath}:`, error) - } - } - } - - public dispose() { - this.disposables.forEach((d) => d.dispose()) - this.disposables = [] - } -} - -const GIT_DISABLED_SUFFIX = "_disabled" - -export default CheckpointTracker diff --git a/src/integrations/checkpoints/CheckpointUtils.ts b/src/integrations/checkpoints/CheckpointUtils.ts index d6d4cadc..36e58ea0 100644 --- a/src/integrations/checkpoints/CheckpointUtils.ts +++ b/src/integrations/checkpoints/CheckpointUtils.ts @@ -2,6 +2,7 @@ import { mkdir, access, constants } from "fs/promises" import * as path from "path" import * as vscode from "vscode" import os from "os" +import { getCwd } from "@/utils/path" /** * Gets the path to the shadow Git repository in globalStorage. @@ -45,7 +46,7 @@ export async function getShadowGitPath(globalStoragePath: string, taskId: string * @throws Error if no workspace is detected, if in a protected directory, or if no read access */ export async function getWorkingDirectory(): Promise { - const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) + const cwd = await getCwd() if (!cwd) { throw new Error("No workspace detected. Please open Cline in a workspace to use checkpoints.") } diff --git a/src/services/test/GitHelper.ts b/src/services/test/GitHelper.ts index 44705b06..06eb6331 100644 --- a/src/services/test/GitHelper.ts +++ b/src/services/test/GitHelper.ts @@ -1,33 +1,6 @@ import * as path from "path" -import * as vscode from "vscode" import { execa } from "execa" import { Logger } from "@services/logging/Logger" -import { WebviewProvider } from "@core/webview" - -/** - * Gets a valid workspace path for Git operations - * @param visibleWebview The visible webview instance - * @returns A valid workspace path - */ -export function getWorkspacePath(visibleWebview: WebviewProvider): string { - // First try to get the path from the controller's state - let workspacePath = visibleWebview.controller.context.workspaceState.get("cwd") || "" - - // If workspace path is empty, try to get it from the active workspace folder - if (!workspacePath) { - const workspaceFolders = vscode.workspace.workspaceFolders - if (workspaceFolders && workspaceFolders.length > 0) { - workspacePath = workspaceFolders[0].uri.fsPath - Logger.log(`Using workspace folder path: ${workspacePath}`) - } else { - // If no workspace folder is open, use the extension directory as a fallback - workspacePath = path.join(__dirname, "..", "..", "..") - Logger.log(`No workspace folder found, using extension directory: ${workspacePath}`) - } - } - - return workspacePath -} /** * Validates that the workspace path is valid and writable for Git operations @@ -42,7 +15,7 @@ export async function validateWorkspacePath(workspacePath: string): Promise { // Get all workspace folders - const workspaceFolders = vscode.workspace.workspaceFolders || [] + const workspaceFolders = await getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) // Check each workspace folder for an evals.env file - for (const folder of workspaceFolders) { - const evalsEnvPath = path.join(folder.uri.fsPath, "evals.env") + for (const folder of workspaceFolders.paths) { + const evalsEnvPath = path.join(folder, "evals.env") if (fs.existsSync(evalsEnvPath)) { Logger.log(`Found evals.env file at ${evalsEnvPath}, activating test mode`) return true @@ -49,14 +51,13 @@ function checkForTestMode(): boolean { /** * Initialize test mode detection and setup file watchers - * @param context VSCode extension context * @param webviewProvider The webview provider instance */ -export function initializeTestMode(context: vscode.ExtensionContext, webviewProvider?: any): vscode.Disposable[] { +export async function initializeTestMode(webviewProvider?: any): Promise { const disposables: vscode.Disposable[] = [] // Check if we're in test mode - const IS_TEST = checkForTestMode() + const IS_TEST = await checkForTestMode() // Set test mode state for other parts of the code if (IS_TEST) { diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index 54155858..65886630 100644 --- a/src/services/test/TestServer.ts +++ b/src/services/test/TestServer.ts @@ -6,13 +6,7 @@ import { Logger } from "@services/logging/Logger" import { WebviewProvider } from "@core/webview" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { TaskServiceClient } from "webview-ui/src/services/grpc-client" -import { - getWorkspacePath, - validateWorkspacePath, - initializeGitRepository, - getFileChanges, - calculateToolSuccessRate, -} from "./GitHelper" +import { validateWorkspacePath, initializeGitRepository, getFileChanges, calculateToolSuccessRate } from "./GitHelper" import { updateGlobalState, getAllExtensionState, @@ -25,6 +19,7 @@ import { ApiProvider } from "@shared/api" import { HistoryItem } from "@shared/HistoryItem" import { getSavedClineMessages, getSavedApiConversationHistory } from "@core/storage/disk" import { AskResponseRequest } from "@/shared/proto/task" +import { getCwd } from "@/utils/path" /** * Creates a tracker to monitor tool calls and failures during task execution @@ -215,7 +210,7 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server try { // Get and validate the workspace path - const workspacePath = getWorkspacePath(visibleWebview) + const workspacePath = await getCwd() Logger.log(`Using workspace path: ${workspacePath}`) // Validate workspace path before proceeding with any operations @@ -375,7 +370,7 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server let fileChanges try { // Get the workspace path using our helper function - const workspacePath = getWorkspacePath(visibleWebview) + const workspacePath = await getCwd() Logger.log(`Getting file changes from workspace path: ${workspacePath}`) // Log directory contents for debugging From c6d91be7210619d074928e7685fbe81d32076834 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 30 Jun 2025 16:07:48 -0700 Subject: [PATCH 40/60] Replace vscode workspaceFolders with getCwd which uses the host bridge. (#4593) --- src/integrations/workspace/get-python-env.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/integrations/workspace/get-python-env.ts b/src/integrations/workspace/get-python-env.ts index 92575b40..f47f0d4c 100644 --- a/src/integrations/workspace/get-python-env.ts +++ b/src/integrations/workspace/get-python-env.ts @@ -1,3 +1,4 @@ +import { getCwd } from "@/utils/path" import * as vscode from "vscode" /* @@ -28,12 +29,12 @@ export async function getPythonEnvPath(): Promise { // Access the Python extension API const pythonApi = pythonExtension.exports // Get the active environment path for the current workspace - const workspaceFolder = vscode.workspace.workspaceFolders?.[0] + const workspaceFolder = await getCwd() if (!workspaceFolder) { return undefined } // Get the active python environment path for the current workspace - const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder.uri) + const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder) if (pythonEnv && pythonEnv.path) { return pythonEnv.path } else { From 020ae3006e13c3c59757a1b9e466c699045b6d1b Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Mon, 30 Jun 2025 16:11:31 -0700 Subject: [PATCH 41/60] adding distance metric safety check to the block-apply, for eval (#4477) * diff apply add Co-authored-by: chi.cat * fname * integrate * optionally save locally * other cli * name * default * return replacements with match type * baseline -1 * baseline for evals * work * more info --------- Co-authored-by: chi.cat --- evals/cli/src/commands/runDiffEval.ts | 5 + evals/cli/src/index.ts | 1 + evals/diff-edits/ClineWrapper.ts | 15 +- evals/diff-edits/TestRunner.ts | 12 +- evals/diff-edits/diff-apply/diff-06-26-25.ts | 954 +++++++++++++++++++ evals/diff-edits/types.ts | 1 + 6 files changed, 985 insertions(+), 3 deletions(-) create mode 100644 evals/diff-edits/diff-apply/diff-06-26-25.ts diff --git a/evals/cli/src/commands/runDiffEval.ts b/evals/cli/src/commands/runDiffEval.ts index 87623a19..909ef4f2 100644 --- a/evals/cli/src/commands/runDiffEval.ts +++ b/evals/cli/src/commands/runDiffEval.ts @@ -16,6 +16,7 @@ interface RunDiffEvalOptions { replay: boolean replayRunId?: string diffApplyFile?: string + saveLocally: boolean maxCases?: number } @@ -74,6 +75,10 @@ export async function runDiffEvalHandler(options: RunDiffEvalOptions) { args.push("--max-cases", String(options.maxCases)) } + if (options.saveLocally) { + args.push("--save-locally") + } + try { console.log(chalk.gray(`Executing: npx tsx ${scriptPath} ${args.join(" ")}`)) diff --git a/evals/cli/src/index.ts b/evals/cli/src/index.ts index 92aef088..036a99c5 100644 --- a/evals/cli/src/index.ts +++ b/evals/cli/src/index.ts @@ -95,6 +95,7 @@ program .option("--replay", "Run evaluation from a pre-recorded LLM output, skipping the API call", false) .option("--replay-run-id ", "The ID of the run to replay from the database") .option("--diff-apply-file ", "The name of the diff apply file to use for the replay") + .option("--save-locally", "Save results to local JSON files in addition to database", false) .option("-v, --verbose", "Enable verbose logging", false) .action(async (options) => { try { diff --git a/evals/diff-edits/ClineWrapper.ts b/evals/diff-edits/ClineWrapper.ts index 1f32d04b..ad435ff5 100644 --- a/evals/diff-edits/ClineWrapper.ts +++ b/evals/diff-edits/ClineWrapper.ts @@ -11,9 +11,10 @@ import { import { constructNewFileContent as constructNewFileContent_06_06_25 } from "./diff-apply/diff-06-06-25" import { constructNewFileContent as constructNewFileContent_06_23_25 } from "./diff-apply/diff-06-23-25" import { constructNewFileContent as constructNewFileContent_06_25_25 } from "./diff-apply/diff-06-25-25" +import { constructNewFileContent as constructNewFileContent_06_26_25 } from "./diff-apply/diff-06-26-25" type ParseAssistantMessageFn = (message: string) => AssistantMessageContent[] -type ConstructNewFileContentFn = (diff: string, original: string, strict: boolean) => Promise +type ConstructNewFileContentFn = (diff: string, original: string, strict: boolean) => Promise const parsingFunctions: Record = { parseAssistantMessageV1: parseAssistantMessageV1, @@ -25,6 +26,7 @@ const diffEditingFunctions: Record = { "diff-06-06-25": constructNewFileContent_06_06_25, "diff-06-23-25": constructNewFileContent_06_23_25, "diff-06-25-25": constructNewFileContent_06_25_25, + "diff-06-26-25": constructNewFileContent_06_26_25, } import { TestInput, TestResult, ExtractedToolCall } from "./types" @@ -308,10 +310,18 @@ export async function runSingleEvaluation(input: TestInput): Promise // checking if the diff edit succeeds, if it failed it will throw an error let diffSuccess = true + let replacementData: any = undefined try { - await constructNewFileContent(diffToolContent, originalFile, true) + const result = await constructNewFileContent(diffToolContent, originalFile, true) + + // Check if result is an object with replacements (new format) + if (typeof result === 'object' && result !== null && 'replacements' in result) { + replacementData = result.replacements + } + // If it's just a string, diffSuccess stays true and replacementData stays undefined } catch (error: any) { diffSuccess = false + console.log("ERROR:",error) } return { @@ -320,6 +330,7 @@ export async function runSingleEvaluation(input: TestInput): Promise toolCalls: detectedToolCalls, diffEdit: diffToolContent, diffEditSuccess: diffSuccess, + replacementData: replacementData, } } catch (error: any) { return { diff --git a/evals/diff-edits/TestRunner.ts b/evals/diff-edits/TestRunner.ts index 7085cbd0..32436fec 100644 --- a/evals/diff-edits/TestRunner.ts +++ b/evals/diff-edits/TestRunner.ts @@ -3,6 +3,7 @@ import { parseAssistantMessageV2, AssistantMessageContent } from "./parsing/pars import { constructNewFileContent as constructNewFileContent_06_06_25 } from "./diff-apply/diff-06-06-25" import { constructNewFileContent as constructNewFileContent_06_23_25 } from "./diff-apply/diff-06-23-25" import { constructNewFileContent as constructNewFileContent_06_25_25 } from "./diff-apply/diff-06-25-25" +import { constructNewFileContent as constructNewFileContent_06_26_25 } from "./diff-apply/diff-06-26-25" import { constructNewFileContent as constructNewFileContentV3 } from "../../src/core/assistant-message/diff" import { basicSystemPrompt } from "./prompts/basicSystemPrompt-06-06-25" import { claude4SystemPrompt } from "./prompts/claude4SystemPrompt-06-06-25" @@ -484,6 +485,7 @@ class NodeTestRunner { "diff-06-06-25": constructNewFileContent_06_06_25, "diff-06-23-25": constructNewFileContent_06_23_25, "diff-06-25-25": constructNewFileContent_06_25_25, + "diff-06-26-25": constructNewFileContent_06_26_25, constructNewFileContentV3: constructNewFileContentV3, } const constructNewFileContent = diffEditingFunctions[diffApplyFile] @@ -927,12 +929,13 @@ async function main() { .option("-n, --valid-attempts-per-case ", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1") .option("--max-cases ", "Maximum number of test cases to run (limits total cases loaded)") .option("--parsing-function ", "The parsing function to use", "parseAssistantMessageV2") - .option("--diff-edit-function ", "The diff editing function to use", "constructNewFileContentV2") + .option("--diff-edit-function ", "The diff editing function to use", "diff-06-25-25") .option("--thinking-budget ", "Set the thinking tokens budget", "0") .option("--parallel", "Run tests in parallel", false) .option("--replay", "Run evaluation from a pre-recorded LLM output, skipping the API call", false) .option("--replay-run-id ", "The ID of the run to replay from the database") .option("--diff-apply-file ", "The name of the diff apply file to use for the replay") + .option("--save-locally", "Save results to local JSON files in addition to database", false) .option("-v, --verbose", "Enable verbose logging", false) .option("--max-concurrency ", "Maximum number of parallel requests", "80") @@ -943,6 +946,7 @@ async function main() { const isVerbose = options.verbose const testPath = options.testPath const outputPath = options.outputPath + const saveLocally = options.saveLocally const maxConcurrency = parseInt(options.maxConcurrency, 10); // Parse model IDs from comma-separated string @@ -1150,6 +1154,12 @@ async function main() { const durationSeconds = ((endTime - startTime) / 1000).toFixed(2) log(isVerbose, `\n-Total execution time: ${durationSeconds} seconds`) + // Save results locally if requested + if (saveLocally) { + runner.saveTestResults(results, outputPath); + log(isVerbose, `✓ Results also saved to JSON files in ${outputPath}`); + } + log(isVerbose, `\n✓ All results stored in database. Use the dashboard to view results.`) } catch (error) { console.error("\nError running tests:", error) diff --git a/evals/diff-edits/diff-apply/diff-06-26-25.ts b/evals/diff-edits/diff-apply/diff-06-26-25.ts new file mode 100644 index 00000000..770a781b --- /dev/null +++ b/evals/diff-edits/diff-apply/diff-06-26-25.ts @@ -0,0 +1,954 @@ +const SEARCH_BLOCK_START = "------- SEARCH" +const SEARCH_BLOCK_END = "=======" +const REPLACE_BLOCK_END = "+++++++ REPLACE" + +const SEARCH_BLOCK_CHAR = "-" +const REPLACE_BLOCK_CHAR = "+" +const LEGACY_SEARCH_BLOCK_CHAR = "<" +const LEGACY_REPLACE_BLOCK_CHAR = ">" + +// Replace the exact string constants with flexible regex patterns +const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH>?$/ +const LEGACY_SEARCH_BLOCK_START_REGEX = /^[<]{3,} SEARCH>?$/ + +const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/ + +const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE>?$/ +const LEGACY_REPLACE_BLOCK_END_REGEX = /^[>]{3,} REPLACE>?$/ + +// Similarity thresholds for block anchor fallback matching +const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.0 +const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.0 + +/** + * Levenshtein distance algorithm implementation + */ +function levenshtein(a: string, b: string): number { + // Handle empty strings + if (a === "" || b === "") { + return Math.max(a.length, b.length) + } + const matrix = Array.from({ length: a.length + 1 }, (_, i) => + Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)), + ) + + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1 + matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost) + } + } + return matrix[a.length][b.length] +} + +// Helper functions to check if a line matches the flexible patterns +function isSearchBlockStart(line: string): boolean { + return SEARCH_BLOCK_START_REGEX.test(line) || LEGACY_SEARCH_BLOCK_START_REGEX.test(line) +} + +function isSearchBlockEnd(line: string): boolean { + return SEARCH_BLOCK_END_REGEX.test(line) +} + +function isReplaceBlockEnd(line: string): boolean { + return REPLACE_BLOCK_END_REGEX.test(line) || LEGACY_REPLACE_BLOCK_END_REGEX.test(line) +} + +/** + * Attempts a line-trimmed fallback match for the given search content in the original content. + * It tries to match `searchContent` lines against a block of lines in `originalContent` starting + * from `lastProcessedIndex`. Lines are matched by trimming leading/trailing whitespace and ensuring + * they are identical afterwards. + * + * Returns [matchIndexStart, matchIndexEnd] if found, or false if not found. + */ +function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false { + // Split both contents into lines + const originalLines = originalContent.split("\n") + const searchLines = searchContent.split("\n") + + // Trim trailing empty line if exists (from the trailing \n in searchContent) + if (searchLines[searchLines.length - 1] === "") { + searchLines.pop() + } + + // Find the line number where startIndex falls + let startLineNum = 0 + let currentIndex = 0 + while (currentIndex < startIndex && startLineNum < originalLines.length) { + currentIndex += originalLines[startLineNum].length + 1 // +1 for \n + startLineNum++ + } + + // For each possible starting position in original content + for (let i = startLineNum; i <= originalLines.length - searchLines.length; i++) { + let matches = true + + // Try to match all search lines from this position + for (let j = 0; j < searchLines.length; j++) { + const originalTrimmed = originalLines[i + j].trim() + const searchTrimmed = searchLines[j].trim() + + if (originalTrimmed !== searchTrimmed) { + matches = false + break + } + } + + // If we found a match, calculate the exact character positions + if (matches) { + // Find start character index + let matchStartIndex = 0 + for (let k = 0; k < i; k++) { + matchStartIndex += originalLines[k].length + 1 // +1 for \n + } + + // Find end character index + let matchEndIndex = matchStartIndex + for (let k = 0; k < searchLines.length; k++) { + matchEndIndex += originalLines[i + k].length + 1 // +1 for \n + } + + return [matchStartIndex, matchEndIndex] + } + } + + return false +} + +/** + * Attempts to match blocks of code by using the first and last lines as anchors, + * with similarity checking to prevent false positives. + * This is a third-tier fallback strategy that helps match blocks where we can identify + * the correct location by matching the beginning and end, even if the exact content + * differs slightly. + * + * The matching strategy: + * 1. Only attempts to match blocks of 3 or more lines to avoid false positives + * 2. Extracts from the search content: + * - First line as the "start anchor" + * - Last line as the "end anchor" + * 3. Collects all candidate positions where both anchors match + * 4. Uses levenshtein distance to calculate similarity of middle lines + * 5. Returns match only if similarity meets threshold requirements + * + * This approach is particularly useful for matching blocks of code where: + * - The exact content might have minor differences + * - The beginning and end of the block are distinctive enough to serve as anchors + * - The overall structure (number of lines) remains the same + * - The middle content is reasonably similar (prevents false positives) + * + * @param originalContent - The full content of the original file + * @param searchContent - The content we're trying to find in the original file + * @param startIndex - The character index in originalContent where to start searching + * @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise + */ +function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number, number] | false { + const originalLines = originalContent.split("\n") + const searchLines = searchContent.split("\n") + + // Only use this approach for blocks of 3+ lines + if (searchLines.length < 3) { + return false + } + + // Trim trailing empty line if exists + if (searchLines[searchLines.length - 1] === "") { + searchLines.pop() + } + + const firstLineSearch = searchLines[0].trim() + const lastLineSearch = searchLines[searchLines.length - 1].trim() + const searchBlockSize = searchLines.length + + // Find the line number where startIndex falls + let startLineNum = 0 + let currentIndex = 0 + while (currentIndex < startIndex && startLineNum < originalLines.length) { + currentIndex += originalLines[startLineNum].length + 1 + startLineNum++ + } + + // Collect all candidate positions + const candidates: number[] = [] + for (let i = startLineNum; i <= originalLines.length - searchBlockSize; i++) { + if (originalLines[i].trim() === firstLineSearch && originalLines[i + searchBlockSize - 1].trim() === lastLineSearch) { + candidates.push(i) + } + } + + // Return immediately if no candidates + if (candidates.length === 0) { + return false + } + + // Handle single candidate scenario (using relaxed threshold) + if (candidates.length === 1) { + const i = candidates[0] + let similarity = 0 + let linesToCheck = searchBlockSize - 2 + + for (let j = 1; j < searchBlockSize - 1; j++) { + const originalLine = originalLines[i + j].trim() + const searchLine = searchLines[j].trim() + const maxLen = Math.max(originalLine.length, searchLine.length) + if (maxLen === 0) { + continue + } + const distance = levenshtein(originalLine, searchLine) + similarity += (1 - distance / maxLen) / linesToCheck + + // Exit early when threshold is reached + if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) { + break + } + } + + if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) { + let matchStartIndex = 0 + for (let k = 0; k < i; k++) { + matchStartIndex += originalLines[k].length + 1 + } + let matchEndIndex = matchStartIndex + for (let k = 0; k < searchBlockSize; k++) { + matchEndIndex += originalLines[i + k].length + 1 + } + return [matchStartIndex, matchEndIndex, similarity] + } + return false + } + + // Calculate similarity for multiple candidates + let bestMatchIndex = -1 + let maxSimilarity = -1 + + for (const i of candidates) { + let similarity = 0 + for (let j = 1; j < searchBlockSize - 1; j++) { + const originalLine = originalLines[i + j].trim() + const searchLine = searchLines[j].trim() + const maxLen = Math.max(originalLine.length, searchLine.length) + if (maxLen === 0) { + continue + } + const distance = levenshtein(originalLine, searchLine) + similarity += 1 - distance / maxLen + } + similarity /= searchBlockSize - 2 // Average similarity + + if (similarity > maxSimilarity) { + maxSimilarity = similarity + bestMatchIndex = i + } + } + + // Threshold judgment + if (maxSimilarity >= MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD) { + const i = bestMatchIndex + let matchStartIndex = 0 + for (let k = 0; k < i; k++) { + matchStartIndex += originalLines[k].length + 1 + } + let matchEndIndex = matchStartIndex + for (let k = 0; k < searchBlockSize; k++) { + matchEndIndex += originalLines[i + k].length + 1 + } + return [matchStartIndex, matchEndIndex, maxSimilarity] + } + + return false +} + +/** + * This function reconstructs the file content by applying a streamed diff (in a + * specialized SEARCH/REPLACE block format) to the original file content. It is designed + * to handle both incremental updates and the final resulting file after all chunks have + * been processed. + * + * The diff format is a custom structure that uses three markers to define changes: + * + * ------- SEARCH + * [Exact content to find in the original file] + * ======= + * [Content to replace with] + * +++++++ REPLACE + * + * Behavior and Assumptions: + * 1. The file is processed chunk-by-chunk. Each chunk of `diffContent` may contain + * partial or complete SEARCH/REPLACE blocks. By calling this function with each + * incremental chunk (with `isFinal` indicating the last chunk), the final reconstructed + * file content is produced. + * + * 2. Matching Strategy (in order of attempt): + * a. Exact Match: First attempts to find the exact SEARCH block text in the original file + * b. Line-Trimmed Match: Falls back to line-by-line comparison ignoring leading/trailing whitespace + * c. Block Anchor Match: For blocks of 3+ lines, tries to match using first/last lines as anchors + * If all matching strategies fail, an error is thrown. + * + * 3. Empty SEARCH Section: + * - If SEARCH is empty and the original file is empty, this indicates creating a new file + * (pure insertion). + * - If SEARCH is empty and the original file is not empty, this indicates a complete + * file replacement (the entire original content is considered matched and replaced). + * + * 4. Applying Changes: + * - Before encountering the "=======" marker, lines are accumulated as search content. + * - After "=======" and before ">>>>>>> REPLACE", lines are accumulated as replacement content. + * - Once the block is complete (">>>>>>> REPLACE"), the matched section in the original + * file is replaced with the accumulated replacement lines, and the position in the original + * file is advanced. + * + * 5. Incremental Output: + * - As soon as the match location is found and we are in the REPLACE section, each new + * replacement line is appended to the result so that partial updates can be viewed + * incrementally. + * + * 6. Partial Markers: + * - If the final line of the chunk looks like it might be part of a marker but is not one + * of the known markers, it is removed. This prevents incomplete or partial markers + * from corrupting the output. + * + * 7. Finalization: + * - Once all chunks have been processed (when `isFinal` is true), any remaining original + * content after the last replaced section is appended to the result. + * - Trailing newlines are not forcibly added. The code tries to output exactly what is specified. + * + * Errors: + * - If the search block cannot be matched using any of the available matching strategies, + * an error is thrown. + */ +export async function constructNewFileContent( + diffContent: string, + originalContent: string, + isFinal: boolean, + version: "v1" | "v2" = "v1", +): Promise { + const constructor = constructNewFileContentVersionMapping[version] + if (!constructor) { + throw new Error(`Invalid version '${version}' for file content constructor`) + } + return constructor(diffContent, originalContent, isFinal) +} + +const constructNewFileContentVersionMapping: Record< + string, + (diffContent: string, originalContent: string, isFinal: boolean) => Promise +> = { + v1: constructNewFileContentV1, + v2: constructNewFileContentV2, +} as const + +async function constructNewFileContentV1(diffContent: string, originalContent: string, isFinal: boolean): Promise<{ + content: string; + replacements: Array<{ + start: number; + end: number; + content: string; + method: string; + similarity: number; + searchContent: string; + matchedText: string; + }>; +}> { + let result = "" + let lastProcessedIndex = 0 + + let currentSearchContent = "" + let currentReplaceContent = "" + let inSearch = false + let inReplace = false + + let searchMatchIndex = -1 + let searchEndIndex = -1 + let matchMethod = "" + let similarityScore = -1.0 + + // Track all replacements to handle out-of-order edits + let replacements: Array<{ + start: number; + end: number; + content: string; + method: string; + similarity: number; + searchContent: string; + matchedText: string; + }> = [] + let pendingOutOfOrderReplacement = false + + let lines = diffContent.split("\n") + + // If the last line looks like a partial marker but isn't recognized, + // remove it because it might be incomplete. + const lastLine = lines[lines.length - 1] + if ( + lines.length > 0 && + (lastLine.startsWith(SEARCH_BLOCK_CHAR) || + lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) || + lastLine.startsWith("=") || + lastLine.startsWith(REPLACE_BLOCK_CHAR) || + lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) && + !isSearchBlockStart(lastLine) && + !isSearchBlockEnd(lastLine) && + !isReplaceBlockEnd(lastLine) + ) { + lines.pop() + } + + for (const line of lines) { + if (isSearchBlockStart(line)) { + inSearch = true + currentSearchContent = "" + currentReplaceContent = "" + continue + } + + if (isSearchBlockEnd(line)) { + inSearch = false + inReplace = true + + // Remove trailing linebreak for adding the === marker + // if (currentSearchContent.endsWith("\r\n")) { + // currentSearchContent = currentSearchContent.slice(0, -2) + // } else if (currentSearchContent.endsWith("\n")) { + // currentSearchContent = currentSearchContent.slice(0, -1) + // } + + if (!currentSearchContent) { + // Empty search block + if (originalContent.length === 0) { + // New file scenario: nothing to match, just start inserting + searchMatchIndex = 0 + searchEndIndex = 0 + matchMethod = "empty_new_file" + } else { + // ERROR: Empty search block with non-empty file indicates malformed SEARCH marker + throw new Error( + "Empty SEARCH block detected with non-empty file. This usually indicates a malformed SEARCH marker.\n" + + "Please ensure your SEARCH marker follows the correct format:\n" + + "- Use '------- SEARCH' (7+ dashes + space + SEARCH)\n", + ) + } + } else { + // Add check for inefficient full-file search + // if (currentSearchContent.trim() === originalContent.trim()) { + // throw new Error( + // "The SEARCH block contains the entire file content. Please either:\n" + + // "1. Use an empty SEARCH block to replace the entire file, or\n" + + // "2. Make focused changes to specific parts of the file that need modification.", + // ) + // } + + // Exact search match scenario + const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex) + if (exactIndex !== -1) { + searchMatchIndex = exactIndex + searchEndIndex = exactIndex + currentSearchContent.length + matchMethod = "exact_match" + } else { + // Attempt fallback line-trimmed matching + const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex) + if (lineMatch) { + ;[searchMatchIndex, searchEndIndex] = lineMatch + matchMethod = "line_trimmed_fallback" + } else { + // Try block anchor fallback for larger blocks + const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex) + if (blockMatch) { + ;[searchMatchIndex, searchEndIndex, similarityScore] = blockMatch + matchMethod = "block_anchor_fallback" + } else { + // Last resort: search the entire file from the beginning + const fullFileIndex = originalContent.indexOf(currentSearchContent, 0) + if (fullFileIndex !== -1) { + // Found in the file - could be out of order + searchMatchIndex = fullFileIndex + searchEndIndex = fullFileIndex + currentSearchContent.length + matchMethod = "full_file_search" + if (searchMatchIndex < lastProcessedIndex) { + pendingOutOfOrderReplacement = true + } + } else { + throw new Error( + `The SEARCH block:\n${currentSearchContent.trimEnd()}\n...does not match anything in the file.`, + ) + } + } + } + } + } + + // Check if this is an out-of-order replacement + if (searchMatchIndex < lastProcessedIndex) { + pendingOutOfOrderReplacement = true + } + + // For in-order replacements, output everything up to the match location + if (!pendingOutOfOrderReplacement) { + result += originalContent.slice(lastProcessedIndex, searchMatchIndex) + } + continue + } + + if (isReplaceBlockEnd(line)) { + // Finished one replace block + + // Store this replacement + replacements.push({ + start: searchMatchIndex, + end: searchEndIndex, + content: currentReplaceContent, + method: matchMethod, + similarity: similarityScore, + searchContent: currentSearchContent, + matchedText: originalContent.slice(searchMatchIndex, searchEndIndex), + }) + + // If this was an in-order replacement, advance lastProcessedIndex + if (!pendingOutOfOrderReplacement) { + lastProcessedIndex = searchEndIndex + } + + // Reset for next block + inSearch = false + inReplace = false + currentSearchContent = "" + currentReplaceContent = "" + searchMatchIndex = -1 + searchEndIndex = -1 + similarityScore = -1.0 + pendingOutOfOrderReplacement = false + continue + } + + // Accumulate content for search or replace + // (currentReplaceContent is not being used for anything right now since we directly append to result.) + // (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.) + // NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well. + if (inSearch) { + currentSearchContent += line + "\n" + } else if (inReplace) { + currentReplaceContent += line + "\n" + // Only output replacement lines immediately for in-order replacements + if (searchMatchIndex !== -1 && !pendingOutOfOrderReplacement) { + result += line + "\n" + } + } + } + + // If this is the final chunk, we need to apply all replacements and build the final result + if (isFinal) { + // Handle the case where we're still in replace mode when processing ends + // and this is the final chunk - treat it as if we encountered the REPLACE marker + if (inReplace && searchMatchIndex !== -1) { + // Store this replacement + replacements.push({ + start: searchMatchIndex, + end: searchEndIndex, + content: currentReplaceContent, + method: matchMethod, + similarity: similarityScore, + searchContent: currentSearchContent, + matchedText: originalContent.slice(searchMatchIndex, searchEndIndex), + }) + + // If this was an in-order replacement, advance lastProcessedIndex + if (!pendingOutOfOrderReplacement) { + lastProcessedIndex = searchEndIndex + } + + // Reset state + inSearch = false + inReplace = false + currentSearchContent = "" + currentReplaceContent = "" + searchMatchIndex = -1 + searchEndIndex = -1 + pendingOutOfOrderReplacement = false + } + // end of handling missing replace marker + + // Sort replacements by start position + replacements.sort((a, b) => a.start - b.start) + + // Rebuild the entire result by applying all replacements + result = "" + let currentPos = 0 + + for (const replacement of replacements) { + // Add original content up to this replacement + result += originalContent.slice(currentPos, replacement.start) + // Add the replacement content + result += replacement.content + // Move position to after the replaced section + currentPos = replacement.end + } + + // Add any remaining original content + result += originalContent.slice(currentPos) + } + + // For testing - return debug info + return { + content: result, + replacements: replacements + } +} + +enum ProcessingState { + Idle = 0, + StateSearch = 1 << 0, + StateReplace = 1 << 1, +} + +class NewFileContentConstructor { + private originalContent: string + private isFinal: boolean + private state: number + private pendingNonStandardLines: string[] + private result: string + private lastProcessedIndex: number + private currentSearchContent: string + private currentReplaceContent: string + private searchMatchIndex: number + private searchEndIndex: number + + constructor(originalContent: string, isFinal: boolean) { + this.originalContent = originalContent + this.isFinal = isFinal + this.pendingNonStandardLines = [] + this.result = "" + this.lastProcessedIndex = 0 + this.state = ProcessingState.Idle + this.currentSearchContent = "" + this.currentReplaceContent = "" + this.searchMatchIndex = -1 + this.searchEndIndex = -1 + } + + private resetForNextBlock() { + // Reset for next block + this.state = ProcessingState.Idle + this.currentSearchContent = "" + this.currentReplaceContent = "" + this.searchMatchIndex = -1 + this.searchEndIndex = -1 + } + + private findLastMatchingLineIndex(regx: RegExp, lineLimit: number) { + for (let i = lineLimit; i > 0; ) { + i-- + if (this.pendingNonStandardLines[i].match(regx)) { + return i + } + } + return -1 + } + + private updateProcessingState(newState: ProcessingState) { + const isValidTransition = + (this.state === ProcessingState.Idle && newState === ProcessingState.StateSearch) || + (this.state === ProcessingState.StateSearch && newState === ProcessingState.StateReplace) + + if (!isValidTransition) { + throw new Error( + `Invalid state transition.\n` + + "Valid transitions are:\n" + + "- Idle → StateSearch\n" + + "- StateSearch → StateReplace", + ) + } + + this.state |= newState + } + + private isStateActive(state: ProcessingState): boolean { + return (this.state & state) === state + } + + private activateReplaceState() { + this.updateProcessingState(ProcessingState.StateReplace) + } + + private activateSearchState() { + this.updateProcessingState(ProcessingState.StateSearch) + this.currentSearchContent = "" + this.currentReplaceContent = "" + } + + private isSearchingActive(): boolean { + return this.isStateActive(ProcessingState.StateSearch) + } + + private isReplacingActive(): boolean { + return this.isStateActive(ProcessingState.StateReplace) + } + + private hasPendingNonStandardLines(pendingNonStandardLineLimit: number): boolean { + return this.pendingNonStandardLines.length - pendingNonStandardLineLimit < this.pendingNonStandardLines.length + } + + public processLine(line: string) { + this.internalProcessLine(line, true, this.pendingNonStandardLines.length) + } + + public getResult() { + // If this is the final chunk, append any remaining original content + if (this.isFinal && this.lastProcessedIndex < this.originalContent.length) { + this.result += this.originalContent.slice(this.lastProcessedIndex) + } + if (this.isFinal && this.state !== ProcessingState.Idle) { + throw new Error("File processing incomplete - SEARCH/REPLACE operations still active during finalization") + } + return this.result + } + + private internalProcessLine( + line: string, + canWritependingNonStandardLines: boolean, + pendingNonStandardLineLimit: number, + ): number { + let removeLineCount = 0 + if (isSearchBlockStart(line)) { + removeLineCount = this.trimPendingNonStandardTrailingEmptyLines(pendingNonStandardLineLimit) + if (removeLineCount > 0) { + pendingNonStandardLineLimit = pendingNonStandardLineLimit - removeLineCount + } + if (this.hasPendingNonStandardLines(pendingNonStandardLineLimit)) { + this.tryFixSearchReplaceBlock(pendingNonStandardLineLimit) + canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0) + } + this.activateSearchState() + } else if (isSearchBlockEnd(line)) { + // 校验非标内容 + if (!this.isSearchingActive()) { + this.tryFixSearchBlock(pendingNonStandardLineLimit) + canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0) + } + this.activateReplaceState() + this.beforeReplace() + } else if (isReplaceBlockEnd(line)) { + if (!this.isReplacingActive()) { + this.tryFixReplaceBlock(pendingNonStandardLineLimit) + canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0) + } + this.lastProcessedIndex = this.searchEndIndex + this.resetForNextBlock() + } else { + // Accumulate content for search or replace + // (currentReplaceContent is not being used for anything right now since we directly append to result.) + // (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.) + // NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well. + if (this.isReplacingActive()) { + this.currentReplaceContent += line + "\n" + // Output replacement lines immediately if we know the insertion point + if (this.searchMatchIndex !== -1) { + this.result += line + "\n" + } + } else if (this.isSearchingActive()) { + this.currentSearchContent += line + "\n" + } else { + let appendToPendingNonStandardLines = canWritependingNonStandardLines + if (appendToPendingNonStandardLines) { + // 处理非标内容 + this.pendingNonStandardLines.push(line) + } + } + } + return removeLineCount + } + + private beforeReplace() { + // Remove trailing linebreak for adding the === marker + // if (currentSearchContent.endsWith("\r\n")) { + // currentSearchContent = currentSearchContent.slice(0, -2) + // } else if (currentSearchContent.endsWith("\n")) { + // currentSearchContent = currentSearchContent.slice(0, -1) + // } + + if (!this.currentSearchContent) { + // Empty search block + if (this.originalContent.length === 0) { + // New file scenario: nothing to match, just start inserting + this.searchMatchIndex = 0 + this.searchEndIndex = 0 + } else { + // Complete file replacement scenario: treat the entire file as matched + this.searchMatchIndex = 0 + this.searchEndIndex = this.originalContent.length + } + } else { + // Add check for inefficient full-file search + // if (currentSearchContent.trim() === originalContent.trim()) { + // throw new Error( + // "The SEARCH block contains the entire file content. Please either:\n" + + // "1. Use an empty SEARCH block to replace the entire file, or\n" + + // "2. Make focused changes to specific parts of the file that need modification.", + // ) + // } + // Exact search match scenario + const exactIndex = this.originalContent.indexOf(this.currentSearchContent, this.lastProcessedIndex) + if (exactIndex !== -1) { + this.searchMatchIndex = exactIndex + this.searchEndIndex = exactIndex + this.currentSearchContent.length + } else { + // Attempt fallback line-trimmed matching + const lineMatch = lineTrimmedFallbackMatch( + this.originalContent, + this.currentSearchContent, + this.lastProcessedIndex, + ) + if (lineMatch) { + ;[this.searchMatchIndex, this.searchEndIndex] = lineMatch + } else { + // Try block anchor fallback for larger blocks + const blockMatch = blockAnchorFallbackMatch( + this.originalContent, + this.currentSearchContent, + this.lastProcessedIndex, + ) + if (blockMatch) { + ;[this.searchMatchIndex, this.searchEndIndex, /* ignore similarity */] = blockMatch + } else { + throw new Error( + `The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...does not match anything in the file.`, + ) + } + } + } + } + if (this.searchMatchIndex < this.lastProcessedIndex) { + throw new Error( + `The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...matched an incorrect content in the file.`, + ) + } + // Output everything up to the match location + this.result += this.originalContent.slice(this.lastProcessedIndex, this.searchMatchIndex) + } + + private tryFixSearchBlock(lineLimit: number): number { + let removeLineCount = 0 + if (lineLimit < 0) { + lineLimit = this.pendingNonStandardLines.length + } + if (!lineLimit) { + throw new Error("Invalid SEARCH/REPLACE block structure - no lines available to process") + } + let searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/ + const searchTagIndex = this.findLastMatchingLineIndex(searchTagRegexp, lineLimit) + if (searchTagIndex !== -1) { + let fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit) + fixLines[0] = SEARCH_BLOCK_START + for (const line of fixLines) { + removeLineCount += this.internalProcessLine(line, false, searchTagIndex) + } + } else { + throw new Error( + `Invalid REPLACE marker detected - could not find matching SEARCH block starting from line ${searchTagIndex + 1}`, + ) + } + return removeLineCount + } + + private tryFixReplaceBlock(lineLimit: number): number { + let removeLineCount = 0 + if (lineLimit < 0) { + lineLimit = this.pendingNonStandardLines.length + } + if (!lineLimit) { + throw new Error() + } + let replaceBeginTagRegexp = /^[=]{3,}$/ + const replaceBeginTagIndex = this.findLastMatchingLineIndex(replaceBeginTagRegexp, lineLimit) + if (replaceBeginTagIndex !== -1) { + // // 校验非标内容 + // if (!this.isSearchingActive()) { + // removeLineCount += this.tryFixSearchBlock(replaceBeginTagIndex) + // } + let fixLines = this.pendingNonStandardLines.slice(replaceBeginTagIndex - removeLineCount, lineLimit - removeLineCount) + fixLines[0] = SEARCH_BLOCK_END + for (const line of fixLines) { + removeLineCount += this.internalProcessLine(line, false, replaceBeginTagIndex - removeLineCount) + } + } else { + throw new Error(`Malformed REPLACE block - missing valid separator after line ${replaceBeginTagIndex + 1}`) + } + return removeLineCount + } + + private tryFixSearchReplaceBlock(lineLimit: number): number { + let removeLineCount = 0 + if (lineLimit < 0) { + lineLimit = this.pendingNonStandardLines.length + } + if (!lineLimit) { + throw new Error() + } + + let replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/ + const replaceEndTagIndex = this.findLastMatchingLineIndex(replaceEndTagRegexp, lineLimit) + const likeReplaceEndTag = replaceEndTagIndex === lineLimit - 1 + if (likeReplaceEndTag) { + // // 校验非标内容 + // if (!this.isReplacingActive()) { + // removeLineCount += this.tryFixReplaceBlock(replaceEndTagIndex) + // } + let fixLines = this.pendingNonStandardLines.slice(replaceEndTagIndex - removeLineCount, lineLimit - removeLineCount) + fixLines[fixLines.length - 1] = REPLACE_BLOCK_END + for (const line of fixLines) { + removeLineCount += this.internalProcessLine(line, false, replaceEndTagIndex - removeLineCount) + } + } else { + throw new Error("Malformed SEARCH/REPLACE block structure: Missing valid closing REPLACE marker") + } + return removeLineCount + } + + /** + * Removes trailing empty lines from the pendingNonStandardLines array + * @param lineLimit - The index to start checking from (exclusive). + * Removes empty lines from lineLimit-1 backwards. + * @returns The number of empty lines removed + */ + private trimPendingNonStandardTrailingEmptyLines(lineLimit: number): number { + let removedCount = 0 + let i = Math.min(lineLimit, this.pendingNonStandardLines.length) - 1 + + while (i >= 0 && this.pendingNonStandardLines[i].trim() === "") { + this.pendingNonStandardLines.pop() + removedCount++ + i-- + } + + return removedCount + } +} + +export async function constructNewFileContentV2(diffContent: string, originalContent: string, isFinal: boolean): Promise { + let newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal) + + let lines = diffContent.split("\n") + + // If the last line looks like a partial marker but isn't recognized, + // remove it because it might be incomplete. + const lastLine = lines[lines.length - 1] + if ( + lines.length > 0 && + (lastLine.startsWith(SEARCH_BLOCK_CHAR) || + lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) || + lastLine.startsWith("=") || + lastLine.startsWith(REPLACE_BLOCK_CHAR) || + lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) && + lastLine !== SEARCH_BLOCK_START && + lastLine !== SEARCH_BLOCK_END && + lastLine !== REPLACE_BLOCK_END + ) { + lines.pop() + } + + for (const line of lines) { + newFileContentConstructor.processLine(line) + } + + let result = newFileContentConstructor.getResult() + return result +} diff --git a/evals/diff-edits/types.ts b/evals/diff-edits/types.ts index 1ff10c6a..a8005b40 100644 --- a/evals/diff-edits/types.ts +++ b/evals/diff-edits/types.ts @@ -81,6 +81,7 @@ export interface TestResult { diffEdit?: string toolCalls?: ExtractedToolCall[] diffEditSuccess?: boolean + replacementData?: any error?: string errorString?: string } From 307b92862b61924e285baed398be0506930e2e52 Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Mon, 30 Jun 2025 17:06:58 -0700 Subject: [PATCH 42/60] deprecating latex support (#4595) Co-authored-by: Cline Evaluation --- .vscodeignore | 4 - .../model_prompts/claude4-experimental.ts | 1 - src/core/prompts/model_prompts/claude4.ts | 1 - src/core/prompts/system.ts | 1 - src/core/webview/index.ts | 9 +- src/integrations/notifications/index.ts | 2 +- webview-ui/package-lock.json | 505 +----------------- webview-ui/package.json | 4 - .../src/components/common/MarkdownBlock.tsx | 32 -- webview-ui/src/index.css | 1 - webview-ui/vite.config.ts | 10 +- 11 files changed, 10 insertions(+), 560 deletions(-) diff --git a/.vscodeignore b/.vscodeignore index bce1642a..f6d27022 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -37,10 +37,6 @@ docs/** !node_modules/@vscode/codicons/dist/codicon.css !node_modules/@vscode/codicons/dist/codicon.ttf -# Include KaTeX CSS and fonts for LaTeX rendering -!webview-ui/node_modules/katex/dist/katex.min.css -!webview-ui/node_modules/katex/dist/fonts/** - # Include default themes JSON files used in getTheme !src/integrations/theme/default-themes/** diff --git a/src/core/prompts/model_prompts/claude4-experimental.ts b/src/core/prompts/model_prompts/claude4-experimental.ts index d18a5f01..f92bc4a3 100644 --- a/src/core/prompts/model_prompts/claude4-experimental.ts +++ b/src/core/prompts/model_prompts/claude4-experimental.ts @@ -257,7 +257,6 @@ CAPABILITIES : "" } - You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively. -- You can use LaTeX syntax in your responses to render mathematical expressions ==== diff --git a/src/core/prompts/model_prompts/claude4.ts b/src/core/prompts/model_prompts/claude4.ts index bf9cde1a..bfa461da 100644 --- a/src/core/prompts/model_prompts/claude4.ts +++ b/src/core/prompts/model_prompts/claude4.ts @@ -597,7 +597,6 @@ CAPABILITIES : "" } - You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively. -- You can use LaTeX syntax in your responses to render mathematical expressions ==== diff --git a/src/core/prompts/system.ts b/src/core/prompts/system.ts index cd63d340..57a303d8 100644 --- a/src/core/prompts/system.ts +++ b/src/core/prompts/system.ts @@ -591,7 +591,6 @@ CAPABILITIES : "" } - You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively. -- You can use LaTeX syntax in your responses to render mathematical expressions ==== diff --git a/src/core/webview/index.ts b/src/core/webview/index.ts index 929de217..ae9a2ed2 100644 --- a/src/core/webview/index.ts +++ b/src/core/webview/index.ts @@ -165,8 +165,6 @@ export abstract class WebviewProvider { // don't forget to add font-src ${webview.cspSource}; const codiconsUri = this.getExtensionUri("node_modules", "@vscode", "codicons", "dist", "codicon.css") - const katexCssUri = this.getExtensionUri("webview-ui", "node_modules", "katex", "dist", "katex.min.css") - // const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "main.js")) // const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "assets", "reset.css")) @@ -198,7 +196,6 @@ export abstract class WebviewProvider { - - Cline diff --git a/src/integrations/notifications/index.ts b/src/integrations/notifications/index.ts index e1f9f919..722df87e 100644 --- a/src/integrations/notifications/index.ts +++ b/src/integrations/notifications/index.ts @@ -74,7 +74,7 @@ export async function showSystemNotification(options: NotificationOptions): Prom const escapedOptions = { ...options, title: title.replace(/"/g, '\\"'), - message: message.replace(/\\/g, "\\\\").replace(/"/g, '\\"'), + message: message.replace(/"/g, '\\"'), subtitle: options.subtitle?.replace(/"/g, '\\"') || "", } diff --git a/webview-ui/package-lock.json b/webview-ui/package-lock.json index 9cd8bf8f..5a10e158 100644 --- a/webview-ui/package-lock.json +++ b/webview-ui/package-lock.json @@ -18,7 +18,6 @@ "framer-motion": "^12.7.4", "fuse.js": "^7.0.0", "fzf": "^0.5.2", - "katex": "^0.16.22", "lucide-react": "^0.511.0", "mermaid": "^11.4.1", "posthog-js": "^1.224.0", @@ -31,10 +30,8 @@ "react-use": "^17.6.0", "react-virtuoso": "^4.12.3", "rehype-highlight": "^7.0.1", - "rehype-katex": "^7.0.1", "rehype-parse": "^9.0.1", "rehype-remark": "^10.0.1", - "remark-math": "^6.0.0", "remark-stringify": "^11.0.0", "styled-components": "^6.1.15", "unified": "^11.0.5", @@ -48,7 +45,6 @@ "@testing-library/user-event": "^14.6.1", "@types/dompurify": "^3.0.5", "@types/jest": "^29.5.14", - "@types/katex": "^0.16.7", "@types/node": "^22.13.4", "@types/react": "^18.3.18", "@types/react-dom": "^18.3.5", @@ -6753,7 +6749,10 @@ "version": "4.1.12", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", + "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@types/ms": "*" } @@ -6882,12 +6881,6 @@ "integrity": "sha512-aLkWa0C0vO5b4Sr798E26QgOkss68Un0bLjs7u9qxzPT5CG+8DuNTffWES58YzJs3hrVAOs1wonycqEBqNJubA==", "license": "MIT" }, - "node_modules/@types/katex": { - "version": "0.16.7", - "resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.7.tgz", - "integrity": "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==", - "license": "MIT" - }, "node_modules/@types/keyv": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", @@ -6932,7 +6925,10 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", - "license": "MIT" + "dev": true, + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/@types/node": { "version": "22.13.8", @@ -10352,31 +10348,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/hast-util-from-dom": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz", - "integrity": "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==", - "license": "ISC", - "dependencies": { - "@types/hast": "^3.0.0", - "hastscript": "^9.0.0", - "web-namespaces": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-from-dom/node_modules/web-namespaces": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz", - "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/hast-util-from-html": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/hast-util-from-html/-/hast-util-from-html-2.0.3.tgz", @@ -10395,22 +10366,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/hast-util-from-html-isomorphic": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hast-util-from-html-isomorphic/-/hast-util-from-html-isomorphic-2.0.0.tgz", - "integrity": "sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "hast-util-from-dom": "^5.0.0", - "hast-util-from-html": "^2.0.0", - "unist-util-remove-position": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/hast-util-from-parse5": { "version": "8.0.3", "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz", @@ -12569,119 +12524,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/mdast-util-math": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-math/-/mdast-util-math-3.0.0.tgz", - "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "devlop": "^1.0.0", - "longest-streak": "^3.0.0", - "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.1.0", - "unist-util-remove-position": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-math/node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/mdast-util-math/node_modules/mdast-util-from-markdown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz", - "integrity": "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "@types/unist": "^3.0.0", - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "mdast-util-to-string": "^4.0.0", - "micromark": "^4.0.0", - "micromark-util-decode-numeric-character-reference": "^2.0.0", - "micromark-util-decode-string": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-math/node_modules/mdast-util-to-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", - "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdast-util-math/node_modules/micromark": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", - "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "@types/debug": "^4.0.0", - "debug": "^4.0.0", - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "micromark-core-commonmark": "^2.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-combine-extensions": "^2.0.0", - "micromark-util-decode-numeric-character-reference": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-resolve-all": "^2.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "micromark-util-subtokenize": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/mdast-util-math/node_modules/unist-util-stringify-position": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", - "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/mdast-util-phrasing": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", @@ -12902,166 +12744,6 @@ "parse-entities": "^2.0.0" } }, - "node_modules/micromark-core-commonmark": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", - "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "decode-named-character-reference": "^1.0.0", - "devlop": "^1.0.0", - "micromark-factory-destination": "^2.0.0", - "micromark-factory-label": "^2.0.0", - "micromark-factory-space": "^2.0.0", - "micromark-factory-title": "^2.0.0", - "micromark-factory-whitespace": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-classify-character": "^2.0.0", - "micromark-util-html-tag-name": "^2.0.0", - "micromark-util-normalize-identifier": "^2.0.0", - "micromark-util-resolve-all": "^2.0.0", - "micromark-util-subtokenize": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-extension-math": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz", - "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==", - "license": "MIT", - "dependencies": { - "@types/katex": "^0.16.0", - "devlop": "^1.0.0", - "katex": "^0.16.0", - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/micromark-factory-destination": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", - "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-label": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", - "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-space": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", - "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-title": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", - "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-factory-whitespace": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", - "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-factory-space": "^2.0.0", - "micromark-util-character": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, "node_modules/micromark-util-character": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", @@ -13082,25 +12764,6 @@ "micromark-util-types": "^2.0.0" } }, - "node_modules/micromark-util-chunked": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", - "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0" - } - }, "node_modules/micromark-util-classify-character": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", @@ -13122,26 +12785,6 @@ "micromark-util-types": "^2.0.0" } }, - "node_modules/micromark-util-combine-extensions": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", - "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-chunked": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, "node_modules/micromark-util-decode-numeric-character-reference": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", @@ -13199,60 +12842,6 @@ ], "license": "MIT" }, - "node_modules/micromark-util-html-tag-name": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", - "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-normalize-identifier": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", - "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-resolve-all": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", - "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-types": "^2.0.0" - } - }, "node_modules/micromark-util-sanitize-uri": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", @@ -13274,28 +12863,6 @@ "micromark-util-symbol": "^2.0.0" } }, - "node_modules/micromark-util-subtokenize": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", - "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "devlop": "^1.0.0", - "micromark-util-chunked": "^2.0.0", - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, "node_modules/micromark-util-symbol": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", @@ -14518,25 +14085,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/rehype-katex": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/rehype-katex/-/rehype-katex-7.0.1.tgz", - "integrity": "sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==", - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/katex": "^0.16.0", - "hast-util-from-html-isomorphic": "^2.0.0", - "hast-util-to-text": "^4.0.0", - "katex": "^0.16.0", - "unist-util-visit-parents": "^6.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/rehype-minify-whitespace": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/rehype-minify-whitespace/-/rehype-minify-whitespace-6.0.2.tgz", @@ -14606,31 +14154,6 @@ "@types/unist": "*" } }, - "node_modules/remark-math": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz", - "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==", - "license": "MIT", - "dependencies": { - "@types/mdast": "^4.0.0", - "mdast-util-math": "^3.0.0", - "micromark-extension-math": "^3.0.0", - "unified": "^11.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/remark-math/node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, "node_modules/remark-parse": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-9.0.0.tgz", @@ -16198,20 +15721,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/unist-util-remove-position": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz", - "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-visit": "^5.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/unist-util-stringify-position": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-2.0.3.tgz", diff --git a/webview-ui/package.json b/webview-ui/package.json index 58d07731..a747f072 100644 --- a/webview-ui/package.json +++ b/webview-ui/package.json @@ -25,7 +25,6 @@ "framer-motion": "^12.7.4", "fuse.js": "^7.0.0", "fzf": "^0.5.2", - "katex": "^0.16.22", "lucide-react": "^0.511.0", "mermaid": "^11.4.1", "posthog-js": "^1.224.0", @@ -38,10 +37,8 @@ "react-use": "^17.6.0", "react-virtuoso": "^4.12.3", "rehype-highlight": "^7.0.1", - "rehype-katex": "^7.0.1", "rehype-parse": "^9.0.1", "rehype-remark": "^10.0.1", - "remark-math": "^6.0.0", "remark-stringify": "^11.0.0", "styled-components": "^6.1.15", "unified": "^11.0.5", @@ -55,7 +52,6 @@ "@testing-library/user-event": "^14.6.1", "@types/dompurify": "^3.0.5", "@types/jest": "^29.5.14", - "@types/katex": "^0.16.7", "@types/node": "^22.13.4", "@types/react": "^18.3.18", "@types/react-dom": "^18.3.5", diff --git a/webview-ui/src/components/common/MarkdownBlock.tsx b/webview-ui/src/components/common/MarkdownBlock.tsx index 26d66b3b..4b794b3d 100644 --- a/webview-ui/src/components/common/MarkdownBlock.tsx +++ b/webview-ui/src/components/common/MarkdownBlock.tsx @@ -2,8 +2,6 @@ import React, { memo, useEffect, useRef, useState } from "react" import type { ComponentProps } from "react" import { useRemark } from "react-remark" import rehypeHighlight, { Options } from "rehype-highlight" -import rehypeKatex from "rehype-katex" -import remarkMath from "remark-math" import styled from "styled-components" import { visit } from "unist-util-visit" import type { Node } from "unist" @@ -238,34 +236,6 @@ const StyledMarkdown = styled.div` overflow-wrap: anywhere; } - /* KaTeX styling */ - .katex { - font-size: 1.1em; - color: var(--vscode-editor-foreground); - font-family: KaTeX_Main, "Times New Roman", serif; - line-height: 1.2; - white-space: normal; - text-indent: 0; - } - - .katex-display { - display: block; - margin: 1em 0; - text-align: center; - padding: 0.5em; - overflow-x: auto; - overflow-y: hidden; - background-color: var(--vscode-textCodeBlock-background); - border-radius: 3px; - } - - .katex-error { - color: var(--vscode-errorForeground); - border: 1px solid var(--vscode-inputValidation-errorBorder); - padding: 8px; - border-radius: 3px; - } - font-family: var(--vscode-font-family), system-ui, @@ -362,7 +332,6 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { remarkPreventBoldFilenames, remarkUrlToLink, remarkHighlightActMode, - remarkMath, () => { return (tree) => { visit(tree, "code", (node: any) => { @@ -380,7 +349,6 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { { // languages: {}, } as Options, - rehypeKatex, ], rehypeReactOptions: { components: { diff --git a/webview-ui/src/index.css b/webview-ui/src/index.css index 5694a02b..24ccb1c5 100644 --- a/webview-ui/src/index.css +++ b/webview-ui/src/index.css @@ -3,7 +3,6 @@ /* Disable Tailwind's CSS reset to preserve existing styles */ /* @import "tailwindcss/preflight.css" layer(base); */ @import "tailwindcss/utilities.css" layer(utilities); -@import "katex/dist/katex.min.css"; @config "../tailwind.config.js"; diff --git a/webview-ui/vite.config.ts b/webview-ui/vite.config.ts index 7189df38..af9d91fc 100644 --- a/webview-ui/vite.config.ts +++ b/webview-ui/vite.config.ts @@ -45,15 +45,7 @@ export default defineConfig({ inlineDynamicImports: true, entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, - assetFileNames: (assetInfo) => { - if ( - assetInfo.name && - (assetInfo.name.endsWith(".woff2") || assetInfo.name.endsWith(".woff") || assetInfo.name.endsWith(".ttf")) - ) { - return "assets/fonts/[name][extname]" - } - return "assets/[name][extname]" - }, + assetFileNames: `assets/[name].[ext]`, }, }, chunkSizeWarningLimit: 100000, From add572cc123ba9e3a334fc2b15f732c130dad99b Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Mon, 30 Jun 2025 17:37:28 -0700 Subject: [PATCH 43/60] fixing closing telemetry banner (#4597) Co-authored-by: Cline Evaluation --- src/core/controller/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index c4c78126..825e915a 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -235,6 +235,7 @@ export class Controller { await updateGlobalState(this.context, "telemetrySetting", telemetrySetting) const isOptedIn = telemetrySetting !== "disabled" telemetryService.updateTelemetryState(isOptedIn) + await this.postStateToWebview() } async togglePlanActModeWithChatSettings(chatSettings: ChatSettings, chatContent?: ChatContent): Promise { From 9ab0cc76482a7c59942c1789f49ff2c7151af010 Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Mon, 30 Jun 2025 17:52:25 -0700 Subject: [PATCH 44/60] deleting mermaid prompts (#4596) Co-authored-by: Cline Evaluation --- src/core/prompts/model_prompts/claude4-experimental.ts | 5 ++--- src/core/prompts/model_prompts/claude4.ts | 5 ++--- src/core/prompts/system.ts | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/core/prompts/model_prompts/claude4-experimental.ts b/src/core/prompts/model_prompts/claude4-experimental.ts index f92bc4a3..84599243 100644 --- a/src/core/prompts/model_prompts/claude4-experimental.ts +++ b/src/core/prompts/model_prompts/claude4-experimental.ts @@ -234,10 +234,9 @@ In each user message, the environment_details will specify the current mode. The ## What is PLAN MODE? - While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task. -- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using ${readTool.name} or ${grepToolDefinition.name} to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding. -- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well. +- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using ${readTool.name} or ${grepToolDefinition.name} to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. +- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. - Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it. -- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.) - Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution. ==== diff --git a/src/core/prompts/model_prompts/claude4.ts b/src/core/prompts/model_prompts/claude4.ts index bfa461da..cd6fc32b 100644 --- a/src/core/prompts/model_prompts/claude4.ts +++ b/src/core/prompts/model_prompts/claude4.ts @@ -574,10 +574,9 @@ In each user message, the environment_details will specify the current mode. The ## What is PLAN MODE? - While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task. -- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding. -- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well. Present the plan to the user using the plan_mode_respond tool. +- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task. +- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool. - Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it. -- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.) - Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution. ==== diff --git a/src/core/prompts/system.ts b/src/core/prompts/system.ts index 57a303d8..968cfe5a 100644 --- a/src/core/prompts/system.ts +++ b/src/core/prompts/system.ts @@ -568,10 +568,9 @@ In each user message, the environment_details will specify the current mode. The ## What is PLAN MODE? - While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task. -- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding. -- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well. +- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. +- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. - Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it. -- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.) - Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution. ==== From dcf91b081e3b5c66da5891bf738f15c59d8a1acb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Garc=C3=ADa=20Rey?= Date: Tue, 1 Jul 2025 02:55:22 +0200 Subject: [PATCH 45/60] [LiteLLM] Group multiple requests into a single session using `litellm_session_id` parameter (#4457) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add litellm_session_id as part of chat completion request Signed-off-by: Jorge García Rey * chore: add changeset Signed-off-by: Jorge García Rey --------- Signed-off-by: Jorge García Rey --- .changeset/khaki-fishes-unite.md | 5 +++++ src/api/providers/litellm.ts | 12 +++--------- 2 files changed, 8 insertions(+), 9 deletions(-) create mode 100644 .changeset/khaki-fishes-unite.md diff --git a/.changeset/khaki-fishes-unite.md b/.changeset/khaki-fishes-unite.md new file mode 100644 index 00000000..b3bf964b --- /dev/null +++ b/.changeset/khaki-fishes-unite.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Include litellm_session_id as part of chat completion requests diff --git a/src/api/providers/litellm.ts b/src/api/providers/litellm.ts index 465d6496..3e6eda39 100644 --- a/src/api/providers/litellm.ts +++ b/src/api/providers/litellm.ts @@ -101,21 +101,15 @@ export class LiteLlmHandler implements ApiHandler { return message }) - const requestPayload: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & { - metadata?: { cline_task_id: string } - } = { + const stream = await this.client.chat.completions.create({ model: this.options.liteLlmModelId || liteLlmDefaultModelId, messages: [enhancedSystemMessage, ...enhancedMessages], temperature, stream: true, stream_options: { include_usage: true }, ...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable - ...(this.options.taskId && { - metadata: { cline_task_id: this.options.taskId }, - }), - } - - const stream = await this.client.chat.completions.create(requestPayload) + ...(this.options.taskId && { litellm_session_id: `cline-${this.options.taskId}` }), // Add session ID for LiteLLM tracking + }) const inputCost = (await this.calculateCost(1e6, 0)) || 0 const outputCost = (await this.calculateCost(0, 1e6)) || 0 From c013b4f3298bfec99456d1af281ea9ab485d4055 Mon Sep 17 00:00:00 2001 From: Andrei Eternal Date: Mon, 30 Jun 2025 15:39:09 -1000 Subject: [PATCH 46/60] [PROTOBUS] showTextDocument host bridge (#4586) * showTextDocument host bridge * format fix * sjf review cleanups * prefer paths over URI based on chats with sjf * also document_uri -> document_path * remove unused metadata import --------- Co-authored-by: Andrei Edell --- .gitignore | 3 +- proto/build-proto-config.js | 1 + proto/host/window.proto | 32 ++++++++++++++ src/core/controller/file/getRelativePaths.ts | 3 +- src/hosts/host-provider-types.ts | 2 + src/hosts/vscode/client/host-grpc-client.ts | 1 + src/hosts/vscode/window/showTextDocument.ts | 26 +++++++++++ src/integrations/editor/DiffViewProvider.ts | 44 ++++++++++++++----- .../git/commit-message-generator.ts | 8 +++- src/integrations/misc/export-markdown.ts | 9 +++- src/integrations/misc/open-file.ts | 9 +++- src/services/mcp/McpHub.ts | 1 - src/standalone/host-bridge-client-manager.ts | 4 ++ 13 files changed, 125 insertions(+), 18 deletions(-) create mode 100644 proto/host/window.proto create mode 100644 src/hosts/vscode/window/showTextDocument.ts diff --git a/.gitignore b/.gitignore index 4dfad92c..5915653b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ tmp *.vsix .DS_Store +.idea pnpm-lock.yaml @@ -37,4 +38,4 @@ src/hosts/vscode/*/methods.ts src/hosts/vscode/*/index.ts src/hosts/vscode/client/host-grpc-client.ts src/hosts/vscode/host-grpc-service-config.ts -src/standalone/server-setup.ts \ No newline at end of file +src/standalone/server-setup.ts diff --git a/proto/build-proto-config.js b/proto/build-proto-config.js index 0fee8494..cd8b4b7c 100644 --- a/proto/build-proto-config.js +++ b/proto/build-proto-config.js @@ -26,5 +26,6 @@ export const hostServiceNameMap = { watch: "host.WatchService", workspace: "host.WorkspaceService", env: "host.EnvService", + window: "host.WindowService", // Add new host services here } diff --git a/proto/host/window.proto b/proto/host/window.proto new file mode 100644 index 00000000..820a78c5 --- /dev/null +++ b/proto/host/window.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package host; +option java_package = "bot.cline.host.proto"; +option java_multiple_files = true; + +import "common.proto"; + +// Provides methods for working with IDE windows and editors. +service WindowService { + // Opens a text document in the editor and returns editor information. + rpc showTextDocument(ShowTextDocumentRequest) returns (TextEditorInfo); +} + +message ShowTextDocumentRequest { + cline.Metadata metadata = 1; + string path = 2; + optional ShowTextDocumentOptions options = 3; +} + +// See https://code.visualstudio.com/api/references/vscode-api#TextDocumentShowOptions +message ShowTextDocumentOptions { + optional bool preview = 1; + optional bool preserve_focus = 2; + optional int32 view_column = 3; +} + +message TextEditorInfo { + string document_path = 1; + optional int32 view_column = 2; + bool is_active = 3; +} diff --git a/src/core/controller/file/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index 684bbce3..bda41ca2 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -3,7 +3,7 @@ import { RelativePathsRequest, RelativePaths } from "@shared/proto/file" import { FileMethodHandler } from "./index" import * as vscode from "vscode" import * as path from "path" -import { Metadata, StringRequest } from "@shared/proto/common" +import { StringRequest } from "@shared/proto/common" import { getHostBridgeProvider } from "@hosts/host-providers" /** @@ -22,7 +22,6 @@ export const getRelativePaths: FileMethodHandler = async ( // Use the host URI service client instead of directly using vscode.Uri.parse const parseResponse = await getHostBridgeProvider().uriServiceClient.parse( StringRequest.create({ - metadata: Metadata.create({}), value: uriString, }), ) diff --git a/src/hosts/host-provider-types.ts b/src/hosts/host-provider-types.ts index 43b5ec44..8290518f 100644 --- a/src/hosts/host-provider-types.ts +++ b/src/hosts/host-provider-types.ts @@ -3,6 +3,7 @@ import { WatchServiceClientInterface, WorkspaceServiceClientInterface, EnvServiceClientInterface, + WindowServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" /** @@ -13,6 +14,7 @@ export interface HostBridgeClientProvider { watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface envClient: EnvServiceClientInterface + windowClient: WindowServiceClientInterface } /** diff --git a/src/hosts/vscode/client/host-grpc-client.ts b/src/hosts/vscode/client/host-grpc-client.ts index 04b06a54..033e38b7 100644 --- a/src/hosts/vscode/client/host-grpc-client.ts +++ b/src/hosts/vscode/client/host-grpc-client.ts @@ -7,4 +7,5 @@ export const vscodeHostBridgeClient: HostBridgeClientProvider = { watchServiceClient: createGrpcClient(host.WatchServiceDefinition), workspaceClient: createGrpcClient(host.WorkspaceServiceDefinition), envClient: createGrpcClient(host.EnvServiceDefinition), + windowClient: createGrpcClient(host.WindowServiceDefinition), } diff --git a/src/hosts/vscode/window/showTextDocument.ts b/src/hosts/vscode/window/showTextDocument.ts new file mode 100644 index 00000000..9bdbf320 --- /dev/null +++ b/src/hosts/vscode/window/showTextDocument.ts @@ -0,0 +1,26 @@ +import * as vscode from "vscode" +import { ShowTextDocumentRequest, TextEditorInfo } from "@/shared/proto/host/window" + +export async function showTextDocument(request: ShowTextDocumentRequest): Promise { + // Convert file path to URI + const uri = vscode.Uri.file(request.path) + const options: vscode.TextDocumentShowOptions = {} + + if (request.options?.preview !== undefined) { + options.preview = request.options.preview + } + if (request.options?.preserveFocus !== undefined) { + options.preserveFocus = request.options.preserveFocus + } + if (request.options?.viewColumn !== undefined) { + options.viewColumn = request.options.viewColumn + } + + const editor = await vscode.window.showTextDocument(uri, options) + + return TextEditorInfo.create({ + documentPath: editor.document.uri.fsPath, + viewColumn: editor.viewColumn, + isActive: vscode.window.activeTextEditor === editor, + }) +} diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index c7dc331d..b801ce49 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -9,6 +9,8 @@ import * as diff from "diff" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { detectEncoding } from "../misc/extract-text" import * as iconv from "iconv-lite" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowTextDocumentRequest, ShowTextDocumentOptions, TextEditorInfo } from "@/shared/proto/host/window" export const DIFF_VIEW_URI_SCHEME = "cline-diff" @@ -236,10 +238,15 @@ export class DiffViewProvider { // get text after save in case there is any auto-formatting done by the editor const postSaveContent = updatedDocument.getText() - await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { - preview: false, - preserveFocus: true, - }) + await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: absolutePath, + options: ShowTextDocumentOptions.create({ + preview: false, + preserveFocus: true, + }), + }), + ) await this.closeAllDiffViews() /* @@ -337,10 +344,15 @@ export class DiffViewProvider { await updatedDocument.save() console.log(`File ${absolutePath} has been reverted to its original content.`) if (this.documentWasOpen) { - await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { - preview: false, - preserveFocus: true, - }) + await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: absolutePath, + options: ShowTextDocumentOptions.create({ + preview: false, + preserveFocus: true, + }), + }), + ) } await this.closeAllDiffViews() } @@ -376,9 +388,19 @@ export class DiffViewProvider { arePathsEqual(tab.input.modified.fsPath, uri.fsPath), ) if (diffTab && diffTab.input instanceof vscode.TabInputTextDiff) { - const editor = await vscode.window.showTextDocument(diffTab.input.modified, { - preserveFocus: true, - }) + const editorInfo = await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: diffTab.input.modified.fsPath, + options: ShowTextDocumentOptions.create({ + preserveFocus: true, + }), + }), + ) + // Find the editor that matches the returned path + const editor = vscode.window.visibleTextEditors.find((e) => e.document.uri.fsPath === editorInfo.documentPath) + if (!editor) { + throw new Error("Failed to find opened text editor") + } return editor } // Open new diff editor diff --git a/src/integrations/git/commit-message-generator.ts b/src/integrations/git/commit-message-generator.ts index 72878b28..a92e5a9a 100644 --- a/src/integrations/git/commit-message-generator.ts +++ b/src/integrations/git/commit-message-generator.ts @@ -1,6 +1,8 @@ import * as vscode from "vscode" import { getWorkingState } from "@utils/git" import { writeTextToClipboard } from "@utils/env" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowTextDocumentRequest } from "@/shared/proto/host/window" /** * Formats the git diff into a prompt for the AI @@ -130,6 +132,10 @@ async function editCommitMessage(message: string): Promise { language: "markdown", }) - await vscode.window.showTextDocument(document) + await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: document.uri.fsPath, + }), + ) vscode.window.showInformationMessage("Edit the commit message and copy when ready") } diff --git a/src/integrations/misc/export-markdown.ts b/src/integrations/misc/export-markdown.ts index 3a78748f..380b61d7 100644 --- a/src/integrations/misc/export-markdown.ts +++ b/src/integrations/misc/export-markdown.ts @@ -2,6 +2,8 @@ import { Anthropic } from "@anthropic-ai/sdk" import os from "os" import * as path from "path" import * as vscode from "vscode" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window" export async function downloadTask(dateTs: number, conversationHistory: Anthropic.MessageParam[]) { // File name @@ -38,7 +40,12 @@ export async function downloadTask(dateTs: number, conversationHistory: Anthropi try { // Write content to the selected location await vscode.workspace.fs.writeFile(saveUri, new TextEncoder().encode(markdownContent)) - vscode.window.showTextDocument(saveUri, { preview: true }) + await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: saveUri.fsPath, + options: ShowTextDocumentOptions.create({ preview: true }), + }), + ) } catch (error) { vscode.window.showErrorMessage( `Failed to save markdown file: ${error instanceof Error ? error.message : String(error)}`, diff --git a/src/integrations/misc/open-file.ts b/src/integrations/misc/open-file.ts index d4604841..54bac06b 100644 --- a/src/integrations/misc/open-file.ts +++ b/src/integrations/misc/open-file.ts @@ -2,6 +2,8 @@ import * as path from "path" import * as os from "os" import * as vscode from "vscode" import { arePathsEqual } from "@utils/path" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window" export async function openImage(dataUri: string) { const matches = dataUri.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/) @@ -42,7 +44,12 @@ export async function openFile(absolutePath: string) { } catch {} // not essential, sometimes tab operations fail const document = await vscode.workspace.openTextDocument(uri) - await vscode.window.showTextDocument(document, { preview: false }) + await getHostBridgeProvider().windowClient.showTextDocument( + ShowTextDocumentRequest.create({ + path: document.uri.fsPath, + options: ShowTextDocumentOptions.create({ preview: false }), + }), + ) } catch (error) { vscode.window.showErrorMessage(`Could not open file!`) } diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index 7e0be7bc..dd47ddc6 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -139,7 +139,6 @@ export class McpHub { console.log("[DEBUG] subscribing to mcp file changes") const cancelSubscription = getHostBridgeProvider().watchServiceClient.subscribeToFile( SubscribeToFileRequest.create({ - metadata: Metadata.create({}), path: settingsPath, }), { diff --git a/src/standalone/host-bridge-client-manager.ts b/src/standalone/host-bridge-client-manager.ts index f6bb26e4..927bbc88 100644 --- a/src/standalone/host-bridge-client-manager.ts +++ b/src/standalone/host-bridge-client-manager.ts @@ -4,12 +4,14 @@ import { WatchServiceClientImpl, WorkspaceServiceClientImpl, EnvServiceClientImpl, + WindowServiceClientImpl, } from "@generated/standalone/host-bridge-clients" import { UriServiceClientInterface, WatchServiceClientInterface, WorkspaceServiceClientInterface, EnvServiceClientInterface, + WindowServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" import { HostBridgeClientProvider } from "@/hosts/host-provider-types" @@ -23,6 +25,7 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider watchServiceClient: WatchServiceClientInterface workspaceClient: WorkspaceServiceClientInterface envClient: EnvServiceClientInterface + windowClient: WindowServiceClientInterface constructor() { const address = process.env.HOST_BRIDGE_ADDRESS || "localhost:50052" @@ -32,6 +35,7 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider this.watchServiceClient = new WatchServiceClientImpl(this.channel) this.workspaceClient = new WorkspaceServiceClientImpl(this.channel) this.envClient = new EnvServiceClientImpl(this.channel) + this.windowClient = new WindowServiceClientImpl(this.channel) } public close(): void { From 559eba5dd1ad0b74fcb49a9715215498ef8f241b Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 30 Jun 2025 18:55:19 -0700 Subject: [PATCH 47/60] Cleanup: Remove unused params from the ToolExecutor constructor. (#4588) Organize imports. --- src/core/task/ToolExecutor.ts | 78 ++++++++++++++++------------------- src/core/task/index.ts | 4 -- 2 files changed, 35 insertions(+), 47 deletions(-) diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 777b7e10..8962a6ab 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -1,17 +1,23 @@ -import * as vscode from "vscode" -import { TaskState } from "./TaskState" -import { MessageStateHandler } from "./message-state" +import { showSystemNotification } from "@/integrations/notifications" +import { listFiles } from "@/services/glob/list-files" +import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" +import { regexSearchFiles } from "@/services/ripgrep" +import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter" +import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array" +import { createAndOpenGitHubIssue } from "@/utils/github-url-utils" +import { getReadablePath, isLocatedInWorkspace } from "@/utils/path" +import Anthropic from "@anthropic-ai/sdk" import { ApiHandler } from "@api/index" -import { TerminalManager } from "@integrations/terminal/TerminalManager" -import { BrowserSession } from "@services/browser/BrowserSession" -import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" -import { McpHub } from "@services/mcp/McpHub" import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" +import { extractTextFromFile, processFilesIntoText } from "@integrations/misc/extract-text" +import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" +import { BrowserSession } from "@services/browser/BrowserSession" +import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" +import { McpHub } from "@services/mcp/McpHub" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" -import { ChatSettings } from "@shared/ChatSettings" -import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message" -import { AutoApprove } from "./tools/autoApprove" +import { BrowserSettings } from "@shared/BrowserSettings" import { BrowserAction, BrowserActionResult, @@ -25,37 +31,29 @@ import { ClineSayTool, COMPLETION_RESULT_CHANGES_FLAG, } from "@shared/ExtensionMessage" -import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker" -import { BrowserSettings } from "@shared/BrowserSettings" import { ClineAskResponse } from "@shared/WebviewMessage" -import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string" -import { fileExistsAtPath } from "@utils/fs" -import { formatResponse } from "../prompts/responses" -import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils" -import { ToolResponse, USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "." -import { serializeError } from "serialize-error" -import * as path from "path" -import { extractTextFromFile, processFilesIntoText } from "@integrations/misc/extract-text" import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences" -import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" -import { constructNewFileContent } from "../assistant-message/diff" -import { getReadablePath, isLocatedInWorkspace } from "@/utils/path" -import { listFiles } from "@/services/glob/list-files" -import { showNotificationForApprovalIfAutoApprovalEnabled } from "./utils" -import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter" -import { regexSearchFiles } from "@/services/ripgrep" -import { showSystemNotification } from "@/integrations/notifications" -import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array" -import { ensureTaskDirectoryExists } from "../storage/disk" -import { telemetryService } from "@/services/posthog/telemetry/TelemetryService" -import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation" -import Anthropic from "@anthropic-ai/sdk" -import { createAndOpenGitHubIssue } from "@/utils/github-url-utils" -import { getWorkspaceState } from "../storage/state" -import os from "os" -import { ContextManager } from "../context/context-management/ContextManager" +import { fileExistsAtPath } from "@utils/fs" +import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils" +import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string" import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import os from "os" +import * as path from "path" +import { serializeError } from "serialize-error" +import * as vscode from "vscode" +import { ToolResponse, USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "." +import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message" +import { constructNewFileContent } from "../assistant-message/diff" import { ChangeLocation, StreamingJsonReplacer } from "../assistant-message/diff-json" +import { ContextManager } from "../context/context-management/ContextManager" +import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation" +import { formatResponse } from "../prompts/responses" +import { ensureTaskDirectoryExists } from "../storage/disk" +import { getWorkspaceState } from "../storage/state" +import { TaskState } from "./TaskState" +import { MessageStateHandler } from "./message-state" +import { AutoApprove } from "./tools/autoApprove" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "./utils" export class ToolExecutor { private autoApprover: AutoApprove @@ -75,7 +73,6 @@ export class ToolExecutor { private taskState: TaskState, private messageStateHandler: MessageStateHandler, private api: ApiHandler, - private terminalManager: TerminalManager, private urlContentFetcher: UrlContentFetcher, private browserSession: BrowserSession, private diffViewProvider: DiffViewProvider, @@ -88,7 +85,6 @@ export class ToolExecutor { // Configuration & Settings private autoApprovalSettings: AutoApprovalSettings, private browserSettings: BrowserSettings, - private chatSettings: ChatSettings, private cwd: string, private taskId: string, @@ -106,8 +102,6 @@ export class ToolExecutor { partial?: boolean, ) => Promise<{ response: ClineAskResponse; text?: string; images?: string[]; files?: string[] }>, private saveCheckpoint: (isAttemptCompletionMessage?: boolean) => Promise, - private reinitExistingTaskFromId: (taskId: string) => Promise, - private cancelTask: () => Promise, private sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise, private removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise, private executeCommandTool: (command: string) => Promise<[boolean, any]>, @@ -336,8 +330,6 @@ export class ToolExecutor { // Handle write error return { shouldBreak: true, error: `Write error: ${e}` } } - - const newContentParsed = this.taskState.streamingJsonReplacer.getSuccessfullyParsedItems() } return { shouldBreak: true } // Wait for more chunks diff --git a/src/core/task/index.ts b/src/core/task/index.ts index a875a4d6..14c61445 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -279,7 +279,6 @@ export class Task { this.taskState, this.messageStateHandler, this.api, - this.terminalManager, this.urlContentFetcher, this.browserSession, this.diffViewProvider, @@ -290,14 +289,11 @@ export class Task { this.contextManager, this.autoApprovalSettings, this.browserSettings, - this.chatSettings, cwd, this.taskId, this.say.bind(this), this.ask.bind(this), this.saveCheckpoint.bind(this), - this.reinitExistingTaskFromId.bind(this), - this.cancelTask.bind(this), this.sayAndCreateMissingParamError.bind(this), this.removeLastPartialMessageIfExistsWithType.bind(this), this.executeCommandTool.bind(this), From 4b5b090b29e5eb8b2d38284c620a0ea679ee0313 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Mon, 30 Jun 2025 20:28:40 -0700 Subject: [PATCH 48/60] Remove unused param cwd (#4602) --- src/core/controller/file/deleteRuleFile.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/core/controller/file/deleteRuleFile.ts b/src/core/controller/file/deleteRuleFile.ts index cceb7fa3..9c9b03b8 100644 --- a/src/core/controller/file/deleteRuleFile.ts +++ b/src/core/controller/file/deleteRuleFile.ts @@ -1,13 +1,9 @@ -import { Controller } from ".." -import { RuleFileRequest, RuleFile } from "@shared/proto/file" -import { FileMethodHandler } from "./index" -import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" -import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules" -import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows" -import * as vscode from "vscode" +import { RuleFile, RuleFileRequest } from "@shared/proto/file" import * as path from "path" -import { cwd } from "@core/task" +import * as vscode from "vscode" +import { Controller } from ".." +import { FileMethodHandler } from "./index" /** * Deletes a rule file from either global or workspace rules directory From e5f78a0456c7b960c0c4f38d0737ca52094ea4ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Barreiro?= <52393857+BarreiroT@users.noreply.github.com> Date: Tue, 1 Jul 2025 08:39:58 +0200 Subject: [PATCH 49/60] Do not read auth variables from the user env when using Claude Code (#4591) --- .changeset/poor-years-grab.md | 5 +++++ src/integrations/claude-code/run.ts | 16 +++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 .changeset/poor-years-grab.md diff --git a/.changeset/poor-years-grab.md b/.changeset/poor-years-grab.md new file mode 100644 index 00000000..97e5ab22 --- /dev/null +++ b/.changeset/poor-years-grab.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +fix: Do not read auth variables from the user env when using Claude Code diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index 94d2766a..b89a1ea6 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -128,15 +128,21 @@ function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions args.push("--model", modelId) } + const env: NodeJS.ProcessEnv = { + ...process.env, + // The default is 32000. However, I've gotten larger responses, so we increase it unless the user specified it. + CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000", + } + + // We don't want to consume the user's ANTHROPIC_API_KEY, + // and will allow Claude Code to resolve auth by itself + delete env["ANTHROPIC_API_KEY"] + const claudeCodeProcess = execa(claudePath, args, { stdin: "pipe", stdout: "pipe", stderr: "pipe", - env: { - ...process.env, - // The default is 32000. However, I've gotten larger responses, so we increase it unless the user specified it. - CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000", - }, + env, cwd, maxBuffer: 1024 * 1024 * 1000, timeout: CLAUDE_CODE_TIMEOUT, From c7548a7f528fc516372d23e1a02e4ecb4cd2b0bc Mon Sep 17 00:00:00 2001 From: Ara Date: Wed, 2 Jul 2025 01:28:18 +0530 Subject: [PATCH 50/60] Fixing Bugs in ChatView with Primary/Secondary Buttons and related issues (#4553) * Splitting chat view into multiple modular files * Adding Comments and removing redundancies * Fixing Bugs in ChatView with Primary/Secondary Buttons and related issues --------- Co-authored-by: Cline Evaluation --- src/core/prompts/responses.ts | 3 + src/core/task/index.ts | 37 +++++++++- webview-ui/src/components/chat/ChatRow.tsx | 10 ++- .../components/layout/MessagesArea.tsx | 9 +-- .../messages/StreamingIndicator.tsx | 52 -------------- .../chat-view/components/messages/index.ts | 2 +- .../chat-view/hooks/useMessageHandlers.ts | 68 +++++++++++++++---- .../chat/chat-view/hooks/useScrollBehavior.ts | 17 ++--- .../chat/chat-view/utils/messageUtils.ts | 12 ++-- 9 files changed, 116 insertions(+), 94 deletions(-) diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts index 6284e795..9f970460 100644 --- a/src/core/prompts/responses.ts +++ b/src/core/prompts/responses.ts @@ -35,6 +35,9 @@ Otherwise, if you have not completed the task and do not need additional informa tooManyMistakes: (feedback?: string) => `You seem to be having trouble proceeding. The user has provided the following feedback to help guide you:\n\n${feedback}\n`, + autoApprovalMaxReached: (feedback?: string) => + `Auto-approval limit reached. The user has provided the following feedback to help guide you:\n\n${feedback}\n`, + missingToolParameterError: (paramName: string) => `Missing value for required parameter '${paramName}'. Please retry with complete response.\n\n${toolUseInstructionsReminder}`, diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 14c61445..270c42c0 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -1436,7 +1436,10 @@ export class Task { try { const { response, text, images, files } = await this.ask("command_output", chunk) if (response === "yesButtonClicked") { - // proceed while running + // proceed while running - but still capture user feedback if provided + if (text || (images && images.length > 0) || (files && files.length > 0)) { + userFeedback = { text, images, files } + } } else { userFeedback = { text, images, files } } @@ -1927,12 +1930,42 @@ export class Task { message: `Cline has auto-approved ${this.autoApprovalSettings.maxRequests.toString()} API requests.`, }) } - await this.ask( + const { response, text, images, files } = await this.ask( "auto_approval_max_req_reached", `Cline has auto-approved ${this.autoApprovalSettings.maxRequests.toString()} API requests. Would you like to reset the count and proceed with the task?`, ) // if we get past the promise it means the user approved and did not start a new task this.taskState.consecutiveAutoApprovedRequestsCount = 0 + + // Process user feedback if provided + if (response === "messageResponse") { + // Display the user's message in the chat UI + await this.say("user_feedback", text, images, files) + + // This userContent is for the *next* API call. + const feedbackUserContent: UserContent = [] + feedbackUserContent.push({ + type: "text", + text: formatResponse.autoApprovalMaxReached(text), + }) + if (images && images.length > 0) { + feedbackUserContent.push(...formatResponse.imageBlocks(images)) + } + + let fileContentString = "" + if (files && files.length > 0) { + fileContentString = await processFilesIntoText(files) + } + + if (fileContentString) { + feedbackUserContent.push({ + type: "text", + text: fileContentString, + }) + } + + userContent = feedbackUserContent + } } // get previous api req's index to check token usage and determine if we need to truncate conversation history diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index d948671c..e8dcde77 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1551,7 +1551,10 @@ export const ChatRowContent = memo( 0) + } inputValue={inputValue} /> {quoteButtonState.visible && ( @@ -1640,7 +1643,10 @@ export const ChatRowContent = memo( 0) + } inputValue={inputValue} /> {quoteButtonState.visible && ( diff --git a/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx b/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx index 47bd5749..78af98f8 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx @@ -66,7 +66,7 @@ export const MessagesArea: React.FC = ({
= ({ components={{ Footer: () =>
, // Add empty padding at the bottom }} + // increasing top by 3_000 to prevent jumping around when user collapses a row increaseViewportBy={{ top: 3_000, bottom: Number.MAX_SAFE_INTEGER, - }} - data={groupedMessages} + }} // hack to make sure the last message is always rendered to get truly perfect scroll to bottom animation when new messages are added (Number.MAX_SAFE_INTEGER is safe for arithmetic operations, which is all virtuoso uses this value for in src/sizeRangeSystem.ts) + data={groupedMessages} // messages is the raw format returned by extension, modifiedMessages is the manipulated structure that combines certain messages of related type, and visibleMessages is the filtered structure that removes messages that should not be rendered itemContent={itemContent} atBottomStateChange={(isAtBottom) => { setIsAtBottom(isAtBottom) @@ -88,7 +89,7 @@ export const MessagesArea: React.FC = ({ } setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom) }} - atBottomThreshold={10} + atBottomThreshold={10} // anything lower causes issues with followOutput initialTopMostItemIndex={groupedMessages.length - 1} />
diff --git a/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx b/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx index b9ed1508..aac8b1ff 100644 --- a/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx +++ b/webview-ui/src/components/chat/chat-view/components/messages/StreamingIndicator.tsx @@ -39,55 +39,3 @@ export const useIsStreaming = ( return false }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText]) } - -/** - * Component that shows a visual streaming indicator - * Can be used to show loading states, typing indicators, etc. - */ -export const StreamingVisualIndicator: React.FC<{ isStreaming: boolean }> = ({ isStreaming }) => { - if (!isStreaming) return null - - return ( -
-
- {[0, 1, 2].map((i) => ( -
- ))} -
- Cline is thinking... - -
- ) -} diff --git a/webview-ui/src/components/chat/chat-view/components/messages/index.ts b/webview-ui/src/components/chat/chat-view/components/messages/index.ts index 3d07a53e..40f9cbde 100644 --- a/webview-ui/src/components/chat/chat-view/components/messages/index.ts +++ b/webview-ui/src/components/chat/chat-view/components/messages/index.ts @@ -3,4 +3,4 @@ */ export { MessageRenderer, createMessageRenderer } from "./MessageRenderer" -export { useIsStreaming, StreamingVisualIndicator } from "./StreamingIndicator" +export { useIsStreaming } from "./StreamingIndicator" diff --git a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts index 82ebc737..afb46274 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts @@ -57,6 +57,8 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat case "resume_task": case "resume_completed_task": case "mistake_limit_reached": + case "auto_approval_max_req_reached": + case "api_req_failed": case "new_task": case "condense": case "report_bug": @@ -111,34 +113,69 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat switch (clineAsk) { case "api_req_failed": case "command": - case "command_output": case "tool": case "browser_action_launch": case "use_mcp_server": - case "resume_task": + // For approval buttons, if there's input content, send it as a proper user message + // If there's no input content, just approve the action + if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { + // Send as a regular message so it appears in the conversation + await handleSendMessage(trimmedInput || "", images || [], files || []) + } else { + // No input content, just approve the action + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "yesButtonClicked", + }), + ) + // Clear input state after sending (only when no content was sent as a message) + setInputValue("") + setActiveQuote(null) + setSelectedImages([]) + setSelectedFiles([]) + } + break case "mistake_limit_reached": case "auto_approval_max_req_reached": + case "command_output": + // For proceed buttons, if there's input content, send it as a proper user message + // If there's no input content, just proceed with the action if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { - await TaskServiceClient.askResponse( - AskResponseRequest.create({ - responseType: "yesButtonClicked", - text: trimmedInput, - images: images, - files: files, - }), - ) + // Send as a regular message so it appears in the conversation + await handleSendMessage(trimmedInput || "", images || [], files || []) } else { + // No input content, just proceed with the action await TaskServiceClient.askResponse( AskResponseRequest.create({ responseType: "yesButtonClicked", }), ) + // Clear input state after sending (only when no content was sent as a message) + setInputValue("") + setActiveQuote(null) + setSelectedImages([]) + setSelectedFiles([]) + } + break + case "resume_task": + // For resume_task, if there's input content, send it as a proper user message + // If there's no input content, just resume the task + if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) { + // Send as a regular message so it appears in the conversation + await handleSendMessage(trimmedInput || "", images || [], files || []) + } else { + // No input content, just resume the task + await TaskServiceClient.askResponse( + AskResponseRequest.create({ + responseType: "yesButtonClicked", + }), + ) + // Clear input state after sending (only when no content was sent as a message) + setInputValue("") + setActiveQuote(null) + setSelectedImages([]) + setSelectedFiles([]) } - // Clear input state after sending - setInputValue("") - setActiveQuote(null) - setSelectedImages([]) - setSelectedFiles([]) break case "completion_result": case "resume_completed_task": @@ -185,6 +222,7 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat setSendingDisabled, setEnableButtons, chatState, + handleSendMessage, ], ) diff --git a/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts b/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts index 5cef086c..60902f85 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts @@ -32,8 +32,6 @@ export function useScrollBehavior( const [showScrollToBottom, setShowScrollToBottom] = useState(false) const [isAtBottom, setIsAtBottom] = useState(false) const [pendingScrollToMessage, setPendingScrollToMessage] = useState(null) - - // Smooth scroll to bottom with debounce const scrollToBottomSmooth = useMemo( () => debounce( @@ -49,7 +47,7 @@ export function useScrollBehavior( [], ) - // Instant scroll to bottom + // Smooth scroll to bottom with debounce const scrollToBottomAuto = useCallback(() => { virtuosoRef.current?.scrollTo({ top: Number.MAX_SAFE_INTEGER, @@ -57,7 +55,6 @@ export function useScrollBehavior( }) }, []) - // Scroll to specific message const scrollToMessage = useCallback( (messageIndex: number) => { setPendingScrollToMessage(messageIndex) @@ -113,7 +110,7 @@ export function useScrollBehavior( [messages, visibleMessages, groupedMessages], ) - // Toggle row expansion with scroll handling + // scroll when user toggles certain rows const toggleRowExpansion = useCallback( (ts: number) => { const isCollapsing = expandedRows[ts] ?? false @@ -165,10 +162,9 @@ export function useScrollBehavior( } } }, - [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom, setExpandedRows], + [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom], ) - // Handle row height changes const handleRowHeightChange = useCallback( (isTaller: boolean) => { if (!disableAutoScrollRef.current) { @@ -184,23 +180,21 @@ export function useScrollBehavior( [scrollToBottomSmooth, scrollToBottomAuto], ) - // Auto-scroll when new messages arrive useEffect(() => { if (!disableAutoScrollRef.current) { setTimeout(() => { scrollToBottomSmooth() }, 50) + // return () => clearTimeout(timer) // dont cleanup since if visibleMessages.length changes it cancels. } }, [groupedMessages.length, scrollToBottomSmooth]) - // Handle pending scroll to message useEffect(() => { if (pendingScrollToMessage !== null) { scrollToMessage(pendingScrollToMessage) } }, [pendingScrollToMessage, groupedMessages, scrollToMessage]) - // Handle wheel events to detect manual scrolling const handleWheel = useCallback((event: Event) => { const wheelEvent = event as WheelEvent if (wheelEvent.deltaY && wheelEvent.deltaY < 0) { @@ -210,8 +204,7 @@ export function useScrollBehavior( } } }, []) - - useEvent("wheel", handleWheel, window, { passive: true }) + useEvent("wheel", handleWheel, window, { passive: true }) // passive improves scrolling performance return { virtuosoRef, diff --git a/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts b/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts index ab5c12ac..9693595d 100644 --- a/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts +++ b/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts @@ -20,23 +20,23 @@ export function filterVisibleMessages(messages: ClineMessage[]): ClineMessage[] return messages.filter((message) => { switch (message.ask) { case "completion_result": - // don't show a chat row for a completion_result ask without text + // don't show a chat row for a completion_result ask without text. This specific type of message only occurs if cline wants to execute a command as part of its completion result, in which case we interject the completion_result tool with the execute_command tool. if (message.text === "") { return false } break - case "api_req_failed": + case "api_req_failed": // this message is used to update the latest api_req_started that the request failed case "resume_task": case "resume_completed_task": return false } switch (message.say) { - case "api_req_finished": - case "api_req_retried": - case "deleted_api_reqs": + case "api_req_finished": // combineApiRequests removes this from modifiedMessages anyways + case "api_req_retried": // this message is used to update the latest api_req_started that the request was retried + case "deleted_api_reqs": // aggregated api_req metrics from deleted messages return false case "text": - // Sometimes cline returns an empty text message, we don't want to render these + // Sometimes cline returns an empty text message, we don't want to render these. (We also use a say text for user messages, so in case they just sent images we still render that) if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) { return false } From da6f705df28dccc65b134b49cc1677cf27c0f86c Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 1 Jul 2025 14:06:14 -0700 Subject: [PATCH 51/60] Remove unused file get-python-env.ts (#4604) --- src/integrations/workspace/get-python-env.ts | 43 -------------------- 1 file changed, 43 deletions(-) delete mode 100644 src/integrations/workspace/get-python-env.ts diff --git a/src/integrations/workspace/get-python-env.ts b/src/integrations/workspace/get-python-env.ts deleted file mode 100644 index f47f0d4c..00000000 --- a/src/integrations/workspace/get-python-env.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { getCwd } from "@/utils/path" -import * as vscode from "vscode" - -/* -Used to get user's current python environment (unnecessary now that we use the IDE's terminal) -${await (async () => { - try { - const pythonEnvPath = await getPythonEnvPath() - if (pythonEnvPath) { - return `\nPython Environment: ${pythonEnvPath}` - } - } catch {} - return "" - })()} -*/ -export async function getPythonEnvPath(): Promise { - const pythonExtension = vscode.extensions.getExtension("ms-python.python") - - if (!pythonExtension) { - return undefined - } - - // Ensure the Python extension is activated - if (!pythonExtension.isActive) { - // if the python extension is not active, we can assume the project is not a python project - return undefined - } - - // Access the Python extension API - const pythonApi = pythonExtension.exports - // Get the active environment path for the current workspace - const workspaceFolder = await getCwd() - if (!workspaceFolder) { - return undefined - } - // Get the active python environment path for the current workspace - const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder) - if (pythonEnv && pythonEnv.path) { - return pythonEnv.path - } else { - return undefined - } -} From c9822161135e633f8125af20d86edfb8ed2cb2c8 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 1 Jul 2025 14:44:41 -0700 Subject: [PATCH 52/60] Cleanup: Remove unused property and param postMessage from ClineAccountService (#4620) * Remove unused property and param postMessage * Remove unused property and param postMessage Remove unused import. --- src/core/controller/index.ts | 11 ++++------- src/services/account/ClineAccountService.ts | 7 +------ src/services/test/TestMode.ts | 1 - 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 825e915a..a80e0567 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -78,13 +78,10 @@ export class Controller { (msg) => this.postMessageToWebview(msg), this.context.extension?.packageJSON?.version ?? "1.0.0", ) - this.accountService = new ClineAccountService( - (msg) => this.postMessageToWebview(msg), - async () => { - const { apiConfiguration } = await this.getStateToPostToWebview() - return apiConfiguration?.clineApiKey - }, - ) + this.accountService = new ClineAccountService(async () => { + const { apiConfiguration } = await this.getStateToPostToWebview() + return apiConfiguration?.clineApiKey + }) // Clean up legacy checkpoints cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath, this.outputChannel).catch((error) => { diff --git a/src/services/account/ClineAccountService.ts b/src/services/account/ClineAccountService.ts index d93afbb4..c87ebf5a 100644 --- a/src/services/account/ClineAccountService.ts +++ b/src/services/account/ClineAccountService.ts @@ -4,14 +4,9 @@ import { ExtensionMessage } from "@shared/ExtensionMessage" export class ClineAccountService { private readonly baseUrl = "https://api.cline.bot/v1" - private postMessageToWebview: (message: ExtensionMessage) => Promise private getClineApiKey: () => Promise - constructor( - postMessageToWebview: (message: ExtensionMessage) => Promise, - getClineApiKey: () => Promise, - ) { - this.postMessageToWebview = postMessageToWebview + constructor(getClineApiKey: () => Promise) { this.getClineApiKey = getClineApiKey } diff --git a/src/services/test/TestMode.ts b/src/services/test/TestMode.ts index 343c6ffe..f99b1319 100644 --- a/src/services/test/TestMode.ts +++ b/src/services/test/TestMode.ts @@ -9,7 +9,6 @@ import * as path from "path" import { Logger } from "../logging/Logger" import { createTestServer, shutdownTestServer } from "./TestServer" import { getHostBridgeProvider } from "@/hosts/host-providers" -import { GetWorkspacePathsRequest } from "@/shared/proto/index.host" // State variable let isTestMode = false From 01178909ee4cadf58cddefa6ae9a6b3748d48b5e Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Tue, 1 Jul 2025 15:15:10 -0700 Subject: [PATCH 53/60] adding unique remote git urls to context on first message env variables (#4622) Co-authored-by: Cline Evaluation --- src/core/task/index.ts | 7 +++++++ src/utils/git.ts | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 270c42c0..d98fbe4f 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -35,6 +35,7 @@ import pTimeout from "p-timeout" import pWaitFor from "p-wait-for" import * as path from "path" import * as vscode from "vscode" +import { getGitRemoteUrls } from "@utils/git" import { parseAssistantMessageV2, parseAssistantMessageV3, ToolUseName } from "@core/assistant-message" import { @@ -2580,6 +2581,12 @@ export class Task { const result = formatResponse.formatFilesList(cwd, files, didHitLimit, this.clineIgnoreController) details += result } + + // Add git remote URLs section + const gitRemotes = await getGitRemoteUrls(cwd) + if (gitRemotes.length > 0) { + details += `\n\n# Git Remote URLs\n${gitRemotes.join("\n")}` + } } // Add context window usage information diff --git a/src/utils/git.ts b/src/utils/git.ts index 55832369..4e0c8484 100644 --- a/src/utils/git.ts +++ b/src/utils/git.ts @@ -185,6 +185,42 @@ export async function getWorkingState(cwd: string): Promise { } } +export async function getGitRemoteUrls(cwd: string): Promise { + try { + const isInstalled = await checkGitInstalled() + if (!isInstalled) { + return [] + } + + const isRepo = await checkGitRepo(cwd) + if (!isRepo) { + return [] + } + + const { stdout } = await execAsync("git remote -v", { cwd }) + if (!stdout.trim()) { + return [] + } + + // Parse output to extract unique URLs + // git remote -v output format: "remoteName remoteUrl (fetch|push)" + const remotes = stdout + .trim() + .split("\n") + .filter((line) => line.includes("(fetch)")) // Only fetch URLs to avoid duplicates + .map((line) => { + const match = line.match(/^(\S+)\s+(\S+)\s+\(fetch\)$/) + return match ? { name: match[1], url: match[2] } : null + }) + .filter((remote): remote is { name: string; url: string } => remote !== null) + + return remotes.map((remote) => `${remote.name}: ${remote.url}`) + } catch (error) { + console.error("Error getting git remotes:", error) + return [] + } +} + function truncateOutput(content: string): string { if (!GIT_OUTPUT_LINE_LIMIT) { return content From b3d3e9861f420807a8fb611ec987bed59791da69 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Tue, 1 Jul 2025 16:01:33 -0700 Subject: [PATCH 54/60] Use the host bridge to get the cwd in autoApprove.ts (#4601) Update the ToolExecutor to use await because the approval is now async. --- src/core/task/ToolExecutor.ts | 25 ++++++++++++++----------- src/core/task/tools/autoApprove.ts | 8 +++----- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 8962a6ab..7afdcc8c 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -63,7 +63,10 @@ export class ToolExecutor { return this.autoApprover.shouldAutoApproveTool(toolName) } - private shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean { + private async shouldAutoApproveToolWithPath( + blockname: ToolUseName, + autoApproveActionpath: string | undefined, + ): Promise { return this.autoApprover.shouldAutoApproveToolWithPath(blockname, autoApproveActionpath) } @@ -573,7 +576,7 @@ export class ToolExecutor { // update gui message const partialMessage = JSON.stringify(sharedMessageProps) - if (this.shouldAutoApproveToolWithPath(block.name, relPath)) { + if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") // in case the user changes auto-approval settings mid stream await this.say("tool", partialMessage, undefined, undefined, block.partial) } else { @@ -645,7 +648,7 @@ export class ToolExecutor { // ) // : undefined, } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, relPath)) { + if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ @@ -782,7 +785,7 @@ export class ToolExecutor { content: undefined, operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", partialMessage, undefined, undefined, block.partial) } else { @@ -813,7 +816,7 @@ export class ToolExecutor { content: absolutePath, operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) // need to be sending partialValue bool, since undefined has its own purpose in that the message is treated neither as a partial or completion of a partial, but as a single complete message this.taskState.consecutiveAutoApprovedRequestsCount++ @@ -864,7 +867,7 @@ export class ToolExecutor { content: "", operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", partialMessage, undefined, undefined, block.partial) } else { @@ -896,7 +899,7 @@ export class ToolExecutor { content: result, operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ @@ -939,7 +942,7 @@ export class ToolExecutor { content: "", operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", partialMessage, undefined, undefined, block.partial) } else { @@ -968,7 +971,7 @@ export class ToolExecutor { content: result, operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ @@ -1015,7 +1018,7 @@ export class ToolExecutor { content: "", operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", partialMessage, undefined, undefined, block.partial) } else { @@ -1052,7 +1055,7 @@ export class ToolExecutor { content: results, operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), } satisfies ClineSayTool) - if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { + if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) this.taskState.consecutiveAutoApprovedRequestsCount++ diff --git a/src/core/task/tools/autoApprove.ts b/src/core/task/tools/autoApprove.ts index 8411a4ae..8150d4aa 100644 --- a/src/core/task/tools/autoApprove.ts +++ b/src/core/task/tools/autoApprove.ts @@ -1,11 +1,8 @@ import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { ToolUseName } from "@core/assistant-message" import * as path from "path" -import * as vscode from "vscode" import os from "os" - -export const cwd = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") +import { getCwd } from "@/utils/path" export class AutoApprove { autoApprovalSettings: AutoApprovalSettings @@ -54,9 +51,10 @@ export class AutoApprove { // Check if the tool should be auto-approved based on the settings // and the path of the action. Returns true if the tool should be auto-approved // based on the user's settings and the path of the action. - shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean { + async shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): Promise { let isLocalRead: boolean = false if (autoApproveActionpath) { + const cwd = await getCwd(path.join(os.homedir(), "Desktop")) const absolutePath = path.resolve(cwd, autoApproveActionpath) isLocalRead = absolutePath.startsWith(cwd) } else { From 27f8372c5bb8e0fd36dcb1daf6043d1518338ee8 Mon Sep 17 00:00:00 2001 From: kevinneung <94151024+kevinneung@users.noreply.github.com> Date: Tue, 1 Jul 2025 16:50:02 -0700 Subject: [PATCH 55/60] add cline.walkthrough to command handler (#4621) added cline.walkthrough to command handler, since it would throw an error otherwise --- .changeset/lucky-fans-greet.md | 5 +++++ src/extension.ts | 8 ++++++++ 2 files changed, 13 insertions(+) create mode 100644 .changeset/lucky-fans-greet.md diff --git a/.changeset/lucky-fans-greet.md b/.changeset/lucky-fans-greet.md new file mode 100644 index 00000000..001f3144 --- /dev/null +++ b/.changeset/lucky-fans-greet.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +add cline.walkthrough command to command handler diff --git a/src/extension.ts b/src/extension.ts index dcc570db..f74cd398 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -640,6 +640,14 @@ export async function activate(context: vscode.ExtensionContext) { }), ) + // Register the openWalkthrough command handler + context.subscriptions.push( + vscode.commands.registerCommand("cline.openWalkthrough", async () => { + await vscode.commands.executeCommand("workbench.action.openWalkthrough", "saoudrizwan.claude-dev#ClineWalkthrough") + telemetryService.captureButtonClick("command_openWalkthrough", undefined, true) + }), + ) + // Register the generateGitCommitMessage command handler context.subscriptions.push( vscode.commands.registerCommand("cline.generateGitCommitMessage", async () => { From 87322feeb704cd78c2fc4b62ddc354220427a4fa Mon Sep 17 00:00:00 2001 From: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com> Date: Tue, 1 Jul 2025 16:57:36 -0700 Subject: [PATCH 56/60] Fall back to getting current terminal content when shell integration API fails to return output (#4605) * Revert to when terminal process worked more reliably * Get last terminal output if no output is retrieved * Fix getting terminal output for when shell integration unavailable * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Revert removing previous changes * Update TerminalProcess to emit current terminal contents instead of a silent command completion message * Revert when first chunk fails message * Revert error title * Fixing tests with fake timers --------- Co-authored-by: Dennise Bartlett Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Cline Evaluation --- .../terminal/TerminalProcess.test.ts | 55 ++++++++++++++++--- src/integrations/terminal/TerminalProcess.ts | 27 ++++++++- webview-ui/src/components/chat/ChatRow.tsx | 12 ++-- 3 files changed, 79 insertions(+), 15 deletions(-) diff --git a/src/integrations/terminal/TerminalProcess.test.ts b/src/integrations/terminal/TerminalProcess.test.ts index 7be7d732..34636155 100644 --- a/src/integrations/terminal/TerminalProcess.test.ts +++ b/src/integrations/terminal/TerminalProcess.test.ts @@ -60,7 +60,14 @@ describe("TerminalProcess (Integration Tests)", () => { const emitSpy = sandbox.spy(process, "emit") // Run a simple command - await process.run(terminal, "echo test") + const runPromise = process.run(terminal, "echo test") + + // If terminal doesn't have shell integration, advance timer + if (!terminal.shellIntegration) { + await sandbox.clock.tickAsync(3000) + } + + await runPromise // Verify that the continue event was emitted ;(emitSpy as sinon.SinonSpy).calledWith("continue").should.be.true() @@ -76,7 +83,14 @@ describe("TerminalProcess (Integration Tests)", () => { const emitSpy = sandbox.spy(process, "emit") // Run a command that produces predictable output - await process.run(terminal, "echo 'Line 1' && echo 'Line 2'") + const runPromise = process.run(terminal, "echo 'Line 1' && echo 'Line 2'") + + // If terminal doesn't have shell integration, advance timer + if (!terminal.shellIntegration) { + await sandbox.clock.tickAsync(3000) + } + + await runPromise // Check that the events were emitted ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() @@ -92,7 +106,14 @@ describe("TerminalProcess (Integration Tests)", () => { const emitSpy = sandbox.spy(process, "emit") // Run a command that lists files - await process.run(terminal, "ls -la") + const runPromise = process.run(terminal, "ls -la") + + // If terminal doesn't have shell integration, advance timer + if (!terminal.shellIntegration) { + await sandbox.clock.tickAsync(3000) + } + + await runPromise // Verify that the continue event was emitted ;(emitSpy as sinon.SinonSpy).calledWith("continue").should.be.true() @@ -130,7 +151,14 @@ describe("TerminalProcess (Integration Tests)", () => { const emitSpy = sandbox.spy(process, "emit") // Run a command that produces predictable output - await process.run(terminal, "echo 'Line 1' 'Line 2'") + const runPromise = process.run(terminal, "echo 'Line 1' 'Line 2'") + + // If terminal doesn't have shell integration, advance timer + if (!terminal.shellIntegration) { + await sandbox.clock.tickAsync(3000) + } + + await runPromise // Check that the events were emitted ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() @@ -146,7 +174,14 @@ describe("TerminalProcess (Integration Tests)", () => { const emitSpy = sandbox.spy(process, "emit") // Run a command that produces predictable output - await process.run(terminal, "echo \"Line 1\" && echo 'Line 2'") + const runPromise = process.run(terminal, "echo \"Line 1\" && echo 'Line 2'") + + // If terminal doesn't have shell integration, advance timer + if (!terminal.shellIntegration) { + await sandbox.clock.tickAsync(3000) + } + + await runPromise // Check that the events were emitted ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() @@ -169,8 +204,14 @@ describe("TerminalProcess (Integration Tests)", () => { // Spy on the emit function to verify events const emitSpy = sandbox.spy(process, "emit") - // Run the command - await process.run(terminal, "test-command") + // Run the command - this returns a promise + const runPromise = process.run(terminal, "test-command") + + // Advance the fake timer by 3 seconds to trigger the setTimeout + await sandbox.clock.tickAsync(3000) + + // Now wait for the promise to resolve + await runPromise // Check that the correct methods were called and events emitted sendTextStub.calledWith("test-command", true).should.be.true() diff --git a/src/integrations/terminal/TerminalProcess.ts b/src/integrations/terminal/TerminalProcess.ts index df4d9c1b..c987d1d1 100644 --- a/src/integrations/terminal/TerminalProcess.ts +++ b/src/integrations/terminal/TerminalProcess.ts @@ -2,6 +2,7 @@ import { EventEmitter } from "events" import { stripAnsi } from "./ansiUtils" import * as vscode from "vscode" import { Logger } from "@services/logging/Logger" +import { getLatestTerminalOutput } from "./get-latest-output" export interface TerminalProcessEvents { line: [line: string] @@ -31,6 +32,19 @@ export class TerminalProcess extends EventEmitter { // super() async run(terminal: vscode.Terminal, command: string) { + // When command does not produce any output, we can assume the shell integration API failed and as a fallback return the current terminal contents + const emitCurrentTerminalContents = async () => { + try { + const terminalSnapshot = await getLatestTerminalOutput() + if (terminalSnapshot && terminalSnapshot.trim()) { + const fallbackMessage = `The command's output could not be captured due to some technical issue, however it has been executed successfully. Here's the current terminal's content to help you get the command's output:\n\n${terminalSnapshot}` + this.emit("line", fallbackMessage) + } + } catch (error) { + console.error("Error capturing terminal output:", error) + } + } + // Clear any existing grace period timer from previous commands if (this.gracePeriodTimer) { clearTimeout(this.gracePeriodTimer) @@ -249,7 +263,8 @@ export class TerminalProcess extends EventEmitter { if (!didEmitEmptyLine) { console.log(`[TerminalProcess] Emitting fallback empty line for no-output command`) this.emit("line", "") // empty line to show proceed button - this.emit("line", "[Command completed with no output]") + // this.emit("line", "[Command completed with no output]") + await emitCurrentTerminalContents() didEmitEmptyLine = true } } @@ -295,7 +310,8 @@ export class TerminalProcess extends EventEmitter { console.log(`[TerminalProcess] WARNING: Process completed but no output was captured`) // Ensure we emit at least one line for UI feedback if (!didEmitEmptyLine) { - this.emit("line", "[Command completed silently]") + // this.emit("line", "[Command completed silently]") + await emitCurrentTerminalContents() } } @@ -314,7 +330,14 @@ export class TerminalProcess extends EventEmitter { this.startGracePeriod() } } else { + // no shell integration detected, we'll fallback to running the command and capturing the terminal's output after some time terminal.sendText(command, true) + + // wait 3 seconds for the command to run + await new Promise((resolve) => setTimeout(resolve, 3000)) + + // For terminals without shell integration, also try to capture terminal content + await emitCurrentTerminalContents() // For terminals without shell integration, we can't know when the command completes // So we'll just emit the continue event after a delay this.emit("completed") diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index e8dcde77..97502031 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1353,7 +1353,7 @@ export const ChatRowContent = memo( style={{ display: "flex", flexDirection: "column", - backgroundColor: "rgba(255, 191, 0, 0.1)", + backgroundColor: "var(--vscode-textBlockQuote-background)", padding: 8, borderRadius: 3, fontSize: 12, @@ -1368,19 +1368,19 @@ export const ChatRowContent = memo( className="codicon codicon-warning" style={{ marginRight: 8, - fontSize: 18, - color: "#FFA500", + fontSize: 14, + color: "var(--vscode-descriptionForeground)", }}>
Shell Integration Unavailable
-
- Cline won't be able to view the command's output. Please update VSCode ( +
+ Cline may have trouble viewing the command's output. Please update VSCode ( CMD/CTRL + Shift + P → "Update") and make sure you're using a supported shell: zsh, bash, fish, or PowerShell (CMD/CTRL + Shift + P → "Terminal: Select Default Profile").{" "} From 52571ccee842b836fb8846c7bba31f2b29755c38 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Tue, 1 Jul 2025 17:08:28 -0700 Subject: [PATCH 57/60] base (#4600) --- evals/diff-edits/diff-apply/diff-06-26-25.ts | 6 +++ src/core/assistant-message/diff.test.ts | 39 ++++++++++++++++++++ src/core/assistant-message/diff.ts | 4 ++ 3 files changed, 49 insertions(+) diff --git a/evals/diff-edits/diff-apply/diff-06-26-25.ts b/evals/diff-edits/diff-apply/diff-06-26-25.ts index 770a781b..27f1d57a 100644 --- a/evals/diff-edits/diff-apply/diff-06-26-25.ts +++ b/evals/diff-edits/diff-apply/diff-06-26-25.ts @@ -492,6 +492,12 @@ async function constructNewFileContentV1(diffContent: string, originalContent: s if (isReplaceBlockEnd(line)) { // Finished one replace block + if (searchMatchIndex === -1) { + throw new Error( + `The SEARCH block:\n${currentSearchContent.trimEnd()}\n...is malformatted.`, + ) + } + // Store this replacement replacements.push({ start: searchMatchIndex, diff --git a/src/core/assistant-message/diff.test.ts b/src/core/assistant-message/diff.test.ts index f821086d..6d4be061 100644 --- a/src/core/assistant-message/diff.test.ts +++ b/src/core/assistant-message/diff.test.ts @@ -156,6 +156,45 @@ replaced expected: "line2\nreplaced\nline4", isFinal: true, }, + { + name: "malformed diff - missing separator", + original: "line1\nline2\nline3", + diff: `------- SEARCH +line2 ++++++++ REPLACE +replaced`, + shouldThrow: true, + }, + { + name: "malformed diff - trailing space on separator", + original: "line1\nline2\nline3", + diff: `------- SEARCH +line2 +======= +replaced ++++++++ REPLACE`, + shouldThrow: true, + }, + { + name: "malformed diff - double replace markers", + original: "line1\nline2\nline3", + diff: `------- SEARCH +line2 ++++++++ REPLACE +first replacement ++++++++ REPLACE`, + shouldThrow: true, + }, + { + name: "malformed diff - malformed separator with dashes", + original: "line1\nline2\nline3", + diff: `------- SEARCH +line2 +------- ======= +replaced ++++++++ REPLACE`, + shouldThrow: true, + }, ] //.filter(({name}) => name === "multiple ordered replacements") //.filter(({name}) => name === "delete then replace") diff --git a/src/core/assistant-message/diff.ts b/src/core/assistant-message/diff.ts index f5696fc6..6fe10a39 100644 --- a/src/core/assistant-message/diff.ts +++ b/src/core/assistant-message/diff.ts @@ -380,6 +380,10 @@ async function constructNewFileContentV1(diffContent: string, originalContent: s if (isReplaceBlockEnd(line)) { // Finished one replace block + if (searchMatchIndex === -1) { + throw new Error(`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...is malformatted.`) + } + // Store this replacement replacements.push({ start: searchMatchIndex, From 64963c4e9c1f579c75fa275f36a73aef206b02e7 Mon Sep 17 00:00:00 2001 From: canvrno <46584286+canvrno@users.noreply.github.com> Date: Tue, 1 Jul 2025 22:41:58 -0700 Subject: [PATCH 58/60] confirmation popup when deleting tasks (#4627) --- .changeset/afraid-experts-beg.md | 5 +++++ src/core/controller/task/deleteTasksWithIds.ts | 13 +++++++++++++ .../chat/task-header/buttons/DeleteTaskButton.tsx | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 .changeset/afraid-experts-beg.md diff --git a/.changeset/afraid-experts-beg.md b/.changeset/afraid-experts-beg.md new file mode 100644 index 00000000..888b827d --- /dev/null +++ b/.changeset/afraid-experts-beg.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Add confirmation popup when deleting tasks diff --git a/src/core/controller/task/deleteTasksWithIds.ts b/src/core/controller/task/deleteTasksWithIds.ts index b63fc1a2..406f742f 100644 --- a/src/core/controller/task/deleteTasksWithIds.ts +++ b/src/core/controller/task/deleteTasksWithIds.ts @@ -1,5 +1,6 @@ import path from "path" import fs from "fs/promises" +import vscode from "vscode" import { Controller } from ".." import { Empty, StringArrayRequest, BooleanRequest } from "../../../shared/proto/common" import { TaskMethodHandler } from "./index" @@ -20,6 +21,18 @@ export const deleteTasksWithIds: TaskMethodHandler = async ( throw new Error("Missing task IDs") } + const taskCount = request.value.length + const message = + taskCount === 1 + ? "Are you sure you want to delete this task? This action cannot be undone." + : `Are you sure you want to delete these ${taskCount} tasks? This action cannot be undone.` + + const userChoice = await vscode.window.showWarningMessage(message, { modal: true }, "Delete") + + if (userChoice === undefined) { + return Empty.create() + } + for (const id of request.value) { await deleteTaskWithId(controller, id) } diff --git a/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx b/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx index d296af25..c35b4cae 100644 --- a/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx @@ -7,7 +7,7 @@ const DeleteTaskButton: React.FC<{ taskSize: string taskId?: string }> = ({ taskSize, taskId }) => ( - + taskId && TaskServiceClient.deleteTasksWithIds(StringArrayRequest.create({ value: [taskId] }))} From 2af151e736f964447f959eee3e54271c32f93002 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Wed, 2 Jul 2025 19:39:49 -0500 Subject: [PATCH 59/60] [SettingsView] [ApiConfig Section] save on change (#4554) * refactor out apiconfig section * add general settings section * duplicate import * move terminal, browser, and feature settings * move files to sections folder * refactor out debug section * pull out about section * implement save on change and remove confirmation modals for api config section * add doc strings to new hook functions * add debounced text field for smooth typing * use context value directly for apiProvider dropdown value; remove unecessary memo; remove keys from ApiOptions * add welcomeViewCompleted state boolean to control welcome view showing * refactor other sections to save-on-change; remove form diff calculation logic * cleanup * remove memo * make welcomeViewCompleted context value initial value false --- proto/state.proto | 1 + src/core/controller/index.ts | 2 + .../state/setWelcomeViewCompleted.ts | 25 + src/core/storage/state-keys.ts | 1 + src/core/storage/state-migrations.ts | 54 +- src/core/storage/state.ts | 3 + src/extension.ts | 4 + src/shared/ExtensionMessage.ts | 1 + .../src/components/chat/ChatTextArea.tsx | 1 - .../src/components/settings/ApiOptions.tsx | 250 ++------- .../settings/OpenRouterModelPicker.tsx | 23 +- .../settings/PreferredLanguageSetting.tsx | 29 +- .../settings/RequestyModelPicker.tsx | 20 +- .../src/components/settings/SettingsView.tsx | 509 +----------------- .../TerminalOutputLineLimitSlider.tsx | 5 +- .../settings/ThinkingBudgetSlider.tsx | 42 +- .../settings/common/ApiKeyField.tsx | 66 ++- .../settings/common/BaseUrlField.tsx | 20 +- .../settings/common/DebouncedTextField.tsx | 33 ++ .../settings/providers/AnthropicProvider.tsx | 41 +- .../settings/providers/AskSageProvider.tsx | 25 +- .../settings/providers/BedrockProvider.tsx | 112 ++-- .../settings/providers/CerebrasProvider.tsx | 17 +- .../settings/providers/ClaudeCodeProvider.tsx | 28 +- .../settings/providers/ClineProvider.tsx | 18 +- .../settings/providers/DeepSeekProvider.tsx | 15 +- .../settings/providers/DoubaoProvider.tsx | 15 +- .../settings/providers/FireworksProvider.tsx | 50 +- .../settings/providers/GeminiProvider.tsx | 41 +- .../settings/providers/LMStudioProvider.tsx | 29 +- .../settings/providers/LiteLlmProvider.tsx | 117 ++-- .../settings/providers/MistralProvider.tsx | 15 +- .../settings/providers/NebiusProvider.tsx | 17 +- .../settings/providers/OllamaProvider.tsx | 53 +- .../settings/providers/OpenAICompatible.tsx | 194 +++---- .../settings/providers/OpenAINative.tsx | 20 +- .../settings/providers/OpenRouterProvider.tsx | 35 +- .../settings/providers/QwenProvider.tsx | 30 +- .../settings/providers/RequestyProvider.tsx | 14 +- .../settings/providers/SambanovaProvider.tsx | 15 +- .../settings/providers/SapAiCoreProvider.tsx | 56 +- .../settings/providers/TogetherProvider.tsx | 23 +- .../settings/providers/VSCodeLmProvider.tsx | 19 +- .../settings/providers/VertexProvider.tsx | 39 +- .../settings/providers/XaiProvider.tsx | 39 +- .../sections/ApiConfigurationSection.tsx | 42 +- .../sections/BrowserSettingsSection.tsx | 192 ++----- .../sections/FeatureSettingsSection.tsx | 41 +- .../sections/GeneralSettingsSection.tsx | 22 +- .../sections/TerminalSettingsSection.tsx | 34 +- .../settings/utils/settingsHandlers.ts | 35 ++ .../utils/useApiConfigurationHandlers.ts | 62 +++ .../settings/utils/useDebouncedInput.ts | 31 ++ .../src/components/welcome/WelcomeView.tsx | 21 +- .../src/context/ExtensionStateContext.tsx | 31 +- 55 files changed, 987 insertions(+), 1690 deletions(-) create mode 100644 src/core/controller/state/setWelcomeViewCompleted.ts create mode 100644 webview-ui/src/components/settings/common/DebouncedTextField.tsx create mode 100644 webview-ui/src/components/settings/utils/settingsHandlers.ts create mode 100644 webview-ui/src/components/settings/utils/useApiConfigurationHandlers.ts create mode 100644 webview-ui/src/components/settings/utils/useDebouncedInput.ts diff --git a/proto/state.proto b/proto/state.proto index 440abae1..b9dccb34 100644 --- a/proto/state.proto +++ b/proto/state.proto @@ -18,6 +18,7 @@ service StateService { rpc updateAutoApprovalSettings(AutoApprovalSettingsRequest) returns (Empty); rpc updateSettings(UpdateSettingsRequest) returns (Empty); rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty); + rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty); } message State { diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index a80e0567..6da05eeb 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -845,6 +845,7 @@ export class Controller { terminalReuseEnabled, defaultTerminalProfile, isNewUser, + welcomeViewCompleted, mcpResponsesCollapsed, terminalOutputLineLimit, } = await getAllExtensionState(this.context) @@ -899,6 +900,7 @@ export class Controller { terminalReuseEnabled, defaultTerminalProfile, isNewUser, + welcomeViewCompleted: welcomeViewCompleted as boolean, // Can be undefined but is set to either true or false by the migration that runs on extension launch in extension.ts mcpResponsesCollapsed, terminalOutputLineLimit, } diff --git a/src/core/controller/state/setWelcomeViewCompleted.ts b/src/core/controller/state/setWelcomeViewCompleted.ts new file mode 100644 index 00000000..a3bb52e1 --- /dev/null +++ b/src/core/controller/state/setWelcomeViewCompleted.ts @@ -0,0 +1,25 @@ +import type { BooleanRequest } from "../../../shared/proto/common" +import { Empty } from "../../../shared/proto/common" +import type { Controller } from "../index" +import { updateGlobalState } from "../../storage/state" + +/** + * Sets the welcomeViewCompleted flag to the specified boolean value + * @param controller The controller instance + * @param request The boolean request containing the value to set + * @returns Empty response + */ +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) + + await controller.postStateToWebview() + + console.log(`Welcome view completed set to: ${request.value}`) + return Empty.create({}) + } catch (error) { + console.error("Failed to set welcome view completed:", error) + throw error + } +} diff --git a/src/core/storage/state-keys.ts b/src/core/storage/state-keys.ts index 0835c673..31ee6cf0 100644 --- a/src/core/storage/state-keys.ts +++ b/src/core/storage/state-keys.ts @@ -71,6 +71,7 @@ export type GlobalStateKey = | "terminalReuseEnabled" | "defaultTerminalProfile" | "isNewUser" + | "welcomeViewCompleted" | "terminalOutputLineLimit" | "mcpRichDisplayEnabled" | "sapAiCoreTokenUrl" diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index 1c957ecb..327ac5b4 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 { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "./state" +import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState, getAllExtensionState } from "./state" import { GlobalStateKey } from "./state-keys" export async function migratePlanActGlobalToWorkspaceStorage(context: vscode.ExtensionContext) { @@ -145,3 +145,55 @@ export async function migrateModeFromWorkspaceStorageToControllerState(context: // Continue execution - migration failure shouldn't break extension startup } } + +export async function migrateWelcomeViewCompleted(context: vscode.ExtensionContext) { + try { + // Check if welcomeViewCompleted is already set + const welcomeViewCompleted = await getGlobalState(context, "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 config = extensionState.apiConfiguration + + // This is the original logic used for checking is the welcome view should be shown + // It was located in the ExtensionStateContextProvider + const hasKey = config + ? [ + config.apiKey, + config.openRouterApiKey, + config.awsRegion, + config.vertexProjectId, + config.openAiApiKey, + config.ollamaModelId, + config.lmStudioModelId, + config.liteLlmApiKey, + config.geminiApiKey, + config.openAiNativeApiKey, + config.deepSeekApiKey, + config.requestyApiKey, + config.togetherApiKey, + config.qwenApiKey, + config.doubaoApiKey, + config.mistralApiKey, + config.vsCodeLmModelSelector, + config.clineApiKey, + config.asksageApiKey, + config.xaiApiKey, + config.sambanovaApiKey, + config.sapAiCoreClientId, + ].some((key) => key !== undefined) + : false + + // Set welcomeViewCompleted based on whether user has keys + await updateGlobalState(context, "welcomeViewCompleted", hasKey) + + console.log(`Migration: Set welcomeViewCompleted to ${hasKey} based on existing API keys`) + } + } catch (error) { + console.error("Failed to migrate welcomeViewCompleted:", error) + // Continue execution - migration failure shouldn't break extension startup + } +} diff --git a/src/core/storage/state.ts b/src/core/storage/state.ts index c4b31c0a..7286abcd 100644 --- a/src/core/storage/state.ts +++ b/src/core/storage/state.ts @@ -55,6 +55,7 @@ export async function getWorkspaceState(context: vscode.ExtensionContext, key: s export async function getAllExtensionState(context: vscode.ExtensionContext) { const [ isNewUser, + welcomeViewCompleted, apiKey, openRouterApiKey, clineApiKey, @@ -128,6 +129,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { claudeCodePath, ] = 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, "clineApiKey") as Promise, @@ -388,6 +390,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) { sapAiCoreModelId, }, isNewUser: isNewUser ?? true, + welcomeViewCompleted, lastShownAnnouncementId, taskHistory, autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string diff --git a/src/extension.ts b/src/extension.ts index f74cd398..e3fbdb3f 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -26,6 +26,7 @@ import { migratePlanActGlobalToWorkspaceStorage, migrateCustomInstructionsToGlobalRules, migrateModeFromWorkspaceStorageToControllerState, + migrateWelcomeViewCompleted, } from "./core/storage/state-migrations" import { sendFocusChatInputEvent } from "./core/controller/ui/subscribeToFocusChatInput" @@ -68,6 +69,9 @@ export async function activate(context: vscode.ExtensionContext) { // Migrate mode from workspace storage to controller state (one-time cleanup) await migrateModeFromWorkspaceStorageToControllerState(context) + // Migrate welcomeViewCompleted setting based on existing API keys (one-time cleanup) + await migrateWelcomeViewCompleted(context) + // Clean up orphaned file context warnings (startup cleanup) await FileContextTracker.cleanupOrphanedWarnings(context) diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index faffa4e5..ed647fc0 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -60,6 +60,7 @@ export const DEFAULT_PLATFORM = "unknown" export interface ExtensionState { isNewUser: boolean + welcomeViewCompleted: boolean apiConfiguration?: ApiConfiguration autoApprovalSettings: AutoApprovalSettings browserSettings: BrowserSettings diff --git a/webview-ui/src/components/chat/ChatTextArea.tsx b/webview-ui/src/components/chat/ChatTextArea.tsx index a008aa93..7a97ba8c 100644 --- a/webview-ui/src/components/chat/ChatTextArea.tsx +++ b/webview-ui/src/components/chat/ChatTextArea.tsx @@ -1725,7 +1725,6 @@ const ChatTextArea = forwardRef( apiErrorMessage={undefined} modelIdErrorMessage={undefined} isPopup={true} - saveImmediately={true} // Ensure popup saves immediately /> )} diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 661e9222..1dee04a2 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -1,11 +1,8 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelsServiceClient } from "@/services/grpc-client" -import { ApiConfiguration } from "@shared/api" import { StringRequest } from "@shared/proto/common" -import { UpdateApiConfigurationRequest } from "@shared/proto/models" -import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" -import { memo, useCallback, useEffect, useMemo, useState } from "react" +import { useCallback, useEffect, useState } from "react" import { useInterval } from "react-use" import styled from "styled-components" import { OPENROUTER_MODEL_PICKER_Z_INDEX } from "./OpenRouterModelPicker" @@ -38,13 +35,13 @@ import { NebiusProvider } from "./providers/NebiusProvider" import { LiteLlmProvider } from "./providers/LiteLlmProvider" import { VSCodeLmProvider } from "./providers/VSCodeLmProvider" import { LMStudioProvider } from "./providers/LMStudioProvider" +import { useApiConfigurationHandlers } from "./utils/useApiConfigurationHandlers" interface ApiOptionsProps { showModelOptions: boolean apiErrorMessage?: string modelIdErrorMessage?: string isPopup?: boolean - saveImmediately?: boolean // Add prop to control immediate saving } // This is necessary to ensure dropdown opens downward, important for when this is used in popup @@ -71,52 +68,15 @@ declare module "vscode" { } } -const ApiOptions = ({ - showModelOptions, - apiErrorMessage, - modelIdErrorMessage, - isPopup, - saveImmediately = false, // Default to false -}: ApiOptionsProps) => { +const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, isPopup }: ApiOptionsProps) => { // Use full context state for immediate save payload - const extensionState = useExtensionState() - const { apiConfiguration, setApiConfiguration, uriScheme } = extensionState + const { apiConfiguration, uriScheme } = useExtensionState() + + const selectedProvider = apiConfiguration?.apiProvider + + const { handleFieldChange } = useApiConfigurationHandlers() + const [ollamaModels, setOllamaModels] = useState([]) - const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) - - const handleInputChange = (field: keyof ApiConfiguration) => (event: any) => { - const newValue = event.target.value - - // Update local state - setApiConfiguration({ - ...apiConfiguration, - [field]: newValue, - }) - - // If the field is the provider AND saveImmediately is true, save it immediately using the full context state - if (saveImmediately && field === "apiProvider") { - // Use apiConfiguration from the full extensionState context to send the most complete data - const currentFullApiConfig = extensionState.apiConfiguration - - // Convert to proto format and send via gRPC - const updatedConfig = { - ...currentFullApiConfig, - apiProvider: newValue, - } - const protoConfig = convertApiConfigurationToProto(updatedConfig) - ModelsServiceClient.updateApiConfigurationProto( - UpdateApiConfigurationRequest.create({ - apiConfiguration: protoConfig, - }), - ).catch((error) => { - console.error("Failed to update API configuration:", error) - }) - } - } - - const { selectedProvider, selectedModelId, selectedModelInfo } = useMemo(() => { - return normalizeApiConfiguration(apiConfiguration) - }, [apiConfiguration]) // Poll ollama/vscode-lm models const requestLocalModels = useCallback(async () => { @@ -161,7 +121,7 @@ const ApiOptions = ({ handleFieldChange("apiProvider", e.target.value)} style={{ minWidth: 130, position: "relative", @@ -196,241 +156,105 @@ const ApiOptions = ({ {apiConfiguration && selectedProvider === "cline" && ( - + )} {apiConfiguration && selectedProvider === "asksage" && ( - + )} {apiConfiguration && selectedProvider === "anthropic" && ( - + )} {apiConfiguration && selectedProvider === "claude-code" && ( - + )} {apiConfiguration && selectedProvider === "openai-native" && ( - + )} {apiConfiguration && selectedProvider === "qwen" && ( - + )} {apiConfiguration && selectedProvider === "doubao" && ( - + )} {apiConfiguration && selectedProvider === "mistral" && ( - + )} {apiConfiguration && selectedProvider === "openrouter" && ( - + )} {apiConfiguration && selectedProvider === "deepseek" && ( - + )} {apiConfiguration && selectedProvider === "together" && ( - + )} {apiConfiguration && selectedProvider === "openai" && ( - + )} {apiConfiguration && selectedProvider === "sambanova" && ( - + )} {apiConfiguration && selectedProvider === "bedrock" && ( - + )} {apiConfiguration && selectedProvider === "vertex" && ( - + )} {apiConfiguration && selectedProvider === "gemini" && ( - + )} {apiConfiguration && selectedProvider === "requesty" && ( - + )} {apiConfiguration && selectedProvider === "fireworks" && ( - + )} - {apiConfiguration && selectedProvider === "vscode-lm" && ( - - )} + {apiConfiguration && selectedProvider === "vscode-lm" && } {apiConfiguration && selectedProvider === "litellm" && ( - + )} {apiConfiguration && selectedProvider === "lmstudio" && ( - + )} {apiConfiguration && selectedProvider === "ollama" && ( - + )} {apiConfiguration && selectedProvider === "nebius" && ( - + )} {apiConfiguration && selectedProvider === "xai" && ( - + )} {apiConfiguration && selectedProvider === "cerebras" && ( - + )} {apiConfiguration && selectedProvider === "sapaicore" && ( - + )} {apiErrorMessage && ( @@ -457,4 +281,4 @@ const ApiOptions = ({ ) } -export default memo(ApiOptions) +export default ApiOptions diff --git a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx index cefebaf1..cbaaf183 100644 --- a/webview-ui/src/components/settings/OpenRouterModelPicker.tsx +++ b/webview-ui/src/components/settings/OpenRouterModelPicker.tsx @@ -1,7 +1,7 @@ import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import { useExtensionState } from "@/context/ExtensionStateContext" import { StateServiceClient } from "@/services/grpc-client" -import { openRouterDefaultModelId } from "@shared/api" +import { ApiConfiguration, openRouterDefaultModelId } from "@shared/api" import { StringRequest } from "@shared/proto/common" import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" import Fuse from "fuse.js" @@ -14,6 +14,7 @@ import { ModelInfoView } from "./common/ModelInfoView" import { normalizeApiConfiguration } from "./utils/providerUtils" import FeaturedModelCard from "./FeaturedModelCard" import ThinkingBudgetSlider from "./ThinkingBudgetSlider" +import { useApiConfigurationHandlers } from "./utils/useApiConfigurationHandlers" // Star icon for favorites const StarIcon = ({ isFavorite, onClick }: { isFavorite: boolean; onClick: (e: React.MouseEvent) => void }) => { @@ -60,7 +61,8 @@ const featuredModels = [ ] const OpenRouterModelPicker: React.FC = ({ isPopup }) => { - const { apiConfiguration, setApiConfiguration, openRouterModels, refreshOpenRouterModels } = useExtensionState() + const { handleFieldsChange } = useApiConfigurationHandlers() + const { apiConfiguration, openRouterModels, refreshOpenRouterModels } = useExtensionState() const [searchTerm, setSearchTerm] = useState(apiConfiguration?.openRouterModelId || openRouterDefaultModelId) const [isDropdownVisible, setIsDropdownVisible] = useState(false) const [selectedIndex, setSelectedIndex] = useState(-1) @@ -70,14 +72,13 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } const handleModelChange = (newModelId: string) => { // could be setting invalid model id/undefined info but validation will catch it - setApiConfiguration({ - ...apiConfiguration, - ...{ - openRouterModelId: newModelId, - openRouterModelInfo: openRouterModels[newModelId], - }, - }) + setSearchTerm(newModelId) + + handleFieldsChange({ + openRouterModelId: newModelId, + openRouterModelInfo: openRouterModels[newModelId], + }) } const { selectedModelId, selectedModelInfo } = useMemo(() => { @@ -306,9 +307,7 @@ const OpenRouterModelPicker: React.FC = ({ isPopup } {hasInfo ? ( <> - {showBudgetSlider && ( - - )} + {showBudgetSlider && } diff --git a/webview-ui/src/components/settings/PreferredLanguageSetting.tsx b/webview-ui/src/components/settings/PreferredLanguageSetting.tsx index 8f50bdd1..8bddcecc 100644 --- a/webview-ui/src/components/settings/PreferredLanguageSetting.tsx +++ b/webview-ui/src/components/settings/PreferredLanguageSetting.tsx @@ -1,13 +1,24 @@ import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import React from "react" -import { ChatSettings } from "@shared/ChatSettings" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { updateSetting } from "./utils/settingsHandlers" +import { convertChatSettingsToProtoChatSettings } from "@shared/proto-conversions/state/chat-settings-conversion" -interface PreferredLanguageSettingProps { - chatSettings: ChatSettings - setChatSettings: (settings: ChatSettings) => void -} +const PreferredLanguageSetting: React.FC = () => { + const { chatSettings } = useExtensionState() + + const handleLanguageChange = (newLanguage: string) => { + if (!chatSettings) return + + const updatedChatSettings = { + ...chatSettings, + preferredLanguage: newLanguage, + } + + const protoChatSettings = convertChatSettingsToProtoChatSettings(updatedChatSettings) + updateSetting("chatSettings", protoChatSettings) + } -const PreferredLanguageSetting: React.FC = ({ chatSettings, setChatSettings }) => { return (
- - Cancel - - handleSubmit(false)} disabled={!hasUnsavedChanges}> - Save - + {/* All settings now save immediately, so only show Done button */} + Done
@@ -763,39 +315,20 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { {/* API Configuration Tab */} {activeTab === "api-config" && ( )} {/* General Settings Tab */} - {activeTab === "general" && ( - - )} + {activeTab === "general" && } {/* Feature Settings Tab */} {activeTab === "features" && } {/* Browser Settings Tab */} - {activeTab === "browser" && ( - - )} + {activeTab === "browser" && } {/* Terminal Settings Tab */} {activeTab === "terminal" && } @@ -813,26 +346,8 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => { ) })()}
- - {/* Unsaved Changes Dialog */} - ) } -export default memo(SettingsView) +export default SettingsView diff --git a/webview-ui/src/components/settings/TerminalOutputLineLimitSlider.tsx b/webview-ui/src/components/settings/TerminalOutputLineLimitSlider.tsx index 4215409b..378462f3 100644 --- a/webview-ui/src/components/settings/TerminalOutputLineLimitSlider.tsx +++ b/webview-ui/src/components/settings/TerminalOutputLineLimitSlider.tsx @@ -1,12 +1,13 @@ import React from "react" import { useExtensionState } from "@/context/ExtensionStateContext" +import { updateSetting } from "./utils/settingsHandlers" const TerminalOutputLineLimitSlider: React.FC = () => { - const { terminalOutputLineLimit, setTerminalOutputLineLimit } = useExtensionState() + const { terminalOutputLineLimit } = useExtensionState() const handleSliderChange = (event: React.ChangeEvent) => { const value = parseInt(event.target.value, 10) - setTerminalOutputLineLimit(value) + updateSetting("terminalOutputLineLimit", value) } return ( diff --git a/webview-ui/src/components/settings/ThinkingBudgetSlider.tsx b/webview-ui/src/components/settings/ThinkingBudgetSlider.tsx index fc21a858..1fe8aeef 100644 --- a/webview-ui/src/components/settings/ThinkingBudgetSlider.tsx +++ b/webview-ui/src/components/settings/ThinkingBudgetSlider.tsx @@ -1,7 +1,9 @@ -import { memo, useCallback, useState } from "react" +import { memo, useCallback, useEffect, useMemo, useState } from "react" import { anthropicModels, ApiConfiguration, geminiDefaultModelId, geminiModels, ModelInfo } from "@shared/api" import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import styled from "styled-components" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "./utils/useApiConfigurationHandlers" // Constants const DEFAULT_MIN_VALID_TOKENS = 1024 @@ -80,26 +82,30 @@ const RangeInput = styled.input<{ $value: number; $min: number; $max: number }>` ` interface ThinkingBudgetSliderProps { - apiConfiguration: ApiConfiguration | undefined - setApiConfiguration: (apiConfiguration: ApiConfiguration) => void maxBudget?: number } -const ThinkingBudgetSlider = ({ apiConfiguration, setApiConfiguration, maxBudget }: ThinkingBudgetSliderProps) => { - const maxTokens = - apiConfiguration?.apiProvider === "gemini" - ? geminiModels[geminiDefaultModelId].maxTokens - : anthropicModels["claude-3-7-sonnet-20250219"].maxTokens +const ThinkingBudgetSlider = ({ maxBudget }: ThinkingBudgetSliderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + + const [isEnabled, setIsEnabled] = useState((apiConfiguration?.thinkingBudgetTokens || 0) > 0) + + const maxTokens = useMemo( + () => + apiConfiguration?.apiProvider === "gemini" + ? geminiModels[geminiDefaultModelId].maxTokens + : anthropicModels["claude-3-7-sonnet-20250219"].maxTokens, + [apiConfiguration?.apiProvider], + ) // use maxBudget prop if provided, otherwise apply the percentage cap to maxTokens - const maxSliderValue = (() => { + const maxSliderValue = useMemo(() => { if (maxBudget !== undefined) { return maxBudget } return Math.floor(maxTokens * MAX_PERCENTAGE) - })() - - const isEnabled = (apiConfiguration?.thinkingBudgetTokens || 0) > 0 + }, [maxBudget, maxTokens]) // Add local state for the slider value const [localValue, setLocalValue] = useState(apiConfiguration?.thinkingBudgetTokens || 0) @@ -110,20 +116,16 @@ const ThinkingBudgetSlider = ({ apiConfiguration, setApiConfiguration, maxBudget }, []) const handleSliderComplete = () => { - setApiConfiguration({ - ...apiConfiguration, - thinkingBudgetTokens: localValue, - }) + handleFieldChange("thinkingBudgetTokens", localValue) } const handleToggleChange = (event: any) => { const isChecked = (event.target as HTMLInputElement).checked const newValue = isChecked ? DEFAULT_MIN_VALID_TOKENS : 0 + setIsEnabled(isChecked) setLocalValue(newValue) - setApiConfiguration({ - ...apiConfiguration, - thinkingBudgetTokens: newValue, - }) + + handleFieldChange("thinkingBudgetTokens", newValue) } return ( diff --git a/webview-ui/src/components/settings/common/ApiKeyField.tsx b/webview-ui/src/components/settings/common/ApiKeyField.tsx index 29d0a695..d70ae231 100644 --- a/webview-ui/src/components/settings/common/ApiKeyField.tsx +++ b/webview-ui/src/components/settings/common/ApiKeyField.tsx @@ -1,11 +1,12 @@ +import { useDebouncedInput } from "../utils/useDebouncedInput" import { VSCodeTextField, VSCodeLink } from "@vscode/webview-ui-toolkit/react" /** * Props for the ApiKeyField component */ interface ApiKeyFieldProps { - value: string - onChange: (e: any) => void + initialValue: string + onChange: (value: string) => void providerName: string signupUrl?: string placeholder?: string @@ -16,34 +17,43 @@ interface ApiKeyFieldProps { * A reusable component for API key input fields with standard styling and help text for signing up for key */ export const ApiKeyField = ({ - value, + initialValue, onChange, providerName, signupUrl, placeholder = "Enter API Key...", helpText, -}: ApiKeyFieldProps) => ( -
- - {providerName} API Key - -

- {helpText || "This key is stored locally and only used to make API requests from this extension."} - {!value && signupUrl && ( - - You can get a{/^[aeiou]/i.test(providerName) ? "n" : ""} {providerName} API key by signing up here. - - )} -

-
-) +}: ApiKeyFieldProps) => { + const [localValue, setLocalValue] = useDebouncedInput(initialValue, onChange) + + return ( +
+ setLocalValue(e.target.value)} + placeholder={placeholder}> + {providerName} API Key + +

+ {helpText || "This key is stored locally and only used to make API requests from this extension."} + {!localValue && signupUrl && ( + + You can get a{/^[aeiou]/i.test(providerName) ? "n" : ""} {providerName} API key by signing up here. + + )} +

+
+ ) +} diff --git a/webview-ui/src/components/settings/common/BaseUrlField.tsx b/webview-ui/src/components/settings/common/BaseUrlField.tsx index 5383ff7a..dd854450 100644 --- a/webview-ui/src/components/settings/common/BaseUrlField.tsx +++ b/webview-ui/src/components/settings/common/BaseUrlField.tsx @@ -1,11 +1,12 @@ import { useState, useEffect } from "react" import { VSCodeCheckbox, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { useDebouncedInput } from "../utils/useDebouncedInput" /** * Props for the BaseUrlField component */ interface BaseUrlFieldProps { - value: string | undefined + initialValue: string | undefined onChange: (value: string) => void defaultValue?: string label?: string @@ -16,24 +17,19 @@ interface BaseUrlFieldProps { * A reusable component for toggling and entering custom base URLs */ export const BaseUrlField = ({ - value, + initialValue, onChange, - defaultValue = "", label = "Use custom base URL", placeholder = "Default: https://api.example.com", }: BaseUrlFieldProps) => { - const [isEnabled, setIsEnabled] = useState(!!value) - - // When value changes externally, update isEnabled state - useEffect(() => { - setIsEnabled(!!value) - }, [value]) + const [isEnabled, setIsEnabled] = useState(!!initialValue) + const [localValue, setLocalValue] = useDebouncedInput(initialValue || "", onChange) const handleToggle = (e: any) => { const checked = e.target.checked === true setIsEnabled(checked) if (!checked) { - onChange("") + setLocalValue("") } } @@ -45,10 +41,10 @@ export const BaseUrlField = ({ {isEnabled && ( onChange(e.target.value)} + onInput={(e: any) => setLocalValue(e.target.value)} placeholder={placeholder} /> )} diff --git a/webview-ui/src/components/settings/common/DebouncedTextField.tsx b/webview-ui/src/components/settings/common/DebouncedTextField.tsx new file mode 100644 index 00000000..34da925f --- /dev/null +++ b/webview-ui/src/components/settings/common/DebouncedTextField.tsx @@ -0,0 +1,33 @@ +import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { useDebouncedInput } from "../utils/useDebouncedInput" + +/** + * Props for the DebouncedTextField component + */ +interface DebouncedTextFieldProps { + // Custom props for debouncing functionality + initialValue: string + onChange: (value: string) => void + + // Common VSCodeTextField props + style?: React.CSSProperties + type?: "text" | "password" | "url" + placeholder?: string + id?: string + children?: React.ReactNode + disabled?: boolean +} + +/** + * A wrapper around VSCodeTextField that automatically handles debounced input + * to prevent excessive API calls while typing + */ +export const DebouncedTextField = ({ initialValue, onChange, children, ...otherProps }: DebouncedTextFieldProps) => { + const [localValue, setLocalValue] = useDebouncedInput(initialValue, onChange) + + return ( + setLocalValue(e.target.value)}> + {children} + + ) +} diff --git a/webview-ui/src/components/settings/providers/AnthropicProvider.tsx b/webview-ui/src/components/settings/providers/AnthropicProvider.tsx index 6dda457b..19f1d782 100644 --- a/webview-ui/src/components/settings/providers/AnthropicProvider.tsx +++ b/webview-ui/src/components/settings/providers/AnthropicProvider.tsx @@ -1,10 +1,12 @@ -import { ApiConfiguration, anthropicModels } from "@shared/api" +import { anthropicModels } from "@shared/api" import { ApiKeyField } from "../common/ApiKeyField" import { BaseUrlField } from "../common/BaseUrlField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" // Anthropic models that support thinking/reasoning mode const SUPPORTED_THINKING_MODELS = ["claude-3-7-sonnet-20250219", "claude-sonnet-4-20250514", "claude-opus-4-20250514"] @@ -13,43 +15,32 @@ const SUPPORTED_THINKING_MODELS = ["claude-3-7-sonnet-20250219", "claude-sonnet- * Props for the AnthropicProvider component */ interface AnthropicProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration?: (config: ApiConfiguration) => void } /** * The Anthropic provider configuration component */ -export const AnthropicProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: AnthropicProviderProps) => { +export const AnthropicProvider = ({ showModelOptions, isPopup }: AnthropicProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) - // Create a wrapper for handling field changes more directly - const handleFieldChange = (field: keyof ApiConfiguration) => (value: string) => { - handleInputChange(field)({ target: { value } }) - } - return (
handleFieldChange("apiKey", value)} providerName="Anthropic" signupUrl="https://console.anthropic.com/settings/keys" /> handleFieldChange("anthropicBaseUrl", value)} placeholder="Default: https://api.anthropic.com" label="Use custom base URL" /> @@ -59,16 +50,12 @@ export const AnthropicProvider = ({ handleFieldChange("apiModelId", e.target.value)} label="Model" /> - {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && setApiConfiguration && ( - + {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( + )} diff --git a/webview-ui/src/components/settings/providers/AskSageProvider.tsx b/webview-ui/src/components/settings/providers/AskSageProvider.tsx index d03d62f3..ce74829e 100644 --- a/webview-ui/src/components/settings/providers/AskSageProvider.tsx +++ b/webview-ui/src/components/settings/providers/AskSageProvider.tsx @@ -1,16 +1,16 @@ import { ApiConfiguration, askSageModels, askSageDefaultURL } from "@shared/api" -import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" import { ApiKeyField } from "../common/ApiKeyField" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the AskSageProvider component */ interface AskSageProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -18,34 +18,37 @@ interface AskSageProviderProps { /** * The AskSage provider configuration component */ -export const AskSageProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: AskSageProviderProps) => { +export const AskSageProvider = ({ showModelOptions, isPopup }: AskSageProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("asksageApiKey", value)} providerName="AskSage" helpText="This key is stored locally and only used to make API requests from this extension." /> - handleFieldChange("asksageApiUrl", value)} style={{ width: "100%" }} type="url" - onInput={handleInputChange("asksageApiUrl")} placeholder="Enter AskSage API URL..."> AskSage API URL - + {showModelOptions && ( <> handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/BedrockProvider.tsx b/webview-ui/src/components/settings/providers/BedrockProvider.tsx index 01c3be6a..7925e4e6 100644 --- a/webview-ui/src/components/settings/providers/BedrockProvider.tsx +++ b/webview-ui/src/components/settings/providers/BedrockProvider.tsx @@ -1,36 +1,26 @@ -import { ApiConfiguration, bedrockDefaultModelId, bedrockModels } from "@shared/api" -import { - VSCodeCheckbox, - VSCodeDropdown, - VSCodeOption, - VSCodeRadio, - VSCodeRadioGroup, - VSCodeTextField, -} from "@vscode/webview-ui-toolkit/react" +import { bedrockDefaultModelId, bedrockModels } from "@shared/api" +import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeRadio, VSCodeRadioGroup } from "@vscode/webview-ui-toolkit/react" import { useState } from "react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelInfoView } from "../common/ModelInfoView" import { DropdownContainer } from "../common/ModelSelector" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" // Z-index constants for proper dropdown layering const DROPDOWN_Z_INDEX = 1000 interface BedrockProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration: (config: ApiConfiguration) => void } -export const BedrockProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: BedrockProviderProps) => { +export const BedrockProvider = ({ showModelOptions, isPopup }: BedrockProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange, handleFieldsChange } = useApiConfigurationHandlers() + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) const [awsEndpointSelected, setAwsEndpointSelected] = useState(!!apiConfiguration?.awsBedrockEndpoint) @@ -46,49 +36,47 @@ export const BedrockProvider = ({ onChange={(e) => { const value = (e.target as HTMLInputElement)?.value const useProfile = value === "profile" - setApiConfiguration({ - ...apiConfiguration, - awsUseProfile: useProfile, - }) + + handleFieldChange("awsUseProfile", useProfile) }}> AWS Credentials AWS Profile {apiConfiguration?.awsUseProfile ? ( - handleFieldChange("awsProfile", value)} style={{ width: "100%" }} - onInput={handleInputChange("awsProfile")} placeholder="Enter profile name (default if empty)"> AWS Profile Name - + ) : ( <> - handleFieldChange("awsAccessKey", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("awsAccessKey")} placeholder="Enter Access Key..."> AWS Access Key - - + handleFieldChange("awsSecretKey", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("awsSecretKey")} placeholder="Enter Secret Key..."> AWS Secret Key - - + handleFieldChange("awsSessionToken", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("awsSessionToken")} placeholder="Enter Session Token..."> AWS Session Token - + )} @@ -100,7 +88,7 @@ export const BedrockProvider = ({ id="aws-region-dropdown" value={apiConfiguration?.awsRegion || ""} style={{ width: "100%" }} - onChange={handleInputChange("awsRegion")}> + onChange={(e: any) => handleFieldChange("awsRegion", e.target.value)}> Select a region... {/* The user will have to choose a region that supports the model they use, but this shouldn't be a problem since they'd have to request access for it in that region in the first place. */} us-east-1 @@ -139,21 +127,18 @@ export const BedrockProvider = ({ const isChecked = e.target.checked === true setAwsEndpointSelected(isChecked) if (!isChecked) { - setApiConfiguration({ - ...apiConfiguration, - awsBedrockEndpoint: "", - }) + handleFieldChange("awsBedrockEndpoint", "") } }}> Use custom VPC endpoint {awsEndpointSelected && ( - handleFieldChange("awsBedrockEndpoint", value)} style={{ width: "100%", marginTop: 3, marginBottom: 5 }} type="url" - onInput={handleInputChange("awsBedrockEndpoint")} placeholder="Enter VPC Endpoint URL (optional)" /> )} @@ -162,10 +147,8 @@ export const BedrockProvider = ({ checked={apiConfiguration?.awsUseCrossRegionInference || false} onChange={(e: any) => { const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - awsUseCrossRegionInference: isChecked, - }) + + handleFieldChange("awsUseCrossRegionInference", isChecked) }}> Use cross-region inference @@ -176,10 +159,7 @@ export const BedrockProvider = ({ checked={apiConfiguration?.awsBedrockUsePromptCache || false} onChange={(e: any) => { const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - awsBedrockUsePromptCache: isChecked, - }) + handleFieldChange("awsBedrockUsePromptCache", isChecked) }}> Use prompt caching @@ -218,8 +198,8 @@ export const BedrockProvider = ({ value={apiConfiguration?.awsBedrockCustomSelected ? "custom" : selectedModelId} onChange={(e: any) => { const isCustom = e.target.value === "custom" - setApiConfiguration({ - ...apiConfiguration, + + handleFieldsChange({ apiModelId: isCustom ? "" : e.target.value, awsBedrockCustomSelected: isCustom, awsBedrockCustomModelBaseId: bedrockDefaultModelId, @@ -254,16 +234,14 @@ export const BedrockProvider = ({ Select "Custom" when using the Application Inference Profile in Bedrock. Enter the Application Inference Profile ARN in the Model ID field.

- - handleFieldChange("apiModelId", value)} style={{ width: "100%", marginTop: 3 }} - onInput={handleInputChange("apiModelId")} - placeholder="Enter custom model ID..." - /> + placeholder="Enter custom model ID..."> + Model ID + @@ -271,7 +249,7 @@ export const BedrockProvider = ({ handleFieldChange("awsBedrockCustomModelBaseId", e.target.value)} style={{ width: "100%" }}> Select a model... {Object.keys(bedrockModels).map((modelId) => ( @@ -300,7 +278,7 @@ export const BedrockProvider = ({ apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-sonnet-4-20250514-v1:0") || (apiConfiguration?.awsBedrockCustomSelected && apiConfiguration?.awsBedrockCustomModelBaseId === "anthropic.claude-opus-4-20250514-v1:0")) && ( - + )} diff --git a/webview-ui/src/components/settings/providers/CerebrasProvider.tsx b/webview-ui/src/components/settings/providers/CerebrasProvider.tsx index c5f07721..4511fe42 100644 --- a/webview-ui/src/components/settings/providers/CerebrasProvider.tsx +++ b/webview-ui/src/components/settings/providers/CerebrasProvider.tsx @@ -1,15 +1,15 @@ -import { ApiConfiguration, cerebrasModels } from "@shared/api" +import { cerebrasModels } from "@shared/api" import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the CerebrasProvider component */ interface CerebrasProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface CerebrasProviderProps { /** * The Cerebras provider configuration component */ -export const CerebrasProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: CerebrasProviderProps) => { +export const CerebrasProvider = ({ showModelOptions, isPopup }: CerebrasProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("cerebrasApiKey", value)} providerName="Cerebras" signupUrl="https://cloud.cerebras.ai/" /> @@ -35,7 +38,7 @@ export const CerebrasProvider = ({ apiConfiguration, handleInputChange, showMode handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx index 85b045cb..2928d326 100644 --- a/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx +++ b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx @@ -1,15 +1,15 @@ -import { ApiConfiguration, claudeCodeModels } from "@shared/api" -import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { claudeCodeModels } from "@shared/api" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the ClaudeCodeProvider component */ interface ClaudeCodeProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,25 +17,23 @@ interface ClaudeCodeProviderProps { /** * The Claude Code provider configuration component */ -export const ClaudeCodeProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, -}: ClaudeCodeProviderProps) => { +export const ClaudeCodeProvider = ({ showModelOptions, isPopup }: ClaudeCodeProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
- handleFieldChange("claudeCodePath", value)} style={{ width: "100%", marginTop: 3 }} type="text" - onInput={handleInputChange("claudeCodePath")} placeholder="Default: claude"> Claude Code CLI Path - +

handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/ClineProvider.tsx b/webview-ui/src/components/settings/providers/ClineProvider.tsx index 16accdfe..b29ac7fb 100644 --- a/webview-ui/src/components/settings/providers/ClineProvider.tsx +++ b/webview-ui/src/components/settings/providers/ClineProvider.tsx @@ -4,13 +4,13 @@ import { useState } from "react" import { ClineAccountInfoCard } from "../ClineAccountInfoCard" import OpenRouterModelPicker, { OPENROUTER_MODEL_PICKER_Z_INDEX } from "../OpenRouterModelPicker" import { DropdownContainer } from "../common/ModelSelector" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the ClineProvider component */ interface ClineProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -18,13 +18,11 @@ interface ClineProviderProps { /** * The Cline provider configuration component */ -export const ClineProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: ClineProviderProps) => { - const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) +export const ClineProvider = ({ showModelOptions, isPopup }: ClineProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() - // Create a wrapper for handling field changes more directly - const handleFieldChange = (field: keyof ApiConfiguration) => (value: any) => { - handleInputChange(field)({ target: { value } }) - } + const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) return (

@@ -43,7 +41,7 @@ export const ClineProvider = ({ apiConfiguration, handleInputChange, showModelOp const isChecked = e.target.checked === true setProviderSortingSelected(isChecked) if (!isChecked) { - handleFieldChange("openRouterProviderSorting")("") + handleFieldChange("openRouterProviderSorting", "") } }}> Sort underlying provider routing @@ -56,7 +54,7 @@ export const ClineProvider = ({ apiConfiguration, handleInputChange, showModelOp style={{ width: "100%", marginTop: 3 }} value={apiConfiguration?.openRouterProviderSorting} onChange={(e: any) => { - handleFieldChange("openRouterProviderSorting")(e.target.value) + handleFieldChange("openRouterProviderSorting", e.target.value) }}> Default Price diff --git a/webview-ui/src/components/settings/providers/DeepSeekProvider.tsx b/webview-ui/src/components/settings/providers/DeepSeekProvider.tsx index cf56810a..81da326a 100644 --- a/webview-ui/src/components/settings/providers/DeepSeekProvider.tsx +++ b/webview-ui/src/components/settings/providers/DeepSeekProvider.tsx @@ -3,13 +3,13 @@ import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the DeepSeekProvider component */ interface DeepSeekProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface DeepSeekProviderProps { /** * The DeepSeek provider configuration component */ -export const DeepSeekProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: DeepSeekProviderProps) => { +export const DeepSeekProvider = ({ showModelOptions, isPopup }: DeepSeekProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("deepSeekApiKey", value)} providerName="DeepSeek" signupUrl="https://www.deepseek.com/" /> @@ -35,7 +38,7 @@ export const DeepSeekProvider = ({ apiConfiguration, handleInputChange, showMode handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/DoubaoProvider.tsx b/webview-ui/src/components/settings/providers/DoubaoProvider.tsx index 76e3d8a8..f6a32126 100644 --- a/webview-ui/src/components/settings/providers/DoubaoProvider.tsx +++ b/webview-ui/src/components/settings/providers/DoubaoProvider.tsx @@ -3,13 +3,13 @@ import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the DoubaoProvider component */ interface DoubaoProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface DoubaoProviderProps { /** * The ByteDance Doubao provider configuration component */ -export const DoubaoProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: DoubaoProviderProps) => { +export const DoubaoProvider = ({ showModelOptions, isPopup }: DoubaoProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("doubaoApiKey", value)} providerName="Doubao" signupUrl="https://console.volcengine.com/home" /> @@ -35,7 +38,7 @@ export const DoubaoProvider = ({ apiConfiguration, handleInputChange, showModelO handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/FireworksProvider.tsx b/webview-ui/src/components/settings/providers/FireworksProvider.tsx index 27fc0412..3e3ee33f 100644 --- a/webview-ui/src/components/settings/providers/FireworksProvider.tsx +++ b/webview-ui/src/components/settings/providers/FireworksProvider.tsx @@ -1,13 +1,13 @@ -import { ApiConfiguration } from "@shared/api" -import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" import { ApiKeyField } from "../common/ApiKeyField" +import { DebouncedTextField } from "../common/DebouncedTextField" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { ApiConfiguration } from "@shared/api" /** * Props for the FireworksProvider component */ interface FireworksProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -15,10 +15,12 @@ interface FireworksProviderProps { /** * The Fireworks provider configuration component */ -export const FireworksProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: FireworksProviderProps) => { +export const FireworksProvider = ({ showModelOptions, isPopup }: FireworksProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Handler for number input fields with validation - const handleNumberInputChange = (field: keyof ApiConfiguration) => (e: any) => { - const value = (e.target as HTMLInputElement).value + const handleNumberInputChange = (field: keyof ApiConfiguration, value: string) => { if (!value) { return } @@ -26,31 +28,27 @@ export const FireworksProvider = ({ apiConfiguration, handleInputChange, showMod if (isNaN(num)) { return } - handleInputChange(field)({ - target: { - value: num, - }, - }) + handleFieldChange(field, num) } return (
handleFieldChange("fireworksApiKey", value)} providerName="Fireworks" signupUrl="https://fireworks.ai/settings/users/api-keys" /> {showModelOptions && ( <> - handleFieldChange("fireworksModelId", value)} style={{ width: "100%" }} - onInput={handleInputChange("fireworksModelId")} placeholder={"Enter Model ID..."}> Model ID - +

- handleNumberInputChange("fireworksModelMaxCompletionTokens", value)} style={{ width: "100%", marginBottom: 8 }} - onInput={handleNumberInputChange("fireworksModelMaxCompletionTokens")} placeholder={"2000"}> Max Completion Tokens - - + handleNumberInputChange("fireworksModelMaxTokens", value)} style={{ width: "100%", marginBottom: 8 }} - onInput={handleNumberInputChange("fireworksModelMaxTokens")} placeholder={"4000"}> Max Context Tokens - + )}
diff --git a/webview-ui/src/components/settings/providers/GeminiProvider.tsx b/webview-ui/src/components/settings/providers/GeminiProvider.tsx index 9889ed9a..846c4ecd 100644 --- a/webview-ui/src/components/settings/providers/GeminiProvider.tsx +++ b/webview-ui/src/components/settings/providers/GeminiProvider.tsx @@ -1,10 +1,12 @@ -import { ApiConfiguration, geminiModels } from "@shared/api" +import { geminiModels } from "@shared/api" import { ApiKeyField } from "../common/ApiKeyField" import { BaseUrlField } from "../common/BaseUrlField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" // Gemini models that support thinking/reasoning mode const SUPPORTED_THINKING_MODELS = ["gemini-2.5-pro", "gemini-2.5-flash"] @@ -13,43 +15,32 @@ const SUPPORTED_THINKING_MODELS = ["gemini-2.5-pro", "gemini-2.5-flash"] * Props for the GeminiProvider component */ interface GeminiProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration?: (config: ApiConfiguration) => void } /** * The Gemini provider configuration component */ -export const GeminiProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: GeminiProviderProps) => { +export const GeminiProvider = ({ showModelOptions, isPopup }: GeminiProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) - // Create a wrapper for handling field changes more directly - const handleFieldChange = (field: keyof ApiConfiguration) => (value: string) => { - handleInputChange(field)({ target: { value } }) - } - return (
handleFieldChange("geminiApiKey", value)} providerName="Gemini" signupUrl="https://aistudio.google.com/apikey" /> handleFieldChange("geminiBaseUrl", value)} placeholder="Default: https://generativelanguage.googleapis.com" label="Use custom base URL" /> @@ -59,16 +50,12 @@ export const GeminiProvider = ({ handleFieldChange("apiModelId", e.target.value)} label="Model" /> - {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && setApiConfiguration && ( - + {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( + )} diff --git a/webview-ui/src/components/settings/providers/LMStudioProvider.tsx b/webview-ui/src/components/settings/providers/LMStudioProvider.tsx index 2b3957d4..a5500d1d 100644 --- a/webview-ui/src/components/settings/providers/LMStudioProvider.tsx +++ b/webview-ui/src/components/settings/providers/LMStudioProvider.tsx @@ -1,17 +1,17 @@ -import { ApiConfiguration } from "@shared/api" -import { VSCodeTextField, VSCodeRadioGroup, VSCodeRadio, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { VSCodeRadioGroup, VSCodeRadio, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { useState, useCallback, useEffect } from "react" import { useInterval } from "react-use" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelsServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/common" import { BaseUrlField } from "../common/BaseUrlField" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the LMStudioProvider component */ interface LMStudioProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -19,7 +19,10 @@ interface LMStudioProviderProps { /** * The LM Studio provider configuration component */ -export const LMStudioProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: LMStudioProviderProps) => { +export const LMStudioProvider = ({ showModelOptions, isPopup }: LMStudioProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + const [lmStudioModels, setLmStudioModels] = useState([]) // Poll LM Studio models @@ -48,19 +51,19 @@ export const LMStudioProvider = ({ apiConfiguration, handleInputChange, showMode return (
handleInputChange("lmStudioBaseUrl")({ target: { value } })} + initialValue={apiConfiguration?.lmStudioBaseUrl} + onChange={(value) => handleFieldChange("lmStudioBaseUrl", value)} placeholder="Default: http://localhost:1234" label="Use custom base URL" /> - handleFieldChange("lmStudioModelId", value)} style={{ width: "100%" }} - onInput={handleInputChange("lmStudioModelId")} placeholder={"e.g. meta-llama-3.1-8b-instruct"}> Model ID - + {lmStudioModels.length > 0 && ( {lmStudioModels.map((model) => ( diff --git a/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx index bfa1e468..d54bb600 100644 --- a/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx +++ b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx @@ -1,32 +1,29 @@ import { useState } from "react" -import { ApiConfiguration, liteLlmModelInfoSaneDefaults } from "@shared/api" -import { VSCodeTextField, VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { liteLlmModelInfoSaneDefaults } from "@shared/api" +import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" import { normalizeApiConfiguration } from "../utils/providerUtils" import { ModelInfoView } from "../common/ModelInfoView" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the LiteLlmProvider component */ interface LiteLlmProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration: (config: ApiConfiguration) => void } /** * The LiteLLM provider configuration component */ -export const LiteLlmProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: LiteLlmProviderProps) => { +export const LiteLlmProvider = ({ showModelOptions, isPopup }: LiteLlmProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) @@ -35,29 +32,29 @@ export const LiteLlmProvider = ({ return (
- handleFieldChange("liteLlmBaseUrl", value)} style={{ width: "100%" }} type="url" - onInput={handleInputChange("liteLlmBaseUrl")} placeholder={"Default: http://localhost:4000"}> Base URL (optional) - - + handleFieldChange("liteLlmApiKey", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("liteLlmApiKey")} placeholder="Default: noop"> API Key - - + handleFieldChange("liteLlmModelId", value)} style={{ width: "100%" }} - onInput={handleInputChange("liteLlmModelId")} placeholder={"e.g. anthropic/claude-sonnet-4-20250514"}> Model ID - +
{selectedModelInfo.supportsPromptCache && ( @@ -66,10 +63,8 @@ export const LiteLlmProvider = ({ checked={apiConfiguration?.liteLlmUsePromptCache || false} onChange={(e: any) => { const isChecked = e.target.checked === true - setApiConfiguration({ - ...apiConfiguration, - liteLlmUsePromptCache: isChecked, - }) + + handleFieldChange("liteLlmUsePromptCache", isChecked) }} style={{ fontWeight: 500, color: "var(--vscode-charts-green)" }}> Use prompt caching (GA) @@ -82,7 +77,7 @@ export const LiteLlmProvider = ({
<> - +

Supports Images

- { + onChange={(value) => { const modelInfo = apiConfiguration?.liteLlmModelInfo ? apiConfiguration.liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } - modelInfo.contextWindow = Number(input.target.value) - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) + modelInfo.contextWindow = Number(value) + + handleFieldChange("liteLlmModelInfo", modelInfo) }}> Context Window Size - - + { + onChange={(value) => { const modelInfo = apiConfiguration?.liteLlmModelInfo ? apiConfiguration.liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } - modelInfo.maxTokens = input.target.value - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) + modelInfo.maxTokens = Number(value) + + handleFieldChange("liteLlmModelInfo", modelInfo) }}> Max Output Tokens - +
- { + onChange={(value) => { const modelInfo = apiConfiguration?.liteLlmModelInfo ? apiConfiguration.liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } // Check if the input ends with a decimal point or has trailing zeros after decimal - const value = input.target.value const shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0")) modelInfo.temperature = - value === "" - ? liteLlmModelInfoSaneDefaults.temperature - : shouldPreserveFormat - ? value // Keep as string to preserve decimal format - : parseFloat(value) + value === "" ? liteLlmModelInfoSaneDefaults.temperature : parseFloat(value) - setApiConfiguration({ - ...apiConfiguration, - liteLlmModelInfo: modelInfo, - }) + handleFieldChange("liteLlmModelInfo", modelInfo) }}> Temperature - +
)} diff --git a/webview-ui/src/components/settings/providers/MistralProvider.tsx b/webview-ui/src/components/settings/providers/MistralProvider.tsx index d0141e10..cee486eb 100644 --- a/webview-ui/src/components/settings/providers/MistralProvider.tsx +++ b/webview-ui/src/components/settings/providers/MistralProvider.tsx @@ -3,13 +3,13 @@ import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the MistralProvider component */ interface MistralProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface MistralProviderProps { /** * The Mistral provider configuration component */ -export const MistralProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: MistralProviderProps) => { +export const MistralProvider = ({ showModelOptions, isPopup }: MistralProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("mistralApiKey", value)} providerName="Mistral" signupUrl="https://console.mistral.ai/codestral" /> @@ -35,7 +38,7 @@ export const MistralProvider = ({ apiConfiguration, handleInputChange, showModel handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/NebiusProvider.tsx b/webview-ui/src/components/settings/providers/NebiusProvider.tsx index ca22ad8d..28ad3cd6 100644 --- a/webview-ui/src/components/settings/providers/NebiusProvider.tsx +++ b/webview-ui/src/components/settings/providers/NebiusProvider.tsx @@ -1,15 +1,15 @@ -import { ApiConfiguration, nebiusModels } from "@shared/api" +import { nebiusModels } from "@shared/api" import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the NebiusProvider component */ interface NebiusProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface NebiusProviderProps { /** * The Nebius AI Studio provider configuration component */ -export const NebiusProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: NebiusProviderProps) => { +export const NebiusProvider = ({ showModelOptions, isPopup }: NebiusProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("nebiusApiKey", value)} providerName="Nebius" signupUrl="https://studio.nebius.com/settings/api-keys" helpText="This key is stored locally and only used to make API requests from this extension. (Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected.)" @@ -36,7 +39,7 @@ export const NebiusProvider = ({ apiConfiguration, handleInputChange, showModelO handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/OllamaProvider.tsx b/webview-ui/src/components/settings/providers/OllamaProvider.tsx index 165efea0..524dc0ef 100644 --- a/webview-ui/src/components/settings/providers/OllamaProvider.tsx +++ b/webview-ui/src/components/settings/providers/OllamaProvider.tsx @@ -1,33 +1,29 @@ -import { ApiConfiguration } from "@shared/api" -import { VSCodeTextField, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { useState, useCallback, useEffect } from "react" import { useInterval } from "react-use" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelsServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/common" import OllamaModelPicker from "../OllamaModelPicker" import { BaseUrlField } from "../common/BaseUrlField" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the OllamaProvider component */ interface OllamaProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration: (config: ApiConfiguration) => void } /** * The Ollama provider configuration component */ -export const OllamaProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: OllamaProviderProps) => { +export const OllamaProvider = ({ showModelOptions, isPopup }: OllamaProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + const [ollamaModels, setOllamaModels] = useState([]) // Poll ollama models @@ -56,8 +52,8 @@ export const OllamaProvider = ({ return (
handleInputChange("ollamaBaseUrl")({ target: { value } })} + initialValue={apiConfiguration?.ollamaBaseUrl} + onChange={(value) => handleFieldChange("ollamaBaseUrl", value)} placeholder="Default: http://localhost:11434" label="Use custom base URL" /> @@ -70,10 +66,7 @@ export const OllamaProvider = ({ ollamaModels={ollamaModels} selectedModelId={apiConfiguration?.ollamaModelId || ""} onModelChange={(modelId) => { - setApiConfiguration({ - ...apiConfiguration, - ollamaModelId: modelId, - }) + handleFieldChange("ollamaModelId", modelId) }} placeholder={ollamaModels.length > 0 ? "Search and select a model..." : "e.g. llama3.1"} /> @@ -92,33 +85,29 @@ export const OllamaProvider = ({

)} - handleFieldChange("ollamaApiOptionsCtxNum", value)} style={{ width: "100%" }} - onInput={handleInputChange("ollamaApiOptionsCtxNum")} placeholder={"e.g. 32768"}> Model Context Window - + {showModelOptions && ( <> - { - const value = e.target.value + { // Convert to number, with validation const numValue = parseInt(value, 10) if (!isNaN(numValue) && numValue > 0) { - setApiConfiguration({ - ...apiConfiguration, - requestTimeoutMs: numValue, - }) + handleFieldChange("requestTimeoutMs", numValue) } }} + style={{ width: "100%" }} placeholder="Default: 30000 (30 seconds)"> Request Timeout (ms) - +

Maximum time in milliseconds to wait for API responses before timing out.

diff --git a/webview-ui/src/components/settings/providers/OpenAICompatible.tsx b/webview-ui/src/components/settings/providers/OpenAICompatible.tsx index 55c125b4..7cd60a70 100644 --- a/webview-ui/src/components/settings/providers/OpenAICompatible.tsx +++ b/webview-ui/src/components/settings/providers/OpenAICompatible.tsx @@ -2,19 +2,20 @@ import { ApiConfiguration, azureOpenAiDefaultApiVersion, openAiModelInfoSaneDefa import { OpenAiModelsRequest } from "@shared/proto/models" import { ModelsServiceClient } from "@/services/grpc-client" import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" -import { VSCodeTextField, VSCodeButton, VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" +import { VSCodeButton, VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import { useCallback, useEffect, useRef, useState } from "react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelInfoView } from "../common/ModelInfoView" import { ApiKeyField } from "../common/ApiKeyField" import { BaseUrlField } from "../common/BaseUrlField" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the OpenAICompatibleProvider component */ interface OpenAICompatibleProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -22,12 +23,10 @@ interface OpenAICompatibleProviderProps { /** * The OpenAI Compatible provider configuration component */ -export const OpenAICompatibleProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, -}: OpenAICompatibleProviderProps) => { +export const OpenAICompatibleProvider = ({ showModelOptions, isPopup }: OpenAICompatibleProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + const [modelConfigurationSelected, setModelConfigurationSelected] = useState(false) // Get the normalized configuration @@ -65,38 +64,34 @@ export const OpenAICompatibleProvider = ({ return (
- { + handleFieldChange("openAiBaseUrl", value) + debouncedRefreshOpenAiModels(value, apiConfiguration?.openAiApiKey) + }} style={{ width: "100%", marginBottom: 10 }} type="url" - onInput={(e: any) => { - const baseUrl = e.target.value - handleInputChange("openAiBaseUrl")({ target: { value: baseUrl } }) - - debouncedRefreshOpenAiModels(baseUrl, apiConfiguration?.openAiApiKey) - }} placeholder={"Enter base URL..."}> Base URL - + { - const apiKey = e.target.value - handleInputChange("openAiApiKey")({ target: { value: apiKey } }) - - debouncedRefreshOpenAiModels(apiConfiguration?.openAiBaseUrl, apiKey) + initialValue={apiConfiguration?.openAiApiKey || ""} + onChange={(value) => { + handleFieldChange("openAiApiKey", value) + debouncedRefreshOpenAiModels(apiConfiguration?.openAiBaseUrl, value) }} providerName="OpenAI Compatible" /> - handleFieldChange("openAiModelId", value)} style={{ width: "100%", marginBottom: 10 }} - onInput={handleInputChange("openAiModelId")} placeholder={"Enter Model ID..."}> Model ID - + {/* OpenAI Compatible Custom Headers */} {(() => { @@ -111,11 +106,7 @@ export const OpenAICompatibleProvider = ({ const headerCount = Object.keys(currentHeaders).length const newKey = `header${headerCount + 1}` currentHeaders[newKey] = "" - handleInputChange("openAiHeaders")({ - target: { - value: currentHeaders, - }, - }) + handleFieldChange("openAiHeaders", currentHeaders) }}> Add Header @@ -123,38 +114,29 @@ export const OpenAICompatibleProvider = ({
{headerEntries.map(([key, value], index) => (
- { + onChange={(newValue) => { const currentHeaders = apiConfiguration?.openAiHeaders ?? {} - const newValue = e.target.value if (newValue && newValue !== key) { const { [key]: _, ...rest } = currentHeaders - handleInputChange("openAiHeaders")({ - target: { - value: { - ...rest, - [newValue]: value, - }, - }, + handleFieldChange("openAiHeaders", { + ...rest, + [newValue]: value, }) } }} /> - { - handleInputChange("openAiHeaders")({ - target: { - value: { - ...(apiConfiguration?.openAiHeaders ?? {}), - [key]: e.target.value, - }, - }, + onChange={(newValue) => { + handleFieldChange("openAiHeaders", { + ...(apiConfiguration?.openAiHeaders ?? {}), + [key]: newValue, }) }} /> @@ -162,11 +144,7 @@ export const OpenAICompatibleProvider = ({ appearance="secondary" onClick={() => { const { [key]: _, ...rest } = apiConfiguration?.openAiHeaders ?? {} - handleInputChange("openAiHeaders")({ - target: { - value: rest, - }, - }) + handleFieldChange("openAiHeaders", rest) }}> Remove @@ -178,8 +156,8 @@ export const OpenAICompatibleProvider = ({ })()} handleInputChange("azureApiVersion")({ target: { value } })} + initialValue={apiConfiguration?.azureApiVersion} + onChange={(value) => handleFieldChange("azureApiVersion", value)} label="Set Azure API version" placeholder={`Default: ${azureOpenAiDefaultApiVersion}`} /> @@ -217,9 +195,7 @@ export const OpenAICompatibleProvider = ({ ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.supportsImages = isChecked - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + handleFieldChange("openAiModelInfo", modelInfo) }}> Supports Images @@ -232,9 +208,7 @@ export const OpenAICompatibleProvider = ({ ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.supportsImages = isChecked - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + handleFieldChange("openAiModelInfo", modelInfo) }}> Supports browser use @@ -248,122 +222,108 @@ export const OpenAICompatibleProvider = ({ : { ...openAiModelInfoSaneDefaults } modelInfo = { ...modelInfo, isR1FormatRequired: isChecked } - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + handleFieldChange("openAiModelInfo", modelInfo) }}> Enable R1 messages format
- { + onChange={(value) => { const modelInfo = apiConfiguration?.openAiModelInfo ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } - modelInfo.contextWindow = Number(input.target.value) - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + modelInfo.contextWindow = Number(value) + handleFieldChange("openAiModelInfo", modelInfo) }}> Context Window Size - + - { + onChange={(value) => { const modelInfo = apiConfiguration?.openAiModelInfo ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } - modelInfo.maxTokens = input.target.value - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + modelInfo.maxTokens = Number(value) + handleFieldChange("openAiModelInfo", modelInfo) }}> Max Output Tokens - +
- { + onChange={(value) => { const modelInfo = apiConfiguration?.openAiModelInfo ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } - modelInfo.inputPrice = input.target.value - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + modelInfo.inputPrice = Number(value) + handleFieldChange("openAiModelInfo", modelInfo) }}> Input Price / 1M tokens - + - { + onChange={(value) => { const modelInfo = apiConfiguration?.openAiModelInfo ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } - modelInfo.outputPrice = input.target.value - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + modelInfo.outputPrice = Number(value) + handleFieldChange("openAiModelInfo", modelInfo) }}> Output Price / 1M tokens - +
- { + onChange={(value) => { const modelInfo = apiConfiguration?.openAiModelInfo ? apiConfiguration.openAiModelInfo : { ...openAiModelInfoSaneDefaults } - // Check if the input ends with a decimal point or has trailing zeros after decimal - const value = input.target.value const shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0")) modelInfo.temperature = value === "" ? openAiModelInfoSaneDefaults.temperature : shouldPreserveFormat - ? value // Keep as string to preserve decimal format + ? (value as any) : parseFloat(value) - handleInputChange("openAiModelInfo")({ - target: { value: modelInfo }, - }) + handleFieldChange("openAiModelInfo", modelInfo) }}> Temperature - +
)} diff --git a/webview-ui/src/components/settings/providers/OpenAINative.tsx b/webview-ui/src/components/settings/providers/OpenAINative.tsx index 795e93c4..4976ca0f 100644 --- a/webview-ui/src/components/settings/providers/OpenAINative.tsx +++ b/webview-ui/src/components/settings/providers/OpenAINative.tsx @@ -3,13 +3,13 @@ import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the OpenAINativeProvider component */ interface OpenAINativeProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,20 +17,18 @@ interface OpenAINativeProviderProps { /** * The OpenAI (native) provider configuration component */ -export const OpenAINativeProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, -}: OpenAINativeProviderProps) => { +export const OpenAINativeProvider = ({ showModelOptions, isPopup }: OpenAINativeProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("openAiNativeApiKey", value)} providerName="OpenAI" signupUrl="https://platform.openai.com/api-keys" /> @@ -40,7 +38,7 @@ export const OpenAINativeProvider = ({ handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx b/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx index 616e2470..c45e3b20 100644 --- a/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx +++ b/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx @@ -1,5 +1,6 @@ import { ApiConfiguration } from "@shared/api" -import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { DropdownContainer } from "../common/ModelSelector" import { useState } from "react" import { getOpenRouterAuthUrl } from "../utils/providerUtils" @@ -7,6 +8,8 @@ import { useOpenRouterKeyInfo } from "../../ui/hooks/useOpenRouterKeyInfo" import VSCodeButtonLink from "../../common/VSCodeButtonLink" import OpenRouterModelPicker, { OPENROUTER_MODEL_PICKER_Z_INDEX } from "../OpenRouterModelPicker" import { formatPrice } from "../utils/pricingUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Component to display OpenRouter balance information @@ -48,8 +51,6 @@ const OpenRouterBalanceDisplay = ({ apiKey }: { apiKey: string }) => { * Props for the OpenRouterProvider component */ interface OpenRouterProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean uriScheme?: string @@ -58,28 +59,20 @@ interface OpenRouterProviderProps { /** * The OpenRouter provider configuration component */ -export const OpenRouterProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - uriScheme, -}: OpenRouterProviderProps) => { - const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) +export const OpenRouterProvider = ({ showModelOptions, isPopup, uriScheme }: OpenRouterProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() - // Create a wrapper for handling field changes more directly - const handleFieldChange = (field: keyof ApiConfiguration) => (value: any) => { - handleInputChange(field)({ target: { value } }) - } + const [providerSortingSelected, setProviderSortingSelected] = useState(!!apiConfiguration?.openRouterProviderSorting) return (
- handleFieldChange("openRouterApiKey", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("openRouterApiKey")} placeholder="Enter API Key...">
OpenRouter API Key @@ -87,7 +80,7 @@ export const OpenRouterProvider = ({ )}
-
+ {!apiConfiguration?.openRouterApiKey && ( Sort underlying provider routing @@ -128,7 +121,7 @@ export const OpenRouterProvider = ({ style={{ width: "100%", marginTop: 3 }} value={apiConfiguration?.openRouterProviderSorting} onChange={(e: any) => { - handleFieldChange("openRouterProviderSorting")(e.target.value) + handleFieldChange("openRouterProviderSorting", e.target.value) }}> Default Price diff --git a/webview-ui/src/components/settings/providers/QwenProvider.tsx b/webview-ui/src/components/settings/providers/QwenProvider.tsx index ec5a1816..04cf4774 100644 --- a/webview-ui/src/components/settings/providers/QwenProvider.tsx +++ b/webview-ui/src/components/settings/providers/QwenProvider.tsx @@ -6,6 +6,8 @@ import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" import { DROPDOWN_Z_INDEX } from "../ApiOptions" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" const SUPPORTED_THINKING_MODELS = [ "qwen3-235b-a22b", @@ -24,23 +26,17 @@ const SUPPORTED_THINKING_MODELS = [ * Props for the QwenProvider component */ interface QwenProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration: (config: ApiConfiguration) => void } /** * The Alibaba Qwen provider configuration component */ -export const QwenProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: QwenProviderProps) => { +export const QwenProvider = ({ showModelOptions, isPopup }: QwenProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) @@ -56,7 +52,7 @@ export const QwenProvider = ({ handleFieldChange("qwenApiLine", e.target.value)} style={{ minWidth: 130, position: "relative", @@ -76,8 +72,8 @@ export const QwenProvider = ({

handleFieldChange("qwenApiKey", value)} providerName="Qwen" signupUrl="https://bailian.console.aliyun.com/" /> @@ -87,17 +83,13 @@ export const QwenProvider = ({ handleFieldChange("apiModelId", e.target.value)} label="Model" zIndex={DROPDOWN_Z_INDEX - 2} /> {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( - + )} diff --git a/webview-ui/src/components/settings/providers/RequestyProvider.tsx b/webview-ui/src/components/settings/providers/RequestyProvider.tsx index 72e3998a..63ccd23e 100644 --- a/webview-ui/src/components/settings/providers/RequestyProvider.tsx +++ b/webview-ui/src/components/settings/providers/RequestyProvider.tsx @@ -1,13 +1,12 @@ -import { ApiConfiguration } from "@shared/api" import { ApiKeyField } from "../common/ApiKeyField" import RequestyModelPicker from "../RequestyModelPicker" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the RequestyProvider component */ interface RequestyProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -15,12 +14,15 @@ interface RequestyProviderProps { /** * The Requesty provider configuration component */ -export const RequestyProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: RequestyProviderProps) => { +export const RequestyProvider = ({ showModelOptions, isPopup }: RequestyProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + return (
handleFieldChange("requestyApiKey", value)} providerName="Requesty" signupUrl="https://app.requesty.ai/manage-api" /> diff --git a/webview-ui/src/components/settings/providers/SambanovaProvider.tsx b/webview-ui/src/components/settings/providers/SambanovaProvider.tsx index e7d81b55..d5f3bc62 100644 --- a/webview-ui/src/components/settings/providers/SambanovaProvider.tsx +++ b/webview-ui/src/components/settings/providers/SambanovaProvider.tsx @@ -3,13 +3,13 @@ import { ApiKeyField } from "../common/ApiKeyField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the SambanovaProvider component */ interface SambanovaProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,15 +17,18 @@ interface SambanovaProviderProps { /** * The SambaNova provider configuration component */ -export const SambanovaProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: SambanovaProviderProps) => { +export const SambanovaProvider = ({ showModelOptions, isPopup }: SambanovaProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
handleFieldChange("sambanovaApiKey", value)} providerName="SambaNova" signupUrl="https://docs.sambanova.ai/cloud/docs/get-started/overview" /> @@ -35,7 +38,7 @@ export const SambanovaProvider = ({ apiConfiguration, handleInputChange, showMod handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx index 1dd195b9..8712f7b7 100644 --- a/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx +++ b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx @@ -1,15 +1,16 @@ -import { ApiConfiguration, sapAiCoreModels } from "@shared/api" -import { VSCodeTextField, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { sapAiCoreModels } from "@shared/api" +import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" +import { useExtensionState } from "@/context/ExtensionStateContext" /** * Props for the SapAiCoreProvider component */ interface SapAiCoreProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -17,62 +18,65 @@ interface SapAiCoreProviderProps { /** * The SAP AI Core provider configuration component */ -export const SapAiCoreProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: SapAiCoreProviderProps) => { +export const SapAiCoreProvider = ({ showModelOptions, isPopup }: SapAiCoreProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) return (
- handleFieldChange("sapAiCoreClientId", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("sapAiCoreClientId")} placeholder="Enter AI Core Client Id..."> AI Core Client Id - + {apiConfiguration?.sapAiCoreClientId && (

Client Id is set. To change it, please re-enter the value.

)} - handleFieldChange("sapAiCoreClientSecret", value)} style={{ width: "100%" }} type="password" - onInput={handleInputChange("sapAiCoreClientSecret")} placeholder="Enter AI Core Client Secret..."> AI Core Client Secret - + {apiConfiguration?.sapAiCoreClientSecret && (

Client Secret is set. To change it, please re-enter the value.

)} - handleFieldChange("sapAiCoreBaseUrl", value)} style={{ width: "100%" }} - onInput={handleInputChange("sapAiCoreBaseUrl")} placeholder="Enter AI Core Base URL..."> AI Core Base URL - + - handleFieldChange("sapAiCoreTokenUrl", value)} style={{ width: "100%" }} - onInput={handleInputChange("sapAiCoreTokenUrl")} placeholder="Enter AI Core Auth URL..."> AI Core Auth URL - + - handleFieldChange("sapAiResourceGroup", value)} style={{ width: "100%" }} - onInput={handleInputChange("sapAiResourceGroup")} placeholder="Enter AI Core Resource Group..."> AI Core Resource Group - +

handleFieldChange("apiModelId", e.target.value)} label="Model" /> diff --git a/webview-ui/src/components/settings/providers/TogetherProvider.tsx b/webview-ui/src/components/settings/providers/TogetherProvider.tsx index 00f2ae83..0a2d84b5 100644 --- a/webview-ui/src/components/settings/providers/TogetherProvider.tsx +++ b/webview-ui/src/components/settings/providers/TogetherProvider.tsx @@ -1,13 +1,13 @@ import { ApiConfiguration } from "@shared/api" -import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ApiKeyField } from "../common/ApiKeyField" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the TogetherProvider component */ interface TogetherProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean } @@ -15,21 +15,24 @@ interface TogetherProviderProps { /** * The Together provider configuration component */ -export const TogetherProvider = ({ apiConfiguration, handleInputChange, showModelOptions, isPopup }: TogetherProviderProps) => { +export const TogetherProvider = ({ showModelOptions, isPopup }: TogetherProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + return (

handleFieldChange("togetherApiKey", value)} providerName="Together" /> - handleFieldChange("togetherModelId", value)} style={{ width: "100%" }} - onInput={handleInputChange("togetherModelId")} placeholder={"Enter Model ID..."}> Model ID - +

(event: any) => void -} - -export const VSCodeLmProvider = ({ apiConfiguration, handleInputChange }: VSCodeLmProviderProps) => { +export const VSCodeLmProvider = () => { const [vsCodeLmModels, setVsCodeLmModels] = useState([]) + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() // Poll VS Code LM models const requestVsCodeLmModels = useCallback(async () => { @@ -54,11 +52,8 @@ export const VSCodeLmProvider = ({ apiConfiguration, handleInputChange }: VSCode return } const [vendor, family] = value.split("/") - handleInputChange("vsCodeLmModelSelector")({ - target: { - value: { vendor, family }, - }, - }) + + handleFieldChange("vsCodeLmModelSelector", { vendor, family }) }} style={{ width: "100%" }}> Select a model... diff --git a/webview-ui/src/components/settings/providers/VertexProvider.tsx b/webview-ui/src/components/settings/providers/VertexProvider.tsx index 8768c840..feb9f391 100644 --- a/webview-ui/src/components/settings/providers/VertexProvider.tsx +++ b/webview-ui/src/components/settings/providers/VertexProvider.tsx @@ -1,20 +1,20 @@ -import { ApiConfiguration, vertexGlobalModels, vertexModels } from "@shared/api" -import { VSCodeTextField, VSCodeDropdown, VSCodeOption, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { vertexGlobalModels, vertexModels } from "@shared/api" +import { VSCodeDropdown, VSCodeOption, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" import { DropdownContainer, DROPDOWN_Z_INDEX } from "../ApiOptions" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" /** * Props for the VertexProvider component */ interface VertexProviderProps { - apiConfiguration: ApiConfiguration - handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void showModelOptions: boolean isPopup?: boolean - setApiConfiguration: (config: ApiConfiguration) => void } // Vertex models that support thinking @@ -29,13 +29,10 @@ const SUPPORTED_THINKING_MODELS = [ /** * The GCP Vertex AI provider configuration component */ -export const VertexProvider = ({ - apiConfiguration, - handleInputChange, - showModelOptions, - isPopup, - setApiConfiguration, -}: VertexProviderProps) => { +export const VertexProvider = ({ showModelOptions, isPopup }: VertexProviderProps) => { + const { apiConfiguration } = useExtensionState() + const { handleFieldChange } = useApiConfigurationHandlers() + // Get the normalized configuration const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration) @@ -49,13 +46,13 @@ export const VertexProvider = ({ flexDirection: "column", gap: 5, }}> - handleFieldChange("vertexProjectId", value)} style={{ width: "100%" }} - onInput={handleInputChange("vertexProjectId")} placeholder="Enter Project ID..."> Google Cloud Project ID - +

handleFieldChange("xaiApiKey", value)} providerName="X AI" signupUrl="https://x.ai" /> @@ -61,7 +54,7 @@ export const XaiProvider = ({ handleFieldChange("apiModelId", e.target.value)} label="Model" /> @@ -74,10 +67,7 @@ export const XaiProvider = ({ const isChecked = e.target.checked === true setReasoningEffortSelected(isChecked) if (!isChecked) { - setApiConfiguration({ - ...apiConfiguration, - reasoningEffort: "", - }) + handleFieldChange("reasoningEffort", "") } }}> Modify reasoning effort @@ -94,10 +84,7 @@ export const XaiProvider = ({ style={{ width: "100%", marginTop: 3 }} value={apiConfiguration?.reasoningEffort || "high"} onChange={(e: any) => { - setApiConfiguration({ - ...apiConfiguration, - reasoningEffort: e.target.value, - }) + handleFieldChange("reasoningEffort", e.target.value) }}> low high diff --git a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx index 7b108c8e..60023040 100644 --- a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx +++ b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx @@ -2,30 +2,22 @@ import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import { TabButton } from "../../mcp/configuration/McpConfigurationView" import ApiOptions from "../ApiOptions" import Section from "../Section" - -import { ChatSettings } from "@shared/ChatSettings" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { StateServiceClient } from "@/services/grpc-client" +import { UpdateSettingsRequest } from "@shared/proto/state" interface ApiConfigurationSectionProps { - planActSeparateModelsSetting: boolean - chatSettings: ChatSettings isSwitchingMode: boolean - apiErrorMessage?: string - modelIdErrorMessage?: string handlePlanActModeChange: (mode: "plan" | "act") => Promise - setPlanActSeparateModelsSetting: (value: boolean) => void renderSectionHeader: (tabId: string) => JSX.Element | null } const ApiConfigurationSection = ({ - planActSeparateModelsSetting, - chatSettings, isSwitchingMode, - apiErrorMessage, - modelIdErrorMessage, handlePlanActModeChange, - setPlanActSeparateModelsSetting, renderSectionHeader, }: ApiConfigurationSectionProps) => { + const { planActSeparateModelsSetting, chatSettings } = useExtensionState() return (
{renderSectionHeader("api-config")} @@ -58,30 +50,28 @@ const ApiConfigurationSection = ({ {/* Content container */}
- +
) : ( - + )}
{ + onChange={async (e: any) => { const checked = e.target.checked === true - setPlanActSeparateModelsSetting(checked) + try { + await StateServiceClient.updateSettings( + UpdateSettingsRequest.create({ + planActSeparateModelsSetting: checked, + }), + ) + } catch (error) { + console.error("Failed to update separate models setting:", error) + } }}> Use different models for Plan and Act modes diff --git a/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx index 8dae8000..c46e9155 100644 --- a/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx @@ -1,17 +1,15 @@ import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" -import debounce from "debounce" import React, { useCallback, useEffect, useState } from "react" import styled from "styled-components" import { BROWSER_VIEWPORT_PRESETS } from "../../../../../src/shared/BrowserSettings" import { useExtensionState } from "../../../context/ExtensionStateContext" import { BrowserServiceClient } from "../../../services/grpc-client" import { EmptyRequest, StringRequest } from "@shared/proto/common" -import { BrowserSettings } from "@shared/BrowserSettings" +import { updateBrowserSetting } from "../utils/settingsHandlers" +import { DebouncedTextField } from "../common/DebouncedTextField" import Section from "../Section" interface BrowserSettingsSectionProps { - localBrowserSettings: BrowserSettings - onBrowserSettingsChange: (settings: BrowserSettings) => void renderSectionHeader: (tabId: string) => JSX.Element | null } @@ -58,13 +56,8 @@ const CollapsibleContent = styled.div<{ isOpen: boolean }>` visibility: ${({ isOpen }) => (isOpen ? "visible" : "hidden")}; ` -export const BrowserSettingsSection: React.FC = ({ - localBrowserSettings, - onBrowserSettingsChange, - renderSectionHeader, -}) => { +export const BrowserSettingsSection: React.FC = ({ renderSectionHeader }) => { const { browserSettings } = useExtensionState() - const [localChromePath, setLocalChromePath] = useState(localBrowserSettings.chromeExecutablePath || "") const [isCheckingConnection, setIsCheckingConnection] = useState(false) const [connectionStatus, setConnectionStatus] = useState(null) const [relaunchResult, setRelaunchResult] = useState<{ success: boolean; message: string } | null>(null) @@ -78,15 +71,12 @@ export const BrowserSettingsSection: React.FC = ({ const timer = setTimeout(() => { setRelaunchResult(null) }, 15000) - - // Clear timeout if component unmounts or relaunchResult changes return () => clearTimeout(timer) } }, [relaunchResult]) // Request detected Chrome path on mount useEffect(() => { - // Use gRPC for getDetectedChromePath BrowserServiceClient.getDetectedChromePath(EmptyRequest.create({})) .then((result) => { setDetectedChromePath(result.path) @@ -97,111 +87,10 @@ export const BrowserSettingsSection: React.FC = ({ }) }, []) - // Sync localChromePath with prop changes - useEffect(() => { - if (localBrowserSettings.chromeExecutablePath !== localChromePath) { - setLocalChromePath(localBrowserSettings.chromeExecutablePath || "") - } - }, [localBrowserSettings.chromeExecutablePath]) - - // Debounced connection check function - const debouncedCheckConnection = useCallback( - debounce(() => { - if (localBrowserSettings.remoteBrowserEnabled) { - setIsCheckingConnection(true) - setConnectionStatus(null) - if (localBrowserSettings.remoteBrowserHost) { - // Use gRPC for testBrowserConnection - BrowserServiceClient.testBrowserConnection( - StringRequest.create({ value: localBrowserSettings.remoteBrowserHost }), - ) - .then((result) => { - setConnectionStatus(result.success) - setIsCheckingConnection(false) - }) - .catch((error) => { - console.error("Error testing browser connection:", error) - setConnectionStatus(false) - setIsCheckingConnection(false) - }) - } else { - BrowserServiceClient.discoverBrowser(EmptyRequest.create({})) - .then((result) => { - setConnectionStatus(result.success) - setIsCheckingConnection(false) - }) - .catch((error) => { - console.error("Error discovering browser:", error) - setConnectionStatus(false) - setIsCheckingConnection(false) - }) - } - } - }, 1000), - [localBrowserSettings.remoteBrowserEnabled, localBrowserSettings.remoteBrowserHost], - ) - - // Check connection when component mounts or when remote settings change - useEffect(() => { - if (localBrowserSettings.remoteBrowserEnabled) { - debouncedCheckConnection() - } else { - setConnectionStatus(null) - } - }, [localBrowserSettings.remoteBrowserEnabled, localBrowserSettings.remoteBrowserHost, debouncedCheckConnection]) - - const handleViewportChange = (event: Event) => { - const target = event.target as HTMLSelectElement - const selectedSize = BROWSER_VIEWPORT_PRESETS[target.value as keyof typeof BROWSER_VIEWPORT_PRESETS] - if (selectedSize) { - onBrowserSettingsChange({ - ...localBrowserSettings, - viewport: { - width: selectedSize.width, - height: selectedSize.height, - }, - }) - } - } - - const updateRemoteBrowserEnabled = (enabled: boolean) => { - onBrowserSettingsChange({ - ...localBrowserSettings, - remoteBrowserEnabled: enabled, - // If disabling, also clear the host - remoteBrowserHost: enabled ? localBrowserSettings.remoteBrowserHost : undefined, - }) - } - - const updateRemoteBrowserHost = (host: string | undefined) => { - onBrowserSettingsChange({ - ...localBrowserSettings, - remoteBrowserHost: host, - }) - } - - const debouncedUpdateChromePath = useCallback( - debounce((newPath: string | undefined) => { - onBrowserSettingsChange({ - ...localBrowserSettings, - chromeExecutablePath: newPath, - }) - }, 500), - [localBrowserSettings, onBrowserSettingsChange], - ) - - const updateChromeExecutablePath = (path: string | undefined) => { - setLocalChromePath(path || "") - debouncedUpdateChromePath(path) - } - // Function to check connection once without changing UI state immediately const checkConnectionOnce = useCallback(() => { - // Don't show the spinner for every check to avoid UI flicker - // We'll rely on the response to update the connectionStatus - if (localBrowserSettings.remoteBrowserHost) { - // Use gRPC for testBrowserConnection - BrowserServiceClient.testBrowserConnection(StringRequest.create({ value: localBrowserSettings.remoteBrowserHost })) + if (browserSettings.remoteBrowserHost) { + BrowserServiceClient.testBrowserConnection(StringRequest.create({ value: browserSettings.remoteBrowserHost })) .then((result) => { setConnectionStatus(result.success) }) @@ -219,40 +108,37 @@ export const BrowserSettingsSection: React.FC = ({ setConnectionStatus(false) }) } - }, [localBrowserSettings.remoteBrowserHost]) + }, [browserSettings.remoteBrowserHost]) // Setup continuous polling for connection status when remote browser is enabled useEffect(() => { - // Only poll if remote browser mode is enabled - if (!localBrowserSettings.remoteBrowserEnabled) { - // Make sure we're not showing checking state when disabled + if (!browserSettings.remoteBrowserEnabled) { setIsCheckingConnection(false) return } - // Check immediately when enabled checkConnectionOnce() - - // Then check every second const pollInterval = setInterval(() => { checkConnectionOnce() }, 1000) - // Cleanup the interval if the component unmounts or remote browser is disabled return () => clearInterval(pollInterval) - }, [localBrowserSettings.remoteBrowserEnabled, checkConnectionOnce]) + }, [browserSettings.remoteBrowserEnabled, checkConnectionOnce]) - const updateDisableToolUse = (disabled: boolean) => { - onBrowserSettingsChange({ - ...localBrowserSettings, - disableToolUse: disabled, - }) + const handleViewportChange = (event: Event) => { + const target = event.target as HTMLSelectElement + const selectedSize = BROWSER_VIEWPORT_PRESETS[target.value as keyof typeof BROWSER_VIEWPORT_PRESETS] + if (selectedSize) { + updateBrowserSetting("viewport", { + width: selectedSize.width, + height: selectedSize.height, + }) + } } const relaunchChromeDebugMode = () => { setDebugMode(true) setRelaunchResult(null) - // The connection status will be automatically updated by our polling BrowserServiceClient.relaunchChromeDebugMode(EmptyRequest.create({})) .then((result) => { @@ -273,9 +159,9 @@ export const BrowserSettingsSection: React.FC = ({ } // Determine if we should show the relaunch button - const isRemoteEnabled = Boolean(localBrowserSettings.remoteBrowserEnabled) + const isRemoteEnabled = Boolean(browserSettings.remoteBrowserEnabled) const shouldShowRelaunchButton = isRemoteEnabled && connectionStatus === false - const isSubSettingsOpen = !(localBrowserSettings.disableToolUse || false) + const isSubSettingsOpen = !(browserSettings.disableToolUse || false) return (
@@ -285,8 +171,8 @@ export const BrowserSettingsSection: React.FC = ({ {/* Master Toggle */}
updateDisableToolUse((e.target as HTMLInputElement).checked)}> + checked={browserSettings.disableToolUse || false} + onChange={(e) => updateBrowserSetting("disableToolUse", (e.target as HTMLInputElement).checked)}> Disable browser tool usage

= ({ Object.entries(BROWSER_VIEWPORT_PRESETS).find(([_, size]) => { const typedSize = size as { width: number; height: number } return ( - typedSize.width === localBrowserSettings.viewport.width && - typedSize.height === localBrowserSettings.viewport.height + typedSize.width === browserSettings.viewport.width && + typedSize.height === browserSettings.viewport.height ) })?.[0] } @@ -343,14 +229,21 @@ export const BrowserSettingsSection: React.FC = ({ justifyContent: "space-between", }}> updateRemoteBrowserEnabled((e.target as HTMLInputElement).checked)}> + checked={browserSettings.remoteBrowserEnabled} + onChange={(e) => { + const enabled = (e.target as HTMLInputElement).checked + updateBrowserSetting("remoteBrowserEnabled", enabled) + // If disabling, also clear the host + if (!enabled) { + updateBrowserSetting("remoteBrowserHost", undefined) + } + }}> Use remote browser connection

= ({ : ""} . You can specify a custom path below. Using a remote browser connection requires starting Chrome in debug mode - {localBrowserSettings.remoteBrowserEnabled ? ( + {browserSettings.remoteBrowserEnabled ? ( <> {" "} manually (--remote-debugging-port=9222) or using the button below. Enter the @@ -378,13 +271,13 @@ export const BrowserSettingsSection: React.FC = ({ )}

{/* Moved remote-specific settings to appear directly after enabling remote connection */} - {localBrowserSettings.remoteBrowserEnabled && ( + {browserSettings.remoteBrowserEnabled && (
- updateRemoteBrowserHost(e.target.value || undefined)} + onChange={(value) => updateBrowserSetting("remoteBrowserHost", value || undefined)} /> {shouldShowRelaunchButton && ( @@ -433,15 +326,12 @@ export const BrowserSettingsSection: React.FC = ({ style={{ fontWeight: "500", display: "block", marginBottom: 5 }}> Chrome Executable Path (Optional) - { - const newValue = e.target.value || "" - updateChromeExecutablePath(newValue) - }} + onChange={(value) => updateBrowserSetting("chromeExecutablePath", value || undefined)} />

{ - const { - enableCheckpointsSetting, - setEnableCheckpointsSetting, - mcpMarketplaceEnabled, - setMcpMarketplaceEnabled, - mcpRichDisplayEnabled, - setMcpRichDisplayEnabled, - mcpResponsesCollapsed, - setMcpResponsesCollapsed, - chatSettings, - setChatSettings, - } = useExtensionState() + const { enableCheckpointsSetting, mcpMarketplaceEnabled, mcpRichDisplayEnabled, mcpResponsesCollapsed, chatSettings } = + useExtensionState() + + const handleReasoningEffortChange = (newValue: OpenAIReasoningEffort) => { + if (!chatSettings) return + + const updatedChatSettings = { + ...chatSettings, + openAIReasoningEffort: newValue, + } + + const protoChatSettings = convertChatSettingsToProtoChatSettings(updatedChatSettings) + updateSetting("chatSettings", protoChatSettings) + } return (

@@ -32,7 +36,7 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP checked={enableCheckpointsSetting} onChange={(e: any) => { const checked = e.target.checked === true - setEnableCheckpointsSetting(checked) + updateSetting("enableCheckpointsSetting", checked) }}> Enable Checkpoints @@ -46,7 +50,7 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP checked={mcpMarketplaceEnabled} onChange={(e: any) => { const checked = e.target.checked === true - setMcpMarketplaceEnabled(checked) + updateSetting("mcpMarketplaceEnabled", checked) }}> Enable MCP Marketplace @@ -59,7 +63,7 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP checked={mcpRichDisplayEnabled} onChange={(e: any) => { const checked = e.target.checked === true - setMcpRichDisplayEnabled(checked) + updateSetting("mcpRichDisplayEnabled", checked) }}> Enable Rich MCP Display @@ -72,7 +76,7 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP checked={mcpResponsesCollapsed} onChange={(e: any) => { const checked = e.target.checked === true - setMcpResponsesCollapsed(checked) + updateSetting("mcpResponsesCollapsed", checked) }}> Collapse MCP Responses @@ -91,10 +95,7 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP currentValue={chatSettings.openAIReasoningEffort || "medium"} onChange={(e: any) => { const newValue = e.target.currentValue as OpenAIReasoningEffort - setChatSettings({ - ...chatSettings, - openAIReasoningEffort: newValue, - }) + handleReasoningEffortChange(newValue) }} className="w-full"> Low diff --git a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx index bd8c90f5..fb6281a6 100644 --- a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx @@ -1,29 +1,21 @@ import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" -import { ChatSettings } from "@shared/ChatSettings" -import { TelemetrySetting } from "@shared/TelemetrySetting" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { updateSetting } from "../utils/settingsHandlers" import PreferredLanguageSetting from "../PreferredLanguageSetting" import Section from "../Section" interface GeneralSettingsSectionProps { - chatSettings: ChatSettings - setChatSettings: (settings: ChatSettings) => void - telemetrySetting: string - setTelemetrySetting: (value: TelemetrySetting) => void renderSectionHeader: (tabId: string) => JSX.Element | null } -const GeneralSettingsSection = ({ - chatSettings, - setChatSettings, - telemetrySetting, - setTelemetrySetting, - renderSectionHeader, -}: GeneralSettingsSectionProps) => { +const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionProps) => { + const { telemetrySetting } = useExtensionState() + return (
{renderSectionHeader("general")}
- {chatSettings && } +
{ const checked = e.target.checked === true - setTelemetrySetting(checked ? "enabled" : "disabled") + updateSetting("telemetrySetting", checked ? "enabled" : "disabled") }}> Allow anonymous error and usage reporting diff --git a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx index 7d1878d1..366b03a1 100644 --- a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx @@ -3,24 +3,17 @@ import { VSCodeTextField, VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@ import { useExtensionState } from "@/context/ExtensionStateContext" import TerminalOutputLineLimitSlider from "../TerminalOutputLineLimitSlider" import { StateServiceClient } from "../../../services/grpc-client" -import { Int64, Int64Request } from "@shared/proto/common" +import { Int64, Int64Request, StringRequest } from "@shared/proto/common" import Section from "../Section" +import { updateSetting } from "../utils/settingsHandlers" interface TerminalSettingsSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null } export const TerminalSettingsSection: React.FC = ({ renderSectionHeader }) => { - const { - shellIntegrationTimeout, - setShellIntegrationTimeout, - terminalReuseEnabled, - setTerminalReuseEnabled, - defaultTerminalProfile, - setDefaultTerminalProfile, - availableTerminalProfiles, - platform, - } = useExtensionState() + const { shellIntegrationTimeout, terminalReuseEnabled, defaultTerminalProfile, availableTerminalProfiles } = + useExtensionState() const [inputValue, setInputValue] = useState((shellIntegrationTimeout / 1000).toString()) const [inputError, setInputError] = useState(null) @@ -40,13 +33,12 @@ export const TerminalSettingsSection: React.FC = ( setInputError(null) const timeout = Math.round(seconds * 1000) - setShellIntegrationTimeout(timeout) - StateServiceClient.updateTerminalConnectionTimeout({ value: timeout, } as Int64Request) .then((response: Int64) => { - setShellIntegrationTimeout(response.value) + // Backend calls postStateToWebview(), so state will update via subscription + // Just sync the input value with the confirmed backend value setInputValue((response.value / 1000).toString()) }) .catch((error) => { @@ -64,18 +56,20 @@ export const TerminalSettingsSection: React.FC = ( const handleTerminalReuseChange = (event: Event) => { const target = event.target as HTMLInputElement const checked = target.checked - setTerminalReuseEnabled(checked) - StateServiceClient.updateTerminalReuseEnabled({ value: checked } as any).catch((error) => { - console.error("Failed to update terminal reuse enabled:", error) - }) + updateSetting("terminalReuseEnabled", checked) } // Use any to avoid type conflicts between Event and FormEvent const handleDefaultTerminalProfileChange = (event: any) => { const target = event.target as HTMLSelectElement const profileId = target.value - // Only update the local state, let the Save button handle the backend update - setDefaultTerminalProfile(profileId) + + // Save immediately - the backend will call postStateToWebview() to update our state + StateServiceClient.updateDefaultTerminalProfile({ + value: profileId || "default", + } as StringRequest).catch((error) => { + console.error("Failed to update default terminal profile:", error) + }) } const profilesToShow = availableTerminalProfiles diff --git a/webview-ui/src/components/settings/utils/settingsHandlers.ts b/webview-ui/src/components/settings/utils/settingsHandlers.ts new file mode 100644 index 00000000..c612a94c --- /dev/null +++ b/webview-ui/src/components/settings/utils/settingsHandlers.ts @@ -0,0 +1,35 @@ +import { StateServiceClient, BrowserServiceClient } from "@/services/grpc-client" +import { UpdateSettingsRequest } from "@shared/proto/state" +import { UpdateBrowserSettingsRequest } from "@shared/proto/browser" + +/** + * Updates a single field in the settings. + * + * @param field - The field key to update + * @param value - The new value for the field + */ +export const updateSetting = (field: keyof UpdateSettingsRequest, value: any) => { + const updateRequest: Partial = {} + updateRequest[field] = value + + StateServiceClient.updateSettings(UpdateSettingsRequest.create(updateRequest)).catch((error) => { + console.error(`Failed to update setting ${field}:`, error) + }) +} + +/** + * Updates a single browser setting field. + * + * @param field - The field key to update + * @param value - The new value for the field + */ +export const updateBrowserSetting = (field: keyof UpdateBrowserSettingsRequest, value: any) => { + const updateRequest: Partial = { + metadata: {}, + [field]: value, + } + + BrowserServiceClient.updateBrowserSettings(UpdateBrowserSettingsRequest.create(updateRequest)).catch((error) => { + console.error(`Failed to update browser setting ${field}:`, error) + }) +} diff --git a/webview-ui/src/components/settings/utils/useApiConfigurationHandlers.ts b/webview-ui/src/components/settings/utils/useApiConfigurationHandlers.ts new file mode 100644 index 00000000..41423cc6 --- /dev/null +++ b/webview-ui/src/components/settings/utils/useApiConfigurationHandlers.ts @@ -0,0 +1,62 @@ +import { useExtensionState } from "@/context/ExtensionStateContext" +import { ModelsServiceClient } from "@/services/grpc-client" +import { ApiConfiguration } from "@shared/api" +import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" +import { UpdateApiConfigurationRequest } from "@shared/proto/models" + +export const useApiConfigurationHandlers = () => { + const { apiConfiguration } = useExtensionState() + + /** + * Updates a single field in the API configuration. + * + * **Warning**: If this function is called multiple times in rapid succession, + * it can lead to race conditions where later calls may overwrite changes from + * earlier calls. For updating multiple fields, use `handleFieldsChange` instead. + * + * @param field - The field key to update + * @param value - The new value for the field + */ + const handleFieldChange = (field: K, value: ApiConfiguration[K]) => { + const updatedConfig = { + ...apiConfiguration, + [field]: value, + } + + const protoConfig = convertApiConfigurationToProto(updatedConfig) + ModelsServiceClient.updateApiConfigurationProto( + UpdateApiConfigurationRequest.create({ + apiConfiguration: protoConfig, + }), + ).catch((error) => { + console.error(`Failed to update API configuration field ${field}:`, error) + }) + } + + /** + * Updates multiple fields in the API configuration at once. + * + * This function should be used when updating multiple fields to avoid race conditions + * that can occur when calling `handleFieldChange` multiple times in succession. + * All updates are applied together as a single operation. + * + * @param updates - An object containing the fields to update and their new values + */ + const handleFieldsChange = (updates: Partial) => { + const updatedConfig = { + ...apiConfiguration, + ...updates, + } + + const protoConfig = convertApiConfigurationToProto(updatedConfig) + ModelsServiceClient.updateApiConfigurationProto( + UpdateApiConfigurationRequest.create({ + apiConfiguration: protoConfig, + }), + ).catch((error) => { + console.error("Failed to update API configuration fields:", error) + }) + } + + return { handleFieldChange, handleFieldsChange } +} diff --git a/webview-ui/src/components/settings/utils/useDebouncedInput.ts b/webview-ui/src/components/settings/utils/useDebouncedInput.ts new file mode 100644 index 00000000..6504f71a --- /dev/null +++ b/webview-ui/src/components/settings/utils/useDebouncedInput.ts @@ -0,0 +1,31 @@ +import { useState } from "react" +import { useDebounceEffect } from "@/utils/useDebounceEffect" + +/** + * A custom hook that provides debounced input handling to prevent jumpy text inputs + * when saving changes directly to backend on every keystroke. + * + * @param initialValue - The initial value for the input + * @param onChange - Callback function to save the value (e.g., to backend) + * @param debounceMs - Debounce delay in milliseconds (default: 500ms) + * @returns A tuple of [currentValue, setValue] similar to useState + */ +export function useDebouncedInput( + initialValue: T, + onChange: (value: T) => void, + debounceMs: number = 100, +): [T, (value: T) => void] { + // Local state to prevent jumpy input - initialize once + const [localValue, setLocalValue] = useState(initialValue) + + // Debounced backend save - saves after user stops changing value + useDebounceEffect( + () => { + onChange(localValue) + }, + debounceMs, + [localValue], + ) + + return [localValue, setLocalValue] +} diff --git a/webview-ui/src/components/welcome/WelcomeView.tsx b/webview-ui/src/components/welcome/WelcomeView.tsx index 8eb6ee52..68409e99 100644 --- a/webview-ui/src/components/welcome/WelcomeView.tsx +++ b/webview-ui/src/components/welcome/WelcomeView.tsx @@ -2,13 +2,10 @@ import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { useEffect, useState, memo } from "react" import { useExtensionState } from "@/context/ExtensionStateContext" import { validateApiConfiguration } from "@/utils/validate" -import { vscode } from "@/utils/vscode" import ApiOptions from "@/components/settings/ApiOptions" import ClineLogoWhite from "@/assets/ClineLogoWhite" -import { AccountServiceClient, ModelsServiceClient } from "@/services/grpc-client" -import { EmptyRequest } from "@shared/proto/common" -import { UpdateApiConfigurationRequest } from "@shared/proto/models" -import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" +import { AccountServiceClient, ModelsServiceClient, StateServiceClient } from "@/services/grpc-client" +import { EmptyRequest, BooleanRequest } from "@shared/proto/common" const WelcomeView = memo(() => { const { apiConfiguration } = useExtensionState() @@ -24,16 +21,10 @@ const WelcomeView = memo(() => { } const handleSubmit = async () => { - if (apiConfiguration) { - try { - await ModelsServiceClient.updateApiConfigurationProto( - UpdateApiConfigurationRequest.create({ - apiConfiguration: convertApiConfigurationToProto(apiConfiguration), - }), - ) - } catch (error) { - console.error("Failed to update API configuration:", error) - } + try { + await StateServiceClient.setWelcomeViewCompleted(BooleanRequest.create({ value: true })) + } catch (error) { + console.error("Failed to update API configuration or complete welcome view:", error) } } diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index c462183d..92891265 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -202,6 +202,7 @@ export const ExtensionStateContextProvider: React.FC<{ terminalOutputLineLimit: 500, defaultTerminalProfile: "default", isNewUser: false, + welcomeViewCompleted: false, mcpResponsesCollapsed: false, // Default value (expanded), will be overwritten by extension state }) const [didHydrateState, setDidHydrateState] = useState(false) @@ -278,35 +279,7 @@ export const ExtensionStateContextProvider: React.FC<{ } // Update welcome screen state based on API configuration - const config = stateData.apiConfiguration - const hasKey = config - ? [ - config.apiKey, - config.openRouterApiKey, - config.awsRegion, - config.vertexProjectId, - config.openAiApiKey, - config.ollamaModelId, - config.lmStudioModelId, - config.liteLlmApiKey, - config.geminiApiKey, - config.openAiNativeApiKey, - config.deepSeekApiKey, - config.requestyApiKey, - config.togetherApiKey, - config.qwenApiKey, - config.doubaoApiKey, - config.mistralApiKey, - config.vsCodeLmModelSelector, - config.clineApiKey, - config.asksageApiKey, - config.xaiApiKey, - config.sambanovaApiKey, - config.sapAiCoreClientId, - ].some((key) => key !== undefined) - : false - - setShowWelcome(!hasKey) + setShowWelcome(!newState.welcomeViewCompleted) setDidHydrateState(true) console.log("[DEBUG] returning new state in ESC") From 72029fe205373da31497da57dd08340a95b01f5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Barreiro?= <52393857+BarreiroT@users.noreply.github.com> Date: Thu, 3 Jul 2025 03:07:32 +0200 Subject: [PATCH 60/60] feat: Introduce Thinking Budget customization for Claude Code (#4618) --- .changeset/shy-fishes-check.md | 5 +++++ src/api/providers/claude-code.ts | 1 + src/integrations/claude-code/run.ts | 4 +++- .../components/settings/providers/AnthropicProvider.tsx | 8 ++++++-- .../components/settings/providers/ClaudeCodeProvider.tsx | 6 ++++++ 5 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 .changeset/shy-fishes-check.md diff --git a/.changeset/shy-fishes-check.md b/.changeset/shy-fishes-check.md new file mode 100644 index 00000000..2acf47df --- /dev/null +++ b/.changeset/shy-fishes-check.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +feat: Introduce Thinking Budget customization for Claude Code diff --git a/src/api/providers/claude-code.ts b/src/api/providers/claude-code.ts index d85f52d3..cca0e442 100644 --- a/src/api/providers/claude-code.ts +++ b/src/api/providers/claude-code.ts @@ -27,6 +27,7 @@ export class ClaudeCodeHandler implements ApiHandler { messages: filteredMessages, path: this.options.claudeCodePath, modelId: this.getModel().id, + thinkingBudgetTokens: this.options.thinkingBudgetTokens, }) // Usage is included with assistant messages, diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index b89a1ea6..90fe9caa 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -11,6 +11,7 @@ type ClaudeCodeOptions = { messages: Anthropic.Messages.MessageParam[] path?: string modelId?: string + thinkingBudgetTokens?: number } type ProcessState = { @@ -107,7 +108,7 @@ const claudeCodeTools = [ const CLAUDE_CODE_TIMEOUT = 600000 // 10 minutes -function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions) { +function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions) { const claudePath = path || "claude" const args = [ @@ -132,6 +133,7 @@ function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions ...process.env, // The default is 32000. However, I've gotten larger responses, so we increase it unless the user specified it. CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000", + MAX_THINKING_TOKENS: (thinkingBudgetTokens || 0).toString(), } // We don't want to consume the user's ANTHROPIC_API_KEY, diff --git a/webview-ui/src/components/settings/providers/AnthropicProvider.tsx b/webview-ui/src/components/settings/providers/AnthropicProvider.tsx index 19f1d782..fbebdfd5 100644 --- a/webview-ui/src/components/settings/providers/AnthropicProvider.tsx +++ b/webview-ui/src/components/settings/providers/AnthropicProvider.tsx @@ -9,7 +9,11 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" // Anthropic models that support thinking/reasoning mode -const SUPPORTED_THINKING_MODELS = ["claude-3-7-sonnet-20250219", "claude-sonnet-4-20250514", "claude-opus-4-20250514"] +export const SUPPORTED_ANTHROPIC_THINKING_MODELS = [ + "claude-3-7-sonnet-20250219", + "claude-sonnet-4-20250514", + "claude-opus-4-20250514", +] /** * Props for the AnthropicProvider component @@ -54,7 +58,7 @@ export const AnthropicProvider = ({ showModelOptions, isPopup }: AnthropicProvid label="Model" /> - {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( + {SUPPORTED_ANTHROPIC_THINKING_MODELS.includes(selectedModelId) && ( )} diff --git a/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx index 2928d326..3017fd06 100644 --- a/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx +++ b/webview-ui/src/components/settings/providers/ClaudeCodeProvider.tsx @@ -5,6 +5,8 @@ import { ModelInfoView } from "../common/ModelInfoView" import { normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" import { useExtensionState } from "@/context/ExtensionStateContext" +import { SUPPORTED_ANTHROPIC_THINKING_MODELS } from "./AnthropicProvider" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" /** * Props for the ClaudeCodeProvider component @@ -53,6 +55,10 @@ export const ClaudeCodeProvider = ({ showModelOptions, isPopup }: ClaudeCodeProv label="Model" /> + {SUPPORTED_ANTHROPIC_THINKING_MODELS.includes(selectedModelId) && ( + + )} + )}