Merge branch 'main' into i18l-l10n

This commit is contained in:
brownrw8 2025-01-22 15:29:51 -10:00 committed by GitHub
commit 2e95f29572
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 2059 additions and 82 deletions

View file

@ -6,6 +6,12 @@ on:
branches:
- main
# Set default permissions for all jobs
permissions:
contents: read # Needed to check out code
checks: write # Needed to report test results
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
test:
runs-on: ubuntu-latest
@ -51,6 +57,5 @@ jobs:
- name: Prettier / Format Check
run: npm run format
- name: Tests
- name: Extension Tests
run: xvfb-run -a npm run test
if: runner.os == 'Linux'

3
.gitignore vendored
View file

@ -1,7 +1,10 @@
out
dist
node_modules
tmp
.vscode-test/
*.vsix
.DS_Store
pnpm-lock.yaml

17
.husky/pre-commit Executable file
View file

@ -0,0 +1,17 @@
echo "Running pre-commit checks..."
# Run ESLint
echo "Running ESLint..."
npm run lint || {
echo "❌ ESLint check failed. Please fix the errors and try committing again."
exit 1
}
# Run Prettier
echo "Running Prettier..."
npm run format || {
echo "❌ Prettier check failed. Run 'npm run format:fix' to automatically fix formatting issues."
exit 1
}
echo "✅ All checks passed!"

View file

@ -1,5 +1,5 @@
dist/
node_modules
webview-ui/build/
CHANGELOG.md
package-lock.json
*.md
package-lock.json

View file

@ -1,8 +1,14 @@
import { defineConfig } from "@vscode/test-cli"
import path from "path"
export default defineConfig({
files: "out/**/*.test.js",
files: "{out/test/**/*.test.js,src/test/suite/**/*.test.js}",
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
},
workspaceFolder: "test-workspace",
version: "stable",
extensionDevelopmentPath: path.resolve("./"),
launchArgs: ["--disable-extensions"],
})

View file

@ -1,5 +1,13 @@
# Change Log
## [3.2.5]
- Use yellow textfield outline in Plan mode to better distinguish from Act mode
## [3.2.3]
- Add DeepSeek-R1 (deepseek-reasoner) model support with proper parameter handling (thanks @slavakurilyak!)
## [3.2.0]
- Add Plan/Act mode toggle to let you plan tasks with Cline before letting him get to work

