diff --git a/.mocharc.json b/.mocharc.json index b5ee9fbf..4e99966c 100644 --- a/.mocharc.json +++ b/.mocharc.json @@ -1,6 +1,15 @@ { - "extension": ["ts"], - "spec": ["src/**/__tests__/*.ts", "eslint-rules/__tests__/**/*.test.ts"], - "require": ["ts-node/register", "source-map-support/register", "./src/test/requires.ts"], + "extension": [ + "ts" + ], + "spec": [ + "src/**/__tests__/*.ts", + "eslint-rules/__tests__/**/*.test.ts" + ], + "require": [ + "ts-node/register", + "source-map-support/register", + "./src/test/requires.ts" + ], "recursive": true } diff --git a/.vscode/launch.json b/.vscode/launch.json index 8537e102..1c2c3619 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -9,8 +9,14 @@ "name": "Run Extension (production)", "type": "extensionHost", "request": "launch", - "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"], - "outFiles": ["${workspaceFolder}/dist/**/*.js"], + "args": [ + "--extensionDevelopmentPath=${workspaceFolder}", + "--disable-workspace-trust", + "${workspaceFolder}" + ], + "outFiles": [ + "${workspaceFolder}/dist/**/*.js" + ], "preLaunchTask": "${defaultBuildTask}", "env": { "IS_DEV": "true", @@ -22,8 +28,14 @@ "name": "Run Extension (staging)", "type": "extensionHost", "request": "launch", - "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"], - "outFiles": ["${workspaceFolder}/dist/**/*.js"], + "args": [ + "--extensionDevelopmentPath=${workspaceFolder}", + "--disable-workspace-trust", + "${workspaceFolder}" + ], + "outFiles": [ + "${workspaceFolder}/dist/**/*.js" + ], "preLaunchTask": "${defaultBuildTask}", "env": { "IS_DEV": "true", @@ -35,8 +47,14 @@ "name": "Run Extension (local)", "type": "extensionHost", "request": "launch", - "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"], - "outFiles": ["${workspaceFolder}/dist/**/*.js"], + "args": [ + "--extensionDevelopmentPath=${workspaceFolder}", + "--disable-workspace-trust", + "${workspaceFolder}" + ], + "outFiles": [ + "${workspaceFolder}/dist/**/*.js" + ], "preLaunchTask": "${defaultBuildTask}", "env": { "IS_DEV": "true", @@ -57,7 +75,9 @@ "--extensionDevelopmentPath=${workspaceFolder}", "${workspaceFolder}" ], - "outFiles": ["${workspaceFolder}/dist/**/*.js"], + "outFiles": [ + "${workspaceFolder}/dist/**/*.js" + ], "preLaunchTask": "clean-tmp-user", "internalConsoleOptions": "openOnSessionStart", "postDebugTask": "stop", @@ -72,11 +92,18 @@ "type": "node", "request": "launch", "name": "Run cline-core service", - "skipFiles": ["/**"], + "skipFiles": [ + "/**" + ], "sourceMaps": true, - "resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"], + "resolveSourceMapLocations": [ + "${workspaceFolder}/**", + "!**/node_modules/**" + ], "cwd": "${workspaceFolder}/dist-standalone", - "outFiles": ["${workspaceFolder}/dist-standalone/**/*.js"], + "outFiles": [ + "${workspaceFolder}/dist-standalone/**/*.js" + ], "preLaunchTask": "compile-standalone", "env": { // Turns on grpc debug log. diff --git a/.vscode/tasks.json b/.vscode/tasks.json index d461eaaa..d6fddc52 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -30,7 +30,13 @@ }, { "label": "watch", - "dependsOn": ["npm: protos", "npm: build:webview", "npm: dev:webview", "npm: watch:tsc", "npm: watch:esbuild"], + "dependsOn": [ + "npm: protos", + "npm: build:webview", + "npm: dev:webview", + "npm: watch:tsc", + "npm: watch:esbuild" + ], "presentation": { "reveal": "always" }, @@ -60,7 +66,9 @@ "problemMatcher": [], "isBackground": true, "label": "npm: build:webview", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -78,7 +86,9 @@ "problemMatcher": [], "isBackground": true, "label": "npm: build:webview:test", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -113,7 +123,9 @@ ], "isBackground": true, "label": "npm: dev:webview", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -149,7 +161,9 @@ }, "isBackground": true, "label": "npm: watch:esbuild", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -185,7 +199,9 @@ }, "isBackground": true, "label": "npm: watch:esbuild:test", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -204,7 +220,9 @@ "problemMatcher": "$tsc-watch", "isBackground": true, "label": "npm: watch:tsc", - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "group": "watch", "reveal": "always" @@ -215,7 +233,9 @@ "script": "watch-tests", "problemMatcher": "$tsc-watch", "isBackground": true, - "dependsOn": ["npm: protos"], + "dependsOn": [ + "npm: protos" + ], "presentation": { "reveal": "always", "group": "watchers" @@ -224,7 +244,11 @@ }, { "label": "tasks: watch-tests", - "dependsOn": ["npm: protos", "npm: watch", "npm: watch-tests"], + "dependsOn": [ + "npm: protos", + "npm: watch", + "npm: watch-tests" + ], "problemMatcher": [] }, { @@ -235,7 +259,9 @@ { "label": "clean-tmp-user", "type": "shell", - "dependsOn": ["watch"], + "dependsOn": [ + "watch" + ], "command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user" } ], diff --git a/biome.jsonc b/biome.jsonc index c0406b5c..4ff4bc97 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -30,17 +30,14 @@ "correctness": { "useExhaustiveDependencies": "off", "noUndeclaredVariables": "off", - "noUnusedVariables": "off", "noEmptyPattern": "off", "useJsxKeyInIterable": "off", "noInnerDeclarations": "off", "useHookAtTopLevel": "off", "useYield": "off", - "noUnusedFunctionParameters": "off", "noConstructorReturn": "off", "noInvalidPositionAtImportRule": "off", - "noSwitchDeclarations": "off", - "noUnusedImports": "off" + "noSwitchDeclarations": "off" }, "a11y": "off", "style": { @@ -57,7 +54,6 @@ "useEnumInitializers": "off", "useSelfClosingElements": "off", "useSingleVarDeclarator": "off", - "noUnusedTemplateLiteral": "off", "useNumberNamespace": "off", "noInferrableTypes": "off", "useTemplate": "off", @@ -95,13 +91,7 @@ "indentWidth": 4, "lineWidth": 130, "lineEnding": "lf", - "formatWithErrors": true, - // TODO: Enable formatter for all files - currently off to keep PR changes minimal - "includes": [ - "**", - "!src/core/prompts/**", - "!webview-ui/src/components/chat/**" - ] + "formatWithErrors": true }, "javascript": { "formatter": { @@ -130,7 +120,9 @@ "!**/playwright/**", "!**/test-results/**", "!**/node_modules/**", - "!**/webview-ui/build/**" + "!**/webview-ui/build/**", + "!**/generated/**", + "!**/proto/**" ] }, "plugins": [ diff --git a/docs/docs.json b/docs/docs.json index 80ef3c4e..e87811b8 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -68,7 +68,10 @@ }, { "group": "Improving Your Prompting Skills", - "pages": ["prompting/prompt-engineering-guide", "prompting/cline-memory-bank"] + "pages": [ + "prompting/prompt-engineering-guide", + "prompting/cline-memory-bank" + ] }, { "group": "Features", @@ -181,11 +184,16 @@ }, { "group": "Troubleshooting", - "pages": ["troubleshooting/terminal-quick-fixes", "troubleshooting/terminal-integration-guide"] + "pages": [ + "troubleshooting/terminal-quick-fixes", + "troubleshooting/terminal-integration-guide" + ] }, { "group": "More Info", - "pages": ["more-info/telemetry"] + "pages": [ + "more-info/telemetry" + ] } ] }, @@ -200,6 +208,8 @@ "prompt": "Search Cline documentation..." }, "contextual": { - "options": ["copy"] + "options": [ + "copy" + ] } } diff --git a/package.json b/package.json index d17ae3fe..cfc9cdac 100644 --- a/package.json +++ b/package.json @@ -355,6 +355,7 @@ "lint": "biome lint --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error && buf lint", "format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error", "format:fix": "biome check --changed --no-errors-on-unmatched --files-ignore-unknown=true --write", + "fix:all": "biome check --no-errors-on-unmatched --files-ignore-unknown=true --write --diagnostic-level=error --unsafe", "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", diff --git a/scripts/build-proto.mjs b/scripts/build-proto.mjs index 93160d0c..192e990b 100755 --- a/scripts/build-proto.mjs +++ b/scripts/build-proto.mjs @@ -8,8 +8,8 @@ import { createRequire } from "module" import os from "os" import * as path from "path" import { rmrf } from "./file-utils.mjs" -import { main as generateProtoBusSetup } from "./generate-protobus-setup.mjs" import { main as generateHostBridgeClient } from "./generate-host-bridge-client.mjs" +import { main as generateProtoBusSetup } from "./generate-protobus-setup.mjs" import { loadProtoDescriptorSet } from "./proto-utils.mjs" const require = createRequire(import.meta.url) @@ -181,7 +181,7 @@ function checkAppleSiliconCompatibility() { console.log(chalk.red("Aborting build process.")) process.exit(1) } - } catch (error) { + } catch (_error) { console.log(chalk.yellow("Could not determine Rosetta installation status. Proceeding anyway.")) } } diff --git a/scripts/generate-host-bridge-client.mjs b/scripts/generate-host-bridge-client.mjs index 00004cc5..81086f8c 100755 --- a/scripts/generate-host-bridge-client.mjs +++ b/scripts/generate-host-bridge-client.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -import { writeFileWithMkdirs } from "./file-utils.mjs" -import * as path from "path" import chalk from "chalk" -import { loadServicesFromProtoDescriptor, getFqn } from "./proto-utils.mjs" +import * as path from "path" +import { writeFileWithMkdirs } from "./file-utils.mjs" +import { getFqn, loadServicesFromProtoDescriptor } from "./proto-utils.mjs" // Contains the interface definitions for the host bridge clients. const TYPES_FILE = path.resolve("src/generated/hosts/host-bridge-client-types.ts") diff --git a/scripts/generate-protobus-setup.mjs b/scripts/generate-protobus-setup.mjs index 437c0a17..9f879d4f 100755 --- a/scripts/generate-protobus-setup.mjs +++ b/scripts/generate-protobus-setup.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -import { writeFileWithMkdirs } from "./file-utils.mjs" import path from "path" import { fileURLToPath } from "url" -import { loadServicesFromProtoDescriptor, getFqn } from "./proto-utils.mjs" +import { writeFileWithMkdirs } from "./file-utils.mjs" +import { getFqn, loadServicesFromProtoDescriptor } from "./proto-utils.mjs" const WEBVIEW_CLIENTS_FILE = path.resolve("webview-ui/src/services/grpc-client.ts") const VSCODE_SERVICES_FILE = path.resolve("src/generated/hosts/vscode/protobus-services.ts") @@ -55,7 +55,7 @@ ${rpcs.join("\n")} } // Create output file - let output = `// GENERATED CODE -- DO NOT EDIT! + const output = `// GENERATED CODE -- DO NOT EDIT! // Generated by ${SCRIPT_NAME} import * as proto from "@shared/proto/index" import { ProtoBusClient, Callbacks } from "./grpc-client-base" @@ -94,7 +94,7 @@ async function generateVscodeServiceTypes(protobusServices) { } // Create output file - let output = `// GENERATED CODE -- DO NOT EDIT! + const output = `// GENERATED CODE -- DO NOT EDIT! // Generated by ${SCRIPT_NAME} import * as proto from "@shared/proto/index" import { Controller } from "@core/controller" @@ -128,7 +128,7 @@ async function generateVscodeProtobusServers(protobusServices) { } // Create output file - let output = `// GENERATED CODE -- DO NOT EDIT! + const output = `// GENERATED CODE -- DO NOT EDIT! // Generated by ${SCRIPT_NAME} import * as serviceTypes from "src/generated/hosts/vscode/protobus-service-types" @@ -176,7 +176,7 @@ async function generateStandaloneProtobusServiceSetup(protobusServices) { } // Create output file - let output = `// GENERATED CODE -- DO NOT EDIT! + const output = `// GENERATED CODE -- DO NOT EDIT! // Generated by ${SCRIPT_NAME} import * as grpc from "@grpc/grpc-js" import { cline } from "@generated/grpc-js" diff --git a/scripts/generate-stubs.js b/scripts/generate-stubs.js index 6096bdd3..c6058c01 100644 --- a/scripts/generate-stubs.js +++ b/scripts/generate-stubs.js @@ -37,7 +37,7 @@ function traverse(container, output, prefix = "") { const name = decl.getName() output.push(`${prefix}.${name} = createStub("${prefix}.${name}");`) } - } else if (kind == SyntaxKind.ClassDeclaration) { + } else if (kind === SyntaxKind.ClassDeclaration) { const name = node.getName() output.push( `${prefix}.${name} = class { constructor(...args) { @@ -55,13 +55,27 @@ function traverse(container, output, prefix = "") { } function mapReturn(typeStr) { - if (!typeStr) return "" - if (typeStr.includes("void")) return "" - if (typeStr.includes("string")) return `return '';` - if (typeStr.includes("number")) return `return 0;` - if (typeStr.includes("boolean")) return `return false;` - if (typeStr.includes("[]")) return `return [];` - if (typeStr.includes("Thenable")) return `return Promise.resolve(null);` + if (!typeStr) { + return "" + } + if (typeStr.includes("void")) { + return "" + } + if (typeStr.includes("string")) { + return `return '';` + } + if (typeStr.includes("number")) { + return `return 0;` + } + if (typeStr.includes("boolean")) { + return `return false;` + } + if (typeStr.includes("[]")) { + return `return [];` + } + if (typeStr.includes("Thenable")) { + return `return Promise.resolve(null);` + } return `return createStub("unknown");` } diff --git a/scripts/report-issue.js b/scripts/report-issue.js index c06dcc29..93dd5d9e 100644 --- a/scripts/report-issue.js +++ b/scripts/report-issue.js @@ -14,7 +14,7 @@ const getClineVersion = () => { const extensions = execSync("code --list-extensions --show-versions").toString() const clineMatch = extensions.match(/claude-dev@(\d+\.\d+\.\d+)/) return clineMatch ? clineMatch[1] : "Not installed" - } catch (err) { + } catch (_err) { return "Error getting version" } } @@ -32,7 +32,7 @@ const collectSystemInfo = () => { cpuInfo = execSync("lscpu").toString().split("\n").slice(0, 5).join("\n") memoryInfo = execSync("free -h").toString() } - } catch (err) { + } catch (_err) { // Fallback for unsupported systems cpuInfo = Array.from(new Set(os.cpus().map((c) => c.model))).join("\n") memoryInfo = `${Math.round(os.totalmem() / 1e9)} GB RAM` @@ -52,7 +52,7 @@ const checkGitHubAuth = async () => { try { execSync("gh auth status", { stdio: "ignore" }) return true - } catch (err) { + } catch (_err) { console.log("\nGitHub authentication required.") console.log("\nPlease run the following command in your terminal to authenticate:") console.log("\n gh auth login\n") @@ -92,7 +92,7 @@ const openUrl = (url) => { console.log("\nPlease open this URL in your browser:") console.log(url) } - } catch (err) { + } catch (_err) { console.log("\nFailed to open URL automatically. Please open this URL in your browser:") console.log(url) } diff --git a/src/core/api/providers/__tests__/bedrock.test.ts b/src/core/api/providers/__tests__/bedrock.test.ts index cafdd474..d1a5ca0a 100644 --- a/src/core/api/providers/__tests__/bedrock.test.ts +++ b/src/core/api/providers/__tests__/bedrock.test.ts @@ -1,8 +1,8 @@ import "should" -import { AwsBedrockHandler } from "../bedrock" -import { ApiHandlerOptions } from "@shared/api" import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime" +import { ApiHandlerOptions } from "@shared/api" import { Readable } from "stream" +import { AwsBedrockHandler } from "../bedrock" describe("AwsBedrockHandler", () => { // Helper function to create a mock stream diff --git a/src/core/api/providers/__tests__/ollama.test.ts b/src/core/api/providers/__tests__/ollama.test.ts index 6f3fe551..bb9b5cfd 100644 --- a/src/core/api/providers/__tests__/ollama.test.ts +++ b/src/core/api/providers/__tests__/ollama.test.ts @@ -1,10 +1,10 @@ -import { describe, it, beforeEach, afterEach, before } from "mocha" +import { afterEach, before, beforeEach, describe, it } from "mocha" import "should" -import sinon from "sinon" import { Anthropic } from "@anthropic-ai/sdk" -import { OllamaHandler } from "../ollama" import { ApiHandlerOptions } from "@shared/api" import axios from "axios" +import sinon from "sinon" +import { OllamaHandler } from "../ollama" describe("OllamaHandler", () => { let ollamaAvailable = false @@ -15,7 +15,7 @@ describe("OllamaHandler", () => { try { await axios.get("http://localhost:11434/api/version", { timeout: 2000 }) ollamaAvailable = true - } catch (error) { + } catch (_error) { console.log("Ollama server not available, skipping tests") ollamaAvailable = false } @@ -94,7 +94,7 @@ describe("OllamaHandler", () => { const testHandler = new OllamaHandler(options) // Replace the createMessage method with one that has a shorter timeout - testHandler.createMessage = async function* (systemPrompt, messages) { + testHandler.createMessage = async function* (_systemPrompt, _messages) { try { // Create a promise that rejects after a short timeout const timeoutPromise = new Promise((_, reject) => { @@ -192,7 +192,7 @@ describe("OllamaHandler", () => { const testHandler = new OllamaHandler(options) // Replace the createMessage method with one that simulates a stream error - testHandler.createMessage = async function* (systemPrompt, messages) { + testHandler.createMessage = async function* (_systemPrompt, _messages) { // First yield a successful chunk yield { type: "text", diff --git a/src/core/api/providers/anthropic.ts b/src/core/api/providers/anthropic.ts index 365e2776..1bb9d6d9 100644 --- a/src/core/api/providers/anthropic.ts +++ b/src/core/api/providers/anthropic.ts @@ -1,6 +1,6 @@ import { Anthropic } from "@anthropic-ai/sdk" import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming" -import { anthropicDefaultModelId, AnthropicModelId, anthropicModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api" +import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api" import { ApiHandler } from "../index" import { withRetry } from "../retry" import { ApiStream } from "../transform/stream" @@ -50,7 +50,7 @@ export class AnthropicHandler implements ApiHandler { const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_4_1M_SUFFIX) const budget_tokens = this.options.thinkingBudgetTokens || 0 - const reasoningOn = (modelId.includes("3-7") || modelId.includes("4-")) && budget_tokens !== 0 ? true : false + const reasoningOn = !!((modelId.includes("3-7") || modelId.includes("4-")) && budget_tokens !== 0) switch (modelId) { // 'latest' alias does not support cache_control diff --git a/src/core/api/providers/asksage.ts b/src/core/api/providers/asksage.ts index 544ef413..f830adf2 100644 --- a/src/core/api/providers/asksage.ts +++ b/src/core/api/providers/asksage.ts @@ -1,8 +1,8 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { AskSageModelId, askSageDefaultModelId, askSageDefaultURL, askSageModels, ModelInfo } from "@shared/api" import { ApiHandler } from ".." -import { ModelInfo, AskSageModelId, askSageModels, askSageDefaultModelId, askSageDefaultURL } from "@shared/api" -import { ApiStream } from "../transform/stream" import { withRetry } from "../retry" +import { ApiStream } from "../transform/stream" interface AskSageHandlerOptions { asksageApiKey?: string diff --git a/src/core/api/providers/baseten.ts b/src/core/api/providers/baseten.ts index adbd0361..dabf53f3 100644 --- a/src/core/api/providers/baseten.ts +++ b/src/core/api/providers/baseten.ts @@ -1,9 +1,9 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" -import { ApiHandler } from "../" -import { BasetenModelId, ModelInfo, basetenDefaultModelId, basetenModels } from "@shared/api" +import { BasetenModelId, basetenDefaultModelId, basetenModels, ModelInfo } from "@shared/api" import { calculateApiCostOpenAI } from "@utils/cost" +import OpenAI from "openai" +import { ApiHandler } from "../" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" @@ -158,7 +158,7 @@ export class BasetenHandler implements ApiHandler { * Checks if the current model supports tools */ supportsTools(): boolean { - const model = this.getModel() + const _model = this.getModel() // Baseten models support tools via OpenAI-compatible API return true } diff --git a/src/core/api/providers/bedrock.ts b/src/core/api/providers/bedrock.ts index 27afba57..d25bdfb3 100644 --- a/src/core/api/providers/bedrock.ts +++ b/src/core/api/providers/bedrock.ts @@ -1,11 +1,6 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { withRetry } from "../retry" -import { ApiHandler } from "../" -import { convertToR1Format } from "../transform/r1-format" -import { bedrockDefaultModelId, BedrockModelId, bedrockModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api" -import { calculateApiCostOpenAI } from "@utils/cost" -import { ApiStream } from "../transform/stream" -import { fromNodeProviderChain } from "@aws-sdk/credential-providers" +// Import proper AWS SDK types +import type { ContentBlock, Message } from "@aws-sdk/client-bedrock-runtime" import { BedrockRuntimeClient, ConversationRole, @@ -13,9 +8,13 @@ import { ConverseStreamCommand, InvokeModelWithResponseStreamCommand, } from "@aws-sdk/client-bedrock-runtime" - -// Import proper AWS SDK types -import type { Message, ContentBlock } from "@aws-sdk/client-bedrock-runtime" +import { fromNodeProviderChain } from "@aws-sdk/credential-providers" +import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api" +import { calculateApiCostOpenAI } from "@utils/cost" +import { ApiHandler } from "../" +import { withRetry } from "../retry" +import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface AwsBedrockHandlerOptions { apiModelId?: string diff --git a/src/core/api/providers/cerebras.ts b/src/core/api/providers/cerebras.ts index 7b3042be..11765b11 100644 --- a/src/core/api/providers/cerebras.ts +++ b/src/core/api/providers/cerebras.ts @@ -1,8 +1,8 @@ import { Anthropic } from "@anthropic-ai/sdk" import Cerebras from "@cerebras/cerebras_cloud_sdk" -import { withRetry } from "../retry" -import { ModelInfo, CerebrasModelId, cerebrasDefaultModelId, cerebrasModels } from "@shared/api" +import { CerebrasModelId, cerebrasDefaultModelId, cerebrasModels, ModelInfo } from "@shared/api" import { ApiHandler } from "../index" +import { withRetry } from "../retry" import { ApiStream } from "../transform/stream" interface CerebrasHandlerOptions { @@ -126,7 +126,7 @@ export class CerebrasHandler implements ApiHandler { reasoning = (reasoning || "") + content // Clean the content by removing think tags for display - let cleanContent = content.replace(//g, "").replace(/<\/think>/g, "") + const cleanContent = content.replace(//g, "").replace(/<\/think>/g, "") // Only yield reasoning content if there's actual content after cleaning if (cleanContent.trim()) { @@ -178,7 +178,7 @@ export class CerebrasHandler implements ApiHandler { // Enhanced error handling for Cerebras API if (error?.status === 429 || error?.code === "rate_limit_exceeded") { // Rate limit error - will be handled by retry decorator with patient backoff - const limits = this.getRateLimits() + const _limits = this.getRateLimits() throw new Error(`Cerebras API rate limit exceeded.`) } else if (error?.status === 401) { throw new Error("Cerebras API authentication failed. Please check your API key.") diff --git a/src/core/api/providers/claude-code.ts b/src/core/api/providers/claude-code.ts index 571abdb1..ee5af452 100644 --- a/src/core/api/providers/claude-code.ts +++ b/src/core/api/providers/claude-code.ts @@ -1,10 +1,10 @@ import type { Anthropic } from "@anthropic-ai/sdk" -import { claudeCodeDefaultModelId, ClaudeCodeModelId, claudeCodeModels } from "@/shared/api" -import { type ApiHandler } from ".." -import { ApiStreamUsageChunk, type ApiStream } from "../transform/stream" -import { withRetry } from "../retry" -import { runClaudeCode } from "@/integrations/claude-code/run" import { filterMessagesForClaudeCode } from "@/integrations/claude-code/message-filter" +import { runClaudeCode } from "@/integrations/claude-code/run" +import { ClaudeCodeModelId, claudeCodeDefaultModelId, claudeCodeModels } from "@/shared/api" +import { type ApiHandler } from ".." +import { withRetry } from "../retry" +import { type ApiStream, ApiStreamUsageChunk } from "../transform/stream" interface ClaudeCodeHandlerOptions { claudeCodePath?: string @@ -38,7 +38,7 @@ export class ClaudeCodeHandler implements ApiHandler { // Usage is included with assistant messages, // but cost is included in the result chunk - let usage: ApiStreamUsageChunk = { + const usage: ApiStreamUsageChunk = { type: "usage", inputTokens: 0, outputTokens: 0, @@ -137,7 +137,7 @@ export class ClaudeCodeHandler implements ApiHandler { private attemptParse(str: string) { try { return JSON.parse(str) - } catch (err) { + } catch (_err) { return null } } diff --git a/src/core/api/providers/cline.ts b/src/core/api/providers/cline.ts index 8708c549..e8067585 100644 --- a/src/core/api/providers/cline.ts +++ b/src/core/api/providers/cline.ts @@ -1,18 +1,18 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { ApiHandler } from "../" -import { ClineAccountService } from "@/services/account/ClineAccountService" import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api" +import { shouldSkipReasoningForModel } from "@utils/model-utils" +import axios from "axios" +import OpenAI from "openai" +import { clineEnvConfig } from "@/config" +import { ClineAccountService } from "@/services/account/ClineAccountService" +import { AuthService } from "@/services/auth/AuthService" +import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount" +import { version as extensionVersion } from "../../../../package.json" +import { ApiHandler } from "../" +import { withRetry } from "../retry" import { createOpenRouterStream } from "../transform/openrouter-stream" import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" -import axios from "axios" import { OpenRouterErrorResponse } from "./types" -import { withRetry } from "../retry" -import { AuthService } from "@/services/auth/AuthService" -import OpenAI from "openai" -import { version as extensionVersion } from "../../../../package.json" -import { shouldSkipReasoningForModel } from "@utils/model-utils" -import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount" -import { clineEnvConfig } from "@/config" interface ClineHandlerOptions { ulid?: string @@ -31,7 +31,6 @@ export class ClineHandler implements ApiHandler { private client: OpenAI | undefined private readonly _baseUrl = clineEnvConfig.apiBaseUrl lastGenerationId?: string - private counter = 0 constructor(options: ClineHandlerOptions) { this.options = options @@ -132,7 +131,7 @@ export class ClineHandler implements ApiHandler { if (!didOutputUsage && chunk.usage) { // @ts-ignore-next-line - let totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0) + const totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0) // const provider = modelId.split("/")[0] // // If provider is x-ai, set totalCost to 0 (we're doing a promo) @@ -202,7 +201,7 @@ export class ClineHandler implements ApiHandler { } getModel(): { id: string; info: ModelInfo } { - let modelId = this.options.openRouterModelId + const modelId = this.options.openRouterModelId const modelInfo = this.options.openRouterModelInfo if (modelId && modelInfo) { return { id: modelId, info: modelInfo } diff --git a/src/core/api/providers/deepseek.ts b/src/core/api/providers/deepseek.ts index bebe5165..5b0742c4 100644 --- a/src/core/api/providers/deepseek.ts +++ b/src/core/api/providers/deepseek.ts @@ -1,12 +1,12 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" -import { ApiHandler } from "../" -import { ApiHandlerOptions, DeepSeekModelId, ModelInfo, deepSeekDefaultModelId, deepSeekModels } from "@shared/api" +import { DeepSeekModelId, deepSeekDefaultModelId, deepSeekModels, ModelInfo } from "@shared/api" import { calculateApiCostOpenAI } from "@utils/cost" +import OpenAI from "openai" +import { ApiHandler } from "../" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface DeepSeekHandlerOptions { deepSeekApiKey?: string diff --git a/src/core/api/providers/doubao.ts b/src/core/api/providers/doubao.ts index 210da1a2..84ede1fe 100644 --- a/src/core/api/providers/doubao.ts +++ b/src/core/api/providers/doubao.ts @@ -1,10 +1,10 @@ -import { ApiHandler } from ".." -import { doubaoDefaultModelId, DoubaoModelId, doubaoModels, ModelInfo } from "@shared/api" import { Anthropic } from "@anthropic-ai/sdk" +import { DoubaoModelId, doubaoDefaultModelId, doubaoModels, ModelInfo } from "@shared/api" import OpenAI from "openai" +import { ApiHandler } from ".." +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" -import { withRetry } from "../retry" interface DoubaoHandlerOptions { doubaoApiKey?: string @@ -51,7 +51,7 @@ export class DoubaoHandler implements ApiHandler { async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { const client = this.ensureClient() const model = this.getModel() - let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages), ] diff --git a/src/core/api/providers/fireworks.ts b/src/core/api/providers/fireworks.ts index b8af5e43..f4c77eac 100644 --- a/src/core/api/providers/fireworks.ts +++ b/src/core/api/providers/fireworks.ts @@ -1,8 +1,8 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" -import { ApiHandler } from ".." import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api" +import OpenAI from "openai" +import { ApiHandler } from ".." +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" diff --git a/src/core/api/providers/gemini-mock.test.ts b/src/core/api/providers/gemini-mock.test.ts index 4c80cf1b..14a6fd9d 100644 --- a/src/core/api/providers/gemini-mock.test.ts +++ b/src/core/api/providers/gemini-mock.test.ts @@ -1,12 +1,12 @@ // Mock for @google/genai module to avoid ESM compatibility issues in tests export class GoogleGenAI { - constructor(options: any) { + constructor(_options: any) { // Mock constructor } models = { - generateContentStream: async (params: any) => { + generateContentStream: async (_params: any) => { // Mock implementation that returns an async iterator return { async *[Symbol.asyncIterator]() { @@ -23,7 +23,7 @@ export class GoogleGenAI { }, } }, - countTokens: async (params: any) => { + countTokens: async (_params: any) => { // Mock token counting return { totalTokens: 100, diff --git a/src/core/api/providers/gemini.ts b/src/core/api/providers/gemini.ts index dbeba17b..d9bdc204 100644 --- a/src/core/api/providers/gemini.ts +++ b/src/core/api/providers/gemini.ts @@ -1,16 +1,15 @@ import type { Anthropic } from "@anthropic-ai/sdk" // Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata -import { GoogleGenAI, type GenerateContentConfig, type GenerateContentResponseUsageMetadata } from "@google/genai" -import { withRetry } from "../retry" -import { Part } from "@google/genai" +import { type GenerateContentConfig, type GenerateContentResponseUsageMetadata, GoogleGenAI, Part } from "@google/genai" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { GeminiModelId, geminiDefaultModelId, geminiModels, ModelInfo } from "@shared/api" import { ApiHandler } from "../" -import { ApiHandlerOptions, geminiDefaultModelId, GeminiModelId, geminiModels, ModelInfo } from "@shared/api" +import { withRetry } from "../retry" import { convertAnthropicMessageToGemini } from "../transform/gemini-format" import { ApiStream } from "../transform/stream" -import { telemetryService } from "@services/posthog/PostHogClientProvider" // Define a default TTL for the cache (e.g., 15 minutes in seconds) -const DEFAULT_CACHE_TTL_SECONDS = 900 +const _DEFAULT_CACHE_TTL_SECONDS = 900 interface GeminiHandlerOptions { isVertex?: boolean @@ -108,7 +107,7 @@ export class GeminiHandler implements ApiHandler { // Configure thinking budget if supported const thinkingBudget = this.options.thinkingBudgetTokens ?? 0 - const maxBudget = info.thinkingConfig?.maxBudget ?? 0 + const _maxBudget = info.thinkingConfig?.maxBudget ?? 0 // Set up base generation config const requestConfig: GenerateContentConfig = { diff --git a/src/core/api/providers/groq.ts b/src/core/api/providers/groq.ts index feee4449..56297648 100644 --- a/src/core/api/providers/groq.ts +++ b/src/core/api/providers/groq.ts @@ -1,9 +1,9 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" -import { ApiHandler } from "../" -import { GroqModelId, ModelInfo, groqDefaultModelId, groqModels } from "@shared/api" +import { GroqModelId, groqDefaultModelId, groqModels, ModelInfo } from "@shared/api" import { calculateApiCostOpenAI } from "@utils/cost" +import OpenAI from "openai" +import { ApiHandler } from "../" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" diff --git a/src/core/api/providers/huawei-cloud-maas.ts b/src/core/api/providers/huawei-cloud-maas.ts index 2dddf71f..9c402d88 100644 --- a/src/core/api/providers/huawei-cloud-maas.ts +++ b/src/core/api/providers/huawei-cloud-maas.ts @@ -1,10 +1,10 @@ -import { ApiHandler } from ".." -import { huaweiCloudMaasDefaultModelId, HuaweiCloudMaasModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api" import { Anthropic } from "@anthropic-ai/sdk" +import { HuaweiCloudMaasModelId, huaweiCloudMaasDefaultModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api" import OpenAI from "openai" +import { ApiHandler } from ".." +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" -import { withRetry } from "../retry" interface HuaweiCloudMaaSHandlerOptions { huaweiCloudMaasApiKey?: string @@ -61,7 +61,7 @@ export class HuaweiCloudMaaSHandler implements ApiHandler { async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { const client = this.ensureClient() const model = this.getModel() - let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages), ] diff --git a/src/core/api/providers/huggingface.ts b/src/core/api/providers/huggingface.ts index bf60572d..a8744600 100644 --- a/src/core/api/providers/huggingface.ts +++ b/src/core/api/providers/huggingface.ts @@ -1,9 +1,9 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" -import { ApiHandler } from "../" -import { ApiHandlerOptions, HuggingFaceModelId, ModelInfo, huggingFaceDefaultModelId, huggingFaceModels } from "@shared/api" +import { HuggingFaceModelId, huggingFaceDefaultModelId, huggingFaceModels, ModelInfo } from "@shared/api" import { calculateApiCostOpenAI } from "@utils/cost" +import OpenAI from "openai" +import { ApiHandler } from "../" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" @@ -86,14 +86,14 @@ export class HuggingFaceHandler implements ApiHandler { const stream = (await client.chat.completions.create(requestParams)) as any - let chunkCount = 0 - let totalContent = "" + let _chunkCount = 0 + let _totalContent = "" for await (const chunk of stream) { - chunkCount++ + _chunkCount++ const delta = chunk.choices[0]?.delta if (delta?.content) { - totalContent += delta.content + _totalContent += delta.content yield { type: "text", @@ -119,7 +119,7 @@ export class HuggingFaceHandler implements ApiHandler { const modelId = this.options.huggingFaceModelId // List all available models for debugging - const availableModels = Object.keys(huggingFaceModels) + const _availableModels = Object.keys(huggingFaceModels) let result: { id: HuggingFaceModelId; info: ModelInfo } if (modelId && modelId in huggingFaceModels) { diff --git a/src/core/api/providers/litellm.ts b/src/core/api/providers/litellm.ts index 922efae5..18f02d97 100644 --- a/src/core/api/providers/litellm.ts +++ b/src/core/api/providers/litellm.ts @@ -1,10 +1,10 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api" import OpenAI from "openai" -import { liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults, LiteLLMModelInfo } from "@shared/api" import { ApiHandler } from ".." -import { ApiStream } from "../transform/stream" -import { convertToOpenAiMessages } from "../transform/openai-format" import { withRetry } from "../retry" +import { convertToOpenAiMessages } from "../transform/openai-format" +import { ApiStream } from "../transform/stream" interface LiteLlmHandlerOptions { liteLlmApiKey?: string @@ -186,7 +186,7 @@ export class LiteLlmHandler implements ApiHandler { // Configuration for extended thinking const budgetTokens = this.options.thinkingBudgetTokens || 0 - const reasoningOn = budgetTokens !== 0 ? true : false + const reasoningOn = budgetTokens !== 0 const thinkingConfig = reasoningOn ? { type: "enabled", budget_tokens: budgetTokens } : undefined let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 0 diff --git a/src/core/api/providers/mistral.ts b/src/core/api/providers/mistral.ts index 3606e553..6da3994a 100644 --- a/src/core/api/providers/mistral.ts +++ b/src/core/api/providers/mistral.ts @@ -1,8 +1,8 @@ import { Anthropic } from "@anthropic-ai/sdk" import { Mistral } from "@mistralai/mistralai" -import { withRetry } from "../retry" +import { MistralModelId, ModelInfo, mistralDefaultModelId, mistralModels } from "@shared/api" import { ApiHandler } from "../" -import { mistralDefaultModelId, MistralModelId, mistralModels, ModelInfo } from "@shared/api" +import { withRetry } from "../retry" import { convertToMistralMessages } from "../transform/mistral-format" import { ApiStream } from "../transform/stream" diff --git a/src/core/api/providers/moonshot.ts b/src/core/api/providers/moonshot.ts index 8cd8949f..283f8880 100644 --- a/src/core/api/providers/moonshot.ts +++ b/src/core/api/providers/moonshot.ts @@ -1,10 +1,10 @@ import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" -import { withRetry } from "../retry" +import { ModelInfo, MoonshotModelId, moonshotDefaultModelId, moonshotModels } from "@/shared/api" import { ApiHandler } from "../index" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" -import { ModelInfo, MoonshotModelId, moonshotModels, moonshotDefaultModelId } from "@/shared/api" interface MoonshotHandlerOptions { moonshotApiKey?: string diff --git a/src/core/api/providers/nebius.ts b/src/core/api/providers/nebius.ts index 1de92d9c..78cefc21 100644 --- a/src/core/api/providers/nebius.ts +++ b/src/core/api/providers/nebius.ts @@ -1,11 +1,11 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { type ModelInfo, type NebiusModelId, nebiusDefaultModelId, nebiusModels } from "@shared/api" import OpenAI from "openai" -import { withRetry } from "../retry" import { ApiHandler } from "../index" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" import { convertToR1Format } from "../transform/r1-format" -import { nebiusDefaultModelId, nebiusModels, type ModelInfo, type NebiusModelId } from "@shared/api" +import { ApiStream } from "../transform/stream" interface NebiusHandlerOptions { nebiusApiKey?: string diff --git a/src/core/api/providers/openai.ts b/src/core/api/providers/openai.ts index c35362ef..7b58440a 100644 --- a/src/core/api/providers/openai.ts +++ b/src/core/api/providers/openai.ts @@ -1,12 +1,12 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { azureOpenAiDefaultApiVersion, ModelInfo, OpenAiCompatibleModelInfo, openAiModelInfoSaneDefaults } from "@shared/api" import OpenAI, { AzureOpenAI } from "openai" -import { withRetry } from "../retry" -import { azureOpenAiDefaultApiVersion, ModelInfo, openAiModelInfoSaneDefaults, OpenAiCompatibleModelInfo } from "@shared/api" -import { ApiHandler } from "../index" -import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" -import { convertToR1Format } from "../transform/r1-format" import type { ChatCompletionReasoningEffort } from "openai/resources/chat/completions" +import { ApiHandler } from "../index" +import { withRetry } from "../retry" +import { convertToOpenAiMessages } from "../transform/openai-format" +import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface OpenAiHandlerOptions { openAiApiKey?: string @@ -73,7 +73,7 @@ export class OpenAiHandler implements ApiHandler { ...convertToOpenAiMessages(messages), ] let temperature: number | undefined = this.options.openAiModelInfo?.temperature ?? openAiModelInfoSaneDefaults.temperature - let reasoningEffort: ChatCompletionReasoningEffort | undefined = undefined + let reasoningEffort: ChatCompletionReasoningEffort | undefined let maxTokens: number | undefined if (this.options.openAiModelInfo?.maxTokens && this.options.openAiModelInfo.maxTokens > 0) { diff --git a/src/core/api/providers/openrouter.ts b/src/core/api/providers/openrouter.ts index ecaa32ac..726133b8 100644 --- a/src/core/api/providers/openrouter.ts +++ b/src/core/api/providers/openrouter.ts @@ -1,14 +1,14 @@ -import { Anthropic } from "@anthropic-ai/sdk" -import axios from "axios" import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import { Anthropic } from "@anthropic-ai/sdk" +import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api" +import { shouldSkipReasoningForModel } from "@utils/model-utils" +import axios from "axios" import OpenAI from "openai" import { ApiHandler } from "../" -import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api" import { withRetry } from "../retry" import { createOpenRouterStream } from "../transform/openrouter-stream" import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" import { OpenRouterErrorResponse } from "./types" -import { shouldSkipReasoningForModel } from "@utils/model-utils" interface OpenRouterHandlerOptions { openRouterApiKey?: string @@ -197,7 +197,7 @@ export class OpenRouterHandler implements ApiHandler { } getModel(): { id: string; info: ModelInfo } { - let modelId = this.options.openRouterModelId + const modelId = this.options.openRouterModelId const modelInfo = this.options.openRouterModelInfo if (modelId && modelInfo) { return { id: modelId, info: modelInfo } diff --git a/src/core/api/providers/qwen.ts b/src/core/api/providers/qwen.ts index 30d64d30..acd1d08a 100644 --- a/src/core/api/providers/qwen.ts +++ b/src/core/api/providers/qwen.ts @@ -1,20 +1,20 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { ApiHandler } from "../" import { - ModelInfo, - mainlandQwenModels, - internationalQwenModels, - mainlandQwenDefaultModelId, - internationalQwenDefaultModelId, - MainlandQwenModelId, InternationalQwenModelId, + internationalQwenDefaultModelId, + internationalQwenModels, + MainlandQwenModelId, + ModelInfo, + mainlandQwenDefaultModelId, + mainlandQwenModels, QwenApiRegions, } from "@shared/api" -import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" -import { convertToR1Format } from "../transform/r1-format" +import OpenAI from "openai" +import { ApiHandler } from "../" import { withRetry } from "../retry" +import { convertToOpenAiMessages } from "../transform/openai-format" +import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface QwenHandlerOptions { qwenApiKey?: string @@ -91,7 +91,7 @@ export class QwenHandler implements ApiHandler { let temperature: number | undefined = 0 // Configuration for extended thinking const budgetTokens = this.options.thinkingBudgetTokens || 0 - const reasoningOn = budgetTokens !== 0 ? true : false + const reasoningOn = budgetTokens !== 0 const thinkingArgs = isReasoningModelFamily ? { enable_thinking: reasoningOn, diff --git a/src/core/api/providers/requesty.ts b/src/core/api/providers/requesty.ts index abdb7783..b6b6e174 100644 --- a/src/core/api/providers/requesty.ts +++ b/src/core/api/providers/requesty.ts @@ -1,10 +1,10 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" import { ModelInfo, requestyDefaultModelId, requestyDefaultModelInfo } from "@shared/api" +import { calculateApiCostOpenAI } from "@utils/cost" +import OpenAI from "openai" import { ApiHandler } from "../index" import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" -import { calculateApiCostOpenAI } from "@utils/cost" import { ApiStream } from "../transform/stream" interface RequestyHandlerOptions { @@ -94,7 +94,7 @@ export class RequestyHandler implements ApiHandler { ...thinkingArgs, }) - let lastUsage: any = undefined + let lastUsage: any for await (const chunk of stream) { const delta = chunk.choices[0]?.delta diff --git a/src/core/api/providers/sambanova.ts b/src/core/api/providers/sambanova.ts index ab6eb19c..b3245479 100644 --- a/src/core/api/providers/sambanova.ts +++ b/src/core/api/providers/sambanova.ts @@ -1,11 +1,11 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" import { ModelInfo, SambanovaModelId, sambanovaDefaultModelId, sambanovaModels } from "@shared/api" +import OpenAI from "openai" import { ApiHandler } from "../index" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface SambanovaHandlerOptions { sambanovaApiKey?: string diff --git a/src/core/api/providers/sapaicore.ts b/src/core/api/providers/sapaicore.ts index 2edd153e..38ebf89a 100644 --- a/src/core/api/providers/sapaicore.ts +++ b/src/core/api/providers/sapaicore.ts @@ -1,15 +1,15 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { + type ContentBlock as BedrockContentBlock, + ConversationRole as BedrockConversationRole, + type Message as BedrockMessage, +} from "@aws-sdk/client-bedrock-runtime" +import { ModelInfo, SapAiCoreModelId, sapAiCoreDefaultModelId, sapAiCoreModels } from "@shared/api" import axios from "axios" import OpenAI from "openai" import { ApiHandler } from "../" -import { ModelInfo, sapAiCoreDefaultModelId, SapAiCoreModelId, sapAiCoreModels } from "@shared/api" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" -import { - type Message as BedrockMessage, - type ContentBlock as BedrockContentBlock, - ConversationRole as BedrockConversationRole, -} from "@aws-sdk/client-bedrock-runtime" interface SapAiCoreHandlerOptions { sapAiCoreClientId?: string @@ -320,7 +320,7 @@ namespace Gemini { // Add thinking config if the model supports it and budget is provided const thinkingBudget = thinkingBudgetTokens ?? 0 - const maxBudget = model.info.thinkingConfig?.maxBudget ?? 0 + const _maxBudget = model.info.thinkingConfig?.maxBudget ?? 0 if (thinkingBudget > 0 && model.info.thinkingConfig) { // Add thinking configuration to the payload @@ -520,7 +520,7 @@ export class SapAiCoreHandler implements ApiHandler { } } } else if (openAIModels.includes(model.id)) { - let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages), ] @@ -628,9 +628,9 @@ export class SapAiCoreHandler implements ApiHandler { private async *streamCompletion( stream: any, - model: { id: SapAiCoreModelId; info: ModelInfo }, + _model: { id: SapAiCoreModelId; info: ModelInfo }, ): AsyncGenerator { - let usage = { input_tokens: 0, output_tokens: 0 } + const usage = { input_tokens: 0, output_tokens: 0 } try { for await (const chunk of stream) { @@ -680,7 +680,7 @@ export class SapAiCoreHandler implements ApiHandler { private async *streamCompletionSonnet37( stream: any, - model: { id: SapAiCoreModelId; info: ModelInfo }, + _model: { id: SapAiCoreModelId; info: ModelInfo }, ): AsyncGenerator { function toStrictJson(str: string): string { // Wrap it in parentheses so JS will treat it as an expression @@ -688,7 +688,7 @@ export class SapAiCoreHandler implements ApiHandler { return JSON.stringify(obj) } - let usage = { input_tokens: 0, output_tokens: 0 } + const _usage = { input_tokens: 0, output_tokens: 0 } try { // Iterate over the stream and process each chunk @@ -761,9 +761,9 @@ export class SapAiCoreHandler implements ApiHandler { private async *streamCompletionGPT( stream: any, - model: { id: SapAiCoreModelId; info: ModelInfo }, + _model: { id: SapAiCoreModelId; info: ModelInfo }, ): AsyncGenerator { - let currentContent = "" + let _currentContent = "" let inputTokens = 0 let outputTokens = 0 @@ -793,7 +793,7 @@ export class SapAiCoreHandler implements ApiHandler { type: "text", text: choice.delta.content, } - currentContent += choice.delta.content + _currentContent += choice.delta.content } } @@ -832,7 +832,7 @@ export class SapAiCoreHandler implements ApiHandler { private async *streamCompletionGemini( stream: any, - model: { id: SapAiCoreModelId; info: ModelInfo }, + _model: { id: SapAiCoreModelId; info: ModelInfo }, ): AsyncGenerator { let promptTokens = 0 let outputTokens = 0 diff --git a/src/core/api/providers/together.ts b/src/core/api/providers/together.ts index 4494aae1..a56f77d0 100644 --- a/src/core/api/providers/together.ts +++ b/src/core/api/providers/together.ts @@ -1,11 +1,11 @@ import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" -import { withRetry } from "../retry" import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api" +import OpenAI from "openai" import { ApiHandler } from "../index" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" -import { ApiStream } from "../transform/stream" import { convertToR1Format } from "../transform/r1-format" +import { ApiStream } from "../transform/stream" interface TogetherHandlerOptions { togetherApiKey?: string diff --git a/src/core/api/providers/vertex.ts b/src/core/api/providers/vertex.ts index 10ba58a4..664ad2d3 100644 --- a/src/core/api/providers/vertex.ts +++ b/src/core/api/providers/vertex.ts @@ -1,8 +1,8 @@ import { Anthropic } from "@anthropic-ai/sdk" import { AnthropicVertex } from "@anthropic-ai/vertex-sdk" -import { withRetry } from "../retry" +import { ModelInfo, VertexModelId, vertexDefaultModelId, vertexModels } from "@shared/api" import { ApiHandler } from "../" -import { ModelInfo, vertexDefaultModelId, VertexModelId, vertexModels } from "@shared/api" +import { withRetry } from "../retry" import { ApiStream } from "../transform/stream" import { GeminiHandler } from "./gemini" @@ -77,11 +77,11 @@ export class VertexHandler implements ApiHandler { const clientAnthropic = this.ensureAnthropicClient() // Claude implementation - let budget_tokens = this.options.thinkingBudgetTokens || 0 - const reasoningOn = - (modelId.includes("3-7") || modelId.includes("sonnet-4") || modelId.includes("opus-4")) && budget_tokens !== 0 - ? true - : false + const budget_tokens = this.options.thinkingBudgetTokens || 0 + const reasoningOn = !!( + (modelId.includes("3-7") || modelId.includes("sonnet-4") || modelId.includes("opus-4")) && + budget_tokens !== 0 + ) let stream switch (modelId) { diff --git a/src/core/api/providers/vscode-lm.ts b/src/core/api/providers/vscode-lm.ts index b32b548d..ad1d926c 100644 --- a/src/core/api/providers/vscode-lm.ts +++ b/src/core/api/providers/vscode-lm.ts @@ -1,12 +1,12 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { ApiStream } from "../transform/stream" -import { convertToVsCodeLmMessages } from "../transform/vscode-lm-format" import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api" import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "@shared/vsCodeSelectorUtils" import { calculateApiCostAnthropic } from "@utils/cost" import * as vscode from "vscode" import { ApiHandler, SingleCompletionHandler } from "../" import { withRetry } from "../retry" +import { ApiStream } from "../transform/stream" +import { convertToVsCodeLmMessages } from "../transform/vscode-lm-format" import type { LanguageModelChatSelector as LanguageModelChatSelectorFromTypes } from "./types" interface VsCodeLmHandlerOptions { @@ -189,7 +189,7 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler { family: "lm", version: "1.0", maxInputTokens: 8192, - sendRequest: async (messages, options, token) => { + sendRequest: async (_messages, _options, _token) => { // Provide a minimal implementation return { stream: (async function* () { @@ -247,10 +247,6 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler { return "" } - private isClaudeModel(): boolean { - return this.client?.family?.startsWith("claude") || false - } - private async countTokens(text: string | vscode.LanguageModelChatMessage): Promise { /** * NOTE (intentional trade-off): @@ -469,8 +465,6 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler { } } catch (error) { console.error("Cline : Failed to process tool call:", error) - // Continue processing other chunks even if one fails - continue } } else { console.warn("Cline : Unknown chunk type received:", chunk) diff --git a/src/core/api/providers/xai.ts b/src/core/api/providers/xai.ts index aeaea1fd..810d3c17 100644 --- a/src/core/api/providers/xai.ts +++ b/src/core/api/providers/xai.ts @@ -1,12 +1,12 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { ModelInfo, XAIModelId, xaiDefaultModelId, xaiModels } from "@shared/api" +import { shouldSkipReasoningForModel } from "@utils/model-utils" import OpenAI from "openai" +import { ChatCompletionReasoningEffort } from "openai/resources/chat/completions" import { ApiHandler } from "../" -import { XAIModelId, ModelInfo, xaiDefaultModelId, xaiModels } from "@shared/api" +import { withRetry } from "../retry" import { convertToOpenAiMessages } from "../transform/openai-format" import { ApiStream } from "../transform/stream" -import { ChatCompletionReasoningEffort } from "openai/resources/chat/completions" -import { withRetry } from "../retry" -import { shouldSkipReasoningForModel } from "@utils/model-utils" interface XAIHandlerOptions { xaiApiKey?: string diff --git a/src/core/api/retry.ts b/src/core/api/retry.ts index f9ff73b2..3b1a9b7e 100644 --- a/src/core/api/retry.ts +++ b/src/core/api/retry.ts @@ -15,7 +15,7 @@ const DEFAULT_OPTIONS: Required = { export function withRetry(options: RetryOptions = {}) { const { maxRetries, baseDelay, maxDelay, retryAllErrors } = { ...DEFAULT_OPTIONS, ...options } - return function (_target: any, _propertyKey: string, descriptor: PropertyDescriptor) { + return (_target: any, _propertyKey: string, descriptor: PropertyDescriptor) => { const originalMethod = descriptor.value descriptor.value = async function* (...args: any[]) { @@ -51,7 +51,7 @@ export function withRetry(options: RetryOptions = {}) { } } else { // Use exponential backoff if no header - delay = Math.min(maxDelay, baseDelay * Math.pow(2, attempt)) + delay = Math.min(maxDelay, baseDelay * 2 ** attempt) } const handlerInstance = this as any diff --git a/src/core/api/transform/openrouter-stream.ts b/src/core/api/transform/openrouter-stream.ts index dbca9d4e..0faf6a78 100644 --- a/src/core/api/transform/openrouter-stream.ts +++ b/src/core/api/transform/openrouter-stream.ts @@ -1,8 +1,8 @@ +import { Anthropic } from "@anthropic-ai/sdk" import { CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo, openRouterClaudeSonnet41mModelId } from "@shared/api" +import OpenAI from "openai" import { convertToOpenAiMessages } from "./openai-format" import { convertToR1Format } from "./r1-format" -import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI from "openai" export async function createOpenRouterStream( client: OpenAI, @@ -109,7 +109,7 @@ export async function createOpenRouterStream( } let temperature: number | undefined = 0 - let topP: number | undefined = undefined + let topP: number | undefined if ( model.id.startsWith("deepseek/deepseek-r1") || model.id === "perplexity/sonar-reasoning" || @@ -122,7 +122,7 @@ export async function createOpenRouterStream( openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) } - let reasoning: { max_tokens: number } | undefined = undefined + let reasoning: { max_tokens: number } | undefined switch (model.id) { case "anthropic/claude-sonnet-4": case "anthropic/claude-opus-4.1": @@ -132,8 +132,8 @@ export async function createOpenRouterStream( case "anthropic/claude-3.7-sonnet:thinking": case "anthropic/claude-3-7-sonnet": case "anthropic/claude-3-7-sonnet:beta": - let budget_tokens = thinkingBudgetTokens || 0 - const reasoningOn = budget_tokens !== 0 ? true : false + const budget_tokens = thinkingBudgetTokens || 0 + const reasoningOn = budget_tokens !== 0 if (reasoningOn) { temperature = undefined // extended thinking does not support non-1 temperature reasoning = { max_tokens: budget_tokens } diff --git a/src/core/api/transform/vscode-lm-format.test.ts b/src/core/api/transform/vscode-lm-format.test.ts index 8c9bbb30..43275ebe 100644 --- a/src/core/api/transform/vscode-lm-format.test.ts +++ b/src/core/api/transform/vscode-lm-format.test.ts @@ -2,9 +2,9 @@ import "../providers/vscode-lm" import { describe, it } from "mocha" import "should" -import * as vscode from "vscode" import { Anthropic } from "@anthropic-ai/sdk" -import { asObjectSafe, convertToAnthropicRole, convertToVsCodeLmMessages, convertToAnthropicMessage } from "./vscode-lm-format" +import * as vscode from "vscode" +import { asObjectSafe, convertToAnthropicMessage, convertToAnthropicRole, convertToVsCodeLmMessages } from "./vscode-lm-format" describe("asObjectSafe", () => { it("should handle falsy values", () => { diff --git a/src/core/assistant-message/diff.test.ts b/src/core/assistant-message/diff.test.ts index 6d4be061..ee9cdda7 100644 --- a/src/core/assistant-message/diff.test.ts +++ b/src/core/assistant-message/diff.test.ts @@ -1,6 +1,6 @@ -import { constructNewFileContent as cnfc } from "./diff" -import { describe, it } from "mocha" import { expect } from "chai" +import { describe, it } from "mocha" +import { constructNewFileContent as cnfc } from "./diff" async function cnfc2(diffContent: string, originalContent: string, isFinal: boolean): Promise { return cnfc(diffContent, originalContent, isFinal, "v2") @@ -217,8 +217,8 @@ replaced } else { const result1 = await cnfc(diff, original, isFinal ?? true) const result2 = await cnfc2(diff, original, isFinal ?? true) - const equal = result1 === result2 - const equal2 = result1 === expected + const _equal = result1 === result2 + const _equal2 = result1 === expected // Verify both implementations produce same result expect(result1).to.equal(result2) diff --git a/src/core/assistant-message/diff.ts b/src/core/assistant-message/diff.ts index 6fe10a39..7b841ac9 100644 --- a/src/core/assistant-message/diff.ts +++ b/src/core/assistant-message/diff.ts @@ -265,10 +265,10 @@ async function constructNewFileContentV1(diffContent: string, originalContent: s let searchEndIndex = -1 // Track all replacements to handle out-of-order edits - let replacements: Array<{ start: number; end: number; content: string }> = [] + const replacements: Array<{ start: number; end: number; content: string }> = [] let pendingOutOfOrderReplacement = false - let lines = diffContent.split("\n") + const lines = diffContent.split("\n") // If the last line looks like a partial marker but isn't recognized, // remove it because it might be incomplete. @@ -487,7 +487,6 @@ class NewFileContentConstructor { private result: string private lastProcessedIndex: number private currentSearchContent: string - private currentReplaceContent: string private searchMatchIndex: number private searchEndIndex: number @@ -499,7 +498,6 @@ class NewFileContentConstructor { this.lastProcessedIndex = 0 this.state = ProcessingState.Idle this.currentSearchContent = "" - this.currentReplaceContent = "" this.searchMatchIndex = -1 this.searchEndIndex = -1 } @@ -508,7 +506,6 @@ class NewFileContentConstructor { // Reset for next block this.state = ProcessingState.Idle this.currentSearchContent = "" - this.currentReplaceContent = "" this.searchMatchIndex = -1 this.searchEndIndex = -1 } @@ -551,7 +548,6 @@ class NewFileContentConstructor { private activateSearchState() { this.updateProcessingState(ProcessingState.StateSearch) this.currentSearchContent = "" - this.currentReplaceContent = "" } private isSearchingActive(): boolean { @@ -618,7 +614,6 @@ class NewFileContentConstructor { // (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" @@ -626,7 +621,7 @@ class NewFileContentConstructor { } else if (this.isSearchingActive()) { this.currentSearchContent += line + "\n" } else { - let appendToPendingNonStandardLines = canWritependingNonStandardLines + const appendToPendingNonStandardLines = canWritependingNonStandardLines if (appendToPendingNonStandardLines) { // 处理非标内容 this.pendingNonStandardLines.push(line) @@ -712,10 +707,10 @@ class NewFileContentConstructor { if (!lineLimit) { throw new Error("Invalid SEARCH/REPLACE block structure - no lines available to process") } - let searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/ + const searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/ const searchTagIndex = this.findLastMatchingLineIndex(searchTagRegexp, lineLimit) if (searchTagIndex !== -1) { - let fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit) + const fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit) fixLines[0] = SEARCH_BLOCK_START for (const line of fixLines) { removeLineCount += this.internalProcessLine(line, false, searchTagIndex) @@ -736,14 +731,17 @@ class NewFileContentConstructor { if (!lineLimit) { throw new Error() } - let replaceBeginTagRegexp = /^[=]{3,}$/ + const 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) + const 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) @@ -763,7 +761,7 @@ class NewFileContentConstructor { throw new Error() } - let replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/ + const replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/ const replaceEndTagIndex = this.findLastMatchingLineIndex(replaceEndTagRegexp, lineLimit) const likeReplaceEndTag = replaceEndTagIndex === lineLimit - 1 if (likeReplaceEndTag) { @@ -771,7 +769,7 @@ class NewFileContentConstructor { // if (!this.isReplacingActive()) { // removeLineCount += this.tryFixReplaceBlock(replaceEndTagIndex) // } - let fixLines = this.pendingNonStandardLines.slice(replaceEndTagIndex - removeLineCount, lineLimit - removeLineCount) + const 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) @@ -803,9 +801,9 @@ class NewFileContentConstructor { } export async function constructNewFileContentV2(diffContent: string, originalContent: string, isFinal: boolean): Promise { - let newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal) + const newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal) - let lines = diffContent.split("\n") + const lines = diffContent.split("\n") // If the last line looks like a partial marker but isn't recognized, // remove it because it might be incomplete. @@ -828,6 +826,6 @@ export async function constructNewFileContentV2(diffContent: string, originalCon newFileContentConstructor.processLine(line) } - let result = newFileContentConstructor.getResult() + const result = newFileContentConstructor.getResult() return result } diff --git a/src/core/assistant-message/diff_edge_cases.test.ts b/src/core/assistant-message/diff_edge_cases.test.ts index ffbbeebc..20d02726 100644 --- a/src/core/assistant-message/diff_edge_cases.test.ts +++ b/src/core/assistant-message/diff_edge_cases.test.ts @@ -1,6 +1,6 @@ -import { constructNewFileContent as cnfc } from "./diff" -import { describe, it } from "mocha" import { expect } from "chai" +import { describe, it } from "mocha" +import { constructNewFileContent as cnfc } from "./diff" async function cnfc2(diffContent: string, originalContent: string, isFinal: boolean): Promise { return cnfc(diffContent, originalContent, isFinal, "v2") diff --git a/src/core/assistant-message/parse-assistant-message.ts b/src/core/assistant-message/parse-assistant-message.ts index d9f96d83..955bb680 100644 --- a/src/core/assistant-message/parse-assistant-message.ts +++ b/src/core/assistant-message/parse-assistant-message.ts @@ -1,4 +1,4 @@ -import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParamNames, toolUseNames, ToolUseName } from "." // Assuming types are defined in index.ts or a similar file +import { AssistantMessageContent, TextContent, ToolParamName, ToolUse, ToolUseName, toolParamNames, toolUseNames } from "." // Assuming types are defined in index.ts or a similar file // parseAssistantmessageV1 removed in https://github.com/cline/cline/pull/5425 @@ -26,11 +26,11 @@ import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParam export function parseAssistantMessageV2(assistantMessage: string): AssistantMessageContent[] { const contentBlocks: AssistantMessageContent[] = [] let currentTextContentStart = 0 // Index where the current text block started - let currentTextContent: TextContent | undefined = undefined + let currentTextContent: TextContent | undefined let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use - let currentToolUse: ToolUse | undefined = undefined + let currentToolUse: ToolUse | undefined let currentParamValueStart = 0 // Index *after* the opening tag of the current param - let currentParamName: ToolParamName | undefined = undefined + let currentParamName: ToolParamName | undefined // Precompute tags for faster lookups const toolUseOpenTags = new Map() diff --git a/src/core/context/context-management/ContextManager-legacy.ts b/src/core/context/context-management/ContextManager-legacy.ts index a7067f28..bf6fb599 100644 --- a/src/core/context/context-management/ContextManager-legacy.ts +++ b/src/core/context/context-management/ContextManager-legacy.ts @@ -1,6 +1,6 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { ClineApiReqInfo, ClineMessage } from "@shared/ExtensionMessage" import { ApiHandler } from "@core/api" +import { ClineApiReqInfo, ClineMessage } from "@shared/ExtensionMessage" import { getContextWindowInfo } from "./context-window-utils" class ContextManager { diff --git a/src/core/context/context-management/ContextManager.ts b/src/core/context/context-management/ContextManager.ts index a848bd64..9893f06d 100644 --- a/src/core/context/context-management/ContextManager.ts +++ b/src/core/context/context-management/ContextManager.ts @@ -174,11 +174,11 @@ export class ContextManager { */ async getNewContextMessagesAndMetadata( apiConversationHistory: Anthropic.Messages.MessageParam[], - clineMessages: ClineMessage[], - api: ApiHandler, + _clineMessages: ClineMessage[], + _api: ApiHandler, conversationHistoryDeletedRange: [number, number] | undefined, - previousApiReqIndex: number, - taskDirectory: string, + _previousApiReqIndex: number, + _taskDirectory: string, ) { const updatedConversationHistoryDeletedRange = false @@ -378,7 +378,7 @@ export class ContextManager { /** * applies the context optimization steps and returns whether any changes were made */ - private applyContextOptimizations( + public applyContextOptimizations( apiMessages: Anthropic.Messages.MessageParam[], startFromIndex: number, timestamp: number, diff --git a/src/core/context/context-management/__tests__/ContextManager.test.ts b/src/core/context/context-management/__tests__/ContextManager.test.ts index 088c8c20..e9f65250 100644 --- a/src/core/context/context-management/__tests__/ContextManager.test.ts +++ b/src/core/context/context-management/__tests__/ContextManager.test.ts @@ -1,6 +1,6 @@ -import { ContextManager } from "../ContextManager" import { Anthropic } from "@anthropic-ai/sdk" import { expect } from "chai" +import { ContextManager } from "../ContextManager" describe("ContextManager", () => { function createMessages(count: number): Anthropic.Messages.MessageParam[] { diff --git a/src/core/context/context-tracking/FileContextTracker.test.ts b/src/core/context/context-tracking/FileContextTracker.test.ts index d72dddb6..f509900f 100644 --- a/src/core/context/context-tracking/FileContextTracker.test.ts +++ b/src/core/context/context-tracking/FileContextTracker.test.ts @@ -1,20 +1,20 @@ -import { HostProvider } from "@/hosts/host-provider" -import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import * as diskModule from "@core/storage/disk" import { expect } from "chai" +import chokidar from "chokidar" import { afterEach, beforeEach, describe, it } from "mocha" import * as path from "path" import * as sinon from "sinon" import * as vscode from "vscode" -import chokidar from "chokidar" +import { Controller } from "@/core/controller" +import { HostProvider } from "@/hosts/host-provider" +import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import type { FileMetadataEntry, TaskMetadata } from "./ContextTrackerTypes" import { FileContextTracker } from "./FileContextTracker" -import { Controller } from "@/core/controller" describe("FileContextTracker", () => { let sandbox: sinon.SinonSandbox let mockController: Controller - let mockWorkspace: sinon.SinonStub + let _mockWorkspace: sinon.SinonStub let mockFileSystemWatcher: any let chokidarWatchStub: sinon.SinonStub let tracker: FileContextTracker @@ -27,7 +27,7 @@ describe("FileContextTracker", () => { sandbox = sinon.createSandbox() // Mock vscode workspace - mockWorkspace = sandbox.stub(vscode.workspace, "workspaceFolders").value([ + _mockWorkspace = sandbox.stub(vscode.workspace, "workspaceFolders").value([ { uri: { fsPath: "/mock/workspace", diff --git a/src/core/context/context-tracking/FileContextTracker.ts b/src/core/context/context-tracking/FileContextTracker.ts index dabaf758..2bf23d96 100644 --- a/src/core/context/context-tracking/FileContextTracker.ts +++ b/src/core/context/context-tracking/FileContextTracker.ts @@ -1,12 +1,12 @@ +import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk" +import type { ClineMessage } from "@shared/ExtensionMessage" +import chokidar, { FSWatcher } from "chokidar" import * as path from "path" import * as vscode from "vscode" -import chokidar, { FSWatcher } from "chokidar" -import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk" -import type { FileMetadataEntry } from "./ContextTrackerTypes" -import type { ClineMessage } from "@shared/ExtensionMessage" -import { getCwd } from "@/utils/path" -import { HistoryItem } from "@/shared/HistoryItem" import { Controller } from "@/core/controller" +import { HistoryItem } from "@/shared/HistoryItem" +import { getCwd } from "@/utils/path" +import type { FileMetadataEntry } from "./ContextTrackerTypes" // 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. @@ -131,7 +131,7 @@ export class FileContextTracker { return relevantEntries.length > 0 ? (relevantEntries[0][field] as number) : null } - let newEntry: FileMetadataEntry = { + const newEntry: FileMetadataEntry = { path: filePath, record_state: "active", record_source: source, diff --git a/src/core/context/context-tracking/ModelContextTracker.test.ts b/src/core/context/context-tracking/ModelContextTracker.test.ts index 74e967c4..4c9c1da7 100644 --- a/src/core/context/context-tracking/ModelContextTracker.test.ts +++ b/src/core/context/context-tracking/ModelContextTracker.test.ts @@ -1,10 +1,10 @@ -import { describe, it, beforeEach, afterEach } from "mocha" +import * as diskModule from "@core/storage/disk" import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" import * as sinon from "sinon" import * as vscode from "vscode" -import { ModelContextTracker } from "./ModelContextTracker" -import * as diskModule from "@core/storage/disk" import type { TaskMetadata } from "./ContextTrackerTypes" +import { ModelContextTracker } from "./ModelContextTracker" describe("ModelContextTracker", () => { let sandbox: sinon.SinonSandbox diff --git a/src/core/context/context-tracking/ModelContextTracker.ts b/src/core/context/context-tracking/ModelContextTracker.ts index 84872eb3..9c6c84d5 100644 --- a/src/core/context/context-tracking/ModelContextTracker.ts +++ b/src/core/context/context-tracking/ModelContextTracker.ts @@ -1,5 +1,5 @@ -import * as vscode from "vscode" import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk" +import * as vscode from "vscode" export class ModelContextTracker { readonly taskId: string diff --git a/src/core/context/instructions/user-instructions/cline-rules.ts b/src/core/context/instructions/user-instructions/cline-rules.ts index 17a0652c..9ce6778a 100644 --- a/src/core/context/instructions/user-instructions/cline-rules.ts +++ b/src/core/context/instructions/user-instructions/cline-rules.ts @@ -1,10 +1,10 @@ -import path from "path" -import { ensureRulesDirectoryExists, GlobalFileNames } from "@core/storage/disk" -import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" +import { getRuleFilesTotalContent, synchronizeRuleToggles } from "@core/context/instructions/user-instructions/rule-helpers" import { formatResponse } from "@core/prompts/responses" -import fs from "fs/promises" +import { ensureRulesDirectoryExists, GlobalFileNames } from "@core/storage/disk" import { ClineRulesToggles } from "@shared/cline-rules" -import { synchronizeRuleToggles, getRuleFilesTotalContent } from "@core/context/instructions/user-instructions/rule-helpers" +import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" +import fs from "fs/promises" +import path from "path" import { Controller } from "@/core/controller" export const getGlobalClineRules = async (globalClineRulesFilePath: string, toggles: ClineRulesToggles) => { diff --git a/src/core/context/instructions/user-instructions/external-rules.ts b/src/core/context/instructions/user-instructions/external-rules.ts index d71ec3ee..62892973 100644 --- a/src/core/context/instructions/user-instructions/external-rules.ts +++ b/src/core/context/instructions/user-instructions/external-rules.ts @@ -1,15 +1,15 @@ -import path from "path" -import fs from "fs/promises" -import { GlobalFileNames } from "@core/storage/disk" -import { fileExistsAtPath, isDirectory } from "@utils/fs" -import { formatResponse } from "@core/prompts/responses" import { - synchronizeRuleToggles, combineRuleToggles, getRuleFilesTotalContent, readDirectoryRecursive, + synchronizeRuleToggles, } from "@core/context/instructions/user-instructions/rule-helpers" +import { formatResponse } from "@core/prompts/responses" +import { GlobalFileNames } from "@core/storage/disk" import { ClineRulesToggles } from "@shared/cline-rules" +import { fileExistsAtPath, isDirectory } from "@utils/fs" +import fs from "fs/promises" +import path from "path" import { Controller } from "@/core/controller" /** diff --git a/src/core/context/instructions/user-instructions/rule-helpers.ts b/src/core/context/instructions/user-instructions/rule-helpers.ts index 10c70435..fe600150 100644 --- a/src/core/context/instructions/user-instructions/rule-helpers.ts +++ b/src/core/context/instructions/user-instructions/rule-helpers.ts @@ -1,8 +1,8 @@ -import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" import { ensureRulesDirectoryExists, ensureWorkflowsDirectoryExists, GlobalFileNames } from "@core/storage/disk" -import * as path from "path" -import fs from "fs/promises" import { ClineRulesToggles } from "@shared/cline-rules" +import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs" +import fs from "fs/promises" +import * as path from "path" import { Controller } from "@/core/controller" /** @@ -15,7 +15,7 @@ export async function readDirectoryRecursive( ): Promise { try { const entries = await readDirectory(directoryPath, excludedPaths) - let results: string[] = [] + const results: string[] = [] for (const entry of entries) { if (allowedFileExtension !== "") { const fileExtension = path.extname(entry) @@ -148,18 +148,18 @@ export async function ensureLocalClineDirExists(clinerulePath: string, defaultRu await fs.unlink(tempPath).catch(() => {}) // delete backup return false // conversion successful with no errors - } catch (conversionError) { + } catch (_conversionError) { // attempt to restore backup on conversion failure try { await fs.rm(clinerulePath, { recursive: true, force: true }).catch(() => {}) await fs.rename(tempPath, clinerulePath) // restore backup - } catch (restoreError) {} + } catch (_restoreError) {} return true // in either case here we consider this an error } } // exists and is a dir or doesn't exist, either of these cases we dont need to handle here return false - } catch (error) { + } catch (_error) { return true } } @@ -214,7 +214,7 @@ export const createRuleFile = async (isGlobal: boolean, filename: string, cwd: s await fs.writeFile(filePath, "", "utf8") return { filePath, fileExists: false } - } catch (error) { + } catch (_error) { return { filePath: null, fileExists: false } } } diff --git a/src/core/context/instructions/user-instructions/workflows.ts b/src/core/context/instructions/user-instructions/workflows.ts index 33d1b894..b5202537 100644 --- a/src/core/context/instructions/user-instructions/workflows.ts +++ b/src/core/context/instructions/user-instructions/workflows.ts @@ -1,7 +1,7 @@ -import path from "path" -import { GlobalFileNames, ensureWorkflowsDirectoryExists } from "@core/storage/disk" -import { ClineRulesToggles } from "@shared/cline-rules" import { synchronizeRuleToggles } from "@core/context/instructions/user-instructions/rule-helpers" +import { ensureWorkflowsDirectoryExists, GlobalFileNames } from "@core/storage/disk" +import { ClineRulesToggles } from "@shared/cline-rules" +import path from "path" import { Controller } from "@/core/controller" /** diff --git a/src/core/controller/account/accountLoginClicked.ts b/src/core/controller/account/accountLoginClicked.ts index 821a69c1..0344348b 100644 --- a/src/core/controller/account/accountLoginClicked.ts +++ b/src/core/controller/account/accountLoginClicked.ts @@ -1,6 +1,6 @@ -import { Controller } from "../index" -import { AuthService } from "@/services/auth/AuthService" import { EmptyRequest, String } from "@shared/proto/cline/common" +import { AuthService } from "@/services/auth/AuthService" +import { Controller } from "../index" /** * Handles the user clicking the login link in the UI. diff --git a/src/core/controller/account/accountLogoutClicked.ts b/src/core/controller/account/accountLogoutClicked.ts index 8b39a8ed..0204c191 100644 --- a/src/core/controller/account/accountLogoutClicked.ts +++ b/src/core/controller/account/accountLogoutClicked.ts @@ -1,6 +1,6 @@ -import { AuthService } from "@/services/auth/AuthService" -import { Empty } from "@shared/proto/cline/common" import type { EmptyRequest } from "@shared/proto/cline/common" +import { Empty } from "@shared/proto/cline/common" +import { AuthService } from "@/services/auth/AuthService" import type { Controller } from "../index" /** diff --git a/src/core/controller/account/authStateChanged.ts b/src/core/controller/account/authStateChanged.ts index 3d518958..b67aeb3e 100644 --- a/src/core/controller/account/authStateChanged.ts +++ b/src/core/controller/account/authStateChanged.ts @@ -1,4 +1,4 @@ -import { AuthStateChangedRequest, AuthState } from "@shared/proto/cline/account" +import { AuthState, AuthStateChangedRequest } from "@shared/proto/cline/account" import type { Controller } from "../index" /** diff --git a/src/core/controller/account/getOrganizationCredits.ts b/src/core/controller/account/getOrganizationCredits.ts index bd0f45cd..2a44fe1a 100644 --- a/src/core/controller/account/getOrganizationCredits.ts +++ b/src/core/controller/account/getOrganizationCredits.ts @@ -1,5 +1,5 @@ -import type { Controller } from "../index" import { GetOrganizationCreditsRequest, OrganizationCreditsData, OrganizationUsageTransaction } from "@shared/proto/cline/account" +import type { Controller } from "../index" /** * Handles fetching all organization credits data (balance, usage, payments) diff --git a/src/core/controller/account/getUserCredits.ts b/src/core/controller/account/getUserCredits.ts index d6e239e8..bfe39971 100644 --- a/src/core/controller/account/getUserCredits.ts +++ b/src/core/controller/account/getUserCredits.ts @@ -1,6 +1,6 @@ -import type { Controller } from "../index" -import type { EmptyRequest } from "@shared/proto/cline/common" import { UserCreditsData } from "@shared/proto/cline/account" +import type { EmptyRequest } from "@shared/proto/cline/common" +import type { Controller } from "../index" /** * Handles fetching all user credits data (balance, usage, payments) @@ -8,7 +8,7 @@ import { UserCreditsData } from "@shared/proto/cline/account" * @param request Empty request * @returns User credits data response */ -export async function getUserCredits(controller: Controller, request: EmptyRequest): Promise { +export async function getUserCredits(controller: Controller, _request: EmptyRequest): Promise { try { if (!controller.accountService) { throw new Error("Account service not available") diff --git a/src/core/controller/account/getUserOrganizations.ts b/src/core/controller/account/getUserOrganizations.ts index 2c16b9d9..c721a076 100644 --- a/src/core/controller/account/getUserOrganizations.ts +++ b/src/core/controller/account/getUserOrganizations.ts @@ -1,6 +1,6 @@ -import type { Controller } from "../index" -import type { EmptyRequest } from "@shared/proto/cline/common" import { UserOrganization, UserOrganizationsResponse } from "@shared/proto/cline/account" +import type { EmptyRequest } from "@shared/proto/cline/common" +import type { Controller } from "../index" /** * Handles fetching all user credits data (balance, usage, payments) @@ -8,7 +8,7 @@ import { UserOrganization, UserOrganizationsResponse } from "@shared/proto/cline * @param request Empty request * @returns User credits data response */ -export async function getUserOrganizations(controller: Controller, request: EmptyRequest): Promise { +export async function getUserOrganizations(controller: Controller, _request: EmptyRequest): Promise { try { if (!controller.accountService) { throw new Error("Account service not available") diff --git a/src/core/controller/account/openrouterAuthClicked.ts b/src/core/controller/account/openrouterAuthClicked.ts index b3183014..eee64433 100644 --- a/src/core/controller/account/openrouterAuthClicked.ts +++ b/src/core/controller/account/openrouterAuthClicked.ts @@ -1,8 +1,7 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" import { HostProvider } from "@/hosts/host-provider" import { openExternal } from "@/utils/env" - import { Controller } from ".." -import { EmptyRequest, Empty } from "@shared/proto/cline/common" /** * Initiates OpenRouter auth diff --git a/src/core/controller/account/setUserOrganization.ts b/src/core/controller/account/setUserOrganization.ts index 3a51388a..1cfd59fa 100644 --- a/src/core/controller/account/setUserOrganization.ts +++ b/src/core/controller/account/setUserOrganization.ts @@ -1,6 +1,6 @@ -import type { Controller } from "../index" -import { Empty } from "@shared/proto/cline/common" import { UserOrganizationUpdateRequest } from "@shared/proto/cline/account" +import { Empty } from "@shared/proto/cline/common" +import type { Controller } from "../index" /** * Handles setting the user's active organization diff --git a/src/core/controller/account/subscribeToAuthStatusUpdate.ts b/src/core/controller/account/subscribeToAuthStatusUpdate.ts index a67250c4..fce948c2 100644 --- a/src/core/controller/account/subscribeToAuthStatusUpdate.ts +++ b/src/core/controller/account/subscribeToAuthStatusUpdate.ts @@ -1,5 +1,5 @@ -import { AuthState, EmptyRequest } from "@/shared/proto/index.cline" import { AuthService } from "@services/auth/AuthService" +import { AuthState, EmptyRequest } from "@/shared/proto/index.cline" import { Controller } from ".." import { StreamingResponseHandler } from "../grpc-handler" diff --git a/src/core/controller/browser/discoverBrowser.ts b/src/core/controller/browser/discoverBrowser.ts index 18e3d64c..88d1844a 100644 --- a/src/core/controller/browser/discoverBrowser.ts +++ b/src/core/controller/browser/discoverBrowser.ts @@ -1,8 +1,8 @@ +import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" +import { BrowserSession } from "@services/browser/BrowserSession" import { BrowserConnection } from "@shared/proto/cline/browser" import { EmptyRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { BrowserSession } from "@services/browser/BrowserSession" -import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" /** * Discover Chrome instances @@ -10,7 +10,7 @@ import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" * @param request The request message * @returns The browser connection result */ -export async function discoverBrowser(controller: Controller, request: EmptyRequest): Promise { +export async function discoverBrowser(controller: Controller, _request: EmptyRequest): Promise { try { const discoveredHost = await discoverChromeInstances() diff --git a/src/core/controller/browser/getDetectedChromePath.ts b/src/core/controller/browser/getDetectedChromePath.ts index bbc5dc2d..6fcf5462 100644 --- a/src/core/controller/browser/getDetectedChromePath.ts +++ b/src/core/controller/browser/getDetectedChromePath.ts @@ -1,7 +1,7 @@ import { ChromePath } from "@shared/proto/cline/browser" import { EmptyRequest } from "@shared/proto/cline/common" -import { Controller } from "../index" import { BrowserSession } from "../../../services/browser/BrowserSession" +import { Controller } from "../index" /** * Get the detected Chrome executable path diff --git a/src/core/controller/browser/relaunchChromeDebugMode.ts b/src/core/controller/browser/relaunchChromeDebugMode.ts index 1bc2034b..c630a2ab 100644 --- a/src/core/controller/browser/relaunchChromeDebugMode.ts +++ b/src/core/controller/browser/relaunchChromeDebugMode.ts @@ -1,6 +1,6 @@ import { EmptyRequest, String as StringMessage } from "@shared/proto/cline/common" -import { Controller } from "../index" import { BrowserSession } from "../../../services/browser/BrowserSession" +import { Controller } from "../index" /** * Relaunch Chrome in debug mode diff --git a/src/core/controller/browser/testBrowserConnection.ts b/src/core/controller/browser/testBrowserConnection.ts index c82c66ad..0847195a 100644 --- a/src/core/controller/browser/testBrowserConnection.ts +++ b/src/core/controller/browser/testBrowserConnection.ts @@ -1,8 +1,8 @@ +import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" +import { BrowserSession } from "@services/browser/BrowserSession" import { BrowserConnection } from "@shared/proto/cline/browser" import { StringRequest } from "@shared/proto/cline/common" import { Controller } from "../index" -import { BrowserSession } from "@services/browser/BrowserSession" -import { discoverChromeInstances } from "@services/browser/BrowserDiscovery" /** * Test connection to a browser instance diff --git a/src/core/controller/browser/updateBrowserSettings.ts b/src/core/controller/browser/updateBrowserSettings.ts index dbfe0ea0..bef7fa5a 100644 --- a/src/core/controller/browser/updateBrowserSettings.ts +++ b/src/core/controller/browser/updateBrowserSettings.ts @@ -1,7 +1,7 @@ import { UpdateBrowserSettingsRequest } from "@shared/proto/cline/browser" import { Boolean } from "@shared/proto/cline/common" +import { DEFAULT_BROWSER_SETTINGS, BrowserSettings as SharedBrowserSettings } from "../../../shared/BrowserSettings" import { Controller } from "../index" -import { BrowserSettings as SharedBrowserSettings, DEFAULT_BROWSER_SETTINGS } from "../../../shared/BrowserSettings" /** * Update browser settings diff --git a/src/core/controller/checkpoints/checkpointDiff.ts b/src/core/controller/checkpoints/checkpointDiff.ts index 57f9d185..f0af96ef 100644 --- a/src/core/controller/checkpoints/checkpointDiff.ts +++ b/src/core/controller/checkpoints/checkpointDiff.ts @@ -1,5 +1,5 @@ -import { Controller } from ".." import { Empty, Int64Request } from "@shared/proto/cline/common" +import { Controller } from ".." export async function checkpointDiff(controller: Controller, request: Int64Request): Promise { if (request.value) { diff --git a/src/core/controller/checkpoints/checkpointRestore.ts b/src/core/controller/checkpoints/checkpointRestore.ts index c27e791e..4cd19f46 100644 --- a/src/core/controller/checkpoints/checkpointRestore.ts +++ b/src/core/controller/checkpoints/checkpointRestore.ts @@ -1,10 +1,10 @@ -import { HostProvider } from "@/hosts/host-provider" -import { Controller } from ".." -import { ClineCheckpointRestore } from "../../../shared/WebviewMessage" import { CheckpointRestoreRequest } from "@shared/proto/cline/checkpoints" import { Empty } from "@shared/proto/cline/common" import pWaitFor from "p-wait-for" +import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/index.host" +import { ClineCheckpointRestore } from "../../../shared/WebviewMessage" +import { Controller } from ".." export async function checkpointRestore(controller: Controller, request: CheckpointRestoreRequest): Promise { await controller.cancelTask() // we cannot alter message history say if the task is active, as it could be in the middle of editing a file or running a command, which expect the ask to be responded to rather than being superseded by a new message eg add deleted_api_reqs diff --git a/src/core/controller/commands/addToCline.ts b/src/core/controller/commands/addToCline.ts index 7ce53241..c42fb59d 100644 --- a/src/core/controller/commands/addToCline.ts +++ b/src/core/controller/commands/addToCline.ts @@ -1,9 +1,9 @@ -import { Controller } from "../index" -import { CommandContext, Empty } from "@/shared/proto/index.cline" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" import { getFileMentionFromPath } from "@/core/mentions" -import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics" import { WebviewProvider } from "@/core/webview" +import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics" +import { telemetryService } from "@/services/posthog/PostHogClientProvider" +import { CommandContext, Empty } from "@/shared/proto/index.cline" +import { Controller } from "../index" import { sendAddToInputEventToClient } from "../ui/subscribeToAddToInput" // 'Add to Cline' context menu in editor and code action diff --git a/src/core/controller/commands/explainWithCline.ts b/src/core/controller/commands/explainWithCline.ts index db9b2140..8924786b 100644 --- a/src/core/controller/commands/explainWithCline.ts +++ b/src/core/controller/commands/explainWithCline.ts @@ -1,9 +1,9 @@ -import { Controller } from "../index" -import { CommandContext, Empty } from "@/shared/proto/index.cline" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" -import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageType } from "@/shared/proto/index.host" import { getFileMentionFromPath } from "@/core/mentions" +import { HostProvider } from "@/hosts/host-provider" +import { telemetryService } from "@/services/posthog/PostHogClientProvider" +import { CommandContext, Empty } from "@/shared/proto/index.cline" +import { ShowMessageType } from "@/shared/proto/index.host" +import { Controller } from "../index" export async function explainWithCline(controller: Controller, request: CommandContext): Promise { if (!request.selectedText || !request.selectedText.trim()) { diff --git a/src/core/controller/commands/fixWithCline.ts b/src/core/controller/commands/fixWithCline.ts index 8cb712c3..eee12daf 100644 --- a/src/core/controller/commands/fixWithCline.ts +++ b/src/core/controller/commands/fixWithCline.ts @@ -1,8 +1,8 @@ -import { Controller } from "../index" -import { CommandContext, Empty } from "@/shared/proto/index.cline" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" import { getFileMentionFromPath } from "@/core/mentions" import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics" +import { telemetryService } from "@/services/posthog/PostHogClientProvider" +import { CommandContext, Empty } from "@/shared/proto/index.cline" +import { Controller } from "../index" export async function fixWithCline(controller: Controller, request: CommandContext): Promise { const filePath = request.filePath || "" diff --git a/src/core/controller/commands/improveWithCline.ts b/src/core/controller/commands/improveWithCline.ts index 71a7d1f3..16c345ab 100644 --- a/src/core/controller/commands/improveWithCline.ts +++ b/src/core/controller/commands/improveWithCline.ts @@ -1,9 +1,9 @@ -import { Controller } from "../index" -import { CommandContext, Empty } from "@/shared/proto/index.cline" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" -import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageType } from "@/shared/proto/index.host" import { getFileMentionFromPath } from "@/core/mentions" +import { HostProvider } from "@/hosts/host-provider" +import { telemetryService } from "@/services/posthog/PostHogClientProvider" +import { CommandContext, Empty } from "@/shared/proto/index.cline" +import { ShowMessageType } from "@/shared/proto/index.host" +import { Controller } from "../index" export async function improveWithCline(controller: Controller, request: CommandContext): Promise { if (!request.selectedText || !request.selectedText.trim()) { diff --git a/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts b/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts index 9583fca8..4886f8e3 100644 --- a/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts +++ b/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts @@ -1,10 +1,10 @@ -import { describe, it, beforeEach, afterEach } from "mocha" +import { Controller } from "@core/controller" +import { BooleanResponse, StringRequest } from "@shared/proto/cline/common" +import * as pathUtils from "@utils/path" import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" import * as sinon from "sinon" import { ifFileExistsRelativePath } from "../ifFileExistsRelativePath" -import { Controller } from "@core/controller" -import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" -import * as pathUtils from "@utils/path" describe("ifFileExistsRelativePath", () => { let sandbox: sinon.SinonSandbox diff --git a/src/core/controller/file/__tests__/openFileRelativePath.test.ts b/src/core/controller/file/__tests__/openFileRelativePath.test.ts index 2c318995..8f6e3a03 100644 --- a/src/core/controller/file/__tests__/openFileRelativePath.test.ts +++ b/src/core/controller/file/__tests__/openFileRelativePath.test.ts @@ -1,12 +1,12 @@ -import { describe, it, beforeEach, afterEach } from "mocha" +import { Controller } from "@core/controller" +import * as openFileIntegration from "@integrations/misc/open-file" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import * as pathUtils from "@utils/path" import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import * as path from "path" import * as sinon from "sinon" import { openFileRelativePath } from "../openFileRelativePath" -import { Controller } from "@core/controller" -import { StringRequest, Empty } from "@shared/proto/cline/common" -import * as openFileIntegration from "@integrations/misc/open-file" -import * as pathUtils from "@utils/path" -import * as path from "path" describe("openFileRelativePath", () => { let sandbox: sinon.SinonSandbox diff --git a/src/core/controller/file/copyToClipboard.ts b/src/core/controller/file/copyToClipboard.ts index b8428004..9181794f 100644 --- a/src/core/controller/file/copyToClipboard.ts +++ b/src/core/controller/file/copyToClipboard.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" import { writeTextToClipboard } from "@/utils/env" +import { Controller } from ".." /** * Copies text to the system clipboard diff --git a/src/core/controller/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 6147de5d..49de429f 100644 --- a/src/core/controller/file/createRuleFile.ts +++ b/src/core/controller/file/createRuleFile.ts @@ -1,12 +1,12 @@ -import { Controller } from ".." -import { RuleFileRequest, RuleFile } from "@shared/proto/cline/file" import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { createRuleFile as createRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" +import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file" import * as path from "path" import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows" -import { getCwd, getDesktopDir } from "@/utils/path" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" +import { getCwd, getDesktopDir } from "@/utils/path" +import { Controller } from ".." import { openFile } from "./openFile" /** diff --git a/src/core/controller/file/deleteRuleFile.ts b/src/core/controller/file/deleteRuleFile.ts index f54cdd45..450b077f 100644 --- a/src/core/controller/file/deleteRuleFile.ts +++ b/src/core/controller/file/deleteRuleFile.ts @@ -1,9 +1,9 @@ import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file" import * as path from "path" -import { Controller } from ".." import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" +import { Controller } from ".." /** * Deletes a rule file from either global or workspace rules directory diff --git a/src/core/controller/file/getRelativePaths.ts b/src/core/controller/file/getRelativePaths.ts index 600ae0d3..5534332a 100644 --- a/src/core/controller/file/getRelativePaths.ts +++ b/src/core/controller/file/getRelativePaths.ts @@ -1,9 +1,9 @@ -import { asRelativePath } from "@/utils/path" import { RelativePaths, RelativePathsRequest } from "@shared/proto/cline/file" import * as path from "path" import { URI } from "vscode-uri" -import { Controller } from ".." import { isDirectory } from "@/utils/fs" +import { asRelativePath } from "@/utils/path" +import { Controller } from ".." /** * Converts a list of URIs to workspace-relative paths diff --git a/src/core/controller/file/ifFileExistsRelativePath.ts b/src/core/controller/file/ifFileExistsRelativePath.ts index 2fe74519..781ce81e 100644 --- a/src/core/controller/file/ifFileExistsRelativePath.ts +++ b/src/core/controller/file/ifFileExistsRelativePath.ts @@ -1,8 +1,8 @@ -import * as path from "path" -import * as fs from "fs" -import { Controller } from ".." -import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" +import { BooleanResponse, StringRequest } from "@shared/proto/cline/common" import { getWorkspacePath } from "@utils/path" +import * as fs from "fs" +import * as path from "path" +import { Controller } from ".." /** * Check if a file exists in the project using a relative path diff --git a/src/core/controller/file/openFile.ts b/src/core/controller/file/openFile.ts index 432483a5..e86cfab5 100644 --- a/src/core/controller/file/openFile.ts +++ b/src/core/controller/file/openFile.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." -import { Empty, StringRequest } from "@shared/proto/cline/common" import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Opens a file in the editor diff --git a/src/core/controller/file/openFileRelativePath.ts b/src/core/controller/file/openFileRelativePath.ts index 20821969..53950dad 100644 --- a/src/core/controller/file/openFileRelativePath.ts +++ b/src/core/controller/file/openFileRelativePath.ts @@ -1,8 +1,8 @@ +import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { getWorkspacePath } from "@utils/path" import * as path from "path" import { Controller } from ".." -import { Empty, StringRequest } from "@shared/proto/cline/common" -import { openFile as openFileIntegration } from "@integrations/misc/open-file" -import { getWorkspacePath } from "@utils/path" /** * Opens a file in the editor by a relative path diff --git a/src/core/controller/file/openFocusChainFile.ts b/src/core/controller/file/openFocusChainFile.ts index d98c3677..66493ca9 100644 --- a/src/core/controller/file/openFocusChainFile.ts +++ b/src/core/controller/file/openFocusChainFile.ts @@ -1,8 +1,8 @@ -import { Controller } from ".." import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { telemetryService } from "../../../services/posthog/PostHogClientProvider" import { Empty, StringRequest } from "../../../shared/proto/cline/common" import { ensureFocusChainFile, extractFocusChainListFromText } from "../../task/focus-chain/file-utils" -import { telemetryService } from "../../../services/posthog/PostHogClientProvider" +import { Controller } from ".." /** * Opens or creates a focus chain checklist markdown file for editing diff --git a/src/core/controller/file/openImage.ts b/src/core/controller/file/openImage.ts index 69a7c18a..4a896778 100644 --- a/src/core/controller/file/openImage.ts +++ b/src/core/controller/file/openImage.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." -import { Empty, StringRequest } from "@shared/proto/cline/common" import { openImage as openImageIntegration } from "@integrations/misc/open-file" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Opens an image in the system viewer diff --git a/src/core/controller/file/openMention.ts b/src/core/controller/file/openMention.ts index 491b4265..d630172b 100644 --- a/src/core/controller/file/openMention.ts +++ b/src/core/controller/file/openMention.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" import { openMention as coreOpenMention } from "../../mentions" +import { Controller } from ".." /** * Opens a mention (file path, problem, terminal, or URL) diff --git a/src/core/controller/file/openTaskHistory.ts b/src/core/controller/file/openTaskHistory.ts index bf7f0858..0335f9aa 100644 --- a/src/core/controller/file/openTaskHistory.ts +++ b/src/core/controller/file/openTaskHistory.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." -import { Empty, StringRequest } from "@shared/proto/cline/common" import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { Empty, StringRequest } from "@shared/proto/cline/common" import path from "path" +import { Controller } from ".." /** * Opens a file in the editor * @param controller The controller instance diff --git a/src/core/controller/file/refreshRules.ts b/src/core/controller/file/refreshRules.ts index b5f38677..69c26b7e 100644 --- a/src/core/controller/file/refreshRules.ts +++ b/src/core/controller/file/refreshRules.ts @@ -1,10 +1,10 @@ -import { EmptyRequest } from "@shared/proto/cline/common" -import { RefreshedRules } from "@shared/proto/cline/file" -import type { Controller } from "../index" import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules" import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows" +import { EmptyRequest } from "@shared/proto/cline/common" +import { RefreshedRules } from "@shared/proto/cline/file" import { getCwd, getDesktopDir } from "@/utils/path" +import type { Controller } from "../index" /** * Refreshes all rule toggles (Cline, External, and Workflows) diff --git a/src/core/controller/file/searchCommits.ts b/src/core/controller/file/searchCommits.ts index f0f64ee0..ea871547 100644 --- a/src/core/controller/file/searchCommits.ts +++ b/src/core/controller/file/searchCommits.ts @@ -1,9 +1,9 @@ -import { Controller } from ".." -import { GitCommits } from "@shared/proto/cline/file" import { StringRequest } from "@shared/proto/cline/common" +import { GitCommits } from "@shared/proto/cline/file" +import { convertGitCommitsToProtoGitCommits } from "@shared/proto-conversions/file/git-commit-conversion" import { searchCommits as searchCommitsUtil } from "@utils/git" import { getWorkspacePath } from "@utils/path" -import { convertGitCommitsToProtoGitCommits } from "@shared/proto-conversions/file/git-commit-conversion" +import { Controller } from ".." /** * Searches for git commits in the workspace repository diff --git a/src/core/controller/file/searchFiles.ts b/src/core/controller/file/searchFiles.ts index 67c6fcd4..43821524 100644 --- a/src/core/controller/file/searchFiles.ts +++ b/src/core/controller/file/searchFiles.ts @@ -1,8 +1,8 @@ -import { Controller } from ".." -import { FileSearchRequest, FileSearchResults, FileSearchType } from "@shared/proto/cline/file" import { searchWorkspaceFiles } from "@services/search/file-search" -import { getWorkspacePath } from "@utils/path" +import { FileSearchRequest, FileSearchResults, FileSearchType } from "@shared/proto/cline/file" import { convertSearchResultsToProtoFileInfos } from "@shared/proto-conversions/file/search-result-conversion" +import { getWorkspacePath } from "@utils/path" +import { Controller } from ".." /** * Searches for files in the workspace with fuzzy matching @@ -24,7 +24,7 @@ export async function searchFiles(_controller: Controller, request: FileSearchRe try { // Map enum to string for the search service - let selectedTypeString: "file" | "folder" | undefined = undefined + let selectedTypeString: "file" | "folder" | undefined if (request.selectedType === FileSearchType.FILE) { selectedTypeString = "file" } else if (request.selectedType === FileSearchType.FOLDER) { diff --git a/src/core/controller/file/selectFiles.ts b/src/core/controller/file/selectFiles.ts index 116b822c..f7810784 100644 --- a/src/core/controller/file/selectFiles.ts +++ b/src/core/controller/file/selectFiles.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." -import { BooleanRequest, StringArrays } from "@shared/proto/cline/common" import { selectFiles as selectFilesIntegration } from "@integrations/misc/process-files" +import { BooleanRequest, StringArrays } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Prompts the user to select images from the file system and returns them as data URLs diff --git a/src/core/controller/file/toggleClineRule.ts b/src/core/controller/file/toggleClineRule.ts index 6e827903..2ed6bb65 100644 --- a/src/core/controller/file/toggleClineRule.ts +++ b/src/core/controller/file/toggleClineRule.ts @@ -1,7 +1,6 @@ -import { ToggleClineRules } from "@shared/proto/cline/file" import type { ToggleClineRuleRequest } from "@shared/proto/cline/file" +import { ToggleClineRules } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** * Toggles a Cline rule (enable or disable) diff --git a/src/core/controller/file/toggleCursorRule.ts b/src/core/controller/file/toggleCursorRule.ts index 99e8ddda..fb1f7a20 100644 --- a/src/core/controller/file/toggleCursorRule.ts +++ b/src/core/controller/file/toggleCursorRule.ts @@ -1,7 +1,6 @@ import type { ToggleCursorRuleRequest } from "@shared/proto/cline/file" import { ClineRulesToggles } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** * Toggles a Cursor rule (enable or disable) diff --git a/src/core/controller/file/toggleWindsurfRule.ts b/src/core/controller/file/toggleWindsurfRule.ts index ff594475..e72680a2 100644 --- a/src/core/controller/file/toggleWindsurfRule.ts +++ b/src/core/controller/file/toggleWindsurfRule.ts @@ -1,7 +1,6 @@ import type { ToggleWindsurfRuleRequest } from "@shared/proto/cline/file" import { ClineRulesToggles } from "@shared/proto/cline/file" import type { Controller } from "../index" -import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules" /** * Toggles a Windsurf rule (enable or disable) diff --git a/src/core/controller/file/toggleWorkflow.ts b/src/core/controller/file/toggleWorkflow.ts index d89e406d..0633acbd 100644 --- a/src/core/controller/file/toggleWorkflow.ts +++ b/src/core/controller/file/toggleWorkflow.ts @@ -1,6 +1,5 @@ +import { ClineRulesToggles, ToggleWorkflowRequest } from "@shared/proto/cline/file" import { Controller } from ".." -import { ToggleWorkflowRequest, ClineRulesToggles } from "@shared/proto/cline/file" -import { ClineRulesToggles as AppClineRulesToggles } from "../../../shared/cline-rules" /** * Toggles a workflow on or off diff --git a/src/core/controller/grpc-handler.test.ts b/src/core/controller/grpc-handler.test.ts index 63f900ec..a4447c9e 100644 --- a/src/core/controller/grpc-handler.test.ts +++ b/src/core/controller/grpc-handler.test.ts @@ -1,10 +1,10 @@ -import { describe, it, beforeEach, afterEach } from "mocha" -import { expect } from "chai" -import * as sinon from "sinon" -import { handleGrpcRequest, handleGrpcRequestCancel, getRequestRegistry } from "./grpc-handler" import { Controller } from "@core/controller" -import { GrpcRequest, GrpcCancel } from "@shared/WebviewMessage" import { serviceHandlers } from "@generated/hosts/vscode/protobus-services" +import { GrpcCancel, GrpcRequest } from "@shared/WebviewMessage" +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import * as sinon from "sinon" +import { getRequestRegistry, handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler" describe("grpc-handler", () => { let sandbox: sinon.SinonSandbox @@ -148,12 +148,14 @@ describe("grpc-handler", () => { // Reset the mock and set up the handler using callsFake mockStreamingHandler.reset() - mockStreamingHandler.callsFake(async (controller: any, message: any, responseStream: any, requestId: string) => { - // Simulate streaming multiple messages - await responseStream({ value: 1 }, false, 0) - await responseStream({ value: 2 }, false, 1) - await responseStream({ value: 3 }, true, 2) // Last message - }) + mockStreamingHandler.callsFake( + async (_controller: any, _message: any, responseStream: any, _requestId: string) => { + // Simulate streaming multiple messages + await responseStream({ value: 1 }, false, 0) + await responseStream({ value: 2 }, false, 1) + await responseStream({ value: 3 }, true, 2) // Last message + }, + ) await handleGrpcRequest(mockController, mockPostMessageToWebview, request) @@ -236,12 +238,14 @@ describe("grpc-handler", () => { // Reset the mock and set up the handler to throw an error after being called mockStreamingHandler.reset() - mockStreamingHandler.callsFake(async (controller: any, message: any, responseStream: any, requestId: string) => { - // Send first message successfully - await responseStream({ value: "first" }, false, 0) - // Throw an error - throw new Error("Mid-stream error") - }) + mockStreamingHandler.callsFake( + async (_controller: any, _message: any, responseStream: any, _requestId: string) => { + // Send first message successfully + await responseStream({ value: "first" }, false, 0) + // Throw an error + throw new Error("Mid-stream error") + }, + ) await handleGrpcRequest(mockController, mockPostMessageToWebview, request) diff --git a/src/core/controller/grpc-handler.ts b/src/core/controller/grpc-handler.ts index 9e8474f0..e2304176 100644 --- a/src/core/controller/grpc-handler.ts +++ b/src/core/controller/grpc-handler.ts @@ -1,8 +1,8 @@ -import { Controller } from "./index" import { serviceHandlers } from "@generated/hosts/vscode/protobus-services" -import { GrpcRequestRegistry } from "./grpc-request-registry" -import { GrpcCancel, GrpcRequest } from "@/shared/WebviewMessage" import { ExtensionMessage } from "@/shared/ExtensionMessage" +import { GrpcCancel, GrpcRequest } from "@/shared/WebviewMessage" +import { GrpcRequestRegistry } from "./grpc-request-registry" +import { Controller } from "./index" /** * Type definition for a streaming response handler diff --git a/src/core/controller/grpc-service.ts b/src/core/controller/grpc-service.ts index 67860249..4de22715 100644 --- a/src/core/controller/grpc-service.ts +++ b/src/core/controller/grpc-service.ts @@ -1,5 +1,5 @@ -import { Controller } from "./index" import { StreamingResponseHandler } from "./grpc-handler" +import { Controller } from "./index" /** * Generic type for service method handlers diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 5a8ca704..5e158ac5 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -1,10 +1,3 @@ -import { clineEnvConfig } from "@/config" -import { HostProvider } from "@/hosts/host-provider" -import { AuthService } from "@/services/auth/AuthService" -import { PostHogClientProvider, telemetryService } from "@/services/posthog/PostHogClientProvider" -import { ShowMessageType } from "@/shared/proto/host/window" -import { getLatestAnnouncementId } from "@/utils/announcements" -import { getCwd, getDesktopDir } from "@/utils/path" import { Anthropic } from "@anthropic-ai/sdk" import { buildApiHandler } from "@core/api" import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration" @@ -25,6 +18,13 @@ import fs from "fs/promises" import pWaitFor from "p-wait-for" import * as path from "path" import * as vscode from "vscode" +import { clineEnvConfig } from "@/config" +import { HostProvider } from "@/hosts/host-provider" +import { AuthService } from "@/services/auth/AuthService" +import { PostHogClientProvider, telemetryService } from "@/services/posthog/PostHogClientProvider" +import { ShowMessageType } from "@/shared/proto/host/window" +import { getLatestAnnouncementId } from "@/utils/announcements" +import { getCwd, getDesktopDir } from "@/utils/path" import { CacheService, PersistenceErrorEvent } from "../storage/CacheService" import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk" import { Task } from "../task" @@ -142,7 +142,7 @@ export class Controller { type: ShowMessageType.INFORMATION, message: "Successfully logged out of Cline", }) - } catch (error) { + } catch (_error) { HostProvider.window.showMessage({ type: ShowMessageType.INFORMATION, message: "Logout failed", diff --git a/src/core/controller/mcp/addRemoteMcpServer.ts b/src/core/controller/mcp/addRemoteMcpServer.ts index 83d468f8..fc9037f3 100644 --- a/src/core/controller/mcp/addRemoteMcpServer.ts +++ b/src/core/controller/mcp/addRemoteMcpServer.ts @@ -1,6 +1,6 @@ -import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion" import type { AddRemoteMcpServerRequest } from "@shared/proto/cline/mcp" import { McpServers } from "@shared/proto/cline/mcp" +import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion" import type { Controller } from "../index" /** diff --git a/src/core/controller/mcp/deleteMcpServer.ts b/src/core/controller/mcp/deleteMcpServer.ts index db0a6fe6..b036d897 100644 --- a/src/core/controller/mcp/deleteMcpServer.ts +++ b/src/core/controller/mcp/deleteMcpServer.ts @@ -1,7 +1,7 @@ -import type { Controller } from "../index" +import { StringRequest } from "@shared/proto/cline/common" import { McpServers } from "@shared/proto/cline/mcp" import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion" -import { StringRequest } from "@shared/proto/cline/common" +import type { Controller } from "../index" /** * Deletes an MCP server diff --git a/src/core/controller/mcp/downloadMcp.ts b/src/core/controller/mcp/downloadMcp.ts index 13863f00..2b055be1 100644 --- a/src/core/controller/mcp/downloadMcp.ts +++ b/src/core/controller/mcp/downloadMcp.ts @@ -1,10 +1,10 @@ -import { Controller } from ".." +import { McpServer } from "@shared/mcp" import { StringRequest } from "@shared/proto/cline/common" import { McpDownloadResponse } from "@shared/proto/cline/mcp" -import { McpServer } from "@shared/mcp" import axios from "axios" -import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" import { clineEnvConfig } from "@/config" +import { Controller } from ".." +import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" /** * Download an MCP server from the marketplace diff --git a/src/core/controller/mcp/getLatestMcpServers.ts b/src/core/controller/mcp/getLatestMcpServers.ts index baa79500..468c8aca 100644 --- a/src/core/controller/mcp/getLatestMcpServers.ts +++ b/src/core/controller/mcp/getLatestMcpServers.ts @@ -1,7 +1,7 @@ import type { Empty } from "@shared/proto/cline/common" import { McpServers } from "@shared/proto/cline/mcp" -import type { Controller } from "../index" import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion" +import type { Controller } from "../index" /** * RPC handler for getting the latest MCP servers diff --git a/src/core/controller/mcp/openMcpSettings.ts b/src/core/controller/mcp/openMcpSettings.ts index 4a1a7093..fab5abc4 100644 --- a/src/core/controller/mcp/openMcpSettings.ts +++ b/src/core/controller/mcp/openMcpSettings.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." -import { Empty, EmptyRequest } from "@shared/proto/cline/common" import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Opens the MCP settings file in the editor diff --git a/src/core/controller/mcp/restartMcpServer.ts b/src/core/controller/mcp/restartMcpServer.ts index 27178112..5f8e9e55 100644 --- a/src/core/controller/mcp/restartMcpServer.ts +++ b/src/core/controller/mcp/restartMcpServer.ts @@ -1,7 +1,7 @@ -import { McpServers } from "@shared/proto/cline/mcp" -import type { Controller } from "../index" -import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" import { StringRequest } from "@shared/proto/cline/common" +import { McpServers } from "@shared/proto/cline/mcp" +import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" +import type { Controller } from "../index" /** * Restarts an MCP server connection diff --git a/src/core/controller/mcp/subscribeToMcpMarketplaceCatalog.ts b/src/core/controller/mcp/subscribeToMcpMarketplaceCatalog.ts index 9027a5b8..af646f86 100644 --- a/src/core/controller/mcp/subscribeToMcpMarketplaceCatalog.ts +++ b/src/core/controller/mcp/subscribeToMcpMarketplaceCatalog.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" import { McpMarketplaceCatalog } from "@shared/proto/cline/mcp" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active subscriptions const activeMcpMarketplaceSubscriptions = new Set>() diff --git a/src/core/controller/mcp/subscribeToMcpServers.ts b/src/core/controller/mcp/subscribeToMcpServers.ts index 077c6962..15ac7768 100644 --- a/src/core/controller/mcp/subscribeToMcpServers.ts +++ b/src/core/controller/mcp/subscribeToMcpServers.ts @@ -1,8 +1,8 @@ -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" import { McpServers } from "@shared/proto/cline/mcp" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active subscriptions const activeMcpServersSubscriptions = new Set>() diff --git a/src/core/controller/mcp/toggleMcpServer.ts b/src/core/controller/mcp/toggleMcpServer.ts index b7846e90..c9475820 100644 --- a/src/core/controller/mcp/toggleMcpServer.ts +++ b/src/core/controller/mcp/toggleMcpServer.ts @@ -1,7 +1,7 @@ import type { ToggleMcpServerRequest } from "@shared/proto/cline/mcp" import { McpServers } from "@shared/proto/cline/mcp" -import type { Controller } from "../index" import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion" +import type { Controller } from "../index" /** * Toggles an MCP server's enabled/disabled status diff --git a/src/core/controller/mcp/toggleToolAutoApprove.ts b/src/core/controller/mcp/toggleToolAutoApprove.ts index f3fe528f..40627053 100644 --- a/src/core/controller/mcp/toggleToolAutoApprove.ts +++ b/src/core/controller/mcp/toggleToolAutoApprove.ts @@ -1,7 +1,7 @@ import type { ToggleToolAutoApproveRequest } from "@shared/proto/cline/mcp" import { McpServers } from "@shared/proto/cline/mcp" -import type { Controller } from "../index" import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" +import type { Controller } from "../index" /** * Toggles auto-approve setting for MCP server tools diff --git a/src/core/controller/mcp/updateMcpTimeout.ts b/src/core/controller/mcp/updateMcpTimeout.ts index f5b3db31..45d23c4f 100644 --- a/src/core/controller/mcp/updateMcpTimeout.ts +++ b/src/core/controller/mcp/updateMcpTimeout.ts @@ -1,6 +1,6 @@ +import { McpServers, UpdateMcpTimeoutRequest } from "@shared/proto/cline/mcp" import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion" import { Controller } from ".." -import { UpdateMcpTimeoutRequest, McpServers } from "@shared/proto/cline/mcp" /** * Updates the timeout configuration for an MCP server. diff --git a/src/core/controller/models/getOllamaModels.ts b/src/core/controller/models/getOllamaModels.ts index 21a3c206..e525c5fe 100644 --- a/src/core/controller/models/getOllamaModels.ts +++ b/src/core/controller/models/getOllamaModels.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { StringArray, StringRequest } from "@shared/proto/cline/common" import axios from "axios" +import { Controller } from ".." /** * Fetches available models from Ollama @@ -8,9 +8,9 @@ import axios from "axios" * @param request The request containing the base URL (optional) * @returns Array of model names */ -export async function getOllamaModels(controller: Controller, request: StringRequest): Promise { +export async function getOllamaModels(_controller: Controller, request: StringRequest): Promise { try { - let baseUrl = request.value || "http://localhost:11434" + const baseUrl = request.value || "http://localhost:11434" if (!URL.canParse(baseUrl)) { return StringArray.create({ values: [] }) @@ -21,7 +21,7 @@ export async function getOllamaModels(controller: Controller, request: StringReq const models = [...new Set(modelsArray)].sort() return StringArray.create({ values: models }) - } catch (error) { + } catch (_error) { return StringArray.create({ values: [] }) } } diff --git a/src/core/controller/models/getVsCodeLmModels.ts b/src/core/controller/models/getVsCodeLmModels.ts index eb56b97b..149f3cee 100644 --- a/src/core/controller/models/getVsCodeLmModels.ts +++ b/src/core/controller/models/getVsCodeLmModels.ts @@ -1,8 +1,8 @@ -import { Controller } from ".." import { EmptyRequest } from "@shared/proto/cline/common" import { VsCodeLmModelsArray } from "@shared/proto/cline/models" import * as vscode from "vscode" import { convertVsCodeNativeModelsToProtoModels } from "../../../shared/proto-conversions/models/vscode-lm-models-conversion" +import { Controller } from ".." /** * Fetches available models from VS Code LM API @@ -10,7 +10,7 @@ import { convertVsCodeNativeModelsToProtoModels } from "../../../shared/proto-co * @param request Empty request * @returns Array of VS Code LM models */ -export async function getVsCodeLmModels(controller: Controller, request: EmptyRequest): Promise { +export async function getVsCodeLmModels(_controller: Controller, _request: EmptyRequest): Promise { try { const models = await vscode.lm.selectChatModels({}) diff --git a/src/core/controller/models/refreshBasetenModels.ts b/src/core/controller/models/refreshBasetenModels.ts index 565ffc20..f5e292a2 100644 --- a/src/core/controller/models/refreshBasetenModels.ts +++ b/src/core/controller/models/refreshBasetenModels.ts @@ -1,12 +1,12 @@ -import { Controller } from ".." +import { GlobalFileNames } from "@core/storage/disk" import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import { basetenModels } from "../../../shared/api" -import axios from "axios" -import path from "path" -import fs from "fs/promises" import { fileExistsAtPath } from "@utils/fs" -import { GlobalFileNames } from "@core/storage/disk" +import axios from "axios" +import fs from "fs/promises" +import path from "path" +import { basetenModels } from "../../../shared/api" +import { Controller } from ".." /** * Refreshes the Baseten models and returns the updated model list @@ -16,7 +16,7 @@ import { GlobalFileNames } from "@core/storage/disk" */ export async function refreshBasetenModels( controller: Controller, - request: EmptyRequest, + _request: EmptyRequest, ): Promise { console.log("=== refreshBasetenModels called ===") const basetenModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.basetenModels) @@ -24,7 +24,7 @@ export async function refreshBasetenModels( // Get the Baseten API key from the controller's state const basetenApiKey = controller.cacheService.getSecretKey("basetenApiKey") - let models: Record> = {} + const models: Record> = {} try { if (!basetenApiKey) { console.log("No Baseten API key found, using static models as fallback") diff --git a/src/core/controller/models/refreshGroqModels.ts b/src/core/controller/models/refreshGroqModels.ts index a2a8b919..60ed902c 100644 --- a/src/core/controller/models/refreshGroqModels.ts +++ b/src/core/controller/models/refreshGroqModels.ts @@ -1,13 +1,13 @@ -import { Controller } from ".." +import { GlobalFileNames } from "@core/storage/disk" import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import { groqModels } from "../../../shared/api" -import axios from "axios" -import path from "path" -import fs from "fs/promises" import { fileExistsAtPath } from "@utils/fs" -import { GlobalFileNames } from "@core/storage/disk" +import axios from "axios" +import fs from "fs/promises" +import path from "path" import { telemetryService } from "@/services/posthog/PostHogClientProvider" +import { groqModels } from "../../../shared/api" +import { Controller } from ".." /** * Refreshes the Groq models and returns the updated model list @@ -15,7 +15,7 @@ import { telemetryService } from "@/services/posthog/PostHogClientProvider" * @param request Empty request object * @returns Response containing the Groq models */ -export async function refreshGroqModels(controller: Controller, request: EmptyRequest): Promise { +export async function refreshGroqModels(controller: Controller, _request: EmptyRequest): Promise { const groqModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.groqModels) const groqApiKey = controller.cacheService.getSecretKey("groqApiKey") diff --git a/src/core/controller/models/refreshHuggingFaceModels.ts b/src/core/controller/models/refreshHuggingFaceModels.ts index 181123bb..c098c505 100644 --- a/src/core/controller/models/refreshHuggingFaceModels.ts +++ b/src/core/controller/models/refreshHuggingFaceModels.ts @@ -1,12 +1,11 @@ -import { Controller } from ".." +import { huggingFaceModels } from "@shared/api" import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import axios from "axios" -import path from "path" -import fs from "fs/promises" import { fileExistsAtPath } from "@utils/fs" -import { GlobalFileNames } from "@core/storage/disk" -import { huggingFaceModels } from "@shared/api" +import axios from "axios" +import fs from "fs/promises" +import path from "path" +import { Controller } from ".." /** * Ensures the cache directory exists and returns its path @@ -15,7 +14,7 @@ async function ensureCacheDirectoryExists(controller: Controller): Promise { +export async function refreshOpenAiModels(_controller: Controller, request: OpenAiModelsRequest): Promise { try { if (!request.baseUrl) { return StringArray.create({ values: [] }) diff --git a/src/core/controller/models/refreshOpenRouterModels.ts b/src/core/controller/models/refreshOpenRouterModels.ts index a73bf832..df5eb45e 100644 --- a/src/core/controller/models/refreshOpenRouterModels.ts +++ b/src/core/controller/models/refreshOpenRouterModels.ts @@ -1,13 +1,13 @@ -import { Controller } from ".." +import { GlobalFileNames } from "@core/storage/disk" import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" -import axios from "axios" -import path from "path" -import fs from "fs/promises" import { fileExistsAtPath } from "@utils/fs" -import { GlobalFileNames } from "@core/storage/disk" -import { CLAUDE_SONNET_4_1M_TIERS, openRouterClaudeSonnet41mModelId } from "@/shared/api" +import axios from "axios" import cloneDeep from "clone-deep" +import fs from "fs/promises" +import path from "path" +import { CLAUDE_SONNET_4_1M_TIERS, openRouterClaudeSonnet41mModelId } from "@/shared/api" +import { Controller } from ".." /** * Refreshes the OpenRouter models and returns the updated model list diff --git a/src/core/controller/models/refreshRequestyModels.ts b/src/core/controller/models/refreshRequestyModels.ts index 3176576a..d0a146d5 100644 --- a/src/core/controller/models/refreshRequestyModels.ts +++ b/src/core/controller/models/refreshRequestyModels.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models" import axios from "axios" +import { Controller } from ".." /** * Refreshes the Requesty models and returns the updated model list @@ -17,7 +17,7 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ return undefined } - let models: Record = {} + const models: Record = {} try { const apiKey = controller.cacheService.getSecretKey("requestyApiKey") const headers = { diff --git a/src/core/controller/models/subscribeToOpenRouterModels.ts b/src/core/controller/models/subscribeToOpenRouterModels.ts index dd1a30b6..89ab5146 100644 --- a/src/core/controller/models/subscribeToOpenRouterModels.ts +++ b/src/core/controller/models/subscribeToOpenRouterModels.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active OpenRouter models subscriptions const activeOpenRouterModelsSubscriptions = new Set>() diff --git a/src/core/controller/models/updateApiConfigurationProto.ts b/src/core/controller/models/updateApiConfigurationProto.ts index 99d98368..daf7627f 100644 --- a/src/core/controller/models/updateApiConfigurationProto.ts +++ b/src/core/controller/models/updateApiConfigurationProto.ts @@ -1,8 +1,8 @@ -import type { Controller } from "../index" +import { buildApiHandler } from "@core/api" import { Empty } from "@shared/proto/cline/common" import { UpdateApiConfigurationRequest } from "@shared/proto/cline/models" -import { buildApiHandler } from "@core/api" import { convertProtoToApiConfiguration } from "@shared/proto-conversions/models/api-configuration-conversion" +import type { Controller } from "../index" /** * Updates API configuration diff --git a/src/core/controller/slash/condense.ts b/src/core/controller/slash/condense.ts index 85bca920..99d805b5 100644 --- a/src/core/controller/slash/condense.ts +++ b/src/core/controller/slash/condense.ts @@ -1,10 +1,10 @@ +import { Empty, StringRequest } from "@shared/proto/cline/common" import { Controller } from ".." -import { StringRequest, Empty } from "@shared/proto/cline/common" /** * Command slash command logic */ -export async function condense(controller: Controller, request: StringRequest): Promise { +export async function condense(controller: Controller, _request: StringRequest): Promise { await controller.task?.handleWebviewAskResponse("yesButtonClicked") return Empty.create() } diff --git a/src/core/controller/slash/reportBug.ts b/src/core/controller/slash/reportBug.ts index 700259e2..964acf14 100644 --- a/src/core/controller/slash/reportBug.ts +++ b/src/core/controller/slash/reportBug.ts @@ -1,10 +1,10 @@ +import { Empty, StringRequest } from "@shared/proto/cline/common" import { Controller } from ".." -import { StringRequest, Empty } from "@shared/proto/cline/common" /** * Report bug slash command logic */ -export async function reportBug(controller: Controller, request: StringRequest): Promise { +export async function reportBug(controller: Controller, _request: StringRequest): Promise { await controller.task?.handleWebviewAskResponse("yesButtonClicked") return Empty.create() } diff --git a/src/core/controller/state/getAvailableTerminalProfiles.ts b/src/core/controller/state/getAvailableTerminalProfiles.ts index 302dfb44..61a0e456 100644 --- a/src/core/controller/state/getAvailableTerminalProfiles.ts +++ b/src/core/controller/state/getAvailableTerminalProfiles.ts @@ -1,10 +1,10 @@ -import { Controller } from "../index" import * as proto from "@/shared/proto" import { getAvailableTerminalProfiles as getTerminalProfilesFromShell } from "../../../utils/shell" +import { Controller } from "../index" export async function getAvailableTerminalProfiles( - controller: Controller, - request: proto.cline.EmptyRequest, + _controller: Controller, + _request: proto.cline.EmptyRequest, ): Promise { const profiles = getTerminalProfilesFromShell() diff --git a/src/core/controller/state/getLatestState.ts b/src/core/controller/state/getLatestState.ts index 8db354db..b1d27885 100644 --- a/src/core/controller/state/getLatestState.ts +++ b/src/core/controller/state/getLatestState.ts @@ -1,7 +1,6 @@ -import * as vscode from "vscode" -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" import { State } from "@shared/proto/cline/state" +import { Controller } from "../index" /** * Get the latest extension state diff --git a/src/core/controller/state/resetState.ts b/src/core/controller/state/resetState.ts index fc9bb445..e765676f 100644 --- a/src/core/controller/state/resetState.ts +++ b/src/core/controller/state/resetState.ts @@ -1,10 +1,10 @@ -import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" import { ResetStateRequest } from "@shared/proto/cline/state" -import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" -import { ShowMessageType } from "@/shared/proto/host/window" -import { HostProvider } from "@/hosts/host-provider" import { resetGlobalState, resetWorkspaceState } from "@/core/storage/utils/state-helpers" +import { HostProvider } from "@/hosts/host-provider" +import { ShowMessageType } from "@/shared/proto/host/window" +import { Controller } from ".." +import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" /** * Resets the extension state to its defaults diff --git a/src/core/controller/state/subscribeToState.ts b/src/core/controller/state/subscribeToState.ts index a36f4715..e7c8894d 100644 --- a/src/core/controller/state/subscribeToState.ts +++ b/src/core/controller/state/subscribeToState.ts @@ -1,9 +1,8 @@ -import * as vscode from "vscode" -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" import { State } from "@shared/proto/cline/state" import { ExtensionState } from "@/shared/ExtensionMessage" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active state subscriptions by controller ID const activeStateSubscriptions = new Map>() diff --git a/src/core/controller/state/toggleFavoriteModel.ts b/src/core/controller/state/toggleFavoriteModel.ts index 5ca3b09e..ef41ad90 100644 --- a/src/core/controller/state/toggleFavoriteModel.ts +++ b/src/core/controller/state/toggleFavoriteModel.ts @@ -1,6 +1,6 @@ import { telemetryService } from "@services/posthog/PostHogClientProvider" -import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Toggles a model's favorite status diff --git a/src/core/controller/state/togglePlanActModeProto.ts b/src/core/controller/state/togglePlanActModeProto.ts index 3d4bf7d9..dbfd997f 100644 --- a/src/core/controller/state/togglePlanActModeProto.ts +++ b/src/core/controller/state/togglePlanActModeProto.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." import { Boolean } from "@shared/proto/cline/common" -import { TogglePlanActModeRequest, PlanActMode } from "@shared/proto/cline/state" +import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/cline/state" import { Mode } from "@shared/storage/types" +import { Controller } from ".." /** * Toggles between Plan and Act modes diff --git a/src/core/controller/state/updateAutoApprovalSettings.ts b/src/core/controller/state/updateAutoApprovalSettings.ts index 842508ae..cf5f5003 100644 --- a/src/core/controller/state/updateAutoApprovalSettings.ts +++ b/src/core/controller/state/updateAutoApprovalSettings.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." -import { AutoApprovalSettingsRequest } from "@shared/proto/cline/state" import { Empty } from "@shared/proto/cline/common" +import { AutoApprovalSettingsRequest } from "@shared/proto/cline/state" import { convertProtoToAutoApprovalSettings } from "../../../shared/proto-conversions/models/auto-approval-settings-conversion" +import { Controller } from ".." /** * Updates the auto approval settings diff --git a/src/core/controller/state/updateDefaultTerminalProfile.ts b/src/core/controller/state/updateDefaultTerminalProfile.ts index 89da59cd..6aa9757c 100644 --- a/src/core/controller/state/updateDefaultTerminalProfile.ts +++ b/src/core/controller/state/updateDefaultTerminalProfile.ts @@ -1,8 +1,8 @@ -import { Controller } from "../index" -import * as proto from "@/shared/proto" -import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" import { HostProvider } from "@/hosts/host-provider" +import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" +import * as proto from "@/shared/proto" import { ShowMessageType } from "@/shared/proto/host/window" +import { Controller } from "../index" export async function updateDefaultTerminalProfile( controller: Controller, diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index af8c23aa..9178e685 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -1,18 +1,17 @@ -import { Controller } from ".." +import { buildApiHandler } from "@core/api" import { Empty } from "@shared/proto/cline/common" import { PlanActMode, - UpdateSettingsRequest, - OpenaiReasoningEffort as ProtoOpenaiReasoningEffort, McpDisplayMode as ProtoMcpDisplayMode, + OpenaiReasoningEffort as ProtoOpenaiReasoningEffort, + UpdateSettingsRequest, } from "@shared/proto/cline/state" -import { buildApiHandler } from "@core/api" import { convertProtoApiConfigurationToApiConfiguration } from "@shared/proto-conversions/state/settings-conversion" -import { TelemetrySetting } from "@shared/TelemetrySetting" import { OpenaiReasoningEffort } from "@shared/storage/types" +import { TelemetrySetting } from "@shared/TelemetrySetting" import { McpDisplayMode } from "@/shared/McpDisplayMode" import { telemetryService } from "../../../services/posthog/PostHogClientProvider" -import { FocusChainSettings } from "@shared/FocusChainSettings" +import { Controller } from ".." /** * Updates multiple extension settings in a single request diff --git a/src/core/controller/state/updateTelemetrySetting.ts b/src/core/controller/state/updateTelemetrySetting.ts index 41a5c6c2..d04db82b 100644 --- a/src/core/controller/state/updateTelemetrySetting.ts +++ b/src/core/controller/state/updateTelemetrySetting.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" import { TelemetrySettingRequest } from "@shared/proto/cline/state" import { convertProtoTelemetrySettingToDomain } from "../../../shared/proto-conversions/state/telemetry-setting-conversion" +import { Controller } from ".." /** * Updates the telemetry setting diff --git a/src/core/controller/state/updateTerminalConnectionTimeout.ts b/src/core/controller/state/updateTerminalConnectionTimeout.ts index 9a4eb58e..6c29d545 100644 --- a/src/core/controller/state/updateTerminalConnectionTimeout.ts +++ b/src/core/controller/state/updateTerminalConnectionTimeout.ts @@ -1,5 +1,5 @@ -import { Controller } from "../index" import { UpdateTerminalConnectionTimeoutRequest, UpdateTerminalConnectionTimeoutResponse } from "@shared/proto/cline/state" +import { Controller } from "../index" export async function updateTerminalConnectionTimeout( controller: Controller, diff --git a/src/core/controller/state/updateTerminalReuseEnabled.ts b/src/core/controller/state/updateTerminalReuseEnabled.ts index 16b9dac9..a57ba473 100644 --- a/src/core/controller/state/updateTerminalReuseEnabled.ts +++ b/src/core/controller/state/updateTerminalReuseEnabled.ts @@ -1,5 +1,5 @@ -import { Controller } from "../index" import * as proto from "@/shared/proto" +import { Controller } from "../index" export async function updateTerminalReuseEnabled( controller: Controller, diff --git a/src/core/controller/task/askResponse.ts b/src/core/controller/task/askResponse.ts index 31cf5711..daae60b6 100644 --- a/src/core/controller/task/askResponse.ts +++ b/src/core/controller/task/askResponse.ts @@ -1,7 +1,7 @@ -import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" import { AskResponseRequest } from "@shared/proto/cline/task" import { ClineAskResponse } from "../../../shared/WebviewMessage" +import { Controller } from ".." /** * Handles a response from the webview for a previous ask operation diff --git a/src/core/controller/task/cancelTask.ts b/src/core/controller/task/cancelTask.ts index 4855ab1b..c152efa7 100644 --- a/src/core/controller/task/cancelTask.ts +++ b/src/core/controller/task/cancelTask.ts @@ -1,5 +1,5 @@ -import { Controller } from ".." import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Cancel the currently running task diff --git a/src/core/controller/task/clearTask.ts b/src/core/controller/task/clearTask.ts index d771e9dd..fd3433c0 100644 --- a/src/core/controller/task/clearTask.ts +++ b/src/core/controller/task/clearTask.ts @@ -1,5 +1,5 @@ -import { Controller } from ".." import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Clears the current task diff --git a/src/core/controller/task/deleteAllTaskHistory.ts b/src/core/controller/task/deleteAllTaskHistory.ts index 6267035f..717ba135 100644 --- a/src/core/controller/task/deleteAllTaskHistory.ts +++ b/src/core/controller/task/deleteAllTaskHistory.ts @@ -1,11 +1,10 @@ -import path from "path" -import fs from "fs/promises" -import { Controller } from ".." import { DeleteAllTaskHistoryCount } from "@shared/proto/cline/task" -import { fileExistsAtPath } from "../../../utils/fs" -import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import fs from "fs/promises" +import path from "path" import { HostProvider } from "@/hosts/host-provider" -import { HistoryItem } from "@/shared/HistoryItem" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { fileExistsAtPath } from "../../../utils/fs" +import { Controller } from ".." /** * Deletes all task history, with an option to preserve favorites diff --git a/src/core/controller/task/deleteTasksWithIds.ts b/src/core/controller/task/deleteTasksWithIds.ts index e565d231..fc5f5bfc 100644 --- a/src/core/controller/task/deleteTasksWithIds.ts +++ b/src/core/controller/task/deleteTasksWithIds.ts @@ -1,10 +1,10 @@ -import path from "path" -import fs from "fs/promises" -import { Controller } from ".." import { Empty, StringArrayRequest } from "@shared/proto/cline/common" -import { fileExistsAtPath } from "../../../utils/fs" +import fs from "fs/promises" +import path from "path" import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { ShowMessageType } from "@/shared/proto/host/window" +import { fileExistsAtPath } from "../../../utils/fs" +import { Controller } from ".." /** * Deletes tasks with the specified IDs diff --git a/src/core/controller/task/executeQuickWin.ts b/src/core/controller/task/executeQuickWin.ts index e17de632..2c1b4032 100644 --- a/src/core/controller/task/executeQuickWin.ts +++ b/src/core/controller/task/executeQuickWin.ts @@ -1,5 +1,5 @@ -import { ExecuteQuickWinRequest } from "@shared/proto/cline/task" import { Empty } from "@shared/proto/cline/common" +import { ExecuteQuickWinRequest } from "@shared/proto/cline/task" import type { Controller } from "../index" /** diff --git a/src/core/controller/task/exportTaskWithId.ts b/src/core/controller/task/exportTaskWithId.ts index b7231f2a..1bfb2061 100644 --- a/src/core/controller/task/exportTaskWithId.ts +++ b/src/core/controller/task/exportTaskWithId.ts @@ -1,5 +1,5 @@ -import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Exports a task with the given ID to markdown diff --git a/src/core/controller/task/getTaskHistory.ts b/src/core/controller/task/getTaskHistory.ts index fe0da1ac..7f433ad4 100644 --- a/src/core/controller/task/getTaskHistory.ts +++ b/src/core/controller/task/getTaskHistory.ts @@ -1,7 +1,6 @@ -import { Controller } from ".." import { GetTaskHistoryRequest, TaskHistoryArray } from "@shared/proto/cline/task" -import { getWorkspacePath, arePathsEqual } from "../../../utils/path" -import { HistoryItem } from "@/shared/HistoryItem" +import { arePathsEqual, getWorkspacePath } from "../../../utils/path" +import { Controller } from ".." /** * Gets filtered task history diff --git a/src/core/controller/task/getTotalTasksSize.ts b/src/core/controller/task/getTotalTasksSize.ts index a8f336d2..b7223f6c 100644 --- a/src/core/controller/task/getTotalTasksSize.ts +++ b/src/core/controller/task/getTotalTasksSize.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { EmptyRequest, Int64 } from "@shared/proto/cline/common" import { getTotalTasksSize as calculateTotalTasksSize } from "../../../utils/storage" +import { Controller } from ".." /** * Gets the total size of all tasks including task data and checkpoints diff --git a/src/core/controller/task/newTask.ts b/src/core/controller/task/newTask.ts index 0eabc8ce..f2e35a67 100644 --- a/src/core/controller/task/newTask.ts +++ b/src/core/controller/task/newTask.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { Empty } from "@shared/proto/cline/common" import { NewTaskRequest } from "@shared/proto/cline/task" +import { Controller } from ".." /** * Creates a new task with the given text and optional images diff --git a/src/core/controller/task/showTaskWithId.ts b/src/core/controller/task/showTaskWithId.ts index f391ca6f..db4908dd 100644 --- a/src/core/controller/task/showTaskWithId.ts +++ b/src/core/controller/task/showTaskWithId.ts @@ -1,8 +1,7 @@ -import { Controller } from ".." import { StringRequest } from "@shared/proto/cline/common" import { TaskResponse } from "@shared/proto/cline/task" +import { Controller } from ".." import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" -import { HistoryItem } from "@/shared/HistoryItem" /** * Shows a task with the specified ID diff --git a/src/core/controller/task/taskCompletionViewChanges.ts b/src/core/controller/task/taskCompletionViewChanges.ts index 4fcd5d46..df82cba4 100644 --- a/src/core/controller/task/taskCompletionViewChanges.ts +++ b/src/core/controller/task/taskCompletionViewChanges.ts @@ -1,6 +1,5 @@ +import { Empty, Int64Request } from "@shared/proto/cline/common" import { Controller } from ".." -import { Empty } from "@shared/proto/cline/common" -import { Int64Request } from "@shared/proto/cline/common" /** * Shows task completion changes in a diff view diff --git a/src/core/controller/task/taskFeedback.ts b/src/core/controller/task/taskFeedback.ts index 52a329c8..729b8a3e 100644 --- a/src/core/controller/task/taskFeedback.ts +++ b/src/core/controller/task/taskFeedback.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." -import { Empty, StringRequest } from "@shared/proto/cline/common" import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { Controller } from ".." /** * Handles task feedback submission (thumbs up/down) diff --git a/src/core/controller/task/toggleTaskFavorite.ts b/src/core/controller/task/toggleTaskFavorite.ts index c59385a6..6607ffff 100644 --- a/src/core/controller/task/toggleTaskFavorite.ts +++ b/src/core/controller/task/toggleTaskFavorite.ts @@ -1,7 +1,6 @@ -import { HistoryItem } from "@/shared/HistoryItem" -import { Controller } from "../" import { Empty } from "@shared/proto/cline/common" import { TaskFavoriteRequest } from "@shared/proto/cline/task" +import { Controller } from "../" export async function toggleTaskFavorite(controller: Controller, request: TaskFavoriteRequest): Promise { if (!request.taskId || request.isFavorited === undefined) { diff --git a/src/core/controller/ui/getWebviewHtml.ts b/src/core/controller/ui/getWebviewHtml.ts index 0cab0e18..dcc453a6 100644 --- a/src/core/controller/ui/getWebviewHtml.ts +++ b/src/core/controller/ui/getWebviewHtml.ts @@ -1,5 +1,5 @@ -import { WebviewProvider } from "@/core/webview" import { EmptyRequest, String } from "@shared/proto/cline/common" +import { WebviewProvider } from "@/core/webview" import type { Controller } from "../index" /** diff --git a/src/core/controller/ui/initializeWebview.ts b/src/core/controller/ui/initializeWebview.ts index bf683525..1be1cbff 100644 --- a/src/core/controller/ui/initializeWebview.ts +++ b/src/core/controller/ui/initializeWebview.ts @@ -1,15 +1,13 @@ -import type { Controller } from "../index" -import { EmptyRequest, Empty } from "@shared/proto/cline/common" - -import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels" -import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" -import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models" import { McpMarketplaceCatalog } from "@shared/mcp" -import { refreshOpenRouterModels } from "../models/refreshOpenRouterModels" -import { refreshGroqModels } from "../models/refreshGroqModels" +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models" +import { featureFlagsService, telemetryService } from "@/services/posthog/PostHogClientProvider" +import type { Controller } from "../index" +import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog" import { refreshBasetenModels } from "../models/refreshBasetenModels" -import { featureFlagsService } from "@/services/posthog/PostHogClientProvider" +import { refreshGroqModels } from "../models/refreshGroqModels" +import { refreshOpenRouterModels } from "../models/refreshOpenRouterModels" +import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels" /** * Initialize webview when it launches @@ -17,7 +15,7 @@ import { featureFlagsService } from "@/services/posthog/PostHogClientProvider" * @param request The empty request * @returns Empty response */ -export async function initializeWebview(controller: Controller, request: EmptyRequest): Promise { +export async function initializeWebview(controller: Controller, _request: EmptyRequest): Promise { try { // Post last cached models in case the call to endpoint fails controller.readOpenRouterModels().then((openRouterModels) => { diff --git a/src/core/controller/ui/onDidShowAnnouncement.ts b/src/core/controller/ui/onDidShowAnnouncement.ts index de8d2ace..3f51baf5 100644 --- a/src/core/controller/ui/onDidShowAnnouncement.ts +++ b/src/core/controller/ui/onDidShowAnnouncement.ts @@ -1,7 +1,7 @@ import type { EmptyRequest } from "@shared/proto/cline/common" import { Boolean } from "@shared/proto/cline/common" -import type { Controller } from "../index" import { getLatestAnnouncementId } from "@/utils/announcements" +import type { Controller } from "../index" /** * Marks the current announcement as shown diff --git a/src/core/controller/ui/openUrl.ts b/src/core/controller/ui/openUrl.ts index 67c84f35..31af90c0 100644 --- a/src/core/controller/ui/openUrl.ts +++ b/src/core/controller/ui/openUrl.ts @@ -1,7 +1,7 @@ -import type { Controller } from "../index" import type { StringRequest } from "@shared/proto/cline/common" import { Empty } from "@shared/proto/cline/common" import { openUrlInBrowser } from "../../../utils/github-url-utils" +import type { Controller } from "../index" /** * Opens a URL in the default browser @@ -9,7 +9,7 @@ import { openUrlInBrowser } from "../../../utils/github-url-utils" * @param request The URL to open * @returns Empty response */ -export async function openUrl(controller: Controller, request: StringRequest): Promise { +export async function openUrl(_controller: Controller, request: StringRequest): Promise { try { await openUrlInBrowser(request.value) return Empty.create({}) diff --git a/src/core/controller/ui/openWalkthrough.ts b/src/core/controller/ui/openWalkthrough.ts index da8fb596..457724ca 100644 --- a/src/core/controller/ui/openWalkthrough.ts +++ b/src/core/controller/ui/openWalkthrough.ts @@ -1,8 +1,8 @@ -import * as vscode from "vscode" -import type { Controller } from "../index" +import { telemetryService } from "@services/posthog/PostHogClientProvider" import type { EmptyRequest } from "@shared/proto/cline/common" import { Empty } from "@shared/proto/cline/common" -import { telemetryService } from "@services/posthog/PostHogClientProvider" +import * as vscode from "vscode" +import type { Controller } from "../index" /** * Opens the Cline walkthrough in VSCode @@ -10,7 +10,7 @@ import { telemetryService } from "@services/posthog/PostHogClientProvider" * @param request Empty request * @returns Empty response */ -export async function openWalkthrough(controller: Controller, request: EmptyRequest): Promise { +export async function openWalkthrough(_controller: Controller, _request: EmptyRequest): Promise { try { await vscode.commands.executeCommand("workbench.action.openWalkthrough", "saoudrizwan.claude-dev#ClineWalkthrough") telemetryService.captureButtonClick("webview_openWalkthrough") diff --git a/src/core/controller/ui/scrollToSettings.ts b/src/core/controller/ui/scrollToSettings.ts index bf4126b2..108c4efd 100644 --- a/src/core/controller/ui/scrollToSettings.ts +++ b/src/core/controller/ui/scrollToSettings.ts @@ -1,5 +1,5 @@ +import { KeyValuePair, StringRequest } from "@shared/proto/cline/common" import { Controller } from ".." -import { StringRequest, KeyValuePair } from "@shared/proto/cline/common" /** * Executes a scroll to settings action @@ -7,7 +7,7 @@ import { StringRequest, KeyValuePair } from "@shared/proto/cline/common" * @param request The request containing the ID of the settings section to scroll to * @returns KeyValuePair with action and value fields for the UI to process */ -export async function scrollToSettings(controller: Controller, request: StringRequest): Promise { +export async function scrollToSettings(_controller: Controller, request: StringRequest): Promise { return KeyValuePair.create({ key: "scrollToSettings", value: request.value || "", diff --git a/src/core/controller/ui/subscribeToAccountButtonClicked.ts b/src/core/controller/ui/subscribeToAccountButtonClicked.ts index 29e5b2c1..7947dcc4 100644 --- a/src/core/controller/ui/subscribeToAccountButtonClicked.ts +++ b/src/core/controller/ui/subscribeToAccountButtonClicked.ts @@ -1,6 +1,6 @@ -import { Controller } from "../index" import { Empty, EmptyRequest } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Track subscriptions by controller ID const activeSubscriptions = new Map>() diff --git a/src/core/controller/ui/subscribeToChatButtonClicked.ts b/src/core/controller/ui/subscribeToChatButtonClicked.ts index 1dbf28aa..e96d0d17 100644 --- a/src/core/controller/ui/subscribeToChatButtonClicked.ts +++ b/src/core/controller/ui/subscribeToChatButtonClicked.ts @@ -1,7 +1,6 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import { Controller } from "../index" -import { Empty } from "@shared/proto/cline/common" -import { EmptyRequest } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" // Keep track of active chatButtonClicked subscriptions by controller ID const activeChatButtonClickedSubscriptions = new Map>() diff --git a/src/core/controller/ui/subscribeToDidBecomeVisible.ts b/src/core/controller/ui/subscribeToDidBecomeVisible.ts index 8cded9a5..35e70dc8 100644 --- a/src/core/controller/ui/subscribeToDidBecomeVisible.ts +++ b/src/core/controller/ui/subscribeToDidBecomeVisible.ts @@ -1,7 +1,6 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import { Controller } from "../index" -import { Empty } from "@shared/proto/cline/common" -import { EmptyRequest } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" // Keep track of active didBecomeVisible subscriptions by controller ID const activeDidBecomeVisibleSubscriptions = new Map>() diff --git a/src/core/controller/ui/subscribeToFocusChatInput.ts b/src/core/controller/ui/subscribeToFocusChatInput.ts index 3fb0280e..1d6d0505 100644 --- a/src/core/controller/ui/subscribeToFocusChatInput.ts +++ b/src/core/controller/ui/subscribeToFocusChatInput.ts @@ -1,5 +1,5 @@ -import { StringRequest, Empty } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import type { Controller } from "../index" // Map client IDs to their subscription handlers diff --git a/src/core/controller/ui/subscribeToHistoryButtonClicked.ts b/src/core/controller/ui/subscribeToHistoryButtonClicked.ts index ac000301..807a9be6 100644 --- a/src/core/controller/ui/subscribeToHistoryButtonClicked.ts +++ b/src/core/controller/ui/subscribeToHistoryButtonClicked.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" import { Empty } from "@shared/proto/cline/common" import { WebviewProviderType, WebviewProviderTypeRequest } from "@shared/proto/cline/ui" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active subscriptions with their provider type const activeHistoryButtonClickedSubscriptions = new Map, WebviewProviderType>() diff --git a/src/core/controller/ui/subscribeToMcpButtonClicked.ts b/src/core/controller/ui/subscribeToMcpButtonClicked.ts index e8145940..4878176c 100644 --- a/src/core/controller/ui/subscribeToMcpButtonClicked.ts +++ b/src/core/controller/ui/subscribeToMcpButtonClicked.ts @@ -1,7 +1,6 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import { Controller } from "../index" -import { Empty } from "@shared/proto/cline/common" -import { EmptyRequest } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" // Keep track of active mcpButtonClicked subscriptions by controller ID const activeMcpButtonClickedSubscriptions = new Map>() diff --git a/src/core/controller/ui/subscribeToPartialMessage.ts b/src/core/controller/ui/subscribeToPartialMessage.ts index 291f7f2d..778bc857 100644 --- a/src/core/controller/ui/subscribeToPartialMessage.ts +++ b/src/core/controller/ui/subscribeToPartialMessage.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" import { EmptyRequest } from "@shared/proto/cline/common" import { ClineMessage } from "@shared/proto/cline/ui" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active partial message subscriptions const activePartialMessageSubscriptions = new Set>() diff --git a/src/core/controller/ui/subscribeToRelinquishControl.ts b/src/core/controller/ui/subscribeToRelinquishControl.ts index 3611fcb5..546b97bd 100644 --- a/src/core/controller/ui/subscribeToRelinquishControl.ts +++ b/src/core/controller/ui/subscribeToRelinquishControl.ts @@ -1,6 +1,6 @@ +import { Empty, EmptyRequest } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import { Controller } from "../index" -import { EmptyRequest, Empty } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" // Keep track of active subscriptions const activeRelinquishControlSubscriptions = new Set>() diff --git a/src/core/controller/ui/subscribeToSettingsButtonClicked.ts b/src/core/controller/ui/subscribeToSettingsButtonClicked.ts index a5f33b43..f8271255 100644 --- a/src/core/controller/ui/subscribeToSettingsButtonClicked.ts +++ b/src/core/controller/ui/subscribeToSettingsButtonClicked.ts @@ -1,6 +1,6 @@ import { Empty } from "@shared/proto/cline/common" import { WebviewProviderType, WebviewProviderTypeRequest } from "@shared/proto/cline/ui" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" import type { Controller } from "../index" // Track subscriptions with their provider type diff --git a/src/core/controller/ui/subscribeToTheme.ts b/src/core/controller/ui/subscribeToTheme.ts index e7985e1b..734a7935 100644 --- a/src/core/controller/ui/subscribeToTheme.ts +++ b/src/core/controller/ui/subscribeToTheme.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" -import { EmptyRequest, String } from "@shared/proto/cline/common" -import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" import { getTheme } from "@integrations/theme/getTheme" +import { EmptyRequest, String } from "@shared/proto/cline/common" +import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler" +import { Controller } from "../index" // Keep track of active theme subscriptions const activeThemeSubscriptions = new Set>() diff --git a/src/core/controller/web/checkIsImageUrl.ts b/src/core/controller/web/checkIsImageUrl.ts index 73b12f6a..59162aae 100644 --- a/src/core/controller/web/checkIsImageUrl.ts +++ b/src/core/controller/web/checkIsImageUrl.ts @@ -1,7 +1,7 @@ -import { Controller } from "../index" +import { detectImageUrl } from "@integrations/misc/link-preview" import { StringRequest } from "@shared/proto/cline/common" import { IsImageUrl } from "@shared/proto/cline/web" -import { detectImageUrl } from "@integrations/misc/link-preview" +import { Controller } from "../index" /** * Checks if a URL is an image URL diff --git a/src/core/controller/web/fetchOpenGraphData.ts b/src/core/controller/web/fetchOpenGraphData.ts index fa05b970..7b2b48b3 100644 --- a/src/core/controller/web/fetchOpenGraphData.ts +++ b/src/core/controller/web/fetchOpenGraphData.ts @@ -1,8 +1,8 @@ -import { Controller } from ".." import { StringRequest } from "@shared/proto/cline/common" import { OpenGraphData } from "@shared/proto/cline/web" import { fetchOpenGraphData as fetchOGData } from "../../../integrations/misc/link-preview" import { convertDomainOpenGraphDataToProto } from "../../../shared/proto-conversions/web/open-graph-conversion" +import { Controller } from ".." /** * Fetches Open Graph metadata from a URL @@ -10,7 +10,7 @@ import { convertDomainOpenGraphDataToProto } from "../../../shared/proto-convers * @param request The request containing the URL to fetch metadata from * @returns Promise resolving to OpenGraphData */ -export async function fetchOpenGraphData(controller: Controller, request: StringRequest): Promise { +export async function fetchOpenGraphData(_controller: Controller, request: StringRequest): Promise { try { const url = request.value || "" // Fetch open graph data using the existing utility diff --git a/src/core/controller/web/openInBrowser.ts b/src/core/controller/web/openInBrowser.ts index de32f7a2..b0c023f9 100644 --- a/src/core/controller/web/openInBrowser.ts +++ b/src/core/controller/web/openInBrowser.ts @@ -1,6 +1,6 @@ -import { Controller } from ".." import { Empty, StringRequest } from "@shared/proto/cline/common" import { openExternal } from "@utils/env" +import { Controller } from ".." /** * Opens a URL in the user's default browser diff --git a/src/core/ignore/ClineIgnoreController.test.ts b/src/core/ignore/ClineIgnoreController.test.ts index 91566479..ca80b150 100644 --- a/src/core/ignore/ClineIgnoreController.test.ts +++ b/src/core/ignore/ClineIgnoreController.test.ts @@ -1,8 +1,8 @@ -import { ClineIgnoreController } from "./ClineIgnoreController" import fs from "fs/promises" -import path from "path" -import os from "os" import { after, beforeEach, describe, it } from "mocha" +import os from "os" +import path from "path" +import { ClineIgnoreController } from "./ClineIgnoreController" import "should" describe("ClineIgnoreController", () => { diff --git a/src/core/ignore/ClineIgnoreController.ts b/src/core/ignore/ClineIgnoreController.ts index f9c452de..70689e31 100644 --- a/src/core/ignore/ClineIgnoreController.ts +++ b/src/core/ignore/ClineIgnoreController.ts @@ -1,7 +1,7 @@ -import path from "path" import { fileExistsAtPath } from "@utils/fs" import fs from "fs/promises" import ignore, { Ignore } from "ignore" +import path from "path" import * as vscode from "vscode" export const LOCK_TEXT_SYMBOL = "\u{1F512}" @@ -152,7 +152,7 @@ export class ClineIgnoreController { // Ignore expects paths to be path.relative()'d return !this.ignoreInstance.ignores(relativePath) - } catch (error) { + } catch (_error) { // console.error(`Error validating access for ${filePath}:`, error) // Ignore is designed to work with relative file paths, so will throw error for paths outside cwd. We are allowing access to all files outside cwd. return true diff --git a/src/core/mentions/index.test.ts b/src/core/mentions/index.test.ts index 1a2458de..964b4604 100644 --- a/src/core/mentions/index.test.ts +++ b/src/core/mentions/index.test.ts @@ -1,5 +1,3 @@ -import { HostProvider } from "@/hosts/host-provider" -import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" import * as extractTextModule from "@integrations/misc/extract-text" import * as terminalModule from "@integrations/terminal/get-latest-output" @@ -10,6 +8,8 @@ import * as fs from "fs" import * as isBinaryFileModule from "isbinaryfile" import * as path from "path" import * as sinon from "sinon" +import { HostProvider } from "@/hosts/host-provider" +import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import { parseMentions } from "." describe("parseMentions", () => { diff --git a/src/core/mentions/index.ts b/src/core/mentions/index.ts index 69eef79e..d1ddc272 100644 --- a/src/core/mentions/index.ts +++ b/src/core/mentions/index.ts @@ -1,21 +1,20 @@ -import * as vscode from "vscode" -import * as path from "path" +import { diagnosticsToProblemsString } from "@integrations/diagnostics" +import { extractTextFromFile } from "@integrations/misc/extract-text" import { openFile } from "@integrations/misc/open-file" +import { getLatestTerminalOutput } from "@integrations/terminal/get-latest-output" import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" import { mentionRegexGlobal } from "@shared/context-mentions" -import fs from "fs/promises" -import { extractTextFromFile } from "@integrations/misc/extract-text" -import { isBinaryFile } from "isbinaryfile" -import { getLatestTerminalOutput } from "@integrations/terminal/get-latest-output" -import { getCommitInfo } from "@utils/git" -import { getWorkingState } from "@utils/git" -import { FileContextTracker } from "../context/context-tracking/FileContextTracker" -import { getCwd } from "@/utils/path" import { openExternal } from "@utils/env" +import { getCommitInfo, getWorkingState } from "@utils/git" +import fs from "fs/promises" +import { isBinaryFile } from "isbinaryfile" +import * as path from "path" +import * as vscode from "vscode" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" -import { diagnosticsToProblemsString } from "@integrations/diagnostics" import { DiagnosticSeverity } from "@/shared/proto/index.cline" +import { getCwd } from "@/utils/path" +import { FileContextTracker } from "../context/context-tracking/FileContextTracker" export async function openMention(mention?: string): Promise { if (!mention) { @@ -220,7 +219,7 @@ async function getFileOrFolderContent(mentionPath: string, cwd: string): Promise } const content = await extractTextFromFile(absoluteFilePath) return `\n${content}\n` - } catch (error) { + } catch (_error) { return undefined } })(), diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts index b812aa35..e7383e75 100644 --- a/src/core/prompts/responses.ts +++ b/src/core/prompts/responses.ts @@ -13,11 +13,11 @@ export const formatResponse = { processFirstUserMessageForTruncation: (originalContent: string) => { const MAX_CHARS = 400_000 - + if (originalContent.length <= MAX_CHARS) { return originalContent } - + const truncated = originalContent.substring(0, MAX_CHARS) return truncated + "\n\n[[NOTE] This message was truncated past this point to preserve context window space.]" }, diff --git a/src/core/slash-commands/index.ts b/src/core/slash-commands/index.ts index 7c7850ea..8ddd234f 100644 --- a/src/core/slash-commands/index.ts +++ b/src/core/slash-commands/index.ts @@ -1,12 +1,12 @@ -import { - newTaskToolResponse, - condenseToolResponse, - newRuleToolResponse, - reportBugToolResponse, - deepPlanningToolResponse, -} from "../prompts/commands" import { ClineRulesToggles } from "@shared/cline-rules" import fs from "fs/promises" +import { + condenseToolResponse, + deepPlanningToolResponse, + newRuleToolResponse, + newTaskToolResponse, + reportBugToolResponse, +} from "../prompts/commands" /** * Processes text for slash commands and transforms them with appropriate instructions @@ -30,10 +30,10 @@ export async function parseSlashCommands( // this currently allows matching prepended whitespace prior to /slash-command const tagPatterns = [ - { tag: "task", regex: /(\s*\/([a-zA-Z0-9_\.-]+))(\s+.+?)?\s*<\/task>/is }, - { tag: "feedback", regex: /(\s*\/([a-zA-Z0-9_\.-]+))(\s+.+?)?\s*<\/feedback>/is }, - { tag: "answer", regex: /(\s*\/([a-zA-Z0-9_\.-]+))(\s+.+?)?\s*<\/answer>/is }, - { tag: "user_message", regex: /(\s*\/([a-zA-Z0-9_\.-]+))(\s+.+?)?\s*<\/user_message>/is }, + { tag: "task", regex: /(\s*\/([a-zA-Z0-9_.-]+))(\s+.+?)?\s*<\/task>/is }, + { tag: "feedback", regex: /(\s*\/([a-zA-Z0-9_.-]+))(\s+.+?)?\s*<\/feedback>/is }, + { tag: "answer", regex: /(\s*\/([a-zA-Z0-9_.-]+))(\s+.+?)?\s*<\/answer>/is }, + { tag: "user_message", regex: /(\s*\/([a-zA-Z0-9_.-]+))(\s+.+?)?\s*<\/user_message>/is }, ] // if we find a valid match, we will return inside that block @@ -63,7 +63,7 @@ export async function parseSlashCommands( const textWithoutSlashCommand = text.substring(0, slashCommandStartIndex) + text.substring(slashCommandEndIndex) const processedText = commandReplacements[commandName] + textWithoutSlashCommand - return { processedText: processedText, needsClinerulesFileCheck: commandName === "newrule" ? true : false } + return { processedText: processedText, needsClinerulesFileCheck: commandName === "newrule" } } const globalWorkflows = Object.entries(globalWorkflowToggles) diff --git a/src/core/storage/disk.ts b/src/core/storage/disk.ts index 699bd886..92045efb 100644 --- a/src/core/storage/disk.ts +++ b/src/core/storage/disk.ts @@ -1,12 +1,12 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import { TaskMetadata } from "@core/context/context-tracking/ContextTrackerTypes" +import { execa } from "@packages/execa" +import { ClineMessage } from "@shared/ExtensionMessage" +import { fileExistsAtPath } from "@utils/fs" +import fs from "fs/promises" +import os from "os" import * as path from "path" import * as vscode from "vscode" -import fs from "fs/promises" -import { Anthropic } from "@anthropic-ai/sdk" -import { fileExistsAtPath } from "@utils/fs" -import { ClineMessage } from "@shared/ExtensionMessage" -import { TaskMetadata } from "@core/context/context-tracking/ContextTrackerTypes" -import os from "os" -import { execa } from "@packages/execa" export const GlobalFileNames = { apiConversationHistory: "api_conversation_history.json", @@ -36,7 +36,7 @@ export async function getDocumentsPath(): Promise { if (trimmedPath) { return trimmedPath } - } catch (err) { + } catch (_err) { console.error("Failed to retrieve Windows Documents path. Falling back to homedir/Documents.") } } else if (process.platform === "linux") { @@ -72,7 +72,7 @@ export async function ensureRulesDirectoryExists(): Promise { const clineRulesDir = path.join(userDocumentsPath, "Cline", "Rules") try { await fs.mkdir(clineRulesDir, { recursive: true }) - } catch (error) { + } catch (_error) { return path.join(os.homedir(), "Documents", "Cline", "Rules") // in case creating a directory in documents fails for whatever reason (e.g. permissions) - this is fine because we will fail gracefully with a path that does not exist } return clineRulesDir @@ -83,7 +83,7 @@ export async function ensureWorkflowsDirectoryExists(): Promise { const clineWorkflowsDir = path.join(userDocumentsPath, "Cline", "Workflows") try { await fs.mkdir(clineWorkflowsDir, { recursive: true }) - } catch (error) { + } catch (_error) { return path.join(os.homedir(), "Documents", "Cline", "Workflows") // in case creating a directory in documents fails for whatever reason (e.g. permissions) - this is fine because we will fail gracefully with a path that does not exist } return clineWorkflowsDir @@ -94,7 +94,7 @@ export async function ensureMcpServersDirectoryExists(): Promise { const mcpServersDir = path.join(userDocumentsPath, "Cline", "MCP") try { await fs.mkdir(mcpServersDir, { recursive: true }) - } catch (error) { + } catch (_error) { return "~/Documents/Cline/MCP" // in case creating a directory in documents fails for whatever reason (e.g. permissions) - this is fine since this path is only ever used in the system prompt } return mcpServersDir diff --git a/src/core/storage/state-migrations.ts b/src/core/storage/state-migrations.ts index fac378fd..ae0e6287 100644 --- a/src/core/storage/state-migrations.ts +++ b/src/core/storage/state-migrations.ts @@ -1,7 +1,7 @@ -import * as vscode from "vscode" -import { ensureRulesDirectoryExists } from "./disk" import fs from "fs/promises" import path from "path" +import * as vscode from "vscode" +import { ensureRulesDirectoryExists } from "./disk" import { readStateFromDisk } from "./utils/state-helpers" export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionContext) { @@ -108,7 +108,7 @@ export async function migrateCustomInstructionsToGlobalRules(context: vscode.Ext let existingContent = "" try { existingContent = await fs.readFile(migrationFilePath, "utf8") - } catch (readError) { + } catch (_readError) { // File doesn't exist, which is fine } diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 54038706..af818bde 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -1348,7 +1348,7 @@ export class ToolExecutor { if (mcp_arguments) { try { parsedArguments = JSON.parse(mcp_arguments) - } catch (error) { + } catch (_error) { this.taskState.consecutiveMistakeCount++ await this.say( "error", diff --git a/src/core/task/focus-chain/index.ts b/src/core/task/focus-chain/index.ts index eb91f8a3..55ea08e1 100644 --- a/src/core/task/focus-chain/index.ts +++ b/src/core/task/focus-chain/index.ts @@ -1,22 +1,22 @@ -import * as vscode from "vscode" +import { featureFlagsService, telemetryService } from "@services/posthog/PostHogClientProvider" +import { FocusChainSettings } from "@shared/FocusChainSettings" import * as fs from "fs/promises" +import * as vscode from "vscode" +import { HostProvider } from "../../../hosts/host-provider" +import { ClineSay } from "../../../shared/ExtensionMessage" +import { FileChangeEvent_ChangeType, SubscribeToFileRequest } from "../../../shared/proto/host/watch" +import { Mode } from "../../../shared/storage/types" import { writeFile } from "../../../utils/fs" +import { CacheService } from "../../storage/CacheService" import { ensureTaskDirectoryExists } from "../../storage/disk" import { TaskState } from "../TaskState" -import { Mode } from "../../../shared/storage/types" -import { ClineSay } from "../../../shared/ExtensionMessage" -import { HostProvider } from "../../../hosts/host-provider" -import { SubscribeToFileRequest, FileChangeEvent_ChangeType } from "../../../shared/proto/host/watch" -import { telemetryService, featureFlagsService } from "@services/posthog/PostHogClientProvider" -import { parseFocusChainListCounts } from "./utils" import { - getFocusChainFilePath, createFocusChainMarkdownContent, - extractFocusChainListFromText, extractFocusChainItemsFromText, + extractFocusChainListFromText, + getFocusChainFilePath, } from "./file-utils" -import { FocusChainSettings } from "@shared/FocusChainSettings" -import { CacheService } from "../../storage/CacheService" +import { parseFocusChainListCounts } from "./utils" export interface FocusChainDependencies { taskId: string @@ -345,7 +345,7 @@ ${listInstrunctionsReminder}\n` const todoList = extractFocusChainListFromText(markdownContent) if (todoList) { - const todoLines = extractFocusChainItemsFromText(markdownContent) + const _todoLines = extractFocusChainItemsFromText(markdownContent) return todoList } @@ -429,7 +429,7 @@ ${listInstrunctionsReminder}\n` // No model update provided, check if markdown file exists and load it const markdownTodoList = await this.readFocusChainFromDisk() if (markdownTodoList) { - const previousList = this.taskState.currentFocusChainChecklist + const _previousList = this.taskState.currentFocusChainChecklist this.taskState.currentFocusChainChecklist = markdownTodoList // Create a task_progress message to display the focus chain list in the UI diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 361b11cd..6bfad346 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -208,7 +208,7 @@ export class Task { this.cacheService = cacheService // Set up MCP notification callback for real-time notifications - this.mcpHub.setNotificationCallback(async (serverName: string, level: string, message: string) => { + this.mcpHub.setNotificationCallback(async (serverName: string, _level: string, message: string) => { // Display notification in chat immediately await this.say("mcp_notification", `[${serverName}] ${message}`) }) @@ -1038,7 +1038,7 @@ export class Task { // load the context history state - const taskDir = await ensureTaskDirectoryExists(context, this.taskId) + const _taskDir = await ensureTaskDirectoryExists(context, this.taskId) await this.contextManager.initializeContextHistory(await ensureTaskDirectoryExists(this.getContext(), this.taskId)) const lastClineMessage = this.messageStateHandler @@ -1408,7 +1408,7 @@ export class Task { }) // Race between command completion and timeout - const result = await Promise.race([childProcess, timeoutPromise]).catch((error) => { + const result = await Promise.race([childProcess, timeoutPromise]).catch((_error) => { // If we get here due to timeout, return a partial result with timeout flag Logger.info(`Command timed out after 30s: ${command}`) return { @@ -2530,7 +2530,7 @@ export class Task { } return didEndLoop // will always be false for now - } catch (error) { + } catch (_error) { // this should never happen since the only thing that can throw an error is the attemptApiRequest, which is wrapped in a try catch that sends an ask where if noButtonClicked, will clear current task and destroy this instance. However to avoid unhandled promise rejection, we will end this loop which will end execution of this instance (see startTask) return true // needs to be true so parent loop knows to end task } @@ -2780,7 +2780,7 @@ export class Task { try { const { tokensIn, tokensOut, cacheWrites, cacheReads } = JSON.parse(msg.text) return (tokensIn || 0) + (tokensOut || 0) + (cacheWrites || 0) + (cacheReads || 0) - } catch (e) { + } catch (_e) { return 0 } } diff --git a/src/core/task/message-state.ts b/src/core/task/message-state.ts index c6806665..bdb55a9a 100644 --- a/src/core/task/message-state.ts +++ b/src/core/task/message-state.ts @@ -1,18 +1,16 @@ -import { combineApiRequests } from "@/shared/combineApiRequests" -import { ensureTaskDirectoryExists, saveApiConversationHistory, saveClineMessages } from "../storage/disk" +import Anthropic from "@anthropic-ai/sdk" +import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker" +import getFolderSize from "get-folder-size" import * as vscode from "vscode" +import { findLastIndex } from "@/shared/array" +import { combineApiRequests } from "@/shared/combineApiRequests" +import { combineCommandSequences } from "@/shared/combineCommandSequences" import { ClineMessage } from "@/shared/ExtensionMessage" import { getApiMetrics } from "@/shared/getApiMetrics" -import { combineCommandSequences } from "@/shared/combineCommandSequences" -import { findLastIndex } from "@/shared/array" -import getFolderSize from "get-folder-size" -import os from "os" -import * as path from "path" -import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker" import { HistoryItem } from "@/shared/HistoryItem" -import Anthropic from "@anthropic-ai/sdk" -import { TaskState } from "./TaskState" import { getCwd, getDesktopDir } from "@/utils/path" +import { ensureTaskDirectoryExists, saveApiConversationHistory, saveClineMessages } from "../storage/disk" +import { TaskState } from "./TaskState" interface MessageStateHandlerParams { context: vscode.ExtensionContext diff --git a/src/core/task/multifile-diff.test.ts b/src/core/task/multifile-diff.test.ts index 6b3b2498..63156e15 100644 --- a/src/core/task/multifile-diff.test.ts +++ b/src/core/task/multifile-diff.test.ts @@ -1,12 +1,12 @@ -import { describe, it, beforeEach, afterEach } from "mocha" -import { expect } from "chai" -import sinon from "sinon" -import { showChangedFilesDiff } from "@core/task/multifile-diff" import { MessageStateHandler } from "@core/task/message-state" -import CheckpointTracker from "@/integrations/checkpoints/CheckpointTracker" +import { showChangedFilesDiff } from "@core/task/multifile-diff" +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import sinon from "sinon" import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageType } from "@/shared/proto/index.host" +import CheckpointTracker from "@/integrations/checkpoints/CheckpointTracker" import { ClineMessage } from "@/shared/ExtensionMessage" +import { ShowMessageType } from "@/shared/proto/index.host" import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" describe("multifile-diff", () => { diff --git a/src/core/task/multifile-diff.ts b/src/core/task/multifile-diff.ts index f987d6c8..f75de860 100644 --- a/src/core/task/multifile-diff.ts +++ b/src/core/task/multifile-diff.ts @@ -1,8 +1,8 @@ -import { findLast } from "@/shared/array" -import { MessageStateHandler } from "./message-state" import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageType } from "@/shared/proto/index.host" import CheckpointTracker from "@/integrations/checkpoints/CheckpointTracker" +import { findLast } from "@/shared/array" +import { ShowMessageType } from "@/shared/proto/index.host" +import { MessageStateHandler } from "./message-state" export async function showChangedFilesDiff( messageStateHandler: MessageStateHandler, diff --git a/src/core/task/tools/autoApprove.ts b/src/core/task/tools/autoApprove.ts index ede57c14..b26455ef 100644 --- a/src/core/task/tools/autoApprove.ts +++ b/src/core/task/tools/autoApprove.ts @@ -1,7 +1,6 @@ -import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { ToolUseName } from "@core/assistant-message" +import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import * as path from "path" -import os from "os" import { getCwd, getDesktopDir } from "@/utils/path" export class AutoApprove { diff --git a/src/core/task/utils.ts b/src/core/task/utils.ts index e7bfab66..29ef56a3 100644 --- a/src/core/task/utils.ts +++ b/src/core/task/utils.ts @@ -1,8 +1,8 @@ +import { ApiHandler } from "@core/api" import { showSystemNotification } from "@/integrations/notifications" import { ClineApiReqCancelReason, ClineApiReqInfo } from "@/shared/ExtensionMessage" -import { MessageStateHandler } from "./message-state" import { calculateApiCostAnthropic } from "@/utils/cost" -import { ApiHandler } from "@core/api" +import { MessageStateHandler } from "./message-state" export const showNotificationForApprovalIfAutoApprovalEnabled = ( message: string, diff --git a/src/core/webview/WebviewProvider.ts b/src/core/webview/WebviewProvider.ts index 5be040ba..6a2ecb8d 100644 --- a/src/core/webview/WebviewProvider.ts +++ b/src/core/webview/WebviewProvider.ts @@ -1,16 +1,15 @@ -import axios from "axios" -import * as vscode from "vscode" -import { getNonce } from "./getNonce" - -import { WebviewProviderType } from "@/shared/webview/types" +import path from "node:path" import { Controller } from "@core/controller/index" import { findLast } from "@shared/array" +import axios from "axios" import { readFile } from "fs/promises" -import path from "node:path" import { v4 as uuidv4 } from "uuid" +import * as vscode from "vscode" import { Uri } from "vscode" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" +import { WebviewProviderType } from "@/shared/webview/types" +import { getNonce } from "./getNonce" export abstract class WebviewProvider { private static activeInstances: Set = new Set() @@ -221,7 +220,7 @@ export abstract class WebviewProvider { return port }) - .catch((err) => { + .catch((_err) => { console.warn( `[getDevServerPort] Port file not found or couldn't be read at ${portFilePath}, using default port: ${DEFAULT_PORT}`, ) @@ -243,7 +242,7 @@ export abstract class WebviewProvider { // Check if local dev server is running. try { await axios.get(`http://${localServerUrl}`) - } catch (error) { + } catch (_error) { // Only show the error message when in development mode. if (process.env.IS_DEV) { HostProvider.window.showMessage({ diff --git a/src/dev/commands/tasks.ts b/src/dev/commands/tasks.ts index 81490ec2..847a7047 100644 --- a/src/dev/commands/tasks.ts +++ b/src/dev/commands/tasks.ts @@ -1,11 +1,11 @@ -import * as vscode from "vscode" +import { Controller } from "@core/controller" +import { ClineMessage } from "@shared/ExtensionMessage" +import { HistoryItem } from "@shared/HistoryItem" import * as fs from "fs/promises" import * as path from "path" -import { Controller } from "@core/controller" -import { HistoryItem } from "@shared/HistoryItem" -import { ClineMessage } from "@shared/ExtensionMessage" -import { ShowMessageType } from "@/shared/proto/host/window" +import * as vscode from "vscode" import { HostProvider } from "@/hosts/host-provider" +import { ShowMessageType } from "@/shared/proto/host/window" /** * Registers development-only commands for task manipulation. diff --git a/src/exports/index.ts b/src/exports/index.ts index 243951d7..f9fb2236 100644 --- a/src/exports/index.ts +++ b/src/exports/index.ts @@ -1,7 +1,7 @@ import { Controller } from "@core/controller" -import { ClineAPI } from "./cline" import { sendChatButtonClickedEvent } from "@core/controller/ui/subscribeToChatButtonClicked" import { HostProvider } from "@/hosts/host-provider" +import { ClineAPI } from "./cline" export function createClineAPI(sidebarController: Controller): ClineAPI { const api: ClineAPI = { diff --git a/src/extension.ts b/src/extension.ts index 57a1de7d..66cda55f 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,10 +1,10 @@ // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below -import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider" -import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui" import assert from "node:assert" import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider" +import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui" import * as vscode from "vscode" import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked" import { sendChatButtonClickedEvent } from "./core/controller/ui/subscribeToChatButtonClicked" @@ -18,10 +18,10 @@ import { cleanupTestMode, initializeTestMode } from "./services/test/TestMode" import { WebviewProviderType } from "./shared/webview/types" import "./utils/path" // necessary to have access to String.prototype.toPosix +import type { ExtensionContext } from "vscode" import { HostProvider } from "@/hosts/host-provider" import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client" import { readTextFromClipboard, writeTextToClipboard } from "@/utils/env" -import type { ExtensionContext } from "vscode" import { initialize, tearDown } from "./common" import { addToCline } from "./core/controller/commands/addToCline" import { explainWithCline } from "./core/controller/commands/explainWithCline" diff --git a/src/hosts/external/AuthHandler.ts b/src/hosts/external/AuthHandler.ts index b75487fe..53f9c939 100644 --- a/src/hosts/external/AuthHandler.ts +++ b/src/hosts/external/AuthHandler.ts @@ -1,7 +1,6 @@ import type { IncomingMessage, Server, ServerResponse } from "node:http" import http from "node:http" import type { AddressInfo } from "node:net" -import { openExternal } from "@/utils/env" import { SharedUriHandler } from "@/services/uri/SharedUriHandler" const SERVER_TIMEOUT = 10 * 60 * 1000 // 10 minutes @@ -184,10 +183,6 @@ export class AuthHandler { res.end(content) } - private async openBrowser(callbackUrl: URL): Promise { - await openExternal(callbackUrl.toString()) - } - public stop(): void { if (this.timeoutId) { clearTimeout(this.timeoutId) diff --git a/src/hosts/external/ExternalDiffviewProvider.ts b/src/hosts/external/ExternalDiffviewProvider.ts index a93afddb..2989975d 100644 --- a/src/hosts/external/ExternalDiffviewProvider.ts +++ b/src/hosts/external/ExternalDiffviewProvider.ts @@ -1,6 +1,6 @@ +import { status } from "@grpc/grpc-js" import { HostProvider } from "@/hosts/host-provider" import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider" -import { status } from "@grpc/grpc-js" export class ExternalDiffViewProvider extends DiffViewProvider { private activeDiffEditorId: string | undefined diff --git a/src/hosts/external/ExternalWebviewProvider.ts b/src/hosts/external/ExternalWebviewProvider.ts index ffc11abf..f43dd5c4 100644 --- a/src/hosts/external/ExternalWebviewProvider.ts +++ b/src/hosts/external/ExternalWebviewProvider.ts @@ -1,7 +1,7 @@ -import { WebviewProviderType } from "@/shared/webview/types" -import { WebviewProvider } from "@/core/webview" import * as vscode from "vscode" import { URI } from "vscode-uri" +import { WebviewProvider } from "@/core/webview" +import { WebviewProviderType } from "@/shared/webview/types" export class ExternalWebviewProvider extends WebviewProvider { // This hostname cannot be changed without updating the external webview handler. diff --git a/src/hosts/external/grpc-types.ts b/src/hosts/external/grpc-types.ts index aedf35e8..d78b4cec 100644 --- a/src/hosts/external/grpc-types.ts +++ b/src/hosts/external/grpc-types.ts @@ -1,5 +1,5 @@ -import * as grpc from "@grpc/grpc-js" import { Controller } from "@core/controller" +import * as grpc from "@grpc/grpc-js" import { Channel, createChannel } from "nice-grpc" /** diff --git a/src/hosts/external/host-bridge-client-manager.ts b/src/hosts/external/host-bridge-client-manager.ts index 6fceeec7..7f1d4b84 100644 --- a/src/hosts/external/host-bridge-client-manager.ts +++ b/src/hosts/external/host-bridge-client-manager.ts @@ -1,18 +1,17 @@ -import { Channel, createChannel } from "nice-grpc" import { - WatchServiceClientImpl, - WorkspaceServiceClientImpl, - EnvServiceClientImpl, - WindowServiceClientImpl, - DiffServiceClientImpl, -} from "@generated/hosts/standalone/host-bridge-clients" -import { - WatchServiceClientInterface, - WorkspaceServiceClientInterface, - EnvServiceClientInterface, - WindowServiceClientInterface, DiffServiceClientInterface, + EnvServiceClientInterface, + WatchServiceClientInterface, + WindowServiceClientInterface, + WorkspaceServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" +import { + DiffServiceClientImpl, + EnvServiceClientImpl, + WatchServiceClientImpl, + WindowServiceClientImpl, + WorkspaceServiceClientImpl, +} from "@generated/hosts/standalone/host-bridge-clients" import { HostBridgeClientProvider } from "@/hosts/host-provider-types" import { HOSTBRIDGE_PORT } from "@/standalone/protobus-service" diff --git a/src/hosts/host-provider-types.ts b/src/hosts/host-provider-types.ts index 92a8aa06..79522bfc 100644 --- a/src/hosts/host-provider-types.ts +++ b/src/hosts/host-provider-types.ts @@ -1,9 +1,9 @@ import { - WatchServiceClientInterface, - WorkspaceServiceClientInterface, - EnvServiceClientInterface, - WindowServiceClientInterface, DiffServiceClientInterface, + EnvServiceClientInterface, + WatchServiceClientInterface, + WindowServiceClientInterface, + WorkspaceServiceClientInterface, } from "@generated/hosts/host-bridge-client-types" /** diff --git a/src/hosts/host-provider.ts b/src/hosts/host-provider.ts index e27169d4..386b6105 100644 --- a/src/hosts/host-provider.ts +++ b/src/hosts/host-provider.ts @@ -1,7 +1,7 @@ import { WebviewProvider } from "@/core/webview" -import { HostBridgeClientProvider } from "./host-provider-types" -import { WebviewProviderType } from "@/shared/webview/types" import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider" +import { WebviewProviderType } from "@/shared/webview/types" +import { HostBridgeClientProvider } from "./host-provider-types" /** * Singleton class that manages host-specific providers for dependency injection. diff --git a/src/hosts/vscode/VscodeDiffViewProvider.ts b/src/hosts/vscode/VscodeDiffViewProvider.ts index 524d0599..a1f21958 100644 --- a/src/hosts/vscode/VscodeDiffViewProvider.ts +++ b/src/hosts/vscode/VscodeDiffViewProvider.ts @@ -1,8 +1,8 @@ -import { arePathsEqual } from "@/utils/path" +import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" import * as path from "path" import * as vscode from "vscode" import { DecorationController } from "@/hosts/vscode/DecorationController" -import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" +import { arePathsEqual } from "@/utils/path" export const DIFF_VIEW_URI_SCHEME = "cline-diff" @@ -21,8 +21,7 @@ export class VscodeDiffViewProvider extends DiffViewProvider { this.documentWasOpen = false // close the tab if it's open (it's already been saved) const tabs = vscode.window.tabGroups.all - .map((tg) => tg.tabs) - .flat() + .flatMap((tg) => tg.tabs) .filter((tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, this.absolutePath)) for (const tab of tabs) { if (!tab.isDirty) { diff --git a/src/hosts/vscode/VscodeWebviewProvider.ts b/src/hosts/vscode/VscodeWebviewProvider.ts index 1b9fc964..4ef76c6d 100644 --- a/src/hosts/vscode/VscodeWebviewProvider.ts +++ b/src/hosts/vscode/VscodeWebviewProvider.ts @@ -4,11 +4,11 @@ import { WebviewProvider } from "@core/webview" import { getTheme } from "@integrations/theme/getTheme" import type { Uri } from "vscode" import * as vscode from "vscode" +import { handleGrpcRequest, handleGrpcRequestCancel } from "@/core/controller/grpc-handler" import { HostProvider } from "@/hosts/host-provider" import type { ExtensionMessage } from "@/shared/ExtensionMessage" -import type { WebviewProviderType } from "@/shared/webview/types" import { WebviewMessage } from "@/shared/WebviewMessage" -import { handleGrpcRequest, handleGrpcRequestCancel } from "@/core/controller/grpc-handler" +import type { WebviewProviderType } from "@/shared/webview/types" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts diff --git a/src/hosts/vscode/commandUtils.ts b/src/hosts/vscode/commandUtils.ts index 14ca7369..60cb13e9 100644 --- a/src/hosts/vscode/commandUtils.ts +++ b/src/hosts/vscode/commandUtils.ts @@ -1,6 +1,6 @@ -import { CommandContext } from "@/shared/proto/index.cline" import pWaitFor from "p-wait-for" import * as vscode from "vscode" +import { CommandContext } from "@/shared/proto/index.cline" import { Controller } from "../../core/controller" import { WebviewProvider } from "../../core/webview" import { convertVscodeDiagnostics } from "./hostbridge/workspace/getDiagnostics" diff --git a/src/hosts/vscode/hostbridge-grpc-handler.ts b/src/hosts/vscode/hostbridge-grpc-handler.ts index 346a75b9..9bad0497 100644 --- a/src/hosts/vscode/hostbridge-grpc-handler.ts +++ b/src/hosts/vscode/hostbridge-grpc-handler.ts @@ -1,6 +1,6 @@ -import { StreamingCallbacks } from "@/hosts/host-provider-types" -import { hostServiceHandlers } from "@generated/hosts/vscode/hostbridge-grpc-service-config" import { GrpcRequestRegistry } from "@core/controller/grpc-request-registry" +import { hostServiceHandlers } from "@generated/hosts/vscode/hostbridge-grpc-service-config" +import { StreamingCallbacks } from "@/hosts/host-provider-types" /** * Type definition for a streaming response handler @@ -40,7 +40,7 @@ export class GrpcHandler { let completionCalled = false // Create a response handler that will call the client's callbacks - const responseHandler: StreamingResponseHandler = async (response, isLast = false, sequenceNumber) => { + const responseHandler: StreamingResponseHandler = async (response, isLast = false, _sequenceNumber) => { try { // Call the client's onResponse callback with the response streamingCallbacks.onResponse(response) diff --git a/src/hosts/vscode/hostbridge/client/host-grpc-client-base.ts b/src/hosts/vscode/hostbridge/client/host-grpc-client-base.ts index 8be82c2d..3150746e 100644 --- a/src/hosts/vscode/hostbridge/client/host-grpc-client-base.ts +++ b/src/hosts/vscode/hostbridge/client/host-grpc-client-base.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid" -import { GrpcHandler } from "@/hosts/vscode/hostbridge-grpc-handler" import { StreamingCallbacks } from "@/hosts/host-provider-types" +import { GrpcHandler } from "@/hosts/vscode/hostbridge-grpc-handler" // Generic type for any protobuf service definition export type ProtoService = { diff --git a/src/hosts/vscode/hostbridge/client/host-grpc-client.ts b/src/hosts/vscode/hostbridge/client/host-grpc-client.ts index f78bf58c..2be02463 100644 --- a/src/hosts/vscode/hostbridge/client/host-grpc-client.ts +++ b/src/hosts/vscode/hostbridge/client/host-grpc-client.ts @@ -1,6 +1,6 @@ import { createGrpcClient } from "@hosts/vscode/hostbridge/client/host-grpc-client-base" -import { HostBridgeClientProvider } from "@/hosts/host-provider-types" import * as host from "@shared/proto/index.host" +import { HostBridgeClientProvider } from "@/hosts/host-provider-types" export const vscodeHostBridgeClient: HostBridgeClientProvider = { watchServiceClient: createGrpcClient(host.WatchServiceDefinition), diff --git a/src/hosts/vscode/hostbridge/diff/openMultiFileDiff.ts b/src/hosts/vscode/hostbridge/diff/openMultiFileDiff.ts index 69fb87e3..a0032176 100644 --- a/src/hosts/vscode/hostbridge/diff/openMultiFileDiff.ts +++ b/src/hosts/vscode/hostbridge/diff/openMultiFileDiff.ts @@ -1,8 +1,8 @@ -import { OpenMultiFileDiffRequest, OpenMultiFileDiffResponse } from "@/shared/proto/index.host" -import * as vscode from "vscode" -import { DIFF_VIEW_URI_SCHEME } from "../../VscodeDiffViewProvider" -import { getCwd } from "@/utils/path" import path from "path" +import * as vscode from "vscode" +import { OpenMultiFileDiffRequest, OpenMultiFileDiffResponse } from "@/shared/proto/index.host" +import { getCwd } from "@/utils/path" +import { DIFF_VIEW_URI_SCHEME } from "../../VscodeDiffViewProvider" export async function openMultiFileDiff(request: OpenMultiFileDiffRequest): Promise { const cwd = await getCwd() diff --git a/src/hosts/vscode/hostbridge/env/clipboardWriteText.ts b/src/hosts/vscode/hostbridge/env/clipboardWriteText.ts index cb01cf61..a1d45f81 100644 --- a/src/hosts/vscode/hostbridge/env/clipboardWriteText.ts +++ b/src/hosts/vscode/hostbridge/env/clipboardWriteText.ts @@ -1,4 +1,4 @@ -import { StringRequest, Empty } from "@shared/proto/cline/common" +import { Empty, StringRequest } from "@shared/proto/cline/common" import * as vscode from "vscode" export async function clipboardWriteText(request: StringRequest): Promise { diff --git a/src/hosts/vscode/hostbridge/env/getHostVersion.ts b/src/hosts/vscode/hostbridge/env/getHostVersion.ts index 35fd3519..bb1afca6 100644 --- a/src/hosts/vscode/hostbridge/env/getHostVersion.ts +++ b/src/hosts/vscode/hostbridge/env/getHostVersion.ts @@ -1,4 +1,4 @@ -import { EmptyRequest, String } from "@shared/proto/cline/common" +import { EmptyRequest } from "@shared/proto/cline/common" import * as vscode from "vscode" import { GetHostVersionResponse } from "@/shared/proto/index.host" diff --git a/src/hosts/vscode/hostbridge/watch/subscribeToFile.ts b/src/hosts/vscode/hostbridge/watch/subscribeToFile.ts index 436b18b4..3f82c00e 100644 --- a/src/hosts/vscode/hostbridge/watch/subscribeToFile.ts +++ b/src/hosts/vscode/hostbridge/watch/subscribeToFile.ts @@ -1,7 +1,7 @@ -import * as fs from "fs/promises" +import { FileChangeEvent_ChangeType, SubscribeToFileRequest } from "@shared/proto/host/watch" import * as fsSync from "fs" -import { SubscribeToFileRequest, FileChangeEvent_ChangeType } from "@shared/proto/host/watch" -import { StreamingResponseHandler, getRequestRegistry } from "@/hosts/vscode/hostbridge-grpc-handler" +import * as fs from "fs/promises" +import { getRequestRegistry, StreamingResponseHandler } from "@/hosts/vscode/hostbridge-grpc-handler" // Debounce configuration const DEBOUNCE_DELAY = 100 // ms @@ -38,7 +38,7 @@ export async function subscribeToFile( if (!fileWatchers.has(filePath)) { // Create a new watcher for this file using Node.js fs.watch API // This is more reliable than the VSCode FileSystemWatcher for detecting file saves - const watcher = fsSync.watch(filePath, { persistent: true }, async (eventType, filename) => { + const watcher = fsSync.watch(filePath, { persistent: true }, async (eventType, _filename) => { if (eventType === "change") { try { const content = await fs.readFile(filePath, "utf8") @@ -120,7 +120,7 @@ export async function subscribeToFile( } } } - } catch (error) { + } catch (_error) { // File doesn't exist, so it was deleted console.log(`[DEBUG] File deleted: ${filePath}`) diff --git a/src/hosts/vscode/hostbridge/window/getOpenTabs.ts b/src/hosts/vscode/hostbridge/window/getOpenTabs.ts index 33c6c84e..076b72b5 100644 --- a/src/hosts/vscode/hostbridge/window/getOpenTabs.ts +++ b/src/hosts/vscode/hostbridge/window/getOpenTabs.ts @@ -1,4 +1,4 @@ -import { window, TabInputText } from "vscode" +import { TabInputText, window } from "vscode" import { GetOpenTabsRequest, GetOpenTabsResponse } from "@/shared/proto/host/window" export async function getOpenTabs(_: GetOpenTabsRequest): Promise { diff --git a/src/hosts/vscode/hostbridge/window/getVisibleTabs.ts b/src/hosts/vscode/hostbridge/window/getVisibleTabs.ts index 47fadcd1..a0c63708 100644 --- a/src/hosts/vscode/hostbridge/window/getVisibleTabs.ts +++ b/src/hosts/vscode/hostbridge/window/getVisibleTabs.ts @@ -1,4 +1,4 @@ -import { window, TabInputText } from "vscode" +import { window } from "vscode" import { GetVisibleTabsRequest, GetVisibleTabsResponse } from "@/shared/proto/host/window" export async function getVisibleTabs(_: GetVisibleTabsRequest): Promise { diff --git a/src/hosts/vscode/hostbridge/window/showMessage.ts b/src/hosts/vscode/hostbridge/window/showMessage.ts index baab02e3..91d1a2a5 100644 --- a/src/hosts/vscode/hostbridge/window/showMessage.ts +++ b/src/hosts/vscode/hostbridge/window/showMessage.ts @@ -8,7 +8,7 @@ export async function showMessage(request: ShowMessageRequest): Promise { const options: vscode.OpenDialogOptions = {} diff --git a/src/hosts/vscode/hostbridge/window/showSaveDialog.ts b/src/hosts/vscode/hostbridge/window/showSaveDialog.ts index 3ccde072..2634e8d3 100644 --- a/src/hosts/vscode/hostbridge/window/showSaveDialog.ts +++ b/src/hosts/vscode/hostbridge/window/showSaveDialog.ts @@ -1,4 +1,4 @@ -import { window, Uri, SaveDialogOptions } from "vscode" +import { SaveDialogOptions, Uri, window } from "vscode" import { ShowSaveDialogRequest, ShowSaveDialogResponse } from "@/shared/proto/index.host" export async function showSaveDialog(request: ShowSaveDialogRequest): Promise { diff --git a/src/hosts/vscode/hostbridge/workspace/getDiagnostics.test.ts b/src/hosts/vscode/hostbridge/workspace/getDiagnostics.test.ts index f6314cb4..0117c2ea 100644 --- a/src/hosts/vscode/hostbridge/workspace/getDiagnostics.test.ts +++ b/src/hosts/vscode/hostbridge/workspace/getDiagnostics.test.ts @@ -1,8 +1,8 @@ -import { describe, it } from "mocha" import { expect } from "chai" +import { describe, it } from "mocha" import * as vscode from "vscode" -import { convertToFileDiagnostics, convertVscodeDiagnostics } from "./getDiagnostics" import { DiagnosticSeverity } from "@/shared/proto/index.cline" +import { convertToFileDiagnostics, convertVscodeDiagnostics } from "./getDiagnostics" describe("getDiagnostics conversion functions", () => { describe("convertToFileDiagnostics", () => { diff --git a/src/hosts/vscode/hostbridge/workspace/getDiagnostics.ts b/src/hosts/vscode/hostbridge/workspace/getDiagnostics.ts index 703e25df..26c78876 100644 --- a/src/hosts/vscode/hostbridge/workspace/getDiagnostics.ts +++ b/src/hosts/vscode/hostbridge/workspace/getDiagnostics.ts @@ -1,6 +1,6 @@ -import { GetDiagnosticsRequest, GetDiagnosticsResponse } from "@/shared/proto/host/workspace" -import { Diagnostic, DiagnosticPosition, DiagnosticRange, DiagnosticSeverity, FileDiagnostics } from "@/shared/proto/index.cline" import * as vscode from "vscode" +import { GetDiagnosticsRequest, GetDiagnosticsResponse } from "@/shared/proto/host/workspace" +import { Diagnostic, DiagnosticSeverity, FileDiagnostics } from "@/shared/proto/index.cline" import "@/utils/path" // for String.prototype.toPosix export async function getDiagnostics(_request: GetDiagnosticsRequest): Promise { diff --git a/src/hosts/vscode/hostbridge/workspace/getWorkspacePaths.ts b/src/hosts/vscode/hostbridge/workspace/getWorkspacePaths.ts index 1fece8e1..6cbe1c8b 100644 --- a/src/hosts/vscode/hostbridge/workspace/getWorkspacePaths.ts +++ b/src/hosts/vscode/hostbridge/workspace/getWorkspacePaths.ts @@ -1,5 +1,5 @@ -import { GetWorkspacePathsRequest, GetWorkspacePathsResponse } from "@/shared/proto/index.host" import * as vscode from "vscode" +import { GetWorkspacePathsRequest, GetWorkspacePathsResponse } from "@/shared/proto/index.host" export async function getWorkspacePaths(_: GetWorkspacePathsRequest): Promise { const paths = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath) ?? [] return GetWorkspacePathsResponse.create({ paths: paths }) diff --git a/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.test.ts b/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.test.ts index 429153f5..59bbe862 100644 --- a/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.test.ts +++ b/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.test.ts @@ -1,9 +1,9 @@ -import { describe, it, before, after, beforeEach } from "mocha" import { expect } from "chai" -import * as vscode from "vscode" -import * as path from "path" import * as fs from "fs/promises" +import { after, before, beforeEach, describe, it } from "mocha" import * as os from "os" +import * as path from "path" +import * as vscode from "vscode" import { saveOpenDocumentIfDirty } from "@/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty" import { SaveOpenDocumentIfDirtyRequest } from "@/shared/proto/index.host" @@ -26,7 +26,7 @@ describe("saveOpenDocumentIfDirty Integration Test", () => { await vscode.commands.executeCommand("workbench.action.closeAllEditors") try { await fs.rm(testWorkspaceRoot, { recursive: true, force: true }) - } catch (error) { + } catch (_error) { // Directory might not exist, ignore } }) diff --git a/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.ts b/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.ts index d9100ee9..1cc92a6e 100644 --- a/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.ts +++ b/src/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty.ts @@ -1,6 +1,6 @@ -import { SaveOpenDocumentIfDirtyRequest, SaveOpenDocumentIfDirtyResponse } from "@/shared/proto/index.host" -import * as vscode from "vscode" import { arePathsEqual } from "@utils/path" +import * as vscode from "vscode" +import { SaveOpenDocumentIfDirtyRequest, SaveOpenDocumentIfDirtyResponse } from "@/shared/proto/index.host" export async function saveOpenDocumentIfDirty(request: SaveOpenDocumentIfDirtyRequest): Promise { const existingDocument = vscode.workspace.textDocuments.find((doc) => arePathsEqual(doc.uri.fsPath, request.filePath)) diff --git a/src/integrations/checkpoints/CheckpointExclusions.ts b/src/integrations/checkpoints/CheckpointExclusions.ts index 66a1e401..a40f0a06 100644 --- a/src/integrations/checkpoints/CheckpointExclusions.ts +++ b/src/integrations/checkpoints/CheckpointExclusions.ts @@ -1,6 +1,6 @@ +import { fileExistsAtPath } from "@utils/fs" import fs from "fs/promises" import { join } from "path" -import { fileExistsAtPath } from "@utils/fs" import { GIT_DISABLED_SUFFIX } from "./CheckpointGitOperations" /** diff --git a/src/integrations/checkpoints/CheckpointGitOperations.ts b/src/integrations/checkpoints/CheckpointGitOperations.ts index 07d6dd2e..b089f86e 100644 --- a/src/integrations/checkpoints/CheckpointGitOperations.ts +++ b/src/integrations/checkpoints/CheckpointGitOperations.ts @@ -202,10 +202,10 @@ export class GitOperations { const durationMs = Math.round(performance.now() - startTime) console.debug(`Checkpoint add operation completed in ${durationMs}ms`) return { success: true } - } catch (error) { + } catch (_error) { return { success: false } } - } catch (error) { + } catch (_error) { return { success: false } } finally { await this.renameNestedGitRepos(false) diff --git a/src/integrations/checkpoints/CheckpointMigration.ts b/src/integrations/checkpoints/CheckpointMigration.ts index 5691c651..e4ec1cc7 100644 --- a/src/integrations/checkpoints/CheckpointMigration.ts +++ b/src/integrations/checkpoints/CheckpointMigration.ts @@ -1,7 +1,6 @@ +import { fileExistsAtPath } from "@utils/fs" import fs from "fs/promises" import * as path from "path" -import * as vscode from "vscode" -import { fileExistsAtPath } from "@utils/fs" import { HostProvider } from "@/hosts/host-provider" /** @@ -54,7 +53,7 @@ export async function cleanupLegacyCheckpoints(globalStoragePath: string): Promi HostProvider.get().logToChannel(`Deleting legacy checkpoints in ${folder.folder}`) try { await fs.rm(folderCheckpointsDir, { recursive: true, force: true }) - } catch (error) { + } catch (_error) { // Ignore error if directory removal fails HostProvider.get().logToChannel( `Warning: Failed to delete checkpoints in ${folder.folder}, continuing...`, diff --git a/src/integrations/checkpoints/CheckpointTracker.ts b/src/integrations/checkpoints/CheckpointTracker.ts index d18550f8..57953295 100644 --- a/src/integrations/checkpoints/CheckpointTracker.ts +++ b/src/integrations/checkpoints/CheckpointTracker.ts @@ -110,7 +110,7 @@ class CheckpointTracker { // Check if git is installed by attempting to get version try { await simpleGit().version() - } catch (error) { + } catch (_error) { throw new Error("Git must be installed to use checkpoints.") // FIXME: must match what we check for in TaskHeader to show link } diff --git a/src/integrations/checkpoints/CheckpointUtils.ts b/src/integrations/checkpoints/CheckpointUtils.ts index aab4c1d5..72c32412 100644 --- a/src/integrations/checkpoints/CheckpointUtils.ts +++ b/src/integrations/checkpoints/CheckpointUtils.ts @@ -1,7 +1,6 @@ -import { mkdir, access, constants } from "fs/promises" -import * as path from "path" -import * as vscode from "vscode" +import { access, constants, mkdir } from "fs/promises" import os from "os" +import * as path from "path" import { getCwd, getDesktopDir } from "@/utils/path" /** @@ -19,7 +18,7 @@ import { getCwd, getDesktopDir } from "@/utils/path" * @returns Promise The absolute path to the shadow git directory * @throws Error if global storage path is invalid */ -export async function getShadowGitPath(globalStoragePath: string, taskId: string, cwdHash: string): Promise { +export async function getShadowGitPath(globalStoragePath: string, _taskId: string, cwdHash: string): Promise { if (!globalStoragePath) { throw new Error("Global storage uri is invalid") } diff --git a/src/integrations/claude-code/run.test.ts b/src/integrations/claude-code/run.test.ts index 09004428..08dbccfd 100644 --- a/src/integrations/claude-code/run.test.ts +++ b/src/integrations/claude-code/run.test.ts @@ -1,6 +1,6 @@ import { expect } from "chai" -import proxyquire from "proxyquire" import path from "path" +import proxyquire from "proxyquire" import sinon from "sinon" const createMockProcess = () => { @@ -53,7 +53,7 @@ const createMockReadlineInterface = () => { return mockInterface } -const mockExeca = sinon.fake((...args) => { +const mockExeca = sinon.fake((..._args) => { return createMockProcess() }) diff --git a/src/integrations/claude-code/run.ts b/src/integrations/claude-code/run.ts index a8bebf27..9716bcff 100644 --- a/src/integrations/claude-code/run.ts +++ b/src/integrations/claude-code/run.ts @@ -1,12 +1,12 @@ -import { getCwd } from "@/utils/path" +import crypto from "node:crypto" +import fs from "node:fs/promises" import os from "node:os" import path from "node:path" -import fs from "node:fs/promises" import type Anthropic from "@anthropic-ai/sdk" import { execa } from "execa" import readline from "readline" +import { getCwd } from "@/utils/path" import { ClaudeCodeMessage } from "./types" -import crypto from "node:crypto" type ClaudeCodeOptions = { systemPrompt: string diff --git a/src/integrations/diagnostics/__tests__/index.test.ts b/src/integrations/diagnostics/__tests__/index.test.ts index 6cda5ee4..9872fca7 100644 --- a/src/integrations/diagnostics/__tests__/index.test.ts +++ b/src/integrations/diagnostics/__tests__/index.test.ts @@ -1,9 +1,9 @@ -import { describe, it, beforeEach } from "mocha" -import { expect } from "chai" -import { getNewDiagnostics, diagnosticsToProblemsString } from "../" import { DiagnosticSeverity, FileDiagnostics } from "@shared/proto/index.cline" +import { expect } from "chai" +import { beforeEach, describe, it } from "mocha" import * as sinon from "sinon" import * as pathUtils from "@/utils/path" +import { diagnosticsToProblemsString, getNewDiagnostics } from "../" describe("Diagnostics Tests", () => { describe("getNewDiagnostics", () => { @@ -171,10 +171,10 @@ describe("Diagnostics Tests", () => { }) describe("diagnosticsToProblemsString", () => { - let getCwdStub: sinon.SinonStub + let _getCwdStub: sinon.SinonStub beforeEach(() => { - getCwdStub = sinon.stub(pathUtils, "getCwd").resolves("/workspace") + _getCwdStub = sinon.stub(pathUtils, "getCwd").resolves("/workspace") }) afterEach(() => { diff --git a/src/integrations/diagnostics/index.ts b/src/integrations/diagnostics/index.ts index c860aba3..03042bb4 100644 --- a/src/integrations/diagnostics/index.ts +++ b/src/integrations/diagnostics/index.ts @@ -1,7 +1,7 @@ -import * as path from "path" import deepEqual from "fast-deep-equal" -import { getCwd } from "@/utils/path" +import * as path from "path" import { Diagnostic, DiagnosticSeverity, FileDiagnostics } from "@/shared/proto/index.cline" +import { getCwd } from "@/utils/path" export function getNewDiagnostics(oldDiagnostics: FileDiagnostics[], newDiagnostics: FileDiagnostics[]): FileDiagnostics[] { const oldMap = new Map() @@ -29,7 +29,7 @@ export async function diagnosticsToProblemsString( diagnostics: FileDiagnostics[], severities?: DiagnosticSeverity[], ): Promise { - let results = [] + const results = [] for (const fileDiagnostics of diagnostics) { const problems = fileDiagnostics.diagnostics.filter((d) => !severities || severities.includes(d.severity)) const problemString = await singleFileDiagnosticsToProblemsString(fileDiagnostics.filePath, problems) diff --git a/src/integrations/editor/detect-omission.ts b/src/integrations/editor/detect-omission.ts index ae2dfb8d..b5dca770 100644 --- a/src/integrations/editor/detect-omission.ts +++ b/src/integrations/editor/detect-omission.ts @@ -1,6 +1,6 @@ -import { openExternal } from "@utils/env" import { HostProvider } from "@hosts/host-provider" import { ShowMessageType } from "@shared/proto/host/window" +import { openExternal } from "@utils/env" /** * Detects potential AI-generated code omissions in the given file content. diff --git a/src/integrations/misc/extract-file-content.ts b/src/integrations/misc/extract-file-content.ts index 6d84bb71..1203043e 100644 --- a/src/integrations/misc/extract-file-content.ts +++ b/src/integrations/misc/extract-file-content.ts @@ -1,8 +1,8 @@ -import * as path from "path" -import fs from "fs/promises" import { Anthropic } from "@anthropic-ai/sdk" -import { callTextExtractionFunctions } from "./extract-text" +import fs from "fs/promises" +import * as path from "path" import { extractImageContent } from "./extract-images" +import { callTextExtractionFunctions } from "./extract-text" export type FileContentResult = { text: string @@ -17,7 +17,7 @@ export async function extractFileContent(absolutePath: string, modelSupportsImag // Check if file exists first try { await fs.access(absolutePath) - } catch (error) { + } catch (_error) { throw new Error(`File not found: ${absolutePath}`) } diff --git a/src/integrations/misc/extract-images.ts b/src/integrations/misc/extract-images.ts index 9c5e8548..98362d88 100644 --- a/src/integrations/misc/extract-images.ts +++ b/src/integrations/misc/extract-images.ts @@ -1,7 +1,6 @@ -import fs from "fs/promises" -import * as path from "path" -import sizeOf from "image-size" import { Anthropic } from "@anthropic-ai/sdk" +import fs from "fs/promises" +import sizeOf from "image-size" import { getMimeType } from "./process-files" /** diff --git a/src/integrations/misc/extract-text.ts b/src/integrations/misc/extract-text.ts index 050d612b..b3a17486 100644 --- a/src/integrations/misc/extract-text.ts +++ b/src/integrations/misc/extract-text.ts @@ -1,12 +1,12 @@ +import ExcelJS from "exceljs" +import fs from "fs/promises" +import * as iconv from "iconv-lite" +import { isBinaryFile } from "isbinaryfile" +import * as chardet from "jschardet" +import mammoth from "mammoth" import * as path from "path" // @ts-ignore-next-line import pdf from "pdf-parse/lib/pdf-parse" -import mammoth from "mammoth" -import fs from "fs/promises" -import { isBinaryFile } from "isbinaryfile" -import * as chardet from "jschardet" -import * as iconv from "iconv-lite" -import ExcelJS from "exceljs" export async function detectEncoding(fileBuffer: Buffer, fileExtension?: string): Promise { const detected = chardet.detect(fileBuffer) @@ -28,7 +28,7 @@ export async function detectEncoding(fileBuffer: Buffer, fileExtension?: string) export async function extractTextFromFile(filePath: string): Promise { try { await fs.access(filePath) - } catch (error) { + } catch (_error) { throw new Error(`File not found: ${filePath}`) } @@ -139,7 +139,7 @@ async function extractTextFromExcel(filePath: string): Promise { try { await workbook.xlsx.readFile(filePath) - workbook.eachSheet((worksheet, sheetId) => { + workbook.eachSheet((worksheet, _sheetId) => { // Skip hidden sheets if (worksheet.state === "hidden" || worksheet.state === "veryHidden") { return @@ -157,7 +157,7 @@ async function extractTextFromExcel(filePath: string): Promise { const rowTexts: string[] = [] let hasContent = false - row.eachCell({ includeEmpty: true }, (cell, colNumber) => { + row.eachCell({ includeEmpty: true }, (cell, _colNumber) => { const cellText = formatCellValue(cell) if (cellText.trim()) { hasContent = true diff --git a/src/integrations/misc/link-preview.ts b/src/integrations/misc/link-preview.ts index 6c371677..e96a2d05 100644 --- a/src/integrations/misc/link-preview.ts +++ b/src/integrations/misc/link-preview.ts @@ -62,7 +62,7 @@ export async function fetchOpenGraphData(url: string): Promise { siteName: data.ogSiteName || new URL(url).hostname, type: data.ogType, } - } catch (error) { + } catch (_error) { // Return basic information based on the URL try { const urlObj = new URL(url) @@ -98,7 +98,7 @@ export async function detectImageUrl(url: string): Promise { const contentType = response.headers["content-type"] return contentType && contentType.startsWith("image/") - } catch (error) { + } catch (_error) { // If we can't determine, fall back to checking the file extension return /\.(jpg|jpeg|png|gif|webp|bmp|svg|tiff|tif|avif)$/i.test(url) } diff --git a/src/integrations/misc/open-file.ts b/src/integrations/misc/open-file.ts index d022b6a4..b62d481a 100644 --- a/src/integrations/misc/open-file.ts +++ b/src/integrations/misc/open-file.ts @@ -1,10 +1,8 @@ import { writeFile } from "@utils/fs" -import { arePathsEqual } from "@utils/path" import * as os from "os" import * as path from "path" -import * as vscode from "vscode" import { HostProvider } from "@/hosts/host-provider" -import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { ShowMessageType } from "@/shared/proto/host/window" export async function openImage(dataUri: string) { const matches = dataUri.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/) @@ -37,7 +35,7 @@ export async function openFile(absolutePath: string, preserveFocus: boolean = fa path: absolutePath, options: { preserveFocus, preview }, }) - } catch (error) { + } catch (_error) { HostProvider.window.showMessage({ type: ShowMessageType.ERROR, message: `Could not open file!`, diff --git a/src/integrations/terminal/TerminalManager.ts b/src/integrations/terminal/TerminalManager.ts index 7b203ec9..57a02a5f 100644 --- a/src/integrations/terminal/TerminalManager.ts +++ b/src/integrations/terminal/TerminalManager.ts @@ -1,7 +1,7 @@ -import pWaitFor from "p-wait-for" -import * as vscode from "vscode" import { arePathsEqual } from "@utils/path" import { getShellForProfile } from "@utils/shell" +import pWaitFor from "p-wait-for" +import * as vscode from "vscode" import { mergePromise, TerminalProcess, TerminalProcessResultPromise } from "./TerminalProcess" import { TerminalInfo, TerminalRegistry } from "./TerminalRegistry" @@ -106,7 +106,7 @@ export class TerminalManager { // Creating a read stream here results in a more consistent output. This is most obvious when running the `date` command. e?.execution?.read() }) - } catch (error) { + } catch (_error) { // console.error("Error setting up onDidEndTerminalShellExecution", error) } if (disposable) { @@ -291,7 +291,7 @@ export class TerminalManager { setTimeout(() => reject(new Error(`CWD timeout: Failed to update to ${cwd}`)), 1000), ), ]) - } catch (err) { + } catch (_err) { // Clear pending state on timeout availableTerminal.pendingCwdChange = undefined availableTerminal.cwdResolved = undefined @@ -366,7 +366,7 @@ export class TerminalManager { return { closedCount: 0, busyTerminals: [] } } - const oldProfileId = this.defaultTerminalProfile + const _oldProfileId = this.defaultTerminalProfile this.defaultTerminalProfile = profileId // Get the shell path for the new profile diff --git a/src/integrations/terminal/TerminalProcess.test.ts b/src/integrations/terminal/TerminalProcess.test.ts index 80c1fe6a..1908983f 100644 --- a/src/integrations/terminal/TerminalProcess.test.ts +++ b/src/integrations/terminal/TerminalProcess.test.ts @@ -1,5 +1,5 @@ -import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import { afterEach, beforeEach, describe, it } from "mocha" +import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils" import "should" import * as sinon from "sinon" import * as vscode from "vscode" @@ -218,7 +218,9 @@ describe("TerminalProcess (Integration Tests)", () => { // Check that the correct methods were called and events emitted sendTextStub.calledWith("test-command", true).should.be.true() ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() - ;(emitSpy as sinon.SinonSpy).calledWith("continue").should.be.true() + ;(emitSpy as sinon.SinonSpy) + .calledWith("continue") + .should.be.true() // This event should be emitted for terminals without shell integration ;(emitSpy as sinon.SinonSpy).calledWith("no_shell_integration").should.be.true() @@ -227,7 +229,7 @@ describe("TerminalProcess (Integration Tests)", () => { // The following tests require shell integration and controlled terminal output describe("Shell integration tests", () => { // We'll mock the terminal run process and TerminalProcess for these tests - it("should emit completed and continue events when command finishes", async function () { + it("should emit completed and continue events when command finishes", async () => { // Create a terminal to ensure proper interface, but we'll use mocking under the hood const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) @@ -252,7 +254,9 @@ describe("TerminalProcess (Integration Tests)", () => { await process.run(terminal, "echo test") // Verify the executeCommand was called with the right command - mockExecuteCommand.calledWith("echo test").should.be.true() + mockExecuteCommand + .calledWith("echo test") + .should.be.true() // Check that the events were emitted ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() @@ -262,7 +266,7 @@ describe("TerminalProcess (Integration Tests)", () => { // Tests with controlled output describe("Controlled output tests", () => { - it("should emit line events for each line of output", async function () { + it("should emit line events for each line of output", async () => { // Create a terminal const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) @@ -287,7 +291,7 @@ describe("TerminalProcess (Integration Tests)", () => { ;(emitSpy as sinon.SinonSpy).calledWith("line", "line3").should.be.true() }) - it("should properly handle process hot state (e.g. compiling)", async function () { + it("should properly handle process hot state (e.g. compiling)", async () => { // Create a terminal const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) @@ -315,7 +319,7 @@ describe("TerminalProcess (Integration Tests)", () => { foundCompilingTimeout.length.should.be.greaterThan(0) }) - it("should handle standard commands with normal hot timeout", async function () { + it("should handle standard commands with normal hot timeout", async () => { // Create a terminal const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) @@ -345,7 +349,7 @@ describe("TerminalProcess (Integration Tests)", () => { ;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true() }) - it("should correctly filter command echoes based on current implementation", async function () { + it("should correctly filter command echoes based on current implementation", async () => { // Create a terminal const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) @@ -371,12 +375,14 @@ describe("TerminalProcess (Integration Tests)", () => { // Check that "test-command" was filtered out but "test command" was not ;(emitSpy as sinon.SinonSpy).calledWith("line", "test command").should.be.true() - ;(emitSpy as sinon.SinonSpy).calledWith("line", "other output").should.be.true() + ;(emitSpy as sinon.SinonSpy) + .calledWith("line", "other output") + .should.be.true() // This should never be called because it should be filtered ;(emitSpy as sinon.SinonSpy).calledWith("line", "test-command").should.be.false() }) - it("should handle npm run commands", async function () { + it("should handle npm run commands", async () => { // Create a terminal const terminal = TerminalRegistry.createTerminal().terminal createdTerminals.push(terminal) diff --git a/src/integrations/terminal/TerminalProcess.ts b/src/integrations/terminal/TerminalProcess.ts index f208a2fa..4f754b16 100644 --- a/src/integrations/terminal/TerminalProcess.ts +++ b/src/integrations/terminal/TerminalProcess.ts @@ -227,7 +227,7 @@ export class TerminalProcess extends EventEmitter { this.buffer += chunk let lineEndIndex: number while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) { - let line = this.buffer.slice(0, lineEndIndex).trimEnd() // removes trailing \r + const line = this.buffer.slice(0, lineEndIndex).trimEnd() // removes trailing \r // Remove \r if present (for Windows-style line endings) // if (line.endsWith("\r")) { // line = line.slice(0, -1) diff --git a/src/integrations/terminal/TerminalRegistry.ts b/src/integrations/terminal/TerminalRegistry.ts index 70f95ea7..f8ddbc15 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -36,41 +36,42 @@ export class TerminalRegistry { } const terminal = vscode.window.createTerminal(terminalOptions) + TerminalRegistry.nextTerminalId++ const newInfo: TerminalInfo = { terminal, busy: false, lastCommand: "", - id: this.nextTerminalId++, + id: TerminalRegistry.nextTerminalId, shellPath, lastActive: Date.now(), } - this.terminals.push(newInfo) + TerminalRegistry.terminals.push(newInfo) return newInfo } static getTerminal(id: number): TerminalInfo | undefined { - const terminalInfo = this.terminals.find((t) => t.id === id) - if (terminalInfo && this.isTerminalClosed(terminalInfo.terminal)) { - this.removeTerminal(id) + const terminalInfo = TerminalRegistry.terminals.find((t) => t.id === id) + if (terminalInfo && TerminalRegistry.isTerminalClosed(terminalInfo.terminal)) { + TerminalRegistry.removeTerminal(id) return undefined } return terminalInfo } static updateTerminal(id: number, updates: Partial) { - const terminal = this.getTerminal(id) + const terminal = TerminalRegistry.getTerminal(id) if (terminal) { Object.assign(terminal, updates) } } static removeTerminal(id: number) { - this.terminals = this.terminals.filter((t) => t.id !== id) + TerminalRegistry.terminals = TerminalRegistry.terminals.filter((t) => t.id !== id) } static getAllTerminals(): TerminalInfo[] { - this.terminals = this.terminals.filter((t) => !this.isTerminalClosed(t.terminal)) - return this.terminals + TerminalRegistry.terminals = TerminalRegistry.terminals.filter((t) => !TerminalRegistry.isTerminalClosed(t.terminal)) + return TerminalRegistry.terminals } // The exit status of the terminal will be undefined while the terminal is active. (This value is set when onDidCloseTerminal is fired.) diff --git a/src/integrations/terminal/get-latest-output.ts b/src/integrations/terminal/get-latest-output.ts index 79192ae3..f08ce1a4 100644 --- a/src/integrations/terminal/get-latest-output.ts +++ b/src/integrations/terminal/get-latest-output.ts @@ -1,5 +1,5 @@ -import * as vscode from "vscode" import { readTextFromClipboard, writeTextToClipboard } from "@utils/env" +import * as vscode from "vscode" /** * Gets the contents of the active terminal diff --git a/src/integrations/theme/default-themes/dark_plus.json b/src/integrations/theme/default-themes/dark_plus.json index 3a45b1eb..8e7c180f 100644 --- a/src/integrations/theme/default-themes/dark_plus.json +++ b/src/integrations/theme/default-themes/dark_plus.json @@ -100,14 +100,19 @@ }, { "name": "Constants and enums", - "scope": ["variable.other.constant", "variable.other.enummember"], + "scope": [ + "variable.other.constant", + "variable.other.enummember" + ], "settings": { "foreground": "#4FC1FF" } }, { "name": "Object keys, TS grammar specific", - "scope": ["meta.object-literal.key"], + "scope": [ + "meta.object-literal.key" + ], "settings": { "foreground": "#9CDCFE" } @@ -154,7 +159,10 @@ } }, { - "scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"], + "scope": [ + "keyword.operator.or.regexp", + "keyword.control.anchor.regexp" + ], "settings": { "foreground": "#DCDCAA" } @@ -166,7 +174,10 @@ } }, { - "scope": ["constant.character", "constant.other.option"], + "scope": [ + "constant.character", + "constant.other.option" + ], "settings": { "foreground": "#569cd6" } diff --git a/src/integrations/theme/default-themes/dark_vs.json b/src/integrations/theme/default-themes/dark_vs.json index 2abaefad..85cd4880 100644 --- a/src/integrations/theme/default-themes/dark_vs.json +++ b/src/integrations/theme/default-themes/dark_vs.json @@ -94,7 +94,10 @@ } }, { - "scope": ["entity.name.tag.css", "entity.name.tag.less"], + "scope": [ + "entity.name.tag.css", + "entity.name.tag.less" + ], "settings": { "foreground": "#d7ba7d" } @@ -203,7 +206,10 @@ } }, { - "scope": ["meta.preprocessor", "entity.name.function.preprocessor"], + "scope": [ + "meta.preprocessor", + "entity.name.function.preprocessor" + ], "settings": { "foreground": "#569cd6" } @@ -245,13 +251,19 @@ } }, { - "scope": ["storage.modifier", "keyword.operator.noexcept"], + "scope": [ + "storage.modifier", + "keyword.operator.noexcept" + ], "settings": { "foreground": "#569cd6" } }, { - "scope": ["string", "meta.embedded.assembly"], + "scope": [ + "string", + "meta.embedded.assembly" + ], "settings": { "foreground": "#ce9178" } @@ -287,7 +299,9 @@ }, { "name": "Reset JavaScript string interpolation expression", - "scope": ["meta.template.expression"], + "scope": [ + "meta.template.expression" + ], "settings": { "foreground": "#d4d4d4" } @@ -345,7 +359,10 @@ } }, { - "scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"], + "scope": [ + "punctuation.section.embedded.begin.php", + "punctuation.section.embedded.end.php" + ], "settings": { "foreground": "#569cd6" } @@ -364,7 +381,11 @@ }, { "name": "coloring of the Java import and package identifiers", - "scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"], + "scope": [ + "storage.modifier.import.java", + "variable.language.wildcard.java", + "storage.modifier.package.java" + ], "settings": { "foreground": "#d4d4d4" } diff --git a/src/integrations/theme/default-themes/hc_black.json b/src/integrations/theme/default-themes/hc_black.json index b88b869d..ebb49d98 100644 --- a/src/integrations/theme/default-themes/hc_black.json +++ b/src/integrations/theme/default-themes/hc_black.json @@ -57,7 +57,12 @@ } }, { - "scope": ["constant.numeric", "constant.other.color.rgb-value", "constant.other.rgb-value", "support.constant.color"], + "scope": [ + "constant.numeric", + "constant.other.color.rgb-value", + "constant.other.rgb-value", + "support.constant.color" + ], "settings": { "foreground": "#b5cea8" } @@ -81,7 +86,10 @@ } }, { - "scope": ["entity.name.tag.css", "entity.name.tag.less"], + "scope": [ + "entity.name.tag.css", + "entity.name.tag.less" + ], "settings": { "foreground": "#d7ba7d" } @@ -165,7 +173,9 @@ }, { "name": "brackets of XML/HTML tags", - "scope": ["punctuation.definition.tag"], + "scope": [ + "punctuation.definition.tag" + ], "settings": { "foreground": "#808080" } @@ -249,7 +259,9 @@ }, { "name": "Reset JavaScript string interpolation expression", - "scope": ["meta.template.expression"], + "scope": [ + "meta.template.expression" + ], "settings": { "foreground": "#ffffff" } @@ -315,7 +327,11 @@ }, { "name": "coloring of the Java import and package identifiers", - "scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"], + "scope": [ + "storage.modifier.import.java", + "variable.language.wildcard.java", + "storage.modifier.package.java" + ], "settings": { "foreground": "#d4d4d4" } @@ -401,14 +417,20 @@ }, { "name": "Variable and parameter name", - "scope": ["variable", "meta.definition.variable.name", "support.variable"], + "scope": [ + "variable", + "meta.definition.variable.name", + "support.variable" + ], "settings": { "foreground": "#9CDCFE" } }, { "name": "Object keys, TS grammar specific", - "scope": ["meta.object-literal.key"], + "scope": [ + "meta.object-literal.key" + ], "settings": { "foreground": "#9CDCFE" } diff --git a/src/integrations/theme/default-themes/hc_light.json b/src/integrations/theme/default-themes/hc_light.json index 5310173d..f93b1ec3 100644 --- a/src/integrations/theme/default-themes/hc_light.json +++ b/src/integrations/theme/default-themes/hc_light.json @@ -3,7 +3,11 @@ "name": "Light High Contrast", "tokenColors": [ { - "scope": ["meta.embedded", "source.groovy.embedded", "variable.legacy.builtin.python"], + "scope": [ + "meta.embedded", + "source.groovy.embedded", + "variable.legacy.builtin.python" + ], "settings": { "foreground": "#292929" } @@ -146,7 +150,10 @@ } }, { - "scope": ["punctuation.definition.quote.begin.markdown", "punctuation.definition.list.begin.markdown"], + "scope": [ + "punctuation.definition.quote.begin.markdown", + "punctuation.definition.list.begin.markdown" + ], "settings": { "foreground": "#0451A5" } @@ -164,7 +171,10 @@ } }, { - "scope": ["meta.preprocessor", "entity.name.function.preprocessor"], + "scope": [ + "meta.preprocessor", + "entity.name.function.preprocessor" + ], "settings": { "foreground": "#0F4A85" } @@ -200,13 +210,19 @@ } }, { - "scope": ["storage.modifier", "keyword.operator.noexcept"], + "scope": [ + "storage.modifier", + "keyword.operator.noexcept" + ], "settings": { "foreground": "#0F4A85" } }, { - "scope": ["string", "meta.embedded.assembly"], + "scope": [ + "string", + "meta.embedded.assembly" + ], "settings": { "foreground": "#0F4A85" } @@ -250,7 +266,9 @@ } }, { - "scope": ["meta.template.expression"], + "scope": [ + "meta.template.expression" + ], "settings": { "foreground": "#000000" } @@ -281,7 +299,9 @@ } }, { - "scope": ["support.type.property-name.json"], + "scope": [ + "support.type.property-name.json" + ], "settings": { "foreground": "#0451A5" } @@ -328,7 +348,10 @@ } }, { - "scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"], + "scope": [ + "punctuation.section.embedded.begin.php", + "punctuation.section.embedded.end.php" + ], "settings": { "foreground": "#0F4A85" } @@ -346,7 +369,11 @@ } }, { - "scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"], + "scope": [ + "storage.modifier.import.java", + "variable.language.wildcard.java", + "storage.modifier.package.java" + ], "settings": { "foreground": "#000000" } @@ -448,13 +475,18 @@ } }, { - "scope": ["variable.other.constant", "variable.other.enummember"], + "scope": [ + "variable.other.constant", + "variable.other.enummember" + ], "settings": { "foreground": "#02715D" } }, { - "scope": ["meta.object-literal.key"], + "scope": [ + "meta.object-literal.key" + ], "settings": { "foreground": "#001080" } @@ -505,7 +537,10 @@ } }, { - "scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"], + "scope": [ + "keyword.operator.or.regexp", + "keyword.control.anchor.regexp" + ], "settings": { "foreground": "#EE0000" } diff --git a/src/integrations/theme/default-themes/light_plus.json b/src/integrations/theme/default-themes/light_plus.json index e103f483..b8e386c0 100644 --- a/src/integrations/theme/default-themes/light_plus.json +++ b/src/integrations/theme/default-themes/light_plus.json @@ -100,14 +100,19 @@ }, { "name": "Constants and enums", - "scope": ["variable.other.constant", "variable.other.enummember"], + "scope": [ + "variable.other.constant", + "variable.other.enummember" + ], "settings": { "foreground": "#0070C1" } }, { "name": "Object keys, TS grammar specific", - "scope": ["meta.object-literal.key"], + "scope": [ + "meta.object-literal.key" + ], "settings": { "foreground": "#001080" } @@ -160,13 +165,19 @@ } }, { - "scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"], + "scope": [ + "keyword.operator.or.regexp", + "keyword.control.anchor.regexp" + ], "settings": { "foreground": "#EE0000" } }, { - "scope": ["constant.character", "constant.other.option"], + "scope": [ + "constant.character", + "constant.other.option" + ], "settings": { "foreground": "#0000ff" } diff --git a/src/integrations/theme/default-themes/light_vs.json b/src/integrations/theme/default-themes/light_vs.json index f75e0942..918cf5b5 100644 --- a/src/integrations/theme/default-themes/light_vs.json +++ b/src/integrations/theme/default-themes/light_vs.json @@ -185,7 +185,10 @@ } }, { - "scope": ["punctuation.definition.quote.begin.markdown", "punctuation.definition.list.begin.markdown"], + "scope": [ + "punctuation.definition.quote.begin.markdown", + "punctuation.definition.list.begin.markdown" + ], "settings": { "foreground": "#0451a5" } @@ -204,7 +207,10 @@ } }, { - "scope": ["meta.preprocessor", "entity.name.function.preprocessor"], + "scope": [ + "meta.preprocessor", + "entity.name.function.preprocessor" + ], "settings": { "foreground": "#0000ff" } @@ -240,13 +246,19 @@ } }, { - "scope": ["storage.modifier", "keyword.operator.noexcept"], + "scope": [ + "storage.modifier", + "keyword.operator.noexcept" + ], "settings": { "foreground": "#0000ff" } }, { - "scope": ["string", "meta.embedded.assembly"], + "scope": [ + "string", + "meta.embedded.assembly" + ], "settings": { "foreground": "#a31515" } @@ -292,7 +304,9 @@ }, { "name": "Reset JavaScript string interpolation expression", - "scope": ["meta.template.expression"], + "scope": [ + "meta.template.expression" + ], "settings": { "foreground": "#000000" } @@ -323,7 +337,9 @@ } }, { - "scope": ["support.type.property-name.json"], + "scope": [ + "support.type.property-name.json" + ], "settings": { "foreground": "#0451a5" } @@ -370,7 +386,10 @@ } }, { - "scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"], + "scope": [ + "punctuation.section.embedded.begin.php", + "punctuation.section.embedded.end.php" + ], "settings": { "foreground": "#800000" } @@ -389,7 +408,11 @@ }, { "name": "coloring of the Java import and package identifiers", - "scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"], + "scope": [ + "storage.modifier.import.java", + "variable.language.wildcard.java", + "storage.modifier.package.java" + ], "settings": { "foreground": "#000000" } diff --git a/src/integrations/theme/getTheme.ts b/src/integrations/theme/getTheme.ts index a5d4493b..5b7fe87f 100644 --- a/src/integrations/theme/getTheme.ts +++ b/src/integrations/theme/getTheme.ts @@ -1,7 +1,7 @@ -import * as vscode from "vscode" -import * as path from "path" import * as fs from "fs/promises" import { convertTheme } from "monaco-vscode-textmate-theme-converter/lib/cjs" +import * as path from "path" +import * as vscode from "vscode" const defaultThemes: Record = { "Default Dark Modern": "dark_modern", @@ -31,7 +31,7 @@ function parseThemeString(themeString: string | undefined): any { } export async function getTheme() { - let currentTheme = undefined + let currentTheme const colorTheme = vscode.workspace.getConfiguration("workbench").get("colorTheme") || "Default Dark Modern" try { diff --git a/src/services/account/ClineAccountService.ts b/src/services/account/ClineAccountService.ts index ae7d4a70..933a237c 100644 --- a/src/services/account/ClineAccountService.ts +++ b/src/services/account/ClineAccountService.ts @@ -1,4 +1,3 @@ -import axios, { AxiosRequestConfig, AxiosResponse } from "axios" import type { BalanceResponse, OrganizationBalanceResponse, @@ -7,8 +6,9 @@ import type { UsageTransaction, UserResponse, } from "@shared/ClineAccount" -import { AuthService } from "../auth/AuthService" +import axios, { AxiosRequestConfig, AxiosResponse } from "axios" import { clineEnvConfig } from "@/config" +import { AuthService } from "../auth/AuthService" export class ClineAccountService { private static instance: ClineAccountService @@ -223,7 +223,7 @@ export class ClineAccountService { // Call API to switch account try { // make XHR request to switch account - const response = await this.authenticatedRequest(`/api/v1/users/active-account`, { + const _response = await this.authenticatedRequest(`/api/v1/users/active-account`, { method: "PUT", headers: { "Content-Type": "application/json", diff --git a/src/services/auth/providers/FirebaseAuthProvider.ts b/src/services/auth/providers/FirebaseAuthProvider.ts index 04b85875..c007f5f2 100644 --- a/src/services/auth/providers/FirebaseAuthProvider.ts +++ b/src/services/auth/providers/FirebaseAuthProvider.ts @@ -3,10 +3,9 @@ import axios from "axios" import { initializeApp } from "firebase/app" import { GithubAuthProvider, GoogleAuthProvider, getAuth, type OAuthCredential, signInWithCredential, User } from "firebase/auth" import { jwtDecode } from "jwt-decode" -import type { ExtensionContext } from "vscode" import { clineEnvConfig } from "@/config" -import type { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService" import { Controller } from "@/core/controller" +import type { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService" export class FirebaseAuthProvider { private _config: any diff --git a/src/services/browser/BrowserDiscovery.ts b/src/services/browser/BrowserDiscovery.ts index 2220e4e9..1f2da7cf 100644 --- a/src/services/browser/BrowserDiscovery.ts +++ b/src/services/browser/BrowserDiscovery.ts @@ -1,5 +1,5 @@ -import * as net from "net" import axios from "axios" +import * as net from "net" /** * Check if a port is open on a given host @@ -46,7 +46,7 @@ export async function tryConnect(ipAddress: string): Promise<{ endpoint: string; const response = await axios.get(`http://${ipAddress}:9222/json/version`, { timeout: 1000 }) const data = response.data return { endpoint: data.webSocketDebuggerUrl, ip: ipAddress } - } catch (error) { + } catch (_error) { return null } } diff --git a/src/services/browser/BrowserSession.ts b/src/services/browser/BrowserSession.ts index b30ec53e..6e410fac 100644 --- a/src/services/browser/BrowserSession.ts +++ b/src/services/browser/BrowserSession.ts @@ -1,22 +1,22 @@ -import * as vscode from "vscode" -import * as fs from "fs/promises" -import * as path from "path" +import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import { Controller } from "@core/controller" +import { BrowserSettings } from "@shared/BrowserSettings" +import { BrowserActionResult } from "@shared/ExtensionMessage" +import { fileExistsAtPath } from "@utils/fs" +import axios from "axios" import { exec, spawn } from "child_process" -import { Browser, Page, TimeoutError, launch, connect } from "puppeteer-core" -import type { ScreenshotOptions, ConsoleMessage } from "puppeteer-core" +import * as chromeLauncher from "chrome-launcher" +import * as fs from "fs/promises" +import os from "os" +import pWaitFor from "p-wait-for" +import * as path from "path" // @ts-ignore import PCR from "puppeteer-chromium-resolver" -import pWaitFor from "p-wait-for" -import { setTimeout as setTimeoutPromise } from "node:timers/promises" -import axios from "axios" -import { fileExistsAtPath } from "@utils/fs" -import { BrowserActionResult } from "@shared/ExtensionMessage" -import { BrowserSettings } from "@shared/BrowserSettings" -import { discoverChromeInstances, testBrowserConnection, isPortOpen } from "./BrowserDiscovery" -import * as chromeLauncher from "chrome-launcher" -import { Controller } from "@core/controller" +import type { ConsoleMessage, ScreenshotOptions } from "puppeteer-core" +import { Browser, connect, launch, Page, TimeoutError } from "puppeteer-core" +import * as vscode from "vscode" import { telemetryService } from "@/services/posthog/PostHogClientProvider" -import os from "os" +import { discoverChromeInstances, isPortOpen, testBrowserConnection } from "./BrowserDiscovery" interface PCRStats { puppeteer: { launch: typeof launch } @@ -137,7 +137,7 @@ export class BrowserSession { return stats } - async relaunchChromeDebugMode(controller: Controller): Promise { + async relaunchChromeDebugMode(_controller: Controller): Promise { try { const userDataDir = path.join(os.tmpdir(), "chrome-debug-profile") const installation = chromeLauncher.Launcher.getFirstInstallation() @@ -263,7 +263,7 @@ export class BrowserSession { async launchRemoteBrowser() { let remoteBrowserHost = this.browserSettings.remoteBrowserHost let browserWSEndpoint: string | undefined = this.cachedWebSocketEndpoint - let reconnectionAttempted = false + let _reconnectionAttempted = false const getViewport = () => { return this.browserSettings.viewport @@ -315,7 +315,7 @@ export class BrowserSession { this.cachedWebSocketEndpoint = undefined // User wants to give up after one reconnection attempt if (remoteBrowserHost) { - reconnectionAttempted = true + _reconnectionAttempted = true } } } diff --git a/src/services/browser/UrlContentFetcher.ts b/src/services/browser/UrlContentFetcher.ts index d09ae461..759d4da4 100644 --- a/src/services/browser/UrlContentFetcher.ts +++ b/src/services/browser/UrlContentFetcher.ts @@ -1,13 +1,13 @@ -import * as vscode from "vscode" +import { BrowserSettings, DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings" // Import the interface and defaults +import { fileExistsAtPath } from "@utils/fs" +import * as cheerio from "cheerio" import * as fs from "fs/promises" import * as path from "path" -import { Browser, Page, launch } from "puppeteer-core" -import * as cheerio from "cheerio" -import TurndownService from "turndown" // @ts-ignore import PCR from "puppeteer-chromium-resolver" -import { fileExistsAtPath } from "@utils/fs" -import { BrowserSettings, DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings" // Import the interface and defaults +import { Browser, launch, Page } from "puppeteer-core" +import TurndownService from "turndown" +import * as vscode from "vscode" interface PCRStats { puppeteer: { launch: typeof launch } diff --git a/src/services/glob/list-files.ts b/src/services/glob/list-files.ts index af44f083..f67d5c44 100644 --- a/src/services/glob/list-files.ts +++ b/src/services/glob/list-files.ts @@ -1,7 +1,7 @@ +import { arePathsEqual } from "@utils/path" import { globby, Options } from "globby" import * as os from "os" import * as path from "path" -import { arePathsEqual } from "@utils/path" // Constants const DEFAULT_IGNORE_DIRECTORIES = [ @@ -124,7 +124,7 @@ async function globbyLevelByLevel(limit: number, options?: Options) { }) try { return await Promise.race([globbingProcess(), timeoutPromise]) - } catch (error) { + } catch (_error) { console.warn("Globbing timed out, returning partial results") return Array.from(results) } diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index 96c23d04..fdf75fd2 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -103,7 +103,7 @@ export class McpHub { // Parse JSON file content try { config = JSON.parse(content) - } catch (error) { + } catch (_error) { HostProvider.window.showMessage({ type: ShowMessageType.ERROR, message: "Invalid MCP settings format. Please ensure your settings follow the correct JSON format.", @@ -165,7 +165,7 @@ export class McpHub { } } - private findConnection(name: string, source: "rpc" | "internal"): McpConnection | undefined { + private findConnection(name: string, _source: "rpc" | "internal"): McpConnection | undefined { return this.connections.find((conn) => conn.server.name === name) } @@ -274,7 +274,7 @@ export class McpHub { } const reconnectingEventSourceOptions = { max_retry_time: 5000, - withCredentials: config.headers?.["Authorization"] ? true : false, + withCredentials: !!config.headers?.["Authorization"], } global.EventSource = ReconnectingEventSource transport = new SSEClientTransport(new URL(config.url), { @@ -470,7 +470,7 @@ export class McpHub { timeout: DEFAULT_REQUEST_TIMEOUT_MS, }) return response?.resources || [] - } catch (error) { + } catch (_error) { // console.error(`Failed to fetch resources for ${serverName}:`, error) return [] } @@ -494,7 +494,7 @@ export class McpHub { ) return response?.resourceTemplates || [] - } catch (error) { + } catch (_error) { // console.error(`Failed to fetch resource templates for ${serverName}:`, error) return [] } diff --git a/src/services/mcp/schemas.ts b/src/services/mcp/schemas.ts index 63b7b3ce..7fb7ec41 100644 --- a/src/services/mcp/schemas.ts +++ b/src/services/mcp/schemas.ts @@ -1,5 +1,5 @@ -import { z } from "zod" import { DEFAULT_MCP_TIMEOUT_SECONDS, MIN_MCP_TIMEOUT_SECONDS } from "@shared/mcp" +import { z } from "zod" import { TYPE_ERROR_MESSAGE } from "./constants" export const AutoApproveSchema = z.array(z.string()).default([]) diff --git a/src/services/mcp/types.ts b/src/services/mcp/types.ts index a8be0b84..9d819fb0 100644 --- a/src/services/mcp/types.ts +++ b/src/services/mcp/types.ts @@ -1,9 +1,9 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js" -import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js" +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js" -import { z } from "zod" import { McpServer } from "@shared/mcp" +import { z } from "zod" import { ServerConfigSchema } from "./schemas" export type Transport = StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport diff --git a/src/services/ripgrep/index.ts b/src/services/ripgrep/index.ts index 6e74ce82..fd14e165 100644 --- a/src/services/ripgrep/index.ts +++ b/src/services/ripgrep/index.ts @@ -1,9 +1,9 @@ -import * as vscode from "vscode" +import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import { fileExistsAtPath } from "@utils/fs" import * as childProcess from "child_process" import * as path from "path" import * as readline from "readline" -import { fileExistsAtPath } from "@utils/fs" -import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import * as vscode from "vscode" /* This file provides functionality to perform regex searches on files using ripgrep. diff --git a/src/services/search/file-search.ts b/src/services/search/file-search.ts index 4935ac4a..216ba0f4 100644 --- a/src/services/search/file-search.ts +++ b/src/services/search/file-search.ts @@ -1,13 +1,13 @@ -import * as vscode from "vscode" -import * as path from "path" -import * as fs from "fs" import * as childProcess from "child_process" +import * as fs from "fs" +import type { FzfResultItem } from "fzf" +import * as path from "path" import * as readline from "readline" -import { getBinPath } from "../ripgrep" -import type { Fzf, FzfResultItem } from "fzf" +import * as vscode from "vscode" import { HostProvider } from "@/hosts/host-provider" import { GetOpenTabsRequest } from "@/shared/proto/host/window" -import { isLocatedInWorkspace, asRelativePath } from "@/utils/path" +import { asRelativePath, isLocatedInWorkspace } from "@/utils/path" +import { getBinPath } from "../ripgrep" // Wrapper function for childProcess.spawn export type SpawnFunction = typeof childProcess.spawn diff --git a/src/services/test/GitHelper.ts b/src/services/test/GitHelper.ts index 06eb6331..aaa5a594 100644 --- a/src/services/test/GitHelper.ts +++ b/src/services/test/GitHelper.ts @@ -1,6 +1,6 @@ -import * as path from "path" -import { execa } from "execa" import { Logger } from "@services/logging/Logger" +import { execa } from "execa" +import * as path from "path" /** * Validates that the workspace path is valid and writable for Git operations @@ -16,7 +16,7 @@ export async function validateWorkspacePath(workspacePath: string): Promise { // Use rm -rf to remove the directory await execa("rm", ["-rf", gitDir]) Logger.log(`Removed existing Git repository`) - } catch (error) { + } catch (_error) { // Directory doesn't exist, which is fine Logger.log(`No existing Git repository found in ${workspacePath}`) } diff --git a/src/services/test/TestMode.ts b/src/services/test/TestMode.ts index 2914b17d..c3c6d5b6 100644 --- a/src/services/test/TestMode.ts +++ b/src/services/test/TestMode.ts @@ -3,12 +3,13 @@ * This provides a centralized way to check if the extension is running in test mode * instead of relying on process.env which may not be consistent across different parts of the extension */ -import * as vscode from "vscode" + import * as fs from "fs" import * as path from "path" +import * as vscode from "vscode" +import { HostProvider } from "@/hosts/host-provider" import { Logger } from "../logging/Logger" import { createTestServer, shutdownTestServer } from "./TestServer" -import { HostProvider } from "@/hosts/host-provider" // State variable let isTestMode = false diff --git a/src/services/test/TestServer.ts b/src/services/test/TestServer.ts index 8e859835..fa49b294 100644 --- a/src/services/test/TestServer.ts +++ b/src/services/test/TestServer.ts @@ -1,16 +1,16 @@ -import { getCwd } from "@/utils/path" import { getSavedApiConversationHistory, getSavedClineMessages } from "@core/storage/disk" import { WebviewProvider } from "@core/webview" import { Logger } from "@services/logging/Logger" -import { ApiProvider } from "@shared/api" import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" +import { ApiProvider } from "@shared/api" import { HistoryItem } from "@shared/HistoryItem" import { execa } from "execa" import * as http from "http" import * as path from "path" import * as vscode from "vscode" -import { calculateToolSuccessRate, getFileChanges, initializeGitRepository, validateWorkspacePath } from "./GitHelper" import { Controller } from "@/core/controller" +import { getCwd } from "@/utils/path" +import { calculateToolSuccessRate, getFileChanges, initializeGitRepository, validateWorkspacePath } from "./GitHelper" /** * Creates a tracker to monitor tool calls and failures during task execution @@ -28,13 +28,13 @@ function createToolCallTracker(): { } // Task completion tracking -let taskCompletionResolver: (() => void) | null = null +let _taskCompletionResolver: (() => void) | null = null // Function to create a new task completion promise function createTaskCompletionTracker(): Promise { // Create a new promise that will resolve when the task is completed return new Promise((resolve) => { - taskCompletionResolver = resolve + _taskCompletionResolver = resolve }) } @@ -46,7 +46,7 @@ let messageCatcherDisposable: vscode.Disposable | undefined * @param context The VSCode extension context * @param controller The webview provider instance */ -async function updateAutoApprovalSettings(context: vscode.ExtensionContext, controller?: Controller) { +async function updateAutoApprovalSettings(_context: vscode.ExtensionContext, controller?: Controller) { try { const autoApprovalSettings = controller?.cacheService.getGlobalStateKey("autoApprovalSettings") @@ -401,7 +401,7 @@ export function createTestServer(controller: Controller): http.Server { files: fileChanges, }), ) - } catch (timeoutError) { + } catch (_timeoutError) { // Task didn't complete within the timeout period res.writeHead(200, { "Content-Type": "application/json" }) res.end( diff --git a/src/services/tree-sitter/index.ts b/src/services/tree-sitter/index.ts index 3a22e460..4eac0936 100644 --- a/src/services/tree-sitter/index.ts +++ b/src/services/tree-sitter/index.ts @@ -1,9 +1,9 @@ +import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import { listFiles } from "@services/glob/list-files" +import { fileExistsAtPath } from "@utils/fs" import * as fs from "fs/promises" import * as path from "path" -import { listFiles } from "@services/glob/list-files" import { LanguageParser, loadRequiredLanguageParsers } from "./languageParser" -import { fileExistsAtPath } from "@utils/fs" -import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" // TODO: implement caching behavior to avoid having to keep analyzing project for new tasks. export async function parseSourceCodeForDefinitionsTopLevel( diff --git a/src/services/tree-sitter/languageParser.ts b/src/services/tree-sitter/languageParser.ts index 1babdd9e..d22e79be 100644 --- a/src/services/tree-sitter/languageParser.ts +++ b/src/services/tree-sitter/languageParser.ts @@ -1,19 +1,19 @@ import * as path from "path" import Parser from "web-tree-sitter" import { - javascriptQuery, - typescriptQuery, - pythonQuery, - rustQuery, - goQuery, cppQuery, cQuery, csharpQuery, - rubyQuery, + goQuery, javaQuery, - phpQuery, - swiftQuery, + javascriptQuery, kotlinQuery, + phpQuery, + pythonQuery, + rubyQuery, + rustQuery, + swiftQuery, + typescriptQuery, } from "./queries" export interface LanguageParser { diff --git a/src/services/tree-sitter/queries/index.ts b/src/services/tree-sitter/queries/index.ts index 818eacca..14df28ee 100644 --- a/src/services/tree-sitter/queries/index.ts +++ b/src/services/tree-sitter/queries/index.ts @@ -1,13 +1,13 @@ -export { default as phpQuery } from "./php" -export { default as typescriptQuery } from "./typescript" -export { default as pythonQuery } from "./python" -export { default as javascriptQuery } from "./javascript" -export { default as javaQuery } from "./java" -export { default as rustQuery } from "./rust" -export { default as rubyQuery } from "./ruby" -export { default as cppQuery } from "./cpp" export { default as cQuery } from "./c" export { default as csharpQuery } from "./c-sharp" +export { default as cppQuery } from "./cpp" export { default as goQuery } from "./go" -export { default as swiftQuery } from "./swift" +export { default as javaQuery } from "./java" +export { default as javascriptQuery } from "./javascript" export { default as kotlinQuery } from "./kotlin" +export { default as phpQuery } from "./php" +export { default as pythonQuery } from "./python" +export { default as rubyQuery } from "./ruby" +export { default as rustQuery } from "./rust" +export { default as swiftQuery } from "./swift" +export { default as typescriptQuery } from "./typescript" diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index ed958f3a..64dc33d1 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -1,14 +1,15 @@ // type that represents json data that is sent from extension to webview, called ExtensionMessage and has 'type' enum which can be 'plusButtonClicked' or 'settingsButtonClicked' or 'hello' -import { ApiConfiguration } from "./api" + import { AutoApprovalSettings } from "./AutoApprovalSettings" +import { ApiConfiguration } from "./api" import { BrowserSettings } from "./BrowserSettings" -import { FocusChainSettings } from "./FocusChainSettings" -import { Mode, OpenaiReasoningEffort } from "./storage/types" -import { HistoryItem } from "./HistoryItem" -import { TelemetrySetting } from "./TelemetrySetting" import { ClineRulesToggles } from "./cline-rules" -import { UserInfo } from "./UserInfo" +import { FocusChainSettings } from "./FocusChainSettings" +import { HistoryItem } from "./HistoryItem" import { McpDisplayMode } from "./McpDisplayMode" +import { Mode, OpenaiReasoningEffort } from "./storage/types" +import { TelemetrySetting } from "./TelemetrySetting" +import { UserInfo } from "./UserInfo" // webview will hold state export interface ExtensionMessage { diff --git a/src/shared/array.test.ts b/src/shared/array.test.ts index 20f06a75..0ae404c3 100644 --- a/src/shared/array.test.ts +++ b/src/shared/array.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "mocha" import "should" -import { findLastIndex, findLast } from "./array" +import { findLast, findLastIndex } from "./array" describe("Array Utilities", () => { describe("findLastIndex", () => { diff --git a/src/shared/proto-conversions/cline-message.ts b/src/shared/proto-conversions/cline-message.ts index 316f38db..7de4a757 100644 --- a/src/shared/proto-conversions/cline-message.ts +++ b/src/shared/proto-conversions/cline-message.ts @@ -1,6 +1,6 @@ -import { ClineMessage as AppClineMessage, ClineAsk as AppClineAsk, ClineSay as AppClineSay } from "@shared/ExtensionMessage" +import { ClineAsk as AppClineAsk, ClineMessage as AppClineMessage, ClineSay as AppClineSay } from "@shared/ExtensionMessage" -import { ClineMessage as ProtoClineMessage, ClineMessageType, ClineAsk, ClineSay } from "@shared/proto/cline/ui" +import { ClineAsk, ClineMessageType, ClineSay, ClineMessage as ProtoClineMessage } from "@shared/proto/cline/ui" // Helper function to convert ClineAsk string to enum function convertClineAskToProtoEnum(ask: AppClineAsk | undefined): ClineAsk | undefined { diff --git a/src/shared/proto-conversions/mcp/mcp-server-conversion.ts b/src/shared/proto-conversions/mcp/mcp-server-conversion.ts index 0cb8476f..48c3df85 100644 --- a/src/shared/proto-conversions/mcp/mcp-server-conversion.ts +++ b/src/shared/proto-conversions/mcp/mcp-server-conversion.ts @@ -1,11 +1,11 @@ -import { McpServer, McpTool, McpResource, McpResourceTemplate } from "../../mcp" import { - McpServer as ProtoMcpServer, - McpTool as ProtoMcpTool, + McpServerStatus, McpResource as ProtoMcpResource, McpResourceTemplate as ProtoMcpResourceTemplate, - McpServerStatus, + McpServer as ProtoMcpServer, + McpTool as ProtoMcpTool, } from "@shared/proto/cline/mcp" +import { McpResource, McpResourceTemplate, McpServer, McpTool } from "../../mcp" // Helper to convert TS status to Proto enum function convertMcpStatusToProto(status: McpServer["status"]): McpServerStatus { diff --git a/src/shared/proto-conversions/models/auto-approval-settings-conversion.ts b/src/shared/proto-conversions/models/auto-approval-settings-conversion.ts index e9050b80..48c58f09 100644 --- a/src/shared/proto-conversions/models/auto-approval-settings-conversion.ts +++ b/src/shared/proto-conversions/models/auto-approval-settings-conversion.ts @@ -1,5 +1,5 @@ -import { AutoApprovalSettings } from "../../AutoApprovalSettings" import { AutoApprovalSettingsRequest } from "@shared/proto/cline/state" +import { AutoApprovalSettings } from "../../AutoApprovalSettings" // Converts domain AutoApprovalSettings to proto AutoApprovalSettingsRequest export function convertAutoApprovalSettingsToProto(settings: AutoApprovalSettings): AutoApprovalSettingsRequest { diff --git a/src/standalone/cline-core.ts b/src/standalone/cline-core.ts index 4607ccfe..0a326b64 100644 --- a/src/standalone/cline-core.ts +++ b/src/standalone/cline-core.ts @@ -1,12 +1,12 @@ +import { ExternalDiffViewProvider } from "@hosts/external/ExternalDiffviewProvider" +import { ExternalWebviewProvider } from "@hosts/external/ExternalWebviewProvider" +import { ExternalHostBridgeClientManager } from "@hosts/external/host-bridge-client-manager" +import { WebviewProviderType } from "@shared/webview/types" import { initialize, tearDown } from "@/common" import { WebviewProvider } from "@/core/webview" import { AuthHandler } from "@/hosts/external/AuthHandler" import { HostProvider } from "@/hosts/host-provider" import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider" -import { ExternalDiffViewProvider } from "@hosts/external/ExternalDiffviewProvider" -import { ExternalWebviewProvider } from "@hosts/external/ExternalWebviewProvider" -import { ExternalHostBridgeClientManager } from "@hosts/external/host-bridge-client-manager" -import { WebviewProviderType } from "@shared/webview/types" import { startProtobusService, waitForHostBridgeReady } from "./protobus-service" import { log } from "./utils" import { extensionContext } from "./vscode-context" diff --git a/src/standalone/protobus-service.ts b/src/standalone/protobus-service.ts index 5aea032a..989df6a2 100644 --- a/src/standalone/protobus-service.ts +++ b/src/standalone/protobus-service.ts @@ -2,11 +2,11 @@ import { Controller } from "@core/controller" import { StreamingResponseHandler } from "@core/controller/grpc-handler" import { addProtobusServices } from "@generated/hosts/standalone/protobus-server-setup" import * as grpc from "@grpc/grpc-js" +import * as protoLoader from "@grpc/proto-loader" import { ReflectionService } from "@grpc/reflection" import { GrpcHandler, GrpcStreamingResponseHandler } from "@hosts/external/grpc-types" import * as health from "grpc-health-check" import { getPackageDefinition, log } from "./utils" -import * as protoLoader from "@grpc/proto-loader" export const PROTOBUS_PORT = 26040 export const HOSTBRIDGE_PORT = 26041 @@ -87,7 +87,7 @@ function wrapStreamingResponseHandler( const requestId = call.metadata.get("request-id").pop()?.toString() log(`ProtoBus gRPC streaming request: ${call.getPath()}`) - const responseHandler: StreamingResponseHandler = (response, isLast, sequenceNumber) => { + const responseHandler: StreamingResponseHandler = (response, isLast, _sequenceNumber) => { try { call.write(response) // Use a bound version of call.write to maintain proper 'this' context diff --git a/src/standalone/utils.ts b/src/standalone/utils.ts index 45b3f2c0..06cfc32a 100644 --- a/src/standalone/utils.ts +++ b/src/standalone/utils.ts @@ -1,5 +1,5 @@ -import * as fs from "fs" import * as protoLoader from "@grpc/proto-loader" +import * as fs from "fs" import * as health from "grpc-health-check" import { StreamingCallbacks } from "@/hosts/host-provider-types" diff --git a/src/standalone/vscode-context-utils.ts b/src/standalone/vscode-context-utils.ts index 6381bfb1..6bf3413b 100644 --- a/src/standalone/vscode-context-utils.ts +++ b/src/standalone/vscode-context-utils.ts @@ -1,6 +1,6 @@ import * as fs from "fs" +import type { EnvironmentVariableMutator, EnvironmentVariableMutatorOptions, EnvironmentVariableScope } from "vscode" import * as vscode from "vscode" -import type { EnvironmentVariableMutatorOptions, EnvironmentVariableMutator, EnvironmentVariableScope } from "vscode" export class SecretStore implements vscode.SecretStorage { private data: JsonKeyValueStore private readonly _onDidChange = new EventEmitter() diff --git a/src/standalone/vscode-context.ts b/src/standalone/vscode-context.ts index 5006d8dd..f619dd15 100644 --- a/src/standalone/vscode-context.ts +++ b/src/standalone/vscode-context.ts @@ -1,9 +1,9 @@ -import { URI } from "vscode-uri" -import os from "os" import { mkdirSync, readFileSync } from "fs" +import os from "os" import path, { join } from "path" import type { Extension, ExtensionContext } from "vscode" import { ExtensionKind, ExtensionMode } from "vscode" +import { URI } from "vscode-uri" import { log } from "./utils" import { EnvironmentVariableCollection, MementoStore, readJson, SecretStore } from "./vscode-context-utils" diff --git a/src/test/cline-api.test.ts b/src/test/cline-api.test.ts index e38acd0a..6fae4e71 100644 --- a/src/test/cline-api.test.ts +++ b/src/test/cline-api.test.ts @@ -1,7 +1,7 @@ -import { createClineAPI } from "@/exports" import { afterEach, beforeEach, describe, it } from "mocha" import * as should from "should" import * as sinon from "sinon" +import { createClineAPI } from "@/exports" import type { ClineAPI } from "../exports/cline" import { setVscodeHostProviderMock } from "./host-provider-test-utils" @@ -10,7 +10,7 @@ describe("ClineAPI Core Functionality", () => { let mockController: any let mockLogToChannel: sinon.SinonStub<[string], void> let sandbox: sinon.SinonSandbox - let getGlobalStateStub: sinon.SinonStub + let _getGlobalStateStub: sinon.SinonStub beforeEach(async () => { sandbox = sinon.createSandbox() diff --git a/src/test/e2e/utils/build.mjs b/src/test/e2e/utils/build.mjs index 8ba7e6ac..0ae71e72 100644 --- a/src/test/e2e/utils/build.mjs +++ b/src/test/e2e/utils/build.mjs @@ -1,7 +1,7 @@ /** * Script to install dependencies for running E2E tests in GitHub Actions. */ -import { SilentReporter, downloadAndUnzipVSCode } from "@vscode/test-electron" +import { downloadAndUnzipVSCode, SilentReporter } from "@vscode/test-electron" import { execa } from "execa" const TIMEOUT_MINUTE = 1 diff --git a/src/test/extension.test.ts b/src/test/extension.test.ts index 063cf3bf..2ab77c0f 100644 --- a/src/test/extension.test.ts +++ b/src/test/extension.test.ts @@ -1,5 +1,5 @@ import { readFile } from "fs/promises" -import { describe, it, after } from "mocha" +import { after, describe, it } from "mocha" import path from "path" import "should" import * as vscode from "vscode" diff --git a/src/test/host-provider-test-utils.ts b/src/test/host-provider-test-utils.ts index e97dbcbf..7b96f12f 100644 --- a/src/test/host-provider-test-utils.ts +++ b/src/test/host-provider-test-utils.ts @@ -1,4 +1,4 @@ -import { HostProvider, WebviewProviderCreator, DiffViewProviderCreator } from "@/hosts/host-provider" +import { DiffViewProviderCreator, HostProvider, WebviewProviderCreator } from "@/hosts/host-provider" import { HostBridgeClientProvider } from "@/hosts/host-provider-types" import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client" diff --git a/src/test/services/search/file-search.test.ts b/src/test/services/search/file-search.test.ts index 25defbf5..2581f694 100644 --- a/src/test/services/search/file-search.test.ts +++ b/src/test/services/search/file-search.test.ts @@ -1,26 +1,24 @@ +import * as ripgrep from "@services/ripgrep" +import * as fileSearch from "@services/search/file-search" +import * as childProcess from "child_process" +import * as fs from "fs" +import type { FzfResultItem } from "fzf" import { describe, it } from "mocha" import should from "should" import sinon from "sinon" import { Readable } from "stream" -import type { FzfResultItem } from "fzf" -import * as childProcess from "child_process" import * as vscode from "vscode" -import * as fs from "fs" -import * as fileSearch from "@services/search/file-search" -import * as ripgrep from "@services/ripgrep" -describe("File Search", function () { +describe("File Search", () => { let sandbox: sinon.SinonSandbox let spawnStub: sinon.SinonStub - beforeEach(function () { + beforeEach(() => { sandbox = sinon.createSandbox() spawnStub = sandbox.stub() // Create a wrapper function that matches the signature of childProcess.spawn - const spawnWrapper: typeof childProcess.spawn = function (command, options) { - return spawnStub(command, options) - } + const spawnWrapper: typeof childProcess.spawn = (command, options) => spawnStub(command, options) sandbox.stub(fileSearch, "getSpawnFunction").returns(spawnWrapper) // Use replaceGetter instead of stub().value() for non-configurable properties @@ -29,12 +27,12 @@ describe("File Search", function () { sandbox.stub(ripgrep, "getBinPath").resolves("mock/ripgrep/path") }) - afterEach(function () { + afterEach(() => { sandbox.restore() }) - describe("executeRipgrepForFiles", function () { - it("should correctly process and return file and folder results", async function () { + describe("executeRipgrepForFiles", () => { + it("should correctly process and return file and folder results", async () => { const mockFiles = ["file1.txt", "folder1/file2.js", "folder1/subfolder/file3.py"] // Create a proper mock for the child process @@ -94,7 +92,7 @@ describe("File Search", function () { ]) }) - it("should handle errors from ripgrep", async function () { + it("should handle errors from ripgrep", async () => { const mockError = "Mock ripgrep error" // Create proper mock streams for error case @@ -128,8 +126,8 @@ describe("File Search", function () { }) }) - describe("searchWorkspaceFiles", function () { - it("should return top N results for empty query", async function () { + describe("searchWorkspaceFiles", () => { + it("should return top N results for empty query", async () => { const mockItems: { path: string; type: "file" | "folder"; label?: string }[] = [ { path: "file1.txt", type: "file", label: "file1.txt" }, { path: "folder1", type: "folder", label: "folder1" }, @@ -148,7 +146,7 @@ describe("File Search", function () { should(result).deepEqual(mockItems.slice(0, 2)) }) - it("should apply fuzzy matching for non-empty query", async function () { + it("should apply fuzzy matching for non-empty query", async () => { const mockItems: { path: string; type: "file" | "folder"; label?: string }[] = [ { path: "file1.txt", type: "file", label: "file1.txt" }, { path: "folder1/important.js", type: "file", label: "important.js" }, @@ -160,14 +158,14 @@ describe("File Search", function () { find: sinon.stub().returns([{ item: mockItems[1], score: 0 }]), } // Create a mock for the fzf module - const fzfModuleStub = { + const _fzfModuleStub = { Fzf: sinon.stub().returns(fzfStub), byLengthAsc: sinon.stub(), } // Use a more reliable approach to mock dynamic imports // This replaces the actual implementation of searchWorkspaceFiles to avoid the dynamic import - sandbox.stub(fileSearch, "searchWorkspaceFiles").callsFake(async (query, workspacePath, limit) => { + sandbox.stub(fileSearch, "searchWorkspaceFiles").callsFake(async (query, _workspacePath, limit) => { if (!query.trim()) { return mockItems.slice(0, limit) } @@ -188,8 +186,8 @@ describe("File Search", function () { }) }) - describe("OrderbyMatchScore", function () { - it("should prioritize results with fewer gaps between matched characters", function () { + describe("OrderbyMatchScore", () => { + it("should prioritize results with fewer gaps between matched characters", () => { const mockItemA: FzfResultItem = { item: {}, positions: new Set([0, 1, 2, 5]), start: 0, end: 5, score: 0 } const mockItemB: FzfResultItem = { item: {}, positions: new Set([0, 2, 4, 6]), start: 0, end: 6, score: 0 } diff --git a/src/test/shell.test.ts b/src/test/shell.test.ts index 4a1b1bf3..41a980b6 100644 --- a/src/test/shell.test.ts +++ b/src/test/shell.test.ts @@ -1,8 +1,8 @@ -import { describe, it, beforeEach, afterEach } from "mocha" -import { expect } from "chai" import { getShell } from "@utils/shell" -import * as vscode from "vscode" +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" import { userInfo } from "os" +import * as vscode from "vscode" describe("Shell Detection Tests", () => { let originalPlatform: string diff --git a/src/utils/cost.test.ts b/src/utils/cost.test.ts index 3dac4aa1..65a62eb2 100644 --- a/src/utils/cost.test.ts +++ b/src/utils/cost.test.ts @@ -1,7 +1,7 @@ import { describe, it } from "mocha" import "should" -import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "@utils/cost" import { ModelInfo } from "@shared/api" +import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "@utils/cost" describe("Cost Utilities", () => { describe("calculateApiCostAnthropic", () => { diff --git a/src/utils/env.ts b/src/utils/env.ts index d9b44f7d..a4f689d1 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -1,6 +1,6 @@ -import { HostProvider } from "@/hosts/host-provider" -import { StringRequest, EmptyRequest } from "@shared/proto/cline/common" +import { EmptyRequest, StringRequest } from "@shared/proto/cline/common" import open from "open" +import { HostProvider } from "@/hosts/host-provider" /** * Writes text to the system clipboard diff --git a/src/utils/git.ts b/src/utils/git.ts index a61ae3e4..7b9795b9 100644 --- a/src/utils/git.ts +++ b/src/utils/git.ts @@ -16,7 +16,7 @@ async function checkGitRepo(cwd: string): Promise { try { await execAsync("git rev-parse --git-dir", { cwd }) return true - } catch (error) { + } catch (_error) { return false } } @@ -25,7 +25,7 @@ async function checkGitInstalled(): Promise { try { await execAsync("git --version") return true - } catch (error) { + } catch (_error) { return false } } @@ -34,7 +34,7 @@ async function checkGitRepoHasCommits(cwd: string): Promise { try { await execAsync("git rev-parse HEAD", { cwd }) return true - } catch (error) { + } catch (_error) { return false } } diff --git a/src/utils/github-url-utils.ts b/src/utils/github-url-utils.ts index 515d6957..7795e63d 100644 --- a/src/utils/github-url-utils.ts +++ b/src/utils/github-url-utils.ts @@ -13,12 +13,12 @@ * fields containing special characters. */ +import { HostProvider } from "@hosts/host-provider" +import { ShowMessageType } from "@shared/proto/host/window" import * as cp from "child_process" import * as os from "os" import * as util from "util" -import { writeTextToClipboard, openExternal } from "@/utils/env" -import { HostProvider } from "@hosts/host-provider" -import { ShowMessageType } from "@shared/proto/host/window" +import { openExternal, writeTextToClipboard } from "@/utils/env" /** * Creates a properly encoded GitHub issue URL. @@ -199,7 +199,7 @@ export async function createAndOpenGitHubIssue( params: Map, ): Promise { // Construct the base URL - let baseUrl = `https://github.com/${repoOwner}/${repoName}/issues/new` + const baseUrl = `https://github.com/${repoOwner}/${repoName}/issues/new` // Add template parameter if provided if (issueTemplate) { diff --git a/src/utils/path.ts b/src/utils/path.ts index d49bc256..4a5ea816 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -1,7 +1,7 @@ -import { HostProvider } from "@/hosts/host-provider" import os from "os" import * as path from "path" import * as vscode from "vscode" +import { HostProvider } from "@/hosts/host-provider" /* The Node.js 'path' module resolves and normalizes paths differently depending on the platform: diff --git a/src/utils/shell.ts b/src/utils/shell.ts index f135ef18..0d09f3c8 100644 --- a/src/utils/shell.ts +++ b/src/utils/shell.ts @@ -1,5 +1,5 @@ -import * as vscode from "vscode" import { userInfo } from "os" +import * as vscode from "vscode" const SHELL_PATHS = { // Windows paths diff --git a/src/utils/storage.ts b/src/utils/storage.ts index 8588dcb4..53315b2b 100644 --- a/src/utils/storage.ts +++ b/src/utils/storage.ts @@ -1,5 +1,5 @@ -import path from "path" import getFolderSize from "get-folder-size" +import path from "path" /** * Gets the total size of tasks and checkpoints directories diff --git a/standalone/runtime-files/vscode/enhanced-terminal.js b/standalone/runtime-files/vscode/enhanced-terminal.js index 53f21056..87e3c618 100644 --- a/standalone/runtime-files/vscode/enhanced-terminal.js +++ b/standalone/runtime-files/vscode/enhanced-terminal.js @@ -1,7 +1,7 @@ const { spawn } = require("child_process") const { EventEmitter } = require("events") -const path = require("path") -const os = require("os") +const _path = require("path") +const _os = require("os") // Enhanced terminal management for standalone Cline // This replaces VSCode's terminal integration with real subprocess management @@ -94,7 +94,7 @@ class StandaloneTerminalProcess extends EventEmitter { } } - handleOutput(data, didEmitEmptyLine) { + handleOutput(data, _didEmitEmptyLine) { // Set process as hot (actively outputting) this.isHot = true if (this.hotTimer) { @@ -140,7 +140,7 @@ class StandaloneTerminalProcess extends EventEmitter { this.buffer += chunk let lineEndIndex while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) { - let line = this.buffer.slice(0, lineEndIndex).trimEnd() + const line = this.buffer.slice(0, lineEndIndex).trimEnd() this.emit("line", line) this.buffer = this.buffer.slice(lineEndIndex + 1) } @@ -232,7 +232,7 @@ class StandaloneTerminal { // Mock shell integration for compatibility this.shellIntegration = { cwd: { fsPath: this._cwd }, - executeCommand: (command) => { + executeCommand: (_command) => { // Return a mock execution object that the TerminalProcess expects return { read: async function* () { @@ -380,7 +380,9 @@ class StandaloneTerminalManager { // Find available terminal with matching CWD const matchingTerminal = terminals.find((t) => { - if (t.busy) return false + if (t.busy) { + return false + } return t.terminal._cwd === cwd }) @@ -446,7 +448,7 @@ class StandaloneTerminalManager { disposeAll() { // Terminate all processes - for (const [terminalId, process] of this.processes) { + for (const [_terminalId, process] of this.processes) { if (process && process.terminate) { process.terminate() } diff --git a/standalone/runtime-files/vscode/stub-utils.js b/standalone/runtime-files/vscode/stub-utils.js index 1d98654a..fc4c4970 100644 --- a/standalone/runtime-files/vscode/stub-utils.js +++ b/standalone/runtime-files/vscode/stub-utils.js @@ -1,15 +1,15 @@ function createStub(path) { - return new Proxy(function () {}, { - get: (target, prop) => { + return new Proxy(() => {}, { + get: (_target, prop) => { const fullPath = `${path}.${String(prop)}` console.log(`Accessed stub: ${fullPath}`) return createStub(fullPath) }, - apply: (target, thisArg, args) => { + apply: (_target, _thisArg, args) => { console.log(`Called stub: ${path} with args:`, args) return createStub(path) }, - construct: (target, args) => { + construct: (_target, args) => { console.log(`Constructed stub: ${path} with args:`, args) return createStub(path) }, diff --git a/standalone/runtime-files/vscode/vscode-impls.js b/standalone/runtime-files/vscode/vscode-impls.js index 928b56cc..e9b61fbd 100644 --- a/standalone/runtime-files/vscode/vscode-impls.js +++ b/standalone/runtime-files/vscode/vscode-impls.js @@ -130,11 +130,21 @@ vscode.Uri = { toJSON: () => uriString, with: (change) => { const newUrl = new URL(uriString) - if (change.scheme) newUrl.protocol = change.scheme + ":" - if (change.authority) newUrl.hostname = change.authority - if (change.path) newUrl.pathname = change.path - if (change.query) newUrl.search = "?" + change.query - if (change.fragment) newUrl.hash = "#" + change.fragment + if (change.scheme) { + newUrl.protocol = change.scheme + ":" + } + if (change.authority) { + newUrl.hostname = change.authority + } + if (change.path) { + newUrl.pathname = change.path + } + if (change.query) { + newUrl.search = "?" + change.query + } + if (change.fragment) { + newUrl.hash = "#" + change.fragment + } return vscode.Uri.parse(newUrl.toString()) }, } diff --git a/standalone/runtime-files/vscode/vscode-stubs.js b/standalone/runtime-files/vscode/vscode-stubs.js index 377dce5d..8d4143fb 100644 --- a/standalone/runtime-files/vscode/vscode-stubs.js +++ b/standalone/runtime-files/vscode/vscode-stubs.js @@ -485,15 +485,15 @@ vscode.Task = class { } } vscode.tasks = {} -vscode.tasks.registerTaskProvider = function (type, provider) { +vscode.tasks.registerTaskProvider = (_type, _provider) => { console.log("Called stubbed function: vscode.tasks.registerTaskProvider") return createStub("unknown") } -vscode.tasks.fetchTasks = function (filter) { +vscode.tasks.fetchTasks = (_filter) => { console.log("Called stubbed function: vscode.tasks.fetchTasks") return [] } -vscode.tasks.executeTask = function (task) { +vscode.tasks.executeTask = (_task) => { console.log("Called stubbed function: vscode.tasks.executeTask") return Promise.resolve(null) } @@ -526,37 +526,37 @@ vscode.env.isNewAppInstall = createStub("vscode.env.isNewAppInstall") vscode.env.isTelemetryEnabled = createStub("vscode.env.isTelemetryEnabled") vscode.env.onDidChangeTelemetryEnabled = createStub("vscode.env.onDidChangeTelemetryEnabled") vscode.env.onDidChangeShell = createStub("vscode.env.onDidChangeShell") -vscode.env.createTelemetryLogger = function (sender, options) { +vscode.env.createTelemetryLogger = (_sender, _options) => { console.log("Called stubbed function: vscode.env.createTelemetryLogger") return createStub("unknown") } vscode.env.remoteName = createStub("vscode.env.remoteName") vscode.env.shell = createStub("vscode.env.shell") vscode.env.uiKind = createStub("vscode.env.uiKind") -vscode.env.openExternal = function (target) { +vscode.env.openExternal = (_target) => { console.log("Called stubbed function: vscode.env.openExternal") return false } -vscode.env.asExternalUri = function (target) { +vscode.env.asExternalUri = (_target) => { console.log("Called stubbed function: vscode.env.asExternalUri") return Promise.resolve(null) } vscode.env.logLevel = createStub("vscode.env.logLevel") vscode.env.onDidChangeLogLevel = createStub("vscode.env.onDidChangeLogLevel") vscode.commands = {} -vscode.commands.registerCommand = function (command, callback, thisArg) { +vscode.commands.registerCommand = (_command, _callback, _thisArg) => { console.log("Called stubbed function: vscode.commands.registerCommand") return createStub("unknown") } -vscode.commands.registerTextEditorCommand = function (command, callback, thisArg) { +vscode.commands.registerTextEditorCommand = (_command, _callback, _thisArg) => { console.log("Called stubbed function: vscode.commands.registerTextEditorCommand") return createStub("unknown") } -vscode.commands.executeCommand = function (command, rest) { +vscode.commands.executeCommand = (_command, _rest) => { console.log("Called stubbed function: vscode.commands.executeCommand") return Promise.resolve(null) } -vscode.commands.getCommands = function (filterInternal) { +vscode.commands.getCommands = (_filterInternal) => { console.log("Called stubbed function: vscode.commands.getCommands") return "" } @@ -584,195 +584,195 @@ vscode.window.onDidCloseTerminal = createStub("vscode.window.onDidCloseTerminal" vscode.window.onDidChangeTerminalState = createStub("vscode.window.onDidChangeTerminalState") vscode.window.state = createStub("vscode.window.state") vscode.window.onDidChangeWindowState = createStub("vscode.window.onDidChangeWindowState") -vscode.window.showTextDocument = function (document, column, preserveFocus) { +vscode.window.showTextDocument = (_document, _column, _preserveFocus) => { console.log("Called stubbed function: vscode.window.showTextDocument") return Promise.resolve(null) } -vscode.window.showTextDocument = function (document, options) { +vscode.window.showTextDocument = (_document, _options) => { console.log("Called stubbed function: vscode.window.showTextDocument") return Promise.resolve(null) } -vscode.window.showTextDocument = function (uri, options) { +vscode.window.showTextDocument = (_uri, _options) => { console.log("Called stubbed function: vscode.window.showTextDocument") return Promise.resolve(null) } -vscode.window.showNotebookDocument = function (document, options) { +vscode.window.showNotebookDocument = (_document, _options) => { console.log("Called stubbed function: vscode.window.showNotebookDocument") return Promise.resolve(null) } -vscode.window.createTextEditorDecorationType = function (options) { +vscode.window.createTextEditorDecorationType = (_options) => { console.log("Called stubbed function: vscode.window.createTextEditorDecorationType") return createStub("unknown") } -vscode.window.showInformationMessage = function (message, items) { +vscode.window.showInformationMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showInformationMessage") return Promise.resolve(null) } -vscode.window.showInformationMessage = function (message, options, items) { +vscode.window.showInformationMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showInformationMessage") return Promise.resolve(null) } -vscode.window.showInformationMessage = function (message, items) { +vscode.window.showInformationMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showInformationMessage") return Promise.resolve(null) } -vscode.window.showInformationMessage = function (message, options, items) { +vscode.window.showInformationMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showInformationMessage") return Promise.resolve(null) } -vscode.window.showWarningMessage = function (message, items) { +vscode.window.showWarningMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showWarningMessage") return Promise.resolve(null) } -vscode.window.showWarningMessage = function (message, options, items) { +vscode.window.showWarningMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showWarningMessage") return Promise.resolve(null) } -vscode.window.showWarningMessage = function (message, items) { +vscode.window.showWarningMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showWarningMessage") return Promise.resolve(null) } -vscode.window.showWarningMessage = function (message, options, items) { +vscode.window.showWarningMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showWarningMessage") return Promise.resolve(null) } -vscode.window.showErrorMessage = function (message, items) { +vscode.window.showErrorMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showErrorMessage") return Promise.resolve(null) } -vscode.window.showErrorMessage = function (message, options, items) { +vscode.window.showErrorMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showErrorMessage") return Promise.resolve(null) } -vscode.window.showErrorMessage = function (message, items) { +vscode.window.showErrorMessage = (_message, _items) => { console.log("Called stubbed function: vscode.window.showErrorMessage") return Promise.resolve(null) } -vscode.window.showErrorMessage = function (message, options, items) { +vscode.window.showErrorMessage = (_message, _options, _items) => { console.log("Called stubbed function: vscode.window.showErrorMessage") return Promise.resolve(null) } -vscode.window.showQuickPick = function (items, options, token) { +vscode.window.showQuickPick = (_items, _options, _token) => { console.log("Called stubbed function: vscode.window.showQuickPick") return "" } -vscode.window.showQuickPick = function (items, options, token) { +vscode.window.showQuickPick = (_items, _options, _token) => { console.log("Called stubbed function: vscode.window.showQuickPick") return "" } -vscode.window.showQuickPick = function (items, options, token) { +vscode.window.showQuickPick = (_items, _options, _token) => { console.log("Called stubbed function: vscode.window.showQuickPick") return [] } -vscode.window.showQuickPick = function (items, options, token) { +vscode.window.showQuickPick = (_items, _options, _token) => { console.log("Called stubbed function: vscode.window.showQuickPick") return Promise.resolve(null) } -vscode.window.showWorkspaceFolderPick = function (options) { +vscode.window.showWorkspaceFolderPick = (_options) => { console.log("Called stubbed function: vscode.window.showWorkspaceFolderPick") return Promise.resolve(null) } -vscode.window.showSaveDialog = function (options) { +vscode.window.showSaveDialog = (_options) => { console.log("Called stubbed function: vscode.window.showSaveDialog") return Promise.resolve(null) } -vscode.window.showInputBox = function (options, token) { +vscode.window.showInputBox = (_options, _token) => { console.log("Called stubbed function: vscode.window.showInputBox") return "" } -vscode.window.createQuickPick = function () { +vscode.window.createQuickPick = () => { console.log("Called stubbed function: vscode.window.createQuickPick") return createStub("unknown") } -vscode.window.createInputBox = function () { +vscode.window.createInputBox = () => { console.log("Called stubbed function: vscode.window.createInputBox") return createStub("unknown") } -vscode.window.createOutputChannel = function (name, languageId) { +vscode.window.createOutputChannel = (_name, _languageId) => { console.log("Called stubbed function: vscode.window.createOutputChannel") return createStub("unknown") } -vscode.window.createOutputChannel = function (name, options) { +vscode.window.createOutputChannel = (_name, _options) => { console.log("Called stubbed function: vscode.window.createOutputChannel") return createStub("unknown") } -vscode.window.createWebviewPanel = function (viewType, title, showOptions, options) { +vscode.window.createWebviewPanel = (_viewType, _title, _showOptions, _options) => { console.log("Called stubbed function: vscode.window.createWebviewPanel") return createStub("unknown") } -vscode.window.setStatusBarMessage = function (text, hideAfterTimeout) { +vscode.window.setStatusBarMessage = (_text, _hideAfterTimeout) => { console.log("Called stubbed function: vscode.window.setStatusBarMessage") return createStub("unknown") } -vscode.window.setStatusBarMessage = function (text, hideWhenDone) { +vscode.window.setStatusBarMessage = (_text, _hideWhenDone) => { console.log("Called stubbed function: vscode.window.setStatusBarMessage") return createStub("unknown") } -vscode.window.setStatusBarMessage = function (text) { +vscode.window.setStatusBarMessage = (_text) => { console.log("Called stubbed function: vscode.window.setStatusBarMessage") return createStub("unknown") } -vscode.window.withScmProgress = function (task) { +vscode.window.withScmProgress = (_task) => { console.log("Called stubbed function: vscode.window.withScmProgress") return Promise.resolve(null) } -vscode.window.withProgress = function (options, task) { +vscode.window.withProgress = (_options, _task) => { console.log("Called stubbed function: vscode.window.withProgress") return Promise.resolve(null) } -vscode.window.createStatusBarItem = function (id, alignment, priority) { +vscode.window.createStatusBarItem = (_id, _alignment, _priority) => { console.log("Called stubbed function: vscode.window.createStatusBarItem") return createStub("unknown") } -vscode.window.createStatusBarItem = function (alignment, priority) { +vscode.window.createStatusBarItem = (_alignment, _priority) => { console.log("Called stubbed function: vscode.window.createStatusBarItem") return createStub("unknown") } -vscode.window.createTerminal = function (name, shellPath, shellArgs) { +vscode.window.createTerminal = (_name, _shellPath, _shellArgs) => { console.log("Called stubbed function: vscode.window.createTerminal") return createStub("unknown") } -vscode.window.createTerminal = function (options) { +vscode.window.createTerminal = (_options) => { console.log("Called stubbed function: vscode.window.createTerminal") return createStub("unknown") } -vscode.window.createTerminal = function (options) { +vscode.window.createTerminal = (_options) => { console.log("Called stubbed function: vscode.window.createTerminal") return createStub("unknown") } -vscode.window.registerTreeDataProvider = function (viewId, treeDataProvider) { +vscode.window.registerTreeDataProvider = (_viewId, _treeDataProvider) => { console.log("Called stubbed function: vscode.window.registerTreeDataProvider") return createStub("unknown") } -vscode.window.createTreeView = function (viewId, options) { +vscode.window.createTreeView = (_viewId, _options) => { console.log("Called stubbed function: vscode.window.createTreeView") return createStub("unknown") } -vscode.window.registerUriHandler = function (handler) { +vscode.window.registerUriHandler = (_handler) => { console.log("Called stubbed function: vscode.window.registerUriHandler") return createStub("unknown") } -vscode.window.registerWebviewPanelSerializer = function (viewType, serializer) { +vscode.window.registerWebviewPanelSerializer = (_viewType, _serializer) => { console.log("Called stubbed function: vscode.window.registerWebviewPanelSerializer") return createStub("unknown") } -vscode.window.registerWebviewViewProvider = function (viewId, provider, options) { +vscode.window.registerWebviewViewProvider = (_viewId, _provider, _options) => { console.log("Called stubbed function: vscode.window.registerWebviewViewProvider") return createStub("unknown") } -vscode.window.registerCustomEditorProvider = function (viewType, provider, options) { +vscode.window.registerCustomEditorProvider = (_viewType, _provider, _options) => { console.log("Called stubbed function: vscode.window.registerCustomEditorProvider") return createStub("unknown") } -vscode.window.registerTerminalLinkProvider = function (provider) { +vscode.window.registerTerminalLinkProvider = (_provider) => { console.log("Called stubbed function: vscode.window.registerTerminalLinkProvider") return createStub("unknown") } -vscode.window.registerTerminalProfileProvider = function (id, provider) { +vscode.window.registerTerminalProfileProvider = (_id, _provider) => { console.log("Called stubbed function: vscode.window.registerTerminalProfileProvider") return createStub("unknown") } -vscode.window.registerFileDecorationProvider = function (provider) { +vscode.window.registerFileDecorationProvider = (_provider) => { console.log("Called stubbed function: vscode.window.registerFileDecorationProvider") return createStub("unknown") } @@ -814,40 +814,40 @@ vscode.workspace.fs = createStub("vscode.workspace.fs") vscode.workspace.rootPath = createStub("vscode.workspace.rootPath") vscode.workspace.name = createStub("vscode.workspace.name") vscode.workspace.workspaceFile = createStub("vscode.workspace.workspaceFile") -vscode.workspace.asRelativePath = function (pathOrUri, includeWorkspaceFolder) { +vscode.workspace.asRelativePath = (_pathOrUri, _includeWorkspaceFolder) => { console.log("Called stubbed function: vscode.workspace.asRelativePath") return "" } -vscode.workspace.createFileSystemWatcher = function (globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents) { +vscode.workspace.createFileSystemWatcher = (_globPattern, _ignoreCreateEvents, _ignoreChangeEvents, _ignoreDeleteEvents) => { console.log("Called stubbed function: vscode.workspace.createFileSystemWatcher") return createStub("unknown") } -vscode.workspace.findFiles = function (include, exclude, maxResults, token) { +vscode.workspace.findFiles = (_include, _exclude, _maxResults, _token) => { console.log("Called stubbed function: vscode.workspace.findFiles") return [] } -vscode.workspace.saveAll = function (includeUntitled) { +vscode.workspace.saveAll = (_includeUntitled) => { console.log("Called stubbed function: vscode.workspace.saveAll") return false } -vscode.workspace.applyEdit = function (edit, metadata) { +vscode.workspace.applyEdit = (_edit, _metadata) => { console.log("Called stubbed function: vscode.workspace.applyEdit") return false } vscode.workspace.textDocuments = [] -vscode.workspace.openTextDocument = function (uri) { +vscode.workspace.openTextDocument = (_uri) => { console.log("Called stubbed function: vscode.workspace.openTextDocument") return Promise.resolve(null) } -vscode.workspace.openTextDocument = function (fileName) { +vscode.workspace.openTextDocument = (_fileName) => { console.log("Called stubbed function: vscode.workspace.openTextDocument") return Promise.resolve(null) } -vscode.workspace.openTextDocument = function (options) { +vscode.workspace.openTextDocument = (_options) => { console.log("Called stubbed function: vscode.workspace.openTextDocument") return Promise.resolve(null) } -vscode.workspace.registerTextDocumentContentProvider = function (scheme, provider) { +vscode.workspace.registerTextDocumentContentProvider = (_scheme, _provider) => { console.log("Called stubbed function: vscode.workspace.registerTextDocumentContentProvider") return createStub("unknown") } @@ -857,18 +857,18 @@ vscode.workspace.onDidChangeTextDocument = createStub("vscode.workspace.onDidCha vscode.workspace.onWillSaveTextDocument = createStub("vscode.workspace.onWillSaveTextDocument") vscode.workspace.onDidSaveTextDocument = createStub("vscode.workspace.onDidSaveTextDocument") vscode.workspace.notebookDocuments = createStub("vscode.workspace.notebookDocuments") -vscode.workspace.openNotebookDocument = function (uri) { +vscode.workspace.openNotebookDocument = (_uri) => { console.log("Called stubbed function: vscode.workspace.openNotebookDocument") return Promise.resolve(null) } -vscode.workspace.openNotebookDocument = function (notebookType, content) { +vscode.workspace.openNotebookDocument = (_notebookType, _content) => { console.log("Called stubbed function: vscode.workspace.openNotebookDocument") return Promise.resolve(null) } vscode.workspace.onDidChangeNotebookDocument = createStub("vscode.workspace.onDidChangeNotebookDocument") vscode.workspace.onWillSaveNotebookDocument = createStub("vscode.workspace.onWillSaveNotebookDocument") vscode.workspace.onDidSaveNotebookDocument = createStub("vscode.workspace.onDidSaveNotebookDocument") -vscode.workspace.registerNotebookSerializer = function (notebookType, serializer, options) { +vscode.workspace.registerNotebookSerializer = (_notebookType, _serializer, _options) => { console.log("Called stubbed function: vscode.workspace.registerNotebookSerializer") return createStub("unknown") } @@ -882,195 +882,188 @@ vscode.workspace.onWillRenameFiles = createStub("vscode.workspace.onWillRenameFi vscode.workspace.onDidRenameFiles = createStub("vscode.workspace.onDidRenameFiles") const workspaceConfigStore = {} -vscode.workspace.getConfiguration = function (section) { - return { - get: (key, defaultValue) => { - return workspaceConfigStore[`${section}.${key}`] ?? defaultValue - }, - update: (key, value, global) => { - workspaceConfigStore[`${section}.${key}`] = value - }, - has: (key) => { - return `${section}.${key}` in workspaceConfigStore - }, - } -} +vscode.workspace.getConfiguration = (section) => ({ + get: (key, defaultValue) => { + return workspaceConfigStore[`${section}.${key}`] ?? defaultValue + }, + update: (key, value, _global) => { + workspaceConfigStore[`${section}.${key}`] = value + }, + has: (key) => { + return `${section}.${key}` in workspaceConfigStore + }, +}) vscode.workspace.onDidChangeConfiguration = createStub("vscode.workspace.onDidChangeConfiguration") -vscode.workspace.registerTaskProvider = function (type, provider) { +vscode.workspace.registerTaskProvider = (_type, _provider) => { console.log("Called stubbed function: vscode.workspace.registerTaskProvider") return createStub("unknown") } -vscode.workspace.registerFileSystemProvider = function (scheme, provider, options) { +vscode.workspace.registerFileSystemProvider = (_scheme, _provider, _options) => { console.log("Called stubbed function: vscode.workspace.registerFileSystemProvider") return createStub("unknown") } vscode.workspace.isTrusted = createStub("vscode.workspace.isTrusted") vscode.workspace.onDidGrantWorkspaceTrust = createStub("vscode.workspace.onDidGrantWorkspaceTrust") vscode.languages = {} -vscode.languages.getLanguages = function () { +vscode.languages.getLanguages = () => { console.log("Called stubbed function: vscode.languages.getLanguages") return "" } -vscode.languages.setTextDocumentLanguage = function (document, languageId) { +vscode.languages.setTextDocumentLanguage = (_document, _languageId) => { console.log("Called stubbed function: vscode.languages.setTextDocumentLanguage") return Promise.resolve(null) } -vscode.languages.match = function (selector, document) { +vscode.languages.match = (_selector, _document) => { console.log("Called stubbed function: vscode.languages.match") return 0 } vscode.languages.onDidChangeDiagnostics = createStub("vscode.languages.onDidChangeDiagnostics") -vscode.languages.getDiagnostics = function (resource) { +vscode.languages.getDiagnostics = (_resource) => { console.log("Called stubbed function: vscode.languages.getDiagnostics") return [] } -vscode.languages.getDiagnostics = function () { +vscode.languages.getDiagnostics = () => { console.log("Called stubbed function: vscode.languages.getDiagnostics") return [] } -vscode.languages.createDiagnosticCollection = function (name) { +vscode.languages.createDiagnosticCollection = (_name) => { console.log("Called stubbed function: vscode.languages.createDiagnosticCollection") return createStub("unknown") } -vscode.languages.createLanguageStatusItem = function (id, selector) { +vscode.languages.createLanguageStatusItem = (_id, _selector) => { console.log("Called stubbed function: vscode.languages.createLanguageStatusItem") return createStub("unknown") } -vscode.languages.registerCompletionItemProvider = function (selector, provider, triggerCharacters) { +vscode.languages.registerCompletionItemProvider = (_selector, _provider, _triggerCharacters) => { console.log("Called stubbed function: vscode.languages.registerCompletionItemProvider") return createStub("unknown") } -vscode.languages.registerInlineCompletionItemProvider = function (selector, provider) { +vscode.languages.registerInlineCompletionItemProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerInlineCompletionItemProvider") return createStub("unknown") } -vscode.languages.registerCodeActionsProvider = function (selector, provider, metadata) { +vscode.languages.registerCodeActionsProvider = (_selector, _provider, _metadata) => { console.log("Called stubbed function: vscode.languages.registerCodeActionsProvider") return createStub("unknown") } -vscode.languages.registerCodeLensProvider = function (selector, provider) { +vscode.languages.registerCodeLensProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerCodeLensProvider") return createStub("unknown") } -vscode.languages.registerDefinitionProvider = function (selector, provider) { +vscode.languages.registerDefinitionProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDefinitionProvider") return createStub("unknown") } -vscode.languages.registerImplementationProvider = function (selector, provider) { +vscode.languages.registerImplementationProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerImplementationProvider") return createStub("unknown") } -vscode.languages.registerTypeDefinitionProvider = function (selector, provider) { +vscode.languages.registerTypeDefinitionProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerTypeDefinitionProvider") return createStub("unknown") } -vscode.languages.registerDeclarationProvider = function (selector, provider) { +vscode.languages.registerDeclarationProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDeclarationProvider") return createStub("unknown") } -vscode.languages.registerHoverProvider = function (selector, provider) { +vscode.languages.registerHoverProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerHoverProvider") return createStub("unknown") } -vscode.languages.registerEvaluatableExpressionProvider = function (selector, provider) { +vscode.languages.registerEvaluatableExpressionProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerEvaluatableExpressionProvider") return createStub("unknown") } -vscode.languages.registerInlineValuesProvider = function (selector, provider) { +vscode.languages.registerInlineValuesProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerInlineValuesProvider") return createStub("unknown") } -vscode.languages.registerDocumentHighlightProvider = function (selector, provider) { +vscode.languages.registerDocumentHighlightProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDocumentHighlightProvider") return createStub("unknown") } -vscode.languages.registerDocumentSymbolProvider = function (selector, provider, metaData) { +vscode.languages.registerDocumentSymbolProvider = (_selector, _provider, _metaData) => { console.log("Called stubbed function: vscode.languages.registerDocumentSymbolProvider") return createStub("unknown") } -vscode.languages.registerWorkspaceSymbolProvider = function (provider) { +vscode.languages.registerWorkspaceSymbolProvider = (_provider) => { console.log("Called stubbed function: vscode.languages.registerWorkspaceSymbolProvider") return createStub("unknown") } -vscode.languages.registerReferenceProvider = function (selector, provider) { +vscode.languages.registerReferenceProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerReferenceProvider") return createStub("unknown") } -vscode.languages.registerRenameProvider = function (selector, provider) { +vscode.languages.registerRenameProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerRenameProvider") return createStub("unknown") } -vscode.languages.registerDocumentSemanticTokensProvider = function (selector, provider, legend) { +vscode.languages.registerDocumentSemanticTokensProvider = (_selector, _provider, _legend) => { console.log("Called stubbed function: vscode.languages.registerDocumentSemanticTokensProvider") return createStub("unknown") } -vscode.languages.registerDocumentRangeSemanticTokensProvider = function (selector, provider, legend) { +vscode.languages.registerDocumentRangeSemanticTokensProvider = (_selector, _provider, _legend) => { console.log("Called stubbed function: vscode.languages.registerDocumentRangeSemanticTokensProvider") return createStub("unknown") } -vscode.languages.registerDocumentFormattingEditProvider = function (selector, provider) { +vscode.languages.registerDocumentFormattingEditProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDocumentFormattingEditProvider") return createStub("unknown") } -vscode.languages.registerDocumentRangeFormattingEditProvider = function (selector, provider) { +vscode.languages.registerDocumentRangeFormattingEditProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDocumentRangeFormattingEditProvider") return createStub("unknown") } -vscode.languages.registerOnTypeFormattingEditProvider = function ( - selector, - provider, - firstTriggerCharacter, - moreTriggerCharacter, -) { +vscode.languages.registerOnTypeFormattingEditProvider = (_selector, _provider, _firstTriggerCharacter, _moreTriggerCharacter) => { console.log("Called stubbed function: vscode.languages.registerOnTypeFormattingEditProvider") return createStub("unknown") } -vscode.languages.registerSignatureHelpProvider = function (selector, provider, triggerCharacters) { +vscode.languages.registerSignatureHelpProvider = (_selector, _provider, _triggerCharacters) => { console.log("Called stubbed function: vscode.languages.registerSignatureHelpProvider") return createStub("unknown") } -vscode.languages.registerSignatureHelpProvider = function (selector, provider, metadata) { +vscode.languages.registerSignatureHelpProvider = (_selector, _provider, _metadata) => { console.log("Called stubbed function: vscode.languages.registerSignatureHelpProvider") return createStub("unknown") } -vscode.languages.registerDocumentLinkProvider = function (selector, provider) { +vscode.languages.registerDocumentLinkProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDocumentLinkProvider") return createStub("unknown") } -vscode.languages.registerColorProvider = function (selector, provider) { +vscode.languages.registerColorProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerColorProvider") return createStub("unknown") } -vscode.languages.registerInlayHintsProvider = function (selector, provider) { +vscode.languages.registerInlayHintsProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerInlayHintsProvider") return createStub("unknown") } -vscode.languages.registerFoldingRangeProvider = function (selector, provider) { +vscode.languages.registerFoldingRangeProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerFoldingRangeProvider") return createStub("unknown") } -vscode.languages.registerSelectionRangeProvider = function (selector, provider) { +vscode.languages.registerSelectionRangeProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerSelectionRangeProvider") return createStub("unknown") } -vscode.languages.registerCallHierarchyProvider = function (selector, provider) { +vscode.languages.registerCallHierarchyProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerCallHierarchyProvider") return createStub("unknown") } -vscode.languages.registerTypeHierarchyProvider = function (selector, provider) { +vscode.languages.registerTypeHierarchyProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerTypeHierarchyProvider") return createStub("unknown") } -vscode.languages.registerLinkedEditingRangeProvider = function (selector, provider) { +vscode.languages.registerLinkedEditingRangeProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerLinkedEditingRangeProvider") return createStub("unknown") } -vscode.languages.registerDocumentDropEditProvider = function (selector, provider) { +vscode.languages.registerDocumentDropEditProvider = (_selector, _provider) => { console.log("Called stubbed function: vscode.languages.registerDocumentDropEditProvider") return createStub("unknown") } -vscode.languages.setLanguageConfiguration = function (language, configuration) { +vscode.languages.setLanguageConfiguration = (_language, _configuration) => { console.log("Called stubbed function: vscode.languages.setLanguageConfiguration") return createStub("unknown") } @@ -1115,21 +1108,21 @@ vscode.NotebookCellStatusBarItem = class { } } vscode.notebooks = {} -vscode.notebooks.createNotebookController = function (id, notebookType, label, handler) { +vscode.notebooks.createNotebookController = (_id, _notebookType, _label, _handler) => { console.log("Called stubbed function: vscode.notebooks.createNotebookController") return createStub("unknown") } -vscode.notebooks.registerNotebookCellStatusBarItemProvider = function (notebookType, provider) { +vscode.notebooks.registerNotebookCellStatusBarItemProvider = (_notebookType, _provider) => { console.log("Called stubbed function: vscode.notebooks.registerNotebookCellStatusBarItemProvider") return createStub("unknown") } -vscode.notebooks.createRendererMessaging = function (rendererId) { +vscode.notebooks.createRendererMessaging = (_rendererId) => { console.log("Called stubbed function: vscode.notebooks.createRendererMessaging") return createStub("unknown") } vscode.scm = {} vscode.scm.inputBox = createStub("vscode.scm.inputBox") -vscode.scm.createSourceControl = function (id, label, rootUri) { +vscode.scm.createSourceControl = (_id, _label, _rootUri) => { console.log("Called stubbed function: vscode.scm.createSourceControl") return createStub("unknown") } @@ -1186,37 +1179,37 @@ vscode.debug.onDidStartDebugSession = createStub("vscode.debug.onDidStartDebugSe vscode.debug.onDidReceiveDebugSessionCustomEvent = createStub("vscode.debug.onDidReceiveDebugSessionCustomEvent") vscode.debug.onDidTerminateDebugSession = createStub("vscode.debug.onDidTerminateDebugSession") vscode.debug.onDidChangeBreakpoints = createStub("vscode.debug.onDidChangeBreakpoints") -vscode.debug.registerDebugConfigurationProvider = function (debugType, provider, triggerKind) { +vscode.debug.registerDebugConfigurationProvider = (_debugType, _provider, _triggerKind) => { console.log("Called stubbed function: vscode.debug.registerDebugConfigurationProvider") return createStub("unknown") } -vscode.debug.registerDebugAdapterDescriptorFactory = function (debugType, factory) { +vscode.debug.registerDebugAdapterDescriptorFactory = (_debugType, _factory) => { console.log("Called stubbed function: vscode.debug.registerDebugAdapterDescriptorFactory") return createStub("unknown") } -vscode.debug.registerDebugAdapterTrackerFactory = function (debugType, factory) { +vscode.debug.registerDebugAdapterTrackerFactory = (_debugType, _factory) => { console.log("Called stubbed function: vscode.debug.registerDebugAdapterTrackerFactory") return createStub("unknown") } -vscode.debug.startDebugging = function (folder, nameOrConfiguration, parentSessionOrOptions) { +vscode.debug.startDebugging = (_folder, _nameOrConfiguration, _parentSessionOrOptions) => { console.log("Called stubbed function: vscode.debug.startDebugging") return false } -vscode.debug.stopDebugging = function (session) { +vscode.debug.stopDebugging = (_session) => { console.log("Called stubbed function: vscode.debug.stopDebugging") } -vscode.debug.addBreakpoints = function (breakpoints) { +vscode.debug.addBreakpoints = (_breakpoints) => { console.log("Called stubbed function: vscode.debug.addBreakpoints") } -vscode.debug.removeBreakpoints = function (breakpoints) { +vscode.debug.removeBreakpoints = (_breakpoints) => { console.log("Called stubbed function: vscode.debug.removeBreakpoints") } -vscode.debug.asDebugSourceUri = function (source, session) { +vscode.debug.asDebugSourceUri = (_source, _session) => { console.log("Called stubbed function: vscode.debug.asDebugSourceUri") return createStub("unknown") } vscode.extensions = {} -vscode.extensions.getExtension = function (extensionId) { +vscode.extensions.getExtension = (_extensionId) => { console.log("Called stubbed function: vscode.extensions.getExtension") return createStub("unknown") } @@ -1226,45 +1219,45 @@ vscode.CommentThreadCollapsibleState = { Collapsed: 0, Expanded: 0 } vscode.CommentMode = { Editing: 0, Preview: 0 } vscode.CommentThreadState = { Unresolved: 0, Resolved: 0 } vscode.comments = {} -vscode.comments.createCommentController = function (id, label) { +vscode.comments.createCommentController = (_id, _label) => { console.log("Called stubbed function: vscode.comments.createCommentController") return createStub("unknown") } vscode.authentication = {} -vscode.authentication.getSession = function (providerId, scopes, options) { +vscode.authentication.getSession = (_providerId, _scopes, _options) => { console.log("Called stubbed function: vscode.authentication.getSession") return Promise.resolve(null) } -vscode.authentication.getSession = function (providerId, scopes, options) { +vscode.authentication.getSession = (_providerId, _scopes, _options) => { console.log("Called stubbed function: vscode.authentication.getSession") return Promise.resolve(null) } -vscode.authentication.getSession = function (providerId, scopes, options) { +vscode.authentication.getSession = (_providerId, _scopes, _options) => { console.log("Called stubbed function: vscode.authentication.getSession") return Promise.resolve(null) } vscode.authentication.onDidChangeSessions = createStub("vscode.authentication.onDidChangeSessions") -vscode.authentication.registerAuthenticationProvider = function (id, label, provider, options) { +vscode.authentication.registerAuthenticationProvider = (_id, _label, _provider, _options) => { console.log("Called stubbed function: vscode.authentication.registerAuthenticationProvider") return createStub("unknown") } vscode.l10n = {} -vscode.l10n.t = function (message, args) { +vscode.l10n.t = (_message, _args) => { console.log("Called stubbed function: vscode.l10n.t") return "" } -vscode.l10n.t = function (message, args) { +vscode.l10n.t = (_message, _args) => { console.log("Called stubbed function: vscode.l10n.t") return "" } -vscode.l10n.t = function (options) { +vscode.l10n.t = (_options) => { console.log("Called stubbed function: vscode.l10n.t") return "" } vscode.l10n.bundle = createStub("vscode.l10n.bundle") vscode.l10n.uri = createStub("vscode.l10n.uri") vscode.tests = {} -vscode.tests.createTestController = function (id, label) { +vscode.tests.createTestController = (_id, _label) => { console.log("Called stubbed function: vscode.tests.createTestController") return createStub("unknown") } diff --git a/tsconfig.test.json b/tsconfig.test.json index 0c999ae3..a4018e95 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -8,11 +8,26 @@ "compilerOptions": { "module": "commonjs", "moduleResolution": "node", - "types": ["node", "mocha", "should", "vscode", "chai"], - "typeRoots": ["./node_modules/@types", "./src/test/types"], + "types": [ + "node", + "mocha", + "should", + "vscode", + "chai" + ], + "typeRoots": [ + "./node_modules/@types", + "./src/test/types" + ], "outDir": "out", "rootDir": "." }, - "include": ["src/**/*.test.ts"], - "exclude": ["src/test/**/*.js", "src/**/__tests__/*", "src/test/e2e/**/*.test.ts"] + "include": [ + "src/**/*.test.ts" + ], + "exclude": [ + "src/test/**/*.js", + "src/**/__tests__/*", + "src/test/e2e/**/*.test.ts" + ] } diff --git a/tsconfig.unit-test.json b/tsconfig.unit-test.json index 349b36ac..aae15f05 100644 --- a/tsconfig.unit-test.json +++ b/tsconfig.unit-test.json @@ -4,8 +4,14 @@ "module": "commonjs" }, "ts-node": { - "require": ["tsconfig-paths/register"] + "require": [ + "tsconfig-paths/register" + ] }, - "include": ["test/**/*.ts"], - "exclude": ["node_modules"] + "include": [ + "test/**/*.ts" + ], + "exclude": [ + "node_modules" + ] } diff --git a/webview-ui/src/App.tsx b/webview-ui/src/App.tsx index 48932e0f..bf957906 100644 --- a/webview-ui/src/App.tsx +++ b/webview-ui/src/App.tsx @@ -64,18 +64,18 @@ const AppContent = () => { {showMcp && } {showAccount && ( )} {/* Do not conditionally load ChatView, it's expensive and there's state we don't want to lose (user input, disableInput, askResponse promise, etc.) */} ) diff --git a/webview-ui/src/Providers.tsx b/webview-ui/src/Providers.tsx index a1ad8934..b078eb1f 100644 --- a/webview-ui/src/Providers.tsx +++ b/webview-ui/src/Providers.tsx @@ -1,9 +1,8 @@ -import { type ReactNode } from "react" - -import { ExtensionStateContextProvider } from "./context/ExtensionStateContext" -import { ClineAuthProvider } from "./context/ClineAuthContext" import { HeroUIProvider } from "@heroui/react" +import { type ReactNode } from "react" import { CustomPostHogProvider } from "./CustomPostHogProvider" +import { ClineAuthProvider } from "./context/ClineAuthContext" +import { ExtensionStateContextProvider } from "./context/ExtensionStateContext" export function Providers({ children }: { children: ReactNode }) { return ( diff --git a/webview-ui/src/assets/ClineLogoBlack.tsx b/webview-ui/src/assets/ClineLogoBlack.tsx index 7da581e4..f9bdccb9 100644 --- a/webview-ui/src/assets/ClineLogoBlack.tsx +++ b/webview-ui/src/assets/ClineLogoBlack.tsx @@ -1,7 +1,7 @@ import { SVGProps } from "react" const ClineLogoBlack = (props: SVGProps) => ( - + ) => ( - + ) => ( - + {clineUser?.uid ? ( ) : ( @@ -123,7 +123,9 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat const fetchCreditBalance = useCallback( async (id: string, skipCache = false) => { try { - if (isLoading) return // Prevent multiple concurrent fetches + if (isLoading) { + return // Prevent multiple concurrent fetches + } // Load cached data immediately if available (unless skipping cache) if (!skipCache && loadCachedData(id)) { @@ -161,7 +163,9 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat const handleOrganizationChange = useCallback( async (event: any) => { const target = event.target as HTMLSelectElement - if (!target) return + if (!target) { + return + } const newValue = target.value if (newValue !== dropdownValue) { @@ -272,11 +276,11 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
- + onChange={handleOrganizationChange}> + Personal {userOrganizations?.map((org: UserOrganization) => ( @@ -297,11 +301,11 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
- + Dashboard
- handleSignOut()} className="w-full min-[225px]:w-1/2"> + handleSignOut()}> Log out
@@ -309,11 +313,11 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat fetchCreditBalance(dropdownValue)} - lastFetchTime={lastFetchTime} creditUrl={getClineUris(clineUrl, "credits", dropdownValue === uid ? "account" : "organization")} + fetchCreditBalance={() => fetchCreditBalance(dropdownValue)} + isLoading={isLoading} + lastFetchTime={lastFetchTime} /> @@ -321,9 +325,9 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
diff --git a/webview-ui/src/components/account/AccountWelcomeView.tsx b/webview-ui/src/components/account/AccountWelcomeView.tsx index fe5dbecc..5a1f21f7 100644 --- a/webview-ui/src/components/account/AccountWelcomeView.tsx +++ b/webview-ui/src/components/account/AccountWelcomeView.tsx @@ -11,7 +11,7 @@ export const AccountWelcomeView = () => ( upcoming features.

- handleSignIn()} className="w-full mb-4"> + handleSignIn()}> Sign up with Cline diff --git a/webview-ui/src/components/account/CreditBalance.tsx b/webview-ui/src/components/account/CreditBalance.tsx index 24e5bcb0..68997443 100644 --- a/webview-ui/src/components/account/CreditBalance.tsx +++ b/webview-ui/src/components/account/CreditBalance.tsx @@ -24,14 +24,14 @@ export const CreditBalance = ({ balance, fetchCreditBalance, creditUrl, lastFetc + disabled={isLoading} + onClick={fetchCreditBalance}>
- + Add Credits
diff --git a/webview-ui/src/components/account/CreditsHistoryTable.tsx b/webview-ui/src/components/account/CreditsHistoryTable.tsx index d9060ca9..070a095c 100644 --- a/webview-ui/src/components/account/CreditsHistoryTable.tsx +++ b/webview-ui/src/components/account/CreditsHistoryTable.tsx @@ -36,77 +36,70 @@ const CreditsHistoryTable = ({ isLoading, usageData, paymentsData, showPayments ) : ( <> - {activeTab === "usage" && ( - <> - {usageData.length > 0 ? ( - - - - Date - - - Model - - {/* + {activeTab === "usage" && + (usageData.length > 0 ? ( + + + + Date + + + Model + + {/* Tokens Used */} - - Credits Used + + Credits Used + + + + {usageData.map((row, index) => ( + + + {formatTimestamp(row.createdAt)} + {`${row.aiModelName}`} + {/* {`${row.promptTokens} → ${row.completionTokens}`} */} + {`$${Number(row.creditsUsed / 1000000).toFixed(4)}`} + ))} + + ) : ( +
+
No usage history
+
+ ))} - {usageData.map((row, index) => ( - - - {formatTimestamp(row.createdAt)} - - {`${row.aiModelName}`} - {/* {`${row.promptTokens} → ${row.completionTokens}`} */} - {`$${Number(row.creditsUsed / 1000000).toFixed(4)}`} - - ))} -
- ) : ( -
-
No usage history
-
- )} - - )} + {showPayments && + activeTab === "payments" && + (paymentsData.length > 0 ? ( + + + + Date + + + Total Cost + + + Credits + + - {showPayments && activeTab === "payments" && ( - <> - {paymentsData.length > 0 ? ( - - - - Date - - - Total Cost - - - Credits - + {paymentsData.map((row, index) => ( + + {formatTimestamp(row.paidAt)} + {`$${formatDollars(row.amountCents)}`} + {`${row.credits}`} - - {paymentsData.map((row, index) => ( - - - {formatTimestamp(row.paidAt)} - - {`$${formatDollars(row.amountCents)}`} - {`${row.credits}`} - - ))} - - ) : ( -
-
No payment history
-
- )} - - )} + ))} +
+ ) : ( +
+
No payment history
+
+ ))} )} diff --git a/webview-ui/src/components/account/helpers.ts b/webview-ui/src/components/account/helpers.ts index 1273c2f4..b09410c2 100644 --- a/webview-ui/src/components/account/helpers.ts +++ b/webview-ui/src/components/account/helpers.ts @@ -2,10 +2,16 @@ import type { UsageTransaction as ClineAccountUsageTransaction } from "@shared/C import type { UsageTransaction as ProtoUsageTransaction } from "@shared/proto/cline/account" export const getMainRole = (roles?: string[]) => { - if (!roles) return undefined + if (!roles) { + return undefined + } - if (roles.includes("owner")) return "Owner" - if (roles.includes("admin")) return "Admin" + if (roles.includes("owner")) { + return "Owner" + } + if (roles.includes("admin")) { + return "Admin" + } return "Member" } diff --git a/webview-ui/src/components/browser/BrowserSettingsMenu.tsx b/webview-ui/src/components/browser/BrowserSettingsMenu.tsx index da14351b..e746768c 100644 --- a/webview-ui/src/components/browser/BrowserSettingsMenu.tsx +++ b/webview-ui/src/components/browser/BrowserSettingsMenu.tsx @@ -1,7 +1,7 @@ -import { useExtensionState } from "@/context/ExtensionStateContext" import { EmptyRequest, StringRequest } from "@shared/proto/cline/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useEffect, useRef, useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" import { BrowserServiceClient, UiServiceClient } from "../../services/grpc-client" interface ConnectionInfo { @@ -149,8 +149,8 @@ export const BrowserSettingsMenu = () => { appearance="icon" className="browser-info-icon" onClick={toggleInfoPopover} - title="Browser connection info" - style={{ marginRight: "4px" }}> + style={{ marginRight: "4px" }} + title="Browser connection info"> { {showInfoPopover && ( // InfoPopover - Dropdown container with connection details
{ const minorVersion = version.split(".").slice(0, 2).join(".") // 2.0.0 -> 2.0 return (
- +

@@ -49,14 +49,14 @@ const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => { Focus Chain: Keeps cline focused on long-horizon tasks with automatic todo list management, breaking down complex tasks into manageable steps with real-time progress tracking and passive reminders. Steps are displayed in a handy todo list, which can be edited mid-task.{" "} - + Learn more
  • Auto Compact: Auto summarizes your task and next steps when your conversation approaches the model’s context window limit. This significantly helps Cline stay on track for long task sessions!{" "} - + Learn more
  • @@ -64,7 +64,7 @@ const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => { Deep Planning: New /deep-planning slash command transforms Cline into an architect who investigates your codebase, asks clarifying questions, and creates a comprehensive plan before writing any code.{" "} - + Learn more @@ -77,17 +77,17 @@ const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => { model for 1M context, or use the original for 200K. - + + }} + key="1" + title="Previous Updates:">
    • Optimized for Claude 4: Cline is now optimized to work with the Claude 4 family of models, @@ -138,14 +138,14 @@ const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => {

      Join us on{" "} - + X, {" "} - + discord, {" "} or{" "} - + r/cline for more updates! diff --git a/webview-ui/src/components/chat/BrowserSessionRow.tsx b/webview-ui/src/components/chat/BrowserSessionRow.tsx index 7586cee7..e71643c2 100644 --- a/webview-ui/src/components/chat/BrowserSessionRow.tsx +++ b/webview-ui/src/components/chat/BrowserSessionRow.tsx @@ -1,9 +1,3 @@ -import { BrowserSettingsMenu } from "@/components/browser/BrowserSettingsMenu" -import { ChatRowContent, ProgressIndicator } from "@/components/chat/ChatRow" -import { CheckpointControls } from "@/components/common/CheckpointControls" -import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { FileServiceClient } from "@/services/grpc-client" import { BROWSER_VIEWPORT_PRESETS } from "@shared/BrowserSettings" import { BrowserAction, BrowserActionResult, ClineMessage, ClineSayBrowserAction } from "@shared/ExtensionMessage" import { StringRequest } from "@shared/proto/cline/common" @@ -12,6 +6,12 @@ import deepEqual from "fast-deep-equal" import React, { CSSProperties, memo, useCallback, useEffect, useMemo, useRef, useState } from "react" import { useSize } from "react-use" import styled from "styled-components" +import { BrowserSettingsMenu } from "@/components/browser/BrowserSettingsMenu" +import { ChatRowContent, ProgressIndicator } from "@/components/chat/ChatRow" +import { CheckpointControls } from "@/components/common/CheckpointControls" +import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { FileServiceClient } from "@/services/grpc-client" interface BrowserSessionRowProps { messages: ClineMessage[] @@ -293,13 +293,13 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {

      {currentPage?.nextAction?.messages.map((message) => ( ))} @@ -320,7 +320,9 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { // Track latest click coordinate const latestClickPosition = useMemo(() => { - if (!isBrowsing) return undefined + if (!isBrowsing) { + return undefined + } // Look through current page's next actions for the latest browser_action const actions = currentPage?.nextAction?.messages || [] @@ -344,7 +346,7 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { // shouldShowCheckpoints = lastModifiedMessage?.ask === "resume_completed_task" || lastModifiedMessage?.ask === "resume_task" // } - const shouldShowSettings = useMemo(() => { + const _shouldShowSettings = useMemo(() => { const lastMessage = messages[messages.length - 1] return lastMessage?.ask === "browser_action_launch" || lastMessage?.say === "browser_action_launch" }, [messages]) @@ -363,7 +365,7 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { )} - <>{isAutoApproved ? "Cline is using the browser:" : "Cline wants to use the browser:"} + {isAutoApproved ? "Cline is using the browser:" : "Cline wants to use the browser:"}
      { }}> {displayState.screenshot ? ( Browser screenshot FileServiceClient.openImage(StringRequest.create({ value: displayState.screenshot })).catch( (err) => console.error("Failed to open image:", err), ) } + src={displayState.screenshot} + style={imgScreenshotStyle} /> ) : (
      @@ -525,7 +527,7 @@ const BrowserSessionRowContent = memo( Browser Session Started
      - +
      ) @@ -540,12 +542,12 @@ const BrowserSessionRowContent = memo( return (
      ) @@ -614,13 +616,13 @@ const BrowserCursor: React.FC<{ style?: CSSProperties }> = ({ style }) => { return ( cursor ) } diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 143ac681..4d05dcb7 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1,22 +1,4 @@ -import { VSCodeBadge, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react" -import deepEqual from "fast-deep-equal" -import React, { memo, MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from "react" -import styled from "styled-components" -import { useSize } from "react-use" - -import { OptionsButtons } from "@/components/chat/OptionsButtons" -import TaskFeedbackButtons from "@/components/chat/TaskFeedbackButtons" -import { CheckmarkControl } from "@/components/common/CheckmarkControl" -import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import MarkdownBlock from "@/components/common/MarkdownBlock" -import SuccessButton from "@/components/common/SuccessButton" -import { WithCopyButton } from "@/components/common/CopyButton" -import McpResponseDisplay from "@/components/mcp/chat-display/McpResponseDisplay" -import McpResourceRow from "@/components/mcp/configuration/tabs/installed/server-row/McpResourceRow" -import McpToolRow from "@/components/mcp/configuration/tabs/installed/server-row/McpToolRow" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { FileServiceClient, TaskServiceClient, UiServiceClient } from "@/services/grpc-client" -import { findMatchingResourceOrTemplate, getMcpServerDisplayName } from "@/utils/mcp" +import { COMMAND_OUTPUT_STRING, COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences" import { ClineApiReqInfo, ClineAskQuestion, @@ -26,22 +8,38 @@ import { ClineSayTool, COMPLETION_RESULT_CHANGES_FLAG, } from "@shared/ExtensionMessage" -import { COMMAND_OUTPUT_STRING, COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences" import { Int64Request, StringRequest } from "@shared/proto/cline/common" - -import CodeAccordian, { cleanPathPrefix } from "../common/CodeAccordian" +import { VSCodeBadge, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react" +import deepEqual from "fast-deep-equal" +import React, { MouseEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from "react" +import { useSize } from "react-use" +import styled from "styled-components" +import { OptionsButtons } from "@/components/chat/OptionsButtons" +import TaskFeedbackButtons from "@/components/chat/TaskFeedbackButtons" +import { CheckmarkControl } from "@/components/common/CheckmarkControl" +import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import { WithCopyButton } from "@/components/common/CopyButton" +import MarkdownBlock from "@/components/common/MarkdownBlock" +import SuccessButton from "@/components/common/SuccessButton" +import McpResponseDisplay from "@/components/mcp/chat-display/McpResponseDisplay" +import McpResourceRow from "@/components/mcp/configuration/tabs/installed/server-row/McpResourceRow" +import McpToolRow from "@/components/mcp/configuration/tabs/installed/server-row/McpToolRow" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { FileServiceClient, TaskServiceClient, UiServiceClient } from "@/services/grpc-client" +import { findMatchingResourceOrTemplate, getMcpServerDisplayName } from "@/utils/mcp" import { CheckpointControls } from "../common/CheckpointControls" +import CodeAccordian, { cleanPathPrefix } from "../common/CodeAccordian" +import { ErrorBlockTitle } from "./ErrorBlockTitle" +import ErrorRow from "./ErrorRow" import NewTaskPreview from "./NewTaskPreview" +import QuoteButton from "./QuoteButton" import ReportBugPreview from "./ReportBugPreview" import UserMessage from "./UserMessage" -import QuoteButton from "./QuoteButton" -import ErrorRow from "./ErrorRow" -import { ErrorBlockTitle } from "./ErrorBlockTitle" const normalColor = "var(--vscode-foreground)" const errorColor = "var(--vscode-errorForeground)" const successColor = "var(--vscode-charts-green)" -const cancelledColor = "var(--vscode-descriptionForeground)" +const _cancelledColor = "var(--vscode-descriptionForeground)" const ChatRowContainer = styled.div` padding: 10px 6px 10px 15px; @@ -371,7 +369,7 @@ export const ChatRowContent = memo( marginBottom: "12px", } - const pStyle: React.CSSProperties = { + const _pStyle: React.CSSProperties = { margin: 0, whiteSpace: "pre-wrap", wordBreak: "break-word", @@ -422,9 +420,9 @@ export const ChatRowContent = memo( ) @@ -438,11 +436,11 @@ export const ChatRowContent = memo( Cline wants to create a new file:
      ) @@ -467,6 +465,15 @@ export const ChatRowContent = memo( border: "1px solid var(--vscode-editorGroup-border)", }}>
      { + FileServiceClient.openFile( + StringRequest.create({ value: tool.content }), + ).catch((err) => console.error("Failed to open file:", err)) + } + } style={{ color: "var(--vscode-descriptionForeground)", display: "flex", @@ -477,16 +484,7 @@ export const ChatRowContent = memo( WebkitUserSelect: isImage ? "text" : "none", MozUserSelect: isImage ? "text" : "none", msUserSelect: isImage ? "text" : "none", - }} - onClick={ - isImage - ? undefined - : () => { - FileServiceClient.openFile( - StringRequest.create({ value: tool.content }), - ).catch((err) => console.error("Failed to open file:", err)) - } - }> + }}> {tool.path?.startsWith(".") && .} ) @@ -550,10 +548,10 @@ export const ChatRowContent = memo(
      ) @@ -572,9 +570,9 @@ export const ChatRowContent = memo(
      ) @@ -591,10 +589,10 @@ export const ChatRowContent = memo(

    ) @@ -613,6 +611,7 @@ export const ChatRowContent = memo( border: "1px solid var(--vscode-editorGroup-border)", }}>
    + }}> {isExpanded ? (
    @@ -689,6 +687,14 @@ export const ChatRowContent = memo(
    { + // 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) + }) + } + }} style={{ borderRadius: 3, backgroundColor: CODE_BLOCK_BG_COLOR, @@ -700,16 +706,6 @@ export const ChatRowContent = memo( WebkitUserSelect: "none", MozUserSelect: "none", msUserSelect: "none", - }} - onClick={() => { - // 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) - }) - } }}> - + {output.length > 0 && (
    e.stopPropagation()}> tool.name === useMcpServer.toolName)?.autoApprove || false, }} - serverName={useMcpServer.serverName} />
    {useMcpServer.arguments && useMcpServer.arguments !== "{}" && ( @@ -885,8 +881,8 @@ export const ChatRowContent = memo(
    @@ -905,6 +901,7 @@ export const ChatRowContent = memo( return ( <>
    + }}>
    {((cost == null && apiRequestFailedMessage) || apiReqStreamingFailedMessage) && ( )} @@ -948,8 +944,8 @@ export const ChatRowContent = memo(
    @@ -993,18 +989,18 @@ export const ChatRowContent = memo( case "text": return ( + position="bottom-right" + ref={contentRef} + textToCopy={message.text}> {quoteButtonState.visible && ( { handleQuoteClick() }} + top={quoteButtonState.top} /> )} @@ -1069,11 +1065,11 @@ export const ChatRowContent = memo( case "user_feedback": return ( ) case "user_feedback_diff": @@ -1086,27 +1082,20 @@ export const ChatRowContent = memo( }}>
    ) case "error": - return + return case "diff_error": - return + return case "clineignore_error": - return + return case "checkpoint_created": - return ( - <> - - - ) + return case "load_mcp_documentation": return (
    + }} + textToCopy={text}> {quoteButtonState.visible && ( )} @@ -1191,53 +1180,51 @@ export const ChatRowContent = memo( ) case "shell_integration_warning": return ( - <> +
    -
    + - - - Shell Integration Unavailable - -
    -
    - 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").{" "} - - Still having trouble? - -
    + Shell Integration Unavailable +
    - +
    + 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").{" "} + + Still having trouble? + +
    +
    ) case "task_progress": return null // task_progress messages should be displayed in TaskHeader only, not in chat @@ -1259,9 +1246,9 @@ export const ChatRowContent = memo( case "ask": switch (message.ask) { case "mistake_limit_reached": - return + return case "auto_approval_max_req_reached": - return + return case "completion_result": if (message.text) { const hasChanges = message.text.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false @@ -1276,32 +1263,32 @@ export const ChatRowContent = memo( {icon} {title}
    + }} + textToCopy={text}> {quoteButtonState.visible && ( )} @@ -1345,7 +1332,7 @@ export const ChatRowContent = memo( question = parsedMessage.question options = parsedMessage.options selected = parsedMessage.selected - } catch (e) { + } catch (_e) { // legacy messages would pass question directly question = message.text } @@ -1359,28 +1346,28 @@ export const ChatRowContent = memo(
    )} + ref={contentRef} + style={{ paddingTop: 10 }} + textToCopy={question}> 0) } - inputValue={inputValue} + options={options} + selected={selected} /> {quoteButtonState.visible && ( { handleQuoteClick() }} + top={quoteButtonState.top} /> )} @@ -1446,33 +1433,33 @@ export const ChatRowContent = memo( response = parsedMessage.response options = parsedMessage.options selected = parsedMessage.selected - } catch (e) { + } catch (_e) { // legacy messages would pass response directly response = message.text } return ( + position="bottom-right" + ref={contentRef} + textToCopy={response}> 0) } - inputValue={inputValue} + options={options} + selected={selected} /> {quoteButtonState.visible && ( { handleQuoteClick() }} + top={quoteButtonState.top} /> )} diff --git a/webview-ui/src/components/chat/ChatTextArea.tsx b/webview-ui/src/components/chat/ChatTextArea.tsx index 5206c294..1610447a 100644 --- a/webview-ui/src/components/chat/ChatTextArea.tsx +++ b/webview-ui/src/components/chat/ChatTextArea.tsx @@ -4,6 +4,7 @@ import { FileSearchRequest, FileSearchType, RelativePathsRequest } from "@shared import { UpdateApiConfigurationRequest } from "@shared/proto/cline/models" import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/cline/state" import { convertApiConfigurationToProto } from "@shared/proto-conversions/models/api-configuration-conversion" +import { Mode } from "@shared/storage/types" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import type React from "react" import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react" @@ -31,6 +32,7 @@ import { shouldShowContextMenu, } from "@/utils/context-mentions" import { useMetaKeyDetection, useShortcut } from "@/utils/hooks" +import { isSafari } from "@/utils/platformUtils" import { getMatchingSlashCommands, insertSlashCommand, @@ -43,8 +45,6 @@ import { import { validateApiConfiguration, validateModelId } from "@/utils/validate" import ClineRulesToggleModal from "../cline-rules/ClineRulesToggleModal" import ServersToggleModal from "./ServersToggleModal" -import { Mode } from "@shared/storage/types" -import { isSafari } from "@/utils/platformUtils" const { MAX_IMAGES_AND_FILES_PER_MESSAGE } = CHAT_CONSTANTS @@ -312,7 +312,7 @@ const ChatTextArea = forwardRef( const [menuPosition, setMenuPosition] = useState(0) const [shownTooltipMode, setShownTooltipMode] = useState(null) const [pendingInsertions, setPendingInsertions] = useState([]) - const shiftHoldTimerRef = useRef(null) + const _shiftHoldTimerRef = useRef(null) const [showUnsupportedFileError, setShowUnsupportedFileError] = useState(false) const unsupportedFileTimerRef = useRef(null) const [showDimensionError, setShowDimensionError] = useState(false) @@ -412,7 +412,7 @@ const ChatTextArea = forwardRef( setSearchLoading(true) // Map ContextMenuOptionType to FileSearchType enum - let searchType = undefined + let searchType if (type === ContextMenuOptionType.File) { searchType = FileSearchType.FILE } else if (type === ContextMenuOptionType.Folder) { @@ -556,7 +556,9 @@ const ChatTextArea = forwardRef( const options = getContextMenuOptions(searchQuery, selectedType, queryItems, fileSearchResults) const optionsLength = options.length - if (optionsLength === 0) return prevIndex + if (optionsLength === 0) { + return prevIndex + } // Find selectable options (non-URL types) const selectableOptions = options.filter( @@ -564,7 +566,9 @@ const ChatTextArea = forwardRef( option.type !== ContextMenuOptionType.URL && option.type !== ContextMenuOptionType.NoResults, ) - if (selectableOptions.length === 0) return -1 // No selectable options + if (selectableOptions.length === 0) { + return -1 // No selectable options + } // Find the index of the next selectable option const currentSelectableIndex = selectableOptions.findIndex((option) => option === options[prevIndex]) @@ -936,7 +940,9 @@ const ChatTextArea = forwardRef( }, []) const updateHighlights = useCallback(() => { - if (!textAreaRef.current || !highlightLayerRef.current) return + if (!textAreaRef.current || !highlightLayerRef.current) { + return + } let processedText = textAreaRef.current.value @@ -1122,7 +1128,9 @@ const ChatTextArea = forwardRef( requestyModelId, } = getModeSpecificFields(apiConfiguration, mode) const unknownModel = "unknown" - if (!apiConfiguration) return unknownModel + if (!apiConfiguration) { + return unknownModel + } switch (selectedProvider) { case "cline": return `${selectedProvider}:${selectedModelId}` @@ -1407,6 +1415,10 @@ const ChatTextArea = forwardRef( return (
    ( display: "flex", // Drag-over styles moved to DynamicTextArea transition: "background-color 0.1s ease-in-out, border 0.1s ease-in-out", - }} - onDrop={onDrop} - onDragOver={onDragOver} - onDragEnter={handleDragEnter} - onDragLeave={handleDragLeave}> + }}> {showDimensionError && (
    ( {showSlashCommandsMenu && (
    )} @@ -1485,15 +1493,15 @@ const ChatTextArea = forwardRef( {showContextMenu && (
    )} @@ -1536,8 +1544,32 @@ const ChatTextArea = forwardRef( }} /> { + handleInputChange(e) + updateHighlights() + }} + onFocus={() => { + setIsTextAreaFocused(true) + onFocusChange?.(true) // Call prop on focus + }} + onHeightChange={(height) => { + if (textAreaBaseHeight === undefined || height < textAreaBaseHeight) { + setTextAreaBaseHeight(height) + } + onHeightChange?.(height) + }} + onKeyDown={handleKeyDown} + onKeyUp={handleKeyUp} + onMouseUp={updateCursorPosition} + onPaste={handlePaste} + onScroll={() => updateHighlights()} + onSelect={updateCursorPosition} + placeholder={showUnsupportedFileError || showDimensionError ? "" : placeholderText} ref={(el) => { if (typeof ref === "function") { ref(el) @@ -1546,30 +1578,6 @@ const ChatTextArea = forwardRef( } textAreaRef.current = el }} - value={inputValue} - onChange={(e) => { - handleInputChange(e) - updateHighlights() - }} - onKeyDown={handleKeyDown} - onKeyUp={handleKeyUp} - onFocus={() => { - setIsTextAreaFocused(true) - onFocusChange?.(true) // Call prop on focus - }} - onBlur={handleBlur} - onPaste={handlePaste} - onSelect={updateCursorPosition} - onMouseUp={updateCursorPosition} - onHeightChange={(height) => { - if (textAreaBaseHeight === undefined || height < textAreaBaseHeight) { - setTextAreaBaseHeight(height) - } - onHeightChange?.(height) - }} - placeholder={showUnsupportedFileError || showDimensionError ? "" : placeholderText} - maxRows={10} - autoFocus={true} style={{ width: "100%", boxSizing: "border-box", @@ -1607,7 +1615,7 @@ const ChatTextArea = forwardRef( : "none", outlineOffset: isDraggingOver && !showUnsupportedFileError ? "1px" : "0px", // Add offset for drag-over outline }} - onScroll={() => updateHighlights()} + value={inputValue} /> {!inputValue && selectedImages.length === 0 && selectedFiles.length === 0 && (
    @@ -1616,11 +1624,11 @@ const ChatTextArea = forwardRef( )} {(selectedImages.length > 0 || selectedFiles.length > 0) && ( ( }} /> */}
    { if (!sendingDisabled) { setIsTextAreaFocused(false) @@ -1695,11 +1703,11 @@ const ChatTextArea = forwardRef( height: "100%", zIndex: 6, }}> - + @@ -1712,9 +1720,9 @@ const ChatTextArea = forwardRef( { if (!shouldDisableFilesAndImages) { @@ -1735,12 +1743,12 @@ const ChatTextArea = forwardRef( + role="button" + tabIndex={0} + title="Select Model / API Provider"> {modelDisplayName} @@ -1752,11 +1760,11 @@ const ChatTextArea = forwardRef( bottom: `calc(100vh - ${menuPosition}px + 6px)`, }}> )} @@ -1765,26 +1773,26 @@ const ChatTextArea = forwardRef(
    {/* Tooltip for Plan/Act toggle remains outside the conditional rendering */} + visible={shownTooltipMode !== null}> setShownTooltipMode(null)} onMouseOver={() => setShownTooltipMode("plan")} - onMouseLeave={() => setShownTooltipMode(null)}> + role="switch"> Plan setShownTooltipMode(null)} onMouseOver={() => setShownTooltipMode("act")} - onMouseLeave={() => setShownTooltipMode(null)}> + role="switch"> Act diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index 28c0253c..bc336198 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -3,13 +3,14 @@ import { combineApiRequests } from "@shared/combineApiRequests" import { combineCommandSequences } from "@shared/combineCommandSequences" import type { ClineApiReqInfo, ClineMessage } from "@shared/ExtensionMessage" import { getApiMetrics } from "@shared/getApiMetrics" -import { BooleanRequest, EmptyRequest, StringRequest } from "@shared/proto/cline/common" +import { BooleanRequest, StringRequest } from "@shared/proto/cline/common" import { useCallback, useEffect, useMemo } from "react" import { useMount } from "react-use" import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils" import { useExtensionState } from "@/context/ExtensionStateContext" import { FileServiceClient, UiServiceClient } from "@/services/grpc-client" import { Navbar } from "../menu/Navbar" +import AutoApproveBar from "./auto-approve-menu/AutoApproveBar" // Import utilities and hooks from the new structure import { ActionButtons, @@ -26,7 +27,6 @@ import { useScrollBehavior, WelcomeSection, } from "./chat-view" -import AutoApproveBar from "./auto-approve-menu/AutoApproveBar" interface ChatViewProps { isHidden: boolean @@ -64,15 +64,21 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie const lastApiReqTotalTokens = useMemo(() => { const getTotalTokensFromApiReqMessage = (msg: ClineMessage) => { - if (!msg.text) return 0 + if (!msg.text) { + return 0 + } const { tokensIn, tokensOut, cacheWrites, cacheReads }: ClineApiReqInfo = JSON.parse(msg.text) return (tokensIn || 0) + (tokensOut || 0) + (cacheWrites || 0) + (cacheReads || 0) } const lastApiReqMessage = findLast(modifiedMessages, (msg) => { - if (msg.say !== "api_req_started") return false + if (msg.say !== "api_req_started") { + return false + } return getTotalTokensFromApiReqMessage(msg) > 0 }) - if (!lastApiReqMessage) return undefined + if (!lastApiReqMessage) { + return undefined + } return getTotalTokensFromApiReqMessage(lastApiReqMessage) }, [modifiedMessages]) @@ -332,60 +338,60 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie {IS_STANDALONE && } {task ? ( ) : ( )} {task && ( )}
    diff --git a/webview-ui/src/components/chat/ContextMenu.tsx b/webview-ui/src/components/chat/ContextMenu.tsx index a42bd93e..8d891bf4 100644 --- a/webview-ui/src/components/chat/ContextMenu.tsx +++ b/webview-ui/src/components/chat/ContextMenu.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useMemo, useRef, useState } from "react" -import { ContextMenuOptionType, ContextMenuQueryItem, getContextMenuOptions, SearchResult } from "@/utils/context-mentions" import { cleanPathPrefix } from "@/components/common/CodeAccordian" +import { ContextMenuOptionType, ContextMenuQueryItem, getContextMenuOptions, SearchResult } from "@/utils/context-mentions" interface ContextMenuProps { onSelect: (type: ContextMenuOptionType, value?: string) => void @@ -166,14 +166,14 @@ const ContextMenu: React.FC = ({ return (
    + }}>
    = ({
    isOptionSelectable(option) && onSelect(option.type, option.value)} + onMouseEnter={() => isOptionSelectable(option) && setSelectedIndex(index)} style={{ padding: "8px 12px", cursor: isOptionSelectable(option) ? "pointer" : "default", @@ -220,8 +221,7 @@ const ContextMenu: React.FC = ({ index === selectedIndex && isOptionSelectable(option) ? "var(--vscode-quickInputList-focusBackground)" : "", - }} - onMouseEnter={() => isOptionSelectable(option) && setSelectedIndex(index)}> + }}>
    = ({ { try { await TaskServiceClient.askResponse( @@ -73,7 +72,6 @@ const CreditLimitError: React.FC = ({ console.error("Error invoking action:", error) } }} - appearance="secondary" style={{ width: "100%", }}> diff --git a/webview-ui/src/components/chat/ErrorBlockTitle.tsx b/webview-ui/src/components/chat/ErrorBlockTitle.tsx index 013fd17d..d8544f70 100644 --- a/webview-ui/src/components/chat/ErrorBlockTitle.tsx +++ b/webview-ui/src/components/chat/ErrorBlockTitle.tsx @@ -96,7 +96,7 @@ export const ErrorBlockTitle = ({ } else if (retryStatus) { // Handle retry state const retryOperations = Math.max(0, retryStatus.maxAttempts - 1) - return + return } return {details.title} diff --git a/webview-ui/src/components/chat/ErrorRow.test.tsx b/webview-ui/src/components/chat/ErrorRow.test.tsx index e3b8cc96..ab9d2184 100644 --- a/webview-ui/src/components/chat/ErrorRow.test.tsx +++ b/webview-ui/src/components/chat/ErrorRow.test.tsx @@ -42,27 +42,27 @@ describe("ErrorRow", () => { }) it("renders basic error message", () => { - render() + render() expect(screen.getByText("Test error message")).toBeInTheDocument() }) it("renders mistake limit reached error", () => { const mistakeMessage = { ...mockMessage, text: "Mistake limit reached" } - render() + render() expect(screen.getByText("Mistake limit reached")).toBeInTheDocument() }) it("renders auto approval max requests error", () => { const maxReqMessage = { ...mockMessage, text: "Max requests reached" } - render() + render() expect(screen.getByText("Max requests reached")).toBeInTheDocument() }) it("renders diff error", () => { - render() + render() expect( screen.getByText("The model used search patterns that don't match anything in the file. Retrying..."), @@ -71,7 +71,7 @@ describe("ErrorRow", () => { it("renders clineignore error", () => { const clineignoreMessage = { ...mockMessage, text: "/path/to/file.txt" } - render() + render() expect(screen.getByText(/Cline tried to access/)).toBeInTheDocument() expect(screen.getByText("/path/to/file.txt")).toBeInTheDocument() @@ -96,7 +96,7 @@ describe("ErrorRow", () => { const { ClineError } = await import("../../../../src/services/error/ClineError") vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any) - render() + render() expect(screen.getByTestId("credit-limit-error")).toBeInTheDocument() expect(screen.getByText("You have run out of credits.")).toBeInTheDocument() @@ -114,7 +114,7 @@ describe("ErrorRow", () => { const { ClineError } = await import("../../../../src/services/error/ClineError") vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any) - render() + render() expect(screen.getByText("Rate limit exceeded")).toBeInTheDocument() expect(screen.getByText("Request ID: req_123456")).toBeInTheDocument() @@ -131,7 +131,7 @@ describe("ErrorRow", () => { const { ClineError } = await import("../../../../src/services/error/ClineError") vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any) - render() + render() expect(screen.getByText("Authentication failed")).toBeInTheDocument() expect(screen.getByText("Sign in to Cline")).toBeInTheDocument() @@ -149,9 +149,9 @@ describe("ErrorRow", () => { render( , ) @@ -173,7 +173,7 @@ describe("ErrorRow", () => { const { ClineError } = await import("../../../../src/services/error/ClineError") vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any) - render() + render() expect(screen.getByText("Streaming failed")).toBeInTheDocument() }) @@ -182,7 +182,7 @@ describe("ErrorRow", () => { const { ClineError } = await import("../../../../src/services/error/ClineError") vi.mocked(ClineError.parse).mockReturnValue(undefined) - render() + render() // When ClineError.parse returns null, clineErrorMessage is undefined, so it renders an empty paragraph // The fallback to message.text only happens when there's no apiRequestFailedMessage at all @@ -192,7 +192,7 @@ describe("ErrorRow", () => { }) it("renders regular error message when no API error messages are provided", () => { - render() + render() expect(screen.getByText("Test error message")).toBeInTheDocument() }) diff --git a/webview-ui/src/components/chat/ErrorRow.tsx b/webview-ui/src/components/chat/ErrorRow.tsx index 24d59d8f..b645e68c 100644 --- a/webview-ui/src/components/chat/ErrorRow.tsx +++ b/webview-ui/src/components/chat/ErrorRow.tsx @@ -1,11 +1,11 @@ -import { memo } from "react" -import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { ClineMessage } from "@shared/ExtensionMessage" -import { ClineError, ClineErrorType } from "../../../../src/services/error/ClineError" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import { memo } from "react" import CreditLimitError from "@/components/chat/CreditLimitError" import { handleSignIn, useClineAuth } from "@/context/ClineAuthContext" +import { ClineError, ClineErrorType } from "../../../../src/services/error/ClineError" -const errorColor = "var(--vscode-errorForeground)" +const _errorColor = "var(--vscode-errorForeground)" interface ErrorRowProps { message: ClineMessage @@ -36,9 +36,9 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre return ( ) @@ -65,8 +65,8 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
    It seems like you're having Windows PowerShell issues, please see this{" "} + className="underline text-inherit" + href="https://github.com/cline/cline/wiki/TroubleShooting-%E2%80%90-%22PowerShell-is-not-recognized-as-an-internal-or-external-command%22"> troubleshooting guide . @@ -82,7 +82,7 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre (Click "Retry" below) ) : ( - + Sign in to Cline )} diff --git a/webview-ui/src/components/chat/OptionsButtons.tsx b/webview-ui/src/components/chat/OptionsButtons.tsx index 8e200713..6e0bfb97 100644 --- a/webview-ui/src/components/chat/OptionsButtons.tsx +++ b/webview-ui/src/components/chat/OptionsButtons.tsx @@ -1,7 +1,7 @@ -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import { TaskServiceClient } from "@/services/grpc-client" import { AskResponseRequest } from "@shared/proto/cline/task" import styled from "styled-components" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import { TaskServiceClient } from "@/services/grpc-client" const OptionButton = styled.button<{ isSelected?: boolean; isNotSelectable?: boolean }>` padding: 8px 12px; @@ -34,7 +34,9 @@ export const OptionsButtons = ({ isActive?: boolean inputValue?: string }) => { - if (!options?.length) return null + if (!options?.length) { + return null + } const hasSelected = selected !== undefined && options.includes(selected) @@ -52,11 +54,11 @@ export const OptionsButtons = ({
    */} {options.map((option, index) => ( { if (hasSelected || !isActive) { return diff --git a/webview-ui/src/components/chat/QuoteButton.tsx b/webview-ui/src/components/chat/QuoteButton.tsx index b143b4b6..8c443afe 100644 --- a/webview-ui/src/components/chat/QuoteButton.tsx +++ b/webview-ui/src/components/chat/QuoteButton.tsx @@ -1,6 +1,6 @@ +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import React from "react" import styled from "styled-components" -import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" interface QuoteButtonProps { top: number @@ -34,16 +34,16 @@ const ButtonContainer = styled.div` const QuoteButton: React.FC = ({ top, left, onClick }) => { return ( // Pass transient props to the styled component - + { e.stopPropagation() // Prevent triggering mouseup on the parent onClick() }} - style={{ padding: "2px 4px", height: "auto", minWidth: "auto" }}> + style={{ padding: "2px 4px", height: "auto", minWidth: "auto" }} + title="Quote selection in reply"> {" "} {/* Adjust padding */} = ({ text, onDismiss, isFocused }) => { - const cardClassName = `reply-card ${isFocused ? "reply-card--focused" : ""}` + const _cardClassName = `reply-card ${isFocused ? "reply-card--focused" : ""}` return ( @@ -78,7 +78,7 @@ const QuotedMessagePreview: React.FC = ({ text, onDis {text} - + diff --git a/webview-ui/src/components/chat/ServersToggleModal.tsx b/webview-ui/src/components/chat/ServersToggleModal.tsx index 849a3c96..f84a7b17 100644 --- a/webview-ui/src/components/chat/ServersToggleModal.tsx +++ b/webview-ui/src/components/chat/ServersToggleModal.tsx @@ -1,15 +1,14 @@ -import React, { useRef, useState, useEffect } from "react" -import { useClickAway, useWindowSize } from "react-use" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import ServersToggleList from "@/components/mcp/configuration/tabs/installed/ServersToggleList" - -import { McpServiceClient } from "@/services/grpc-client" -import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" -import Tooltip from "@/components/common/Tooltip" +import { EmptyRequest } from "@shared/proto/cline/common" import { McpServers } from "@shared/proto/cline/mcp" import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" -import { EmptyRequest } from "@shared/proto/cline/common" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import React, { useEffect, useRef, useState } from "react" +import { useClickAway, useWindowSize } from "react-use" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import Tooltip from "@/components/common/Tooltip" +import ServersToggleList from "@/components/mcp/configuration/tabs/installed/ServersToggleList" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { McpServiceClient } from "@/services/grpc-client" const ServersToggleModal: React.FC = () => { const { mcpServers, navigateToMcp, setMcpServers } = useExtensionState() @@ -54,7 +53,7 @@ const ServersToggleModal: React.FC = () => { return (
    -
    +
    {
    - +
    )} diff --git a/webview-ui/src/components/chat/SlashCommandMenu.tsx b/webview-ui/src/components/chat/SlashCommandMenu.tsx index 5f366b8f..ad3ea77f 100644 --- a/webview-ui/src/components/chat/SlashCommandMenu.tsx +++ b/webview-ui/src/components/chat/SlashCommandMenu.tsx @@ -1,5 +1,5 @@ -import React, { useCallback, useRef, useEffect } from "react" -import { SlashCommand, getMatchingSlashCommands } from "@/utils/slash-commands" +import React, { useCallback, useEffect, useRef } from "react" +import { getMatchingSlashCommands, SlashCommand } from "@/utils/slash-commands" interface SlashCommandMenuProps { onSelect: (command: SlashCommand) => void @@ -52,7 +52,9 @@ const SlashCommandMenu: React.FC = ({ // Create a reusable function for rendering a command section const renderCommandSection = (commands: SlashCommand[], title: string, indexOffset: number, showDescriptions: boolean) => { - if (commands.length === 0) return null + if (commands.length === 0) { + return null + } return ( <> @@ -63,13 +65,13 @@ const SlashCommandMenu: React.FC = ({ const itemIndex = index + indexOffset return (
    handleClick(command)} onMouseEnter={() => setSelectedIndex(itemIndex)}>
    @@ -92,8 +94,8 @@ const SlashCommandMenu: React.FC = ({ className="absolute bottom-[calc(100%-10px)] left-[15px] right-[15px] overflow-x-hidden z-[1000]" onMouseDown={onMouseDown}>
    {filteredCommands.length > 0 ? ( <> diff --git a/webview-ui/src/components/chat/TaskFeedbackButtons.tsx b/webview-ui/src/components/chat/TaskFeedbackButtons.tsx index bb17775b..91e3df33 100644 --- a/webview-ui/src/components/chat/TaskFeedbackButtons.tsx +++ b/webview-ui/src/components/chat/TaskFeedbackButtons.tsx @@ -1,9 +1,9 @@ -import { TaskServiceClient } from "@/services/grpc-client" -import { TaskFeedbackType } from "@shared/WebviewMessage" import { StringRequest } from "@shared/proto/cline/common" +import { TaskFeedbackType } from "@shared/WebviewMessage" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import React, { useEffect, useState } from "react" import styled from "styled-components" +import { TaskServiceClient } from "@/services/grpc-client" interface TaskFeedbackButtonsProps { messageTs: number @@ -43,7 +43,9 @@ const TaskFeedbackButtons: React.FC = ({ messageTs, is } const handleFeedback = async (type: TaskFeedbackType) => { - if (feedback !== null) return // Already provided feedback + if (feedback !== null) { + return // Already provided feedback + } setFeedback(type) @@ -74,10 +76,10 @@ const TaskFeedbackButtons: React.FC = ({ messageTs, is handleFeedback("thumbs_up")} + aria-label="This was helpful" disabled={feedback !== null} - title="This was helpful" - aria-label="This was helpful"> + onClick={() => handleFeedback("thumbs_up")} + title="This was helpful"> = ({ messageTs, is handleFeedback("thumbs_down")} + aria-label="This wasn't helpful" disabled={feedback !== null && feedback !== "thumbs_down"} - title="This wasn't helpful" - aria-label="This wasn't helpful"> + onClick={() => handleFeedback("thumbs_down")} + title="This wasn't helpful"> = ({ text, images, files, messageT return (
    = ({ text, images, files, messageT padding: "9px", whiteSpace: "pre-line", wordWrap: "break-word", - }} - onClick={handleClick}> + }}> {isEditing ? ( <> setEditedText(e.target.value)} - onBlur={(e) => handleBlur(e)} - onKeyDown={handleKeyDown} autoFocus + onBlur={(e) => handleBlur(e)} + onChange={(e) => setEditedText(e.target.value)} + onKeyDown={handleKeyDown} + ref={textAreaRef} style={{ width: "100%", backgroundColor: "var(--vscode-input-background)", @@ -122,25 +121,26 @@ const UserMessage: React.FC = ({ text, images, files, messageT overflowY: "scroll", scrollbarWidth: "none", }} + value={editedText} />
    {!checkpointTrackerErrorMessage && ( )}
    @@ -150,7 +150,7 @@ const UserMessage: React.FC = ({ text, images, files, messageT )} {((images && images.length > 0) || (files && files.length > 0)) && ( - + )}
    ) @@ -173,9 +173,8 @@ const RestoreButton = forwardRef(({ type, return ( ) diff --git a/webview-ui/src/components/chat/__tests__/Announcement.spec.tsx b/webview-ui/src/components/chat/__tests__/Announcement.spec.tsx index d234c197..c879d297 100644 --- a/webview-ui/src/components/chat/__tests__/Announcement.spec.tsx +++ b/webview-ui/src/components/chat/__tests__/Announcement.spec.tsx @@ -1,7 +1,7 @@ -import React from "react" +import { fireEvent, render, screen } from "@testing-library/react" import type { ComponentProps } from "react" -import { render, screen, fireEvent } from "@testing-library/react" -import { describe, it, expect, vi } from "vitest" +import React from "react" +import { describe, expect, it, vi } from "vitest" import Announcement from "../Announcement" vi.mock("@vscode/webview-ui-toolkit/react", () => ({ @@ -14,12 +14,12 @@ describe("Announcement", () => { const hideAnnouncement = vi.fn() it("renders the announcement with the correct version", () => { - render() + render() expect(screen.getByText(/New in v2.0/)).toBeInTheDocument() }) it("calls hideAnnouncement when close button is clicked", () => { - render() + render() fireEvent.click(screen.getByTestId("close-button")) expect(hideAnnouncement).toHaveBeenCalled() }) diff --git a/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx b/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx index 27e45688..688309d3 100644 --- a/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx +++ b/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest" +import { describe, expect, it } from "vitest" import { ErrorBlockTitle } from "../ErrorBlockTitle" describe("ErrorBlockTitle", () => { diff --git a/webview-ui/src/components/chat/__tests__/UserMessage.ime.test.tsx b/webview-ui/src/components/chat/__tests__/UserMessage.ime.test.tsx index 091a9a8a..e92792dd 100644 --- a/webview-ui/src/components/chat/__tests__/UserMessage.ime.test.tsx +++ b/webview-ui/src/components/chat/__tests__/UserMessage.ime.test.tsx @@ -5,9 +5,8 @@ * even if you confirm the IME conversion (Enter) in message re-edit mode. */ -import React from "react" -import { render, fireEvent } from "@testing-library/react" -import { describe, it, expect, vi } from "vitest" +import { fireEvent, render } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" vi.mock("@/context/ExtensionStateContext", () => ({ __esModule: true, @@ -24,7 +23,7 @@ describe("UserMessage – IME composition handling", () => { const sendMessageFromChatRow = vi.fn() const { getByText } = render( - , + , ) const editable = getByText("変換テスト") as HTMLElement diff --git a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveBar.tsx b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveBar.tsx index efe70d1a..6f546eee 100644 --- a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveBar.tsx +++ b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveBar.tsx @@ -1,7 +1,7 @@ -import { useRef, useState, useMemo } from "react" +import { useMemo, useRef, useState } from "react" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import { useExtensionState } from "@/context/ExtensionStateContext" import { useAutoApproveActions } from "@/hooks/useAutoApproveActions" -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import { getAsVar, VSC_TITLEBAR_INACTIVE_FOREGROUND } from "@/utils/vscStyles" import AutoApproveMenuItem from "./AutoApproveMenuItem" import AutoApproveModal from "./AutoApproveModal" @@ -24,15 +24,17 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => { const renderFavoritedItem = (favId: string) => { const actions = [...ACTION_METADATA.flatMap((a) => [a, a.subAction]), NOTIFICATIONS_SETTING] const action = actions.find((a) => a?.id === favId) - if (!action) return null + if (!action) { + return null + } return ( ) @@ -47,7 +49,7 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => { return ACTION_METADATA.flatMap((a) => [a, a.subAction]).find((a) => a?.id === action) }) - let minusFavorites = enabledActions.filter((action) => !favorites.includes(action?.id ?? "") && action?.shortName) + const minusFavorites = enabledActions.filter((action) => !favorites.includes(action?.id ?? "") && action?.shortName) if (notificationsEnabled) { minusFavorites.push(NOTIFICATIONS_SETTING) @@ -79,11 +81,11 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => { ...style, }}>
    { setIsModalVisible((prev) => !prev) - }}> + }} + ref={buttonRef}>
    {
    ) diff --git a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenuItem.tsx b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenuItem.tsx index 62e0d9b5..3d2b1b18 100644 --- a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenuItem.tsx +++ b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenuItem.tsx @@ -1,8 +1,8 @@ +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import React from "react" import styled from "styled-components" import HeroTooltip from "@/components/common/HeroTooltip" import { ActionMetadata } from "./types" -import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" interface AutoApproveMenuItemProps { action: ActionMetadata @@ -94,18 +94,20 @@ const AutoApproveMenuItem = ({
    {onToggleFavorite && !condensed && ( + content={favorited ? "Remove from quick-access menu" : "Add to quick-access menu"} + delay={500}> { e.stopPropagation() - if (action.id === "enableAll") return + if (action.id === "enableAll") { + return + } await onToggleFavorite?.(action.id) }} + style={{ + cursor: "pointer", + }} /> )} diff --git a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveModal.tsx b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveModal.tsx index 91926a98..a1186bd9 100644 --- a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveModal.tsx +++ b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveModal.tsx @@ -1,11 +1,11 @@ -import React, { useRef, useState, useEffect } from "react" +import { VSCodeButton, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import React, { useEffect, useRef, useState } from "react" import { useClickAway, useWindowSize } from "react-use" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import HeroTooltip from "@/components/common/HeroTooltip" import { useExtensionState } from "@/context/ExtensionStateContext" import { useAutoApproveActions } from "@/hooks/useAutoApproveActions" -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import { VSCodeTextField, VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { getAsVar, VSC_TITLEBAR_INACTIVE_FOREGROUND } from "@/utils/vscStyles" -import HeroTooltip from "@/components/common/HeroTooltip" import AutoApproveMenuItem from "./AutoApproveMenuItem" import { ActionMetadata } from "./types" @@ -58,7 +58,9 @@ const AutoApproveModal: React.FC = ({ // Track container width for responsive layout useEffect(() => { - if (!isVisible) return + if (!isVisible) { + return + } const updateWidth = () => { if (itemsContainerRef.current) { @@ -81,7 +83,9 @@ const AutoApproveModal: React.FC = ({ } }, [isVisible]) - if (!isVisible) return null + if (!isVisible) { + return null + } return (
    @@ -118,8 +122,8 @@ const AutoApproveModal: React.FC = ({
    breakpoint ? 2 : 1, columnGap: "4px", @@ -138,10 +142,10 @@ const AutoApproveModal: React.FC = ({ {/* All items in a single list - CSS Grid will handle the column distribution */} {ACTION_METADATA.map((action) => ( @@ -153,10 +157,10 @@ const AutoApproveModal: React.FC = ({
    @@ -169,13 +173,12 @@ const AutoApproveModal: React.FC = ({ Max Requests: { const input = e.target as HTMLInputElement // Remove any non-numeric characters input.value = input.value.replace(/[^0-9]/g, "") const value = parseInt(input.value) - if (!isNaN(value) && value > 0) { + if (!Number.isNaN(value) && value > 0) { await updateMaxRequests(value) } }} @@ -185,6 +188,7 @@ const AutoApproveModal: React.FC = ({ e.preventDefault() } }} + value={autoApprovalSettings.maxRequests.toString()} />
    diff --git a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveSettingsAPI.ts b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveSettingsAPI.ts index 06f256af..fb1c93bc 100644 --- a/webview-ui/src/components/chat/auto-approve-menu/AutoApproveSettingsAPI.ts +++ b/webview-ui/src/components/chat/auto-approve-menu/AutoApproveSettingsAPI.ts @@ -1,6 +1,6 @@ -import { StateServiceClient } from "@/services/grpc-client" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { convertAutoApprovalSettingsToProto } from "@shared/proto-conversions/models/auto-approval-settings-conversion" +import { StateServiceClient } from "@/services/grpc-client" /** * Updates auto approval settings using the gRPC/Protobus client 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 index c68de63c..decf57f9 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx @@ -88,6 +88,7 @@ export const ActionButtons: React.FC = ({
    { @@ -95,8 +96,7 @@ export const ActionButtons: React.FC = ({ e.preventDefault() handleScrollToBottom() } - }} - aria-label="Scroll to bottom"> + }}>
    @@ -111,8 +111,8 @@ export const ActionButtons: React.FC = ({ {primaryButtonText && ( { if (primaryButtonText === "Start New Task") { messageHandlers.startNewTask() @@ -126,8 +126,8 @@ export const ActionButtons: React.FC = ({ {secondaryButtonText && ( { messageHandlers.handleButtonClick(secondaryButtonText, inputValue, selectedImages, selectedFiles) }}> 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 index d89bcbe8..f3e5cc4d 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/InputSection.tsx @@ -1,6 +1,6 @@ import React from "react" -import QuotedMessagePreview from "@/components/chat/QuotedMessagePreview" import ChatTextArea from "@/components/chat/ChatTextArea" +import QuotedMessagePreview from "@/components/chat/QuotedMessagePreview" import { ChatState, MessageHandlers, ScrollBehavior } from "../../types/chatTypes" interface InputSectionProps { @@ -45,33 +45,33 @@ export const InputSection: React.FC = ({ {activeQuote && (
    setActiveQuote(null)} isFocused={isTextAreaFocused} + onDismiss={() => setActiveQuote(null)} + text={activeQuote} />
    )} messageHandlers.handleSendMessage(inputValue, selectedImages, selectedFiles)} - onSelectFilesAndImages={selectFilesAndImages} - shouldDisableFilesAndImages={shouldDisableFilesAndImages} + onFocusChange={handleFocusChange} onHeightChange={() => { if (isAtBottom) { scrollToBottomAuto() } }} + onSelectFilesAndImages={selectFilesAndImages} + onSend={() => messageHandlers.handleSendMessage(inputValue, selectedImages, selectedFiles)} + placeholderText={placeholderText} + ref={textAreaRef} + selectedFiles={selectedFiles} + selectedImages={selectedImages} + sendingDisabled={sendingDisabled} + setInputValue={setInputValue} + setSelectedFiles={setSelectedFiles} + setSelectedImages={setSelectedImages} + shouldDisableFilesAndImages={shouldDisableFilesAndImages} /> ) 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 bfff9706..7bf22c21 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 @@ -1,8 +1,7 @@ +import { ClineMessage } from "@shared/ExtensionMessage" 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 { ChatState, MessageHandlers, ScrollBehavior } from "../../types/chatTypes" import { createMessageRenderer } from "../messages/MessageRenderer" interface MessagesAreaProps { @@ -65,23 +64,6 @@ export const MessagesArea: React.FC = ({
    , // 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) { @@ -89,8 +71,25 @@ export const MessagesArea: React.FC = ({ } setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom) }} - atBottomThreshold={10} // anything lower causes issues with followOutput - initialTopMostItemIndex={groupedMessages.length - 1} + atBottomThreshold={10} // trick to make sure virtuoso re-renders when task changes, and we use initialTopMostItemIndex to start at the bottom + className="scrollable" + components={{ + Footer: () =>
    , // Add empty padding at the bottom + }} + data={groupedMessages} + // 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) + initialTopMostItemIndex={groupedMessages.length - 1} // 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} + key={task.ts} + ref={virtuosoRef} // anything lower causes issues with followOutput + style={{ + flexGrow: 1, + overflowY: "scroll", // always show scrollbar + }} />
    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 index def0a395..29af16c9 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/TaskSection.tsx @@ -1,6 +1,6 @@ +import { ClineMessage } from "@shared/ExtensionMessage" 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 { @@ -37,17 +37,17 @@ export const TaskSection: React.FC = ({ }) => { 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 index 4a64eabe..8cf6e9c1 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/WelcomeSection.tsx @@ -1,10 +1,9 @@ import React from "react" -import TelemetryBanner from "@/components/common/TelemetryBanner" import Announcement from "@/components/chat/Announcement" -import HomeHeader from "@/components/welcome/HomeHeader" +import TelemetryBanner from "@/components/common/TelemetryBanner" import HistoryPreview from "@/components/history/HistoryPreview" +import HomeHeader from "@/components/welcome/HomeHeader" import { SuggestedTasks } from "@/components/welcome/SuggestedTasks" -import AutoApproveBar from "@/components/chat/auto-approve-menu/AutoApproveBar" import { WelcomeSectionProps } from "../../types/chatTypes" /** @@ -24,7 +23,7 @@ export const WelcomeSection: React.FC = ({
    {telemetrySetting === "unset" && } - {showAnnouncement && } + {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 index f9404b54..e1fa1755 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/index.ts +++ b/webview-ui/src/components/chat/chat-view/components/layout/index.ts @@ -2,9 +2,9 @@ * 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 { ChatLayout } from "./ChatLayout" export { InputSection } from "./InputSection" +export { MessagesArea } from "./MessagesArea" +export { TaskSection } from "./TaskSection" +export { WelcomeSection } from "./WelcomeSection" 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 index a4fc393f..68e5b3db 100644 --- a/webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx +++ b/webview-ui/src/components/chat/chat-view/components/messages/MessageRenderer.tsx @@ -1,7 +1,7 @@ -import React, { useCallback } from "react" +import { ClineMessage } from "@shared/ExtensionMessage" +import React 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 { @@ -37,14 +37,14 @@ export const MessageRenderer: React.FC = ({ if (Array.isArray(messageOrGroup)) { return ( ) } @@ -58,16 +58,16 @@ export const MessageRenderer: React.FC = ({ // Regular message return ( ) } @@ -88,16 +88,16 @@ export const createMessageRenderer = ( ) => { return (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => ( ) } diff --git a/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts b/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts index d5f7cc4e..51a1ba56 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useChatState.ts @@ -1,6 +1,6 @@ -import { useState, useMemo, useRef, useCallback } from "react" -import { ClineMessage, ClineAsk } from "@shared/ExtensionMessage" -import { ChatState, MessageHandlers } from "../types/chatTypes" +import { ClineMessage } from "@shared/ExtensionMessage" +import { useCallback, useMemo, useRef, useState } from "react" +import { ChatState } from "../types/chatTypes" /** * Custom hook for managing chat state 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 76d2b938..954b1243 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useScrollBehavior.ts @@ -1,8 +1,8 @@ -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 debounce from "debounce" +import { useCallback, useEffect, useMemo, useRef, useState } from "react" +import { useEvent } from "react-use" +import { VirtuosoHandle } from "react-virtuoso" import { ScrollBehavior } from "../types/chatTypes" /** diff --git a/webview-ui/src/components/chat/chat-view/index.ts b/webview-ui/src/components/chat/chat-view/index.ts index 8c35d10d..4813d36a 100644 --- a/webview-ui/src/components/chat/chat-view/index.ts +++ b/webview-ui/src/components/chat/chat-view/index.ts @@ -2,20 +2,17 @@ * Barrel export for chat-view utilities, hooks, components, and types */ +// Export layout components +export * from "./components/layout" +// Export message components +export * from "./components/messages" +export * from "./constants" + +// Export hooks +export * from "./hooks" +// Export types and constants +export * from "./types/chatTypes" // 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 index e54567ff..5b491bd2 100644 --- a/webview-ui/src/components/chat/chat-view/types/chatTypes.ts +++ b/webview-ui/src/components/chat/chat-view/types/chatTypes.ts @@ -2,7 +2,7 @@ * Shared types and interfaces for the chat view components */ -import { ClineMessage, ClineAsk } from "@shared/ExtensionMessage" +import { ClineAsk, ClineMessage } from "@shared/ExtensionMessage" import { VirtuosoHandle } from "react-virtuoso" /** diff --git a/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts b/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts index fcd079f6..53cc348a 100644 --- a/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts +++ b/webview-ui/src/components/chat/chat-view/utils/markdownUtils.ts @@ -2,10 +2,10 @@ * 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" +import rehypeRemark from "rehype-remark" +import remarkStringify from "remark-stringify" +import { unified } from "unified" /** * Clean up markdown escape characters 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 f5dec410..726867e2 100644 --- a/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts +++ b/webview-ui/src/components/chat/chat-view/utils/messageUtils.ts @@ -2,9 +2,9 @@ * Utility functions for message filtering, grouping, and manipulation */ -import { ClineMessage, ClineSayBrowserAction } from "@shared/ExtensionMessage" import { combineApiRequests } from "@shared/combineApiRequests" import { combineCommandSequences } from "@shared/combineCommandSequences" +import { ClineMessage, ClineSayBrowserAction } from "@shared/ExtensionMessage" /** * Combine API requests and command sequences in messages diff --git a/webview-ui/src/components/chat/task-header/TaskHeader.tsx b/webview-ui/src/components/chat/task-header/TaskHeader.tsx index b9b899b6..239088c7 100644 --- a/webview-ui/src/components/chat/task-header/TaskHeader.tsx +++ b/webview-ui/src/components/chat/task-header/TaskHeader.tsx @@ -1,7 +1,7 @@ import { mentionRegexGlobal } from "@shared/context-mentions" import { ClineMessage } from "@shared/ExtensionMessage" import { FOCUS_CHAIN_ITEM_REGEX, isCompletedFocusChainItem, isFocusChainItem } from "@shared/focus-chain-utils" -import { StringArrayRequest, StringRequest } from "@shared/proto/cline/common" +import { StringRequest } from "@shared/proto/cline/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import React, { memo, useEffect, useMemo, useRef, useState } from "react" import { useWindowSize } from "react-use" @@ -10,7 +10,7 @@ import HeroTooltip from "@/components/common/HeroTooltip" import Thumbnails from "@/components/common/Thumbnails" import { getModeSpecificFields, normalizeApiConfiguration } from "@/components/settings/utils/providerUtils" import { useExtensionState } from "@/context/ExtensionStateContext" -import { FileServiceClient, TaskServiceClient, UiServiceClient } from "@/services/grpc-client" +import { FileServiceClient, UiServiceClient } from "@/services/grpc-client" import { formatLargeNumber, formatSize } from "@/utils/format" import { validateSlashCommand } from "@/utils/slash-commands" import CopyTaskButton from "./buttons/CopyTaskButton" @@ -22,7 +22,9 @@ const IS_DEV = process.env.IS_DEV // Utility function to parse checklist and extract current todo info const parseCurrentTodoInfo = (text: string) => { - if (!text) return null + if (!text) { + return null + } const lines = text.split("\n") const todoItems: { text: string; completed: boolean; index: number }[] = [] @@ -36,7 +38,9 @@ const parseCurrentTodoInfo = (text: string) => { } }) - if (todoItems.length === 0) return null + if (todoItems.length === 0) { + return null + } const currentTodoIndex = todoItems.findIndex((item) => !item.completed) const currentTodo = currentTodoIndex >= 0 ? todoItems[currentTodoIndex] : null @@ -531,7 +535,9 @@ const TaskHeader: React.FC = ({ {(() => { const todoInfo = parseCurrentTodoInfo(lastProgressMessageText || "") - if (!todoInfo?.hasItems) return null + if (!todoInfo?.hasItems) { + return null + } if (todoInfo.completedCount === todoInfo.totalCount) { return ( @@ -757,27 +763,25 @@ const TaskHeader: React.FC = ({ {checkpointTrackerErrorMessage.replace(/disabling checkpoints\.$/, "")} {checkpointTrackerErrorMessage.endsWith("disabling checkpoints.") && ( - <> - - + // After a short delay, send a message to scroll to settings + setTimeout(async () => { + try { + await UiServiceClient.scrollToSettings( + StringRequest.create({ value: "features" }), + ) + } catch (error) { + console.error("Error scrolling to checkpoint settings:", error) + } + }, 300) + }}> + disabling checkpoints. + )} {checkpointTrackerErrorMessage.includes("Git must be installed to use checkpoints.") && ( <> diff --git a/webview-ui/src/components/chat/task-header/TaskTimeline.tsx b/webview-ui/src/components/chat/task-header/TaskTimeline.tsx index e5b15afd..983681ab 100644 --- a/webview-ui/src/components/chat/task-header/TaskTimeline.tsx +++ b/webview-ui/src/components/chat/task-header/TaskTimeline.tsx @@ -1,9 +1,9 @@ import { combineApiRequests } from "@shared/combineApiRequests" import { combineCommandSequences } from "@shared/combineCommandSequences" import { ClineMessage } from "@shared/ExtensionMessage" -import React, { useCallback, useEffect, useMemo, useRef, useState } from "react" +import React, { useCallback, useEffect, useMemo, useRef } from "react" import { Virtuoso } from "react-virtuoso" -import { COLOR_BEIGE, COLOR_BLUE, COLOR_DARK_GRAY, COLOR_GRAY, COLOR_GREEN, COLOR_PURPLE, COLOR_WHITE } from "../colors" +import { COLOR_GRAY } from "../colors" import TaskTimelineTooltip from "./TaskTimelineTooltip" import { getColor } from "./util" @@ -11,7 +11,7 @@ import { getColor } from "./util" const TIMELINE_HEIGHT = "13px" const BLOCK_WIDTH = "13px" const BLOCK_GAP = "3px" -const TOOLTIP_MARGIN = 32 // 32px margin on each side +const _TOOLTIP_MARGIN = 32 // 32px margin on each side interface TaskTimelineProps { messages: ClineMessage[] @@ -23,12 +23,14 @@ const TaskTimeline: React.FC = ({ messages, onBlockClick }) = const scrollableRef = useRef(null) const { taskTimelinePropsMessages, messageIndexMap } = useMemo(() => { - if (messages.length <= 1) return { taskTimelinePropsMessages: [], messageIndexMap: [] } + if (messages.length <= 1) { + return { taskTimelinePropsMessages: [], messageIndexMap: [] } + } const processed = combineApiRequests(combineCommandSequences(messages.slice(1))) const indexMap: number[] = [] - const filtered = processed.filter((msg, processedIndex) => { + const filtered = processed.filter((msg, _processedIndex) => { const originalIndex = messages.findIndex((originalMsg, idx) => idx > 0 && originalMsg.ts === msg.ts) // Filter out standard "say" events we don't want to show diff --git a/webview-ui/src/components/chat/task-header/TaskTimelineTooltip.tsx b/webview-ui/src/components/chat/task-header/TaskTimelineTooltip.tsx index 4a0a7026..aa45211d 100644 --- a/webview-ui/src/components/chat/task-header/TaskTimelineTooltip.tsx +++ b/webview-ui/src/components/chat/task-header/TaskTimelineTooltip.tsx @@ -1,6 +1,6 @@ -import React from "react" -import { ClineMessage } from "@shared/ExtensionMessage" import { Tooltip } from "@heroui/react" +import { ClineMessage } from "@shared/ExtensionMessage" +import React from "react" import { getColor } from "./util" interface TaskTimelineTooltipProps { @@ -39,7 +39,7 @@ const TaskTimelineTooltip = ({ message, children }: TaskTimelineTooltipProps) => return `Web Fetch: ${toolData.path || "Unknown URL"}` } return `Tool: ${toolData.tool}` - } catch (e) { + } catch (_e) { return "Tool Use" } } @@ -85,7 +85,7 @@ const TaskTimelineTooltip = ({ message, children }: TaskTimelineTooltipProps) => return `Web Fetch: ${toolData.path || "Unknown URL"}` } return `Tool Approval: ${toolData.tool}` - } catch (e) { + } catch (_e) { return "Tool Approval" } } @@ -107,14 +107,14 @@ const TaskTimelineTooltip = ({ message, children }: TaskTimelineTooltipProps) => try { const planData = JSON.parse(message.text) return planData.response || message.text - } catch (e) { + } catch (_e) { return message.text } } else if (message.type === "say" && message.say === "tool" && message.text) { try { const toolData = JSON.parse(message.text) return JSON.stringify(toolData, null, 2) - } catch (e) { + } catch (_e) { return message.text } } @@ -153,6 +153,10 @@ const TaskTimelineTooltip = ({ message, children }: TaskTimelineTooltipProps) => return (
    @@ -197,14 +201,10 @@ const TaskTimelineTooltip = ({ message, children }: TaskTimelineTooltipProps) => )}
    } - classNames={{ - base: "bg-[var(--vscode-editor-background)] text-[var(--vscode-editor-foreground)] border-[var(--vscode-widget-border)] py-1 rounded-[3px] max-w-[calc(100dvw-2rem)] text-xs", - }} - shadow="sm" - placement="bottom" disableAnimation - closeDelay={100} - isKeyboardDismissDisabled={true}> + isKeyboardDismissDisabled={true} + placement="bottom" + shadow="sm"> {children}
    ) diff --git a/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx b/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx index 2c89e8e8..015adb5e 100644 --- a/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/CopyTaskButton.tsx @@ -1,6 +1,6 @@ -import HeroTooltip from "@/components/common/HeroTooltip" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useState } from "react" +import HeroTooltip from "@/components/common/HeroTooltip" const CopyTaskButton: React.FC<{ taskText?: string @@ -8,7 +8,9 @@ const CopyTaskButton: React.FC<{ const [copied, setCopied] = useState(false) const handleCopy = () => { - if (!taskText) return + if (!taskText) { + return + } navigator.clipboard.writeText(taskText).then(() => { setCopied(true) @@ -20,10 +22,10 @@ const CopyTaskButton: React.FC<{ + onClick={handleCopy} + style={{ padding: "0px 0px" }}>
    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 d165a0a5..8230258b 100644 --- a/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx +++ b/webview-ui/src/components/chat/task-header/buttons/DeleteTaskButton.tsx @@ -1,7 +1,7 @@ -import HeroTooltip from "@/components/common/HeroTooltip" -import { TaskServiceClient } from "@/services/grpc-client" import { StringArrayRequest } from "@shared/proto/cline/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import HeroTooltip from "@/components/common/HeroTooltip" +import { TaskServiceClient } from "@/services/grpc-client" const DeleteTaskButton: React.FC<{ taskSize: string @@ -10,8 +10,8 @@ const DeleteTaskButton: React.FC<{ taskId && TaskServiceClient.deleteTasksWithIds(StringArrayRequest.create({ value: [taskId] }))} aria-label="Delete task" + onClick={() => taskId && TaskServiceClient.deleteTasksWithIds(StringArrayRequest.create({ value: [taskId] }))} style={{ padding: "0px 0px" }}>
    = ({ taskId }) => { const handleOpenDiskTaskHistory = () => { - if (!taskId) return + if (!taskId) { + return + } FileServiceClient.openTaskHistory(StringRequest.create({ value: taskId })).catch((err) => { console.error(err) @@ -18,10 +20,10 @@ const OpenDiskTaskHistoryButton: React.FC<{ + onClick={handleOpenDiskTaskHistory} + style={{ padding: "0px 0px" }}>
    diff --git a/webview-ui/src/components/chat/task-header/util.ts b/webview-ui/src/components/chat/task-header/util.ts index 8ac1db20..45e2fe58 100644 --- a/webview-ui/src/components/chat/task-header/util.ts +++ b/webview-ui/src/components/chat/task-header/util.ts @@ -1,5 +1,5 @@ import { ClineMessage } from "@shared/ExtensionMessage" -import { COLOR_WHITE, COLOR_GRAY, COLOR_DARK_GRAY, COLOR_BEIGE, COLOR_BLUE, COLOR_PURPLE, COLOR_GREEN } from "../colors" +import { COLOR_BEIGE, COLOR_BLUE, COLOR_DARK_GRAY, COLOR_GRAY, COLOR_GREEN, COLOR_PURPLE, COLOR_WHITE } from "../colors" /** * @@ -34,7 +34,7 @@ export const getColor = (message: ClineMessage): string => { } else if (toolData.tool === "webFetch") { return COLOR_PURPLE // Purple for web fetch operations } - } catch (e) { + } catch (_e) { // JSON parse error here } } @@ -74,7 +74,7 @@ export const getColor = (message: ClineMessage): string => { } else if (toolData.tool === "webFetch") { return COLOR_PURPLE // Purple for web fetch operations } - } catch (e) { + } catch (_e) { // JSON parse error here } } diff --git a/webview-ui/src/components/cline-rules/ClineRulesToggleModal.tsx b/webview-ui/src/components/cline-rules/ClineRulesToggleModal.tsx index e713c1b5..e6236c47 100644 --- a/webview-ui/src/components/cline-rules/ClineRulesToggleModal.tsx +++ b/webview-ui/src/components/cline-rules/ClineRulesToggleModal.tsx @@ -1,8 +1,3 @@ -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import Tooltip from "@/components/common/Tooltip" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { FileServiceClient } from "@/services/grpc-client" -import { vscode } from "@/utils/vscode" import { EmptyRequest } from "@shared/proto/cline/common" import { ClineRulesToggles, @@ -16,6 +11,10 @@ import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import React, { useEffect, useRef, useState } from "react" import { useClickAway, useWindowSize } from "react-use" import styled from "styled-components" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import Tooltip from "@/components/common/Tooltip" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { FileServiceClient } from "@/services/grpc-client" import RulesToggleList from "./RulesToggleList" const ClineRulesToggleModal: React.FC = () => { @@ -196,7 +195,7 @@ const ClineRulesToggleModal: React.FC = () => { return (
    -
    +
    { Rules allow you to provide Cline with system-level guidance. Think of them as a persistent way to include context and preferences for your projects or globally for every conversation.{" "} + style={{ display: "inline" }}> Docs

    @@ -277,9 +276,9 @@ const ClineRulesToggleModal: React.FC = () => { {" "} in the chat.{" "} + style={{ display: "inline" }}> Docs

    @@ -292,13 +291,13 @@ const ClineRulesToggleModal: React.FC = () => {
    Global Rules
    toggleRule(true, rulePath, enabled)} - listGap="small" isGlobal={true} + listGap="small" + rules={globalRules} ruleType={"cline"} showNewRule={true} showNoRules={false} + toggleRule={(rulePath, enabled) => toggleRule(true, rulePath, enabled)} />
    @@ -306,31 +305,31 @@ const ClineRulesToggleModal: React.FC = () => {
    Workspace Rules
    toggleRule(false, rulePath, enabled)} - listGap="small" isGlobal={false} + listGap="small" + rules={localRules} ruleType={"cline"} showNewRule={false} showNoRules={false} + toggleRule={(rulePath, enabled) => toggleRule(false, rulePath, enabled)} />
    @@ -340,13 +339,13 @@ const ClineRulesToggleModal: React.FC = () => {
    Global Workflows
    toggleWorkflow(true, rulePath, enabled)} - listGap="small" isGlobal={true} + listGap="small" + rules={globalWorkflows} ruleType={"workflow"} showNewRule={true} showNoRules={false} + toggleRule={(rulePath, enabled) => toggleWorkflow(true, rulePath, enabled)} />
    @@ -354,13 +353,13 @@ const ClineRulesToggleModal: React.FC = () => {
    Workspace Workflows
    toggleWorkflow(false, rulePath, enabled)} - listGap="small" isGlobal={false} + listGap="small" + rules={localWorkflows} ruleType={"workflow"} showNewRule={true} showNoRules={false} + toggleRule={(rulePath, enabled) => toggleWorkflow(false, rulePath, enabled)} />
    diff --git a/webview-ui/src/components/cline-rules/NewRuleRow.tsx b/webview-ui/src/components/cline-rules/NewRuleRow.tsx index bcbce9cf..894c4d3f 100644 --- a/webview-ui/src/components/cline-rules/NewRuleRow.tsx +++ b/webview-ui/src/components/cline-rules/NewRuleRow.tsx @@ -1,9 +1,8 @@ -import { useState, useRef, useEffect } from "react" -import { vscode } from "@/utils/vscode" +import { CreateRuleFileRequest } from "@shared/proto-conversions/file/rule-files-conversion" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import { useEffect, useRef, useState } from "react" import { useClickAway } from "react-use" import { FileServiceClient } from "@/services/grpc-client" -import { CreateRuleFileRequest } from "@shared/proto-conversions/file/rule-files-conversion" interface NewRuleRowProps { isGlobal: boolean @@ -34,7 +33,9 @@ const NewRuleRow: React.FC = ({ isGlobal, ruleType }) => { }) const getExtension = (filename: string): string => { - if (filename.startsWith(".") && !filename.includes(".", 1)) return "" + if (filename.startsWith(".") && !filename.includes(".", 1)) { + return "" + } const match = filename.match(/\.[^.]+$/) return match ? match[0].toLowerCase() : "" } @@ -87,39 +88,39 @@ const NewRuleRow: React.FC = ({ isGlobal, ruleType }) => { return (
    !isExpanded && setIsExpanded(true)}> + onClick={() => !isExpanded && setIsExpanded(true)} + ref={componentRef}>
    {isExpanded ? ( -
    + setFilename(e.target.value)} + onKeyDown={handleKeyDown} placeholder={ ruleType === "workflow" ? "workflow-name (.md, .txt, or no extension)" : "rule-name (.md, .txt, or no extension)" } - value={filename} - onChange={(e) => setFilename(e.target.value)} - onKeyDown={handleKeyDown} - className="flex-1 bg-[var(--vscode-input-background)] text-[var(--vscode-input-foreground)] border-0 outline-0 rounded focus:outline-none focus:ring-0 focus:border-transparent" + ref={inputRef} style={{ outline: "none", }} + type="text" + value={filename} />
    + type="submit">
    @@ -133,12 +134,12 @@ const NewRuleRow: React.FC = ({ isGlobal, ruleType }) => { { e.stopPropagation() setIsExpanded(true) }} - style={{ padding: "0px" }}> + style={{ padding: "0px" }} + title="New rule file">
    diff --git a/webview-ui/src/components/cline-rules/RuleRow.tsx b/webview-ui/src/components/cline-rules/RuleRow.tsx index 626b4230..5df032fb 100644 --- a/webview-ui/src/components/cline-rules/RuleRow.tsx +++ b/webview-ui/src/components/cline-rules/RuleRow.tsx @@ -1,7 +1,7 @@ -import { FileServiceClient } from "@/services/grpc-client" -import { DeleteRuleFileRequest } from "@shared/proto-conversions/file/rule-files-conversion" import { StringRequest } from "@shared/proto/cline/common" +import { DeleteRuleFileRequest } from "@shared/proto-conversions/file/rule-files-conversion" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import { FileServiceClient } from "@/services/grpc-client" const RuleRow: React.FC<{ rulePath: string @@ -20,34 +20,34 @@ const RuleRow: React.FC<{ case "cursor": return ( + width="16" + xmlns="http://www.w3.org/2000/svg"> - - - + + + ) case "windsurf": return ( + width="16" + xmlns="http://www.w3.org/2000/svg"> - + - + ) @@ -86,9 +86,7 @@ const RuleRow: React.FC<{ {/* Toggle Switch */}
    + }} + role="switch" + tabIndex={0}>
    + style={{ height: "20px" }} + title="Edit rule file"> + style={{ height: "20px" }} + title="Delete rule file">
    diff --git a/webview-ui/src/components/cline-rules/RulesToggleList.tsx b/webview-ui/src/components/cline-rules/RulesToggleList.tsx index 29cb4233..235491fc 100644 --- a/webview-ui/src/components/cline-rules/RulesToggleList.tsx +++ b/webview-ui/src/components/cline-rules/RulesToggleList.tsx @@ -32,12 +32,12 @@ const RulesToggleList = ({ <> {rules.map(([rulePath, enabled]) => ( ))} {showNewRule && } diff --git a/webview-ui/src/components/common/AlertDialog.tsx b/webview-ui/src/components/common/AlertDialog.tsx index 072f63b2..1eaa2cc0 100644 --- a/webview-ui/src/components/common/AlertDialog.tsx +++ b/webview-ui/src/components/common/AlertDialog.tsx @@ -1,6 +1,6 @@ -import React, { ReactNode } from "react" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { AlertTriangle } from "lucide-react" +import React, { ReactNode } from "react" import { OPENROUTER_MODEL_PICKER_Z_INDEX } from "../settings/OpenRouterModelPicker" interface AlertDialogProps { @@ -10,7 +10,9 @@ interface AlertDialogProps { } export function AlertDialog({ open, onOpenChange, children }: AlertDialogProps) { - if (!open) return null + if (!open) { + return null + } // Close the dialog when clicking on the backdrop const handleBackdropClick = (e: React.MouseEvent) => { @@ -95,7 +97,7 @@ export function UnsavedChangesDialog({ showSaveOption?: boolean }) { return ( - + @@ -107,7 +109,7 @@ export function UnsavedChangesDialog({ Cancel {showSaveOption && onSave && {saveText}} - + {confirmText} diff --git a/webview-ui/src/components/common/CheckmarkControl.tsx b/webview-ui/src/components/common/CheckmarkControl.tsx index 05628d4b..e407ce3d 100644 --- a/webview-ui/src/components/common/CheckmarkControl.tsx +++ b/webview-ui/src/components/common/CheckmarkControl.tsx @@ -1,5 +1,3 @@ -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import { CheckpointsServiceClient } from "@/services/grpc-client" import { flip, offset, shift, useFloating } from "@floating-ui/react" import { CheckpointRestoreRequest } from "@shared/proto/cline/checkpoints" import { Int64Request } from "@shared/proto/cline/common" @@ -8,7 +6,9 @@ import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useCallback, useEffect, useRef, useState } from "react" import { createPortal } from "react-dom" import styled from "styled-components" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import { useExtensionState } from "@/context/ExtensionStateContext" +import { CheckpointsServiceClient } from "@/services/grpc-client" interface CheckmarkControlProps { messageTs?: number @@ -161,8 +161,8 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar return ( { setCompareDisabled(true) try { @@ -195,10 +194,11 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar } finally { setCompareDisabled(false) } - }}> + }} + style={{ cursor: compareDisabled ? "wait" : "pointer" }}> Compare - +
    + onMouseLeave={handleMouseLeave} + ref={refs.setFloating} + style={floatingStyles}> - + ) diff --git a/webview-ui/src/components/common/CheckpointControls.tsx b/webview-ui/src/components/common/CheckpointControls.tsx index 8a1c5f59..95be5646 100644 --- a/webview-ui/src/components/common/CheckpointControls.tsx +++ b/webview-ui/src/components/common/CheckpointControls.tsx @@ -1,12 +1,12 @@ -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" -import { CheckpointsServiceClient } from "@/services/grpc-client" import { CheckpointRestoreRequest } from "@shared/proto/cline/checkpoints" import { Int64Request } from "@shared/proto/cline/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useEffect, useRef, useState } from "react" import { useClickAway } from "react-use" import styled from "styled-components" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import { useExtensionState } from "@/context/ExtensionStateContext" +import { CheckpointsServiceClient } from "@/services/grpc-client" interface CheckpointOverlayProps { messageTs?: number @@ -121,10 +121,8 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => { return ( { setCompareDisabled(true) try { @@ -138,23 +136,25 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => { } finally { setCompareDisabled(false) } - }}> + }} + style={{ cursor: compareDisabled ? "wait" : "pointer" }} + title="Compare"> -
    +
    setShowRestoreConfirm(true)} style={{ cursor: "pointer" }} - onClick={() => setShowRestoreConfirm(true)}> + title="Restore"> {showRestoreConfirm && ( - + @@ -164,8 +164,8 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => { @@ -175,8 +175,8 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => { diff --git a/webview-ui/src/components/common/CodeAccordian.tsx b/webview-ui/src/components/common/CodeAccordian.tsx index 69936a33..5b777698 100644 --- a/webview-ui/src/components/common/CodeAccordian.tsx +++ b/webview-ui/src/components/common/CodeAccordian.tsx @@ -1,6 +1,6 @@ import { memo, useMemo } from "react" -import { getLanguageFromPath } from "@/utils/getLanguageFromPath" import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import { getLanguageFromPath } from "@/utils/getLanguageFromPath" interface CodeAccordianProps { code?: string @@ -55,6 +55,7 @@ const CodeAccordian = ({ }}> {(path || isFeedback || isConsoleLogs) && (
    + }}> {isFeedback || isConsoleLogs ? (
    diff --git a/webview-ui/src/components/common/CodeBlock.tsx b/webview-ui/src/components/common/CodeBlock.tsx index c194c97e..87d29191 100644 --- a/webview-ui/src/components/common/CodeBlock.tsx +++ b/webview-ui/src/components/common/CodeBlock.tsx @@ -100,7 +100,7 @@ const StyledPre = styled.pre<{ theme: any }>` ${(props) => Object.keys(props.theme) - .map((key, index) => { + .map((key, _index) => { return ` & ${key} { color: ${props.theme[key]}; diff --git a/webview-ui/src/components/common/CopyButton.tsx b/webview-ui/src/components/common/CopyButton.tsx index ddacd515..1774c87d 100644 --- a/webview-ui/src/components/common/CopyButton.tsx +++ b/webview-ui/src/components/common/CopyButton.tsx @@ -1,12 +1,12 @@ -import React, { useState, useRef, forwardRef } from "react" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import React, { forwardRef, useState } from "react" import styled from "styled-components" // ======== Interfaces ======== interface CopyButtonProps { textToCopy?: string - onCopy?: () => string | void | null + onCopy?: () => string | undefined | null className?: string ariaLabel?: string } @@ -14,7 +14,7 @@ interface CopyButtonProps { interface WithCopyButtonProps { children: React.ReactNode textToCopy?: string - onCopy?: () => string | void | null + onCopy?: () => string | undefined | null position?: "top-right" | "bottom-right" style?: React.CSSProperties className?: string @@ -62,7 +62,9 @@ export const CopyButton: React.FC = ({ textToCopy, onCopy, clas const [copied, setCopied] = useState(false) const handleCopy = () => { - if (!textToCopy && !onCopy) return + if (!textToCopy && !onCopy) { + return + } let textToCopyFinal = textToCopy @@ -87,9 +89,9 @@ export const CopyButton: React.FC = ({ textToCopy, onCopy, clas return ( + onClick={handleCopy}> ) @@ -114,14 +116,14 @@ export const WithCopyButton = forwardRef( ref, ) => { return ( - + {children} {(textToCopy || onCopy) && ( )} diff --git a/webview-ui/src/components/common/Demo.tsx b/webview-ui/src/components/common/Demo.tsx index 3ac2396a..da3bc3a9 100644 --- a/webview-ui/src/components/common/Demo.tsx +++ b/webview-ui/src/components/common/Demo.tsx @@ -86,7 +86,7 @@ function Demo() { - + diff --git a/webview-ui/src/components/common/HeroTooltip.tsx b/webview-ui/src/components/common/HeroTooltip.tsx index f9057d48..09eaf337 100644 --- a/webview-ui/src/components/common/HeroTooltip.tsx +++ b/webview-ui/src/components/common/HeroTooltip.tsx @@ -1,5 +1,5 @@ -import React from "react" import { Tooltip } from "@heroui/react" +import React from "react" interface HeroTooltipProps { content: React.ReactNode @@ -41,16 +41,16 @@ const HeroTooltip: React.FC = ({ return ( + }} + closeDelay={0} + content={formattedContent} // Immediate close when cursor moves away + delay={delay} + disableAnimation={true} + isDisabled={false} + placement={placement} // Disable animation for immediate appearance/disappearance + showArrow={false}> {children} ) diff --git a/webview-ui/src/components/common/MarkdownBlock.tsx b/webview-ui/src/components/common/MarkdownBlock.tsx index 11df2592..895923c2 100644 --- a/webview-ui/src/components/common/MarkdownBlock.tsx +++ b/webview-ui/src/components/common/MarkdownBlock.tsx @@ -1,17 +1,17 @@ -import React, { memo, useEffect, useRef, useState } from "react" +import { StringRequest } from "@shared/proto/cline/common" +import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/cline/state" import type { ComponentProps } from "react" +import React, { memo, useEffect, useRef } from "react" import { useRemark } from "react-remark" import rehypeHighlight, { Options } from "rehype-highlight" import styled from "styled-components" -import { visit } from "unist-util-visit" import type { Node } from "unist" -import { useExtensionState } from "@/context/ExtensionStateContext" -import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" +import { visit } from "unist-util-visit" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import MermaidBlock from "@/components/common/MermaidBlock" -import { WithCopyButton } from "./CopyButton" +import { useExtensionState } from "@/context/ExtensionStateContext" import { FileServiceClient, StateServiceClient } from "@/services/grpc-client" -import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/cline/state" -import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" +import { WithCopyButton } from "./CopyButton" // Styled component for Act Mode text with more specific styling const ActModeHighlight: React.FC = () => { @@ -19,6 +19,9 @@ const ActModeHighlight: React.FC = () => { return ( { // Only toggle to Act mode if we're currently in Plan mode if (mode === "plan") { @@ -29,10 +32,7 @@ const ActModeHighlight: React.FC = () => { ) } }} - title={mode === "plan" ? "Click to toggle to Act Mode" : "Already in Act Mode"} - className={`text-[var(--vscode-textLink-foreground)] inline-flex items-center gap-1 ${ - mode === "plan" ? "hover:opacity-90 cursor-pointer" : "cursor-default opacity-60" - }`}> + title={mode === "plan" ? "Click to toggle to Act Mode" : "Already in Act Mode"}>
    @@ -59,13 +59,17 @@ const remarkUrlToLink = () => { visit(tree, "text", (node: any, index, parent) => { const urlRegex = /https?:\/\/[^\s<>)"]+/g const matches = node.value.match(urlRegex) - if (!matches) return + if (!matches) { + return + } const parts = node.value.split(urlRegex) const children: any[] = [] parts.forEach((part: string, i: number) => { - if (part) children.push({ type: "text", value: part }) + if (part) { + children.push({ type: "text", value: part }) + } if (matches[i]) { children.push({ type: "link", @@ -96,19 +100,25 @@ const remarkHighlightActMode = () => { // Added negative lookahead to avoid matching if already followed by the shortcut const actModeRegex = /\bto\s+Act\s+Mode\b(?!\s*\(⌘⇧A\))/i - if (!node.value.match(actModeRegex)) return + if (!node.value.match(actModeRegex)) { + return + } // Split the text by the matches const parts = node.value.split(actModeRegex) const matches = node.value.match(actModeRegex) - if (!matches || parts.length <= 1) return + if (!matches || parts.length <= 1) { + return + } const children: any[] = [] parts.forEach((part: string, i: number) => { // Add the text before the match - if (part) children.push({ type: "text", value: part }) + if (part) { + children.push({ type: "text", value: part }) + } // Add the match, but only make "Act Mode" bold (not the "to" part) if (matches[i]) { @@ -156,22 +166,32 @@ const remarkPreventBoldFilenames = () => { return (tree: any) => { visit(tree, "strong", (node: any, index: number | undefined, parent: any) => { // Only process if there's a next node (potential file extension) - if (!parent || typeof index === "undefined" || index === parent.children.length - 1) return + if (!parent || typeof index === "undefined" || index === parent.children.length - 1) { + return + } const nextNode = parent.children[index + 1] // Check if next node is text and starts with . followed by extension - if (nextNode.type !== "text" || !nextNode.value.match(/^\.[a-zA-Z0-9]+/)) return + if (nextNode.type !== "text" || !nextNode.value.match(/^\.[a-zA-Z0-9]+/)) { + return + } // If the strong node has multiple children, something weird is happening - if (node.children?.length !== 1) return + if (node.children?.length !== 1) { + return + } // Get the text content from inside the strong node const strongContent = node.children?.[0]?.value - if (!strongContent || typeof strongContent !== "string") return + if (!strongContent || typeof strongContent !== "string") { + return + } // Validate that the strong content is a valid filename - if (!strongContent.match(/^[a-zA-Z0-9_-]+$/)) return + if (!strongContent.match(/^[a-zA-Z0-9_-]+$/)) { + return + } // Combine into a single text node const newNode = { @@ -282,7 +302,7 @@ const StyledPre = styled.pre<{ theme: any }>` ${(props) => Object.keys(props.theme) - .map((key, index) => { + .map((key, _index) => { return ` & ${key} { color: ${props.theme[key]}; @@ -304,7 +324,9 @@ const PreWithCopyButton = ({ const codeElement = preRef.current.querySelector("code") const textToCopy = codeElement ? codeElement.textContent : preRef.current.textContent - if (!textToCopy) return + if (!textToCopy) { + return + } return textToCopy } return null @@ -313,7 +335,7 @@ const PreWithCopyButton = ({ const styledPreProps = theme ? { ...preProps, theme } : preProps return ( - + {children} @@ -328,7 +350,7 @@ const PreWithCopyButton = ({ const remarkFilePathDetection = () => { return async (tree: Node) => { const fileNameRegex = /^(?!\/)[\w\-./]+(?[] = [] // Collect all inline code nodes that might be file paths @@ -412,10 +434,10 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { <> diff --git a/webview-ui/src/components/common/TelemetryBanner.tsx b/webview-ui/src/components/common/TelemetryBanner.tsx index 4adbafb9..427e3132 100644 --- a/webview-ui/src/components/common/TelemetryBanner.tsx +++ b/webview-ui/src/components/common/TelemetryBanner.tsx @@ -1,9 +1,9 @@ -import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" -import { memo, useState } from "react" +import { TelemetrySettingEnum, TelemetrySettingRequest } from "@shared/proto/cline/state" +import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { memo } from "react" import styled from "styled-components" import { useExtensionState } from "@/context/ExtensionStateContext" import { StateServiceClient } from "@/services/grpc-client" -import { TelemetrySettingEnum, TelemetrySettingRequest } from "@shared/proto/cline/state" const BannerContainer = styled.div` background-color: var(--vscode-banner-background); @@ -35,7 +35,7 @@ const CloseButton = styled.button` } ` -const ButtonContainer = styled.div` +const _ButtonContainer = styled.div` display: flex; gap: 8px; width: 100%; @@ -67,7 +67,7 @@ const TelemetryBanner = () => { return ( - + ✕
    diff --git a/webview-ui/src/components/common/Thumbnails.tsx b/webview-ui/src/components/common/Thumbnails.tsx index a035a520..23ce970f 100644 --- a/webview-ui/src/components/common/Thumbnails.tsx +++ b/webview-ui/src/components/common/Thumbnails.tsx @@ -1,7 +1,7 @@ -import { FileServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/cline/common" import React, { memo, useLayoutEffect, useRef, useState } from "react" import { useWindowSize } from "react-use" +import { FileServiceClient } from "@/services/grpc-client" interface ThumbnailsProps { images: string[] @@ -65,12 +65,13 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange {images.map((image, index) => (
    setHoveredIndex(`image-${index}`)} - onMouseLeave={() => setHoveredIndex(null)}> + onMouseLeave={() => setHoveredIndex(null)} + style={{ position: "relative" }}> {`Thumbnail handleImageClick(image)} + src={image} style={{ width: 34, height: 34, @@ -78,7 +79,6 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange borderRadius: 4, cursor: "pointer", }} - onClick={() => handleImageClick(image)} /> {isDeletableImages && hoveredIndex === `image-${index}` && (
    setHoveredIndex(`file-${index}`)} - onMouseLeave={() => setHoveredIndex(null)}> + onMouseLeave={() => setHoveredIndex(null)} + style={{ position: "relative" }}>
    handleFileClick(filePath)} style={{ width: 34, height: 34, @@ -129,8 +130,7 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange flexDirection: "column", alignItems: "center", justifyContent: "center", - }} - onClick={() => handleFileClick(filePath)}> + }}> = ({ visible, tipText, hintText, children, return (
    setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)}> + onMouseLeave={() => setIsHovered(false)} + style={{ position: "relative", display: "inline-block" }}> {children} {shouldShow && ( diff --git a/webview-ui/src/components/common/VSCodeButtonLink.tsx b/webview-ui/src/components/common/VSCodeButtonLink.tsx index 8d0c87d6..2a8c39ff 100644 --- a/webview-ui/src/components/common/VSCodeButtonLink.tsx +++ b/webview-ui/src/components/common/VSCodeButtonLink.tsx @@ -1,5 +1,5 @@ -import React from "react" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import React from "react" interface VSCodeButtonLinkProps { href: string diff --git a/webview-ui/src/components/history/HistoryPreview.tsx b/webview-ui/src/components/history/HistoryPreview.tsx index 4462d44a..9ca1a6ad 100644 --- a/webview-ui/src/components/history/HistoryPreview.tsx +++ b/webview-ui/src/components/history/HistoryPreview.tsx @@ -1,9 +1,9 @@ -import { useExtensionState } from "@/context/ExtensionStateContext" -import { TaskServiceClient } from "@/services/grpc-client" -import { formatLargeNumber } from "@/utils/format" import { StringRequest } from "@shared/proto/cline/common" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { memo, useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { TaskServiceClient } from "@/services/grpc-client" +import { formatLargeNumber } from "@/utils/format" type HistoryPreviewProps = { showHistoryView: () => void @@ -106,8 +106,8 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { .slice(0, 3) .map((item) => (
    handleHistorySelect(item.id)}>
    @@ -129,13 +129,13 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => { right: "12px", color: "var(--vscode-button-background)", }}> - +
    )}
    void @@ -31,8 +28,8 @@ interface CustomFilterRadioProps { const CustomFilterRadio = ({ checked, onChange, icon, label }: CustomFilterRadioProps) => { return (
    + className="flex items-center cursor-pointer py-[0.3em] px-0 mr-[10px] text-[var(--vscode-font-size)] select-none" + onClick={onChange}>
    { // Calculate total size of selected items const selectedItemsSize = useMemo(() => { - if (selectedItems.length === 0) return 0 + if (selectedItems.length === 0) { + return 0 + } return taskHistory.filter((item) => selectedItems.includes(item.id)).reduce((total, item) => total + (item.size || 0), 0) }, [selectedItems, taskHistory]) @@ -335,9 +334,6 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { gap: "6px", }}> { const newValue = (e.target as HTMLInputElement)?.value setSearchQuery(newValue) @@ -345,10 +341,13 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { setLastNonRelevantSort(sortOption) setSortOption("mostRelevant") } - }}> + }} + placeholder="Fuzzy search history..." + style={{ width: "100%" }} + value={searchQuery}>
    { }}>
    {searchQuery && (
    setSearchQuery("")} slot="end" style={{ @@ -370,27 +369,27 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { )} setSortOption((e.target as HTMLInputElement).value as SortOption)} style={{ display: "flex", flexWrap: "wrap" }} - value={sortOption} - onChange={(e) => setSortOption((e.target as HTMLInputElement).value as SortOption)}> + value={sortOption}> Newest Oldest Most Expensive Most Tokens - + Most Relevant setShowCurrentWorkspaceOnly(!showCurrentWorkspaceOnly)} icon="workspace" label="Workspace" + onChange={() => setShowCurrentWorkspaceOnly(!showCurrentWorkspaceOnly)} /> setShowFavoritesOnly(!showFavoritesOnly)} icon="star-full" label="Favorites" + onChange={() => setShowFavoritesOnly(!showFavoritesOnly)} /> @@ -428,15 +427,11 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
    )} */} (
    { display: "flex", }}> { const checked = (e.target as HTMLInputElement).checked handleHistorySelect(item.id, checked) @@ -453,6 +448,7 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { }} />
    handleShowTaskWithId(item.id)} style={{ display: "flex", flexDirection: "column", @@ -461,8 +457,7 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { paddingLeft: "16px", position: "relative", flexGrow: 1, - }} - onClick={() => handleShowTaskWithId(item.id)}> + }}>
    { {!(pendingFavoriteToggles[item.id] ?? item.isFavorited) && ( { e.stopPropagation() handleDeleteHistoryItem(item.id) }} - className="delete-button" style={{ padding: "0px 0px" }}>
    {
    )} + style={{ + flexGrow: 1, + overflowY: "scroll", + }} />
    { }}> {selectedItems.length > 0 ? ( { handleDeleteSelectedHistoryItems(selectedItems) - }}> + }} + style={{ width: "100%" }}> Delete {selectedItems.length > 1 ? selectedItems.length : ""} Selected {selectedItemsSize > 0 ? ` (${formatSize(selectedItemsSize)})` : ""} ) : ( { setDeleteAllDisabled(true) TaskServiceClient.deleteAllTaskHistory(BooleanRequest.create({})) .catch((error) => console.error("Error deleting task history:", error)) .finally(() => setDeleteAllDisabled(false)) - }}> + }} + style={{ width: "100%" }}> Delete All History{totalTasksSize !== null ? ` (${formatSize(totalTasksSize)})` : ""} )} @@ -742,8 +741,8 @@ const HistoryView = ({ onDone }: HistoryViewProps) => { const ExportButton = ({ itemId }: { itemId: string }) => ( { e.stopPropagation() TaskServiceClient.exportTaskWithId(StringRequest.create({ value: itemId })).catch((err) => @@ -769,7 +768,9 @@ export const highlight = (fuseSearchResult: FuseResult[], highlightClassNam // Function to merge overlapping regions const mergeRegions = (regions: [number, number][]): [number, number][] => { - if (regions.length === 0) return regions + if (regions.length === 0) { + return regions + } // Sort regions by start index regions.sort((a, b) => a[0] - b[0]) diff --git a/webview-ui/src/components/mcp/chat-display/ImagePreview.tsx b/webview-ui/src/components/mcp/chat-display/ImagePreview.tsx index 5623fe45..7e0e735e 100644 --- a/webview-ui/src/components/mcp/chat-display/ImagePreview.tsx +++ b/webview-ui/src/components/mcp/chat-display/ImagePreview.tsx @@ -1,8 +1,8 @@ -import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary" -import { WebServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/cline/common" import DOMPurify from "dompurify" import React from "react" +import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary" +import { WebServiceClient } from "@/services/grpc-client" import { checkIfImageUrl, formatUrlForOpening, getSafeHostname } from "./utils/mcpRichUtil" interface ImagePreviewProps { @@ -202,19 +202,19 @@ class ImagePreview extends React.Component< {/* Hidden image that we'll use to detect load/error events */} {/\.svg(\?.*)?$/i.test(url) ? ( ) : ( )} @@ -227,12 +227,6 @@ class ImagePreview extends React.Component< return (
    { try { await WebServiceClient.openInBrowser( @@ -243,6 +237,12 @@ class ImagePreview extends React.Component< } catch (err) { console.error("Error opening URL in browser:", err) } + }} + style={{ + padding: "12px", + border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))", + borderRadius: "4px", + color: "var(--vscode-errorForeground)", }}>
    Failed to load image
    {getSafeHostname(url)}
    @@ -257,11 +257,6 @@ class ImagePreview extends React.Component< return (
    { try { await WebServiceClient.openInBrowser( @@ -272,22 +267,27 @@ class ImagePreview extends React.Component< } catch (err) { console.error("Error opening URL in browser:", err) } + }} + style={{ + margin: "10px 0", + maxWidth: "100%", + cursor: "pointer", }}> {/\.svg(\?.*)?$/i.test(url) ? ( // Special handling for SVG images + type="image/svg+xml"> {/* Fallback if object tag fails */} {`SVG ) : ( {`Image 3 || this.aspectRatio < 0.33 ? "contain" : "cover", - }} loading="eager" onLoad={(e) => { // Double-check aspect ratio from the actual loaded image @@ -322,6 +314,14 @@ class ImagePreview extends React.Component< } } }} + src={DOMPurify.sanitize(url)} + style={{ + width: "85%", + height: "auto", + borderRadius: "4px", + // Use contain only for very extreme aspect ratios, otherwise use cover + objectFit: this.aspectRatio > 3 || this.aspectRatio < 0.33 ? "contain" : "cover", + }} /> )} diff --git a/webview-ui/src/components/mcp/chat-display/LinkPreview.tsx b/webview-ui/src/components/mcp/chat-display/LinkPreview.tsx index a1f02946..b6ed060a 100644 --- a/webview-ui/src/components/mcp/chat-display/LinkPreview.tsx +++ b/webview-ui/src/components/mcp/chat-display/LinkPreview.tsx @@ -1,8 +1,8 @@ -import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary" -import { WebServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/cline/common" import DOMPurify from "dompurify" import React from "react" +import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary" +import { WebServiceClient } from "@/services/grpc-client" import { getSafeHostname, normalizeRelativeUrl } from "./utils/mcpRichUtil" interface OpenGraphData { @@ -231,15 +231,6 @@ class LinkPreview extends React.Component { return (
    { try { await WebServiceClient.openInBrowser( @@ -250,6 +241,15 @@ class LinkPreview extends React.Component { } catch (err) { console.error("Error opening URL in browser:", err) } + }} + style={{ + padding: "12px", + border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))", + borderRadius: "4px", + color: "var(--vscode-errorForeground)", + height: "128px", + maxWidth: "512px", + overflow: "auto", }}>
    {errorDisplay}
    {getSafeHostname(url)}
    @@ -273,15 +273,6 @@ class LinkPreview extends React.Component { return (
    { try { await WebServiceClient.openInBrowser( @@ -292,17 +283,24 @@ class LinkPreview extends React.Component { } catch (err) { console.error("Error opening URL in browser:", err) } + }} + style={{ + display: "flex", + border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))", + borderRadius: "4px", + overflow: "hidden", + cursor: "pointer", + height: "128px", + maxWidth: "512px", }}> {data.image && (
    { + console.log(`Image could not be loaded: ${data.image}`) + // Hide the broken image + ;(e.target as HTMLImageElement).style.display = "none" }} onLoad={(e) => { // Check aspect ratio to determine if we should use contain or cover @@ -318,10 +316,12 @@ class LinkPreview extends React.Component { } } }} - onError={(e) => { - console.log(`Image could not be loaded: ${data.image}`) - // Hide the broken image - ;(e.target as HTMLImageElement).style.display = "none" + src={DOMPurify.sanitize(normalizeRelativeUrl(data.image, url))} + style={{ + width: "100%", + height: "100%", + objectFit: "contain", // Use contain for link preview thumbnails to handle logos + objectPosition: "center", // Center the image }} />
    diff --git a/webview-ui/src/components/mcp/chat-display/McpDisplayModeDropdown.tsx b/webview-ui/src/components/mcp/chat-display/McpDisplayModeDropdown.tsx index a34a4306..e8facd67 100644 --- a/webview-ui/src/components/mcp/chat-display/McpDisplayModeDropdown.tsx +++ b/webview-ui/src/components/mcp/chat-display/McpDisplayModeDropdown.tsx @@ -1,6 +1,6 @@ -import React from "react" -import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import { McpDisplayMode } from "@shared/McpDisplayMode" +import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import React from "react" interface McpDisplayModeDropdownProps { value: McpDisplayMode @@ -18,7 +18,7 @@ const McpDisplayModeDropdown: React.FC = ({ value, } return ( - + Plain Text Rich Display Markdown diff --git a/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx b/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx index db5fbd09..572f02cc 100644 --- a/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx +++ b/webview-ui/src/components/mcp/chat-display/McpResponseDisplay.tsx @@ -1,17 +1,17 @@ -import React, { useEffect, useState, useCallback } from "react" +import { McpDisplayMode } from "@shared/McpDisplayMode" import { VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react" -import { useExtensionState } from "../../../context/ExtensionStateContext" -import LinkPreview from "./LinkPreview" -import ImagePreview from "./ImagePreview" +import React, { useCallback, useEffect, useState } from "react" import styled from "styled-components" -import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary" +import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import MarkdownBlock from "@/components/common/MarkdownBlock" -import McpDisplayModeDropdown from "./McpDisplayModeDropdown" import { DropdownContainer } from "@/components/settings/ApiOptions" import { updateSetting } from "@/components/settings/utils/settingsHandlers" -import { McpDisplayMode } from "@shared/McpDisplayMode" -import { UrlMatch, processResponseUrls, DisplaySegment, buildDisplaySegments } from "./utils/mcpRichUtil" +import { useExtensionState } from "../../../context/ExtensionStateContext" +import ImagePreview from "./ImagePreview" +import LinkPreview from "./LinkPreview" +import McpDisplayModeDropdown from "./McpDisplayModeDropdown" +import { buildDisplaySegments, DisplaySegment, processResponseUrls, UrlMatch } from "./utils/mcpRichUtil" // Maximum number of URLs to process in total, per response export const MAX_URLS = 50 @@ -226,10 +226,10 @@ const McpResponseDisplay: React.FC = ({ responseText }) e.stopPropagation()} style={{ minWidth: "120px" }} + value={mcpDisplayMode} /> @@ -237,7 +237,7 @@ const McpResponseDisplay: React.FC = ({ responseText }) {isExpanded &&
    {renderContent()}
    } ) - } catch (error) { + } catch (_error) { console.log("Error rendering MCP response - falling back to plain text") // Restored comment // Fallback for critical rendering errors return ( diff --git a/webview-ui/src/components/mcp/chat-display/utils/mcpRichUtil.ts b/webview-ui/src/components/mcp/chat-display/utils/mcpRichUtil.ts index 89925843..e667b5b6 100644 --- a/webview-ui/src/components/mcp/chat-display/utils/mcpRichUtil.ts +++ b/webview-ui/src/components/mcp/chat-display/utils/mcpRichUtil.ts @@ -1,5 +1,5 @@ -import { WebServiceClient } from "@/services/grpc-client" import { StringRequest } from "@shared/proto/cline/common" +import { WebServiceClient } from "@/services/grpc-client" // Represents a URL found in the text with its position and metadata export interface UrlMatch { @@ -27,12 +27,12 @@ export const safeCreateUrl = (url: string): URL | null => { } return new URL(url) - } catch (e) { + } catch (_e) { // If the URL doesn't have a protocol, add https:// if (!url.startsWith("https://")) { try { return new URL(`https://${url}`) - } catch (e) { + } catch (_e) { console.log(`Invalid URL: ${url}`) return null } @@ -52,7 +52,7 @@ export const getSafeHostname = (url: string): string => { try { const urlObj = safeCreateUrl(url) return urlObj ? urlObj.hostname : "unknown-host" - } catch (e) { + } catch (_e) { return "unknown-host" } } @@ -69,7 +69,7 @@ export const isLocalhostUrl = (url: string): boolean => { hostname.startsWith("10.") || hostname.endsWith(".local") ) - } catch (e) { + } catch (_e) { // If we can't parse the URL, assume it's not localhost return false } @@ -172,7 +172,7 @@ export const checkIfImageUrl = async (url: string): Promise => { // Race between the service call and the timeout return Promise.race([servicePromise, timeoutPromise]) - } catch (error) { + } catch (_error) { console.log("Error checking if URL is an image:", url) // Return false to indicate it's not an image return false @@ -245,7 +245,9 @@ export const processUrlTypes = async ( for (let i = 0; i < matches.length; i++) { // Skip already processed URLs - if (matches[i].isProcessed) continue + if (matches[i].isProcessed) { + continue + } // Check if processing has been canceled if (cancellationToken.cancelled) { @@ -261,7 +263,9 @@ export const processUrlTypes = async ( const isImage = await checkIfImageUrl(match.url) // Skip if processing has been canceled - if (cancellationToken.cancelled) return + if (cancellationToken.cancelled) { + return + } // Update the match match.isImage = isImage @@ -316,7 +320,7 @@ export const processResponseUrls = ( // Process URLs in the background await processUrlTypes(matches, onMatchesUpdated, cancellationToken) - } catch (error) { + } catch (_error) { onError("Failed to process response content. Switch to plain text mode to view safely.") } } diff --git a/webview-ui/src/components/mcp/configuration/McpConfigurationView.tsx b/webview-ui/src/components/mcp/configuration/McpConfigurationView.tsx index b5141fa3..38d54b12 100644 --- a/webview-ui/src/components/mcp/configuration/McpConfigurationView.tsx +++ b/webview-ui/src/components/mcp/configuration/McpConfigurationView.tsx @@ -1,15 +1,15 @@ -import { useExtensionState } from "@/context/ExtensionStateContext" -import { McpServiceClient } from "@/services/grpc-client" import { McpViewTab } from "@shared/mcp" import { EmptyRequest } from "@shared/proto/cline/common" +import { McpServers } from "@shared/proto/cline/mcp" +import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { useEffect, useState } from "react" import styled from "styled-components" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { McpServiceClient } from "@/services/grpc-client" import AddRemoteServerForm from "./tabs/add-server/AddRemoteServerForm" import InstalledServersView from "./tabs/installed/InstalledServersView" import McpMarketplaceView from "./tabs/marketplace/McpMarketplaceView" -import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" -import { McpServers } from "@shared/proto/cline/mcp" type McpViewProps = { onDone: () => void @@ -145,7 +145,7 @@ export const TabButton = ({ disabled?: boolean style?: React.CSSProperties }) => ( - + {children} ) diff --git a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddLocalServerForm.tsx b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddLocalServerForm.tsx index 0747e40c..e4316542 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddLocalServerForm.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddLocalServerForm.tsx @@ -1,8 +1,8 @@ -import { LINKS } from "@/constants" -import { McpServiceClient } from "@/services/grpc-client" import { EmptyRequest } from "@shared/proto/cline/common" import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import styled from "styled-components" +import { LINKS } from "@/constants" +import { McpServiceClient } from "@/services/grpc-client" type AddLocalServerFormProps = { onServerAdded: () => void @@ -21,12 +21,12 @@ const AddLocalServerForm = ({ onServerAdded }: AddLocalServerFormProps) => { { McpServiceClient.openMcpSettings(EmptyRequest.create({})).catch((error) => { console.error("Error opening MCP settings:", error) }) - }}> + }} + style={{ width: "100%", marginBottom: "5px", marginTop: 8 }}> Open cline_mcp_settings.json diff --git a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx index 7b881fda..e333b924 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/add-server/AddRemoteServerForm.tsx @@ -1,12 +1,11 @@ +import { EmptyRequest } from "@shared/proto/cline/common" +import { AddRemoteMcpServerRequest, McpServers } from "@shared/proto/cline/mcp" +import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" +import { VSCodeButton, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { useState } from "react" import { LINKS } from "@/constants" import { useExtensionState } from "@/context/ExtensionStateContext" import { McpServiceClient } from "@/services/grpc-client" -import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" -import { McpServers } from "@shared/proto/cline/mcp" -import { EmptyRequest } from "@shared/proto/cline/common" -import { AddRemoteMcpServerRequest } from "@shared/proto/cline/mcp" -import { VSCodeButton, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" -import { useState } from "react" const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) => { const [serverName, setServerName] = useState("") @@ -31,7 +30,7 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = try { new URL(serverUrl) - } catch (err) { + } catch (_err) { setError("Invalid URL format") return } @@ -76,28 +75,28 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
    { setServerName((e.target as HTMLInputElement).value) setError("") }} - disabled={isSubmitting} - className="w-full" - placeholder="mcp-server"> + placeholder="mcp-server" + value={serverName}> Server Name
    { setServerUrl((e.target as HTMLInputElement).value) setError("") }} - disabled={isSubmitting} placeholder="https://example.com/mcp-server" - className="w-full mr-4"> + value={serverUrl}> Server URL
    @@ -105,7 +104,7 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = {error &&
    {error}
    }
    - + {isSubmitting ? "Adding..." : "Add Server"} @@ -118,12 +117,12 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) = { McpServiceClient.openMcpSettings(EmptyRequest.create({})).catch((error) => { console.error("Error opening MCP settings:", error) }) - }}> + }} + style={{ width: "100%", marginBottom: "5px", marginTop: 15 }}> Edit Configuration diff --git a/webview-ui/src/components/mcp/configuration/tabs/installed/InstalledServersView.tsx b/webview-ui/src/components/mcp/configuration/tabs/installed/InstalledServersView.tsx index 58184ea7..0ec469a5 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/installed/InstalledServersView.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/installed/InstalledServersView.tsx @@ -1,10 +1,9 @@ -import { useExtensionState } from "@/context/ExtensionStateContext" -import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" - -import { McpServiceClient, UiServiceClient } from "@/services/grpc-client" - import { EmptyRequest, StringRequest } from "@shared/proto/cline/common" +import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { McpServiceClient, UiServiceClient } from "@/services/grpc-client" import ServersToggleList from "./ServersToggleList" + const InstalledServersView = () => { const { mcpServers: servers, navigateToSettings } = useExtensionState() @@ -32,18 +31,18 @@ const InstalledServersView = () => {
    - + {/* Settings Section */}
    { McpServiceClient.openMcpSettings(EmptyRequest.create({})).catch((error) => { console.error("Error opening MCP settings:", error) }) - }}> + }} + style={{ width: "100%", marginBottom: "5px" }}> Configure MCP Servers diff --git a/webview-ui/src/components/mcp/configuration/tabs/installed/ServersToggleList.tsx b/webview-ui/src/components/mcp/configuration/tabs/installed/ServersToggleList.tsx index 27fb6353..f10333da 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/installed/ServersToggleList.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/installed/ServersToggleList.tsx @@ -23,7 +23,7 @@ const ServersToggleList = ({ return servers.length > 0 ? (
    {servers.map((server) => ( - + ))}
    ) : ( diff --git a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/McpToolRow.tsx b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/McpToolRow.tsx index b1993755..04fcc6a5 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/McpToolRow.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/McpToolRow.tsx @@ -1,9 +1,9 @@ +import { McpTool } from "@shared/mcp" +import { ToggleToolAutoApproveRequest } from "@shared/proto/cline/mcp" +import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import { useExtensionState } from "@/context/ExtensionStateContext" import { McpServiceClient } from "@/services/grpc-client" -import { McpTool } from "@shared/mcp" -import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" -import { ToggleToolAutoApproveRequest } from "@shared/proto/cline/mcp" -import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" type McpToolRowProps = { tool: McpTool @@ -16,7 +16,7 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => { const { setMcpServers } = useExtensionState() // Accept the event object - const handleAutoApproveChange = (event: any) => { + const handleAutoApproveChange = (_event: any) => { if (!serverName) { return } @@ -44,14 +44,14 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => { }}>
    e.stopPropagation()}> + onClick={(e) => e.stopPropagation()} + style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
    {tool.name}
    {serverName && autoApprovalSettings.enabled && autoApprovalSettings.actions.useMcp && ( - + Auto-approve )} diff --git a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx index f11b2eac..fcf6bf42 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/installed/server-row/ServerRow.tsx @@ -1,9 +1,4 @@ -import DangerButton from "@/components/common/DangerButton" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { McpServiceClient } from "@/services/grpc-client" -import { getMcpServerDisplayName } from "@/utils/mcp" import { DEFAULT_MCP_TIMEOUT_SECONDS, McpServer } from "@shared/mcp" -import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" import { StringRequest } from "@shared/proto/cline/common" import { McpServers, @@ -11,6 +6,7 @@ import { ToggleToolAutoApproveRequest, UpdateMcpTimeoutRequest, } from "@shared/proto/cline/mcp" +import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" import { VSCodeButton, VSCodeCheckbox, @@ -21,8 +17,13 @@ import { VSCodePanelView, } from "@vscode/webview-ui-toolkit/react" import { useCallback, useState } from "react" +import DangerButton from "@/components/common/DangerButton" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { McpServiceClient } from "@/services/grpc-client" +import { getMcpServerDisplayName } from "@/utils/mcp" import McpResourceRow from "./McpResourceRow" import McpToolRow from "./McpToolRow" + // constant JSX.Elements const TimeoutOptions = [ { value: "30", label: "30 seconds" }, @@ -135,7 +136,9 @@ const ServerRow = ({ } const handleAutoApproveChange = () => { - if (!server.name) return + if (!server.name) { + return + } McpServiceClient.toggleToolAutoApprove( ToggleToolAutoApproveRequest.create({ @@ -172,6 +175,7 @@ const ServerRow = ({ return (
    + }}> {!server.error && isExpandable && ( )} @@ -203,34 +206,42 @@ const ServerRow = ({
    { e.stopPropagation() handleRestart() }} - disabled={server.status === "connecting" || isRestarting}> + title="Restart Server"> {hasTrashIcon && ( { e.stopPropagation() handleDelete() }} - disabled={isDeleting}> + title="Delete Server"> )}
    )} {/* Toggle Switch */} -
    e.stopPropagation()}> +
    e.stopPropagation()} style={{ display: "flex", alignItems: "center", marginLeft: "8px" }}>
    { + handleToggleMcpServer() + }} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault() + handleToggleMcpServer() + } + }} + role="switch" style={{ width: "20px", height: "10px", @@ -243,15 +254,7 @@ const ServerRow = ({ transition: "background-color 0.2s", opacity: server.disabled ? 0.5 : 0.9, }} - onClick={() => { - handleToggleMcpServer() - }} - onKeyDown={(e) => { - if (e.key === "Enter" || e.key === " ") { - e.preventDefault() - handleToggleMcpServer() - } - }}> + tabIndex={0}>
    + onClick={handleDelete} + style={{ width: "calc(100% - 20px)", margin: "0 10px 10px 10px" }}> {isDeleting ? "Deleting..." : "Delete Server"}
    @@ -339,14 +342,14 @@ const ServerRow = ({ width: "100%", }}> {server.tools.map((tool) => ( - + ))} {server.name && autoApprovalSettings.enabled && autoApprovalSettings.actions.useMcp && ( tool.autoApprove)} + data-tool="all-tools" onChange={handleAutoApproveChange} - data-tool="all-tools"> + style={{ marginBottom: -10 }}> Auto-approve all tools )} @@ -374,8 +377,8 @@ const ServerRow = ({ }}> {[...(server.resourceTemplates || []), ...(server.resources || [])].map((item) => ( ))}
    @@ -393,14 +396,14 @@ const ServerRow = ({
    - + {TimeoutOptions}
    + onClick={handleDelete} + style={{ width: "calc(100% - 14px)", margin: "5px 7px 3px 7px" }}> {isDeleting ? "Deleting..." : "Delete Server"}
    diff --git a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx index bcd43f54..98c02294 100644 --- a/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx +++ b/webview-ui/src/components/mcp/configuration/tabs/marketplace/McpMarketplaceCard.tsx @@ -1,9 +1,9 @@ -import { McpServiceClient } from "@/services/grpc-client" import { McpMarketplaceItem, McpServer } from "@shared/mcp" import { StringRequest } from "@shared/proto/cline/common" import { useEffect, useMemo, useRef, useState } from "react" import styled from "styled-components" import { useExtensionState } from "@/context/ExtensionStateContext" +import { McpServiceClient } from "@/services/grpc-client" interface McpMarketplaceCardProps { item: McpMarketplaceItem @@ -50,8 +50,8 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace `} - + {isInstalled ? "Installed" : isDownloading ? "Installing..." : "Install"}
    @@ -146,7 +146,16 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace rowGap: 0, }}> { + e.currentTarget.style.opacity = "1" + e.currentTarget.style.color = "var(--link-active-foreground)" + }} + onMouseLeave={(e) => { + e.currentTarget.style.opacity = "0.7" + e.currentTarget.style.color = "var(--vscode-foreground)" + }} style={{ display: "flex", alignItems: "center", @@ -155,17 +164,8 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace opacity: 0.7, textDecoration: "none", border: "none !important", - }} - className="github-link" - onMouseEnter={(e) => { - e.currentTarget.style.opacity = "1" - e.currentTarget.style.color = "var(--link-active-foreground)" - }} - onMouseLeave={(e) => { - e.currentTarget.style.opacity = "0.7" - e.currentTarget.style.color = "var(--vscode-foreground)" }}> -
    +
    {item.downloadCount?.toLocaleString() ?? 0}
    {item.requiresApiKey && ( - + )}
    @@ -227,6 +227,13 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace

    {item.description}

    { + const target = e.currentTarget + const gradient = target.querySelector(".tags-gradient") as HTMLElement + if (gradient) { + gradient.style.visibility = target.scrollLeft > 0 ? "hidden" : "visible" + } + }} style={{ display: "flex", gap: "6px", @@ -234,13 +241,6 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace overflowX: "auto", scrollbarWidth: "none", position: "relative", - }} - onScroll={(e) => { - const target = e.currentTarget - const gradient = target.querySelector(".tags-gradient") as HTMLElement - if (gradient) { - gradient.style.visibility = target.scrollLeft > 0 ? "hidden" : "visible" - } }}> { const { mcpServers, mcpMarketplaceCatalog, setMcpMarketplaceCatalog, mcpMarketplaceEnabled } = useExtensionState() const [isLoading, setIsLoading] = useState(true) @@ -140,13 +139,13 @@ const McpMarketplaceView = () => {
    {/* Search row */} setSearchQuery((e.target as HTMLInputElement).value)} placeholder="Search MCPs..." - value={searchQuery} - onInput={(e) => setSearchQuery((e.target as HTMLInputElement).value)}> + style={{ width: "100%" }} + value={searchQuery}>
    { /> {searchQuery && (
    setSearchQuery("")} slot="end" style={{ @@ -193,11 +192,11 @@ const McpMarketplaceView = () => { flex: 1, }}> setSelectedCategory((e.target as HTMLSelectElement).value || null)} style={{ width: "100%", }} - value={selectedCategory || ""} - onChange={(e) => setSelectedCategory((e.target as HTMLSelectElement).value || null)}> + value={selectedCategory || ""}> All Categories {categories.map((category) => ( @@ -225,13 +224,13 @@ const McpMarketplaceView = () => { Sort: setSortBy((e.target as HTMLInputElement).value as typeof sortBy)} style={{ display: "flex", flexWrap: "wrap", marginTop: "-2.5px", }} - value={sortBy} - onChange={(e) => setSortBy((e.target as HTMLInputElement).value as typeof sortBy)}> + value={sortBy}> Most Installs Newest GitHub Stars @@ -276,7 +275,7 @@ const McpMarketplaceView = () => {
    ) : ( filteredItems.map((item) => ( - + )) )} diff --git a/webview-ui/src/components/menu/Navbar.tsx b/webview-ui/src/components/menu/Navbar.tsx index 7b960485..c9f4999f 100644 --- a/webview-ui/src/components/menu/Navbar.tsx +++ b/webview-ui/src/components/menu/Navbar.tsx @@ -1,9 +1,9 @@ +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import { HistoryIcon, PlusIcon, SettingsIcon, UserCircleIcon } from "lucide-react" import { useMemo } from "react" -import { useExtensionState } from "../../context/ExtensionStateContext" -import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" -import HeroTooltip from "../common/HeroTooltip" import { TaskServiceClient } from "@/services/grpc-client" +import { useExtensionState } from "../../context/ExtensionStateContext" +import HeroTooltip from "../common/HeroTooltip" // Custom MCP Server Icon component using VSCode codicon const McpServerIcon = ({ className, size }: { className?: string; size?: number }) => ( @@ -66,20 +66,20 @@ export const Navbar = () => { return (
    ) } diff --git a/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx index ab0acac5..8c72ac24 100644 --- a/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx +++ b/webview-ui/src/components/settings/providers/LiteLlmProvider.tsx @@ -1,14 +1,15 @@ -import { useState } from "react" import { liteLlmModelInfoSaneDefaults } from "@shared/api" +import { Mode } from "@shared/storage/types" import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" -import { DebouncedTextField } from "../common/DebouncedTextField" +import { useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" -import { normalizeApiConfiguration, getModeSpecificFields } from "../utils/providerUtils" +import { DebouncedTextField } from "../common/DebouncedTextField" import { ModelInfoView } from "../common/ModelInfoView" import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { Mode } from "@shared/storage/types" + /** * Props for the LiteLlmProvider component */ @@ -39,17 +40,17 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite handleFieldChange("liteLlmBaseUrl", value)} + placeholder={"Default: http://localhost:4000"} style={{ width: "100%" }} - type="url" - placeholder={"Default: http://localhost:4000"}> + type="url"> Base URL (optional) handleFieldChange("liteLlmApiKey", value)} + placeholder="Default: noop" style={{ width: "100%" }} - type="password" - placeholder="Default: noop"> + type="password"> API Key handleModeFieldChange({ plan: "planModeLiteLlmModelId", act: "actModeLiteLlmModelId" }, value, currentMode) } - style={{ width: "100%" }} - placeholder={"e.g. anthropic/claude-sonnet-4-20250514"}> + placeholder={"e.g. anthropic/claude-sonnet-4-20250514"} + style={{ width: "100%" }}> Model ID @@ -82,32 +83,30 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite )}
    - <> - -

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

    - + +

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

    setModelConfigurationSelected((val) => !val)} style={{ color: getAsVar(VSC_DESCRIPTION_FOREGROUND), display: "flex", margin: "10px 0", cursor: "pointer", alignItems: "center", - }} - onClick={() => setModelConfigurationSelected((val) => !val)}> + }}> { const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } modelInfo.contextWindow = Number(value) @@ -155,7 +153,8 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Context Window Size { const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } modelInfo.maxTokens = Number(value) @@ -174,7 +172,8 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Max Output Tokens
    @@ -189,7 +188,7 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite const modelInfo = liteLlmModelInfo ? liteLlmModelInfo : { ...liteLlmModelInfoSaneDefaults } // Check if the input ends with a decimal point or has trailing zeros after decimal - const shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0")) + const _shouldPreserveFormat = value.endsWith(".") || (value.includes(".") && value.endsWith("0")) modelInfo.temperature = value === "" ? liteLlmModelInfoSaneDefaults.temperature : parseFloat(value) @@ -219,7 +218,7 @@ export const LiteLlmProvider = ({ showModelOptions, isPopup, currentMode }: Lite

    {showModelOptions && ( - + )}
    ) diff --git a/webview-ui/src/components/settings/providers/MistralProvider.tsx b/webview-ui/src/components/settings/providers/MistralProvider.tsx index 93e0db26..11431aa2 100644 --- a/webview-ui/src/components/settings/providers/MistralProvider.tsx +++ b/webview-ui/src/components/settings/providers/MistralProvider.tsx @@ -1,11 +1,12 @@ import { mistralModels } from "@shared/api" -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" import { Mode } from "@shared/storage/types" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the MistralProvider component */ @@ -37,8 +38,8 @@ export const MistralProvider = ({ showModelOptions, isPopup, currentMode }: Mist {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -46,10 +47,10 @@ export const MistralProvider = ({ showModelOptions, isPopup, currentMode }: Mist currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )}
    diff --git a/webview-ui/src/components/settings/providers/MoonshotProvider.tsx b/webview-ui/src/components/settings/providers/MoonshotProvider.tsx index 89e8de67..011e6ea1 100644 --- a/webview-ui/src/components/settings/providers/MoonshotProvider.tsx +++ b/webview-ui/src/components/settings/providers/MoonshotProvider.tsx @@ -1,13 +1,13 @@ import { moonshotModels } from "@shared/api" +import { Mode } from "@shared/storage/types" +import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" import { ApiKeyField } from "../common/ApiKeyField" -import { DropdownContainer, ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" +import { DropdownContainer, ModelSelector } from "../common/ModelSelector" import { normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { useState } from "react" -import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" -import { Mode } from "@shared/storage/types" + /** * Props for the MoonshotProvider component */ @@ -35,17 +35,18 @@ export const MoonshotProvider = ({ showModelOptions, isPopup, currentMode }: Moo handleFieldChange("moonshotApiLine", (e.target as any).value)} style={{ minWidth: 130, position: "relative", - }}> + }} + value={apiConfiguration?.moonshotApiLine || "international"}> api.moonshot.ai api.moonshot.cn handleFieldChange("moonshotApiKey", value)} providerName="Moonshot" @@ -54,14 +55,13 @@ export const MoonshotProvider = ({ showModelOptions, isPopup, currentMode }: Moo ? "https://platform.moonshot.cn/console/api-keys" : "https://platform.moonshot.ai/console/api-keys" } - helpText="This key is stored locally and only used to make API requests from this extension." /> {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -69,10 +69,10 @@ export const MoonshotProvider = ({ showModelOptions, isPopup, currentMode }: Moo currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )}
    diff --git a/webview-ui/src/components/settings/providers/NebiusProvider.tsx b/webview-ui/src/components/settings/providers/NebiusProvider.tsx index 45d7a031..d63f0af5 100644 --- a/webview-ui/src/components/settings/providers/NebiusProvider.tsx +++ b/webview-ui/src/components/settings/providers/NebiusProvider.tsx @@ -1,11 +1,12 @@ import { nebiusModels } from "@shared/api" +import { Mode } from "@shared/storage/types" +import { useExtensionState } from "@/context/ExtensionStateContext" import { ApiKeyField } from "../common/ApiKeyField" -import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" import { normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { Mode } from "@shared/storage/types" + /** * Props for the NebiusProvider component */ @@ -27,18 +28,18 @@ export const NebiusProvider = ({ showModelOptions, isPopup, currentMode }: Nebiu 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.)" /> {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -46,10 +47,10 @@ export const NebiusProvider = ({ showModelOptions, isPopup, currentMode }: Nebiu currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )}
    diff --git a/webview-ui/src/components/settings/providers/OllamaProvider.tsx b/webview-ui/src/components/settings/providers/OllamaProvider.tsx index f57f2c88..7161cbd4 100644 --- a/webview-ui/src/components/settings/providers/OllamaProvider.tsx +++ b/webview-ui/src/components/settings/providers/OllamaProvider.tsx @@ -116,7 +116,7 @@ export const OllamaProvider = ({ showModelOptions, isPopup, currentMode }: Ollam onChange={(value) => { // Convert to number, with validation const numValue = parseInt(value, 10) - if (!isNaN(numValue) && numValue > 0) { + if (!Number.isNaN(numValue) && numValue > 0) { handleFieldChange("requestTimeoutMs", numValue) } }} diff --git a/webview-ui/src/components/settings/providers/OpenAICompatible.tsx b/webview-ui/src/components/settings/providers/OpenAICompatible.tsx index 08a485eb..d2df3519 100644 --- a/webview-ui/src/components/settings/providers/OpenAICompatible.tsx +++ b/webview-ui/src/components/settings/providers/OpenAICompatible.tsx @@ -1,17 +1,18 @@ -import { ApiConfiguration, azureOpenAiDefaultApiVersion, openAiModelInfoSaneDefaults } from "@shared/api" +import { azureOpenAiDefaultApiVersion, openAiModelInfoSaneDefaults } from "@shared/api" import { OpenAiModelsRequest } from "@shared/proto/cline/models" -import { ModelsServiceClient } from "@/services/grpc-client" -import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" +import { Mode } from "@shared/storage/types" 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 { useExtensionState } from "@/context/ExtensionStateContext" +import { ModelsServiceClient } from "@/services/grpc-client" +import { getAsVar, VSC_DESCRIPTION_FOREGROUND } from "@/utils/vscStyles" import { ApiKeyField } from "../common/ApiKeyField" import { BaseUrlField } from "../common/BaseUrlField" -import { normalizeApiConfiguration, getModeSpecificFields } from "../utils/providerUtils" -import { useExtensionState } from "@/context/ExtensionStateContext" +import { DebouncedTextField } from "../common/DebouncedTextField" +import { ModelInfoView } from "../common/ModelInfoView" +import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { Mode } from "@shared/storage/types" + /** * Props for the OpenAICompatibleProvider component */ @@ -74,9 +75,9 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod handleFieldChange("openAiBaseUrl", value) debouncedRefreshOpenAiModels(value, apiConfiguration?.openAiApiKey) }} + placeholder={"Enter base URL..."} style={{ width: "100%", marginBottom: 10 }} - type="url" - placeholder={"Enter base URL..."}> + type="url"> Base URL @@ -94,8 +95,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod onChange={(value) => handleModeFieldChange({ plan: "planModeOpenAiModelId", act: "actModeOpenAiModelId" }, value, currentMode) } - style={{ width: "100%", marginBottom: 10 }} - placeholder={"Enter Model ID..."}> + placeholder={"Enter Model ID..."} + style={{ width: "100%", marginBottom: 10 }}> Model ID @@ -122,8 +123,6 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod
    { const currentHeaders = apiConfiguration?.openAiHeaders ?? {} if (newValue && newValue !== key) { @@ -134,17 +133,19 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod }) } }} + placeholder="Header name" + style={{ width: "40%" }} /> { handleFieldChange("openAiHeaders", { ...(apiConfiguration?.openAiHeaders ?? {}), [key]: newValue, }) }} + placeholder="Header value" + style={{ width: "40%" }} /> handleFieldChange("azureApiVersion", value)} label="Set Azure API version" + onChange={(value) => handleFieldChange("azureApiVersion", value)} placeholder={`Default: ${azureOpenAiDefaultApiVersion}`} />
    setModelConfigurationSelected((val) => !val)} style={{ color: getAsVar(VSC_DESCRIPTION_FOREGROUND), display: "flex", margin: "10px 0", cursor: "pointer", alignItems: "center", - }} - onClick={() => setModelConfigurationSelected((val) => !val)}> + }}> { const isChecked = e.target.checked === true - let modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } + const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.supportsImages = isChecked handleModeFieldChange( { plan: "planModeOpenAiModelInfo", act: "actModeOpenAiModelInfo" }, @@ -246,7 +247,6 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod ? openAiModelInfo.contextWindow.toString() : (openAiModelInfoSaneDefaults.contextWindow?.toString() ?? "") } - style={{ flex: 1 }} onChange={(value) => { const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.contextWindow = Number(value) @@ -255,7 +255,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Context Window Size @@ -265,7 +266,6 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod ? openAiModelInfo.maxTokens.toString() : (openAiModelInfoSaneDefaults.maxTokens?.toString() ?? "") } - style={{ flex: 1 }} onChange={(value) => { const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.maxTokens = Number(value) @@ -274,7 +274,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Max Output Tokens
    @@ -286,7 +287,6 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod ? openAiModelInfo.inputPrice.toString() : (openAiModelInfoSaneDefaults.inputPrice?.toString() ?? "") } - style={{ flex: 1 }} onChange={(value) => { const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.inputPrice = Number(value) @@ -295,7 +295,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Input Price / 1M tokens
    @@ -305,7 +306,6 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod ? openAiModelInfo.outputPrice.toString() : (openAiModelInfoSaneDefaults.outputPrice?.toString() ?? "") } - style={{ flex: 1 }} onChange={(value) => { const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults } modelInfo.outputPrice = Number(value) @@ -314,7 +314,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod modelInfo, currentMode, ) - }}> + }} + style={{ flex: 1 }}> Output Price / 1M tokens
    @@ -363,7 +364,7 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod

    {showModelOptions && ( - + )}
    ) diff --git a/webview-ui/src/components/settings/providers/OpenAINative.tsx b/webview-ui/src/components/settings/providers/OpenAINative.tsx index b9d93949..fdc90bd8 100644 --- a/webview-ui/src/components/settings/providers/OpenAINative.tsx +++ b/webview-ui/src/components/settings/providers/OpenAINative.tsx @@ -1,11 +1,12 @@ -import { ApiConfiguration, openAiNativeModels } from "@shared/api" -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" +import { openAiNativeModels } from "@shared/api" import { Mode } from "@shared/storage/types" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the OpenAINativeProvider component */ @@ -37,8 +38,8 @@ export const OpenAINativeProvider = ({ showModelOptions, isPopup, currentMode }: {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -46,10 +47,10 @@ export const OpenAINativeProvider = ({ showModelOptions, isPopup, currentMode }: currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )}
    diff --git a/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx b/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx index f84249bb..00042722 100644 --- a/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx +++ b/webview-ui/src/components/settings/providers/OpenRouterProvider.tsx @@ -1,15 +1,16 @@ -import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeLink, VSCodeButton } from "@vscode/webview-ui-toolkit/react" +import { EmptyRequest } from "@shared/proto/cline/common" +import { Mode } from "@shared/storage/types" +import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeLink, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { AccountServiceClient } from "@/services/grpc-client" +import { useOpenRouterKeyInfo } from "../../ui/hooks/useOpenRouterKeyInfo" import { DebouncedTextField } from "../common/DebouncedTextField" import { DropdownContainer } from "../common/ModelSelector" -import { useState } from "react" -import { AccountServiceClient } from "@/services/grpc-client" -import { EmptyRequest } from "@shared/proto/cline/common" -import { useOpenRouterKeyInfo } from "../../ui/hooks/useOpenRouterKeyInfo" import OpenRouterModelPicker, { OPENROUTER_MODEL_PICKER_Z_INDEX } from "../OpenRouterModelPicker" import { formatPrice } from "../utils/pricingUtils" -import { useExtensionState } from "@/context/ExtensionStateContext" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { Mode } from "@shared/storage/types" + /** * Component to display OpenRouter balance information */ @@ -32,7 +33,6 @@ const OpenRouterBalanceDisplay = ({ apiKey }: { apiKey: string }) => { return ( { fontWeight: 500, paddingLeft: 4, cursor: "pointer", - }}> + }} + title={`Remaining balance: ${formattedBalance}\nLimit: ${formatPrice(keyInfo.limit)}\nUsage: ${formatPrice(keyInfo.usage)}`}> Balance: {formattedBalance} ) @@ -70,9 +71,9 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O handleFieldChange("openRouterApiKey", value)} + placeholder="Enter API Key..." style={{ width: "100%" }} - type="password" - placeholder="Enter API Key..."> + type="password">
    OpenRouter API Key {apiConfiguration?.openRouterApiKey && ( @@ -82,6 +83,7 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O {!apiConfiguration?.openRouterApiKey && ( { try { await AccountServiceClient.openrouterAuthClicked(EmptyRequest.create()) @@ -89,8 +91,7 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O console.error("Failed to open OpenRouter auth:", error) } }} - style={{ margin: "5px 0 0 0" }} - appearance="secondary"> + style={{ margin: "5px 0 0 0" }}> Get OpenRouter API Key )} @@ -107,7 +108,6 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O {showModelOptions && ( <> { const isChecked = e.target.checked === true @@ -115,7 +115,8 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O if (!isChecked) { handleFieldChange("openRouterProviderSorting", "") } - }}> + }} + style={{ marginTop: -10 }}> Sort underlying provider routing @@ -123,11 +124,11 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O
    { handleFieldChange("openRouterProviderSorting", e.target.value) - }}> + }} + style={{ width: "100%", marginTop: 3 }} + value={apiConfiguration?.openRouterProviderSorting}> Default Price Throughput @@ -147,7 +148,7 @@ export const OpenRouterProvider = ({ showModelOptions, isPopup, currentMode }: O
    )} - + )}
    diff --git a/webview-ui/src/components/settings/providers/QwenProvider.tsx b/webview-ui/src/components/settings/providers/QwenProvider.tsx index 731d6834..ea74a7d2 100644 --- a/webview-ui/src/components/settings/providers/QwenProvider.tsx +++ b/webview-ui/src/components/settings/providers/QwenProvider.tsx @@ -1,15 +1,15 @@ import { internationalQwenModels, mainlandQwenModels, QwenApiRegions } from "@shared/api" -import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" -import { ApiKeyField } from "../common/ApiKeyField" -import { ModelSelector, DropdownContainer } from "../common/ModelSelector" -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" import { Mode } from "@shared/storage/types" +import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import { useMemo } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { DROPDOWN_Z_INDEX } from "../ApiOptions" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelInfoView } from "../common/ModelInfoView" +import { DropdownContainer, ModelSelector } from "../common/ModelSelector" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" const SUPPORTED_THINKING_MODELS = [ "qwen3-235b-a22b", @@ -60,12 +60,12 @@ export const QwenProvider = ({ showModelOptions, isPopup, currentMode }: QwenPro handleFieldChange("qwenApiLine", e.target.value as QwenApiRegions)} style={{ minWidth: 130, position: "relative", - }}> + }} + value={apiConfiguration?.qwenApiLine || qwenApiOptions[0]}> {qwenApiOptions.map((line) => ( {line.charAt(0).toUpperCase() + line.slice(1)} API @@ -93,8 +93,8 @@ export const QwenProvider = ({ showModelOptions, isPopup, currentMode }: QwenPro {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -102,15 +102,15 @@ export const QwenProvider = ({ showModelOptions, isPopup, currentMode }: QwenPro currentMode, ) } - label="Model" + selectedModelId={selectedModelId} 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 ce2198db..cb81f66a 100644 --- a/webview-ui/src/components/settings/providers/RequestyProvider.tsx +++ b/webview-ui/src/components/settings/providers/RequestyProvider.tsx @@ -1,11 +1,11 @@ import { Mode } from "@shared/storage/types" +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" +import { useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" import { ApiKeyField } from "../common/ApiKeyField" +import { DebouncedTextField } from "../common/DebouncedTextField" import RequestyModelPicker from "../RequestyModelPicker" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { useState } from "react" -import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" -import { DebouncedTextField } from "../common/DebouncedTextField" /** * Props for the RequestyProvider component @@ -51,12 +51,12 @@ export const RequestyProvider = ({ showModelOptions, isPopup, currentMode }: Req onChange={(value) => { handleFieldChange("requestyBaseUrl", value) }} + placeholder="Custom base URL" style={{ width: "100%", marginBottom: 5 }} type="url" - placeholder="Custom base URL" /> )} - {showModelOptions && } + {showModelOptions && } ) } diff --git a/webview-ui/src/components/settings/providers/SambanovaProvider.tsx b/webview-ui/src/components/settings/providers/SambanovaProvider.tsx index 8c0113e3..0b99b88d 100644 --- a/webview-ui/src/components/settings/providers/SambanovaProvider.tsx +++ b/webview-ui/src/components/settings/providers/SambanovaProvider.tsx @@ -1,11 +1,12 @@ -import { ApiConfiguration, sambanovaModels } from "@shared/api" -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" +import { sambanovaModels } from "@shared/api" import { Mode } from "@shared/storage/types" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the SambanovaProvider component */ @@ -37,8 +38,8 @@ export const SambanovaProvider = ({ showModelOptions, isPopup, currentMode }: Sa {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -46,10 +47,10 @@ export const SambanovaProvider = ({ showModelOptions, isPopup, currentMode }: Sa currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )} diff --git a/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx index 8e0da541..5a93e920 100644 --- a/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx +++ b/webview-ui/src/components/settings/providers/SapAiCoreProvider.tsx @@ -1,12 +1,13 @@ import { sapAiCoreModels } from "@shared/api" +import { Mode } from "@shared/storage/types" import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" import { DebouncedTextField } from "../common/DebouncedTextField" -import { ModelSelector } from "../common/ModelSelector" import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" import { normalizeApiConfiguration } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { Mode } from "@shared/storage/types" + /** * Props for the SapAiCoreProvider component */ @@ -30,9 +31,9 @@ export const SapAiCoreProvider = ({ showModelOptions, isPopup, currentMode }: Sa handleFieldChange("sapAiCoreClientId", value)} + placeholder="Enter AI Core Client Id..." style={{ width: "100%" }} - type="password" - placeholder="Enter AI Core Client Id..."> + type="password"> AI Core Client Id {apiConfiguration?.sapAiCoreClientId && ( @@ -44,9 +45,9 @@ export const SapAiCoreProvider = ({ showModelOptions, isPopup, currentMode }: Sa handleFieldChange("sapAiCoreClientSecret", value)} + placeholder="Enter AI Core Client Secret..." style={{ width: "100%" }} - type="password" - placeholder="Enter AI Core Client Secret..."> + type="password"> AI Core Client Secret {apiConfiguration?.sapAiCoreClientSecret && ( @@ -58,24 +59,24 @@ export const SapAiCoreProvider = ({ showModelOptions, isPopup, currentMode }: Sa handleFieldChange("sapAiCoreBaseUrl", value)} - style={{ width: "100%" }} - placeholder="Enter AI Core Base URL..."> + placeholder="Enter AI Core Base URL..." + style={{ width: "100%" }}> AI Core Base URL handleFieldChange("sapAiCoreTokenUrl", value)} - style={{ width: "100%" }} - placeholder="Enter AI Core Auth URL..."> + placeholder="Enter AI Core Auth URL..." + style={{ width: "100%" }}> AI Core Auth URL handleFieldChange("sapAiResourceGroup", value)} - style={{ width: "100%" }} - placeholder="Enter AI Core Resource Group..."> + placeholder="Enter AI Core Resource Group..." + style={{ width: "100%" }}> AI Core Resource Group @@ -96,8 +97,8 @@ export const SapAiCoreProvider = ({ showModelOptions, isPopup, currentMode }: Sa {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -105,10 +106,10 @@ export const SapAiCoreProvider = ({ showModelOptions, isPopup, currentMode }: Sa currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> - + )} diff --git a/webview-ui/src/components/settings/providers/TogetherProvider.tsx b/webview-ui/src/components/settings/providers/TogetherProvider.tsx index 5177a283..ce487b40 100644 --- a/webview-ui/src/components/settings/providers/TogetherProvider.tsx +++ b/webview-ui/src/components/settings/providers/TogetherProvider.tsx @@ -1,9 +1,10 @@ -import { DebouncedTextField } from "../common/DebouncedTextField" -import { ApiKeyField } from "../common/ApiKeyField" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { getModeSpecificFields } from "../utils/providerUtils" import { Mode } from "@shared/storage/types" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { ApiKeyField } from "../common/ApiKeyField" +import { DebouncedTextField } from "../common/DebouncedTextField" +import { getModeSpecificFields } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the TogetherProvider component */ @@ -34,8 +35,8 @@ export const TogetherProvider = ({ showModelOptions, isPopup, currentMode }: Tog onChange={(value) => handleModeFieldChange({ plan: "planModeTogetherModelId", act: "actModeTogetherModelId" }, value, currentMode) } - style={{ width: "100%" }} - placeholder={"Enter Model ID..."}> + placeholder={"Enter Model ID..."} + style={{ width: "100%" }}> Model ID

    { return (

    - + {vsCodeLmModels.length > 0 ? ( { const value = (e.target as HTMLInputElement).value if (!value) { @@ -66,7 +62,12 @@ export const VSCodeLmProvider = ({ currentMode }: VSCodeLmProviderProps) => { currentMode, ) }} - style={{ width: "100%" }}> + style={{ width: "100%" }} + value={ + vsCodeLmModelSelector + ? `${vsCodeLmModelSelector.vendor ?? ""}/${vsCodeLmModelSelector.family ?? ""}` + : "" + }> Select a model... {vsCodeLmModels.map((model) => ( diff --git a/webview-ui/src/components/settings/providers/VertexProvider.tsx b/webview-ui/src/components/settings/providers/VertexProvider.tsx index f8abf4eb..45f60ae7 100644 --- a/webview-ui/src/components/settings/providers/VertexProvider.tsx +++ b/webview-ui/src/components/settings/providers/VertexProvider.tsx @@ -1,14 +1,15 @@ 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" import { Mode } from "@shared/storage/types" +import { VSCodeDropdown, VSCodeLink, VSCodeOption } from "@vscode/webview-ui-toolkit/react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { DROPDOWN_Z_INDEX, DropdownContainer } from "../ApiOptions" +import { DebouncedTextField } from "../common/DebouncedTextField" +import { ModelInfoView } from "../common/ModelInfoView" +import { ModelSelector } from "../common/ModelSelector" +import ThinkingBudgetSlider from "../ThinkingBudgetSlider" +import { normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the VertexProvider component */ @@ -52,20 +53,20 @@ export const VertexProvider = ({ showModelOptions, isPopup, currentMode }: Verte handleFieldChange("vertexProjectId", value)} - style={{ width: "100%" }} - placeholder="Enter Project ID..."> + placeholder="Enter Project ID..." + style={{ width: "100%" }}> Google Cloud Project ID - + handleFieldChange("vertexRegion", e.target.value)} style={{ width: "100%" }} - onChange={(e: any) => handleFieldChange("vertexRegion", e.target.value)}> + value={apiConfiguration?.vertexRegion || ""}> Select a region... us-east5 us-central1 @@ -98,8 +99,8 @@ export const VertexProvider = ({ showModelOptions, isPopup, currentMode }: Verte {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -107,15 +108,15 @@ export const VertexProvider = ({ showModelOptions, isPopup, currentMode }: Verte currentMode, ) } - label="Model" + selectedModelId={selectedModelId} zIndex={DROPDOWN_Z_INDEX - 2} /> {SUPPORTED_THINKING_MODELS.includes(selectedModelId) && ( - + )} - + )}
    diff --git a/webview-ui/src/components/settings/providers/XaiProvider.tsx b/webview-ui/src/components/settings/providers/XaiProvider.tsx index f487ddf8..80620c7c 100644 --- a/webview-ui/src/components/settings/providers/XaiProvider.tsx +++ b/webview-ui/src/components/settings/providers/XaiProvider.tsx @@ -1,14 +1,15 @@ import { xaiModels } from "@shared/api" +import { Mode } from "@shared/storage/types" import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import { useState } from "react" -import { ApiKeyField } from "../common/ApiKeyField" -import { ModelSelector, DropdownContainer } from "../common/ModelSelector" -import { ModelInfoView } from "../common/ModelInfoView" -import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils" -import { DROPDOWN_Z_INDEX } from "../ApiOptions" -import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" import { useExtensionState } from "@/context/ExtensionStateContext" -import { Mode } from "@shared/storage/types" +import { DROPDOWN_Z_INDEX } from "../ApiOptions" +import { ApiKeyField } from "../common/ApiKeyField" +import { ModelInfoView } from "../common/ModelInfoView" +import { DropdownContainer, ModelSelector } from "../common/ModelSelector" +import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils" +import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" + /** * Props for the XaiProvider component */ @@ -55,8 +56,8 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi {showModelOptions && ( <> handleModeFieldChange( { plan: "planModeApiModelId", act: "actModeApiModelId" }, @@ -64,13 +65,12 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi currentMode, ) } - label="Model" + selectedModelId={selectedModelId} /> {selectedModelId && selectedModelId.includes("3-mini") && ( <> { const isChecked = e.target.checked === true @@ -82,7 +82,8 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi currentMode, ) } - }}> + }} + style={{ marginTop: 0 }}> Modify reasoning effort @@ -94,15 +95,15 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi { handleModeFieldChange( { plan: "planModeReasoningEffort", act: "actModeReasoningEffort" }, e.target.value, currentMode, ) - }}> + }} + style={{ width: "100%", marginTop: 3 }} + value={modeFields.reasoningEffort || "high"}> low high @@ -121,7 +122,7 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi )} - + )} diff --git a/webview-ui/src/components/settings/providers/ZAiProvider.tsx b/webview-ui/src/components/settings/providers/ZAiProvider.tsx index c0a9ee12..e2016f13 100644 --- a/webview-ui/src/components/settings/providers/ZAiProvider.tsx +++ b/webview-ui/src/components/settings/providers/ZAiProvider.tsx @@ -1,4 +1,4 @@ -import { ApiConfiguration, internationalZAiModels, mainlandZAiModels } from "@shared/api" +import { internationalZAiModels, mainlandZAiModels } from "@shared/api" import { Mode } from "@shared/storage/types" import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" import { useMemo } from "react" diff --git a/webview-ui/src/components/settings/sections/AboutSection.tsx b/webview-ui/src/components/settings/sections/AboutSection.tsx index 4ea7464c..4d2e7a9c 100644 --- a/webview-ui/src/components/settings/sections/AboutSection.tsx +++ b/webview-ui/src/components/settings/sections/AboutSection.tsx @@ -1,5 +1,5 @@ -import Section from "../Section" import { VSCodeLink } from "@vscode/webview-ui-toolkit/react" +import Section from "../Section" interface AboutSectionProps { version: string @@ -14,7 +14,7 @@ const AboutSection = ({ version, renderSectionHeader }: AboutSectionProps) => {

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

    diff --git a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx index 0522e84e..8ed89864 100644 --- a/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx +++ b/webview-ui/src/components/settings/sections/ApiConfigurationSection.tsx @@ -1,14 +1,15 @@ +import { UpdateSettingsRequest } from "@shared/proto/cline/state" +import { Mode } from "@shared/storage/types" import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" +import { useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { StateServiceClient } from "@/services/grpc-client" import { TabButton } from "../../mcp/configuration/McpConfigurationView" import ApiOptions from "../ApiOptions" import Section from "../Section" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { StateServiceClient } from "@/services/grpc-client" -import { UpdateSettingsRequest } from "@shared/proto/cline/state" -import { useState } from "react" import { syncModeConfigurations } from "../utils/providerUtils" import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers" -import { Mode } from "@shared/storage/types" + interface ApiConfigurationSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null } @@ -26,9 +27,9 @@ const ApiConfigurationSection = ({ renderSectionHeader }: ApiConfigurationSectio
    setCurrentTab("plan")} - disabled={currentTab === "plan"} style={{ opacity: 1, cursor: "pointer", @@ -36,9 +37,9 @@ const ApiConfigurationSection = ({ renderSectionHeader }: ApiConfigurationSectio Plan Mode setCurrentTab("act")} - disabled={currentTab === "act"} style={{ opacity: 1, cursor: "pointer", @@ -49,17 +50,17 @@ const ApiConfigurationSection = ({ renderSectionHeader }: ApiConfigurationSectio {/* Content container */}
    - +
    ) : ( - + )}
    { const checked = e.target.checked === true try { diff --git a/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx index 7e562566..a838565f 100644 --- a/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/BrowserSettingsSection.tsx @@ -1,13 +1,13 @@ -import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { EmptyRequest, StringRequest } from "@shared/proto/cline/common" +import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react" 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/cline/common" -import { updateBrowserSetting } from "../utils/settingsHandlers" import { DebouncedTextField } from "../common/DebouncedTextField" import Section from "../Section" +import { updateBrowserSetting } from "../utils/settingsHandlers" interface BrowserSettingsSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null @@ -22,7 +22,9 @@ const ConnectionStatusIndicator = ({ isConnected: boolean | null remoteBrowserEnabled?: boolean }) => { - if (!remoteBrowserEnabled) return null + if (!remoteBrowserEnabled) { + return null + } return ( @@ -190,6 +192,7 @@ export const BrowserSettingsSection: React.FC = ({
    handleViewportChange(event as Event)} style={{ width: "100%" }} value={ Object.entries(BROWSER_VIEWPORT_PRESETS).find(([_, size]) => { @@ -199,8 +202,7 @@ export const BrowserSettingsSection: React.FC = ({ typedSize.height === browserSettings.viewport.height ) })?.[0] - } - onChange={(event) => handleViewportChange(event as Event)}> + }> {Object.entries(BROWSER_VIEWPORT_PRESETS).map(([name]) => ( {name} @@ -275,17 +277,17 @@ export const BrowserSettingsSection: React.FC = ({
    updateBrowserSetting("remoteBrowserHost", value || undefined)} placeholder="http://localhost:9222" style={{ width: "100%", marginBottom: 8 }} - onChange={(value) => updateBrowserSetting("remoteBrowserHost", value || undefined)} /> {shouldShowRelaunchButton && (
    + onClick={relaunchChromeDebugMode} + style={{ flex: 1 }}> {debugMode ? "Launching Browser..." : "Launch Browser with Debug Mode"}
    @@ -329,9 +331,9 @@ export const BrowserSettingsSection: React.FC = ({ updateBrowserSetting("chromeExecutablePath", value)} placeholder="e.g., /usr/bin/google-chrome or C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" style={{ width: "100%" }} - onChange={(value) => updateBrowserSetting("chromeExecutablePath", value)} />

    = ({ updateBrowserSetting("customArgs", value)} placeholder="e.g., --no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu --no-first-run --no-zygote" style={{ width: "100%" }} - onChange={(value) => updateBrowserSetting("customArgs", value)} />

    Promise @@ -12,14 +12,14 @@ const DebugSection = ({ onResetState, renderSectionHeader }: DebugSectionProps) {renderSectionHeader("debug")}

    onResetState()} className="mt-[5px] w-auto" + onClick={() => onResetState()} style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> Reset Workspace State onResetState(true)} className="mt-[5px] w-auto" + onClick={() => onResetState(true)} style={{ backgroundColor: "var(--vscode-errorForeground)", color: "black" }}> Reset Global State diff --git a/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx index 09e97423..7f5b45c1 100644 --- a/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/FeatureSettingsSection.tsx @@ -1,11 +1,11 @@ -import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" -import { useExtensionState } from "@/context/ExtensionStateContext" -import { memo } from "react" -import { OpenaiReasoningEffort } from "@shared/storage/types" -import { updateSetting } from "../utils/settingsHandlers" import { McpDisplayMode } from "@shared/McpDisplayMode" +import { OpenaiReasoningEffort } from "@shared/storage/types" +import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import { memo } from "react" import McpDisplayModeDropdown from "@/components/mcp/chat-display/McpDisplayModeDropdown" +import { useExtensionState } from "@/context/ExtensionStateContext" import Section from "../Section" +import { updateSetting } from "../utils/settingsHandlers" interface FeatureSettingsSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null @@ -61,15 +61,15 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP
    updateSetting("mcpDisplayMode", newMode)} className="w-full" + id="mcp-display-mode-dropdown" + onChange={(newMode: McpDisplayMode) => updateSetting("mcpDisplayMode", newMode)} + value={mcpDisplayMode} />

    Controls how MCP responses are displayed: plain text, rich formatting with links/images, or markdown @@ -91,18 +91,18 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP

    { const newValue = e.target.currentValue as OpenaiReasoningEffort handleReasoningEffortChange(newValue) - }} - className="w-full"> + }}> Low Medium High @@ -143,23 +143,23 @@ const FeatureSettingsSection = ({ renderSectionHeader }: FeatureSettingsSectionP {focusChainFeatureFlagEnabled && focusChainSettings?.enabled && (
    { const value = parseInt(e.target.value, 10) - if (!isNaN(value) && value >= 1 && value <= 100) { + if (!Number.isNaN(value) && value >= 1 && value <= 100) { updateSetting("focusChainSettings", { ...focusChainSettings, remindClineInterval: value, }) } }} - className="w-20" + value={String(focusChainSettings?.remindClineInterval || 6)} />

    Interval (in messages) to remind Cline about it's focus chain checklist (1-100). Lower values diff --git a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx index 72fd85f4..f8f73b76 100644 --- a/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/GeneralSettingsSection.tsx @@ -1,8 +1,8 @@ import { VSCodeCheckbox, VSCodeLink } from "@vscode/webview-ui-toolkit/react" import { useExtensionState } from "@/context/ExtensionStateContext" -import { updateSetting } from "../utils/settingsHandlers" import PreferredLanguageSetting from "../PreferredLanguageSetting" import Section from "../Section" +import { updateSetting } from "../utils/settingsHandlers" interface GeneralSettingsSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null @@ -19,8 +19,8 @@ const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionP

    { const checked = e.target.checked === true updateSetting("telemetrySetting", checked ? "enabled" : "disabled") @@ -30,11 +30,11 @@ const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionP

    Help improve Cline by sending usage data and error reports. No code, prompts, or personal information are ever sent. See our{" "} - + telemetry overview {" "} and{" "} - + privacy policy {" "} for more details. diff --git a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx index ed2a589b..867e0beb 100644 --- a/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx +++ b/webview-ui/src/components/settings/sections/TerminalSettingsSection.tsx @@ -1,12 +1,12 @@ -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, StringRequest } from "@shared/proto/cline/common" -import Section from "../Section" -import { updateSetting } from "../utils/settingsHandlers" +import { StringRequest } from "@shared/proto/cline/common" import { UpdateTerminalConnectionTimeoutResponse } from "@shared/proto/index.cline" +import { VSCodeCheckbox, VSCodeDropdown, VSCodeOption, VSCodeTextField } from "@vscode/webview-ui-toolkit/react" +import React, { useState } from "react" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { StateServiceClient } from "../../../services/grpc-client" +import Section from "../Section" +import TerminalOutputLineLimitSlider from "../TerminalOutputLineLimitSlider" +import { updateSetting } from "../utils/settingsHandlers" interface TerminalSettingsSectionProps { renderSectionHeader: (tabId: string) => JSX.Element | null @@ -26,7 +26,7 @@ export const TerminalSettingsSection: React.FC = ( setInputValue(value) const seconds = parseFloat(value) - if (isNaN(seconds) || seconds <= 0) { + if (Number.isNaN(seconds) || seconds <= 0) { setInputError("Please enter a positive number") return } @@ -80,18 +80,18 @@ export const TerminalSettingsSection: React.FC = (

    {renderSectionHeader("terminal")}
    -
    +
    -

    I can do all kinds of tasks thanks to breakthroughs in{" "} - + Claude 4 Sonnet's agentic coding capabilities and access to tools that let me create & edit files, explore complex projects, use @@ -54,15 +54,15 @@ const WelcomeView = memo(() => { 3.7 Sonnet.

    - + Get Started for Free {!showApiOptions && ( setShowApiOptions(!showApiOptions)} - className="mt-2.5 w-full"> + className="mt-2.5 w-full" + onClick={() => setShowApiOptions(!showApiOptions)}> Use your own API key )} @@ -70,8 +70,8 @@ const WelcomeView = memo(() => {
    {showApiOptions && (
    - - + + Let's go!
    diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 6a9d447f..1e5e8cf0 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -4,21 +4,21 @@ import "../../../src/shared/webview/types" import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings" import { findLastIndex } from "@shared/array" import { DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings" -import { DEFAULT_FOCUS_CHAIN_SETTINGS } from "@shared/FocusChainSettings" import { DEFAULT_PLATFORM, type ExtensionState } from "@shared/ExtensionMessage" +import { DEFAULT_FOCUS_CHAIN_SETTINGS } from "@shared/FocusChainSettings" import { DEFAULT_MCP_DISPLAY_MODE } from "@shared/McpDisplayMode" import type { UserInfo } from "@shared/proto/cline/account" import { EmptyRequest, StringRequest } from "@shared/proto/cline/common" import type { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models" -import { type TerminalProfile, UpdateSettingsRequest } from "@shared/proto/cline/state" +import { type TerminalProfile } from "@shared/proto/cline/state" import { WebviewProviderType as WebviewProviderTypeEnum, WebviewProviderTypeRequest } from "@shared/proto/cline/ui" import { convertProtoToClineMessage } from "@shared/proto-conversions/cline-message" import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion" import { - groqDefaultModelId, - groqModels, basetenDefaultModelId, basetenModels, + groqDefaultModelId, + groqModels, type ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo, @@ -26,13 +26,7 @@ import { requestyDefaultModelInfo, } from "../../../src/shared/api" import type { McpMarketplaceCatalog, McpServer, McpViewTab } from "../../../src/shared/mcp" -import { - FileServiceClient, - McpServiceClient, - ModelsServiceClient, - StateServiceClient, - UiServiceClient, -} from "../services/grpc-client" +import { McpServiceClient, ModelsServiceClient, StateServiceClient, UiServiceClient } from "../services/grpc-client" import { convertTextMateToHljs } from "../utils/textMateToHljs" interface ExtensionStateContextType extends ExtensionState { @@ -213,7 +207,7 @@ export const ExtensionStateContextProvider: React.FC<{ const [totalTasksSize, setTotalTasksSize] = useState(null) const [availableTerminalProfiles, setAvailableTerminalProfiles] = useState([]) - const [openAiModels, setOpenAiModels] = useState([]) + const [openAiModels, _setOpenAiModels] = useState([]) const [requestyModels, setRequestyModels] = useState>({ [requestyDefaultModelId]: requestyDefaultModelInfo, }) diff --git a/webview-ui/src/hooks/useAutoApproveActions.ts b/webview-ui/src/hooks/useAutoApproveActions.ts index e8e8372d..7f58079a 100644 --- a/webview-ui/src/hooks/useAutoApproveActions.ts +++ b/webview-ui/src/hooks/useAutoApproveActions.ts @@ -1,8 +1,8 @@ -import { useCallback } from "react" -import { useExtensionState } from "@/context/ExtensionStateContext" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" +import { useCallback } from "react" import { updateAutoApproveSettings } from "@/components/chat/auto-approve-menu/AutoApproveSettingsAPI" import { ActionMetadata } from "@/components/chat/auto-approve-menu/types" +import { useExtensionState } from "@/context/ExtensionStateContext" export function useAutoApproveActions() { const { autoApprovalSettings } = useExtensionState() @@ -75,7 +75,7 @@ export function useAutoApproveActions() { return } - let newActions = { + const newActions = { ...autoApprovalSettings.actions, [actionId]: value, } @@ -128,8 +128,8 @@ export function useAutoApproveActions() { // Toggle all actions const toggleAll = useCallback( - async (action: ActionMetadata, checked: boolean) => { - let actions = { ...autoApprovalSettings.actions } + async (_action: ActionMetadata, checked: boolean) => { + const actions = { ...autoApprovalSettings.actions } for (const action of Object.keys(actions)) { actions[action as keyof AutoApprovalSettings["actions"]] = checked diff --git a/webview-ui/src/services/grpc-client-base.ts b/webview-ui/src/services/grpc-client-base.ts index edacf8a9..b3a189e4 100644 --- a/webview-ui/src/services/grpc-client-base.ts +++ b/webview-ui/src/services/grpc-client-base.ts @@ -1,5 +1,7 @@ -import { vscode } from "../utils/vscode" +/** biome-ignore-all lint/complexity/noThisInStatic: In static methods, this refers to the constructor (the subclass that invoked the method) when we want to refer to the subclass serviceName. + */ import { v4 as uuidv4 } from "uuid" +import { vscode } from "../utils/vscode" export interface Callbacks { onResponse: (response: TResponse) => void diff --git a/webview-ui/src/utils/__tests__/context-mentions.test.ts b/webview-ui/src/utils/__tests__/context-mentions.test.ts index 42d474f5..f410bc34 100644 --- a/webview-ui/src/utils/__tests__/context-mentions.test.ts +++ b/webview-ui/src/utils/__tests__/context-mentions.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest" +import { describe, expect, it } from "vitest" import { insertMention, insertMentionDirectly } from "../context-mentions" describe("context-mentions", () => { diff --git a/webview-ui/src/utils/__tests__/hooks.spec.ts b/webview-ui/src/utils/__tests__/hooks.spec.ts index 2a1466f1..72cd21c5 100644 --- a/webview-ui/src/utils/__tests__/hooks.spec.ts +++ b/webview-ui/src/utils/__tests__/hooks.spec.ts @@ -1,6 +1,6 @@ import { renderHook } from "@testing-library/react" -import { useShortcut, useMetaKeyDetection } from "../hooks" import { vi } from "vitest" +import { useMetaKeyDetection, useShortcut } from "../hooks" describe("useShortcut", () => { it("should call the callback when the shortcut is pressed", () => { diff --git a/webview-ui/src/utils/__tests__/platformUtils.spec.ts b/webview-ui/src/utils/__tests__/platformUtils.spec.ts index 2938280a..e41a2ddc 100644 --- a/webview-ui/src/utils/__tests__/platformUtils.spec.ts +++ b/webview-ui/src/utils/__tests__/platformUtils.spec.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest" +import { describe, expect, it } from "vitest" import { detectMetaKeyChar } from "../platformUtils" describe("detectMetaKeyChar", () => { diff --git a/webview-ui/src/utils/hooks.ts b/webview-ui/src/utils/hooks.ts index 4a49fd26..3a3dc931 100644 --- a/webview-ui/src/utils/hooks.ts +++ b/webview-ui/src/utils/hooks.ts @@ -1,4 +1,4 @@ -import { useCallback, useRef, useLayoutEffect, useState, useEffect } from "react" +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react" import { detectMetaKeyChar, detectOS, unknown } from "./platformUtils" export const useMetaKeyDetection = (platform: string) => { diff --git a/webview-ui/src/utils/useDebounceEffect.ts b/webview-ui/src/utils/useDebounceEffect.ts index 8f52284a..6d0d9b5d 100644 --- a/webview-ui/src/utils/useDebounceEffect.ts +++ b/webview-ui/src/utils/useDebounceEffect.ts @@ -1,5 +1,5 @@ -import { useEffect, useRef } from "react" import type { DependencyList } from "react" +import { useEffect, useRef } from "react" type VoidFn = () => void diff --git a/webview-ui/tsconfig.app.json b/webview-ui/tsconfig.app.json index 85ce444c..930150d7 100644 --- a/webview-ui/tsconfig.app.json +++ b/webview-ui/tsconfig.app.json @@ -3,8 +3,15 @@ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "target": "ES2020", "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "types": ["vitest/globals", "@testing-library/jest-dom"], + "lib": [ + "ES2020", + "DOM", + "DOM.Iterable" + ], + "types": [ + "vitest/globals", + "@testing-library/jest-dom" + ], "module": "ESNext", "skipLibCheck": true, @@ -24,12 +31,24 @@ /* Aliasing */ "baseUrl": ".", "paths": { - "@/*": ["src/*"], - "@components/*": ["src/components/*"], - "@context/*": ["src/context/*"], - "@shared/*": ["../src/shared/*"], - "@utils/*": ["src/utils/*"] + "@/*": [ + "src/*" + ], + "@components/*": [ + "src/components/*" + ], + "@context/*": [ + "src/context/*" + ], + "@shared/*": [ + "../src/shared/*" + ], + "@utils/*": [ + "src/utils/*" + ] } }, - "include": ["src"] + "include": [ + "src" + ] } diff --git a/webview-ui/tsconfig.json b/webview-ui/tsconfig.json index 88a659fb..a5b06bfb 100644 --- a/webview-ui/tsconfig.json +++ b/webview-ui/tsconfig.json @@ -1,4 +1,11 @@ { "files": [], - "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }] + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.node.json" + } + ] } diff --git a/webview-ui/tsconfig.node.json b/webview-ui/tsconfig.node.json index 50130b3a..1ae38659 100644 --- a/webview-ui/tsconfig.node.json +++ b/webview-ui/tsconfig.node.json @@ -2,7 +2,9 @@ "compilerOptions": { "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "target": "ES2022", - "lib": ["ES2023"], + "lib": [ + "ES2023" + ], "module": "ESNext", "skipLibCheck": true, @@ -20,5 +22,7 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["vite.config.ts"] + "include": [ + "vite.config.ts" + ] } diff --git a/webview-ui/vite.config.ts b/webview-ui/vite.config.ts index 23f4ad3c..e06fd274 100644 --- a/webview-ui/vite.config.ts +++ b/webview-ui/vite.config.ts @@ -1,10 +1,10 @@ /// -import { defineConfig, ViteDevServer, type Plugin } from "vite" +import { writeFileSync } from "node:fs" import tailwindcss from "@tailwindcss/vite" import react from "@vitejs/plugin-react-swc" import { resolve } from "path" -import { writeFileSync } from "node:fs" +import { defineConfig, type Plugin, ViteDevServer } from "vite" // Custom plugin to write the server port to a file const writePortToFile = (): Plugin => {