Compare commits

..
70 changed files with 846 additions and 2424 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate showAccountViewClicked to protobus
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Adding Telemetry for button clicks
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate openMcpSettings to protobus
-1
View File
@@ -164,7 +164,6 @@ Key providers include:
- **OpenRouter**: Meta-provider supporting multiple model providers
- **AWS Bedrock**: Integration with Amazon's AI services
- **Gemini**: Google's AI models
- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
- **Ollama**: Local model hosting
- **LM Studio**: Local model hosting
- **VSCode LM**: VSCode's built-in language models
-10
View File
@@ -1,15 +1,5 @@
# Changelog
## [3.17.6]
- Add Cerebras as a new API provider with 5 high-performance models including reasoning-capable models (Thanks @kevint-cerebras!)
- Add support for uploading various file types (XML, JSON, TXT, LOG, MD, DOCX, IPYNB, PDF) alongside images
- Add improved onboarding experience for new users with guided setup
- Add prompt cache indicator for Gemini 2.5 Flash models
- Update SambaNova provider with new model list and documentation links (Thanks @luisfucros!)
- Fix diff editing support for Claude 4 family of models
- Improve telemetry and analytics for better user experience insights
## [3.17.5]
- Fix issue with Claude 4 models where after several conversation turns, it would start making invalid diff edits
+1 -1
View File
@@ -51,7 +51,7 @@ Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthrop
### Use any API and Model
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, and Cerebras. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, and GCP Vertex. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
The extension also keeps track of total tokens and API usage cost for the entire task loop and individual requests, keeping you informed of spend every step of the way.
@@ -1,44 +0,0 @@
---
title: "VS Code Language Model API"
description: "Learn how to use Cline with the experimental VS Code Language Model API, enabling access to models from GitHub Copilot and other compatible extensions."
---
Cline offers _experimental_ support for the [VS Code Language Model API](https://code.visualstudio.com/api/extension-guides/language-model). This API enables extensions to grant access to language models directly within the VS Code environment. Consequently, you might be able to leverage models from:
- **GitHub Copilot:** Provided you have an active Copilot subscription and the extension installed.
- **Other VS Code Extensions:** Any extension that implements the Language Model API.
**Important Note:** This integration is currently in an experimental phase and might not perform as anticipated. Its functionality relies on other extensions correctly implementing the VS Code Language Model API.
### Prerequisites
- **VS Code:** The Language Model API is accessible via VS Code (it is not currently supported by Cursor).
- **A Language Model Provider Extension:** An extension that furnishes a language model is required. Examples include:
- **GitHub Copilot:** With a Copilot subscription, the GitHub Copilot and GitHub Copilot Chat extensions can serve as model providers.
- **Alternative Extensions:** Explore the VS Code Marketplace for extensions mentioning "Language Model API" or "lm". Other experimental options may be available.
### Configuration Steps
1. **Access Cline Settings:** Click the gear icon (⚙️) located in the Cline panel.
2. **Choose Provider:** Select "VS Code LM API" from the "API Provider" dropdown menu.
3. **Select Model:** The "Language Model" dropdown will (eventually) populate with available models. The naming convention is `vendor/family`. For instance, if Copilot is active, you might encounter options such as:
- `copilot - claude-3.5-sonnet`
- `copilot - o3-mini`
- `copilot - o1-ga`
- `copilot - gemini-2.0-flash`
### Current Limitations
- **Experimental API Status:** The VS Code Language Model API is still under active development. Anticipate potential changes and instability.
- **Dependency on Extensions:** This feature is entirely contingent on other extensions making models available. Cline does not directly control the list of accessible models.
- **Restricted Functionality:** The VS Code Language Model API might not encompass all features available through other API providers (e.g., image input capabilities, streaming responses, detailed usage metrics).
- **No Direct Cost Management:** Users are subject to the pricing structures and terms of service of the extension providing the model. Cline cannot directly monitor or regulate associated costs.
- **GitHub Copilot Rate Throttling:** When employing the VS Code LM API with GitHub Copilot, be mindful that GitHub may enforce rate limits on Copilot usage. These limitations are governed by GitHub, not Cline.
### Troubleshooting Tips
- **Models Not Appearing:**
- Confirm that VS Code is installed.
- Verify that a language model provider extension (e.g., GitHub Copilot, GitHub Copilot Chat) is installed and enabled.
- If utilizing Copilot, ensure you have previously sent a Copilot Chat message using the desired model.
- **Unexpected Operation:** Should you encounter unforeseen behavior, it is likely an issue stemming from the underlying Language Model API or the provider extension. Consider reporting the problem to the developers of the provider extension.
+1 -2
View File
@@ -148,8 +148,7 @@
"custom-model-configs/aws-bedrock-with-credentials-authentication",
"custom-model-configs/aws-bedrock-with-profile-authentication",
"custom-model-configs/gcp-vertex-ai",
"custom-model-configs/litellm-and-cline-using-codestral",
"custom-model-configs/vscode-language-model-api"
"custom-model-configs/litellm-and-cline-using-codestral"
]
},
{
+27 -27
View File
@@ -13,13 +13,35 @@ Before you jump into coding, make sure you have these essentials ready:
A popular, free, and powerful code editor.
- [<u>Download VS Code</u>](https://code.visualstudio.com/)
- [Download VS Code](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](https://www.youtube.com/watch?v=MlIzFUI1QGA)
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
> ✅ **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
#### 2. **Organize Your Projects**
#### 2. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.
📺 **Recommended YouTube Tutorials:**
- **For macOS:**
- [Install Homebrew on Mac](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [Install Git on MacOS 2024](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [Install Node.js on Mac (M1 | M2 | M3)](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [Install Git on Windows 10/11 (2024)](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [Install Node.js in Windows 10/11](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
#### 3. **Organize Your Projects**
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
@@ -33,36 +55,14 @@ Inside your `Cline` folder, structure projects clearly:
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 3. **Install the Cline VS Code Extension**
#### 4. **Install the Cline VS Code Extension**
Enhance your coding workflow by installing the Cline extension directly within VS Code:
- Get Started with Cline Extension Tutorial
📺 **Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](https://www.youtube.com/watch?v=E7trgwZa-mk)
📺 **Recommended YouTube Tutorial:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
> ✅ **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
#### 4. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 [<u>Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.</u>](https://docs.cline.bot/getting-started/installing-dev-essentials#installing-dev-essentials)
📺 **Recommended YouTube Tutorials for Manual Installation:**
- **For macOS:**
- [<u>Install Homebrew on Mac</u>](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [<u>Install Git on macOS 2024</u>](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [<u>Install Node.js on Mac (M1 | M2 | M3)</u>](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [<u>Install Git on Windows 10/11 (2024)</u>](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [<u>Install Node.js in Windows 10/11</u>](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
@@ -69,9 +69,9 @@ Choose your AI assistant based on your needs:
### Getting Started
1. Install the development essentials:
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/getting-started-new-coders/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/cline-memory-bank)
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)
- Create an empty `cline_docs` folder in your project root
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
- Tell Cline to "initialize memory bank"
@@ -197,20 +197,20 @@ git push origin main # Upload to GitHub
1. **Start of day**: Get latest changes
```bash
git pull origin main # Download latest code
bashCopygit pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
git add .
bashCopygit add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
git push origin main # Upload to GitHub
bashCopygit push origin main # Upload to GitHub
```
**Best Practices**
@@ -38,7 +38,7 @@ Cline actively builds context in two ways:
- Guide focus areas
- Share design thoughts and requirements
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/features/plan-and-act) mode.
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) mode.
### Context & Context Windows
@@ -93,7 +93,7 @@ Context files help maintain understanding across sessions. They serve as documen
#### Approaches to Context Files
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/prompting/cline-memory-bank)**)**
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
- Living documentation that evolves with your project
- Updated as architecture and patterns emerge
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
@@ -151,7 +151,7 @@ Context files help maintain understanding across sessions. They serve as documen
- Use Plan mode for complex discussions
- Start fresh sessions when needed
3. **Team Projects**
- Share common context files (consider using [.clinerules](https://docs.cline.bot/features/cline-rules) files in project roots)
- Share common context files (consider using [.clinerules](https://docs.cline.bot/improving-your-prompting-skills/prompting) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
+2 -63
View File
@@ -1,12 +1,12 @@
{
"name": "claude-dev",
"version": "3.17.6",
"version": "3.17.2",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "claude-dev",
"version": "3.17.6",
"version": "3.17.2",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.12.4",
@@ -14,7 +14,6 @@
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
"@google/genai": "^0.13.0",
"@grpc/grpc-js": "^1.9.15",
@@ -28,7 +27,6 @@
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@vscode/codicons": "^0.0.36",
"archiver": "^7.0.1",
"axios": "^1.8.2",
@@ -4091,30 +4089,6 @@
"integrity": "sha512-/g5EzJifw5GF8aren8wZ/G5oMuPoGeS6MQD3ca8ddcvdXR5UELUfdTZITCGNhNXynY/AYl3Z4plmxdj/tRl/hQ==",
"license": "(Apache-2.0 AND BSD-3-Clause)"
},
"node_modules/@cerebras/cerebras_cloud_sdk": {
"version": "1.35.0",
"resolved": "https://registry.npmjs.org/@cerebras/cerebras_cloud_sdk/-/cerebras_cloud_sdk-1.35.0.tgz",
"integrity": "sha512-bQ6KYHmcvudHJ1aLzqkeETn3Y071/8/zpcZho6g4pKZ+VluHvLmIG0buhrwF9qJY5WSLmXR/s4pruxVRmfV7yQ==",
"license": "Apache-2.0",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7"
}
},
"node_modules/@cerebras/cerebras_cloud_sdk/node_modules/@types/node": {
"version": "18.19.103",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.103.tgz",
"integrity": "sha512-hHTHp+sEz6SxFsp+SA+Tqrua3AbmlAw+Y//aEwdHrdZkYVRWdvWD3y5uPZ0flYOkgskaFWqZ/YGFm3FaFQ0pRw==",
"license": "MIT",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@changesets/apply-release-plan": {
"version": "7.0.8",
"resolved": "https://registry.npmjs.org/@changesets/apply-release-plan/-/apply-release-plan-7.0.8.tgz",
@@ -10921,12 +10895,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true
},
"node_modules/@streamparser/json": {
"version": "0.0.22",
"resolved": "https://registry.npmjs.org/@streamparser/json/-/json-0.0.22.tgz",
"integrity": "sha512-b6gTSBjJ8G8SuO3Gbbj+zXbVx8NSs1EbpbMKpzGLWMdkR+98McH9bEjSz3+0mPJf68c5nxa3CrJHp5EQNXM6zQ==",
"license": "MIT"
},
"node_modules/@szmarczak/http-timer": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-5.0.1.tgz",
@@ -28924,30 +28892,6 @@
"resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.2.5.tgz",
"integrity": "sha512-/g5EzJifw5GF8aren8wZ/G5oMuPoGeS6MQD3ca8ddcvdXR5UELUfdTZITCGNhNXynY/AYl3Z4plmxdj/tRl/hQ=="
},
"@cerebras/cerebras_cloud_sdk": {
"version": "1.35.0",
"resolved": "https://registry.npmjs.org/@cerebras/cerebras_cloud_sdk/-/cerebras_cloud_sdk-1.35.0.tgz",
"integrity": "sha512-bQ6KYHmcvudHJ1aLzqkeETn3Y071/8/zpcZho6g4pKZ+VluHvLmIG0buhrwF9qJY5WSLmXR/s4pruxVRmfV7yQ==",
"requires": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7"
},
"dependencies": {
"@types/node": {
"version": "18.19.103",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.103.tgz",
"integrity": "sha512-hHTHp+sEz6SxFsp+SA+Tqrua3AbmlAw+Y//aEwdHrdZkYVRWdvWD3y5uPZ0flYOkgskaFWqZ/YGFm3FaFQ0pRw==",
"requires": {
"undici-types": "~5.26.4"
}
}
}
},
"@changesets/apply-release-plan": {
"version": "7.0.8",
"resolved": "https://registry.npmjs.org/@changesets/apply-release-plan/-/apply-release-plan-7.0.8.tgz",
@@ -34148,11 +34092,6 @@
"integrity": "sha512-Pb6M8TDO9DtSVla9yXSTAxmo9GVEouq5P40DWXdOie69bXogZTkgvopCq+yEvTMA0F6PEvdJmbtTV3ccIp11VQ==",
"dev": true
},
"@streamparser/json": {
"version": "0.0.22",
"resolved": "https://registry.npmjs.org/@streamparser/json/-/json-0.0.22.tgz",
"integrity": "sha512-b6gTSBjJ8G8SuO3Gbbj+zXbVx8NSs1EbpbMKpzGLWMdkR+98McH9bEjSz3+0mPJf68c5nxa3CrJHp5EQNXM6zQ=="
},
"@szmarczak/http-timer": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-5.0.1.tgz",
+1 -3
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.17.6",
"version": "3.17.5",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -349,7 +349,6 @@
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
"@google/genai": "^0.13.0",
"@grpc/grpc-js": "^1.9.15",
@@ -363,7 +362,6 @@
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@vscode/codicons": "^0.0.36",
"archiver": "^7.0.1",
"axios": "^1.8.2",
-3
View File
@@ -16,7 +16,4 @@ service AccountService {
// Handles the user clicking the logout button in the UI.
// Clears API keys and user state.
rpc accountLogoutClicked(EmptyRequest) returns (Empty);
// Subscribe to auth callback events (when authentication tokens are received)
rpc subscribeToAuthCallback(EmptyRequest) returns (stream String);
}
-5
View File
@@ -58,8 +58,3 @@ message Boolean {
message StringArray {
repeated string values = 1;
}
message StringArrays {
repeated string values1 = 1;
repeated string values2 = 2;
}
-3
View File
@@ -31,9 +31,6 @@ service FileService {
// Select images from the file system and return as data URLs
rpc selectImages(EmptyRequest) returns (StringArray);
// Select images and other files from the file system and returns as data URLs & paths respectively
rpc selectFiles(EmptyRequest) returns (StringArrays);
// Convert URIs to workspace-relative paths
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
-1
View File
@@ -37,7 +37,6 @@ message ChatSettings {
message ChatContent {
optional string message = 1;
repeated string images = 2;
repeated string files = 3;
}
// Message for auto approval settings
-4
View File
@@ -11,8 +11,6 @@ service TaskService {
rpc cancelTask(EmptyRequest) returns (Empty);
// Clears the current task
rpc clearTask(EmptyRequest) returns (Empty);
// Gets the total size of all tasks
rpc getTotalTasksSize(EmptyRequest) returns (Int64);
// Deletes multiple tasks with the given IDs
rpc deleteTasksWithIds(StringArrayRequest) returns (Empty);
// Creates a new task with the given text and optional images
@@ -40,7 +38,6 @@ message NewTaskRequest {
Metadata metadata = 1;
string text = 2;
repeated string images = 3;
repeated string files = 4;
}
// Request message for toggling task favorite status
@@ -105,5 +102,4 @@ message AskResponseRequest {
string response_type = 2;
string text = 3;
repeated string images = 4;
repeated string files = 5;
}
-1
View File
@@ -9,7 +9,6 @@ import "common.proto";
service WebService {
rpc checkIsImageUrl(StringRequest) returns (IsImageUrl);
rpc fetchOpenGraphData(StringRequest) returns (OpenGraphData);
rpc openInBrowser(StringRequest) returns (Empty);
}
message IsImageUrl {
-3
View File
@@ -24,7 +24,6 @@ import { FireworksHandler } from "./providers/fireworks"
import { AskSageHandler } from "./providers/asksage"
import { XAIHandler } from "./providers/xai"
import { SambanovaHandler } from "./providers/sambanova"
import { CerebrasHandler } from "./providers/cerebras"
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
@@ -85,8 +84,6 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
return new XAIHandler(options)
case "sambanova":
return new SambanovaHandler(options)
case "cerebras":
return new CerebrasHandler(options)
default:
return new AnthropicHandler(options)
}
-169
View File
@@ -1,169 +0,0 @@
import { Anthropic } from "@anthropic-ai/sdk"
import Cerebras from "@cerebras/cerebras_cloud_sdk"
import { withRetry } from "../retry"
import { ApiHandlerOptions, ModelInfo, CerebrasModelId, cerebrasDefaultModelId, cerebrasModels } from "@shared/api"
import { ApiHandler } from "../index"
import { ApiStream } from "@api/transform/stream"
export class CerebrasHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Cerebras
constructor(options: ApiHandlerOptions) {
this.options = options
// Clean and validate the API key
const cleanApiKey = this.options.cerebrasApiKey?.trim()
if (!cleanApiKey) {
throw new Error("Cerebras API key is required")
}
this.client = new Cerebras({
apiKey: cleanApiKey,
timeout: 30000, // 30 second timeout
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
// Convert Anthropic messages to Cerebras format
const cerebrasMessages: Array<{
role: "system" | "user" | "assistant"
content: string
}> = [{ role: "system", content: systemPrompt }]
// Convert Anthropic messages to Cerebras format
for (const message of messages) {
if (message.role === "user") {
const content = Array.isArray(message.content)
? message.content
.map((block) => {
if (block.type === "text") {
return block.text
} else if (block.type === "image") {
return "[Image content not supported in Cerebras]"
}
return ""
})
.join("\n")
: message.content
cerebrasMessages.push({ role: "user", content })
} else if (message.role === "assistant") {
const content = Array.isArray(message.content)
? message.content
.map((block) => {
if (block.type === "text") {
return block.text
}
return ""
})
.join("\n")
: message.content || ""
cerebrasMessages.push({ role: "assistant", content })
}
}
try {
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: cerebrasMessages,
temperature: 0,
stream: true,
})
// Handle streaming response
let reasoning: string | null = null // Track reasoning content for models that support thinking
const modelId = this.getModel().id
const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill")
for await (const chunk of stream as any) {
// Type assertion for the streaming chunk
const streamChunk = chunk as any
if (streamChunk.choices?.[0]?.delta?.content) {
const content = streamChunk.choices[0].delta.content
// Handle reasoning models (Qwen and DeepSeek R1 Distill) that use <think> tags
if (isReasoningModel) {
// Check if we're entering or continuing reasoning mode
if (reasoning || content.includes("<think>")) {
reasoning = (reasoning || "") + content
// Clean the content by removing think tags for display
let cleanContent = content.replace(/<think>/g, "").replace(/<\/think>/g, "")
// Only yield reasoning content if there's actual content after cleaning
if (cleanContent.trim()) {
yield {
type: "reasoning",
reasoning: cleanContent,
}
}
// Check if reasoning is complete
if (reasoning.includes("</think>")) {
reasoning = null
}
} else {
// Regular content outside of thinking tags
yield {
type: "text",
text: content,
}
}
} else {
// Non-reasoning models - just yield text content
yield {
type: "text",
text: content,
}
}
}
// Handle usage information from Cerebras API
// Usage is typically only available in the final chunk
if (streamChunk.usage) {
const totalCost = this.calculateCost({
inputTokens: streamChunk.usage.prompt_tokens || 0,
outputTokens: streamChunk.usage.completion_tokens || 0,
})
yield {
type: "usage",
inputTokens: streamChunk.usage.prompt_tokens || 0,
outputTokens: streamChunk.usage.completion_tokens || 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
totalCost,
}
}
}
} catch (error) {
throw error
}
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in cerebrasModels) {
const id = modelId as CerebrasModelId
return { id, info: cerebrasModels[id] }
}
return {
id: cerebrasDefaultModelId,
info: cerebrasModels[cerebrasDefaultModelId],
}
}
private calculateCost({ inputTokens, outputTokens }: { inputTokens: number; outputTokens: number }): number {
const model = this.getModel()
const inputPrice = model.info.inputPrice || 0
const outputPrice = model.info.outputPrice || 0
const inputCost = (inputPrice / 1_000_000) * inputTokens
const outputCost = (outputPrice / 1_000_000) * outputTokens
return inputCost + outputCost
}
}
-135
View File
@@ -1,135 +0,0 @@
import { JSONParser } from "@streamparser/json"
// Fallback type definition based on the error message: "Property 'value' is optional in type 'ParsedElementInfo'"
type ParsedElementInfo = {
value?: any
key?: string | number
parent?: any
stack?: any[]
}
export interface ReplacementItem {
old_str: string
new_str: string
}
export interface ChangeLocation {
startLine: number
endLine: number
startChar: number
endChar: number
}
export class StreamingJsonReplacer {
private currentFileContent: string
private parser: JSONParser
private onContentUpdated: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void
private onErrorCallback: (error: Error) => void
private itemsProcessed: number = 0
private successfullyParsedItems: ReplacementItem[] = []
constructor(
initialContent: string,
onContentUpdatedCallback: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void,
onErrorCallback: (error: Error) => void,
) {
this.currentFileContent = initialContent
this.onContentUpdated = onContentUpdatedCallback
this.onErrorCallback = onErrorCallback
this.parser = new JSONParser({ paths: ["$.replacements.*"] })
this.parser.onValue = (parsedElementInfo: ParsedElementInfo) => {
const { value } = parsedElementInfo // Destructure to get value, which might be undefined
// This callback is triggered for each item matched by '$.replacements.*'
if (value && typeof value === "object" && "old_str" in value && "new_str" in value) {
const item = value as ReplacementItem // Value here is confirmed to be an object
if (typeof item.old_str === "string" && typeof item.new_str === "string") {
this.successfullyParsedItems.push(item) // Store the structurally valid item
if (this.currentFileContent.includes(item.old_str)) {
// Calculate the change location before making the replacement
const changeLocation = this.calculateChangeLocation(item.old_str, item.new_str)
this.currentFileContent = this.currentFileContent.replace(item.old_str, item.new_str)
this.itemsProcessed++
// Notify that an item has been processed. The `isFinalItem` argument here is tricky
// as we don't know from the parser alone if this is the *absolute* last item
// until the stream ends. The caller (Task.ts) will manage the final update.
// For now, we'll pass `false` and let Task.ts handle the final diff view update.
this.onContentUpdated(this.currentFileContent, false, changeLocation)
} else {
const snippet = item.old_str.length > 50 ? item.old_str.substring(0, 47) + "..." : item.old_str
const error = new Error(`Streaming Replacement failed: 'old_str' not found. Snippet: "${snippet}"`)
this.onErrorCallback(error) // Call our own error callback
}
} else {
const error = new Error(`Invalid item structure in replacements stream: ${JSON.stringify(item)}`)
this.onErrorCallback(error) // Call our own error callback
}
} else if (value && (Array.isArray(value) || (typeof value === "object" && "replacements" in value))) {
// This might be the 'replacements' array itself or the root object.
// The `paths: ['$.replacements.*']` should mean we only get items.
// If we get here, it's likely the root object if paths wasn't specific enough or if it's an empty replacements array.
console.log("Streaming parser emitted container:", value)
} else {
// Value is not a ReplacementItem or a known container, could be an issue with the JSON structure or path.
// If `paths` is correct, this path should ideally not be hit often for valid streams.
console.warn("Streaming parser emitted unexpected value:", value)
}
}
this.parser.onError = (err: Error) => {
// Propagate the error to the caller via the callback
this.onErrorCallback(err)
// Note: The @streamparser/json library might throw synchronously on write if onError is not set,
// or if it re-throws. We'll ensure Task.ts wraps write/end in try-catch.
}
}
public write(jsonChunk: string): void {
// Errors during write will be caught by the parser's onError or thrown.
this.parser.write(jsonChunk)
}
public getCurrentContent(): string {
return this.currentFileContent
}
public getSuccessfullyParsedItems(): ReplacementItem[] {
return [...this.successfullyParsedItems] // Return a copy
}
private calculateChangeLocation(oldStr: string, newStr: string): ChangeLocation {
// Find the index where the old string starts
const startIndex = this.currentFileContent.indexOf(oldStr)
if (startIndex === -1) {
// This shouldn't happen since we already checked includes(), but just in case
return { startLine: 0, endLine: 0, startChar: 0, endChar: 0 }
}
// Calculate line numbers by counting newlines before the start index
const contentBeforeStart = this.currentFileContent.substring(0, startIndex)
const startLine = (contentBeforeStart.match(/\n/g) || []).length
// Calculate the end index after replacement
const endIndex = startIndex + oldStr.length
const contentBeforeEnd = this.currentFileContent.substring(0, endIndex)
const endLine = (contentBeforeEnd.match(/\n/g) || []).length
// Calculate character positions within their respective lines
const lastNewlineBeforeStart = contentBeforeStart.lastIndexOf("\n")
const startChar = lastNewlineBeforeStart === -1 ? startIndex : startIndex - lastNewlineBeforeStart - 1
const lastNewlineBeforeEnd = contentBeforeEnd.lastIndexOf("\n")
const endChar = lastNewlineBeforeEnd === -1 ? endIndex : endIndex - lastNewlineBeforeEnd - 1
return {
startLine,
endLine,
startChar,
endChar,
}
}
}
@@ -1,59 +0,0 @@
import { Controller } from "../index"
import { EmptyRequest } from "../../../shared/proto/common"
import { String as ProtoString } from "../../../shared/proto/common"
import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler"
// Keep track of active authCallback subscriptions
const activeAuthCallbackSubscriptions = new Set<StreamingResponseHandler>()
/**
* Subscribe to authCallback events
* @param controller The controller instance
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToAuthCallback(
controller: Controller,
request: EmptyRequest,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
// Add this subscription to the active subscriptions
activeAuthCallbackSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeAuthCallbackSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "authCallback_subscription" }, responseStream)
}
}
/**
* Send an authCallback event to all active subscribers
* @param customToken The custom token for authentication
*/
export async function sendAuthCallbackEvent(customToken: string): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeAuthCallbackSubscriptions).map(async (responseStream) => {
try {
const event: ProtoString = {
value: customToken,
}
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending authCallback event:", error)
// Remove the subscription if there was an error
activeAuthCallbackSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
-21
View File
@@ -1,21 +0,0 @@
import { Controller } from ".."
import { BooleanRequest, StringArrays } from "@shared/proto/common"
import { selectFiles as selectFilesIntegration } from "@integrations/misc/process-files"
import { FileMethodHandler } from "./index"
/**
* Prompts the user to select images from the file system and returns them as data URLs
* @param controller The controller instance
* @param request Boolean request, with the value defining whether this model supports images
* @returns Two arrays of image data URLs and other file paths
*/
export const selectFiles: FileMethodHandler = async (controller: Controller, request: BooleanRequest): Promise<StringArrays> => {
try {
const { images, files } = await selectFilesIntegration(request.value)
return StringArrays.create({ values1: images, values2: files })
} catch (error) {
console.error("Error selecting images & files:", error)
// Return empty array on error
return StringArrays.create({ values1: [], values2: [] })
}
}
+75 -28
View File
@@ -23,7 +23,7 @@ import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { ApiProvider, ModelInfo } from "@shared/api"
import { ChatContent } from "@shared/ChatContent"
import { ChatSettings } from "@shared/ChatSettings"
import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage"
import { ExtensionMessage, ExtensionState, Invoke, Platform } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { McpDownloadResponse, McpMarketplaceCatalog, McpServer } from "@shared/mcp"
import { TelemetrySetting } from "@shared/TelemetrySetting"
@@ -52,7 +52,6 @@ import {
import { Task, cwd } from "../task"
import { ClineRulesToggles } from "@shared/cline-rules"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback"
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"
@@ -141,7 +140,7 @@ export class Controller {
await updateGlobalState(this.context, "userInfo", info)
}
async initTask(task?: string, images?: string[], files?: string[], historyItem?: HistoryItem) {
async initTask(task?: string, images?: string[], historyItem?: HistoryItem) {
await this.clearTask() // ensures that an existing task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
const {
apiConfiguration,
@@ -188,7 +187,6 @@ export class Controller {
customInstructions,
task,
images,
files,
historyItem,
)
}
@@ -196,7 +194,7 @@ export class Controller {
async reinitExistingTaskFromId(taskId: string) {
const history = await this.getTaskWithId(taskId)
if (history) {
await this.initTask(undefined, undefined, undefined, history.historyItem)
await this.initTask(undefined, undefined, history.historyItem)
}
}
@@ -263,6 +261,13 @@ export class Controller {
}
}
})
// If user already opted in to telemetry, enable telemetry service
this.getStateToPostToWebview().then((state) => {
const { telemetrySetting } = state
const isOptedIn = telemetrySetting !== "disabled"
telemetryService.updateTelemetryState(isOptedIn)
})
break
case "showChatView": {
this.postMessageToWebview({
@@ -280,7 +285,7 @@ export class Controller {
// Could also do this in extension .ts
//this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
// initializing new instance of Cline will make sure that any agentically running promises in old instance don't affect our new task. this essentially creates a fresh slate for the new task
await this.initTask(message.text, message.images, message.files)
await this.initTask(message.text, message.images)
break
case "apiConfiguration":
if (message.apiConfiguration) {
@@ -292,8 +297,15 @@ export class Controller {
await this.postStateToWebview()
break
case "optionsResponse":
if (this.task) {
await this.task.handleWebviewAskResponse("messageResponse", message.text || "", [])
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: message.text,
})
break
case "openInBrowser":
if (message.url) {
vscode.env.openExternal(vscode.Uri.parse(message.url))
}
break
case "fetchUserCreditsData": {
@@ -357,10 +369,32 @@ export class Controller {
}
break
}
case "requestTotalTasksSize": {
this.refreshTotalTasksSize()
break
}
case "fetchLatestMcpServersFromHub": {
this.mcpHub?.sendLatestMcpServers()
break
}
case "openExtensionSettings": {
const settingsFilter = message.text || ""
await vscode.commands.executeCommand(
"workbench.action.openSettings",
`@ext:saoudrizwan.claude-dev ${settingsFilter}`.trim(), // trim whitespace if no settings filter
)
break
}
case "invoke": {
if (message.text) {
await this.postMessageToWebview({
type: "invoke",
invoke: message.text as Invoke,
})
}
break
}
// telemetry
case "telemetrySetting": {
if (message.telemetrySetting) {
@@ -423,9 +457,11 @@ export class Controller {
if (answer === "Delete All Except Favorites") {
await this.deleteNonFavoriteTaskHistory()
await this.postStateToWebview()
this.refreshTotalTasksSize()
} else if (answer === "Delete Everything") {
await this.deleteAllTaskHistory()
await this.postStateToWebview()
this.refreshTotalTasksSize()
}
this.postMessageToWebview({ type: "relinquishControl" })
break
@@ -442,13 +478,6 @@ export class Controller {
}
break
}
case "executeQuickWin":
if (message.payload) {
const { command, title } = message.payload
this.outputChannel.appendLine(`Received executeQuickWin: command='${command}', title='${title}'`)
await this.initTask(title)
}
break
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
@@ -615,12 +644,12 @@ export class Controller {
if (this.task.isAwaitingPlanResponse && didSwitchToActMode) {
this.task.didRespondToPlanAskBySwitchingMode = true
// Use chatContent if provided, otherwise use default message
await this.task.handleWebviewAskResponse(
"messageResponse",
chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
chatContent?.images || [],
chatContent?.files || [],
)
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
images: chatContent?.images,
})
} else {
this.cancelTask()
}
@@ -651,7 +680,7 @@ export class Controller {
// 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request
this.task.abandoned = true
}
await this.initTask(undefined, undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
await this.initTask(undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
// await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list
}
}
@@ -695,7 +724,10 @@ export class Controller {
await storeSecret(this.context, "clineApiKey", apiKey)
// Send custom token to webview for Firebase auth
await sendAuthCallbackEvent(customToken)
await this.postMessageToWebview({
type: "authCallback",
customToken,
})
const clineProvider: ApiProvider = "cline"
await updateGlobalState(this.context, "apiProvider", clineProvider)
@@ -767,7 +799,6 @@ export class Controller {
const response = await axios.get("https://api.cline.bot/v1/mcp/marketplace", {
headers: {
"Content-Type": "application/json",
"User-Agent": "cline-vscode-extension",
},
})
@@ -1042,7 +1073,7 @@ export class Controller {
if (id !== this.task?.taskId) {
// non-current task
const { historyItem } = await this.getTaskWithId(id)
await this.initTask(undefined, undefined, undefined, historyItem) // clears existing task
await this.initTask(undefined, undefined, historyItem) // clears existing task
}
await this.postMessageToWebview({
type: "action",
@@ -1114,6 +1145,19 @@ export class Controller {
await this.postStateToWebview()
}
async refreshTotalTasksSize() {
getTotalTasksSize(this.context.globalStorageUri.fsPath)
.then((newTotalSize) => {
this.postMessageToWebview({
type: "totalTasksSize",
totalTasksSize: newTotalSize,
})
})
.catch((error) => {
console.error("Error calculating total tasks size:", error)
})
}
async deleteTaskWithId(id: string) {
console.info("deleteTaskWithId: ", id)
@@ -1156,7 +1200,7 @@ export class Controller {
console.debug(`Error deleting task:`, error)
}
await this.postStateToWebview()
this.refreshTotalTasksSize()
}
async deleteTaskFromState(id: string) {
@@ -1173,7 +1217,10 @@ export class Controller {
async postStateToWebview() {
const state = await this.getStateToPostToWebview()
await sendStateUpdate(state)
// For testing: Bypass gRPC stream and send state directly
console.log("[Controller Test Revert] Posting full state via direct 'state' message.")
await this.postMessageToWebview({ type: "state", state: state })
// await sendStateUpdate(state) // Original line for the GrPC stream
}
async getStateToPostToWebview(): Promise<ExtensionState> {
@@ -1229,7 +1276,7 @@ export class Controller {
telemetrySetting,
planActSeparateModelsSetting,
enableCheckpointsSetting: enableCheckpointsSetting ?? true,
distinctId: telemetryService.distinctId,
vscMachineId: vscode.env.machineId,
globalClineRulesToggles: globalClineRulesToggles || {},
localClineRulesToggles: localClineRulesToggles || {},
localWindsurfRulesToggles: localWindsurfRulesToggles || {},
+1 -1
View File
@@ -35,7 +35,7 @@ export async function askResponse(controller: Controller, request: AskResponseRe
}
// Call the task's handler for webview responses
await controller.task.handleWebviewAskResponse(responseType, request.text, request.images, request.files)
await controller.task.handleWebviewAskResponse(responseType, request.text, request.images)
return Empty.create()
} catch (error) {
@@ -1,14 +0,0 @@
import { Controller } from ".."
import { EmptyRequest, Int64 } from "../../../shared/proto/common"
import { getTotalTasksSize as calculateTotalTasksSize } from "../../../utils/storage"
/**
* Gets the total size of all tasks including task data and checkpoints
* @param controller The controller instance
* @param _request The empty request
* @returns The total size as an Int64 value
*/
export async function getTotalTasksSize(controller: Controller, _request: EmptyRequest): Promise<Int64> {
const totalSize = await calculateTotalTasksSize(controller.context.globalStorageUri.fsPath)
return Int64.create({ value: totalSize || 0 })
}
+1 -1
View File
@@ -9,6 +9,6 @@ import { NewTaskRequest } from "../../../shared/proto/task"
* @returns Empty response
*/
export async function newTask(controller: Controller, request: NewTaskRequest): Promise<Empty> {
await controller.initTask(request.text, request.images, request.files)
await controller.initTask(request.text, request.images)
return Empty.create()
}
+2 -2
View File
@@ -19,7 +19,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
// We need to initialize the task before returning data
if (historyItem) {
// Always initialize the task with the history item
await controller.initTask(undefined, undefined, undefined, historyItem)
await controller.initTask(undefined, undefined, historyItem)
// Send UI update to show the chat view
await controller.postMessageToWebview({
@@ -46,7 +46,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
const { historyItem: fetchedItem } = await controller.getTaskWithId(id)
// Initialize the task with the fetched item
await controller.initTask(undefined, undefined, undefined, fetchedItem)
await controller.initTask(undefined, undefined, fetchedItem)
// Send UI update to show the chat view
await controller.postMessageToWebview({
-21
View File
@@ -1,21 +0,0 @@
import * as vscode from "vscode"
import { Controller } from ".."
import { Empty, StringRequest } from "../../../shared/proto/common"
/**
* Opens a URL in the user's default browser
* @param controller The controller instance
* @param request The URL to open
* @returns Empty response since the client doesn't need a return value
*/
export async function openInBrowser(controller: Controller, request: StringRequest): Promise<Empty> {
try {
if (request.value) {
await vscode.env.openExternal(vscode.Uri.parse(request.value))
}
return Empty.create()
} catch (error) {
console.error("Error opening URL in browser:", error)
return Empty.create()
}
}
+7 -23
View File
@@ -41,31 +41,15 @@ Otherwise, if you have not completed the task and do not need additional informa
invalidMcpToolArgumentError: (serverName: string, toolName: string) =>
`Invalid JSON argument used with ${serverName} for ${toolName}. Please retry with a properly formatted JSON argument.`,
toolResult: (
text: string,
images?: string[],
fileString?: string,
): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
let toolResultOutput = []
if (!(images && images.length > 0) && !fileString) {
toolResult: (text: string, images?: string[]): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
if (images && images.length > 0) {
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
// Placing images after text leads to better results
return [textBlock, ...imageBlocks]
} else {
return text
}
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
toolResultOutput.push(textBlock)
if (images && images.length > 0) {
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
toolResultOutput.push(...imageBlocks)
}
if (fileString) {
const fileBlock: Anthropic.TextBlockParam = { type: "text", text: fileString }
toolResultOutput.push(fileBlock)
}
return toolResultOutput
},
imageBlocks: (images?: string[]): Anthropic.ImageBlockParam[] => {
+3 -92
View File
@@ -9,7 +9,6 @@ export const SYSTEM_PROMPT = async (
supportsBrowserUse: boolean,
mcpHub: McpHub,
browserSettings: BrowserSettings,
isClaude4ModelFamily: boolean,
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
@@ -72,46 +71,7 @@ Your file content here
</write_to_file>
## replace_in_file
${
isClaude4ModelFamily
? `
"Description: Return your edits as a JSON object with a "replacements" array. Each replacement should have "old_str" and "new_str" fields. The old_str must match exactly what's in the file (including whitespace, indentation and new lines). You can edit multiple lines, but please keep the replacements as simple as possible.
Both old_str and new_str can be multiline strings, but they must be valid JSON strings.
Usage:
<replace_in_file>
<path>File path here</path>
<diff>
{{
"replacements": [
{{
"old_str": "exact string from file",
"new_str": "replacement string"
}}
]
}}
</diff>
</replace_in_file>
Important: Make sure each old_str matches the exact text in the file, character for character.
Parameters:
- path: (required) The path of the file to modify (relative to the current working directory ${cwd.toPosix()})
- replacements_json: (required) A JSON string containing an object with a "replacements" array. Each object in the array must have "old_str" (the exact string to find in the file) and "new_str" (the string to replace it with). Refer to the example format in the main description.
Usage:
<replace_in_file>
<path>File path here</path>
<diff>
{{
"replacements": [
{{
"old_str": "exact string from file",
"new_str": "replacement string"
}}
]
}}
</diff>
</replace_in_file>`
: `Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.
Parameters:
- path: (required) The path of the file to modify (relative to the current working directory ${cwd.toPosix()})
- diff: (required) One or more SEARCH/REPLACE blocks following this exact format:
@@ -143,9 +103,8 @@ Usage:
<path>File path here</path>
<diff>
Search and replace blocks here
</diff>
</replace_in_file>`
}
</diff>
</replace_in_file>
## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
@@ -370,31 +329,6 @@ Usage:
## Example 4: Requesting to make targeted edits to a file
<replace_in_file>
${
isClaude4ModelFamily
? `
<path>src/baseApp.py</path>
<diff>
{
"replacements": [
{
"old_str": "def try_dotdotdots(whole, part, replace):",
"new_str": "# Handles search/replace blocks that use ellipsis (...) to represent omitted code sections\n# Validates that ellipsis usage is consistent between search and replace blocks\ndef try_dotdotdots(whole, part, replace):"
},
{
"old_str": "def strip_filename(filename, fence):",
"new_str": "# Extracts and cleans filename from various markdown formatting styles\n# Handles filenames with different prefixes, suffixes, and decorations\ndef strip_filename(filename, fence):"
},
{
"old_str": "def main():",
"new_str": "# Main entry point for command-line usage\n# Processes chat history and displays diffs for all found edit blocks\ndef main():"
}
]
}
</diff>
</replace_in_file>
`
: `
<path>src/components/App.tsx</path>
<diff>
<<<<<<< SEARCH
@@ -426,9 +360,6 @@ return (
>>>>>>> REPLACE
</diff>
</replace_in_file>
`
}
## Example 5: Requesting to use an MCP tool
@@ -598,21 +529,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
# Workflow Tips
1. Before editing, assess the scope of your changes and decide which tool to use.
${
isClaude4ModelFamily
? `
2. For major overhauls or initial file creation, rely on write_to_file.
3. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
4. All edits are applied in sequence, in the order they are provided
5. All edits must be valid for the operation to succeed - if any edit fails, none will be applied
`
: `
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
`
}
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
@@ -683,17 +602,9 @@ 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.
${
isClaude4ModelFamily
? `
- When using the replace_in_file tool, you must include complete lines
`
: `
- 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.
- When using the replace_in_file tool, Do NOT add extra characters to the markers (e.g., <<<<<<< SEARCH> is INVALID). Do NOT forget to use the closing >>>>>>> REPLACE marker. Do NOT modify the marker format in any way. Malformed XML will cause complete tool failure and break the entire editing process.
`
}
- 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.${
supportsBrowserUse
? " 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."
-1
View File
@@ -21,7 +21,6 @@ export type SecretKey =
| "xaiApiKey"
| "nebiusApiKey"
| "sambanovaApiKey"
| "cerebrasApiKey"
export type GlobalStateKey =
| "apiProvider"
-6
View File
@@ -155,7 +155,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
thinkingBudgetTokens,
reasoningEffort,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
planActSeparateModelsSettingRaw,
favoritedModelIds,
@@ -245,7 +244,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getGlobalState(context, "thinkingBudgetTokens") as Promise<number | undefined>,
getGlobalState(context, "reasoningEffort") as Promise<string | undefined>,
getSecret(context, "sambanovaApiKey") as Promise<string | undefined>,
getSecret(context, "cerebrasApiKey") as Promise<string | undefined>,
getSecret(context, "nebiusApiKey") as Promise<string | undefined>,
getGlobalState(context, "planActSeparateModelsSetting") as Promise<boolean | undefined>,
getGlobalState(context, "favoritedModelIds") as Promise<string[] | undefined>,
@@ -359,7 +357,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
asksageApiUrl,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
favoritedModelIds,
requestTimeoutMs,
@@ -454,7 +451,6 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
reasoningEffort,
clineApiKey,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
favoritedModelIds,
} = apiConfiguration
@@ -516,7 +512,6 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
await updateGlobalState(context, "reasoningEffort", reasoningEffort)
await storeSecret(context, "clineApiKey", clineApiKey)
await storeSecret(context, "sambanovaApiKey", sambanovaApiKey)
await storeSecret(context, "cerebrasApiKey", cerebrasApiKey)
await storeSecret(context, "nebiusApiKey", nebiusApiKey)
await updateGlobalState(context, "favoritedModelIds", favoritedModelIds)
await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs)
@@ -547,7 +542,6 @@ export async function resetExtensionState(context: vscode.ExtensionContext) {
"asksageApiKey",
"xaiApiKey",
"sambanovaApiKey",
"cerebrasApiKey",
"nebiusApiKey",
]
for (const key of secretKeys) {
+117 -410
View File
File diff suppressed because it is too large Load Diff
-285
View File
@@ -1,285 +0,0 @@
import { describe, it, beforeEach, afterEach } from "mocha"
import * as sinon from "sinon"
import * as should from "should"
import * as vscode from "vscode"
import * as stateModule from "@core/storage/state"
import { createClineAPI } from "../index"
import type { ClineAPI } from "../cline"
describe("ClineAPI Core Functionality", () => {
let api: ClineAPI
let mockController: any
let mockOutputChannel: sinon.SinonStubbedInstance<vscode.OutputChannel>
let sandbox: sinon.SinonSandbox
let getGlobalStateStub: sinon.SinonStub
beforeEach(() => {
sandbox = sinon.createSandbox()
// Create mock output channel
mockOutputChannel = {
appendLine: sandbox.stub(),
append: sandbox.stub(),
clear: sandbox.stub(),
show: sandbox.stub(),
hide: sandbox.stub(),
dispose: sandbox.stub(),
replace: sandbox.stub(),
name: "Cline Test",
} as any
// Stub the getGlobalState function from the state module
// This is needed because the real createClineAPI uses it for getCustomInstructions
getGlobalStateStub = sandbox.stub(stateModule, "getGlobalState")
// Create a mock controller that matches what the real createClineAPI expects
// We don't import the real Controller to avoid the webview dependencies
mockController = {
context: {
globalState: {
get: sandbox.stub(),
update: sandbox.stub(),
keys: sandbox.stub().returns([]),
setKeysForSync: sandbox.stub(),
},
secrets: {
get: sandbox.stub(),
store: sandbox.stub(),
delete: sandbox.stub(),
onDidChange: sandbox.stub(),
},
},
updateCustomInstructions: sandbox.stub().resolves(),
clearTask: sandbox.stub().resolves(),
postStateToWebview: sandbox.stub().resolves(),
postMessageToWebview: sandbox.stub().resolves(),
initTask: sandbox.stub().resolves(),
task: undefined,
}
// Create API instance
api = createClineAPI(mockOutputChannel as any, mockController)
})
afterEach(() => {
sandbox.restore()
})
describe("setCustomInstructions", () => {
it("should update custom instructions in controller", async () => {
const testInstructions = "Test custom instructions"
await api.setCustomInstructions(testInstructions)
// Verify controller method was called
sinon.assert.calledOnce(mockController.updateCustomInstructions)
sinon.assert.calledWith(mockController.updateCustomInstructions, testInstructions)
// Verify output channel was updated
sinon.assert.calledWith(mockOutputChannel.appendLine, "Custom instructions set")
})
it("should handle empty instructions", async () => {
await api.setCustomInstructions("")
sinon.assert.calledWith(mockController.updateCustomInstructions, "")
sinon.assert.calledWith(mockOutputChannel.appendLine, "Custom instructions set")
})
it("should handle very long instructions", async () => {
const longInstructions = "a".repeat(10000)
await api.setCustomInstructions(longInstructions)
sinon.assert.calledWith(mockController.updateCustomInstructions, longInstructions)
})
})
describe("getCustomInstructions", () => {
it("should retrieve custom instructions from state", async () => {
const testInstructions = "Retrieved instructions"
// The real implementation uses getGlobalState from the state module
getGlobalStateStub.resolves(testInstructions)
const result = await api.getCustomInstructions()
result!.should.equal(testInstructions)
sinon.assert.calledWith(getGlobalStateStub, mockController.context, "customInstructions")
})
it("should return undefined when no instructions set", async () => {
// The real implementation uses getGlobalState from the state module
getGlobalStateStub.resolves(undefined)
const result = await api.getCustomInstructions()
should.not.exist(result)
sinon.assert.calledWith(getGlobalStateStub, mockController.context, "customInstructions")
})
})
describe("startNewTask", () => {
it("should clear existing task and start new one with description", async () => {
const taskDescription = "Create a test function"
const images = ["image1.png", "image2.png"]
await api.startNewTask(taskDescription, images)
// Verify task clearing sequence
sinon.assert.called(mockController.clearTask)
sinon.assert.called(mockController.postStateToWebview)
sinon.assert.calledWith(mockController.postMessageToWebview, {
type: "action",
action: "chatButtonClicked",
})
sinon.assert.calledWith(mockController.initTask, taskDescription, images)
// Verify logging - first it logs "Starting new task"
sinon.assert.calledWith(mockOutputChannel.appendLine, "Starting new task")
// Then it logs the task details
sinon.assert.calledWith(
mockOutputChannel.appendLine,
`Task started with message: "Create a test function" and 2 image(s)`,
)
})
it("should handle undefined task description", async () => {
await api.startNewTask(undefined, [])
sinon.assert.called(mockController.clearTask)
sinon.assert.calledWith(mockController.initTask, undefined, [])
sinon.assert.calledWith(mockOutputChannel.appendLine, "Task started with message: undefined and 0 image(s)")
})
it("should handle task with no images", async () => {
await api.startNewTask("Task without images")
sinon.assert.calledWith(mockController.initTask, "Task without images", undefined)
sinon.assert.calledWith(
mockOutputChannel.appendLine,
`Task started with message: "Task without images" and 0 image(s)`,
)
})
})
describe("sendMessage", () => {
it("should send message to active task", async () => {
const mockTask = {
handleWebviewAskResponse: sandbox.stub().resolves(),
}
mockController.task = mockTask
await api.sendMessage("Test message", ["image.png"])
sinon.assert.calledWith(mockTask.handleWebviewAskResponse, "messageResponse", "Test message", ["image.png"])
sinon.assert.calledWith(mockOutputChannel.appendLine, `Sending message: "Test message" with 1 image(s)`)
})
it("should handle no active task gracefully", async () => {
mockController.task = undefined
await api.sendMessage("Message to nowhere", [])
sinon.assert.calledWith(mockOutputChannel.appendLine, "No active task to send message to")
})
it("should handle empty message", async () => {
const mockTask = {
handleWebviewAskResponse: sandbox.stub().resolves(),
}
mockController.task = mockTask
await api.sendMessage("", [])
sinon.assert.calledWith(mockTask.handleWebviewAskResponse, "messageResponse", "", [])
})
it("should handle undefined message", async () => {
const mockTask = {
handleWebviewAskResponse: sandbox.stub().resolves(),
}
mockController.task = mockTask
await api.sendMessage(undefined, [])
sinon.assert.calledWith(mockTask.handleWebviewAskResponse, "messageResponse", "", [])
sinon.assert.calledWith(mockOutputChannel.appendLine, `Sending message: undefined with 0 image(s)`)
})
})
describe("Button Press Methods", () => {
describe("pressPrimaryButton", () => {
it("should handle primary button press with active task", async () => {
const mockTask = {
handleWebviewAskResponse: sandbox.stub().resolves(),
}
mockController.task = mockTask
await api.pressPrimaryButton()
sinon.assert.calledWith(mockTask.handleWebviewAskResponse, "yesButtonClicked", "", [])
sinon.assert.calledWith(mockOutputChannel.appendLine, "Pressing primary button")
})
it("should handle primary button press with no active task", async () => {
mockController.task = undefined
await api.pressPrimaryButton()
sinon.assert.calledWith(mockOutputChannel.appendLine, "No active task to press button for")
})
})
describe("pressSecondaryButton", () => {
it("should handle secondary button press with active task", async () => {
const mockTask = {
handleWebviewAskResponse: sandbox.stub().resolves(),
}
mockController.task = mockTask
await api.pressSecondaryButton()
sinon.assert.calledWith(mockTask.handleWebviewAskResponse, "noButtonClicked", "", [])
sinon.assert.calledWith(mockOutputChannel.appendLine, "Pressing secondary button")
})
it("should handle secondary button press with no active task", async () => {
mockController.task = undefined
await api.pressSecondaryButton()
sinon.assert.calledWith(mockOutputChannel.appendLine, "No active task to press button for")
})
})
})
describe("Error Handling", () => {
it("should handle errors in setCustomInstructions", async () => {
mockController.updateCustomInstructions.rejects(new Error("Update failed"))
try {
await api.setCustomInstructions("test")
should.fail("", "", "Should have thrown an error", "")
} catch (error: any) {
error.message.should.equal("Update failed")
}
})
it("should handle errors in task initialization", async () => {
mockController.initTask.rejects(new Error("Init failed"))
try {
await api.startNewTask("test task")
should.fail("", "", "Should have thrown an error", "")
} catch (error: any) {
error.message.should.equal("Init failed")
}
})
})
})
+20 -16
View File
@@ -22,7 +22,12 @@ export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarContr
type: "action",
action: "chatButtonClicked",
})
await sidebarController.initTask(task, images)
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: task,
images: images,
})
outputChannel.appendLine(
`Task started with message: ${task ? `"${task}"` : "undefined"} and ${images?.length || 0} image(s)`,
)
@@ -32,29 +37,28 @@ export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarContr
outputChannel.appendLine(
`Sending message: ${message ? `"${message}"` : "undefined"} with ${images?.length || 0} image(s)`,
)
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("messageResponse", message || "", images || [])
} else {
outputChannel.appendLine("No active task to send message to")
}
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: message,
images: images,
})
},
pressPrimaryButton: async () => {
outputChannel.appendLine("Pressing primary button")
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("yesButtonClicked", "", [])
} else {
outputChannel.appendLine("No active task to press button for")
}
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "primaryButtonClick",
})
},
pressSecondaryButton: async () => {
outputChannel.appendLine("Pressing secondary button")
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("noButtonClicked", "", [])
} else {
outputChannel.appendLine("No active task to press button for")
}
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "secondaryButtonClick",
})
},
}
-11
View File
@@ -14,7 +14,6 @@ import { Controller } from "./core/controller"
import { ErrorService } from "./services/error/ErrorService"
import { initializeTestMode, cleanupTestMode } from "./services/test/TestMode"
import { telemetryService } from "./services/posthog/telemetry/TelemetryService"
import { v4 as uuidv4 } from "uuid"
/*
Built using https://github.com/microsoft/vscode-webview-ui-toolkit
@@ -76,16 +75,6 @@ export async function activate(context: vscode.ExtensionContext) {
console.error(`Error during post-update actions: ${errorMessage}, Stack trace: ${error.stack}`)
}
// backup id in case vscMachineID doesn't work
let installId = context.globalState.get<string>("installId")
if (!installId) {
installId = uuidv4()
await context.globalState.update("installId", installId)
}
telemetryService.captureExtensionActivated(installId)
context.subscriptions.push(
vscode.commands.registerCommand("cline.plusButtonClicked", async (webview: any) => {
const openChat = async (instance?: WebviewProvider) => {
+20 -31
View File
@@ -101,11 +101,7 @@ export class DiffViewProvider {
})
}
async update(
accumulatedContent: string,
isFinal: boolean,
changeLocation?: { startLine: number; endLine: number; startChar: number; endChar: number },
) {
async update(accumulatedContent: string, isFinal: boolean) {
if (!this.relPath || !this.activeLineController || !this.fadedOverlayController) {
throw new Error("Required values not set")
}
@@ -152,36 +148,29 @@ export class DiffViewProvider {
this.activeLineController.setActiveLine(currentLine)
this.fadedOverlayController.updateOverlayAfterLine(currentLine, document.lineCount)
// Scroll to the actual change location if provided, otherwise use the old logic
// Scroll to the last changed line only if the user hasn't scrolled up
if (this.shouldAutoScroll) {
if (changeLocation) {
// We have the actual location of the change, scroll to it
const targetLine = changeLocation.startLine
this.scrollEditorToLine(targetLine)
if (diffLines.length <= 5) {
// For small changes, just jump directly to the line
this.scrollEditorToLine(currentLine)
} else {
// Fallback to the old logic for non-replacement updates
if (diffLines.length <= 5) {
// For small changes, just jump directly to the line
this.scrollEditorToLine(currentLine)
} else {
// For larger changes, create a quick scrolling animation
const startLine = this.streamedLines.length
const endLine = currentLine
const totalLines = endLine - startLine
const numSteps = 10 // Adjust this number to control animation speed
const stepSize = Math.max(1, Math.floor(totalLines / numSteps))
// For larger changes, create a quick scrolling animation
const startLine = this.streamedLines.length
const endLine = currentLine
const totalLines = endLine - startLine
const numSteps = 10 // Adjust this number to control animation speed
const stepSize = Math.max(1, Math.floor(totalLines / numSteps))
// Create and await the smooth scrolling animation
for (let line = startLine; line <= endLine; line += stepSize) {
this.activeDiffEditor?.revealRange(
new vscode.Range(line, 0, line, 0),
vscode.TextEditorRevealType.InCenter,
)
await new Promise((resolve) => setTimeout(resolve, 16)) // ~60fps
}
// Ensure we end at the final line
this.scrollEditorToLine(currentLine)
// Create and await the smooth scrolling animation
for (let line = startLine; line <= endLine; line += stepSize) {
this.activeDiffEditor?.revealRange(
new vscode.Range(line, 0, line, 0),
vscode.TextEditorRevealType.InCenter,
)
await new Promise((resolve) => setTimeout(resolve, 16)) // ~60fps
}
// Ensure we end at the final line
this.scrollEditorToLine(currentLine)
}
}
}
-31
View File
@@ -75,34 +75,3 @@ async function extractTextFromIPYNB(filePath: string): Promise<string> {
return extractedText
}
/**
* Helper function used to load file(s) and format them into a string
*/
export async function processFilesIntoText(files: string[]): Promise<string> {
const fileContentsPromises = files.map(async (filePath) => {
try {
// Check if file exists and is binary
//const isBinary = await isBinaryFile(filePath).catch(() => false)
//if (isBinary) {
// return `<file_content path="${filePath.toPosix()}">\n(Binary file, unable to display content)\n</file_content>`
//}
const content = await extractTextFromFile(filePath)
return `<file_content path="${filePath.toPosix()}">\n${content}\n</file_content>`
} catch (error) {
console.error(`Error processing file ${filePath}:`, error)
return `<file_content path="${filePath.toPosix()}">\nError fetching content: ${error.message}\n</file_content>`
}
})
const fileContents = await Promise.all(fileContentsPromises)
const validFileContents = fileContents.filter((content) => content !== null).join("\n\n")
if (validFileContents) {
return `Files attached by the user:\n\n${validFileContents}`
}
// returns empty string if no files were loaded properly
return ""
}
-109
View File
@@ -1,109 +0,0 @@
import * as vscode from "vscode"
import fs from "fs/promises"
import * as path from "path"
import sizeOf from "image-size"
/**
* Supports processing of images and other file types
* For models which don't support images, will not allow them to be selected
*/
export async function selectFiles(imagesAllowed: boolean): Promise<{ images: string[]; files: string[] }> {
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"] // supported by anthropic and openrouter
const OTHER_FILE_EXTENSIONS = ["xml", "json", "txt", "log", "md", "docx", "ipynb", "pdf"]
const options: vscode.OpenDialogOptions = {
canSelectMany: true,
openLabel: "Select",
filters: {
Files: imagesAllowed ? [...IMAGE_EXTENSIONS, ...OTHER_FILE_EXTENSIONS] : OTHER_FILE_EXTENSIONS,
},
}
const fileUris = await vscode.window.showOpenDialog(options)
if (!fileUris || fileUris.length === 0) {
return { images: [], files: [] }
}
const processFilesPromises = fileUris.map(async (uri) => {
const filePath = uri.fsPath
const fileExtension = path.extname(filePath).toLowerCase().substring(1)
//const fileName = path.basename(filePath)
const isImage = IMAGE_EXTENSIONS.includes(fileExtension)
if (isImage) {
let buffer: Buffer
try {
// Read the file into a buffer first
buffer = await fs.readFile(filePath)
// Convert Node.js Buffer to Uint8Array
const uint8Array = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
const dimensions = sizeOf(uint8Array) // Get dimensions from Uint8Array
if (dimensions.width! > 7500 || dimensions.height! > 7500) {
console.warn(`Image dimensions exceed 7500px, skipping: ${filePath}`)
vscode.window.showErrorMessage(
`Image too large: ${path.basename(filePath)} was skipped (dimensions exceed 7500px).`,
)
return null
}
} catch (error) {
console.error(`Error reading file or getting dimensions for ${filePath}:`, error)
vscode.window.showErrorMessage(`Could not read dimensions for ${path.basename(filePath)}, skipping.`)
return null
}
// If dimensions are valid, proceed to convert the existing buffer to base64
const base64 = buffer.toString("base64")
const mimeType = getMimeType(filePath)
return { type: "image", data: `data:${mimeType};base64,${base64}` }
} else {
// for standard models we will check the size of the file to ensure its not too large
try {
const stats = await fs.stat(filePath)
if (stats.size > 20 * 1000 * 1024) {
console.warn(`File too large, skipping: ${filePath}`)
vscode.window.showErrorMessage(`File too large: ${path.basename(filePath)} was skipped (size exceeds 20MB).`)
return null
}
} catch (error) {
console.error(`Error checking file size for ${filePath}:`, error)
vscode.window.showErrorMessage(`Could not check file size for ${path.basename(filePath)}, skipping.`)
return null
}
return { type: "file", data: filePath }
}
})
const dataUrlsWithNulls = await Promise.all(processFilesPromises)
const dataUrlsWithoutNulls = dataUrlsWithNulls.filter((item) => item !== null)
const images: string[] = []
const files: string[] = []
for (const item of dataUrlsWithoutNulls) {
if (item.type === "image") {
images.push(item.data)
} else {
files.push(item.data)
}
}
return { images, files }
}
function getMimeType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase()
switch (ext) {
case ".png":
return "image/png"
case ".jpeg":
case ".jpg":
return "image/jpeg"
case ".webp":
return "image/webp"
default:
throw new Error(`Unsupported file type: ${ext}`)
}
}
@@ -9,6 +9,7 @@ class PostHogClientProvider {
this.client = new PostHog(posthogConfig.apiKey, {
host: posthogConfig.host,
enableExceptionAutocapture: false,
defaultOptIn: false,
})
}
+191 -110
View File
@@ -7,7 +7,7 @@ import type { BrowserSettings } from "@shared/BrowserSettings"
import { posthogClientProvider } from "../PostHogClientProvider"
/**
* TelemetryService handles telemetry event tracking for the Cline extension
* PostHogClient handles telemetry event tracking for the Cline extension
* Uses PostHog analytics to track user interactions and system events
* Respects user privacy settings and VSCode's global telemetry configuration
*/
@@ -29,7 +29,7 @@ interface Collection {
*/
type TelemetryCategory = "checkpoints" | "browser"
class TelemetryService {
class PostHogClient {
// Map to control specific telemetry categories (event types)
private telemetryCategoryEnabled: Map<TelemetryCategory, boolean> = new Map([
["checkpoints", false], // Checkpoints telemetry disabled
@@ -41,11 +41,6 @@ class TelemetryService {
// Event constants for tracking user interactions and system events
private static readonly EVENTS = {
// Task-related events for tracking conversation and execution flow
USER: {
OPT_OUT: "user.opt_out",
EXTENSION_ACTIVATED: "user.extension_activated",
},
TASK: {
// Tracks when a new task/conversation is started
CREATED: "task.created",
@@ -88,21 +83,37 @@ class TelemetryService {
},
// UI interaction events for tracking user engagement
UI: {
// Tracks when user switches between API providers
PROVIDER_SWITCH: "ui.provider_switch",
// Tracks when images are attached to a conversation
IMAGE_ATTACHED: "ui.image_attached",
// Tracks general button click interactions
BUTTON_CLICK: "ui.button_click",
// Tracks when the marketplace view is opened
MARKETPLACE_OPENED: "ui.marketplace_opened",
// Tracks when settings panel is opened
SETTINGS_OPENED: "ui.settings_opened",
// Tracks when task history view is opened
HISTORY_OPENED: "ui.history_opened",
// Tracks when a task is removed from history
TASK_POPPED: "ui.task_popped",
// Tracks when a different model is selected
MODEL_SELECTED: "ui.model_selected",
// Tracks when planning mode is toggled on
PLAN_MODE_TOGGLED: "ui.plan_mode_toggled",
// Tracks when action mode is toggled on
ACT_MODE_TOGGLED: "ui.act_mode_toggled",
// Tracks when users use the "favorite" button in the model picker
MODEL_FAVORITE_TOGGLED: "ui.model_favorite_toggled",
// Tracks when a button is clicked
BUTTON_CLICKED: "ui.button_clicked",
},
}
/** Singleton instance of the TelemetryService */
private static instance: TelemetryService
/** Singleton instance of the PostHogClient */
private static instance: PostHogClient
/** PostHog client instance for sending analytics events */
private client: PostHog
/** Unique identifier for the current VSCode instance */
public distinctId: string = vscode.env.machineId
private distinctId: string = vscode.env.machineId
/** Whether telemetry is currently enabled based on user and VSCode settings */
private telemetryEnabled: boolean = false
/** Current version of the extension */
@@ -118,18 +129,14 @@ class TelemetryService {
this.client = posthogClientProvider.getClient()
}
private setDistinctId(installId: string) {
if (this.distinctId === "someValue.machineId") {
this.distinctId = installId
}
}
/**
* Updates the telemetry state based on user preferences and VSCode settings
* Only enables telemetry if both VSCode global telemetry is enabled and user has opted in
* @param didUserOptIn Whether the user has explicitly opted into telemetry
*/
public async updateTelemetryState(didUserOptIn: boolean): Promise<void> {
public updateTelemetryState(didUserOptIn: boolean): void {
this.telemetryEnabled = false
// First check global telemetry level - telemetry should only be enabled when level is "all"
const telemetryLevel = vscode.workspace.getConfiguration("telemetry").get<string>("telemetryLevel", "all")
const globalTelemetryEnabled = telemetryLevel === "all"
@@ -137,53 +144,25 @@ class TelemetryService {
// We only enable telemetry if global vscode telemetry is enabled
if (globalTelemetryEnabled) {
this.telemetryEnabled = didUserOptIn
} else {
// Show warning to user that global telemetry is disabled
void vscode.window
.showWarningMessage(
"VSCode telemetry is disabled. To enable telemetry for this extension, first enable VSCode telemetry in settings.",
"Open Settings",
)
.then((selection) => {
if (selection === "Open Settings") {
void vscode.commands.executeCommand("workbench.action.openSettings", "telemetry.telemetryLevel")
}
})
}
// Update PostHog client state based on telemetry preference
if (this.telemetryEnabled) {
this.client.optIn()
this.client.identify({ distinctId: this.distinctId })
} else {
this.client.capture({
distinctId: this.distinctId,
event: TelemetryService.EVENTS.USER.OPT_OUT,
properties: this.addProperties({}),
})
await new Promise((resolve) => setTimeout(resolve, 1000)) // Delay 1 second before opting out
this.client.optOut()
}
}
/**
* Gets or creates the singleton instance of TelemetryService
* @returns The TelemetryService instance
* Gets or creates the singleton instance of PostHogClient
* @returns The PostHogClient instance
*/
public static getInstance(): TelemetryService {
if (!TelemetryService.instance) {
TelemetryService.instance = new TelemetryService()
}
return TelemetryService.instance
}
private addProperties(properties: any): any {
return {
...properties,
extension_version: this.version,
is_dev: this.isDev,
public static getInstance(): PostHogClient {
if (!PostHogClient.instance) {
PostHogClient.instance = new PostHogClient()
}
return PostHogClient.instance
}
/**
@@ -192,14 +171,13 @@ class TelemetryService {
* @param collect If true, store the event in collectedEvents instead of sending to PostHog
*/
public capture(event: { event: string; properties?: any }, collect: boolean = false): void {
if (!this.telemetryEnabled) {
return
}
const taskId = event.properties.taskId
const propertiesWithVersion = this.addProperties(event.properties)
if (collect && taskId) {
const propertiesWithVersion = {
...event.properties,
extension_version: this.version,
is_dev: this.isDev,
}
if (collect) {
const existingTask = this.collectedTasks.find((task) => task.taskId === taskId)
if (existingTask) {
existingTask.collection.push({
@@ -217,20 +195,11 @@ class TelemetryService {
],
})
}
} else {
} else if (this.telemetryEnabled) {
this.client.capture({ distinctId: this.distinctId, event: event.event, properties: propertiesWithVersion })
}
}
public captureExtensionActivated(installId: string) {
this.setDistinctId(installId)
if (this.telemetryEnabled) {
this.client.identify({ distinctId: this.distinctId })
this.client.capture({ distinctId: this.distinctId, event: TelemetryService.EVENTS.USER.EXTENSION_ACTIVATED })
}
}
// Task events
/**
* Records when a new task/conversation is started
@@ -241,7 +210,7 @@ class TelemetryService {
public captureTaskCreated(taskId: string, apiProvider?: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.CREATED,
event: PostHogClient.EVENTS.TASK.CREATED,
properties: { taskId, apiProvider },
},
collect,
@@ -257,7 +226,7 @@ class TelemetryService {
public captureTaskRestarted(taskId: string, apiProvider?: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.RESTARTED,
event: PostHogClient.EVENTS.TASK.RESTARTED,
properties: { taskId, apiProvider },
},
collect,
@@ -272,7 +241,7 @@ class TelemetryService {
public captureTaskCompleted(taskId: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.COMPLETED,
event: PostHogClient.EVENTS.TASK.COMPLETED,
properties: { taskId },
},
collect,
@@ -309,7 +278,7 @@ class TelemetryService {
this.capture(
{
event: TelemetryService.EVENTS.TASK.CONVERSATION_TURN,
event: PostHogClient.EVENTS.TASK.CONVERSATION_TURN,
properties,
},
collect,
@@ -326,7 +295,7 @@ class TelemetryService {
public captureTokenUsage(taskId: string, tokensIn: number, tokensOut: number, model: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.TOKEN_USAGE,
event: PostHogClient.EVENTS.TASK.TOKEN_USAGE,
properties: {
taskId,
tokensIn,
@@ -346,7 +315,7 @@ class TelemetryService {
public captureModeSwitch(taskId: string, mode: "plan" | "act", collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.MODE_SWITCH,
event: PostHogClient.EVENTS.TASK.MODE_SWITCH,
properties: {
taskId,
mode,
@@ -365,7 +334,7 @@ class TelemetryService {
console.info("TelemetryService: Capturing task feedback", { taskId, feedbackType })
this.capture(
{
event: TelemetryService.EVENTS.TASK.FEEDBACK,
event: PostHogClient.EVENTS.TASK.FEEDBACK,
properties: {
taskId,
feedbackType,
@@ -386,7 +355,7 @@ class TelemetryService {
public captureToolUsage(taskId: string, tool: string, autoApproved: boolean, success: boolean, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.TOOL_USED,
event: PostHogClient.EVENTS.TASK.TOOL_USED,
properties: {
taskId,
tool,
@@ -416,7 +385,7 @@ class TelemetryService {
this.capture(
{
event: TelemetryService.EVENTS.TASK.CHECKPOINT_USED,
event: PostHogClient.EVENTS.TASK.CHECKPOINT_USED,
properties: {
taskId,
action,
@@ -427,6 +396,135 @@ class TelemetryService {
)
}
// UI events
/**
* Records when the user switches between different API providers
* @param from Previous provider name
* @param to New provider name
* @param location Where the switch occurred (settings panel or bottom bar)
* @param taskId Optional task identifier if switch occurred during a task
*/
public captureProviderSwitch(
from: string,
to: string,
location: "settings" | "bottom",
taskId?: string,
collect: boolean = false,
) {
this.capture(
{
event: PostHogClient.EVENTS.UI.PROVIDER_SWITCH,
properties: {
from,
to,
location,
taskId,
},
},
collect,
)
}
/**
* Records when images are attached to a conversation
* @param taskId Unique identifier for the task
* @param imageCount Number of images attached
*/
public captureImageAttached(taskId: string, imageCount: number, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.IMAGE_ATTACHED,
properties: {
taskId,
imageCount,
},
},
collect,
)
}
/**
* Records general button click interactions in the UI
* @param button Identifier for the button that was clicked
* @param taskId Optional task identifier if click occurred during a task
*/
public captureButtonClick(button: string, taskId?: string, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.BUTTON_CLICK,
properties: {
button,
taskId,
},
},
collect,
)
}
/**
* Records when the marketplace view is opened
* @param taskId Optional task identifier if marketplace was opened during a task
*/
public captureMarketplaceOpened(taskId?: string, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.MARKETPLACE_OPENED,
properties: {
taskId,
},
},
collect,
)
}
/**
* Records when the settings panel is opened
* @param taskId Optional task identifier if settings were opened during a task
*/
public captureSettingsOpened(taskId?: string, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.SETTINGS_OPENED,
properties: {
taskId,
},
},
collect,
)
}
/**
* Records when the task history view is opened
* @param taskId Optional task identifier if history was opened during a task
*/
public captureHistoryOpened(taskId?: string, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.HISTORY_OPENED,
properties: {
taskId,
},
},
collect,
)
}
/**
* Records when a task is removed from the task history
* @param taskId Unique identifier for the task being removed
*/
public captureTaskPopped(taskId: string, collect: boolean = false) {
this.capture(
{
event: PostHogClient.EVENTS.UI.TASK_POPPED,
properties: {
taskId,
},
},
collect,
)
}
/**
* Records when a diff edit (replace_in_file) operation fails
* @param taskId Unique identifier for the task
@@ -435,7 +533,7 @@ class TelemetryService {
public captureDiffEditFailure(taskId: string, modelId: string, errorType?: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.DIFF_EDIT_FAILED,
event: PostHogClient.EVENTS.TASK.DIFF_EDIT_FAILED,
properties: {
taskId,
errorType,
@@ -455,7 +553,7 @@ class TelemetryService {
public captureModelSelected(model: string, provider: string, taskId?: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.UI.MODEL_SELECTED,
event: PostHogClient.EVENTS.UI.MODEL_SELECTED,
properties: {
model,
provider,
@@ -473,7 +571,7 @@ class TelemetryService {
public captureHistoricalTaskLoaded(taskId: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.HISTORICAL_LOADED,
event: PostHogClient.EVENTS.TASK.HISTORICAL_LOADED,
properties: {
taskId,
},
@@ -489,7 +587,7 @@ class TelemetryService {
public captureRetryClicked(taskId: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.RETRY_CLICKED,
event: PostHogClient.EVENTS.TASK.RETRY_CLICKED,
properties: {
taskId,
},
@@ -510,7 +608,7 @@ class TelemetryService {
this.capture(
{
event: TelemetryService.EVENTS.TASK.BROWSER_TOOL_START,
event: PostHogClient.EVENTS.TASK.BROWSER_TOOL_START,
properties: {
taskId,
viewport: browserSettings.viewport,
@@ -543,7 +641,7 @@ class TelemetryService {
this.capture(
{
event: TelemetryService.EVENTS.TASK.BROWSER_TOOL_END,
event: PostHogClient.EVENTS.TASK.BROWSER_TOOL_END,
properties: {
taskId,
actionCount: stats.actionCount,
@@ -581,7 +679,7 @@ class TelemetryService {
this.capture(
{
event: TelemetryService.EVENTS.TASK.BROWSER_ERROR,
event: PostHogClient.EVENTS.TASK.BROWSER_ERROR,
properties: {
taskId,
errorType,
@@ -603,7 +701,7 @@ class TelemetryService {
public captureOptionSelected(taskId: string, qty: number, mode: "plan" | "act", collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.OPTION_SELECTED,
event: PostHogClient.EVENTS.TASK.OPTION_SELECTED,
properties: {
taskId,
qty,
@@ -623,7 +721,7 @@ class TelemetryService {
public captureOptionsIgnored(taskId: string, qty: number, mode: "plan" | "act", collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.OPTIONS_IGNORED,
event: PostHogClient.EVENTS.TASK.OPTIONS_IGNORED,
properties: {
taskId,
qty,
@@ -660,7 +758,7 @@ class TelemetryService {
) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.GEMINI_API_PERFORMANCE,
event: PostHogClient.EVENTS.TASK.GEMINI_API_PERFORMANCE,
properties: {
taskId,
modelId,
@@ -679,7 +777,7 @@ class TelemetryService {
public captureModelFavoritesUsage(model: string, isFavorited: boolean, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.UI.MODEL_FAVORITE_TOGGLED,
event: PostHogClient.EVENTS.UI.MODEL_FAVORITE_TOGGLED,
properties: {
model,
isFavorited,
@@ -689,19 +787,6 @@ class TelemetryService {
)
}
public captureButtonClick(button: string, taskId?: string, collect: boolean = false) {
this.capture(
{
event: TelemetryService.EVENTS.UI.BUTTON_CLICKED,
properties: {
button,
taskId,
},
},
collect,
)
}
/**
* Checks if telemetry is enabled
* @returns Boolean indicating whether telemetry is enabled
@@ -721,17 +806,13 @@ class TelemetryService {
}
public async sendCollectedEvents(taskId?: string): Promise<void> {
if (!this.telemetryEnabled) {
return
}
if (this.collectedTasks.length > 0) {
if (taskId) {
const task = this.collectedTasks.find((t) => t.taskId === taskId)
if (task) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.TASK_COLLECTION,
event: PostHogClient.EVENTS.TASK.TASK_COLLECTION,
properties: { taskId, events: task.collection },
},
false,
@@ -742,7 +823,7 @@ class TelemetryService {
for (const task of this.collectedTasks) {
this.capture(
{
event: TelemetryService.EVENTS.TASK.TASK_COLLECTION,
event: PostHogClient.EVENTS.TASK.TASK_COLLECTION,
properties: { taskId: task.taskId, events: task.collection },
},
false,
@@ -758,4 +839,4 @@ class TelemetryService {
}
}
export const telemetryService = TelemetryService.getInstance()
export const telemetryService = PostHogClient.getInstance()
-1
View File
@@ -1,5 +1,4 @@
export interface ChatContent {
message?: string
images?: string[]
files?: string[]
}
+8 -3
View File
@@ -21,12 +21,14 @@ export interface ExtensionMessage {
| "lmStudioModels"
| "theme"
| "workspaceUpdated"
| "invoke"
| "partialMessage"
| "openRouterModels"
| "openAiModels"
| "requestyModels"
| "mcpServers"
| "relinquishControl"
| "authCallback"
| "mcpMarketplaceCatalog"
| "mcpDownloadDetails"
| "commitSearchResults"
@@ -35,6 +37,7 @@ export interface ExtensionMessage {
| "userCreditsBalance"
| "userCreditsUsage"
| "userCreditsPayments"
| "totalTasksSize"
| "addToInput"
| "browserConnectionResult"
| "fileSearchResults"
@@ -49,9 +52,9 @@ export interface ExtensionMessage {
| "accountLogoutClicked"
| "accountButtonClicked"
| "focusChatInput"
invoke?: Invoke
state?: ExtensionState
images?: string[]
files?: string[]
ollamaModels?: string[]
lmStudioModels?: string[]
vsCodeLmModels?: { vendor?: string; family?: string; version?: string; id?: string }[]
@@ -79,6 +82,7 @@ export interface ExtensionMessage {
userCreditsBalance?: BalanceResponse
userCreditsUsage?: UsageTransaction[]
userCreditsPayments?: PaymentTransaction[]
totalTasksSize?: number | null
success?: boolean
endpoint?: string
isBundled?: boolean
@@ -101,6 +105,8 @@ export interface ExtensionMessage {
}
}
export type Invoke = "sendMessage" | "primaryButtonClick" | "secondaryButtonClick"
export type Platform = "aix" | "darwin" | "freebsd" | "linux" | "openbsd" | "sunos" | "win32" | "unknown"
export const DEFAULT_PLATFORM = "unknown"
@@ -131,7 +137,7 @@ export interface ExtensionState {
photoURL: string | null
}
version: string
distinctId: string
vscMachineId: string
globalClineRulesToggles: ClineRulesToggles
localClineRulesToggles: ClineRulesToggles
localWorkflowToggles: ClineRulesToggles
@@ -148,7 +154,6 @@ export interface ClineMessage {
text?: string
reasoning?: string
images?: string[]
files?: string[]
partial?: boolean
lastCheckpointHash?: string
isCheckpointCheckedOut?: boolean
+7 -4
View File
@@ -13,28 +13,31 @@ export interface WebviewMessage {
| "newTask"
| "condense"
| "reportBug"
| "openInBrowser"
| "showChatView"
| "openExtensionSettings"
| "requestVsCodeLmModels"
| "authStateChanged"
| "authCallback"
| "fetchMcpMarketplace"
| "searchCommits"
| "fetchLatestMcpServersFromHub"
| "telemetrySetting"
| "invoke"
| "updateSettings"
| "clearAllTaskHistory"
| "fetchUserCreditsData"
| "optionsResponse"
| "requestTotalTasksSize"
| "searchFiles"
| "grpc_request"
| "grpc_request_cancel"
| "toggleWorkflow"
| "executeQuickWin"
text?: string
disabled?: boolean
apiConfiguration?: ApiConfiguration
images?: string[]
files?: string[]
bool?: boolean
number?: number
browserSettings?: BrowserSettings
@@ -52,6 +55,8 @@ export interface WebviewMessage {
// For auth
user?: UserInfo | null
customToken?: string
// For openInBrowser
url?: string
planActSeparateModelsSetting?: boolean
enableCheckpointsSetting?: boolean
mcpMarketplaceEnabled?: boolean
@@ -78,8 +83,6 @@ export interface WebviewMessage {
enabled?: boolean
filename?: string
payload?: { command: string; title: string }
offset?: number
shellIntegrationTimeout?: number
}
+49 -103
View File
@@ -24,7 +24,6 @@ export type ApiProvider =
| "asksage"
| "xai"
| "sambanova"
| "cerebras"
export interface ApiHandlerOptions {
apiModelId?: string
@@ -90,7 +89,6 @@ export interface ApiHandlerOptions {
thinkingBudgetTokens?: number
reasoningEffort?: string
sambanovaApiKey?: string
cerebrasApiKey?: string
requestTimeoutMs?: number
onRetryAttempt?: (attempt: number, maxRetries: number, delay: number, error: any) => void
}
@@ -360,7 +358,7 @@ export const bedrockModels = {
// OpenRouter
// https://openrouter.ai/models?order=newest&supported_parameters=tools
export const openRouterDefaultModelId = "anthropic/claude-3.7-sonnet" // will always exist in openRouterModels
export const openRouterDefaultModelId = "anthropic/claude-sonnet-4" // will always exist in openRouterModels
export const openRouterDefaultModelInfo: ModelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
@@ -372,7 +370,7 @@ export const openRouterDefaultModelInfo: ModelInfo = {
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description:
"Claude 3.7 Sonnet is an advanced large language model with improved reasoning, coding, and problem-solving capabilities. It introduces a hybrid reasoning approach, allowing users to choose between rapid responses and extended, step-by-step processing for complex tasks. The model demonstrates notable improvements in coding, particularly in front-end development and full-stack updates, and excels in agentic workflows, where it can autonomously navigate multi-step processes. \n\nClaude 3.7 Sonnet maintains performance parity with its predecessor in standard mode while offering an extended reasoning mode for enhanced accuracy in math, coding, and instruction-following tasks.\n\nRead more at the [blog post here](https://www.anthropic.com/news/claude-3-7-sonnet)",
"Claude 4 Sonnet is an advanced large language model with improved reasoning, coding, and problem-solving capabilities. It introduces a hybrid reasoning approach, allowing users to choose between rapid responses and extended, step-by-step processing for complex tasks. The model demonstrates notable improvements in coding, particularly in front-end development and full-stack updates, and excels in agentic workflows, where it can autonomously navigate multi-step processes. \n\nClaude 4 Sonnet maintains performance parity with its predecessor in standard mode while offering an extended reasoning mode for enhanced accuracy in math, coding, and instruction-following tasks.\n\nRead more at the [blog post here](https://www.anthropic.com/news/claude-4)",
}
// Vertex AI
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude
@@ -539,7 +537,7 @@ export const vertexModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
supportsPromptCache: false,
supportsGlobalEndpoint: true,
inputPrice: 0.15,
outputPrice: 0.6,
@@ -552,7 +550,7 @@ export const vertexModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
supportsPromptCache: false,
supportsGlobalEndpoint: true,
inputPrice: 0.15,
outputPrice: 0.6,
@@ -683,7 +681,7 @@ export const geminiModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
supportsPromptCache: false,
inputPrice: 0.15,
outputPrice: 0.6,
thinkingConfig: {
@@ -695,7 +693,7 @@ export const geminiModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
supportsPromptCache: false,
inputPrice: 0.15,
outputPrice: 0.6,
thinkingConfig: {
@@ -1832,85 +1830,85 @@ export const xaiModels = {
export type SambanovaModelId = keyof typeof sambanovaModels
export const sambanovaDefaultModelId: SambanovaModelId = "Meta-Llama-3.3-70B-Instruct"
export const sambanovaModels = {
"Llama-4-Maverick-17B-128E-Instruct": {
maxTokens: 4096,
contextWindow: 8_000,
supportsImages: true,
supportsPromptCache: false,
inputPrice: 0.63,
outputPrice: 1.8,
},
"Llama-4-Scout-17B-16E-Instruct": {
maxTokens: 4096,
contextWindow: 8_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.4,
outputPrice: 0.7,
},
"Meta-Llama-3.3-70B-Instruct": {
maxTokens: 4096,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.6,
outputPrice: 1.2,
inputPrice: 0,
outputPrice: 0,
},
"DeepSeek-R1-Distill-Llama-70B": {
maxTokens: 4096,
contextWindow: 128_000,
contextWindow: 32_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.7,
outputPrice: 1.4,
inputPrice: 0,
outputPrice: 0,
},
"DeepSeek-R1": {
"Llama-3.1-Swallow-70B-Instruct-v0.3": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 5.0,
outputPrice: 7.0,
inputPrice: 0,
outputPrice: 0,
},
"Llama-3.1-Swallow-8B-Instruct-v0.3": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
},
"Meta-Llama-3.1-405B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 5.0,
outputPrice: 10.0,
inputPrice: 0,
outputPrice: 0,
},
"Meta-Llama-3.1-8B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.1,
outputPrice: 0.2,
inputPrice: 0,
outputPrice: 0,
},
"Meta-Llama-3.2-1B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.04,
outputPrice: 0.08,
inputPrice: 0,
outputPrice: 0,
},
"Meta-Llama-3.2-3B-Instruct": {
maxTokens: 4096,
contextWindow: 8_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.08,
outputPrice: 0.16,
},
"Qwen3-32B": {
"Qwen2.5-72B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.4,
outputPrice: 0.8,
inputPrice: 0,
outputPrice: 0,
},
"Qwen2.5-Coder-32B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
},
"QwQ-32B-Preview": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
},
"QwQ-32B": {
maxTokens: 4096,
@@ -1922,63 +1920,11 @@ export const sambanovaModels = {
},
"DeepSeek-V3-0324": {
maxTokens: 4096,
contextWindow: 8_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 3.0,
outputPrice: 4.5,
},
} as const satisfies Record<string, ModelInfo>
// Cerebras
// https://inference-docs.cerebras.ai/api-reference/models
export type CerebrasModelId = keyof typeof cerebrasModels
export const cerebrasDefaultModelId: CerebrasModelId = "llama3.1-8b"
export const cerebrasModels = {
"llama-4-scout-17b-16e-instruct": {
maxTokens: 8192,
contextWindow: 8192,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description: "Fast inference model with ~2700 tokens/s",
},
"llama3.1-8b": {
maxTokens: 8192,
contextWindow: 8192,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description: "Efficient model with ~2100 tokens/s",
},
"llama-3.3-70b": {
maxTokens: 8192,
contextWindow: 8192,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description: "Powerful model with ~2600 tokens/s",
},
"qwen-3-32b": {
maxTokens: 16382,
contextWindow: 16382,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description: "SOTA coding performance with ~2500 tokens/s",
},
"deepseek-r1-distill-llama-70b": {
maxTokens: 8192,
contextWindow: 8192,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description: "Advanced reasoning model with ~2300 tokens/s (private preview)",
inputPrice: 1.0,
outputPrice: 1.5,
},
} as const satisfies Record<string, ModelInfo>
@@ -35,7 +35,6 @@ export function convertChatContentToProtoChatContent(chatContent?: ChatContent):
return {
message: chatContent.message,
images: chatContent.images || [],
files: chatContent.files || [],
}
}
@@ -50,6 +49,5 @@ export function convertProtoChatContentToChatContent(protoChatContent?: ProtoCha
return {
message: protoChatContent.message,
images: protoChatContent.images || [],
files: protoChatContent.files || [],
}
}
+17 -14
View File
@@ -35,19 +35,21 @@ describe("Chat Integration Tests", () => {
}
});
break;
case 'primaryButtonClick':
vscode.postMessage({
type: 'grpc_request',
grpc_request: {
service: 'cline.TaskService',
method: 'askResponse',
message: {
responseType: 'yesButtonClicked'
},
request_id: 'test-request-id',
is_streaming: false
}
});
case 'invoke':
if (message.invoke === 'primaryButtonClick') {
vscode.postMessage({
type: 'grpc_request',
grpc_request: {
service: 'cline.TaskService',
method: 'askResponse',
message: {
responseType: 'yesButtonClicked'
},
request_id: 'test-request-id',
is_streaming: false
}
});
}
break;
}
});
@@ -141,7 +143,8 @@ describe("Chat Integration Tests", () => {
// Trigger tool approval
await panel.webview.postMessage({
type: "primaryButtonClick",
type: "invoke",
invoke: "primaryButtonClick",
})
// Verify gRPC request was sent with correct parameters
+14 -26
View File
@@ -5,44 +5,32 @@ import { posthogConfig } from "@shared/services/config/posthog-config"
import { useExtensionState } from "./context/ExtensionStateContext"
export function CustomPostHogProvider({ children }: { children: ReactNode }) {
const { telemetrySetting, distinctId, version } = useExtensionState()
const { telemetrySetting, vscMachineId } = useExtensionState()
const isTelemetryEnabled = telemetrySetting !== "disabled"
useEffect(() => {
posthog.init(posthogConfig.apiKey, {
api_host: posthogConfig.host,
ui_host: posthogConfig.uiHost,
disable_session_recording: true,
capture_pageview: false,
capture_dead_clicks: true,
})
}, [])
useEffect(() => {
if (distinctId.length === 0 || version.length === 0) {
if (vscMachineId.length === 0) {
return
}
posthog.set_config({
before_send: (payload: any) => {
if (payload?.properties) {
payload.properties.extension_version = version
payload.properties.distinct_id = distinctId
}
return payload
posthog.init(posthogConfig.apiKey, {
api_host: posthogConfig.host,
ui_host: posthogConfig.uiHost,
opt_out_capturing_by_default: true,
disable_session_recording: true,
capture_pageview: false,
capture_dead_clicks: true,
bootstrap: {
distinctID: vscMachineId,
},
})
const optedIn = posthog.has_opted_in_capturing()
const optedOut = posthog.has_opted_out_capturing()
if (isTelemetryEnabled && !optedIn) {
if (isTelemetryEnabled) {
posthog.opt_in_capturing()
posthog.identify(distinctId)
} else if (!isTelemetryEnabled && !optedOut) {
} else {
posthog.opt_out_capturing()
}
}, [isTelemetryEnabled, distinctId, version])
}, [isTelemetryEnabled, vscMachineId])
return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}
+1 -2
View File
@@ -111,7 +111,7 @@ interface ChatRowProps {
isLast: boolean
onHeightChange: (isTaller: boolean) => void
inputValue?: string
sendMessageFromChatRow?: (text: string, images: string[], files: string[]) => void
sendMessageFromChatRow?: (text: string, images: string[]) => void
onSetQuote: (text: string) => void
}
@@ -1046,7 +1046,6 @@ export const ChatRowContent = ({
<UserMessage
text={message.text}
images={message.images}
files={message.files}
messageTs={message.ts}
sendMessageFromChatRow={sendMessageFromChatRow}
/>
+20 -48
View File
@@ -33,7 +33,7 @@ import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import Thumbnails from "@/components/common/Thumbnails"
import Tooltip from "@/components/common/Tooltip"
import ApiOptions, { normalizeApiConfiguration } from "@/components/settings/ApiOptions"
import { MAX_IMAGES_AND_FILES_PER_MESSAGE } from "@/components/chat/ChatView"
import { MAX_IMAGES_PER_MESSAGE } from "@/components/chat/ChatView"
import ContextMenu from "@/components/chat/ContextMenu"
import SlashCommandMenu from "@/components/chat/SlashCommandMenu"
import { ChatSettings } from "@shared/ChatSettings"
@@ -65,13 +65,11 @@ interface ChatTextAreaProps {
setInputValue: (value: string) => void
sendingDisabled: boolean
placeholderText: string
selectedFiles: string[]
selectedImages: string[]
setSelectedImages: React.Dispatch<React.SetStateAction<string[]>>
setSelectedFiles: React.Dispatch<React.SetStateAction<string[]>>
onSend: () => void
onSelectFilesAndImages: () => void
shouldDisableFilesAndImages: boolean
onSelectImages: () => void
shouldDisableImages: boolean
onHeightChange?: (height: number) => void
onFocusChange?: (isFocused: boolean) => void
}
@@ -252,13 +250,11 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
setInputValue,
sendingDisabled,
placeholderText,
selectedFiles,
selectedImages,
setSelectedImages,
setSelectedFiles,
onSend,
onSelectFilesAndImages,
shouldDisableFilesAndImages,
onSelectImages,
shouldDisableImages,
onHeightChange,
onFocusChange,
},
@@ -840,7 +836,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const [type, subtype] = item.type.split("/")
return type === "image" && acceptedTypes.includes(subtype)
})
if (!shouldDisableFilesAndImages && imageItems.length > 0) {
if (!shouldDisableImages && imageItems.length > 0) {
e.preventDefault()
const imagePromises = imageItems.map((item) => {
return new Promise<string | null>((resolve) => {
@@ -877,28 +873,13 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
//.map((dataUrl) => dataUrl.split(",")[1]) // strip the mime type prefix, sharp doesn't need it
if (dataUrls.length > 0) {
const filesAndImagesLength = selectedImages.length + selectedFiles.length
const availableSlots = MAX_IMAGES_AND_FILES_PER_MESSAGE - filesAndImagesLength
if (availableSlots > 0) {
const imagesToAdd = Math.min(dataUrls.length, availableSlots)
setSelectedImages((prevImages) => [...prevImages, ...dataUrls.slice(0, imagesToAdd)])
}
setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
} else {
console.warn("No valid images were processed")
}
}
},
[
shouldDisableFilesAndImages,
setSelectedImages,
selectedImages,
selectedFiles,
cursorPosition,
setInputValue,
inputValue,
showDimensionErrorMessage,
],
[shouldDisableImages, setSelectedImages, cursorPosition, setInputValue, inputValue, showDimensionErrorMessage],
)
const handleThumbnailsHeightChange = useCallback((height: number) => {
@@ -1007,7 +988,6 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
chatContent: {
message: inputValue.trim() ? inputValue : undefined,
images: selectedImages.length > 0 ? selectedImages : undefined,
files: selectedFiles.length > 0 ? selectedFiles : undefined,
},
})
// Focus the textarea after mode toggle with slight delay
@@ -1015,7 +995,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
textAreaRef.current?.focus()
}, 100)
}, changeModeDelay)
}, [chatSettings.mode, showModelSelector, submitApiConfig, inputValue, selectedImages, selectedFiles])
}, [chatSettings.mode, showModelSelector, submitApiConfig, inputValue, selectedImages])
useShortcut("Meta+Shift+a", onModeToggle, { disableTextInputs: false }) // important that we don't disable the text input here
@@ -1292,7 +1272,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
return type === "image" && acceptedTypes.includes(subtype)
})
if (shouldDisableFilesAndImages || imageFiles.length === 0) {
if (shouldDisableImages || imageFiles.length === 0) {
return
}
@@ -1300,13 +1280,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
if (dataUrls.length > 0) {
const filesAndImagesLength = selectedImages.length + selectedFiles.length
const availableSlots = MAX_IMAGES_AND_FILES_PER_MESSAGE - filesAndImagesLength
if (availableSlots > 0) {
const imagesToAdd = Math.min(dataUrls.length, availableSlots)
setSelectedImages((prevImages) => [...prevImages, ...dataUrls.slice(0, imagesToAdd)])
}
setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
} else {
console.warn("No valid images were processed")
}
@@ -1426,7 +1400,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
fontWeight: "bold",
fontSize: "12px",
}}>
Files other than images are currently disabled
Only image files are supported
</span>
</div>
)}
@@ -1570,12 +1544,10 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}}
onScroll={() => updateHighlights()}
/>
{(selectedImages.length > 0 || selectedFiles.length > 0) && (
{selectedImages.length > 0 && (
<Thumbnails
images={selectedImages}
files={selectedFiles}
setImages={setSelectedImages}
setFiles={setSelectedFiles}
onHeightChange={handleThumbnailsHeightChange}
style={{
position: "absolute",
@@ -1665,21 +1637,21 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
</VSCodeButton>
</Tooltip>
<Tooltip tipText="Add Files & Images">
<Tooltip tipText="Add Images">
<VSCodeButton
data-testid="files-button"
data-testid="images-button"
appearance="icon"
aria-label="Add Files & Images"
disabled={shouldDisableFilesAndImages}
aria-label="Add Images"
disabled={shouldDisableImages}
onClick={() => {
if (!shouldDisableFilesAndImages) {
onSelectFilesAndImages()
if (!shouldDisableImages) {
onSelectImages()
}
}}
style={{ padding: "0px 0px", height: "20px" }}>
<ButtonContainer>
<span
className="codicon codicon-add flex items-center"
className="codicon codicon-device-camera flex items-center"
style={{ fontSize: "14px", marginBottom: -3 }}
/>
</ButtonContainer>
+53 -65
View File
@@ -34,8 +34,6 @@ import rehypeRemark from "rehype-remark"
import rehypeParse from "rehype-parse"
import HomeHeader from "../welcome/HomeHeader"
import AutoApproveBar from "./auto-approve-menu/AutoApproveBar"
import { SuggestedTasks } from "../welcome/SuggestedTasks"
interface ChatViewProps {
isHidden: boolean
showAnnouncement: boolean
@@ -88,13 +86,11 @@ async function convertHtmlToMarkdown(html: string) {
return cleanupMarkdownEscapes(md)
}
// Anthropic limits to 20 images, which we use to constrain both images & files for simplicity
export const MAX_IMAGES_AND_FILES_PER_MESSAGE = 20
const QUICK_WINS_HISTORY_THRESHOLD = 300
export const MAX_IMAGES_PER_MESSAGE = 20 // Anthropic limits to 20 images
const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryView }: ChatViewProps) => {
const { version, clineMessages: messages, taskHistory, apiConfiguration, telemetrySetting } = useExtensionState()
const shouldShowQuickWins = false // !taskHistory || taskHistory.length < QUICK_WINS_HISTORY_THRESHOLD
//const task = messages.length > 0 ? (messages[0].say === "task" ? messages[0] : undefined) : undefined) : undefined
const task = useMemo(() => messages.at(0), [messages]) // leaving this less safe version here since if the first message is not a task, then the extension is in a bad state and needs to be debugged (see Cline.abort)
const modifiedMessages = useMemo(() => combineApiRequests(combineCommandSequences(messages.slice(1))), [messages])
@@ -121,7 +117,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const [sendingDisabled, setSendingDisabled] = useState(false)
const [selectedImages, setSelectedImages] = useState<string[]>([])
const [selectedFiles, setSelectedFiles] = useState<string[]>([])
// we need to hold on to the ask because useEffect > lastMessage will always let us know when an ask comes in and handle it, but by the time handleMessage is called, the last message might not be the ask anymore (it could be a say that followed)
const [clineAsk, setClineAsk] = useState<ClineAsk | undefined>(undefined)
@@ -372,7 +367,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setInputValue("")
setSendingDisabled(true)
setSelectedImages([])
setSelectedFiles([])
setClineAsk(undefined)
setEnableButtons(false)
}
@@ -445,9 +439,9 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
}, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
const handleSendMessage = useCallback(
async (text: string, images: string[], files: string[]) => {
async (text: string, images: string[]) => {
let messageToSend = text.trim()
const hasContent = messageToSend || images.length > 0 || files.length > 0
const hasContent = messageToSend || images.length > 0
// Prepend the active quote if it exists
if (activeQuote && hasContent) {
@@ -460,7 +454,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
if (hasContent) {
console.log("[ChatView] handleSendMessage - Sending message:", messageToSend)
if (messages.length === 0) {
await TaskServiceClient.newTask({ text: messageToSend, images, files })
await TaskServiceClient.newTask({ text: messageToSend, images })
} else if (clineAsk) {
switch (clineAsk) {
case "followup":
@@ -475,13 +469,24 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
case "resume_completed_task":
case "mistake_limit_reached":
case "new_task": // user can provide feedback or reject the new task suggestion
await TaskServiceClient.askResponse({
responseType: "messageResponse",
text: messageToSend,
images,
})
break
case "condense":
await TaskServiceClient.askResponse({
responseType: "messageResponse",
text: messageToSend,
images,
})
break
case "report_bug":
await TaskServiceClient.askResponse({
responseType: "messageResponse",
text: messageToSend,
images,
files,
})
break
// there is no other case that a textfield should be enabled
@@ -491,7 +496,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setActiveQuote(null) // Clear quote when sending message
setSendingDisabled(true)
setSelectedImages([])
setSelectedFiles([])
setClineAsk(undefined)
setEnableButtons(false)
// setPrimaryButtonText(undefined)
@@ -511,7 +515,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
This logic depends on the useEffect[messages] above to set clineAsk, after which buttons are shown and we then send an askResponse to the extension.
*/
const handlePrimaryButtonClick = useCallback(
async (text?: string, images?: string[], files?: string[]) => {
async (text?: string, images?: string[]) => {
const trimmedInput = text?.trim()
switch (clineAsk) {
case "api_req_failed":
@@ -523,12 +527,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
case "resume_task":
case "mistake_limit_reached":
case "auto_approval_max_req_reached":
if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) {
if (trimmedInput || (images && images.length > 0)) {
await TaskServiceClient.askResponse({
responseType: "yesButtonClicked",
text: trimmedInput,
images: images,
files: files,
})
} else {
await TaskServiceClient.askResponse({
@@ -539,7 +542,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setInputValue("")
setActiveQuote(null) // Clear quote when using primary button
setSelectedImages([])
setSelectedFiles([])
break
case "completion_result":
case "resume_completed_task":
@@ -551,7 +553,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
await TaskServiceClient.newTask({
text: lastMessage?.text,
images: [],
files: [],
})
break
case "condense":
@@ -572,7 +573,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
)
const handleSecondaryButtonClick = useCallback(
async (text?: string, images?: string[], files?: string[]) => {
async (text?: string, images?: string[]) => {
const trimmedInput = text?.trim()
if (isStreaming) {
await TaskServiceClient.cancelTask({})
@@ -590,12 +591,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
case "tool":
case "browser_action_launch":
case "use_mcp_server":
if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) {
if (trimmedInput || (images && images.length > 0)) {
await TaskServiceClient.askResponse({
responseType: "noButtonClicked",
text: trimmedInput,
images: images,
files: files,
})
} else {
// responds to the API with a "This operation failed" and lets it try again
@@ -607,7 +607,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setInputValue("")
setActiveQuote(null) // Clear quote when using secondary button
setSelectedImages([])
setSelectedFiles([])
break
}
setSendingDisabled(true)
@@ -632,40 +631,18 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
return normalizeApiConfiguration(apiConfiguration)
}, [apiConfiguration])
const selectFilesAndImages = useCallback(async () => {
const selectImages = useCallback(async () => {
try {
const response = await FileServiceClient.selectFiles({
value: selectedModelInfo.supportsImages,
})
if (
response &&
response.values1 &&
response.values2 &&
(response.values1.length > 0 || response.values2.length > 0)
) {
const currentTotal = selectedImages.length + selectedFiles.length
const availableSlots = MAX_IMAGES_AND_FILES_PER_MESSAGE - currentTotal
if (availableSlots > 0) {
// Prioritize images first
const imagesToAdd = Math.min(response.values1.length, availableSlots)
if (imagesToAdd > 0) {
setSelectedImages((prevImages) => [...prevImages, ...response.values1.slice(0, imagesToAdd)])
}
// Use remaining slots for files
const remainingSlots = availableSlots - imagesToAdd
if (remainingSlots > 0) {
setSelectedFiles((prevFiles) => [...prevFiles, ...response.values2.slice(0, remainingSlots)])
}
}
const response = await FileServiceClient.selectImages({})
if (response && response.values && response.values.length > 0) {
setSelectedImages((prevImages) => [...prevImages, ...response.values].slice(0, MAX_IMAGES_PER_MESSAGE))
}
} catch (error) {
console.error("Error selecting images & files:", error)
console.error("Error selecting images:", error)
}
}, [selectedModelInfo.supportsImages])
}, [])
const shouldDisableFilesAndImages = selectedImages.length + selectedFiles.length >= MAX_IMAGES_AND_FILES_PER_MESSAGE
const shouldDisableImages = !selectedModelInfo.supportsImages || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
const handleMessage = useCallback(
(e: MessageEvent) => {
@@ -687,6 +664,12 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
break
}
break
case "selectedImages":
const newImages = message.images ?? []
if (newImages.length > 0) {
setSelectedImages((prevImages) => [...prevImages, ...newImages].slice(0, MAX_IMAGES_PER_MESSAGE))
}
break
case "addToInput":
setInputValue((prevValue) => {
const newText = message.text ?? ""
@@ -702,6 +685,18 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
}
}, 0)
break
case "invoke":
switch (message.invoke!) {
case "sendMessage":
handleSendMessage(message.text ?? "", message.images ?? [])
break
case "primaryButtonClick":
handlePrimaryButtonClick(message.text ?? "", message.images ?? [])
break
case "secondaryButtonClick":
handleSecondaryButtonClick(message.text ?? "", message.images ?? [])
break
}
}
// textAreaRef.current is not explicitly required here since react guarantees that ref will be stable across re-renders, and we're not using its value but its reference.
},
@@ -1061,16 +1056,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
{showAnnouncement && <Announcement version={version} hideAnnouncement={hideAnnouncement} />}
<HomeHeader />
{!shouldShowQuickWins && taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
{taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
</div>
)}
{!task && (
<>
<SuggestedTasks shouldShowQuickWins={shouldShowQuickWins} />
<AutoApproveBar />
</>
)}
{!task && <AutoApproveBar />}
{task && (
<>
@@ -1139,7 +1129,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
flex: secondaryButtonText ? 1 : 2,
marginRight: secondaryButtonText ? "6px" : "0",
}}
onClick={() => handlePrimaryButtonClick(inputValue, selectedImages, selectedFiles)}>
onClick={() => handlePrimaryButtonClick(inputValue, selectedImages)}>
{primaryButtonText}
</VSCodeButton>
)}
@@ -1151,7 +1141,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
flex: isStreaming ? 2 : 1,
marginLeft: isStreaming ? 0 : "6px",
}}
onClick={() => handleSecondaryButtonClick(inputValue, selectedImages, selectedFiles)}>
onClick={() => handleSecondaryButtonClick(inputValue, selectedImages)}>
{isStreaming ? "Cancel" : secondaryButtonText}
</VSCodeButton>
)}
@@ -1181,11 +1171,9 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
placeholderText={placeholderText}
selectedImages={selectedImages}
setSelectedImages={setSelectedImages}
setSelectedFiles={setSelectedFiles}
selectedFiles={selectedFiles}
onSend={() => handleSendMessage(inputValue, selectedImages, selectedFiles)}
onSelectFilesAndImages={selectFilesAndImages}
shouldDisableFilesAndImages={shouldDisableFilesAndImages}
onSend={() => handleSendMessage(inputValue, selectedImages)}
onSelectImages={selectImages}
shouldDisableImages={shouldDisableImages}
onHeightChange={() => {
if (isAtBottom) {
scrollToBottomAuto()
@@ -1,7 +1,8 @@
import React from "react"
import VSCodeButtonLink from "@/components/common/VSCodeButtonLink"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { TaskServiceClient } from "@/services/grpc-client"
import { vscode } from "@/utils/vscode"
import { Invoke } from "@shared/ExtensionMessage"
interface CreditLimitErrorProps {
currentBalance: number
@@ -39,16 +40,11 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({ currentBalance, tot
</VSCodeButtonLink>
<VSCodeButton
onClick={async () => {
try {
await TaskServiceClient.askResponse({
responseType: "yesButtonClicked",
text: "",
images: [],
})
} catch (error) {
console.error("Error invoking action:", error)
}
onClick={() => {
vscode.postMessage({
type: "invoke",
text: "primaryButtonClick" satisfies Invoke,
})
}}
appearance="secondary"
style={{
+14 -20
View File
@@ -11,7 +11,7 @@ import Thumbnails from "@/components/common/Thumbnails"
import { normalizeApiConfiguration } from "@/components/settings/ApiOptions"
import { validateSlashCommand } from "@/utils/slash-commands"
import TaskTimeline from "./TaskTimeline"
import { TaskServiceClient, FileServiceClient, UiServiceClient } from "@/services/grpc-client"
import { TaskServiceClient, FileServiceClient } from "@/services/grpc-client"
import HeroTooltip from "@/components/common/HeroTooltip"
interface TaskHeaderProps {
@@ -37,8 +37,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
lastApiReqTotalTokens,
onClose,
}) => {
const { apiConfiguration, currentTaskItem, checkpointTrackerErrorMessage, clineMessages, navigateToSettings } =
useExtensionState()
const { apiConfiguration, currentTaskItem, checkpointTrackerErrorMessage, clineMessages } = useExtensionState()
const [isTaskExpanded, setIsTaskExpanded] = useState(true)
const [isTextExpanded, setIsTextExpanded] = useState(false)
const [showSeeMore, setShowSeeMore] = useState(false)
@@ -352,9 +351,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
See less
</div>
)}
{((task.images && task.images.length > 0) || (task.files && task.files.length > 0)) && (
<Thumbnails images={task.images ?? []} files={task.files ?? []} />
)}
{task.images && task.images.length > 0 && <Thumbnails images={task.images} />}
<div
style={{
@@ -486,23 +483,20 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
{checkpointTrackerErrorMessage.replace(/disabling checkpoints\.$/, "")}
{checkpointTrackerErrorMessage.endsWith("disabling checkpoints.") && (
<>
<button
<a
onClick={() => {
// First open the settings panel using direct navigation
navigateToSettings()
// After a short delay, send a message to scroll to settings
setTimeout(async () => {
try {
await UiServiceClient.scrollToSettings({ value: "features" })
} catch (error) {
console.error("Error scrolling to checkpoint settings:", error)
}
}, 300)
vscode.postMessage({
type: "openExtensionSettings",
text: "enableCheckpoints",
})
}}
className="underline cursor-pointer bg-transparent border-0 p-0 text-inherit font-inherit">
style={{
color: "inherit",
textDecoration: "underline",
cursor: "pointer",
}}>
disabling checkpoints.
</button>
</a>
</>
)}
{checkpointTrackerErrorMessage.includes("Git must be installed to use checkpoints.") && (
@@ -8,13 +8,12 @@ import { ClineCheckpointRestore } from "@shared/WebviewMessage"
interface UserMessageProps {
text?: string
files?: string[]
images?: string[]
messageTs?: number // Timestamp for the message, needed for checkpoint restore
sendMessageFromChatRow?: (text: string, images: string[], files: string[]) => void
sendMessageFromChatRow?: (text: string, images: string[]) => void
}
const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageTs, sendMessageFromChatRow }) => {
const UserMessage: React.FC<UserMessageProps> = ({ text, images, messageTs, sendMessageFromChatRow }) => {
const [isEditing, setIsEditing] = useState(false)
const [editedText, setEditedText] = useState(text || "")
const textAreaRef = useRef<HTMLTextAreaElement>(null)
@@ -53,7 +52,7 @@ const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageT
})
setTimeout(() => {
sendMessageFromChatRow?.(editedText, images || [], files || [])
sendMessageFromChatRow?.(editedText, images || [])
}, delay)
} catch (err) {
console.error("Checkpoint restore error:", err)
@@ -146,9 +145,7 @@ const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageT
{highlightText(editedText || text)}
</span>
)}
{((images && images.length > 0) || (files && files.length > 0)) && (
<Thumbnails images={images ?? []} files={files ?? []} style={{ marginTop: "8px" }} />
)}
{images && images.length > 0 && <Thumbnails images={images} style={{ marginTop: "8px" }} />}
</div>
)
}
+10 -93
View File
@@ -5,15 +5,13 @@ import { vscode } from "@/utils/vscode"
interface ThumbnailsProps {
images: string[]
files: string[]
style?: React.CSSProperties
setImages?: React.Dispatch<React.SetStateAction<string[]>>
setFiles?: React.Dispatch<React.SetStateAction<string[]>>
onHeightChange?: (height: number) => void
}
const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange }: ThumbnailsProps) => {
const [hoveredIndex, setHoveredIndex] = useState<string | null>(null)
const Thumbnails = ({ images, style, setImages, onHeightChange }: ThumbnailsProps) => {
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
const containerRef = useRef<HTMLDivElement>(null)
const { width } = useWindowSize()
@@ -27,27 +25,18 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange
onHeightChange?.(height)
}
setHoveredIndex(null)
}, [images, files, width, onHeightChange])
}, [images, width, onHeightChange])
const handleDeleteImages = (index: number) => {
const handleDelete = (index: number) => {
setImages?.((prevImages) => prevImages.filter((_, i) => i !== index))
}
const handleDeleteFiles = (index: number) => {
setFiles?.((prevFiles) => prevFiles.filter((_, i) => i !== index))
}
const isDeletableImages = setImages !== undefined
const isDeletableFiles = setFiles !== undefined
const isDeletable = setImages !== undefined
const handleImageClick = (image: string) => {
FileServiceClient.openImage({ value: image }).catch((err) => console.error("Failed to open image:", err))
}
const handleFileClick = (filePath: string) => {
FileServiceClient.openFile({ value: filePath }).catch((err) => console.error("Failed to open file:", err))
}
return (
<div
ref={containerRef}
@@ -60,13 +49,13 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange
}}>
{images.map((image, index) => (
<div
key={`image-${index}`}
key={index}
style={{ position: "relative" }}
onMouseEnter={() => setHoveredIndex(`image-${index}`)}
onMouseEnter={() => setHoveredIndex(index)}
onMouseLeave={() => setHoveredIndex(null)}>
<img
src={image}
alt={`Thumbnail image-${index + 1}`}
alt={`Thumbnail ${index + 1}`}
style={{
width: 34,
height: 34,
@@ -76,9 +65,9 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange
}}
onClick={() => handleImageClick(image)}
/>
{isDeletableImages && hoveredIndex === `image-${index}` && (
{isDeletable && hoveredIndex === index && (
<div
onClick={() => handleDeleteImages(index)}
onClick={() => handleDelete(index)}
style={{
position: "absolute",
top: -4,
@@ -103,78 +92,6 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange
)}
</div>
))}
{files.map((filePath, index) => {
const fileName = filePath.split(/[\\/]/).pop() || filePath
return (
<div
key={`file-${index}`}
style={{ position: "relative" }}
onMouseEnter={() => setHoveredIndex(`file-${index}`)}
onMouseLeave={() => setHoveredIndex(null)}>
<div
style={{
width: 34,
height: 34,
borderRadius: 4,
cursor: "pointer",
backgroundColor: "var(--vscode-editor-background)",
border: "1px solid var(--vscode-input-border)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
}}
onClick={() => handleFileClick(filePath)}>
<span
className="codicon codicon-file"
style={{
fontSize: 16,
color: "var(--vscode-foreground)",
}}></span>
<span
style={{
fontSize: 7,
marginTop: 1,
overflow: "hidden",
textOverflow: "ellipsis",
maxWidth: "90%",
whiteSpace: "nowrap",
textAlign: "center",
}}
title={fileName}>
{fileName}
</span>
</div>
{isDeletableFiles && hoveredIndex === `file-${index}` && (
<div
onClick={() => handleDeleteFiles(index)}
style={{
position: "absolute",
top: -4,
right: -4,
width: 13,
height: 13,
borderRadius: "50%",
backgroundColor: "var(--vscode-badge-background)",
display: "flex",
justifyContent: "center",
alignItems: "center",
cursor: "pointer",
}}>
<span
className="codicon codicon-close"
style={{
color: "var(--vscode-foreground)",
fontSize: 10,
fontWeight: "bold",
}}></span>
</div>
)}
</div>
)
})}
</div>
)
}
@@ -47,8 +47,7 @@ const CustomFilterRadio = ({ checked, onChange, icon, label }: CustomFilterRadio
}
const HistoryView = ({ onDone }: HistoryViewProps) => {
const extensionStateContext = useExtensionState()
const { taskHistory, filePaths } = extensionStateContext
const { taskHistory, totalTasksSize, filePaths } = useExtensionState()
const [searchQuery, setSearchQuery] = useState("")
const [sortOption, setSortOption] = useState<SortOption>("newest")
const [lastNonRelevantSort, setLastNonRelevantSort] = useState<SortOption | null>("newest")
@@ -132,23 +131,10 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
}, [])
useEvent("message", handleMessage)
const { totalTasksSize, setTotalTasksSize } = extensionStateContext
const fetchTotalTasksSize = useCallback(async () => {
try {
const response = await TaskServiceClient.getTotalTasksSize({})
if (response && typeof response.value === "number") {
setTotalTasksSize?.(response.value || 0)
}
} catch (error) {
console.error("Error getting total tasks size:", error)
}
}, [setTotalTasksSize])
// Request total tasks size when component mounts
useEffect(() => {
fetchTotalTasksSize()
}, [fetchTotalTasksSize])
vscode.postMessage({ type: "requestTotalTasksSize" })
}, [])
useEffect(() => {
if (searchQuery && sortOption !== "mostRelevant" && !lastNonRelevantSort) {
@@ -174,26 +160,16 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
})
}, [])
const handleDeleteHistoryItem = useCallback(
(id: string) => {
TaskServiceClient.deleteTasksWithIds({ value: [id] })
.then(() => fetchTotalTasksSize())
.catch((error) => console.error("Error deleting task:", error))
},
[fetchTotalTasksSize],
)
const handleDeleteHistoryItem = useCallback((id: string) => {
TaskServiceClient.deleteTasksWithIds({ value: [id] })
}, [])
const handleDeleteSelectedHistoryItems = useCallback(
(ids: string[]) => {
if (ids.length > 0) {
TaskServiceClient.deleteTasksWithIds({ value: ids })
.then(() => fetchTotalTasksSize())
.catch((error) => console.error("Error deleting tasks:", error))
setSelectedItems([])
}
},
[fetchTotalTasksSize],
)
const handleDeleteSelectedHistoryItems = useCallback((ids: string[]) => {
if (ids.length > 0) {
TaskServiceClient.deleteTasksWithIds({ value: ids })
setSelectedItems([])
}
}, [])
const formatDate = useCallback((timestamp: number) => {
const date = new Date(timestamp)
@@ -1,6 +1,5 @@
import React from "react"
import { vscode } from "@/utils/vscode"
import { WebServiceClient } from "@/services/grpc-client"
import DOMPurify from "dompurify"
import { getSafeHostname, formatUrlForOpening, checkIfImageUrl } from "./utils/mcpRichUtil"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
@@ -233,14 +232,11 @@ class ImagePreview extends React.Component<
borderRadius: "4px",
color: "var(--vscode-errorForeground)",
}}
onClick={async () => {
try {
await WebServiceClient.openInBrowser({
value: DOMPurify.sanitize(url),
})
} catch (err) {
console.error("Error opening URL in browser:", err)
}
onClick={() => {
vscode.postMessage({
type: "openInBrowser",
url: DOMPurify.sanitize(url),
})
}}>
<div style={{ fontWeight: "bold" }}>Failed to load image</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
@@ -260,14 +256,11 @@ class ImagePreview extends React.Component<
maxWidth: "100%",
cursor: "pointer",
}}
onClick={async () => {
try {
await WebServiceClient.openInBrowser({
value: DOMPurify.sanitize(formatUrlForOpening(url)),
})
} catch (err) {
console.error("Error opening URL in browser:", err)
}
onClick={() => {
vscode.postMessage({
type: "openInBrowser",
url: DOMPurify.sanitize(formatUrlForOpening(url)),
})
}}>
{/\.svg(\?.*)?$/i.test(url) ? (
// Special handling for SVG images
@@ -238,14 +238,11 @@ class LinkPreview extends React.Component<LinkPreviewProps, LinkPreviewState> {
maxWidth: "512px",
overflow: "auto",
}}
onClick={async () => {
try {
await WebServiceClient.openInBrowser({
value: DOMPurify.sanitize(url),
})
} catch (err) {
console.error("Error opening URL in browser:", err)
}
onClick={() => {
vscode.postMessage({
type: "openInBrowser",
url: DOMPurify.sanitize(url),
})
}}>
<div style={{ fontWeight: "bold" }}>{errorDisplay}</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
@@ -278,14 +275,11 @@ class LinkPreview extends React.Component<LinkPreviewProps, LinkPreviewState> {
height: "128px",
maxWidth: "512px",
}}
onClick={async () => {
try {
await WebServiceClient.openInBrowser({
value: DOMPurify.sanitize(url),
})
} catch (err) {
console.error("Error opening URL in browser:", err)
}
onClick={() => {
vscode.postMessage({
type: "openInBrowser",
url: DOMPurify.sanitize(url),
})
}}>
{data.image && (
<div className="link-preview-image" style={{ width: "128px", height: "128px", flexShrink: 0 }}>
@@ -51,8 +51,6 @@ import {
nebiusDefaultModelId,
sambanovaModels,
sambanovaDefaultModelId,
cerebrasModels,
cerebrasDefaultModelId,
doubaoModels,
doubaoDefaultModelId,
liteLlmModelInfoSaneDefaults,
@@ -331,7 +329,6 @@ const ApiOptions = ({
<VSCodeOption value="asksage">AskSage</VSCodeOption>
<VSCodeOption value="xai">xAI</VSCodeOption>
<VSCodeOption value="sambanova">SambaNova</VSCodeOption>
<VSCodeOption value="cerebras">Cerebras</VSCodeOption>
</VSCodeDropdown>
</DropdownContainer>
@@ -2016,37 +2013,6 @@ const ApiOptions = ({
</div>
)}
{selectedProvider === "cerebras" && (
<div>
<VSCodeTextField
value={apiConfiguration?.cerebrasApiKey || ""}
style={{ width: "100%" }}
type="password"
onInput={handleInputChange("cerebrasApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Cerebras API Key</span>
</VSCodeTextField>
<p
style={{
fontSize: "12px",
marginTop: 3,
color: "var(--vscode-descriptionForeground)",
}}>
This key is stored locally and only used to make API requests from this extension.
{!apiConfiguration?.cerebrasApiKey && (
<VSCodeLink
href="https://cloud.cerebras.ai/"
style={{
display: "inline",
fontSize: "inherit",
}}>
You can get a Cerebras API key by signing up here.
</VSCodeLink>
)}
</p>
</div>
)}
{apiErrorMessage && (
<p
style={{
@@ -2164,7 +2130,6 @@ const ApiOptions = ({
{selectedProvider === "asksage" && createDropdown(askSageModels)}
{selectedProvider === "xai" && createDropdown(xaiModels)}
{selectedProvider === "sambanova" && createDropdown(sambanovaModels)}
{selectedProvider === "cerebras" && createDropdown(cerebrasModels)}
{selectedProvider === "nebius" && createDropdown(nebiusModels)}
</DropdownContainer>
@@ -2600,8 +2565,6 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration):
return getProviderData(nebiusModels, nebiusDefaultModelId)
case "sambanova":
return getProviderData(sambanovaModels, sambanovaDefaultModelId)
case "cerebras":
return getProviderData(cerebrasModels, cerebrasDefaultModelId)
default:
return getProviderData(anthropicModels, anthropicDefaultModelId)
}
@@ -41,8 +41,8 @@ export interface OpenRouterModelPickerProps {
// Featured models for Cline provider
const featuredModels = [
{
id: "anthropic/claude-3.7-sonnet",
description: "Recommended for agentic coding in Cline",
id: "anthropic/claude-sonnet-4",
description: "Best model for agentic coding",
label: "Best",
},
{
@@ -336,8 +336,8 @@ const OpenRouterModelPicker: React.FC<OpenRouterModelPickerProps> = ({ isPopup }
If you're unsure which model to choose, Cline works best with{" "}
<VSCodeLink
style={{ display: "inline", fontSize: "inherit" }}
onClick={() => handleModelChange("anthropic/claude-3.7-sonnet")}>
anthropic/claude-3.7-sonnet.
onClick={() => handleModelChange("anthropic/claude-sonnet-4")}>
anthropic/claude-sonnet-4.
</VSCodeLink>
You can also try searching "free" for no-cost options currently available.
</>
@@ -607,7 +607,7 @@ const SettingsView = ({ onDone, targetSection }: SettingsViewProps) => {
<div className="mb-[5px]">
<VSCodeCheckbox
className="mb-[5px]"
checked={telemetrySetting !== "disabled"}
checked={telemetrySetting === "enabled"}
onChange={(e: any) => {
const checked = e.target.checked === true
setTelemetrySetting(checked ? "enabled" : "disabled")
@@ -1,46 +0,0 @@
import React from "react"
import { QuickWinTask } from "./quickWinTasks"
interface QuickWinCardProps {
task: QuickWinTask
onExecute: () => void
}
const renderIcon = (iconName?: string) => {
if (!iconName) return <span className="codicon codicon-rocket text-lg"></span>
let iconClass = "codicon-rocket"
switch (iconName) {
case "WebAppIcon":
iconClass = "codicon-dashboard"
break
case "TerminalIcon":
iconClass = "codicon-terminal"
break
case "GameIcon":
iconClass = "codicon-game"
break
default:
break
}
return <span className={`codicon ${iconClass} text-lg`}></span>
}
const QuickWinCard: React.FC<QuickWinCardProps> = ({ task, onExecute }) => {
return (
<div
className="flex items-center p-1 space-x-1.5 rounded-full cursor-pointer group transition-colors duration-150 ease-in-out bg-[var(--vscode-sideBar-background)] border border-[var(--vscode-panel-border)] hover:bg-[var(--vscode-list-hoverBackground)]"
onClick={() => onExecute()}>
<div className="flex-shrink-0 flex items-center justify-center w-5 h-5 text-[var(--vscode-icon-foreground)]">
{renderIcon(task.icon)}
</div>
<div className="flex-grow min-w-0">
<h3 className="text-xs font-medium truncate text-[var(--vscode-editor-foreground)]">{task.title}</h3>
<p className="text-xs truncate text-[var(--vscode-descriptionForeground)]">{task.description}</p>
</div>
</div>
)
}
export default QuickWinCard
@@ -1,27 +0,0 @@
import React from "react"
import { TaskServiceClient } from "@/services/grpc-client"
import QuickWinCard from "./QuickWinCard"
import { QuickWinTask, quickWinTasks } from "./quickWinTasks"
export const SuggestedTasks: React.FC<{ shouldShowQuickWins: boolean }> = ({ shouldShowQuickWins }) => {
const handleExecuteQuickWin = async (prompt: string) => {
await TaskServiceClient.newTask({ text: prompt, images: [] })
}
if (shouldShowQuickWins) {
return (
<div className="px-4 pt-1 pb-3 select-none">
{" "}
<h2 className="text-sm font-medium mb-2.5 text-center text-[var(--vscode-editor-foreground)]">
Quick <span className="text-[var(--vscode-terminal-ansiBrightCyan)]">[Wins]</span> with Cline
</h2>
<div className="flex flex-col space-y-1">
{" "}
{quickWinTasks.map((task: QuickWinTask) => (
<QuickWinCard key={task.id} task={task} onExecute={() => handleExecuteQuickWin(task.prompt)} />
))}
</div>
</div>
)
}
}
@@ -38,8 +38,8 @@ const WelcomeView = memo(() => {
</div>
<p>
I can do all kinds of tasks thanks to breakthroughs in{" "}
<VSCodeLink href="https://www.anthropic.com/news/claude-3-7-sonnet" className="inline">
Claude 3.7 Sonnet's
<VSCodeLink href="https://www.anthropic.com/claude/sonnet" className="inline">
Claude 4 Sonnet's
</VSCodeLink>
agentic coding capabilities and access to tools that let me create & edit files, explore complex projects, use
a browser, and execute terminal commands <i>(with your permission, of course)</i>. I can even use MCP to
@@ -47,8 +47,8 @@ const WelcomeView = memo(() => {
</p>
<p className="text-[var(--vscode-descriptionForeground)]">
Sign up for an account to get started for free, or use an API key that provides access to models like Claude
3.7 Sonnet.
Sign up for an account to get started for free, or use an API key that provides access to models like Claude 4
Sonnet.
</p>
<VSCodeButton appearance="primary" onClick={handleLogin} className="w-full mt-1">
@@ -1,39 +0,0 @@
export interface QuickWinTask {
id: string
title: string
description: string
icon?: string
actionCommand: string
prompt: string
buttonText?: string
}
export const quickWinTasks: QuickWinTask[] = [
{
id: "nextjs_notetaking_app",
title: "Build a Next.js App",
description: "Create a beautiful notetaking application with Next.js and Tailwind CSS.",
icon: "WebAppIcon",
actionCommand: "cline/createNextJsApp",
prompt: "Make a beautiful Next.js notetaking app, using Tailwind CSS for styling. Set up the basic structure and a simple UI for adding and viewing notes.",
buttonText: ">",
},
{
id: "terminal_cli_tool",
title: "Craft a CLI Tool",
description: "Develop a powerful terminal CLI to automate a cool task.",
icon: "TerminalIcon",
actionCommand: "cline/createCliTool",
prompt: "Make a terminal CLI tool using Node.js that fetches the current weather for a given city using a free weather API and displays it in a user-friendly format.",
buttonText: ">",
},
{
id: "snake_game",
title: "Develop a Game",
description: "Code a classic Snake game that runs in the browser.",
icon: "GameIcon",
actionCommand: "cline/createSnakeGame",
prompt: "Make a classic Snake game using HTML, CSS, and JavaScript. The game should be playable in the browser, with keyboard controls for the snake, a scoring system, and a game over state.",
buttonText: ">",
},
]
@@ -59,7 +59,6 @@ interface ExtensionStateContextType extends ExtensionState {
setLocalWorkflowToggles: (toggles: Record<string, boolean>) => void
setGlobalWorkflowToggles: (toggles: Record<string, boolean>) => void
setMcpMarketplaceCatalog: (value: McpMarketplaceCatalog) => void
setTotalTasksSize: (value: number | null) => void
// Navigation state setters
setShowMcp: (value: boolean) => void
@@ -157,7 +156,7 @@ export const ExtensionStateContextProvider: React.FC<{
chatSettings: DEFAULT_CHAT_SETTINGS,
platform: DEFAULT_PLATFORM,
telemetrySetting: "unset",
distinctId: "",
vscMachineId: "",
planActSeparateModelsSetting: true,
enableCheckpointsSetting: true,
globalClineRulesToggles: {},
@@ -207,6 +206,60 @@ export const ExtensionStateContextProvider: React.FC<{
}
break
}
case "state": {
// Handler for direct state messages
if (message.state) {
const stateData = message.state as ExtensionState
console.log("[Webview Context Test Revert] Received direct 'state' message, updating state.")
setState((prevState) => {
// Versioning logic for autoApprovalSettings (copied from original onResponse)
const incomingVersion = stateData.autoApprovalSettings?.version ?? 1
const currentVersion = prevState.autoApprovalSettings?.version ?? 1
const shouldUpdateAutoApproval = incomingVersion > currentVersion
const newState = {
...stateData,
autoApprovalSettings: shouldUpdateAutoApproval
? stateData.autoApprovalSettings
: prevState.autoApprovalSettings,
}
// Update welcome screen state based on API configuration (copied from original onResponse)
const config = stateData.apiConfiguration
const hasKey = config
? [
config.apiKey,
config.openRouterApiKey,
config.awsRegion,
config.vertexProjectId,
config.openAiApiKey,
config.ollamaModelId,
config.lmStudioModelId,
config.liteLlmApiKey,
config.geminiApiKey,
config.openAiNativeApiKey,
config.deepSeekApiKey,
config.requestyApiKey,
config.togetherApiKey,
config.qwenApiKey,
config.doubaoApiKey,
config.mistralApiKey,
config.vsCodeLmModelSelector,
config.clineApiKey,
config.asksageApiKey,
config.xaiApiKey,
config.sambanovaApiKey,
config.nebiusApiKey,
].some((key) => key !== undefined)
: false
setShowWelcome(!hasKey)
setDidHydrateState(true)
return newState
})
}
break
}
case "theme": {
if (message.text) {
setTheme(convertTextMateToHljs(JSON.parse(message.text)))
@@ -263,6 +316,10 @@ export const ExtensionStateContextProvider: React.FC<{
}
break
}
case "totalTasksSize": {
setTotalTasksSize(message.totalTasksSize ?? null)
break
}
}
}, [])
@@ -272,31 +329,33 @@ export const ExtensionStateContextProvider: React.FC<{
const stateSubscriptionRef = useRef<(() => void) | null>(null)
// Subscribe to state updates using the new gRPC streaming API
/* // TEST REVERT: Commenting out gRPC state subscription
useEffect(() => {
// Set up state subscription
stateSubscriptionRef.current = StateServiceClient.subscribeToState(
{},
{
onResponse: (response) => {
console.log("[DEBUG] got state update via subscription", response);
if (response.stateJson) {
try {
const stateData = JSON.parse(response.stateJson) as ExtensionState
console.log("[DEBUG] parsed state JSON, updating state")
const stateData = JSON.parse(response.stateJson) as ExtensionState;
console.log("[DEBUG] parsed state JSON, updating state");
setState((prevState) => {
// Versioning logic for autoApprovalSettings
const incomingVersion = stateData.autoApprovalSettings?.version ?? 1
const currentVersion = prevState.autoApprovalSettings?.version ?? 1
const shouldUpdateAutoApproval = incomingVersion > currentVersion
const incomingVersion = stateData.autoApprovalSettings?.version ?? 1;
const currentVersion = prevState.autoApprovalSettings?.version ?? 1;
const shouldUpdateAutoApproval = incomingVersion > currentVersion;
const newState = {
...stateData,
autoApprovalSettings: shouldUpdateAutoApproval
? stateData.autoApprovalSettings
: prevState.autoApprovalSettings,
}
};
// Update welcome screen state based on API configuration
const config = stateData.apiConfiguration
const config = stateData.apiConfiguration;
const hasKey = config
? [
config.apiKey,
@@ -321,41 +380,52 @@ export const ExtensionStateContextProvider: React.FC<{
config.xaiApiKey,
config.sambanovaApiKey,
].some((key) => key !== undefined)
: false
: false;
setShowWelcome(!hasKey)
setDidHydrateState(true)
setShowWelcome(!hasKey);
setDidHydrateState(true);
console.log("[DEBUG] returning new state in ESC")
console.log("[DEBUG] returning new state in ESC");
return newState
})
return newState;
});
} catch (error) {
console.error("Error parsing state JSON:", error)
console.log("[DEBUG] ERR getting state", error)
console.error("Error parsing state JSON:", error);
console.log("[DEBUG] ERR getting state", error);
}
}
console.log('[DEBUG] ended "got subscribed state"')
console.log('[DEBUG] ended "got subscribed state"');
},
onError: (error) => {
console.error("Error in state subscription:", error)
console.error("Error in state subscription:", error);
},
onComplete: () => {
console.log("State subscription completed")
console.log("State subscription completed");
},
},
)
);
// Still send the webviewDidLaunch message for other initialization
vscode.postMessage({ type: "webviewDidLaunch" })
vscode.postMessage({ type: "webviewDidLaunch" });
// Clean up subscription when component unmounts
return () => {
if (stateSubscriptionRef.current) {
stateSubscriptionRef.current()
stateSubscriptionRef.current = null
stateSubscriptionRef.current();
stateSubscriptionRef.current = null;
}
}
};
}, []);
*/ // END TEST REVERT
// For the test revert, ensure webviewDidLaunch is still sent if not done by the above useEffect
useEffect(() => {
// This effect now only sends webviewDidLaunch if the gRPC subscription is commented out.
// If the gRPC subscription is active, it sends webviewDidLaunch.
// To avoid sending it twice if you uncomment the above, you might add a flag.
// For this specific test (gRPC sub commented out), this is fine.
console.log("[Webview Context Test Revert] Sending webviewDidLaunch from separate useEffect.")
vscode.postMessage({ type: "webviewDidLaunch" })
}, [])
const contextValue: ExtensionStateContextType = {
@@ -488,7 +558,6 @@ export const ExtensionStateContextProvider: React.FC<{
globalWorkflowToggles: toggles,
})),
setMcpTab,
setTotalTasksSize,
}
return <ExtensionStateContext.Provider value={contextValue}>{children}</ExtensionStateContext.Provider>
+11 -17
View File
@@ -2,7 +2,6 @@ import { User, getAuth, signInWithCustomToken, signOut } from "firebase/auth"
import { initializeApp } from "firebase/app"
import React, { createContext, useCallback, useContext, useEffect, useState } from "react"
import { vscode } from "@/utils/vscode"
import { AccountServiceClient } from "@/services/grpc-client"
// Firebase configuration from extension
const firebaseConfig = {
@@ -38,6 +37,8 @@ export const FirebaseAuthProvider: React.FC<{ children: React.ReactNode }> = ({
setUser(user)
setIsInitialized(true)
console.log("onAuthStateChanged user", user)
if (!user) {
// when opening the extension in a new webview (ie if you logged in to sidebar webview but then open a popout tab webview) this effect will trigger without the original webview's session, resulting in us clearing out the user info object.
// we rely on this object to determine if the user is logged in, so we only want to clear it when the user logs out, rather than whenever a webview without a session is opened.
@@ -72,24 +73,17 @@ export const FirebaseAuthProvider: React.FC<{ children: React.ReactNode }> = ({
[auth],
)
// Set up authCallback subscription
// Listen for auth callback from extension
useEffect(() => {
const cleanup = AccountServiceClient.subscribeToAuthCallback(
{},
{
onResponse: (event) => {
if (event.value) {
signInWithToken(event.value)
}
},
onError: (error) => {
console.error("Error in authCallback subscription:", error)
},
onComplete: () => {},
},
)
const handleMessage = (event: MessageEvent) => {
const message = event.data
if (message.type === "authCallback" && message.customToken) {
signInWithToken(message.customToken)
}
}
return cleanup
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}, [signInWithToken])
const handleSignOut = useCallback(async () => {
@@ -94,6 +94,7 @@ export function createGrpcClient<T extends ProtoService>(service: T): GrpcClient
if (message.grpc_response.message) {
const responseType = method.responseType
const response = responseType.fromJSON(message.grpc_response.message)
console.log("[DEBUG] Received streaming response:", message.grpc_response.message)
options.onResponse(response)
}
}
@@ -148,6 +149,7 @@ export function createGrpcClient<T extends ProtoService>(service: T): GrpcClient
// Convert JSON back to protobuf message
const responseType = method.responseType
const response = responseType.fromJSON(message.grpc_response.message)
console.log("[DEBUG] grpc-client sending response:", response)
resolve(response)
}
}