1025
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.2.0",
"version": "3.2.5",
"icon": "assets/icons/icon.png",
"galleryBanner": {
"color": "#617A91",
@ -141,6 +141,11 @@
}
},
"description": "Settings for VSCode Language Model API"
},
"cline.mcp.enabled": {
"type": "boolean",
"default": true,
"description": "Include MCP server functionality in AI prompts. When disabled, the AI will not be aware of MCP capabilities. This saves context window tokens."
}
}
}
@ -164,9 +169,11 @@
"start:webview": "cd webview-ui && npm run start",
"build:webview": "cd webview-ui && npm run build",
"test:webview": "cd webview-ui && npm run test",
"publish:marketplace": "vsce publish && ovsx publish"
"publish:marketplace": "vsce publish && ovsx publish",
"prepare": "husky"
},
"devDependencies": {
"@types/chai": "^5.0.1",
"@types/diff": "^5.2.1",
"@types/mocha": "^10.0.7",
"@types/node": "20.x",
@ -176,8 +183,10 @@
"@typescript-eslint/parser": "^7.11.0",
"@vscode/test-cli": "^0.0.9",
"@vscode/test-electron": "^2.4.0",
"chai": "^4.3.10",
"esbuild": "^0.21.5",
"eslint": "^8.57.0",
"husky": "^9.1.7",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"should": "^13.2.3",
@ -204,6 +213,7 @@
"diff": "^5.2.0",
"execa": "^9.5.2",
"fast-deep-equal": "^3.1.3",
"firebase": "^11.2.0",
"get-folder-size": "^5.0.0",
"globby": "^14.0.2",
"isbinaryfile": "^5.0.2",

View file

@ -18,13 +18,15 @@ export class DeepSeekHandler implements ApiHandler {
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const model = this.getModel()
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
max_completion_tokens: this.getModel().info.maxTokens,
temperature: 0,
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
stream: true,
stream_options: { include_usage: true },
// Only set temperature for non-reasoner models
...(model.id === "deepseek-reasoner" ? {} : { temperature: 0 }),
})
for await (const chunk of stream) {

View file

@ -3290,12 +3290,11 @@ export class Cline {
if (this.chatSettings.mode === "plan") {
details += "\nPLAN MODE"
details +=
"\nIn this mode you should focus on information gathering and architecting a solution. If you haven't done so already, it's a good idea to start by reading files to get context and then asking questions."
"\nIn this mode you should focus on information gathering, asking questions, and architecting a solution. Once you have a plan, use the plan_mode_response tool to engage in a conversational back and forth with the user. Do not use the plan_mode_response tool until you've gathered all the information you need e.g. with read_file or ask_followup_question."
details +=
'\n(Remember: You now have access to the plan_mode_response tool, which allows you to engage in a more conversational back and forth with the user rather than jumping into executing the task. If it seems the user wants you to use tools only available in ACT MODE, you should ask the user to "toggle to Act mode" - they will have to manually do this themselves with the Plan/Act toggle button below. You do not have the ability to switch to ACT MODE yourself, and must wait for the user to do it themselves once they are satisfied with the plan.)'
'\n(Remember: If it seems the user wants you to use tools only available in Act Mode, you should ask the user to "toggle to Act mode" (use those words) - they will have to manually do this themselves with the Plan/Act toggle button below. You do not have the ability to switch to Act Mode yourself, and must wait for the user to do it themselves once they are satisfied with the plan.)'
} else {
details += "\nACT MODE"
details += "\n(Remember: You cannot use the plan_mode_response tool.)"
}
return `<environment_details>\n${details.trim()}\n</environment_details>`

View file

@ -177,6 +177,9 @@ Usage:
: ""
}
${
mcpHub.isMcpEnabled()
? `
## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
@ -205,6 +208,9 @@ Usage:
<server_name>server name here</server_name>
<uri>resource URI here</uri>
</access_mcp_resource>
`
: ""
}
## ask_followup_question
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
@ -230,9 +236,9 @@ Your final result description here
</attempt_completion>
## plan_mode_response
Description: Respond to the user's inquiry with a clear answer in an effort to plan a solution to the user's task. This tool should be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. This tool is only available in PLAN MODE. The environment_details will specify the current mode, if it is not PLAN MODE then you should not use this tool. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.
Description: Respond to the user's inquiry in an effort to plan a solution to the user's task. This tool should be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. This tool is only available in PLAN MODE. The environment_details will specify the current mode, if it is not PLAN MODE then you should not use this tool. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.
Parameters:
- response: (required) The response to provide to the user.
- response: (required) The response to provide to the user. Do not try to use tools in this parameter, this is simply a chat response.
Usage:
<plan_mode_response>
<response>Your response here</response>
@ -247,27 +253,7 @@ Usage:
<requires_approval>false</requires_approval>
</execute_command>
## Example 2: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 3: Requesting to access an MCP resource
<access_mcp_resource>
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>
## Example 4: Requesting to create a new file
## Example 2: Requesting to create a new file
<write_to_file>
<path>src/frontend-config.json</path>
@ -289,7 +275,7 @@ Usage:
</content>
</write_to_file>
## Example 6: Requesting to make targeted edits to a file
## Example 3: Requesting to make targeted edits to a file
<replace_in_file>
<path>src/components/App.tsx</path>
@ -323,6 +309,31 @@ return (
>>>>>>> REPLACE
</diff>
</replace_in_file>
${
mcpHub.isMcpEnabled()
? `
## Example 4: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 5: Requesting to access an MCP resource
<access_mcp_resource>
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>`
: ""
}
# Tool Use Guidelines
@ -345,6 +356,9 @@ It is crucial to proceed step-by-step, waiting for the user's message after each
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
${
mcpHub.isMcpEnabled()
? `
====
MCP SERVERS
@ -737,12 +751,13 @@ IMPORTANT: Regardless of what else you see in the MCP settings file, you must de
## Editing MCP Servers
The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' above: ${
mcpHub
.getServers()
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use replace_in_file to make changes to the files.
The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' below: ${
mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use replace_in_file to make changes to the files.
However some MCP servers may be running from installed packages rather than a local repository, in which case it may make more sense to create a new MCP server.
@ -751,7 +766,9 @@ However some MCP servers may be running from installed packages rather than a lo
The user may not always request the use or creation of MCP servers. Instead, they might provide tasks that can be completed with existing tools. While using the MCP SDK to extend your capabilities can be useful, it's important to understand that this is just one specialized type of task you can accomplish. You should only implement MCP servers when the user explicitly requests it (e.g., "add a tool that...").
Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.
`
: ""
}
====
EDITING FILES
@ -834,10 +851,10 @@ ACT MODE V.S. PLAN MODE
In each user message, the environment_details will specify the current mode. There are two modes:
- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_response tool.
- In act mode, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
- In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
- PLAN MODE: In this special mode, you have access to the plan_mode_response tool.
- In plan mode, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before you switch back to ACT MODE to implement the solution.
- In plan mode, you should use the plan_mode_response tool to deliver your response, rather than using <thinking> tags to analyze when to respond. Do not talk about using plan_mode_response - just use it directly to share your thoughts and provide helpful answers.
- In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
- In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_response tool to deliver your response directly, rather than using <thinking> tags to analyze when to respond. Do not talk about using plan_mode_response - just use it directly to share your thoughts and provide helpful answers.
## What is PLAN MODE?
@ -863,7 +880,13 @@ CAPABILITIES
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
: ""
}
${
mcpHub.isMcpEnabled()
? `
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
`
: ""
}
====
@ -884,7 +907,7 @@ RULES
- The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
supportsComputerUse
? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question.${mcpHub.isMcpEnabled() ? "However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action." : ""}`
: ""
}
- NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
@ -892,7 +915,6 @@ RULES
- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
- When using the replace_in_file tool, you must include complete lines in your SEARCH blocks, not partial lines. The system requires exact line matches and cannot match partial lines. For example, if you want to match a line containing "const x = 5;", your SEARCH block must include the entire line, not just "x = 5" or other fragments.
- When using the replace_in_file tool, if you use multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. For example if you need to make changes to both line 10 and line 50, first include the SEARCH/REPLACE block for line 10, followed by the SEARCH/REPLACE block for line 50.
- It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to make a todo app, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.${
@ -900,6 +922,13 @@ RULES
? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
: ""
}
${
mcpHub.isMcpEnabled()
? `
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
`
: ""
}
====

View file

@ -2,6 +2,7 @@ import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import fs from "fs/promises"
import os from "os"
import crypto from "crypto"
import pWaitFor from "p-wait-for"
import * as path from "path"
import * as vscode from "vscode"
@ -12,6 +13,7 @@ import { selectImages } from "../../integrations/misc/process-images"
import { getTheme } from "../../integrations/theme/getTheme"
import WorkspaceTracker from "../../integrations/workspace/WorkspaceTracker"
import { McpHub } from "../../services/mcp/McpHub"
import { FirebaseAuthManager, UserInfo } from "../../services/auth/FirebaseAuthManager"
import { ApiProvider, ModelInfo } from "../../shared/api"
import { findLast } from "../../shared/array"
import { ExtensionMessage, ExtensionState } from "../../shared/ExtensionMessage"
@ -43,6 +45,8 @@ type SecretKey =
| "openAiNativeApiKey"
| "deepSeekApiKey"
| "mistralApiKey"
| "authToken"
| "authNonce"
type GlobalStateKey =
| "apiProvider"
| "apiModelId"
@ -68,6 +72,7 @@ type GlobalStateKey =
| "chatSettings"
| "vsCodeLmModelSelector"
| "localeLanguage"
| "userInfo"
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
@ -86,7 +91,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
private cline?: Cline
private workspaceTracker?: WorkspaceTracker
mcpHub?: McpHub
private latestAnnouncementId = "jan-20a-2025" // update to some unique identifier when we add a new announcement
private authManager: FirebaseAuthManager
private latestAnnouncementId = "jan-20-2025" // update to some unique identifier when we add a new announcement
constructor(
readonly context: vscode.ExtensionContext,
@ -96,6 +102,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
ClineProvider.activeInstances.add(this)
this.workspaceTracker = new WorkspaceTracker(this)
this.mcpHub = new McpHub(this)
this.authManager = new FirebaseAuthManager(this)
}
/*
@ -121,10 +128,29 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.workspaceTracker = undefined
this.mcpHub?.dispose()
this.mcpHub = undefined
this.authManager.dispose()
this.outputChannel.appendLine("Disposed all disposables")
ClineProvider.activeInstances.delete(this)
}
// Auth methods
async handleSignOut() {
try {
await this.authManager.signOut()
vscode.window.showInformationMessage("Successfully logged out of Cline")
} catch (error) {
vscode.window.showErrorMessage("Logout failed")
}
}
async setAuthToken(token?: string) {
await this.storeSecret("authToken", token)
}
async setUserInfo(info?: { displayName: string | null; email: string | null; photoURL: string | null }) {
await this.updateGlobalState("userInfo", info)
}
public static getVisibleInstance(): ClineProvider | undefined {
return findLast(Array.from(this.activeInstances), (instance) => instance.view?.visible === true)
}
@ -314,7 +340,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource} 'unsafe-inline'; img-src ${webview.cspSource} data:; script-src 'nonce-${nonce}';">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource} 'unsafe-inline'; img-src ${webview.cspSource} https: data:; script-src 'nonce-${nonce}';">
<link rel="stylesheet" type="text/css" href="${stylesUri}">
<link href="${codiconsUri}" rel="stylesheet" />
<title>Cline</title>
@ -595,6 +621,27 @@ export class ClineProvider implements vscode.WebviewViewProvider {
case "getLatestState":
await this.postStateToWebview()
break
case "accountLoginClicked": {
// Generate nonce for state validation
const nonce = crypto.randomBytes(32).toString("hex")
await this.storeSecret("authNonce", nonce)
// Open browser for authentication with state param
console.log("Login button clicked in account page")
console.log("Opening auth page with state param")
const uriScheme = vscode.env.uriScheme
const authUrl = vscode.Uri.parse(
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
vscode.env.openExternal(authUrl)
break
}
case "accountLogoutClicked": {
await this.handleSignOut()
break
}
case "openMcpSettings": {
const mcpSettingsFilePath = await this.mcpHub?.getMcpSettingsFilePath()
if (mcpSettingsFilePath) {
@ -626,6 +673,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
}
case "openExtensionSettings": {
await vscode.commands.executeCommand("workbench.action.openSettings", "@ext:saoudrizwan.claude-dev")
break
}
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
}
@ -741,6 +792,32 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
}
// Auth
public async validateAuthState(state: string | null): Promise<boolean> {
const storedNonce = await this.getSecret("authNonce")
if (!state || state !== storedNonce) {
return false
}
await this.storeSecret("authNonce", undefined) // Clear after use
return true
}
async handleAuthCallback(token: string) {
try {
// First sign in with Firebase to trigger auth state change
await this.authManager.signInWithCustomToken(token)
// Then store the token securely
await this.storeSecret("authToken", token)
await this.postStateToWebview()
vscode.window.showInformationMessage("Successfully logged in to Cline")
} catch (error) {
console.error("Failed to handle auth callback:", error)
vscode.window.showErrorMessage("Failed to log in to Cline")
}
}
// OpenRouter
async handleOpenRouterCallback(code: string) {
@ -1014,7 +1091,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
autoApprovalSettings,
browserSettings,
chatSettings,
userInfo,
} = await this.getState()
const authToken = await this.getSecret("authToken")
return {
version: this.context.extension?.packageJSON?.version ?? "",
apiConfiguration,
@ -1029,6 +1109,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
browserSettings,
chatSettings,
localeLanguage: vscode.env.language,
isLoggedIn: !!authToken,
userInfo,
}
}
@ -1119,6 +1201,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
chatSettings,
vsCodeLmModelSelector,
localeLanguage,
userInfo,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
@ -1154,6 +1237,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("chatSettings") as Promise<ChatSettings | undefined>,
this.getGlobalState("vsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
this.getGlobalState("localeLanguage") as Promise<string | undefined>,
this.getGlobalState("userInfo") as Promise<UserInfo | undefined>,
])
let apiProvider: ApiProvider
@ -1206,6 +1290,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
browserSettings: browserSettings || DEFAULT_BROWSER_SETTINGS,
chatSettings: chatSettings || DEFAULT_CHAT_SETTINGS,
userInfo,
}
}
@ -1261,7 +1346,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
}
private async getSecret(key: SecretKey) {
async getSecret(key: SecretKey) {
return await this.context.secrets.get(key)
}
@ -1283,6 +1368,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
"openAiNativeApiKey",
"deepSeekApiKey",
"mistralApiKey",
"authToken",
]
for (const key of secretKeys) {
await this.storeSecret(key, undefined)

View file

@ -110,6 +110,15 @@ export function activate(context: vscode.ExtensionContext) {
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.accountLoginClicked", () => {
sidebarProvider.postMessageToWebview({
type: "action",
action: "accountLoginClicked",
})
}),
)
/*
We use the text document content provider API to show the left side for diff view by creating a virtual document for the original content. This makes it readonly so users know to edit the right side if they want to keep their changes.
@ -126,6 +135,12 @@ export function activate(context: vscode.ExtensionContext) {
// URI Handler
const handleUri = async (uri: vscode.Uri) => {
console.log("URI Handler called with:", {
path: uri.path,
query: uri.query,
scheme: uri.scheme,
})
const path = uri.path
const query = new URLSearchParams(uri.query.replace(/\+/g, "%2B"))
const visibleProvider = ClineProvider.getVisibleInstance()
@ -140,6 +155,26 @@ export function activate(context: vscode.ExtensionContext) {
}
break
}
case "/auth": {
const token = query.get("token")
const state = query.get("state")
console.log("Auth callback received:", {
token: token,
state: state,
})
// Validate state parameter
if (!(await visibleProvider.validateAuthState(state))) {
vscode.window.showErrorMessage("Invalid auth state")
return
}
if (token) {
await visibleProvider.handleAuthCallback(token)
}
break
}
default:
break
}

View file

@ -0,0 +1,73 @@
import * as vscode from "vscode"
interface DebugSession {
id: string
name: string
output: string[]
lastRetrievedIndex: number
}
export class DebugConsoleManager {
private sessions: Map<string, DebugSession> = new Map()
private disposables: vscode.Disposable[] = []
constructor() {
// Listen for debug session start events
this.disposables.push(
vscode.debug.onDidStartDebugSession((session) => {
this.sessions.set(session.id, {
id: session.id,
name: session.name,
output: [],
lastRetrievedIndex: -1,
})
}),
)
// Listen for debug session end events
this.disposables.push(
vscode.debug.onDidTerminateDebugSession((session) => {
this.sessions.delete(session.id)
}),
)
// Listen for debug console output
this.disposables.push(
vscode.debug.onDidReceiveDebugSessionCustomEvent((e: vscode.DebugSessionCustomEvent) => {
if (e.event === "output" && e.body?.output) {
const session = this.sessions.get(e.session.id)
if (session) {
session.output.push(e.body.output)
}
}
}),
)
}
/**
* Get all active debug sessions
*/
getActiveSessions(): { id: string; name: string }[] {
return Array.from(this.sessions.values()).map(({ id, name }) => ({ id, name }))
}
/**
* Get any new output since the last retrieval for a specific debug session
*/
getUnretrievedOutput(sessionId: string): string | undefined {
const session = this.sessions.get(sessionId)
if (!session) return undefined
const newOutput = session.output.slice(session.lastRetrievedIndex + 1).join("")
session.lastRetrievedIndex = session.output.length - 1
return newOutput || undefined
}
/**
* Clean up resources
*/
dispose() {
this.disposables.forEach((d) => d.dispose())
this.sessions.clear()
}
}

View file

@ -0,0 +1,99 @@
import { initializeApp } from "firebase/app"
import { Auth, User, getAuth, onAuthStateChanged, signInWithCustomToken, signOut } from "firebase/auth"
import * as vscode from "vscode"
import { ClineProvider } from "../../core/webview/ClineProvider"
import { firebaseConfig } from "./config"
export interface UserInfo {
displayName: string | null
email: string | null
photoURL: string | null
}
export class FirebaseAuthManager {
private providerRef: WeakRef<ClineProvider>
private auth: Auth
private disposables: vscode.Disposable[] = []
constructor(provider: ClineProvider) {
console.log("Initializing FirebaseAuthManager", { provider })
this.providerRef = new WeakRef(provider)
const app = initializeApp(firebaseConfig)
this.auth = getAuth(app)
console.log("Firebase app initialized", { appConfig: firebaseConfig })
// Auth state listener
onAuthStateChanged(this.auth, this.handleAuthStateChange.bind(this))
console.log("Auth state change listener added")
// Try to restore session
this.restoreSession()
}
private async restoreSession() {
console.log("Attempting to restore session")
const provider = this.providerRef.deref()
if (!provider) {
console.log("Provider reference lost during session restore")
return
}
const storedToken = await provider.getSecret("authToken")
if (storedToken) {
console.log("Found stored auth token, attempting to restore session")
try {
await this.signInWithCustomToken(storedToken)
console.log("Session restored successfully")
} catch (error) {
console.error("Failed to restore session, clearing token:", error)
await provider.setAuthToken(undefined)
await provider.setUserInfo(undefined)
}
} else {
console.log("No stored auth token found")
}
}
private async handleAuthStateChange(user: User | null) {
console.log("Auth state changed", { user })
const provider = this.providerRef.deref()
if (!provider) {
console.log("Provider reference lost")
return
}
if (user) {
console.log("User signed in", { userId: user.uid })
const idToken = await user.getIdToken()
await provider.setAuthToken(idToken)
// Store public user info in state
await provider.setUserInfo({
displayName: user.displayName,
email: user.email,
photoURL: user.photoURL,
})
console.log("User info set in provider", { user })
} else {
console.log("User signed out")
await provider.setAuthToken(undefined)
await provider.setUserInfo(undefined)
}
await provider.postStateToWebview()
console.log("Webview state updated")
}
async signInWithCustomToken(token: string) {
console.log("Signing in with custom token", { token })
await signInWithCustomToken(this.auth, token)
}
async signOut() {
console.log("Signing out")
await signOut(this.auth)
}
dispose() {
this.disposables.forEach((d) => d.dispose())
console.log("Disposables disposed", { count: this.disposables.length })
}
}

View file

@ -0,0 +1,10 @@
// Public Firebase config (safe for open source)
export const firebaseConfig = {
apiKey: "AIzaSyDcXAaanNgR2_T0dq2oOl5XyKPksYHppVo",
authDomain: "cline-bot.firebaseapp.com",
projectId: "cline-bot",
storageBucket: "cline-bot.firebasestorage.app",
messagingSenderId: "364369702101",
appId: "1:364369702101:web:0013885dcf20b43799c65c",
measurementId: "G-MDPRELSCD1",
}

View file

@ -59,6 +59,10 @@ export class McpHub {
return this.connections.filter((conn) => !conn.server.disabled).map((conn) => conn.server)
}
isMcpEnabled(): boolean {
return vscode.workspace.getConfiguration("cline.mcp").get("enabled") ?? true
}
async getMcpServersPath(): Promise<string> {
const provider = this.providerRef.deref()
if (!provider) {

View file

@ -25,7 +25,14 @@ export interface ExtensionMessage {
| "vsCodeLmModels"
| "requestVsCodeLmModels"
text?: string
action?: "chatButtonClicked" | "mcpButtonClicked" | "settingsButtonClicked" | "historyButtonClicked" | "didBecomeVisible"
action?:
| "chatButtonClicked"
| "mcpButtonClicked"
| "settingsButtonClicked"
| "historyButtonClicked"
| "didBecomeVisible"
| "accountLoginClicked"
| "accountLogoutClicked"
invoke?: "sendMessage" | "primaryButtonClick" | "secondaryButtonClick"
state?: ExtensionState
images?: string[]
@ -52,6 +59,12 @@ export interface ExtensionState {
browserSettings: BrowserSettings
chatSettings: ChatSettings
localeLanguage: string
isLoggedIn: boolean
userInfo?: {
displayName: string | null
email: string | null
photoURL: string | null
}
}
export interface ClineMessage {

View file

@ -33,10 +33,13 @@ export interface WebviewMessage {
| "checkpointDiff"
| "checkpointRestore"
| "taskCompletionViewChanges"
| "openExtensionSettings"
| "requestVsCodeLmModels"
| "toggleToolAutoApprove"
| "toggleMcpServer"
| "getLatestState"
| "accountLoginClicked"
| "accountLogoutClicked"
// | "relaunchChromeDebugMode"
text?: string
disabled?: boolean

View file

@ -377,6 +377,16 @@ export const deepSeekModels = {
cacheWritesPrice: 0.14,
cacheReadsPrice: 0.014,
},
"deepseek-reasoner": {
maxTokens: 8_000,
contextWindow: 64_000,
supportsImages: false,
supportsPromptCache: true, // supports context caching, but not in the way anthropic does it (deepseek reports input tokens and reads/writes in the same usage report) FIXME: we need to show users cache stats how deepseek does it
inputPrice: 0, // technically there is no input price, it's all either a cache hit or miss (ApiOptions will not show this)
outputPrice: 2.19,
cacheWritesPrice: 0.55,
cacheReadsPrice: 0.14,
},
} as const satisfies Record<string, ModelInfo>
// Mistral

View file

@ -4,7 +4,7 @@ import path from "path"
import "should"
import * as vscode from "vscode"
const packagePath = path.join(__dirname, "..", "..", "..", "package.json")
const packagePath = path.join(__dirname, "..", "..", "package.json")
describe("Cline Extension", () => {
after(() => {
@ -23,4 +23,69 @@ describe("Cline Extension", () => {
await new Promise((resolve) => setTimeout(resolve, 400))
await vscode.commands.executeCommand("cline.plusButtonClicked")
})
// New test to verify xvfb and webview functionality
it("should create and display a webview panel", async () => {
// Create a webview panel
const panel = vscode.window.createWebviewPanel("testWebview", "CI/CD Test", vscode.ViewColumn.One, {
enableScripts: true,
})
// Set some HTML content
panel.webview.html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>xvfb Test</title>
</head>
<body>
<div id="test">Testing xvfb display server</div>
</body>
</html>
`
// Verify panel exists
should.exist(panel)
panel.visible.should.be.true()
// Clean up
panel.dispose()
})
// Test webview message passing
it("should handle webview messages", async () => {
const panel = vscode.window.createWebviewPanel("testWebview", "Message Test", vscode.ViewColumn.One, {
enableScripts: true,
})
// Set up message handling
const messagePromise = new Promise<string>((resolve) => {
panel.webview.onDidReceiveMessage((message) => resolve(message.text), undefined)
})
// Add message sending script
panel.webview.html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Message Test</title>
</head>
<body>
<script>
const vscode = acquireVsCodeApi();
vscode.postMessage({ text: 'test-message' });
</script>
</body>
</html>
`
// Wait for message
const message = await messagePromise
message.should.equal("test-message")
// Clean up
panel.dispose()
})
})

View file

@ -0,0 +1,37 @@
const { expect } = require("chai")
const vscode = require("vscode")
describe("Extension Tests", function () {
this.timeout(60000) // Increased timeout for extension operations
it("should activate extension successfully", async () => {
// Get the extension
const extension = vscode.extensions.getExtension("saoudrizwan.claude-dev")
expect(extension).to.not.be.undefined
// Activate the extension if not already activated
if (!extension.isActive) {
await extension.activate()
}
expect(extension.isActive).to.be.true
})
it("should open sidebar view", async () => {
// Execute the command to open sidebar
await vscode.commands.executeCommand("cline.plusButtonClicked")
// Wait for sidebar to be visible
await new Promise((resolve) => setTimeout(resolve, 1000))
// Get all views
const views = vscode.window.visibleTextEditors
// Just verify the command executed without error
// The actual view verification is handled in the TypeScript tests
})
it("should handle basic commands", async () => {
// Test basic command execution
await vscode.commands.executeCommand("cline.historyButtonClicked")
// Success if no error thrown
})
})

43
src/test/suite/index.js Normal file
View file

@ -0,0 +1,43 @@
const path = require("path")
const Mocha = require("mocha")
const glob = require("glob")
async function run() {
// Create the mocha test
const mocha = new Mocha({
ui: "bdd",
color: true,
timeout: 60000, // Increased timeout for extension operations
})
const testsRoot = path.resolve(__dirname, ".")
try {
// Find all test files
const files = await glob("*.test.js", { cwd: testsRoot })
// Add files to the test suite
files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)))
// Run the mocha test
return new Promise((resolve, reject) => {
try {
// Run the tests
mocha.run((failures) => {
if (failures > 0) {
reject(new Error(`${failures} tests failed.`))
} else {
resolve()
}
})
} catch (err) {
reject(err)
}
})
} catch (err) {
console.error("Failed to run tests:", err)
throw err
}
}
module.exports = { run }

View file

@ -0,0 +1,116 @@
import * as vscode from "vscode"
import { describe, it, beforeEach, afterEach } from "mocha"
import { strict as assert } from "assert"
import { join } from "path"
describe("Chat Integration Tests", () => {
let panel: vscode.WebviewPanel
let disposables: vscode.Disposable[] = []
beforeEach(async () => {
// Create VSCode webview panel
panel = vscode.window.createWebviewPanel("testWebview", "Chat Test", vscode.ViewColumn.One, {
enableScripts: true,
retainContextWhenHidden: true,
})
// Set up minimal test webview
panel.webview.html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
const vscode = acquireVsCodeApi();
window.addEventListener('message', event => {
const message = event.data;
switch (message.type) {
case 'sendMessage':
vscode.postMessage({ type: 'newTask', text: message.text });
break;
case 'toggleMode':
vscode.postMessage({ type: 'chatSettings', chatSettings: { mode: 'act' } });
break;
case 'invoke':
if (message.invoke === 'primaryButtonClick') {
vscode.postMessage({ type: 'askResponse', askResponse: 'yesButtonClicked' });
}
break;
}
});
</script>
</head>
<body>
<div id="test-webview"></div>
</body>
</html>
`
})
afterEach(() => {
panel.dispose()
disposables.forEach((d) => d.dispose())
disposables = []
})
it("should send chat messages", async () => {
// Set up message listener
const messagePromise = new Promise<any>((resolve) => {
panel.webview.onDidReceiveMessage((message) => {
if (message.type === "newTask") {
resolve(message)
}
})
})
// Trigger send message
await panel.webview.postMessage({
type: "sendMessage",
text: "Create a hello world app",
})
// Verify message was sent
const message = await messagePromise
assert.equal(message.type, "newTask")
assert.equal(message.text, "Create a hello world app")
})
it("should toggle between plan and act modes", async () => {
// Set up state change listener
const stateChangePromise = new Promise<any>((resolve) => {
panel.webview.onDidReceiveMessage((message) => {
if (message.type === "chatSettings") {
resolve(message)
}
})
})
// Trigger mode toggle
await panel.webview.postMessage({ type: "toggleMode" })
// Verify mode changed
const stateChange = await stateChangePromise
assert.equal(stateChange.chatSettings.mode, "act")
})
it("should handle tool approval flow", async () => {
// Set up approval listener
const approvalPromise = new Promise<any>((resolve) => {
panel.webview.onDidReceiveMessage((message) => {
if (message.type === "askResponse") {
resolve(message)
}
})
})
// Trigger tool approval
await panel.webview.postMessage({
type: "invoke",
invoke: "primaryButtonClick",
})
// Verify approval was sent
const response = await approvalPromise
assert.equal(response.type, "askResponse")
assert.equal(response.askResponse, "yesButtonClicked")
})
})

