Compare commits

...

44 Commits

Author SHA1 Message Date
Cline Evaluation f3ac8b13e7 forgot .name 2025-05-29 20:00:03 -07:00
Cline Evaluation 14028f90c5 bashTool 2025-05-29 19:41:43 -07:00
Cline Evaluation 7efe72b6ff bash tool now getting cwd 2025-05-29 19:39:09 -07:00
Cline Evaluation 9d6e4e778f bash tool working 2025-05-29 19:27:16 -07:00
Cline Evaluation fe2e02b260 rebasing 2025-05-29 16:56:11 -07:00
Cline Evaluation 26616b3b6a modularizing prompt a bit 2025-05-29 15:37:55 -07:00
Cline Evaluation 5f98e42e6a bash tool cont 2025-05-29 15:34:59 -07:00
Cline Evaluation e77fad3e52 bashtool cont 2025-05-29 15:30:19 -07:00
Cline Evaluation 145977504e alignment 2025-05-29 15:25:42 -07:00
Toshii cc9fc9bd1f update chat box ui (#3868)
* chat area

* changeset

* arrow

* nit

* tailwind
2025-05-29 13:23:59 -07:00
Ara dcf59bc29f Fix Title for Cline on Windows (#3917)
* Fix Title for Cline on Windows

* Fix Title for Cline on Windows

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-30 01:04:54 +05:30
Caleb Eom 5c3e7a38d4 Scroll to message onclick from task timeline (#3890)
* Scroll to message onclick from task timeline

* version

* fixing ellipsis-dev's suggestion on potential infinite loop
2025-05-29 00:49:08 -07:00
github-actions[bot] d6ccbcdf22 v3.17.8 Release Notes
v3.17.8 Release Notes
2025-05-28 23:01:23 -07:00
pashpashpash e4e03fa0dd reverting timeout if no first chunk (#3899)
* reverting timeout if no first chunk

* Create fresh-days-end.md

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-05-28 21:04:48 -07:00
Cline Evaluation 22585b3145 prettier 2025-05-28 19:15:28 -07:00
pashpashpash 10892670be exact antml (#3891)
* exact antml

* only one invoke

* linter warnings

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 19:12:26 -07:00
Evan 3c7a42c35d Add grep tool new format (#3893)
* add ls file tool description, parsing, and return formatting

* add json tool definition and remove extra '.'

* changeset

* use separate function for new format

* using json

* add grep tool new format

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 18:32:18 -07:00
Cline Evaluation c4a5b3f761 bashTool 2025-05-28 17:43:23 -07:00
Evan abfaf6ca7a LS is moar (#3883)
* add ls file tool description, parsing, and return formatting

* add json tool definition and remove extra '.'

* changeset

* use separate function for new format

* using json

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 16:15:38 -07:00
pashpashpash f699f1fd80 exact antml (#3887)
* exact antml

* moved system prompt after tool defs

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 16:07:17 -07:00
Sarah Fortune a6fbdcb5c1 Add secrets to the vscode extension context. (#3881)
* Add secrets to the vscode extension context.

Add a secrets store backed by a file.
Compile the standalone distribtion during `npm run pretest`

* Fix type

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Remove logging

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-28 15:02:21 -07:00
Sarah Fortune a4200869c9 Add java_package to state.proto (#3886) 2025-05-28 15:01:21 -07:00
canvrno 9f59b6010e browserConnectionResult removal (#3885) 2025-05-28 14:48:07 -07:00
canvrno 29d3175e0b Add ReadTool & WriteTool alternate tools (#3873)
* Added ReadTool and WriteTool alternate tool calls

* claude4 system prompt - add read & write alt tools
2025-05-28 14:08:46 -07:00
pashpashpash 600174322e created framework for idiomatic tool calling in claude 4 models (#3872)
* created framework for idiomatic tool calling in claude 4 models

* aligning

* Update src/core/tools/bashTool.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Fix Diff edit prompt

* commented out for now

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-27 23:39:33 -07:00
pashpashpash 9818d976dd Canvrno/modular system prompt (#3863)
* System prompt refactor

* Commented out model switching for now

* Claude4 system prompt switching

* cleanup

* added system.ts to prettier ignore

* workflow tips

---------

Co-authored-by: canvrno <kevin@cline.bot>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 22:42:58 -07:00
Andrei Eternal 3938e23cde [PROTOBUS] subscription for addToInput (#3781)
* Protobus subscription for addToInput

* formatfix

* prettier

* dont re-add selectedImages

---------

Co-authored-by: Andrei Eternal <eternal@cline.bot>
2025-05-27 21:43:14 -07:00
github-actions[bot] 86bb0c6ded Changeset version bump (#3864)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.17.7

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 20:15:08 -07:00
Ara 36f57ce6c0 Fix Claude 4 family diff edit prompt (#3866)
* Fix Claude 4 diff edits prompt

* Show gemini 2.5 flash prompt cache

* Update src/core/prompts/system.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-27 20:02:11 -07:00
canvrno ed0181a114 showChatView protobus (#3862) 2025-05-27 18:19:51 -07:00
github-actions[bot] 439c62935d v3.17.6 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for version 3.17.6

* attribution

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 17:33:54 -07:00
Sean Gallen 9bc24ecd96 Minor fixes in the Documentation for broken links and typos. (#3820)
* fix bash commands

* fix links in the Context Management

* fix for internal links in Our Favorite Tech Stack
2025-05-27 17:17:34 -07:00
francis 2150e4882e feat: add vscode language model api config docs (#3836) 2025-05-27 17:15:04 -07:00
Toshii ee347bfe9d allow uploading more file types (#3824)
* Changeset version bump (#3740)

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for version 3.17.1

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>

* process files

* grpc

* select files

* update messaging

* chat view support

* thumbnails base

* ui component

* more files

* pre file parsing

* keep old file

* base 3

* file passing update

* ui fixes

* task base

* header ui

* grpc

* changeset

* nit

* remove binary check

* small

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 17:13:15 -07:00
kevinneung 08d86990e2 Improve documentation for "For New Coders" page (#3785)
* Improve documentation for new coders

- Reorganized steps for better flow and clarity
- Added missing hyperlinks for better navigation
- Underlined hyperlinks for improved accessibility and visual consistency

* Update docs/getting-started/for-new-coders.mdx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-27 16:52:27 -07:00
Ara f74a8ba82e Show Gemini 2.5 Pro prompt cache (#3859)
* Show gemini 2.5 flash prompt cache

* Show gemini 2.5 flash prompt cache

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-28 04:42:41 +05:30
Evan ad51b7a4e1 reset recommended model (#3857)
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-27 16:10:06 -07:00
Ara 94516092b1 Support Diff Editing for Claude 4 family of Models (#3816)
* feat: add JSON-based diff format for Claude 4 model family

- Bump version to 3.17.5
- Add @streamparser/json dependency for streaming JSON parsing
- Implement new JSON diff format in replace_in_file tool for Claude 4 models
- Add diff-json.ts module for handling JSON-based file replacements
- Update system prompts to use JSON format when Claude 4 model detected
- Enhance DiffViewProvider to support new JSON diff format

* Adding diffs

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 15:10:48 -07:00
Ara adf25681cc Add a beautiful experience for new users of Cline (#3719)
* Adding AGI Blog

* feat: disable quick wins feature in chat interface

Removes quick wins display by setting shouldShowQuickWins to false, cleans up related code in ChatView and simplifies component rendering logic. Also includes code cleanup in QuickWinCard component by removing redundant comments.

* Initial edit commands

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-27 14:34:43 -07:00
canvrno e2f73bce61 [PROTOBUS] remove invoke message, replace usage (#3609)
* invoke protobus migration

Updated Cline API invoke usage for GRPC

cleanup

* cleanup

* Updated ClineAPI

* cleanup

* Added ClineAPI tests

* removed invoke

* One line cleanup
2025-05-27 13:59:52 -07:00
Evan fec8626291 Migrate authCallback protobus (#3846)
* migrate authCallback

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-27 08:57:05 -07:00
Kevin Taylor 6fa819a170 Added Cerebras as a Provider (#3810)
* Added Cerebras as a Provider

* prettier fix

* prettier

---------

Co-authored-by: sam <sam@MacBook-Air-3.local>
2025-05-26 20:06:15 -07:00
Andrei Eternal 2ca3e9ac82 [PROTOBUS] Re-enable streaming state, fix the memory leak probably (#3754)
* Revert "fix: Address memory leak by bypassing subscribeToState gRPC stream for state updates (#3597)"

This reverts commit 8ab35a5b06.

* memory leak console boys

* cleanup

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
Co-authored-by: Andrei Eternal <eternal@cline.bot>
2025-05-26 18:17:09 -07:00
Luis Felipe Salazar Ucros 9d801a1a68 Sambanova models update list and docs link (#3419)
* update models list

* update docs link with utm

* remove tracking link
2025-05-26 15:50:59 -07:00
82 changed files with 3950 additions and 702 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate openExtensionSettings to protobus
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
add back missing function
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate showAccountViewClicked to protobus
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Adding Telemetry for button clicks
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
openInBrowser protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Use identify to enhance distinct user segmentation
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
update chat box ui
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix Title for windows in cline
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
scroll to task timeline
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate openMcpSettings to protobus
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
requestTotalTasksSize protobus migration
+1
View File
@@ -164,6 +164,7 @@ 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
+2
View File
@@ -3,3 +3,5 @@ node_modules
webview-ui/build/
*.md
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
+18
View File
@@ -1,5 +1,23 @@
# Changelog
## [3.17.8]
- Fix bug where terminal would get stuck and output "capture failure"
## [3.17.7]
- Fix diff editing reliability for Claude 4 family models by adding constraints to prevent errors with large replacements
## [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, 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.
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.
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.
@@ -0,0 +1,44 @@
---
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.
+2 -1
View File
@@ -148,7 +148,8 @@
"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/litellm-and-cline-using-codestral",
"custom-model-configs/vscode-language-model-api"
]
},
{
+27 -27
View File
@@ -13,35 +13,13 @@ Before you jump into coding, make sure you have these essentials ready:
A popular, free, and powerful code editor.
- [Download VS Code](https://code.visualstudio.com/)
- [<u>Download VS Code</u>](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
📺 **Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](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. **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**
#### 2. **Organize Your Projects**
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
@@ -55,14 +33,36 @@ Inside your `Cline` folder, structure projects clearly:
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 4. **Install the Cline VS Code Extension**
#### 3. **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:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
📺 **Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](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/getting-started-new-coders/installing-dev-essentials)
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/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
bashCopygit pull origin main # Download latest code
git pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
bashCopygit add .
git add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
bashCopygit push origin main # Upload to GitHub
git 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/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) 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/features/plan-and-act) 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/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/prompting/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/improving-your-prompting-skills/prompting) files in project roots)
- Share common context files (consider using [.clinerules](https://docs.cline.bot/features/cline-rules) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
+63 -2
View File
@@ -1,12 +1,12 @@
{
"name": "claude-dev",
"version": "3.17.2",
"version": "3.17.8",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "claude-dev",
"version": "3.17.2",
"version": "3.17.8",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.12.4",
@@ -14,6 +14,7 @@
"@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",
@@ -27,6 +28,7 @@
"@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",
@@ -4089,6 +4091,30 @@
"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",
@@ -10895,6 +10921,12 @@
"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",
@@ -28892,6 +28924,30 @@
"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",
@@ -34092,6 +34148,11 @@
"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",
+5 -9
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.5",
"version": "3.17.8",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -58,13 +58,7 @@
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "isWindows"
},
{
"id": "claude-dev-ActivityBar",
"title": "Cline (Ctrl+')",
"icon": "assets/icons/icon.svg",
"when": "isLinux || !isMac && !isWindows"
"when": "!isMac"
}
]
},
@@ -283,7 +277,7 @@
"postprotos": "prettier src/shared/proto src/core/controller webview-ui/src/services src/standalone/server-setup.ts --write --log-level silent",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run lint",
"pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint",
"check-types": "npm run protos && tsc --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts",
"format": "prettier . --check",
@@ -349,6 +343,7 @@
"@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",
@@ -362,6 +357,7 @@
"@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,4 +16,7 @@ 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,3 +58,8 @@ message Boolean {
message StringArray {
repeated string values = 1;
}
message StringArrays {
repeated string values1 = 1;
repeated string values2 = 2;
}
+3
View File
@@ -31,6 +31,9 @@ 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);
+3
View File
@@ -1,5 +1,7 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
@@ -37,6 +39,7 @@ message ChatSettings {
message ChatContent {
optional string message = 1;
repeated string images = 2;
repeated string files = 3;
}
// Message for auto approval settings
+2
View File
@@ -40,6 +40,7 @@ message NewTaskRequest {
Metadata metadata = 1;
string text = 2;
repeated string images = 3;
repeated string files = 4;
}
// Request message for toggling task favorite status
@@ -104,4 +105,5 @@ message AskResponseRequest {
string response_type = 2;
string text = 3;
repeated string images = 4;
repeated string files = 5;
}
+3
View File
@@ -13,4 +13,7 @@ service UiService {
// Marks the current announcement as shown and returns whether an announcement should still be shown
rpc onDidShowAnnouncement(EmptyRequest) returns (Boolean);
// Subscribe to addToInput events (when user adds content via context menu)
rpc subscribeToAddToInput(EmptyRequest) returns (stream String);
}
+3
View File
@@ -24,6 +24,7 @@ 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
@@ -84,6 +85,8 @@ 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
@@ -0,0 +1,169 @@
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
@@ -0,0 +1,135 @@
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,
}
}
}
@@ -473,3 +473,394 @@ export function parseAssistantMessageV2(assistantMessage: string): AssistantMess
return contentBlocks
}
export function parseAssistantMessageV3(assistantMessage: string): AssistantMessageContent[] {
const contentBlocks: AssistantMessageContent[] = []
let currentTextContentStart = 0 // Index where the current text block started
let currentTextContent: TextContent | undefined = undefined
let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use
let currentToolUse: ToolUse | undefined = undefined
let currentParamValueStart = 0 // Index *after* the opening tag of the current param
let currentParamName: ToolParamName | undefined = undefined
// Precompute tags for faster lookups
const toolUseOpenTags = new Map<string, ToolUseName>()
const toolParamOpenTags = new Map<string, ToolParamName>()
for (const name of toolUseNames) {
toolUseOpenTags.set(`<${name}>`, name)
}
for (const name of toolParamNames) {
toolParamOpenTags.set(`<${name}>`, name)
}
// Function calls format detection
const isFunctionCallsOpen = "<function_calls>"
const isFunctionCallsClose = "</function_calls>"
const isInvokeStart = '<invoke name="'
const isInvokeEnd = '">'
const isInvokeClose = "</invoke>"
const isParameterStart = '<parameter name="'
const isParameterNameEnd = '">'
const isParameterClose = "</parameter>"
// Variables for function calls parsing
let inFunctionCalls = false
let currentInvokeName = ""
let currentParameterName = ""
const len = assistantMessage.length
for (let i = 0; i < len; i++) {
const currentCharIndex = i
// --- State: Parsing Function Calls ---
// Check for opening function_calls tag
if (
!inFunctionCalls &&
currentCharIndex >= isFunctionCallsOpen.length - 1 &&
assistantMessage.startsWith(isFunctionCallsOpen, currentCharIndex - isFunctionCallsOpen.length + 1)
) {
// End current text block if one was active
if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(currentTextContentStart, currentCharIndex - isFunctionCallsOpen.length + 1)
.trim()
currentTextContent.partial = false
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
}
inFunctionCalls = true
continue
}
// Check for invoke start within function_calls
if (
inFunctionCalls &&
currentInvokeName === "" &&
currentCharIndex >= isInvokeStart.length - 1 &&
assistantMessage.startsWith(isInvokeStart, currentCharIndex - isInvokeStart.length + 1)
) {
// Find the end of the invoke name
const nameEndPos = assistantMessage.indexOf(isInvokeEnd, currentCharIndex + 1)
if (nameEndPos !== -1) {
// Extract the invoke name
currentInvokeName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
i = nameEndPos + isInvokeEnd.length - 1 // Skip to after the '">
// If this is an LS invoke, create a list_files tool
if (currentInvokeName === "LS") {
currentToolUse = {
type: "tool_use",
name: "list_files",
params: {},
partial: true,
}
}
// If this is a Grep invoke, create a search_files tool
if (currentInvokeName === "Grep") {
currentToolUse = {
type: "tool_use",
name: "search_files",
params: {},
partial: true,
}
}
if (currentInvokeName === "Bash") {
currentToolUse = {
type: "tool_use",
name: "execute_command",
params: {},
partial: true,
}
}
continue
}
}
// Check for parameter start within invoke
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentParameterName === "" &&
currentCharIndex >= isParameterStart.length - 1 &&
assistantMessage.startsWith(isParameterStart, currentCharIndex - isParameterStart.length + 1)
) {
// Find the end of the parameter name
const nameEndPos = assistantMessage.indexOf(isParameterNameEnd, currentCharIndex + 1)
if (nameEndPos !== -1) {
// Extract the parameter name
currentParameterName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
currentParamValueStart = nameEndPos + isParameterNameEnd.length
i = nameEndPos + isParameterNameEnd.length - 1 // Skip to after the '">'
continue
}
}
// Check for parameter end
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentParameterName !== "" &&
currentCharIndex >= isParameterClose.length - 1 &&
assistantMessage.startsWith(isParameterClose, currentCharIndex - isParameterClose.length + 1)
) {
// Extract parameter value
const value = assistantMessage.slice(currentParamValueStart, currentCharIndex - isParameterClose.length + 1).trim()
// Map parameter to tool params
if (currentToolUse && currentInvokeName === "LS" && currentParameterName === "path") {
currentToolUse.params["path"] = value
// Default recursive to false - only show top level
currentToolUse.params["recursive"] = "false"
}
// Map parameter to tool params for Grep
if (currentToolUse && currentInvokeName === "Grep") {
if (currentParameterName === "pattern") {
currentToolUse.params["regex"] = value
} else if (currentParameterName === "path") {
currentToolUse.params["path"] = value
} else if (currentParameterName === "include") {
currentToolUse.params["file_pattern"] = value
}
}
if (currentToolUse && currentInvokeName === "Bash") {
if (currentParameterName === "command") {
currentToolUse.params["command"] = value
} else if (currentParameterName === "requires_approval") {
currentToolUse.params["requires_approval"] = value === "true" ? "true" : "false"
}
}
currentParameterName = ""
continue
}
// Check for invoke end
if (
inFunctionCalls &&
currentInvokeName !== "" &&
currentCharIndex >= isInvokeClose.length - 1 &&
assistantMessage.startsWith(isInvokeClose, currentCharIndex - isInvokeClose.length + 1)
) {
// If we have a tool use from this invoke, finalize it
if (currentToolUse && (currentInvokeName === "LS" || currentInvokeName === "Grep" || currentInvokeName === "Bash")) {
currentToolUse.partial = false
contentBlocks.push(currentToolUse)
currentToolUse = undefined
}
currentInvokeName = ""
continue
}
// Check for function_calls end
if (
inFunctionCalls &&
currentCharIndex >= isFunctionCallsClose.length - 1 &&
assistantMessage.startsWith(isFunctionCallsClose, currentCharIndex - isFunctionCallsClose.length + 1)
) {
inFunctionCalls = false
currentTextContentStart = currentCharIndex + 1
continue
}
// Skip normal parsing when inside function_calls
if (inFunctionCalls) {
continue
}
// --- State: Parsing a Tool Parameter ---
if (currentToolUse && currentParamName) {
const closeTag = `</${currentParamName}>`
// Check if the string *ending* at index `i` matches the closing tag
if (
currentCharIndex >= closeTag.length - 1 &&
assistantMessage.startsWith(
closeTag,
currentCharIndex - closeTag.length + 1, // Start checking from potential start of tag
)
) {
// Found the closing tag for the parameter
const value = assistantMessage
.slice(
currentParamValueStart, // Start after the opening tag
currentCharIndex - closeTag.length + 1, // End before the closing tag
)
.trim()
currentToolUse.params[currentParamName] = value
currentParamName = undefined // Go back to parsing tool content
// We don't continue loop here, need to check for tool close or other params at index i
} else {
continue // Still inside param value, move to next char
}
}
// --- State: Parsing a Tool Use (but not a specific parameter) ---
if (currentToolUse && !currentParamName) {
// Ensure we are not inside a parameter already
// Check if starting a new parameter
let startedNewParam = false
for (const [tag, paramName] of toolParamOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
currentParamName = paramName
currentParamValueStart = currentCharIndex + 1 // Value starts after the tag
startedNewParam = true
break
}
}
if (startedNewParam) {
continue // Handled start of param, move to next char
}
// Check if closing the current tool use
const toolCloseTag = `</${currentToolUse.name}>`
if (
currentCharIndex >= toolCloseTag.length - 1 &&
assistantMessage.startsWith(toolCloseTag, currentCharIndex - toolCloseTag.length + 1)
) {
// End of the tool use found
// Special handling for content params *before* finalizing the tool
const toolContentSlice = assistantMessage.slice(
currentToolUseStart, // From after the tool opening tag
currentCharIndex - toolCloseTag.length + 1, // To before the tool closing tag
)
// Check if content parameter needs special handling (write_to_file/new_rule)
// This check is important if the closing </content> tag was missed by the parameter parsing logic
// (e.g., if content is empty or parsing logic prioritizes tool close)
const contentParamName: ToolParamName = "content"
if (
currentToolUse.name === "write_to_file" /* || currentToolUse.name === "new_rule" */ &&
toolContentSlice.includes(`<${contentParamName}>`)
) {
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
const contentStart = toolContentSlice.indexOf(contentStartTag)
// Use lastIndexOf for robustness against nested tags
const contentEnd = toolContentSlice.lastIndexOf(contentEndTag)
if (contentStart !== -1 && contentEnd !== -1 && contentEnd > contentStart) {
const contentValue = toolContentSlice.slice(contentStart + contentStartTag.length, contentEnd).trim()
currentToolUse.params[contentParamName] = contentValue
}
}
currentToolUse.partial = false // Mark as complete
contentBlocks.push(currentToolUse)
currentToolUse = undefined // Reset state
currentTextContentStart = currentCharIndex + 1 // Potential text starts after this tag
continue // Move to next char
}
// If not starting a param and not closing the tool, continue accumulating tool content implicitly
continue
}
// --- State: Parsing Text / Looking for Tool Start ---
if (!currentToolUse) {
// Check if starting a new tool use
let startedNewTool = false
for (const [tag, toolName] of toolUseOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
// End current text block if one was active
if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(
currentTextContentStart, // From where text started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
currentTextContent.partial = false // Ended because tool started
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
} else {
// Check for any text between the last block and this tag
const potentialText = assistantMessage
.slice(
currentTextContentStart, // From where text *might* have started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
if (potentialText.length > 0) {
contentBlocks.push({
type: "text",
content: potentialText,
partial: false,
})
}
}
// Start the new tool use
currentToolUse = {
type: "tool_use",
name: toolName,
params: {},
partial: true, // Assume partial until closing tag is found
}
currentToolUseStart = currentCharIndex + 1 // Tool content starts after the opening tag
startedNewTool = true
break
}
}
if (startedNewTool) {
continue // Handled start of tool, move to next char
}
// If not starting a tool, it must be text content
if (!currentTextContent) {
// Start a new text block if we aren't already in one
currentTextContentStart = currentCharIndex // Text starts at the current character
// Check if the current char is the start of potential text *immediately* after a tag
// This needs the previous state - simpler to let slicing handle it later.
// Resetting start index accurately is key.
// It should be the index *after* the last processed tag.
// The logic managing currentTextContentStart after closing tags handles this.
currentTextContent = {
type: "text",
content: "", // Will be determined by slicing at the end or when a tool starts
partial: true,
}
}
// Continue accumulating text implicitly; content is extracted later.
}
} // End of loop
// --- Finalization after loop ---
// Finalize any open parameter within an open tool use
if (currentToolUse && currentParamName) {
currentToolUse.params[currentParamName] = assistantMessage
.slice(currentParamValueStart) // From param start to end of string
.trim()
// Tool use remains partial
}
// Finalize any open tool use (which might contain the finalized partial param)
if (currentToolUse) {
// Tool use is partial because the loop finished before its closing tag
contentBlocks.push(currentToolUse)
}
// Finalize any trailing text content
// Only possible if a tool use wasn't open at the very end
else if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(currentTextContentStart) // From text start to end of string
.trim()
// Text is partial because the loop finished
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
}
return contentBlocks
}
@@ -0,0 +1,59 @@
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
@@ -0,0 +1,21 @@
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: [] })
}
}
+29 -49
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, Invoke, Platform } from "@shared/ExtensionMessage"
import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { McpDownloadResponse, McpMarketplaceCatalog, McpServer } from "@shared/mcp"
import { TelemetrySetting } from "@shared/TelemetrySetting"
@@ -52,6 +52,8 @@ import {
import { Task, cwd } from "../task"
import { ClineRulesToggles } from "@shared/cline-rules"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendAddToInputEvent } from "./ui/subscribeToAddToInput"
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"
@@ -140,7 +142,7 @@ export class Controller {
await updateGlobalState(this.context, "userInfo", info)
}
async initTask(task?: string, images?: string[], historyItem?: HistoryItem) {
async initTask(task?: string, images?: string[], files?: 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,
@@ -187,6 +189,7 @@ export class Controller {
customInstructions,
task,
images,
files,
historyItem,
)
}
@@ -194,7 +197,7 @@ export class Controller {
async reinitExistingTaskFromId(taskId: string) {
const history = await this.getTaskWithId(taskId)
if (history) {
await this.initTask(undefined, undefined, history.historyItem)
await this.initTask(undefined, undefined, undefined, history.historyItem)
}
}
@@ -262,13 +265,6 @@ export class Controller {
}
})
break
case "showChatView": {
this.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
break
}
case "newTask":
// Code that should run in response to the hello message command
//vscode.window.showInformationMessage(message.text!)
@@ -278,7 +274,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)
await this.initTask(message.text, message.images, message.files)
break
case "apiConfiguration":
if (message.apiConfiguration) {
@@ -290,11 +286,9 @@ export class Controller {
await this.postStateToWebview()
break
case "optionsResponse":
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: message.text,
})
if (this.task) {
await this.task.handleWebviewAskResponse("messageResponse", message.text || "", [])
}
break
case "fetchUserCreditsData": {
await this.fetchUserCreditsData()
@@ -361,15 +355,6 @@ export class Controller {
this.mcpHub?.sendLatestMcpServers()
break
}
case "invoke": {
if (message.text) {
await this.postMessageToWebview({
type: "invoke",
invoke: message.text as Invoke,
})
}
break
}
// telemetry
case "telemetrySetting": {
if (message.telemetrySetting) {
@@ -451,6 +436,13 @@ 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)
@@ -617,12 +609,12 @@ export class Controller {
if (this.task.isAwaitingPlanResponse && didSwitchToActMode) {
this.task.didRespondToPlanAskBySwitchingMode = true
// Use chatContent if provided, otherwise use default message
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
images: chatContent?.images,
})
await this.task.handleWebviewAskResponse(
"messageResponse",
chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
chatContent?.images || [],
chatContent?.files || [],
)
} else {
this.cancelTask()
}
@@ -653,7 +645,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, historyItem) // clears task again, so we need to abortTask manually above
await this.initTask(undefined, 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
}
}
@@ -697,10 +689,7 @@ export class Controller {
await storeSecret(this.context, "clineApiKey", apiKey)
// Send custom token to webview for Firebase auth
await this.postMessageToWebview({
type: "authCallback",
customToken,
})
await sendAuthCallbackEvent(customToken)
const clineProvider: ApiProvider = "cline"
await updateGlobalState(this.context, "apiProvider", clineProvider)
@@ -934,10 +923,7 @@ export class Controller {
input += `\nProblems:\n${problemsString}`
}
await this.postMessageToWebview({
type: "addToInput",
text: input,
})
await sendAddToInputEvent(input)
console.log("addSelectedCodeToChat", code, filePath, languageId)
}
@@ -955,10 +941,7 @@ export class Controller {
// terminalName
// })
await this.postMessageToWebview({
type: "addToInput",
text: `Terminal output:\n\`\`\`\n${output}\n\`\`\``,
})
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${output}\n\`\`\``)
console.log("addSelectedTerminalOutputToChat", output, terminalName)
}
@@ -1047,7 +1030,7 @@ export class Controller {
if (id !== this.task?.taskId) {
// non-current task
const { historyItem } = await this.getTaskWithId(id)
await this.initTask(undefined, undefined, historyItem) // clears existing task
await this.initTask(undefined, undefined, undefined, historyItem) // clears existing task
}
await this.postMessageToWebview({
type: "action",
@@ -1178,10 +1161,7 @@ export class Controller {
async postStateToWebview() {
const state = await this.getStateToPostToWebview()
// 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
await sendStateUpdate(state)
}
async getStateToPostToWebview(): Promise<ExtensionState> {
+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)
await controller.task.handleWebviewAskResponse(responseType, request.text, request.images, request.files)
return Empty.create()
} catch (error) {
+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)
await controller.initTask(request.text, request.images, request.files)
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, historyItem)
await controller.initTask(undefined, 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, fetchedItem)
await controller.initTask(undefined, undefined, undefined, fetchedItem)
// Send UI update to show the chat view
await controller.postMessageToWebview({
@@ -0,0 +1,64 @@
import * as vscode from "vscode"
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 addToInput subscriptions
const activeAddToInputSubscriptions = new Set<StreamingResponseHandler>()
/**
* Subscribe to addToInput 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 subscribeToAddToInput(
controller: Controller,
request: EmptyRequest,
responseStream: StreamingResponseHandler,
requestId?: string,
): Promise<void> {
console.log("[DEBUG] set up addToInput subscription")
// Add this subscription to the active subscriptions
activeAddToInputSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeAddToInputSubscriptions.delete(responseStream)
console.log("[DEBUG] Cleaned up addToInput subscription")
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "addToInput_subscription" }, responseStream)
}
}
/**
* Send an addToInput event to all active subscribers
* @param text The text to add to the input
*/
export async function sendAddToInputEvent(text: string): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeAddToInputSubscriptions).map(async (responseStream) => {
try {
const event: ProtoString = {
value: text,
}
await responseStream(
event,
false, // Not the last message
)
console.log("[DEBUG] sending addToInput event", text.length, "chars")
} catch (error) {
console.error("Error sending addToInput event:", error)
// Remove the subscription if there was an error
activeAddToInputSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
+600
View File
@@ -0,0 +1,600 @@
import { getShell } from "@utils/shell"
import os from "os"
import osName from "os-name"
import { McpHub } from "@services/mcp/McpHub"
import { BrowserSettings } from "@shared/BrowserSettings"
import { createAntmlToolPrompt, createSimpleXmlToolPrompt, toolDefinitionToSimpleXml } from "@core/prompts/model_prompts/jsonToolToXml"
import { bashToolDefinition } from "@core/tools/bashTool"
import { readToolDefinition } from "@core/tools/readTool"
import { writeToolDefinition } from "@core/tools/writeTool"
import {lsToolDefinition} from "@core/tools/lsTool"
import { grepToolDefinition } from "@/core/tools/grepTool"
export const SYSTEM_PROMPT_CLAUDE4 = async (
cwd: string,
supportsBrowserUse: boolean,
mcpHub: McpHub,
browserSettings: BrowserSettings,
) => {
const bashTool = bashToolDefinition(cwd);
const systemPrompt = `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
TOOL USE
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
# Tool Use Formatting
Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
<tool_name>
<parameter1_name>value1</parameter1_name>
<parameter2_name>value2</parameter2_name>
...
</tool_name>
For example:
<read_file>
<path>src/main.js</path>
</read_file>
Always adhere to this format for the tool use to ensure proper parsing and execution.
# Tools
## read_file
Description: Request to read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file you do not know the contents of, for example to analyze code, review text files, or extract information from configuration files. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string.
Parameters:
- path: (required) The path of the file to read (relative to the current working directory ${cwd.toPosix()})
Usage:
<read_file>
<path>File path here</path>
</read_file>
## write_to_file
Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory ${cwd.toPosix()})
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
Usage:
<write_to_file>
<path>File path here</path>
<content>
Your file content here
</content>
</write_to_file>
## replace_in_file
"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>
## list_code_definition_names
Description: Request to list definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.
Parameters:
- path: (required) The path of the directory (relative to the current working directory ${cwd.toPosix()}) to list top level source code definitions for.
Usage:
<list_code_definition_names>
<path>Directory path here</path>
</list_code_definition_names>${
supportsBrowserUse
? `
## browser_action
Description: Request to interact with a Puppeteer-controlled browser. Every action, except \`close\`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action.
- The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL.
- While the browser is active, only the \`browser_action\` tool can be used. No other tools should be called during this time. You may proceed to use other tools only after closing the browser. For example if you run into an error and need to fix a file, you must close the browser, then use other tools to make the necessary changes, then re-launch the browser to verify the result.
- The browser window has a resolution of **${browserSettings.viewport.width}x${browserSettings.viewport.height}** pixels. When performing any click actions, ensure the coordinates are within this resolution range.
- Before clicking on any elements such as icons, links, or buttons, you must consult the provided screenshot of the page to determine the coordinates of the element. The click should be targeted at the **center of the element**, not on its edges.
Parameters:
- action: (required) The action to perform. The available actions are:
* launch: Launch a new Puppeteer-controlled browser instance at the specified URL. This **must always be the first action**.
- Use with the \`url\` parameter to provide the URL.
- Ensure the URL is valid and includes the appropriate protocol (e.g. http://localhost:3000/page, file:///path/to/file.html, etc.)
* click: Click at a specific x,y coordinate.
- Use with the \`coordinate\` parameter to specify the location.
- Always click in the center of an element (icon, button, link, etc.) based on coordinates derived from a screenshot.
* type: Type a string of text on the keyboard. You might use this after clicking on a text field to input text.
- Use with the \`text\` parameter to provide the string to type.
* scroll_down: Scroll down the page by one page height.
* scroll_up: Scroll up the page by one page height.
* close: Close the Puppeteer-controlled browser instance. This **must always be the final browser action**.
- Example: \`<action>close</action>\`
- url: (optional) Use this for providing the URL for the \`launch\` action.
* Example: <url>https://example.com</url>
- coordinate: (optional) The X and Y coordinates for the \`click\` action. Coordinates should be within the **${browserSettings.viewport.width}x${browserSettings.viewport.height}** resolution.
* Example: <coordinate>450,300</coordinate>
- text: (optional) Use this for providing the text for the \`type\` action.
* Example: <text>Hello, world!</text>
Usage:
<browser_action>
<action>Action to perform (e.g., launch, click, type, scroll_down, scroll_up, close)</action>
<url>URL to launch the browser at (optional)</url>
<coordinate>x,y coordinates (optional)</coordinate>
<text>Text to type (optional)</text>
</browser_action>`
: ""
}
## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
- server_name: (required) The name of the MCP server providing the tool
- tool_name: (required) The name of the tool to execute
- arguments: (required) A JSON object containing the tool's input parameters, following the tool's input schema
Usage:
<use_mcp_tool>
<server_name>server name here</server_name>
<tool_name>tool name here</tool_name>
<arguments>
{
"param1": "value1",
"param2": "value2"
}
</arguments>
</use_mcp_tool>
## access_mcp_resource
Description: Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.
Parameters:
- server_name: (required) The name of the MCP server providing the resource
- uri: (required) The URI identifying the specific resource to access
Usage:
<access_mcp_resource>
<server_name>server name here</server_name>
<uri>resource URI here</uri>
</access_mcp_resource>
## ask_followup_question
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
Parameters:
- question: (required) The question to ask the user. This should be a clear, specific question that addresses the information you need.
- options: (optional) An array of 2-5 options for the user to choose from. Each option should be a string describing a possible answer. You may not always need to provide options, but it may be helpful in many cases where it can save the user from having to type out a response manually. IMPORTANT: NEVER include an option to toggle to Act mode, as this would be something you need to direct the user to do manually themselves if needed.
Usage:
<ask_followup_question>
<question>Your question here</question>
<options>
Array of options here (optional), e.g. ["Option 1", "Option 2", "Option 3"]
</options>
</ask_followup_question>
## attempt_completion
Description: After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in <thinking></thinking> tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool.
Parameters:
- result: (required) The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.
- command: (optional) A CLI command to execute to show a live demo of the result to the user. For example, use \`open index.html\` to display a created html website, or \`open localhost:3000\` to display a locally running development server. But DO NOT use commands like \`echo\` or \`cat\` that merely print text. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
Usage:
<attempt_completion>
<result>
Your final result description here
</result>
<command>Command to demonstrate result (optional)</command>
</attempt_completion>
## new_task
Description: Request to create a new task with preloaded context covering the conversation with the user up to this point and key information for continuing with the new task. With this tool, you will create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions, with a focus on the most relevant information required for the new task.
Among other important areas of focus, this summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing with the new task. The user will be presented with a preview of your generated context and can choose to create a new task or keep chatting in the current conversation. The user may choose to start a new task at any point.
Parameters:
- Context: (required) The context to preload the new task with. If applicable based on the current task, this should include:
1. Current Work: Describe in detail what was being worked on prior to this request to create a new task. Pay special attention to the more recent messages / conversation.
2. Key Technical Concepts: List all important technical concepts, technologies, coding conventions, and frameworks discussed, which might be relevant for the new task.
3. Relevant Files and Code: If applicable, enumerate specific files and code sections examined, modified, or created for the task continuation. Pay special attention to the most recent messages and changes.
4. Problem Solving: Document problems solved thus far and any ongoing troubleshooting efforts.
5. Pending Tasks and Next Steps: Outline all pending tasks that you have explicitly been asked to work on, as well as list the next steps you will take for all outstanding work, if applicable. Include code snippets where they add clarity. For any next steps, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no information loss in context between tasks. It's important to be detailed here.
Usage:
<new_task>
<context>context to preload new task with</context>
</new_task>
## plan_mode_respond
Description: Respond to the user's inquiry in an effort to plan a solution to the user's task. This tool should be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. This tool is only available in PLAN MODE. The environment_details will specify the current mode, if it is not PLAN MODE then you should not use this tool. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.
Parameters:
- response: (required) The response to provide to the user. Do not try to use tools in this parameter, this is simply a chat response. (You MUST use the response parameter, do not simply place the response text directly within <plan_mode_respond> tags.)
Usage:
<plan_mode_respond>
<response>Your response here</response>
</plan_mode_respond>
## load_mcp_documentation
Description: Load documentation about creating MCP servers. This tool should be used when the user requests to create or install an MCP server (the user may ask you something along the lines of "add a tool" that does some function, in other words to create an MCP server that provides tools and resources that may connect to external APIs for example. You have the ability to create an MCP server and add it to a configuration file that will then expose the tools and resources for you to use with \`use_mcp_tool\` and \`access_mcp_resource\`). The documentation provides detailed information about the MCP server creation process, including setup instructions, best practices, and examples.
Parameters: None
Usage:
<load_mcp_documentation>
</load_mcp_documentation>
# Tool Use Examples
## Example 1: Requesting to create a new file
<write_to_file>
<path>src/frontend-config.json</path>
<content>
{
"apiEndpoint": "https://api.example.com",
"theme": {
"primaryColor": "#007bff",
"secondaryColor": "#6c757d",
"fontFamily": "Arial, sans-serif"
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": false
},
"version": "1.0.0"
}
</content>
</write_to_file>
## Example 2: Creating a new task
<new_task>
<context>
1. Current Work:
[Detailed description]
2. Key Technical Concepts:
- [Concept 1]
- [Concept 2]
- [...]
3. Relevant Files and Code:
- [File Name 1]
- [Summary of why this file is important]
- [Summary of the changes made to this file, if any]
- [Important Code Snippet]
- [File Name 2]
- [Important Code Snippet]
- [...]
4. Problem Solving:
[Detailed description]
5. Pending Tasks and Next Steps:
- [Task 1 details & next steps]
- [Task 2 details & next steps]
- [...]
</context>
</new_task>
## Example 3: Requesting to make targeted edits to a file
<replace_in_file>
<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>
## Example 4: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 5: Another example of using an MCP tool (where the server name is a unique identifier such as a URL)
<use_mcp_tool>
<server_name>github.com/modelcontextprotocol/servers/tree/main/src/github</server_name>
<tool_name>create_issue</tool_name>
<arguments>
{
"owner": "octocat",
"repo": "hello-world",
"title": "Found a bug",
"body": "I'm having a problem with this.",
"labels": ["bug", "help wanted"],
"assignees": ["octocat"]
}
</arguments>
</use_mcp_tool>
# Tool Use Guidelines
1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. It's critical that you think about each available tool and use the one that best fits the current step in the task.
3. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively, with each tool use being informed by the result of the previous tool use. Do not assume the outcome of any tool use. Each step must be informed by the previous step's result.
4. Formulate your tool use using the XML format specified for each tool.
5. After each tool use, the user will respond with the result of that tool use. This result will provide you with the necessary information to continue your task or make further decisions. This response may include:
- Information about whether the tool succeeded or failed, along with any reasons for failure.
- Linter errors that may have arisen due to the changes you made, which you'll need to address.
- New terminal output in reaction to the changes, which you may need to consider or act upon.
- Any other relevant feedback or information related to the tool use.
6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user.
It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to:
1. Confirm the success of each step before proceeding.
2. Address any issues or errors that arise immediately.
3. Adapt your approach based on new information or unexpected results.
4. Ensure that each action builds correctly on the previous ones.
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
====
MCP SERVERS
The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
# Connected MCP Servers
When a server is connected, you can use the server's tools via the \`use_mcp_tool\` tool, and access the server's resources via the \`access_mcp_resource\` tool.
${
mcpHub.getServers().length > 0
? `${mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => {
const tools = server.tools
?.map((tool) => {
const schemaStr = tool.inputSchema
? ` Input Schema:
${JSON.stringify(tool.inputSchema, null, 2).split("\n").join("\n ")}`
: ""
return `- ${tool.name}: ${tool.description}\n${schemaStr}`
})
.join("\n\n")
const templates = server.resourceTemplates
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
.join("\n")
const resources = server.resources
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
.join("\n")
const config = JSON.parse(server.config)
return (
`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
(tools ? `\n\n### Available Tools\n${tools}` : "") +
(templates ? `\n\n### Resource Templates\n${templates}` : "") +
(resources ? `\n\n### Direct Resources\n${resources}` : "")
)
})
.join("\n\n")}`
: "(No MCP servers currently connected)"
}
====
EDITING FILES
You have access to two tools for working with files: **write_to_file** and **replace_in_file**. Understanding their roles and selecting the right one for the job will help ensure efficient and accurate modifications.
# write_to_file
## Purpose
- Create a new file, or overwrite the entire contents of an existing file.
## When to Use
- Initial file creation, such as when scaffolding a new project.
- Overwriting large boilerplate files where you want to replace the entire content at once.
- When the complexity or number of changes would make replace_in_file unwieldy or error-prone.
- When you need to completely restructure a file's content or change its fundamental organization.
## Important Considerations
- Using write_to_file requires providing the file's complete final content.
- If you only need to make small changes to an existing file, consider using replace_in_file instead to avoid unnecessarily rewriting the entire file.
- While write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
# replace_in_file
## Purpose
- Make targeted edits to specific parts of an existing file without overwriting the entire file.
## When to Use
- Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
- Targeted improvements where only specific portions of the file's content needs to be altered.
- Especially useful for long files where much of the file will remain unchanged.
## Advantages
- More efficient for minor edits, since you don't need to supply the entire file content.
- Reduces the chance of errors that can occur when overwriting large files.
# Choosing the Appropriate Tool
- **Default to replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
- **Use write_to_file** when:
- Creating new files
- The changes are so extensive that using replace_in_file would be more complex or risky
- You need to completely reorganize or restructure a file
- The file is relatively small and the changes affect most of its content
- You're generating boilerplate or template files
# Auto-formatting Considerations
- After using either write_to_file or replace_in_file, the user's editor may automatically format the file
- This auto-formatting may modify the file contents, for example:
- Breaking single lines into multiple lines
- Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
- Converting single quotes to double quotes (or vice versa based on project preferences)
- Organizing imports (e.g. sorting, grouping by type)
- Adding/removing trailing commas in objects and arrays
- Enforcing consistent brace style (e.g. same-line vs new-line)
- Standardizing semicolon usage (adding or removing based on style)
- The write_to_file and replace_in_file tool responses will include the final state of the file after any auto-formatting
- Use this final state as your reference point for any subsequent edits. This is ESPECIALLY important when crafting SEARCH blocks for replace_in_file which require the content to match what's in the file exactly.
# Workflow Tips
1. Before editing, assess the scope of your changes and decide which tool to use.
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
6. Do not make more than 4 replacements in a single replace_in_file call, as this can lead to errors and make it difficult to track changes. If you need to make more than 4 changes, consider breaking them into multiple replace_in_file calls.
7. Make sure a single old_str in a replace_in_file call is no more than 4 lines, as too many lines can lead to errors. If you need to replace a larger section, break it into smaller blocks.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
ACT MODE V.S. PLAN MODE
In each user message, the environment_details will specify the current mode. There are two modes:
- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
- In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
- In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
- In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly, rather than using <thinking> tags to analyze when to respond. Do not talk about using plan_mode_respond - just use it directly to share your thoughts and provide helpful answers.
## What is PLAN MODE?
- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or ${grepToolDefinition.name} to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well.
- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.)
- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
====
CAPABILITIES
- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search${
supportsBrowserUse ? ", use the browser" : ""
}, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd.toPosix()}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
- You can use ${grepToolDefinition.name} to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use ${grepToolDefinition.name} to ensure you update other files as needed.
- You can use the ${bashTool.name} tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
supportsBrowserUse
? `\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use the ${bashTool.name} tool to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser.`
: ""
}
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
- You can use LaTeX syntax in your responses to render mathematical expressions
====
RULES
- Your current working directory is: ${cwd.toPosix()}
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '${cwd.toPosix()}', so be sure to pass in the correct 'path' parameter when using tools that require a path.
- Do not use the ~ character or $HOME to refer to the home directory.
- Before using the ${bashTool.name} tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the ${grepToolDefinition.name} tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the ${grepToolDefinition.name} tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using replace_in_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when creating files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- When you want to modify a file, use the replace_in_file or write_to_file tool directly with the desired changes. You do not need to display the changes before using the tool.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the ${lsToolDefinition.name} tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ask_followup_question tool to request the user to copy and paste it back to you.
- The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
supportsBrowserUse
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.`
: ""
}
- NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
- You are STRICTLY FORBIDDEN from starting your messages with "Great", "Certainly", "Okay", "Sure". You should NOT be conversational in your responses, but rather direct and to the point. For example you should NOT say "Great, I've updated the CSS" but instead something like "I've updated the CSS". It is important you be clear and technical in your messages.
- 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.
- When using the replace_in_file tool, you must include complete lines
- 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."
: ""
}
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
====
SYSTEM INFORMATION
Operating System: ${osName()}
Default Shell: ${getShell()}
Home Directory: ${os.homedir().toPosix()}
Current Working Directory: ${cwd.toPosix()}
====
OBJECTIVE
You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
return createAntmlToolPrompt([bashToolDefinition(cwd), lsToolDefinition, grepToolDefinition], true, systemPrompt);
}
@@ -0,0 +1,283 @@
function escapeXml(text: string): string {
// Anything that could be interpreted as markup has to be entity-encoded
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
}
export interface ToolDefinition {
name: string
description?: string
descriptionForAgent?: string
inputSchema: {
type: string
properties: Record<string, any>
required?: string[]
[key: string]: any
}
}
/**
* Converts a single tool definition (JSON schema) to the <function> tag format.
* This is for *defining* the tool, not calling it.
* @param toolDef The tool definition object
* @returns The tool definition as a JSON string wrapped in <function> tags
*/
export function toolDefinitionToAntmlDefinition(toolDef: ToolDefinition): string {
// Restructure the parameters object to match the expected order
const { type, properties, required, ...rest } = toolDef.inputSchema
const parameters = {
properties,
required,
type,
...rest,
}
const functionDef = {
description: toolDef.descriptionForAgent || toolDef.description || "",
name: toolDef.name,
parameters,
}
// 1. Create a custom JSON string with the exact format we want
let rawJson = `{"description": "${functionDef.description}", "name": "${functionDef.name}", "parameters": {`
// Add properties
rawJson += `"properties": {`
const propEntries = Object.entries(parameters.properties)
propEntries.forEach(([propName, propDef], index) => {
rawJson += `"${propName}": {`
rawJson += `"description": "${(propDef as any).description || ""}", `
rawJson += `"type": "${(propDef as any).type || "string"}"`
rawJson += `}`
if (index < propEntries.length - 1) {
rawJson += ", "
}
})
rawJson += `}, `
// Add required
rawJson += `"required": ${JSON.stringify(parameters.required || [])}, `
// Add type
rawJson += `"type": "object"`
// Close parameters and the whole object
rawJson += `}}`
// 2. Escape <, > and & so the JSON can sit INSIDE the XML tag safely.
// (Quotes dont need escaping - theyre not markup.)
const safeJson = escapeXml(rawJson)
// 3. Return wrapped in <function> tags
return `<function>${safeJson}</function>`
}
/**
* Converts multiple tool definitions to the complete <functions> block.
* This is for *defining* the tools.
* @param toolDefs Array of tool definition objects
* @returns Complete <functions> block with all tool definitions
*/
export function toolDefinitionsToAntmlDefinitions(toolDefs: ToolDefinition[]): string {
const functionTags = toolDefs.map(toolDefinitionToAntmlDefinition)
return `Here are the functions available in JSONSchema format:
<functions>
${functionTags.join("\n")}
</functions>`
}
/**
* Creates an example of an ANTML tool call for a given tool definition.
* This is for *calling* a tool.
* @param toolDef The tool definition object
* @param exampleValues Optional example values for parameters
* @returns Example ANTML function call string
*/
export function toolDefinitionToAntmlCallExample(toolDef: ToolDefinition, exampleValues: Record<string, any> = {}): string {
const props = toolDef.inputSchema.properties ?? {}
const paramLines = Object.keys(props).length
? Object.entries(props)
.map(([name]) => {
const value = exampleValues[name] ?? `$${name.toUpperCase()}` // placeholder
// Don't escape XML here - the example should show raw format
return `<parameter name="${name}">${value}</parameter>`
})
.join("\n")
: ""
// Only include one invoke block
return ["<function_calls>", `<invoke name="${toolDef.name}">`, paramLines, "</invoke>", "</function_calls>"]
.filter(Boolean)
.join("\n")
}
/**
* Creates a complete system prompt section for tools in ANTML format,
* including instructions and tool definitions.
* @param toolDefs Array of tool definition objects
* @param includeInstructions Whether to include the standard tool calling instructions
* @returns Complete system prompt section for ANTML tools
*/
export function createAntmlToolPrompt(toolDefs: ToolDefinition[], includeInstructions = true, systemPrompt = ""): string {
if (toolDefs.length === 0) {
if (!includeInstructions) {
return ""
}
const noToolsMessage = [
"In this environment you have access to a set of tools you can use to answer the user's question.",
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
"<function_calls>",
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
"...",
"</invoke>",
"</function_calls>",
"",
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
"",
"However, no tools are currently available.",
].join("\n")
return noToolsMessage
}
let prompt = ""
if (includeInstructions) {
const instructionLines = [
"In this environment you have access to a set of tools you can use to answer the user's question.",
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
"<function_calls>",
'<invoke name="$FUNCTION_NAME">',
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
"...",
"</invoke>",
"</function_calls>",
"",
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
"",
]
prompt += instructionLines.join("\n")
}
prompt += toolDefinitionsToAntmlDefinitions(toolDefs)
if (includeInstructions) {
const closingInstructions = [
"",
"",
systemPrompt,
"",
"",
"Answer the user's request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.",
]
prompt += closingInstructions.join("\n")
}
return prompt // Don't trim - preserve exact formatting
}
// --- SimpleXML Functions (Cline's internal format) ---
/**
* Converts a single tool definition to the SimpleXML format
* as used by Cline's current system prompts for non-ANTML models.
* @param toolDef The tool definition object
* @returns The tool definition formatted for SimpleXML usage
*/
export function toolDefinitionToSimpleXml(toolDef: ToolDefinition): string {
const description = toolDef.descriptionForAgent || toolDef.description || ""
const properties = toolDef.inputSchema.properties || {}
const required = toolDef.inputSchema.required || []
let parameterDocs = ""
if (Object.keys(properties).length > 0) {
parameterDocs = "Parameters:\n"
for (const [paramName, paramDef] of Object.entries(properties)) {
const isRequired = required.includes(paramName)
const requiredText = isRequired ? "(required)" : "(optional)"
const paramDescription = (paramDef as any).description || "No description."
parameterDocs += `- ${paramName}: ${requiredText} ${paramDescription}\n`
}
}
const exampleParams = Object.keys(properties)
.map((paramName) => `<${paramName}>${paramName} value here</${paramName}>`)
.join("\n")
const usageExample = `Usage:
<${toolDef.name}>
${exampleParams.length > 0 ? exampleParams + "\n" : ""}</${toolDef.name}>`
return `## ${toolDef.name}
Description: ${description}
${parameterDocs.trim()}
${usageExample}`
}
/**
* Converts multiple tool definitions to the complete SimpleXML format.
* @param toolDefs Array of tool definition objects
* @returns Complete tools documentation in SimpleXML format
*/
export function toolDefinitionsToSimpleXml(toolDefs: ToolDefinition[]): string {
const toolDocs = toolDefs.map((toolDef) => toolDefinitionToSimpleXml(toolDef))
return `# Tools
${toolDocs.join("\n\n")}`
}
/**
* Creates a complete system prompt section for tools in SimpleXML format.
* @param toolDefs Array of tool definition objects
* @param includeInstructions Whether to include the standard tool calling instructions
* @returns Complete system prompt section for SimpleXML tools
*/
export function createSimpleXmlToolPrompt(toolDefs: ToolDefinition[], includeInstructions: boolean = true): string {
if (toolDefs.length === 0) {
return ""
}
let prompt = ""
if (includeInstructions) {
prompt += `TOOL USE
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
# Tool Use Formatting
Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
<tool_name>
<parameter1_name>value1</parameter1_name>
<parameter2_name>value2</parameter2_name>
...
</tool_name>
For example:
<read_file>
<path>src/main.js</path>
</read_file>
Always adhere to this format for the tool use to ensure proper parsing and execution.
`
}
prompt += toolDefinitionsToSimpleXml(toolDefs)
if (includeInstructions) {
prompt += `
# Tool Use Guidelines
1. Choose the most appropriate tool based on the task and the tool descriptions provided.
2. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively.
3. Formulate your tool use using the XML format specified for each tool.
4. After each tool use, the user will respond with the result of that tool use.
5. ALWAYS wait for user confirmation after each tool use before proceeding.`
}
return prompt.trimEnd()
}
+23 -7
View File
@@ -41,15 +41,31 @@ 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[]): 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 {
toolResult: (
text: string,
images?: string[],
fileString?: string,
): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
let toolResultOutput = []
if (!(images && images.length > 0) && !fileString) {
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[] => {
+12 -3
View File
@@ -3,13 +3,19 @@ import os from "os"
import osName from "os-name"
import { McpHub } from "@services/mcp/McpHub"
import { BrowserSettings } from "@shared/BrowserSettings"
import { SYSTEM_PROMPT_CLAUDE4 } from "./model_prompts/claude4"
export const SYSTEM_PROMPT = async (
cwd: string,
supportsBrowserUse: boolean,
mcpHub: McpHub,
browserSettings: BrowserSettings,
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
isClaude4ModelFamily: boolean = false,
) => {
if (isClaude4ModelFamily) {
return SYSTEM_PROMPT_CLAUDE4(cwd, supportsBrowserUse, mcpHub, browserSettings)
} else {
return `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
@@ -103,9 +109,10 @@ Usage:
<path>File path here</path>
<diff>
Search and replace blocks here
</diff>
</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.
Parameters:
@@ -361,6 +368,7 @@ return (
</diff>
</replace_in_file>
## Example 5: Requesting to use an MCP tool
<use_mcp_tool>
@@ -532,7 +540,6 @@ You have access to two tools for working with files: **write_to_file** and **rep
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.
====
@@ -632,6 +639,8 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
}
}
export function addUserInstructions(
settingsCustomInstructions?: string,
+1
View File
@@ -21,6 +21,7 @@ export type SecretKey =
| "xaiApiKey"
| "nebiusApiKey"
| "sambanovaApiKey"
| "cerebrasApiKey"
export type GlobalStateKey =
| "apiProvider"
+6
View File
@@ -155,6 +155,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
thinkingBudgetTokens,
reasoningEffort,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
planActSeparateModelsSettingRaw,
favoritedModelIds,
@@ -244,6 +245,7 @@ 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>,
@@ -357,6 +359,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
asksageApiUrl,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
favoritedModelIds,
requestTimeoutMs,
@@ -451,6 +454,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
reasoningEffort,
clineApiKey,
sambanovaApiKey,
cerebrasApiKey,
nebiusApiKey,
favoritedModelIds,
} = apiConfiguration
@@ -512,6 +516,7 @@ 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)
@@ -542,6 +547,7 @@ export async function resetExtensionState(context: vscode.ExtensionContext) {
"asksageApiKey",
"xaiApiKey",
"sambanovaApiKey",
"cerebrasApiKey",
"nebiusApiKey",
]
for (const key of secretKeys) {
+460 -141
View File
File diff suppressed because it is too large Load Diff
+126
View File
@@ -0,0 +1,126 @@
export const bashToolName = "Bash"
const CO_AUTHORED_COMMIT_MSG = `\uD83E\uDD16 Generated with [Cline](https://docs.cline.bot)
Co-Authored-By: Cline <noreply@cline.bot>`
const CO_AUTHORED_PR_MSG = `\uD83E\uDD16 Generated with [Cline](https://docs.cline.bot)`
const descriptionForAgent = (
cwd: string,
) => `Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${cwd.toPosix()}.
# Committing changes with git
When the user asks you to create a new git commit, follow these steps carefully:
1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel, each using the Bash tool:
- Run a git status command to see all untracked files.
- Run a git diff command to see both staged and unstaged changes that will be committed.
- Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
2. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
<commit_analysis>
- List the files that have been changed or added
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
- Brainstorm the purpose or motivation behind these changes
- Assess the impact of these changes on the overall project
- Check for any sensitive information that shouldn't be committed
- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
- Ensure your language is clear, concise, and to the point
- Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
- Review the draft message to ensure it accurately reflects the changes and their purpose
</commit_analysis>
3. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
Important notes:
- Use the git context at the start of this conversation to determine which files are relevant to your commit. Be careful not to stage and commit files (e.g. with \\\`git add .\\\`) that aren't relevant to your commit.
- NEVER update the git config
- DO NOT run additional commands to read or explore code, beyond what is available in the git context
- DO NOT push to the remote repository
- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
- Return an empty response - the user will see the git output directly
- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
<example>
git commit -m "\$(cat <<'EOF'
Commit message here.
\${CO_AUTHORED_COMMIT_MSG}
EOF
)"
</example>
# Creating pull requests
Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
1. Gather information
- Run a git status command to see all untracked files
- Run a git diff command to see both staged and unstaged changes that will be committed
- Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
- Run a git log command and \\\`git diff main...HEAD\\\` to understand the full commit history for the current branch (from the time it diverged from the \\\`main\\\` branch)
2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary. Wrap your analysis process in <pr_analysis> tags:
<pr_analysis>
- List the commits since diverging from the main branch
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
- Brainstorm the purpose or motivation behind these changes
- Assess the impact of these changes on the overall project
- Do not use tools to explore code, beyond what is available in the git context
- Check for any sensitive information that shouldn't be committed
- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
- Ensure the summary accurately reflects all changes since diverging from the main branch
- Ensure your language is clear, concise, and to the point
- Ensure the summary accurately reflects the changes and their purpose (ie. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
- Review the draft summary to ensure it accurately reflects the changes and their purpose
</pr_analysis>
<example>
gh pr create \
--title "the pr title" \
--body "$(cat <<'EOF'
## Summary
<1-3 bullet points>
## Test plan
[Checklist of TODOs for testing the pull request...]
${CO_AUTHORED_PR_MSG}
EOF
)"
</example>
Important:
- NEVER update the git config
- Return the PR URL when you're done, so the user can see it
# Other common operations
- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments`
export const bashToolDefinition = (cwd: string) => ({
name: bashToolName,
descriptionForAgent: descriptionForAgent(cwd),
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description:
"The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.",
},
requires_approval: {
type: "boolean",
description:
"A boolean indicating whether this command requires explicit user approval before execution in case the user has auto-approve mode enabled. Set to 'true' for potentially impactful operations like installing/uninstalling packages, deleting/overwriting files, system configuration changes, network operations, or any commands that could have unintended side effects. Set to 'false' for safe operations like reading files/directories, running development servers, building projects, and other non-destructive operations.",
},
},
required: ["command", "requires_approval"],
},
})
+29
View File
@@ -0,0 +1,29 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const grepToolDefinition: ToolDefinition = {
name: "Grep",
descriptionForAgent: `- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\\\\s+\\\\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths with at least one match
- Use this tool when you need to find files containing specific patterns`,
inputSchema: {
type: "object",
properties: {
pattern: {
type: "string",
description: "The regular expression pattern to search for in file contents",
},
path: {
type: "string",
description: "The directory to search in.",
},
include: {
type: "string",
description: "File pattern to filter which files to search (e.g., '*.js' for JavaScript files)",
},
},
required: ["pattern", "path"],
},
}
+17
View File
@@ -0,0 +1,17 @@
import { ToolDefinition } from "@core/prompts/model_prompts/jsonToolToXml"
export const lsToolDefinition: ToolDefinition = {
name: "LS",
descriptionForAgent:
"Lists files and directories in a given path. The path parameter must be an absolute path, not a relative path. You should generally prefer the Glob and Grep tools, if you know which directories to search.",
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: "The path of the directory to list contents for",
},
},
required: ["path"],
},
}
+41
View File
@@ -0,0 +1,41 @@
const DEFAULT_LINE_LIMIT = 2000
const MAX_LINE_LENGTH = 2000
const descriptionForAgent = `Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
Usage:
- The file_path parameter must be an absolute path, not a relative path
- By default, it reads up to ${DEFAULT_LINE_LIMIT} lines starting from the beginning of the file
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
- Any lines longer than ${MAX_LINE_LENGTH} characters will be truncated
- Results are returned using cat -n format, with line numbers starting at 1
- This tool allows Cline to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Cline is a multimodal LLM.
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/Temporary_Screenshots/2026-09-08/Screenshot.png
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`
export const readToolDefinition = {
name: "Read",
descriptionForAgent: descriptionForAgent,
inputSchema: {
type: "object",
properties: {
file_path: {
type: "string",
description: "The absolute path to the file to read",
},
offset: {
type: "number",
description: "The line number to start reading from. Only provide if the file is too large to read at once",
optional: true,
},
limit: {
type: "number",
description: "The number of lines to read. Only provide if the file is too large to read at once.",
optional: true,
},
},
required: ["file_path"],
},
}
+27
View File
@@ -0,0 +1,27 @@
const descriptionForAgent = `Writes a file to the local filesystem.
Usage:
- The file_path parameter must be an absolute path, not a relative path
- This tool will overwrite the existing file if there is one at the provided path.
- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.`
export const writeToolDefinition = {
name: "Write",
descriptionForAgent: descriptionForAgent,
inputSchema: {
type: "object",
properties: {
file_path: {
type: "string",
description: "The absolute path to the file to write (must be absolute, not relative)",
},
content: {
type: "string",
description: "The content to write to the file",
},
},
required: ["file_path", "content"],
},
}
+285
View File
@@ -0,0 +1,285 @@
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")
}
})
})
})
+16 -20
View File
@@ -22,12 +22,7 @@ export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarContr
type: "action",
action: "chatButtonClicked",
})
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: task,
images: images,
})
await sidebarController.initTask(task, images)
outputChannel.appendLine(
`Task started with message: ${task ? `"${task}"` : "undefined"} and ${images?.length || 0} image(s)`,
)
@@ -37,28 +32,29 @@ export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarContr
outputChannel.appendLine(
`Sending message: ${message ? `"${message}"` : "undefined"} with ${images?.length || 0} image(s)`,
)
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: message,
images: images,
})
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("messageResponse", message || "", images || [])
} else {
outputChannel.appendLine("No active task to send message to")
}
},
pressPrimaryButton: async () => {
outputChannel.appendLine("Pressing primary button")
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "primaryButtonClick",
})
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("yesButtonClicked", "", [])
} else {
outputChannel.appendLine("No active task to press button for")
}
},
pressSecondaryButton: async () => {
outputChannel.appendLine("Pressing secondary button")
await sidebarController.postMessageToWebview({
type: "invoke",
invoke: "secondaryButtonClick",
})
if (sidebarController.task) {
await sidebarController.task.handleWebviewAskResponse("noButtonClicked", "", [])
} else {
outputChannel.appendLine("No active task to press button for")
}
},
}
+31 -20
View File
@@ -101,7 +101,11 @@ export class DiffViewProvider {
})
}
async update(accumulatedContent: string, isFinal: boolean) {
async update(
accumulatedContent: string,
isFinal: boolean,
changeLocation?: { startLine: number; endLine: number; startChar: number; endChar: number },
) {
if (!this.relPath || !this.activeLineController || !this.fadedOverlayController) {
throw new Error("Required values not set")
}
@@ -148,29 +152,36 @@ export class DiffViewProvider {
this.activeLineController.setActiveLine(currentLine)
this.fadedOverlayController.updateOverlayAfterLine(currentLine, document.lineCount)
// Scroll to the last changed line only if the user hasn't scrolled up
// Scroll to the actual change location if provided, otherwise use the old logic
if (this.shouldAutoScroll) {
if (diffLines.length <= 5) {
// For small changes, just jump directly to the line
this.scrollEditorToLine(currentLine)
if (changeLocation) {
// We have the actual location of the change, scroll to it
const targetLine = changeLocation.startLine
this.scrollEditorToLine(targetLine)
} 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))
// 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))
// 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
// 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)
}
// Ensure we end at the final line
this.scrollEditorToLine(currentLine)
}
}
}
+31
View File
@@ -75,3 +75,34 @@ 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
@@ -0,0 +1,109 @@
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}`)
}
}
@@ -35,42 +35,8 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
let isFirstChunk = true
let didOutputNonCommand = false
let didEmitEmptyLine = false
let firstChunkTimeout: NodeJS.Timeout
const isWindows = process.platform === "win32"
const timeoutMs = isWindows ? 5000 : 500
const onTimeout = () => {
// In rare cases (e.g. running the same command twice like `npm run build`),
// the shell integration stream enters a broken state where no data is ever emitted.
// We never even get the first chunk, which bricks the UI and locks the user out.
// Interestingly, the stream still gets created, and future commands (like `ls`) will work,
// suggesting the stream itself isn't one-shot—but certain shell states break its behavior.
// To recover, we add a timeout waiting for the first chunk.
// If it doesnt arrive in time, we assume the terminal is broken, dispose it,
// and emit an error so the user can safely retry in a clean terminal.
Logger.debug(
`[TerminalProcess.run] First chunk timeout hit — terminal likely in bad state. Terminating terminal.`,
)
try {
terminal.dispose()
} catch (err) {
Logger.debug(`[TerminalProcess.run] Failed to dispose terminal: ${String(err)}`)
}
this.emit(
"error",
new Error("The command ran successfully, but we couldn't capture its output. Please proceed accordingly."),
)
this.emit("completed")
this.emit("continue")
}
firstChunkTimeout = setTimeout(onTimeout, timeoutMs)
for await (let data of stream) {
clearTimeout(firstChunkTimeout)
// 1. Process chunk and remove artifacts
if (isFirstChunk) {
/*
+1
View File
@@ -1,4 +1,5 @@
export interface ChatContent {
message?: string
images?: string[]
files?: string[]
}
+2 -7
View File
@@ -21,14 +21,12 @@ export interface ExtensionMessage {
| "lmStudioModels"
| "theme"
| "workspaceUpdated"
| "invoke"
| "partialMessage"
| "openRouterModels"
| "openAiModels"
| "requestyModels"
| "mcpServers"
| "relinquishControl"
| "authCallback"
| "mcpMarketplaceCatalog"
| "mcpDownloadDetails"
| "commitSearchResults"
@@ -37,8 +35,6 @@ export interface ExtensionMessage {
| "userCreditsBalance"
| "userCreditsUsage"
| "userCreditsPayments"
| "addToInput"
| "browserConnectionResult"
| "fileSearchResults"
| "grpc_response" // New type for gRPC responses
text?: string
@@ -51,9 +47,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 }[]
@@ -103,8 +99,6 @@ 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"
@@ -152,6 +146,7 @@ export interface ClineMessage {
text?: string
reasoning?: string
images?: string[]
files?: string[]
partial?: boolean
lastCheckpointHash?: string
isCheckpointCheckedOut?: boolean
+4 -3
View File
@@ -13,15 +13,12 @@ export interface WebviewMessage {
| "newTask"
| "condense"
| "reportBug"
| "showChatView"
| "requestVsCodeLmModels"
| "authStateChanged"
| "authCallback"
| "fetchMcpMarketplace"
| "searchCommits"
| "fetchLatestMcpServersFromHub"
| "telemetrySetting"
| "invoke"
| "updateSettings"
| "clearAllTaskHistory"
| "fetchUserCreditsData"
@@ -30,11 +27,13 @@ export interface WebviewMessage {
| "grpc_request"
| "grpc_request_cancel"
| "toggleWorkflow"
| "executeQuickWin"
text?: string
disabled?: boolean
apiConfiguration?: ApiConfiguration
images?: string[]
files?: string[]
bool?: boolean
number?: number
browserSettings?: BrowserSettings
@@ -78,6 +77,8 @@ export interface WebviewMessage {
enabled?: boolean
filename?: string
payload?: { command: string; title: string }
offset?: number
shellIntegrationTimeout?: number
}
+103 -49
View File
@@ -24,6 +24,7 @@ export type ApiProvider =
| "asksage"
| "xai"
| "sambanova"
| "cerebras"
export interface ApiHandlerOptions {
apiModelId?: string
@@ -89,6 +90,7 @@ export interface ApiHandlerOptions {
thinkingBudgetTokens?: number
reasoningEffort?: string
sambanovaApiKey?: string
cerebrasApiKey?: string
requestTimeoutMs?: number
onRetryAttempt?: (attempt: number, maxRetries: number, delay: number, error: any) => void
}
@@ -358,7 +360,7 @@ export const bedrockModels = {
// OpenRouter
// https://openrouter.ai/models?order=newest&supported_parameters=tools
export const openRouterDefaultModelId = "anthropic/claude-sonnet-4" // will always exist in openRouterModels
export const openRouterDefaultModelId = "anthropic/claude-3.7-sonnet" // will always exist in openRouterModels
export const openRouterDefaultModelInfo: ModelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
@@ -370,7 +372,7 @@ export const openRouterDefaultModelInfo: ModelInfo = {
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description:
"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)",
"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)",
}
// Vertex AI
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude
@@ -537,7 +539,7 @@ export const vertexModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: false,
supportsPromptCache: true,
supportsGlobalEndpoint: true,
inputPrice: 0.15,
outputPrice: 0.6,
@@ -550,7 +552,7 @@ export const vertexModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: false,
supportsPromptCache: true,
supportsGlobalEndpoint: true,
inputPrice: 0.15,
outputPrice: 0.6,
@@ -681,7 +683,7 @@ export const geminiModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 0.15,
outputPrice: 0.6,
thinkingConfig: {
@@ -693,7 +695,7 @@ export const geminiModels = {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: false,
supportsPromptCache: true,
inputPrice: 0.15,
outputPrice: 0.6,
thinkingConfig: {
@@ -1830,85 +1832,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,
outputPrice: 0,
inputPrice: 0.6,
outputPrice: 1.2,
},
"DeepSeek-R1-Distill-Llama-70B": {
maxTokens: 4096,
contextWindow: 32_000,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
inputPrice: 0.7,
outputPrice: 1.4,
},
"Llama-3.1-Swallow-70B-Instruct-v0.3": {
"DeepSeek-R1": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
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,
inputPrice: 5.0,
outputPrice: 7.0,
},
"Meta-Llama-3.1-405B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
inputPrice: 5.0,
outputPrice: 10.0,
},
"Meta-Llama-3.1-8B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
inputPrice: 0.1,
outputPrice: 0.2,
},
"Meta-Llama-3.2-1B-Instruct": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
inputPrice: 0.04,
outputPrice: 0.08,
},
"Qwen2.5-72B-Instruct": {
"Meta-Llama-3.2-3B-Instruct": {
maxTokens: 4096,
contextWindow: 8_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.08,
outputPrice: 0.16,
},
"Qwen3-32B": {
maxTokens: 4096,
contextWindow: 16_000,
supportsImages: false,
supportsPromptCache: false,
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,
inputPrice: 0.4,
outputPrice: 0.8,
},
"QwQ-32B": {
maxTokens: 4096,
@@ -1920,11 +1922,63 @@ 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: 1.0,
outputPrice: 1.5,
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)",
},
} as const satisfies Record<string, ModelInfo>
@@ -35,6 +35,7 @@ export function convertChatContentToProtoChatContent(chatContent?: ChatContent):
return {
message: chatContent.message,
images: chatContent.images || [],
files: chatContent.files || [],
}
}
@@ -49,5 +50,6 @@ export function convertProtoChatContentToChatContent(protoChatContent?: ProtoCha
return {
message: protoChatContent.message,
images: protoChatContent.images || [],
files: protoChatContent.files || [],
}
}
+48 -8
View File
@@ -1,8 +1,13 @@
// @ts-nocheck
import * as vscode from "vscode"
import * as fs from "fs"
import * as path from "path"
import open from "open"
import { log } from "./utils"
const DATA_DIR = process.env.DATA_DIR ?? "."
function stubUri(path: string): vscode.Uri {
console.log(`Using file path: ${path}`)
return {
@@ -46,6 +51,46 @@ function createMemento(): vscode.Memento {
}
}
class SecretStore {
// A simple key-value store for secrets backed by a JSON file. This is not secure, and it is not thread-safe.
private store = new Map<string, string>()
private filePath: string
constructor() {
this.filePath = path.join(DATA_DIR, "secrets.json")
this.load()
}
private load(): void {
if (fs.existsSync(this.filePath)) {
const data = JSON.parse(fs.readFileSync(this.filePath, "utf-8"))
Object.entries(data).forEach(([k, v]) => {
if (typeof v === "string") {
this.store.set(k, v)
}
})
}
}
private save(): void {
fs.writeFileSync(this.filePath, JSON.stringify(Object.fromEntries(this.store), null, 2))
}
get(key: string): string | undefined {
return this.store.get(key)
}
storeSecret(key: string, value: string): void {
this.store.set(key, value)
this.save()
}
delete(key: string): void {
this.store.delete(key)
this.save()
}
}
const extensionContext: vscode.ExtensionContext = {
extensionPath: "/tmp/vscode/extension",
extensionUri: stubUri("/tmp/vscode/extension"),
@@ -121,7 +166,7 @@ const extensionContext: vscode.ExtensionContext = {
extensionMode: 1, // Development
extension: {
id: "your.extension.id",
id: "saoudrizwan.claude-dev",
isActive: true,
extensionPath: "/tmp/vscode/extension",
extensionUri: stubUri("/tmp/vscode/extension"),
@@ -134,15 +179,10 @@ const extensionContext: vscode.ExtensionContext = {
subscriptions: [],
asAbsolutePath: (relPath) => `/tmp/vscode/extension/${relPath}`,
secrets: {
store: async () => {},
get: async () => undefined,
delete: async () => {},
onDidChange: {},
},
}
extensionContext.secrets = new SecretStore()
const outputChannel: vscode.OutputChannel = {
append: (text) => process.stdout.write(text),
appendLine: (line) => console.log(line),
+14 -17
View File
@@ -35,21 +35,19 @@ describe("Chat Integration Tests", () => {
}
});
break;
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
}
});
}
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
}
});
break;
}
});
@@ -143,8 +141,7 @@ describe("Chat Integration Tests", () => {
// Trigger tool approval
await panel.webview.postMessage({
type: "invoke",
invoke: "primaryButtonClick",
type: "primaryButtonClick",
})
// Verify gRPC request was sent with correct parameters
+2 -1
View File
@@ -111,7 +111,7 @@ interface ChatRowProps {
isLast: boolean
onHeightChange: (isTaller: boolean) => void
inputValue?: string
sendMessageFromChatRow?: (text: string, images: string[]) => void
sendMessageFromChatRow?: (text: string, images: string[], files: string[]) => void
onSetQuote: (text: string) => void
}
@@ -1046,6 +1046,7 @@ export const ChatRowContent = ({
<UserMessage
text={message.text}
images={message.images}
files={message.files}
messageTs={message.ts}
sendMessageFromChatRow={sendMessageFromChatRow}
/>
+62 -27
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_PER_MESSAGE } from "@/components/chat/ChatView"
import { MAX_IMAGES_AND_FILES_PER_MESSAGE } from "@/components/chat/ChatView"
import ContextMenu from "@/components/chat/ContextMenu"
import SlashCommandMenu from "@/components/chat/SlashCommandMenu"
import { ChatSettings } from "@shared/ChatSettings"
@@ -65,11 +65,13 @@ 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
onSelectImages: () => void
shouldDisableImages: boolean
onSelectFilesAndImages: () => void
shouldDisableFilesAndImages: boolean
onHeightChange?: (height: number) => void
onFocusChange?: (isFocused: boolean) => void
}
@@ -250,11 +252,13 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
setInputValue,
sendingDisabled,
placeholderText,
selectedFiles,
selectedImages,
setSelectedImages,
setSelectedFiles,
onSend,
onSelectImages,
shouldDisableImages,
onSelectFilesAndImages,
shouldDisableFilesAndImages,
onHeightChange,
onFocusChange,
},
@@ -836,7 +840,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const [type, subtype] = item.type.split("/")
return type === "image" && acceptedTypes.includes(subtype)
})
if (!shouldDisableImages && imageItems.length > 0) {
if (!shouldDisableFilesAndImages && imageItems.length > 0) {
e.preventDefault()
const imagePromises = imageItems.map((item) => {
return new Promise<string | null>((resolve) => {
@@ -873,13 +877,28 @@ 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) {
setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
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)])
}
} else {
console.warn("No valid images were processed")
}
}
},
[shouldDisableImages, setSelectedImages, cursorPosition, setInputValue, inputValue, showDimensionErrorMessage],
[
shouldDisableFilesAndImages,
setSelectedImages,
selectedImages,
selectedFiles,
cursorPosition,
setInputValue,
inputValue,
showDimensionErrorMessage,
],
)
const handleThumbnailsHeightChange = useCallback((height: number) => {
@@ -887,10 +906,10 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}, [])
useEffect(() => {
if (selectedImages.length === 0) {
if (selectedImages.length === 0 && selectedFiles.length === 0) {
setThumbnailsHeight(0)
}
}, [selectedImages])
}, [selectedImages, selectedFiles])
const handleMenuMouseDown = useCallback(() => {
setIsMouseDownOnMenu(true)
@@ -988,6 +1007,7 @@ 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
@@ -995,7 +1015,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
textAreaRef.current?.focus()
}, 100)
}, changeModeDelay)
}, [chatSettings.mode, showModelSelector, submitApiConfig, inputValue, selectedImages])
}, [chatSettings.mode, showModelSelector, submitApiConfig, inputValue, selectedImages, selectedFiles])
useShortcut("Meta+Shift+a", onModeToggle, { disableTextInputs: false }) // important that we don't disable the text input here
@@ -1272,7 +1292,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
return type === "image" && acceptedTypes.includes(subtype)
})
if (shouldDisableImages || imageFiles.length === 0) {
if (shouldDisableFilesAndImages || imageFiles.length === 0) {
return
}
@@ -1280,7 +1300,13 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
if (dataUrls.length > 0) {
setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
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)])
}
} else {
console.warn("No valid images were processed")
}
@@ -1400,7 +1426,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
fontWeight: "bold",
fontSize: "12px",
}}>
Only image files are supported
Files other than images are currently disabled
</span>
</div>
)}
@@ -1467,12 +1493,13 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
borderRight: 0,
borderTop: 0,
borderColor: "transparent",
borderBottom: `${thumbnailsHeight + 6}px solid transparent`,
padding: "9px 28px 3px 9px",
borderBottom: `${thumbnailsHeight}px solid transparent`,
padding: "9px 28px 9px 9px",
}}
/>
<DynamicTextArea
data-testid="chat-input"
minRows={3}
ref={(el) => {
if (typeof ref === "function") {
ref(el)
@@ -1524,13 +1551,13 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
borderLeft: 0,
borderRight: 0,
borderTop: 0,
borderBottom: `${thumbnailsHeight + 6}px solid transparent`,
borderBottom: `${thumbnailsHeight}px solid transparent`,
borderColor: "transparent",
// borderRight: "54px solid transparent",
// borderLeft: "9px solid transparent", // NOTE: react-textarea-autosize doesn't calculate correct height when using borderLeft/borderRight so we need to use horizontal padding instead
// Instead of using boxShadow, we use a div with a border to better replicate the behavior when the textarea is focused
// boxShadow: "0px 0px 0px 1px var(--vscode-input-border)",
padding: "9px 28px 3px 9px",
padding: "9px 28px 9px 9px",
cursor: "text",
flex: 1,
zIndex: 1,
@@ -1544,10 +1571,17 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}}
onScroll={() => updateHighlights()}
/>
{selectedImages.length > 0 && (
{!inputValue && selectedImages.length === 0 && selectedFiles.length === 0 && (
<div className="absolute bottom-4 left-[25px] right-[60px] text-[10px] text-[var(--vscode-input-placeholderForeground)] opacity-70 whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none z-[1]">
Type @ for context, / for slash commands & workflows
</div>
)}
{(selectedImages.length > 0 || selectedFiles.length > 0) && (
<Thumbnails
images={selectedImages}
files={selectedFiles}
setImages={setSelectedImages}
setFiles={setSelectedFiles}
onHeightChange={handleThumbnailsHeightChange}
style={{
position: "absolute",
@@ -1564,9 +1598,10 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
position: "absolute",
right: 23,
display: "flex",
alignItems: "flex-center",
alignItems: "flex-end",
height: textAreaBaseHeight || 31,
bottom: 9.5, // should be 10 but doesn't look good on mac
paddingBottom: "8px",
zIndex: 2,
}}>
<div
@@ -1637,21 +1672,21 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
</VSCodeButton>
</Tooltip>
<Tooltip tipText="Add Images">
<Tooltip tipText="Add Files & Images">
<VSCodeButton
data-testid="images-button"
data-testid="files-button"
appearance="icon"
aria-label="Add Images"
disabled={shouldDisableImages}
aria-label="Add Files & Images"
disabled={shouldDisableFilesAndImages}
onClick={() => {
if (!shouldDisableImages) {
onSelectImages()
if (!shouldDisableFilesAndImages) {
onSelectFilesAndImages()
}
}}
style={{ padding: "0px 0px", height: "20px" }}>
<ButtonContainer>
<span
className="codicon codicon-device-camera flex items-center"
className="codicon codicon-add flex items-center"
style={{ fontSize: "14px", marginBottom: -3 }}
/>
</ButtonContainer>
+164 -71
View File
@@ -18,7 +18,7 @@ import { combineCommandSequences } from "@shared/combineCommandSequences"
import { getApiMetrics } from "@shared/getApiMetrics"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { vscode } from "@/utils/vscode"
import { TaskServiceClient, SlashServiceClient, FileServiceClient } from "@/services/grpc-client"
import { TaskServiceClient, SlashServiceClient, FileServiceClient, UiServiceClient } from "@/services/grpc-client"
import HistoryPreview from "@/components/history/HistoryPreview"
import { normalizeApiConfiguration } from "@/components/settings/ApiOptions"
import Announcement from "@/components/chat/Announcement"
@@ -34,6 +34,8 @@ 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
@@ -86,11 +88,13 @@ async function convertHtmlToMarkdown(html: string) {
return cleanupMarkdownEscapes(md)
}
export const MAX_IMAGES_PER_MESSAGE = 20 // Anthropic limits to 20 images
// 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
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])
@@ -117,6 +121,7 @@ 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)
@@ -130,6 +135,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const disableAutoScrollRef = useRef(false)
const [showScrollToBottom, setShowScrollToBottom] = useState(false)
const [isAtBottom, setIsAtBottom] = useState(false)
const [pendingScrollToMessage, setPendingScrollToMessage] = useState<number | null>(null)
useEffect(() => {
const handleCopy = async (e: ClipboardEvent) => {
@@ -367,6 +373,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setInputValue("")
setSendingDisabled(true)
setSelectedImages([])
setSelectedFiles([])
setClineAsk(undefined)
setEnableButtons(false)
}
@@ -439,9 +446,9 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
}, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
const handleSendMessage = useCallback(
async (text: string, images: string[]) => {
async (text: string, images: string[], files: string[]) => {
let messageToSend = text.trim()
const hasContent = messageToSend || images.length > 0
const hasContent = messageToSend || images.length > 0 || files.length > 0
// Prepend the active quote if it exists
if (activeQuote && hasContent) {
@@ -454,7 +461,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 })
await TaskServiceClient.newTask({ text: messageToSend, images, files })
} else if (clineAsk) {
switch (clineAsk) {
case "followup":
@@ -469,24 +476,13 @@ 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
@@ -496,6 +492,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setActiveQuote(null) // Clear quote when sending message
setSendingDisabled(true)
setSelectedImages([])
setSelectedFiles([])
setClineAsk(undefined)
setEnableButtons(false)
// setPrimaryButtonText(undefined)
@@ -515,7 +512,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[]) => {
async (text?: string, images?: string[], files?: string[]) => {
const trimmedInput = text?.trim()
switch (clineAsk) {
case "api_req_failed":
@@ -527,11 +524,12 @@ 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)) {
if (trimmedInput || (images && images.length > 0) || (files && files.length > 0)) {
await TaskServiceClient.askResponse({
responseType: "yesButtonClicked",
text: trimmedInput,
images: images,
files: files,
})
} else {
await TaskServiceClient.askResponse({
@@ -542,6 +540,7 @@ 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":
@@ -553,6 +552,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
await TaskServiceClient.newTask({
text: lastMessage?.text,
images: [],
files: [],
})
break
case "condense":
@@ -573,7 +573,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
)
const handleSecondaryButtonClick = useCallback(
async (text?: string, images?: string[]) => {
async (text?: string, images?: string[], files?: string[]) => {
const trimmedInput = text?.trim()
if (isStreaming) {
await TaskServiceClient.cancelTask({})
@@ -591,11 +591,12 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
case "tool":
case "browser_action_launch":
case "use_mcp_server":
if (trimmedInput || (images && images.length > 0)) {
if (trimmedInput || (images && images.length > 0) || (files && files.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,6 +608,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
setInputValue("")
setActiveQuote(null) // Clear quote when using secondary button
setSelectedImages([])
setSelectedFiles([])
break
}
setSendingDisabled(true)
@@ -631,18 +633,40 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
return normalizeApiConfiguration(apiConfiguration)
}, [apiConfiguration])
const selectImages = useCallback(async () => {
const selectFilesAndImages = useCallback(async () => {
try {
const response = await FileServiceClient.selectImages({})
if (response && response.values && response.values.length > 0) {
setSelectedImages((prevImages) => [...prevImages, ...response.values].slice(0, MAX_IMAGES_PER_MESSAGE))
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)])
}
}
}
} catch (error) {
console.error("Error selecting images:", error)
console.error("Error selecting images & files:", error)
}
}, [])
}, [selectedModelInfo.supportsImages])
const shouldDisableImages = !selectedModelInfo.supportsImages || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
const shouldDisableFilesAndImages = selectedImages.length + selectedFiles.length >= MAX_IMAGES_AND_FILES_PER_MESSAGE
const handleMessage = useCallback(
(e: MessageEvent) => {
@@ -658,45 +682,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
case "focusChatInput":
textAreaRef.current?.focus()
if (isHidden) {
// Send message back to extension to show chat view
vscode.postMessage({ type: "showChatView" })
window.dispatchEvent(new CustomEvent("chatButtonClicked"))
}
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 ?? ""
const newTextWithNewline = newText + "\n"
return prevValue ? `${prevValue}\n${newTextWithNewline}` : newTextWithNewline
})
// Add scroll to bottom after state update
// Auto focus the input and start the cursor on a new linefor easy typing
setTimeout(() => {
if (textAreaRef.current) {
textAreaRef.current.scrollTop = textAreaRef.current.scrollHeight
textAreaRef.current.focus()
}
}, 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.
},
@@ -705,6 +695,40 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
useEvent("message", handleMessage)
// Set up addToInput subscription
useEffect(() => {
const cleanup = UiServiceClient.subscribeToAddToInput(
{},
{
onResponse: (event) => {
if (event.value) {
setInputValue((prevValue) => {
const newText = event.value
const newTextWithNewline = newText + "\n"
return prevValue ? `${prevValue}\n${newTextWithNewline}` : newTextWithNewline
})
// Add scroll to bottom after state update
// Auto focus the input and start the cursor on a new line for easy typing
setTimeout(() => {
if (textAreaRef.current) {
textAreaRef.current.scrollTop = textAreaRef.current.scrollHeight
textAreaRef.current.focus()
}
}, 0)
}
},
onError: (error) => {
console.error("Error in addToInput subscription:", error)
},
onComplete: () => {
console.log("addToInput subscription completed")
},
},
)
return cleanup
}, [])
useMount(() => {
// NOTE: the vscode window needs to be focused for this to work
textAreaRef.current?.focus()
@@ -864,6 +888,61 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
})
}, [])
const scrollToMessage = useCallback(
(messageIndex: number) => {
setPendingScrollToMessage(messageIndex)
const targetMessage = messages[messageIndex]
if (!targetMessage) {
setPendingScrollToMessage(null)
return
}
const visibleIndex = visibleMessages.findIndex((msg) => msg.ts === targetMessage.ts)
if (visibleIndex === -1) {
setPendingScrollToMessage(null)
return
}
let groupIndex = -1
let currentVisibleIndex = 0
for (let i = 0; i < groupedMessages.length; i++) {
const group = groupedMessages[i]
if (Array.isArray(group)) {
const groupSize = group.length
const messageInGroup = group.some((msg) => msg.ts === targetMessage.ts)
if (messageInGroup) {
groupIndex = i
break
}
currentVisibleIndex += groupSize
} else {
if (group.ts === targetMessage.ts) {
groupIndex = i
break
}
currentVisibleIndex++
}
}
if (groupIndex !== -1) {
setPendingScrollToMessage(null)
disableAutoScrollRef.current = true
requestAnimationFrame(() => {
requestAnimationFrame(() => {
virtuosoRef.current?.scrollToIndex({
index: groupIndex,
align: "start",
behavior: "smooth",
})
})
})
}
},
[messages, visibleMessages, groupedMessages],
)
// scroll when user toggles certain rows
const toggleRowExpansion = useCallback(
(ts: number) => {
@@ -943,6 +1022,12 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
}
}, [groupedMessages.length, scrollToBottomSmooth])
useEffect(() => {
if (pendingScrollToMessage !== null) {
scrollToMessage(pendingScrollToMessage)
}
}, [pendingScrollToMessage, groupedMessages, scrollToMessage])
const handleWheel = useCallback((event: Event) => {
const wheelEvent = event as WheelEvent
if (wheelEvent.deltaY && wheelEvent.deltaY < 0) {
@@ -1040,6 +1125,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
totalCost={apiMetrics.totalCost}
lastApiReqTotalTokens={lastApiReqTotalTokens}
onClose={handleTaskCloseButtonClick}
onScrollToMessage={scrollToMessage}
/>
) : (
<div
@@ -1056,11 +1142,16 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
{showAnnouncement && <Announcement version={version} hideAnnouncement={hideAnnouncement} />}
<HomeHeader />
{taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
{!shouldShowQuickWins && taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
</div>
)}
{!task && <AutoApproveBar />}
{!task && (
<>
<SuggestedTasks shouldShowQuickWins={shouldShowQuickWins} />
<AutoApproveBar />
</>
)}
{task && (
<>
@@ -1129,7 +1220,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
flex: secondaryButtonText ? 1 : 2,
marginRight: secondaryButtonText ? "6px" : "0",
}}
onClick={() => handlePrimaryButtonClick(inputValue, selectedImages)}>
onClick={() => handlePrimaryButtonClick(inputValue, selectedImages, selectedFiles)}>
{primaryButtonText}
</VSCodeButton>
)}
@@ -1141,7 +1232,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
flex: isStreaming ? 2 : 1,
marginLeft: isStreaming ? 0 : "6px",
}}
onClick={() => handleSecondaryButtonClick(inputValue, selectedImages)}>
onClick={() => handleSecondaryButtonClick(inputValue, selectedImages, selectedFiles)}>
{isStreaming ? "Cancel" : secondaryButtonText}
</VSCodeButton>
)}
@@ -1171,9 +1262,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
placeholderText={placeholderText}
selectedImages={selectedImages}
setSelectedImages={setSelectedImages}
onSend={() => handleSendMessage(inputValue, selectedImages)}
onSelectImages={selectImages}
shouldDisableImages={shouldDisableImages}
setSelectedFiles={setSelectedFiles}
selectedFiles={selectedFiles}
onSend={() => handleSendMessage(inputValue, selectedImages, selectedFiles)}
onSelectFilesAndImages={selectFilesAndImages}
shouldDisableFilesAndImages={shouldDisableFilesAndImages}
onHeightChange={() => {
if (isAtBottom) {
scrollToBottomAuto()
@@ -1,8 +1,7 @@
import React from "react"
import VSCodeButtonLink from "@/components/common/VSCodeButtonLink"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { vscode } from "@/utils/vscode"
import { Invoke } from "@shared/ExtensionMessage"
import { TaskServiceClient } from "@/services/grpc-client"
interface CreditLimitErrorProps {
currentBalance: number
@@ -40,11 +39,16 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({ currentBalance, tot
</VSCodeButtonLink>
<VSCodeButton
onClick={() => {
vscode.postMessage({
type: "invoke",
text: "primaryButtonClick" satisfies Invoke,
})
onClick={async () => {
try {
await TaskServiceClient.askResponse({
responseType: "yesButtonClicked",
text: "",
images: [],
})
} catch (error) {
console.error("Error invoking action:", error)
}
}}
appearance="secondary"
style={{
+41 -2
View File
@@ -13,6 +13,7 @@ import { validateSlashCommand } from "@/utils/slash-commands"
import TaskTimeline from "./TaskTimeline"
import { TaskServiceClient, FileServiceClient, UiServiceClient } from "@/services/grpc-client"
import HeroTooltip from "@/components/common/HeroTooltip"
const { IS_DEV } = process.env
interface TaskHeaderProps {
task: ClineMessage
@@ -24,6 +25,7 @@ interface TaskHeaderProps {
totalCost: number
lastApiReqTotalTokens?: number
onClose: () => void
onScrollToMessage?: (messageIndex: number) => void
}
const TaskHeader: React.FC<TaskHeaderProps> = ({
@@ -36,6 +38,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
totalCost,
lastApiReqTotalTokens,
onClose,
onScrollToMessage,
}) => {
const { apiConfiguration, currentTaskItem, checkpointTrackerErrorMessage, clineMessages, navigateToSettings } =
useExtensionState()
@@ -145,6 +148,8 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
)
}
console.log("IS_DEV", { IS_DEV, isItTrue: IS_DEV === '"true"' })
const ContextWindowComponent = (
<>
{isTaskExpanded && contextWindow && (
@@ -352,7 +357,9 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
See less
</div>
)}
{task.images && task.images.length > 0 && <Thumbnails images={task.images} />}
{((task.images && task.images.length > 0) || (task.files && task.files.length > 0)) && (
<Thumbnails images={task.images ?? []} files={task.files ?? []} />
)}
<div
style={{
@@ -407,6 +414,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
{!shouldShowPromptCacheInfo() && (
<div className="flex items-center flex-wrap">
<CopyButton taskText={task.text} />
{IS_DEV === '"true"' && <TaskFolderButton taskId={currentTaskItem?.id} />}
<DeleteButton taskSize={formatSize(currentTaskItem?.size)} taskId={currentTaskItem?.id} />
</div>
)}
@@ -462,12 +470,13 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
</div>
<div className="flex items-center flex-wrap">
<CopyButton taskText={task.text} />
{IS_DEV === '"true"' && <TaskFolderButton taskId={currentTaskItem?.id} />}
<DeleteButton taskSize={formatSize(currentTaskItem?.size)} taskId={currentTaskItem?.id} />
</div>
</div>
)}
<div className="flex flex-col">
<TaskTimeline messages={clineMessages} />
<TaskTimeline messages={clineMessages} onBlockClick={onScrollToMessage} />
{ContextWindowComponent}
</div>
{checkpointTrackerErrorMessage && (
@@ -663,6 +672,36 @@ const CopyButton: React.FC<{
)
}
const TaskFolderButton: React.FC<{
taskId?: string
}> = ({ taskId }) => {
const [copied, setCopied] = useState(false)
const handleCopy = () => {
if (!taskId) return
navigator.clipboard.writeText(taskId).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
}
return (
<HeroTooltip content="Copy Task ID">
<VSCodeButton
appearance="icon"
onClick={handleCopy}
style={{ padding: "0px 0px" }}
className="p-0"
aria-label="Copy Task ID">
<div className="flex items-center gap-[3px] text-[8px] font-bold opacity-60">
<i className={`codicon codicon-${copied ? "check" : "folder"}`} />
</div>
</VSCodeButton>
</HeroTooltip>
)
}
const DeleteButton: React.FC<{
taskSize: string
taskId?: string
@@ -14,6 +14,7 @@ const TOOLTIP_MARGIN = 32 // 32px margin on each side
interface TaskTimelineProps {
messages: ClineMessage[]
onBlockClick?: (messageIndex: number) => void
}
const getBlockColor = (message: ClineMessage): string => {
@@ -94,16 +95,19 @@ const getBlockColor = (message: ClineMessage): string => {
return COLOR_WHITE // Default color
}
const TaskTimeline: React.FC<TaskTimelineProps> = ({ messages }) => {
const TaskTimeline: React.FC<TaskTimelineProps> = ({ messages, onBlockClick }) => {
const containerRef = useRef<HTMLDivElement>(null)
const scrollableRef = useRef<HTMLDivElement>(null)
const taskTimelinePropsMessages = useMemo(() => {
if (messages.length <= 1) return []
const { taskTimelinePropsMessages, messageIndexMap } = useMemo(() => {
if (messages.length <= 1) return { taskTimelinePropsMessages: [], messageIndexMap: [] }
const processed = combineApiRequests(combineCommandSequences(messages.slice(1)))
const indexMap: number[] = []
const filtered = processed.filter((msg, processedIndex) => {
const originalIndex = messages.findIndex((originalMsg, idx) => idx > 0 && originalMsg.ts === msg.ts)
return processed.filter((msg) => {
// Filter out standard "say" events we don't want to show
if (
msg.type === "say" &&
@@ -124,9 +128,13 @@ const TaskTimeline: React.FC<TaskTimelineProps> = ({ messages }) => {
) {
return false
}
if (originalIndex !== -1) {
indexMap.push(originalIndex)
}
return true
})
return { taskTimelinePropsMessages: filtered, messageIndexMap: indexMap }
}, [messages])
useEffect(() => {
@@ -145,9 +153,18 @@ const TaskTimeline: React.FC<TaskTimelineProps> = ({ messages }) => {
const TimelineBlock = useCallback(
(index: number) => {
const message = taskTimelinePropsMessages[index]
const originalMessageIndex = messageIndexMap[index]
const handleClick = () => {
if (onBlockClick && originalMessageIndex !== undefined) {
onBlockClick(originalMessageIndex)
}
}
return (
<TaskTimelineTooltip message={message}>
<div
onClick={handleClick}
style={{
width: BLOCK_WIDTH,
height: "100%",
@@ -160,7 +177,7 @@ const TaskTimeline: React.FC<TaskTimelineProps> = ({ messages }) => {
</TaskTimelineTooltip>
)
},
[taskTimelinePropsMessages],
[taskTimelinePropsMessages, messageIndexMap, onBlockClick],
)
// Scroll to the end when messages change
@@ -8,12 +8,13 @@ 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[]) => void
sendMessageFromChatRow?: (text: string, images: string[], files: string[]) => void
}
const UserMessage: React.FC<UserMessageProps> = ({ text, images, messageTs, sendMessageFromChatRow }) => {
const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageTs, sendMessageFromChatRow }) => {
const [isEditing, setIsEditing] = useState(false)
const [editedText, setEditedText] = useState(text || "")
const textAreaRef = useRef<HTMLTextAreaElement>(null)
@@ -52,7 +53,7 @@ const UserMessage: React.FC<UserMessageProps> = ({ text, images, messageTs, send
})
setTimeout(() => {
sendMessageFromChatRow?.(editedText, images || [])
sendMessageFromChatRow?.(editedText, images || [], files || [])
}, delay)
} catch (err) {
console.error("Checkpoint restore error:", err)
@@ -145,7 +146,9 @@ const UserMessage: React.FC<UserMessageProps> = ({ text, images, messageTs, send
{highlightText(editedText || text)}
</span>
)}
{images && images.length > 0 && <Thumbnails images={images} style={{ marginTop: "8px" }} />}
{((images && images.length > 0) || (files && files.length > 0)) && (
<Thumbnails images={images ?? []} files={files ?? []} style={{ marginTop: "8px" }} />
)}
</div>
)
}
+93 -10
View File
@@ -5,13 +5,15 @@ 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, style, setImages, onHeightChange }: ThumbnailsProps) => {
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange }: ThumbnailsProps) => {
const [hoveredIndex, setHoveredIndex] = useState<string | null>(null)
const containerRef = useRef<HTMLDivElement>(null)
const { width } = useWindowSize()
@@ -25,18 +27,27 @@ const Thumbnails = ({ images, style, setImages, onHeightChange }: ThumbnailsProp
onHeightChange?.(height)
}
setHoveredIndex(null)
}, [images, width, onHeightChange])
}, [images, files, width, onHeightChange])
const handleDelete = (index: number) => {
const handleDeleteImages = (index: number) => {
setImages?.((prevImages) => prevImages.filter((_, i) => i !== index))
}
const isDeletable = setImages !== undefined
const handleDeleteFiles = (index: number) => {
setFiles?.((prevFiles) => prevFiles.filter((_, i) => i !== index))
}
const isDeletableImages = setImages !== undefined
const isDeletableFiles = setFiles !== 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}
@@ -49,13 +60,13 @@ const Thumbnails = ({ images, style, setImages, onHeightChange }: ThumbnailsProp
}}>
{images.map((image, index) => (
<div
key={index}
key={`image-${index}`}
style={{ position: "relative" }}
onMouseEnter={() => setHoveredIndex(index)}
onMouseEnter={() => setHoveredIndex(`image-${index}`)}
onMouseLeave={() => setHoveredIndex(null)}>
<img
src={image}
alt={`Thumbnail ${index + 1}`}
alt={`Thumbnail image-${index + 1}`}
style={{
width: 34,
height: 34,
@@ -65,9 +76,9 @@ const Thumbnails = ({ images, style, setImages, onHeightChange }: ThumbnailsProp
}}
onClick={() => handleImageClick(image)}
/>
{isDeletable && hoveredIndex === index && (
{isDeletableImages && hoveredIndex === `image-${index}` && (
<div
onClick={() => handleDelete(index)}
onClick={() => handleDeleteImages(index)}
style={{
position: "absolute",
top: -4,
@@ -92,6 +103,78 @@ const Thumbnails = ({ images, style, setImages, onHeightChange }: ThumbnailsProp
)}
</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>
)
}
@@ -51,6 +51,8 @@ import {
nebiusDefaultModelId,
sambanovaModels,
sambanovaDefaultModelId,
cerebrasModels,
cerebrasDefaultModelId,
doubaoModels,
doubaoDefaultModelId,
liteLlmModelInfoSaneDefaults,
@@ -329,6 +331,7 @@ const ApiOptions = ({
<VSCodeOption value="asksage">AskSage</VSCodeOption>
<VSCodeOption value="xai">xAI</VSCodeOption>
<VSCodeOption value="sambanova">SambaNova</VSCodeOption>
<VSCodeOption value="cerebras">Cerebras</VSCodeOption>
</VSCodeDropdown>
</DropdownContainer>
@@ -2013,6 +2016,37 @@ 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={{
@@ -2130,6 +2164,7 @@ const ApiOptions = ({
{selectedProvider === "asksage" && createDropdown(askSageModels)}
{selectedProvider === "xai" && createDropdown(xaiModels)}
{selectedProvider === "sambanova" && createDropdown(sambanovaModels)}
{selectedProvider === "cerebras" && createDropdown(cerebrasModels)}
{selectedProvider === "nebius" && createDropdown(nebiusModels)}
</DropdownContainer>
@@ -2565,6 +2600,8 @@ 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)
}
@@ -59,20 +59,6 @@ export const BrowserSettingsSection: React.FC = () => {
const [isBundled, setIsBundled] = useState(false)
const [detectedChromePath, setDetectedChromePath] = useState<string | null>(null)
// Listen for browser connection test results
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
const message = event.data
if (message.type === "browserConnectionResult") {
setConnectionStatus(message.success)
setIsCheckingConnection(false)
}
}
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}, [])
// Auto-clear relaunch result message after 15 seconds
useEffect(() => {
if (relaunchResult) {
@@ -41,8 +41,8 @@ export interface OpenRouterModelPickerProps {
// Featured models for Cline provider
const featuredModels = [
{
id: "anthropic/claude-sonnet-4",
description: "Best model for agentic coding",
id: "anthropic/claude-3.7-sonnet",
description: "Recommended for agentic coding in Cline",
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-sonnet-4")}>
anthropic/claude-sonnet-4.
onClick={() => handleModelChange("anthropic/claude-3.7-sonnet")}>
anthropic/claude-3.7-sonnet.
</VSCodeLink>
You can also try searching "free" for no-cost options currently available.
</>
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,27 @@
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/claude/sonnet" className="inline">
Claude 4 Sonnet's
<VSCodeLink href="https://www.anthropic.com/news/claude-3-7-sonnet" className="inline">
Claude 3.7 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 4
Sonnet.
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.
</p>
<VSCodeButton appearance="primary" onClick={handleLogin} className="w-full mt-1">
@@ -0,0 +1,39 @@
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: ">",
},
]
@@ -207,60 +207,6 @@ 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)))
@@ -326,33 +272,31 @@ 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,
@@ -377,52 +321,41 @@ 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 = {
+17 -11
View File
@@ -2,6 +2,7 @@ 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 = {
@@ -37,8 +38,6 @@ 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.
@@ -73,17 +72,24 @@ export const FirebaseAuthProvider: React.FC<{ children: React.ReactNode }> = ({
[auth],
)
// Listen for auth callback from extension
// Set up authCallback subscription
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
const message = event.data
if (message.type === "authCallback" && message.customToken) {
signInWithToken(message.customToken)
}
}
const cleanup = AccountServiceClient.subscribeToAuthCallback(
{},
{
onResponse: (event) => {
if (event.value) {
signInWithToken(event.value)
}
},
onError: (error) => {
console.error("Error in authCallback subscription:", error)
},
onComplete: () => {},
},
)
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
return cleanup
}, [signInWithToken])
const handleSignOut = useCallback(async () => {
@@ -94,7 +94,6 @@ 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)
}
}
@@ -149,7 +148,6 @@ 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)
}
}