View file

@ -8,7 +8,11 @@
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"types": ["node", "mocha", "should", "vscode"]
"types": ["node", "mocha", "should", "vscode", "chai"],
"typeRoots": ["./node_modules/@types", "./src/test/types"],
"outDir": "out",
"rootDir": "src"
},
"include": ["src/**/*.test.ts"]
"include": ["src/**/*.test.ts"],
"exclude": ["src/test/**/*.js"]
}

View file

@ -5,6 +5,7 @@ import ChatView from "./components/chat/ChatView"
import HistoryView from "./components/history/HistoryView"
import SettingsView from "./components/settings/SettingsView"
import WelcomeView from "./components/welcome/WelcomeView"
import AccountView from "./components/account/AccountView"
import { ExtensionStateContextProvider, useExtensionState } from "./context/ExtensionStateContext"
import { vscode } from "./utils/vscode"
import McpView from "./components/mcp/McpView"
@ -16,6 +17,7 @@ const AppContent = () => {
const [showSettings, setShowSettings] = useState(false)
const [showHistory, setShowHistory] = useState(false)
const [showMcp, setShowMcp] = useState(false)
const [showAccount, setShowAccount] = useState(false)
const [showAnnouncement, setShowAnnouncement] = useState(false)
const handleMessage = useCallback((e: MessageEvent) => {
@ -27,21 +29,31 @@ const AppContent = () => {
setShowSettings(true)
setShowHistory(false)
setShowMcp(false)
setShowAccount(false)
break
case "historyButtonClicked":
setShowSettings(false)
setShowHistory(true)
setShowMcp(false)
setShowAccount(false)
break
case "mcpButtonClicked":
setShowSettings(false)
setShowHistory(false)
setShowMcp(true)
setShowAccount(false)
break
case "accountLoginClicked":
setShowSettings(false)
setShowHistory(false)
setShowMcp(false)
setShowAccount(true)
break
case "chatButtonClicked":
setShowSettings(false)
setShowHistory(false)
setShowMcp(false)
setShowAccount(false)
break
}
break
@ -76,6 +88,7 @@ const AppContent = () => {
{showSettings && <SettingsView onDone={() => setShowSettings(false)} />}
{showHistory && <HistoryView onDone={() => setShowHistory(false)} />}
{showMcp && <McpView onDone={() => setShowMcp(false)} />}
{showAccount && <AccountView onDone={() => setShowAccount(false)} />}
{/* Do not conditionally load ChatView, it's expensive and there's state we don't want to lose (user input, disableInput, askResponse promise, etc.) */}
<ChatView
showHistoryView={() => {
@ -83,7 +96,7 @@ const AppContent = () => {
setShowMcp(false)
setShowHistory(true)
}}
isHidden={showSettings || showHistory || showMcp}
isHidden={showSettings || showHistory || showMcp || showAccount}
showAnnouncement={showAnnouncement}
hideAnnouncement={() => {
setShowAnnouncement(false)

View file

@ -0,0 +1,15 @@
import { memo } from "react"
import { vscode } from "../../utils/vscode"
const AccountOptions = () => {
const handleAccountClick = () => {
vscode.postMessage({ type: "accountLoginClicked" })
}
// Call handleAccountClick immediately when component mounts
handleAccountClick()
return null // This component doesn't render anything
}
export default memo(AccountOptions)

View file

@ -0,0 +1,83 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { memo } from "react"
import { useExtensionState } from "../../context/ExtensionStateContext"
import { vscode } from "../../utils/vscode"
type AccountViewProps = {
onDone: () => void
}
const AccountView = ({ onDone }: AccountViewProps) => {
const { isLoggedIn, userInfo } = useExtensionState()
const handleLogin = () => {
vscode.postMessage({ type: "accountLoginClicked" })
}
const handleLogout = () => {
vscode.postMessage({ type: "accountLogoutClicked" })
}
return (
<div
style={{
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
padding: "10px 0px 0px 20px",
display: "flex",
flexDirection: "column",
overflow: "hidden",
}}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "17px",
paddingRight: 17,
}}>
<h3 style={{ color: "var(--vscode-foreground)", margin: 0 }}>Account</h3>
<VSCodeButton onClick={onDone}>Done</VSCodeButton>
</div>
<div
style={{
flexGrow: 1,
overflowY: "scroll",
paddingRight: 8,
display: "flex",
flexDirection: "column",
}}>
<div style={{ marginBottom: 5 }}>
{isLoggedIn ? (
<>
{userInfo?.photoURL && (
<img
src={userInfo.photoURL}
alt="Profile"
style={{
width: 48,
height: 48,
borderRadius: "50%",
marginBottom: 10,
}}
/>
)}
<div style={{ fontSize: "14px", marginBottom: 10 }}>
{userInfo?.displayName && <div>Name: {userInfo.displayName}</div>}
{userInfo?.email && <div>Email: {userInfo.email}</div>}
</div>
<VSCodeButton onClick={handleLogout}>Log out</VSCodeButton>
</>
) : (
<VSCodeButton onClick={handleLogin}>Log in to Cline</VSCodeButton>
)}
</div>
</div>
</div>
)
}
export default memo(AccountView)

View file

@ -43,6 +43,8 @@ interface ChatTextAreaProps {
onHeightChange?: (height: number) => void
}
const PLAN_MODE_COLOR = "var(--vscode-inputValidation-warningBorder)"
const SwitchOption = styled.div<{ isActive: boolean }>`
padding: 2px 8px;
color: ${(props) => (props.isActive ? "white" : "var(--vscode-input-foreground)")};
@ -69,13 +71,14 @@ const SwitchContainer = styled.div<{ disabled: boolean }>`
transform: scale(0.85);
transform-origin: right center;
margin-left: -10px; // compensate for the transform so flex spacing works
user-select: none; // Prevent text selection
`
const Slider = styled.div<{ isAct: boolean }>`
const Slider = styled.div<{ isAct: boolean; isPlan?: boolean }>`
position: absolute;
height: 100%;
width: 50%;
background-color: var(--vscode-focusBorder);
background-color: ${(props) => (props.isPlan ? PLAN_MODE_COLOR : "var(--vscode-focusBorder)")};
transition: transform 0.2s ease;
transform: translateX(${(props) => (props.isAct ? "100%" : "0%")});
`
@ -372,6 +375,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const isComposing = event.nativeEvent?.isComposing ?? false
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault()
setIsTextAreaFocused(false)
onSend()
}
@ -742,6 +746,93 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}
}, [showModelSelector])
/**
* Handles the drag over event to allow dropping.
* Prevents the default behavior to enable drop.
*
* @param {React.DragEvent} e - The drag event.
*/
const onDragOver = (e: React.DragEvent) => {
e.preventDefault()
}
/**
* Handles the drop event for files and text.
* Processes dropped images and text, updating the state accordingly.
*
* @param {React.DragEvent} e - The drop event.
*/
const onDrop = async (e: React.DragEvent) => {
e.preventDefault()
const files = Array.from(e.dataTransfer.files)
const text = e.dataTransfer.getData("text")
if (text) {
handleTextDrop(text)
return
}
const acceptedTypes = ["png", "jpeg", "webp"]
const imageFiles = files.filter((file) => {
const [type, subtype] = file.type.split("/")
return type === "image" && acceptedTypes.includes(subtype)
})
if (shouldDisableImages || imageFiles.length === 0) return
const imageDataArray = await readImageFiles(imageFiles)
const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
if (dataUrls.length > 0) {
setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
} else {
console.warn("No valid images were processed")
}
}
/**
* Handles the drop event for text.
* Inserts the dropped text at the current cursor position.
*
* @param {string} text - The dropped text.
*/
const handleTextDrop = (text: string) => {
const newValue = inputValue.slice(0, cursorPosition) + text + inputValue.slice(cursorPosition)
setInputValue(newValue)
const newCursorPosition = cursorPosition + text.length
setCursorPosition(newCursorPosition)
setIntendedCursorPosition(newCursorPosition)
}
/**
* Reads image files and returns their data URLs.
* Uses FileReader to read the files as data URLs.
*
* @param {File[]} imageFiles - The image files to read.
* @returns {Promise<(string | null)[]>} - A promise that resolves to an array of data URLs or null values.
*/
const readImageFiles = (imageFiles: File[]): Promise<(string | null)[]> => {
return Promise.all(
imageFiles.map(
(file) =>
new Promise<string | null>((resolve) => {
const reader = new FileReader()
reader.onloadend = () => {
if (reader.error) {
console.error("Error reading file:", reader.error)
resolve(null)
} else {
const result = reader.result
resolve(typeof result === "string" ? result : null)
}
}
reader.readAsDataURL(file)
}),
),
)
}
return (
<div>
<div
@ -750,7 +841,9 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
opacity: textAreaDisabled ? 0.5 : 1,
position: "relative",
display: "flex",
}}>
}}
onDrop={onDrop}
onDragOver={onDragOver}>
{showContextMenu && (
<div ref={contextMenuContainerRef}>
<ContextMenu
@ -803,6 +896,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}}
/>
<DynamicTextArea
data-testid="chat-input"
ref={(el) => {
if (typeof ref === "function") {
ref(el)
@ -862,6 +956,9 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
cursor: textAreaDisabled ? "not-allowed" : undefined,
flex: 1,
zIndex: 1,
outline: isTextAreaFocused
? `1px solid ${chatSettings.mode === "plan" ? PLAN_MODE_COLOR : "var(--vscode-focusBorder)"}`
: "none",
}}
onScroll={() => updateHighlights()}
/>
@ -909,9 +1006,11 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}}
/> */}
<div
data-testid="send-button"
className={`input-icon-button ${textAreaDisabled ? "disabled" : ""} codicon codicon-send`}
onClick={() => {
if (!textAreaDisabled) {
setIsTextAreaFocused(false)
onSend()
}
}}
@ -923,6 +1022,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
<ControlsContainer>
<ButtonGroup>
<VSCodeButton
data-testid="context-button"
appearance="icon"
aria-label="Add Context"
disabled={textAreaDisabled}
@ -935,6 +1035,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
</VSCodeButton>
<VSCodeButton
data-testid="images-button"
appearance="icon"
aria-label="Add Images"
disabled={shouldDisableImages}
@ -985,8 +1086,8 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
</ModelContainer>
</ButtonGroup>
<SwitchContainer disabled={textAreaDisabled} onClick={onModeToggle}>
<Slider isAct={chatSettings.mode === "act"} />
<SwitchContainer data-testid="mode-switch" disabled={textAreaDisabled} onClick={onModeToggle}>
<Slider isAct={chatSettings.mode === "act"} isPlan={chatSettings.mode === "plan"} />
<SwitchOption isActive={chatSettings.mode === "plan"}>Plan</SwitchOption>
<SwitchOption isActive={chatSettings.mode === "act"}>Act</SwitchOption>
</SwitchContainer>

View file

@ -0,0 +1,36 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import styled from "styled-components"
const StyledButton = styled(VSCodeButton)`
--settings-button-bg: var(--vscode-button-secondaryBackground);
--settings-button-hover: var(--vscode-button-secondaryHoverBackground);
--settings-button-active: var(--vscode-button-secondaryBackground);
background-color: var(--settings-button-bg) !important;
border-color: var(--settings-button-bg) !important;
width: 100% !important;
&:hover {
background-color: var(--settings-button-hover) !important;
border-color: var(--settings-button-hover) !important;
}
&:active {
background-color: var(--settings-button-active) !important;
border-color: var(--settings-button-active) !important;
}
i.codicon {
margin-right: 6px;
flex-shrink: 0;
font-size: 16px !important;
}
`
interface SettingsButtonProps extends React.ComponentProps<typeof VSCodeButton> {}
const SettingsButton: React.FC<SettingsButtonProps> = (props) => {
return <StyledButton appearance="secondary" {...props} />
}
export default SettingsButton

View file

@ -12,6 +12,7 @@ type McpViewProps = {
const McpView = ({ onDone }: McpViewProps) => {
const { mcpServers: servers } = useExtensionState()
// const [servers, setServers] = useState<McpServer[]>([
// // Add some mock servers for testing
// {
@ -100,7 +101,7 @@ const McpView = ({ onDone }: McpViewProps) => {
style={{
color: "var(--vscode-foreground)",
fontSize: "13px",
marginBottom: "20px",
marginBottom: "16px",
marginTop: "5px",
}}>
The{" "}
@ -118,7 +119,6 @@ const McpView = ({ onDone }: McpViewProps) => {
</VSCodeLink>
</div>
{/* Server List */}
{servers.length > 0 && (
<div
style={{
@ -132,7 +132,8 @@ const McpView = ({ onDone }: McpViewProps) => {
</div>
)}
{/* Edit Settings Button */}
{/* Server Configuration Button */}
<div style={{ marginTop: "10px", width: "100%" }}>
<VSCodeButton
appearance="secondary"
@ -140,11 +141,25 @@ const McpView = ({ onDone }: McpViewProps) => {
onClick={() => {
vscode.postMessage({ type: "openMcpSettings" })
}}>
<span className="codicon codicon-edit" style={{ marginRight: "6px" }}></span>
Edit MCP Settings
<span className="codicon codicon-server" style={{ marginRight: "6px" }}></span>
Configure MCP Servers
</VSCodeButton>
</div>
{/* Advanced Settings Link */}
<div style={{ textAlign: "center", marginTop: "5px" }}>
<VSCodeLink
onClick={() => {
vscode.postMessage({
type: "openExtensionSettings",
text: "cline.mcp",
})
}}
style={{ fontSize: "12px" }}>
Advanced MCP Settings
</VSCodeLink>
</div>
{/* Bottom padding */}
<div style={{ height: "20px" }} />
</div>

View file

@ -52,9 +52,9 @@ interface ApiOptionsProps {
// This is necessary to ensure dropdown opens downward, important for when this is used in popup
const DROPDOWN_Z_INDEX = 1001 // Higher than the OpenRouterModelPicker's and ModelSelectorTooltip's z-index
const DropdownContainer = styled.div`
const DropdownContainer = styled.div<{ zIndex?: number }>`
position: relative;
z-index: ${DROPDOWN_Z_INDEX};
z-index: ${(props) => props.zIndex || DROPDOWN_Z_INDEX};
// Force dropdowns to open downward
& vscode-dropdown::part(listbox) {
@ -403,7 +403,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
placeholder={t("enterAwsSessionToken")}>
<span style={{ fontWeight: 500 }}>{t("awsSessionToken")}</span>
</VSCodeTextField>
<div className="dropdown-container">
<DropdownContainer zIndex={DROPDOWN_Z_INDEX - 1} className="dropdown-container">
<label htmlFor="aws-region-dropdown">
<span style={{ fontWeight: 500 }}>{t("getRegion", { vendor: "AWS" })}</span>
</label>
@ -439,7 +439,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
<VSCodeOption value="us-gov-west-1">us-gov-west-1</VSCodeOption>
{/* <VSCodeOption value="us-gov-east-1">us-gov-east-1</VSCodeOption> */}
</VSCodeDropdown>
</div>
</DropdownContainer>
<VSCodeCheckbox
checked={apiConfiguration?.awsUseCrossRegionInference || false}
onChange={(e: any) => {
@ -476,7 +476,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
placeholder={t("enterGcpProjectId")}>
<span style={{ fontWeight: 500 }}>{t("gcpProjectId")}</span>
</VSCodeTextField>
<div className="dropdown-container">
<DropdownContainer zIndex={DROPDOWN_Z_INDEX - 2} className="dropdown-container">
<label htmlFor="vertex-region-dropdown">
<span style={{ fontWeight: 500 }}>{t("getRegion", { vendor: "Google Cloud" })}</span>
</label>
@ -492,7 +492,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
<VSCodeOption value="europe-west4">europe-west4</VSCodeOption>
<VSCodeOption value="asia-southeast1">asia-southeast1</VSCodeOption>
</VSCodeDropdown>
</div>
</DropdownContainer>
<p
style={{
fontSize: "12px",
@ -606,7 +606,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
{selectedProvider === "vscode-lm" && (
<div>
<div className="dropdown-container">
<DropdownContainer zIndex={DROPDOWN_Z_INDEX - 2} className="dropdown-container">
<label htmlFor="vscode-lm-model">
<span style={{ fontWeight: 500 }}>{t("languageModel")}</span>
</label>
@ -660,7 +660,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
}}>
{t("experimentalFeature")}
</p>
</div>
</DropdownContainer>
</div>
)}
@ -798,7 +798,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
selectedProvider !== "vscode-lm" &&
showModelOptions && (
<>
<div className="dropdown-container">
<DropdownContainer zIndex={DROPDOWN_Z_INDEX - 2} className="dropdown-container">
<label htmlFor="model-id">
<span style={{ fontWeight: 500 }}>{t("model")}</span>
</label>
@ -809,7 +809,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
{selectedProvider === "openai-native" && createDropdown(openAiNativeModels)}
{selectedProvider === "deepseek" && createDropdown(deepSeekModels)}
{selectedProvider === "mistral" && createDropdown(mistralModels)}
</div>
</DropdownContainer>
<ModelInfoView
selectedModelId={selectedModelId}
@ -840,7 +840,6 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is
export function getOpenRouterAuthUrl(uriScheme?: string) {
return `https://openrouter.ai/auth?callback_url=${uriScheme || "vscode"}://saoudrizwan.claude-dev/openrouter`
}
export const formatPrice = (price: number) => {
return new Intl.NumberFormat("en-US", {
style: "currency",

View file

@ -6,6 +6,7 @@ import { validateApiConfiguration, validateModelId } from "../../utils/validate"
import { vscode } from "../../utils/vscode"
import ApiOptions from "./ApiOptions"
import LanguageOptions from "./LanguageOptions"
import SettingsButton from "../common/SettingsButton"
const IS_DEV = false // FIXME: use flags when packaging
@ -136,14 +137,29 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
</>
)}
<div
style={{
marginTop: "auto",
paddingRight: 8,
display: "flex",
justifyContent: "center",
}}>
<SettingsButton
onClick={() => vscode.postMessage({ type: "openExtensionSettings" })}
style={{
margin: "0 0 16px 0",
}}>
<i className="codicon codicon-settings-gear" />
Advanced Settings
</SettingsButton>
</div>
<div
style={{
textAlign: "center",
color: "var(--vscode-descriptionForeground)",
fontSize: "12px",
lineHeight: "1.2",
marginTop: "auto",
padding: "10px 8px 15px 0px",
padding: "0 8px 15px 0",
}}>
<p
style={{

View file

@ -36,6 +36,7 @@ export const ExtensionStateContextProvider: React.FC<{
browserSettings: DEFAULT_BROWSER_SETTINGS,
localeLanguage: "en",
chatSettings: DEFAULT_CHAT_SETTINGS,
isLoggedIn: false,
})
const [didHydrateState, setDidHydrateState] = useState(false)
const [showWelcome, setShowWelcome] = useState(false)