Compare commits

...

56 Commits

Author SHA1 Message Date
kvyb 52717893e4 refactor: migrate diagnostics to workspace service and host separation 2025-08-06 09:10:08 +08:00
kvyb b79c3d662a remove test logging 2025-08-05 22:46:53 +08:00
kvyb 625a2bc4b5 feat: migrate diff edit diagnostics to hostbridge; Migrate diagnostics functionality from direct VS Code API calls to the hostbridge layer to enable multi-host support (VS Code + IntelliJ). 2025-08-05 22:36:35 +08:00
Sarah Fortune 616800fcb9 Refactoring: move vscode specific property out of the WebviewProvider into the VscodeViewProvider (#5364) 2025-08-05 06:48:12 +01:00
Sarah Fortune df3826a59f In the webview grpc client, JSON encode/decode the messages when not running in Vscode (#5362) 2025-08-04 22:39:32 -07:00
Sarah Fortune 873917810d Remove left code from ProtoBus migration (#5363)
There is one place in the McpHub that sends messages mcp notification messages directly to the webview (not using the ProtoBus).

There is nowhere in the webview that is listening for this message, so this code is not doing anything.
2025-08-04 22:39:20 -07:00
Alex Ker e3c966f4e9 Baseten provider (#5238)
* kimi working

* fixed description rendering

* nit

* changeset

* revert openai version in package.json

* revert package-lock.json

* added space back in

* maintained previous protofield map order

* fixed import error due to location change from main

* updated Mode import for BasetenModelPicker

* revert readme since baseten is openai compatible

* refactored extensionStateContext

* added didOutputUsage flag

* fixed frontend loading

* no support for images on llama

* shifted VSCode Option order

* deleted typo

---------

Co-authored-by: Alex Ker <alexker@mac.mynetworksettings.com>
Co-authored-by: Alex Ker <alexker@Alexs-MacBook-Pro.local>
2025-08-04 20:07:59 -07:00
Sarah Fortune 7eeb43ab41 Simplify the GrpcHandler and add tests (#5356)
* Simplify the GrpcHandler

* Use two functions handleUnaryRequest and handleStreamingRequest, instead of creating a GrpcHandler object and calling class methods on it.
* Remove redundant try/catch and empty finally blocks. Each of the two handler functions has it's own try/catch.
* Each of the two functions is responsible for posting the result to the webview- Instead of unary and streaming responses being handled at different levels.
* Use the GrpcRequest and GrpcCancel types.

* Update comment
2025-08-04 19:15:29 -07:00
Bee 7620f177ac fix: clear streamingFailedMessage when user manually retries (#5222)
* fix: clear streamingFailedMessage when user manually retries

- Clear streamingFailedMessage when user manually retries
- Convert imports to type-only where appropriate
- Reorder imports for better organization
- Add explicit type annotations for better type safety
- Move node:timers/promises import to top

* add changeset

* merge main and reset fail flag

* revert autoformat
2025-08-04 17:04:42 -07:00
Bee 67bab94911 Revert "Add getCallUri to the HostProvider (#5322)" (#5359)
This reverts commit b8227c19c3.
2025-08-04 16:30:04 -07:00
Bee eb91bfd738 Update ChatView footer background to use sidebar theme (#5357)
Change footer background from editor to sidebar background color
and remove border styling.
2025-08-04 16:06:02 -07:00
Sarah Fortune b8227c19c3 Add getCallUri to the HostProvider (#5322)
**Centralize callback URI management** through the HostProvider instead of having it in multiple places in the codebase.

**Simplify error handling** by making the callback URI required rather than optional

The changes are related to **authentication callback URI handling** in the Cline extension. Here's what's being modified:

  - Simplified callback URI retrieval
- Changed return type from `Promise<string | undefined>` to `Promise<string>`
- Now throws an error if AuthHandler is not enabled instead of returning undefined

- Added a new `getCallbackUri` property that returns a `Promise<string>`
- This allows the host provider to supply callback URIs for authentication

  - Implemented callback URI provider

  - Updated to use HostProvider for callback URI

  - Updated to match new signature
2025-08-05 00:03:07 +01:00
Sarah Fortune 8fee09f09e Add logging to the webview ProtoBus client if it recieves a badly formed message (#5353) 2025-08-04 22:34:08 +01:00
Bee 1c026c26d2 fix: chatbox position styling (#5352)
* fix: chatbox position styling

* add changeset
2025-08-04 14:18:53 -07:00
Sarah Fortune 5bc4e5a4a0 Add comments for HostBridge RPC showSaveDialog (#5351) 2025-08-04 21:15:45 +01:00
Ara 2cfce5734e Change Vscode LM token counts to use approx counting method (#5280) 2025-08-04 12:41:34 -07:00
Bee e2045bf5c3 fix: flaky check for editor search bar (#5347)
* fix: flaky check for editor search bar

* remove disabling notification
2025-08-04 12:37:33 -07:00
Sarah Fortune 0d933e804f Support mentions for filenames with spaces (#5309)
* feat: support file mentions with spaces using quoted syntax

This change allows users to reference files with spaces in their names, which was previously impossible due to the space-delimited mention syntax.
File names with spaces can be @ mentioned by quoting the file name, e.g. @"/path with spaces/file.txt".

- Update mention regex in `src/shared/context-mentions.ts` to accept quoted file paths
  - Add support for quoted file paths that can contain spaces.
  - Allow multiple trailing punctuation chars; previously only a single limited punctuation characters were allowed.
  - Maintain support for unquoted paths, URLs, git hashes, and special keywords

- Update `src/core/mentions/index.ts` to handle quoted file names in mention parsing
  - Process quoted file paths by removing quotes when accessing the file system
  - Preserve existing functionality for all other mention types

- Update `webview-ui/src/utils/context-mentions.ts` to auto-quote file names with spaces
  - `insertMention()` and `insertMentionDirectly()` now wrap file paths containing spaces in quotes
  - Non-file mentions (URLs, keywords) remain unquoted

- Add comprehensive unit tests:
  - New test file `src/core/mentions/__tests__/index.test.ts` covering all mention types
  - New test file `webview-ui/src/utils/__tests__/context-mentions.test.ts` for webview mention insertion
  - Expanded `src/shared/__tests__/context-mentions.test.ts` to cover quoted paths and edge cases

* Use const instead of var
2025-08-04 19:42:44 +01:00
Sarah Fortune 16f73532f4 Remove things that were left over from the ProtoBus migration. (#5321) 2025-08-04 18:04:54 +01:00
Sarah Fortune 88bea8eeb4 Update saveOpenDocumentIfDirty to return if the doc was saved or not (#5343) 2025-08-04 18:04:36 +01:00
Sarah Fortune 1a570e98ba Update the GitHub test action to produce more readable output (#5333) 2025-08-04 18:04:21 +01:00
Toshii d86b7dd036 Add optional way to enforce no file edits in plan mode (#5299)
* base implementation

* base messaging implementation & ui

* update state
2025-08-04 09:55:59 -07:00
Sarah Fortune 0178c3fa90 Fix flakey test getOpenTabs and re-enable unit tests (#5332)
- Replace fixed 100ms timeout with pWaitFor polling mechanism
- Set 2-second timeout with 50ms polling interval
- Test now waits exactly as long as needed for tabs to be created
2025-08-03 20:51:05 -07:00
github-actions[bot] a107f45c6a v3.20.8 Release Notes (#5330)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

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: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 17:17:54 -07:00
Saoud Rizwan 3dd2ed9161 Add comment about testing fix (#5329)
* Add comment about testing fix

* Create cool-cherries-brush.md
2025-08-03 17:15:04 -07:00
Saoud Rizwan 9a6603fdfb Disable unit tests in publish pipeline (#5327) 2025-08-03 17:09:59 -07:00
Sarah Fortune 6d5c3e6aa4 Switch remaining uses of vscode.window.show*Message to the HostBridge (#5324)
* Move remaining uses of vscode.window.show*Message to the HostBridge

Switch over the remaining uses.

Turn on the linter check to prevent these APIs being reintroduced later.

Exclude test files from the linter check.

* Update unit test
2025-08-04 01:03:43 +01:00
Sarah Fortune 24b9e821bb refactor: update navbar styling and remove shadow (#5323)
- Replace database icon with MCP server icon (codicon-server)
- Remove shadow-sm class for a flatter appearance
- Maintain consistent button styling with VSCodeButton components
- Add tooltips using HeroTooltip
2025-08-04 00:59:04 +01:00
github-actions[bot] 9960a3c57c v3.20.7 Release Notes (#5328)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

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: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 16:57:50 -07:00
Sarah Fortune 88947592f0 Fix errors in tests (#5294)
* Fix errors in tests:

```
[TerminalProcess] Terminal ID: Cline
Error capturing terminal output: Error: Failed to read from clipboard: HostProvider not setup. Call HostProvider.initialize() first.
  at readTextFromClipboard (/Users/sjf/cline/out/src/utils/env.js:39:15)
  at getLatestTerminalOutput (/Users/sjf/cline/out/src/integrations/terminal/get-latest-output.js:35:69)
  at TerminalProcess.emitCurrentTerminalContents (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:26:92)
  at TerminalProcess.runWithoutShellIntegration (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:366:20)
  at async TerminalProcess.run (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:47:13)
      ✔ should execute a command that lists files
[TerminalProcess] Starting command: "sleep 0.5 && echo 'Done sleeping'"
[TerminalProcess] Shell integration available: false
[TerminalProcess] Terminal ID: Cline
Error capturing terminal output: Error: Failed to read from clipboard: HostProvider not setup. Call HostProvider.initialize() first.
  at readTextFromClipboard (/Users/sjf/cline/out/src/utils/env.js:39:15)
  at getLatestTerminalOutput (/Users/sjf/cline/out/src/integrations/terminal/get-latest-output.js:35:69)
  at TerminalProcess.emitCurrentTerminalContents (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:26:92)
  at TerminalProcess.runWithoutShellIntegration (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:366:20)
  at async TerminalProcess.run (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:47:13)
  at async Context.<anonymous> (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.test.js:119:13)
FakeTimers: clearTimeout was invoked to clear a native timer instead of one created by this library.
To automatically clean-up native timers, use `shouldClearNativeTimers`.
      ✔ should handle a longer running command (3007ms)
[TerminalProcess] Starting command: "echo 'Line 1' 'Line 2'"
[TerminalProcess] Shell integration available: false
[TerminalProcess] Terminal ID: Cline
Error capturing terminal output: Error: Failed to read from clipboard: HostProvider not setup. Call HostProvider.initialize() first.
  at readTextFromClipboard (/Users/sjf/cline/out/src/utils/env.js:39:15)
  at getLatestTerminalOutput (/Users/sjf/cline/out/src/integrations/terminal/get-latest-output.js:35:69)
  at TerminalProcess.emitCurrentTerminalContents (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:26:92)
  at TerminalProcess.runWithoutShellIntegration (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:366:20)
  at async TerminalProcess.run (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:47:13)
      ✔ should execute a command with arguments
[TerminalProcess] Starting command: "echo "Line 1" && echo 'Line 2'"
[TerminalProcess] Shell integration available: false
[TerminalProcess] Terminal ID: Cline
Error capturing terminal output: Error: Failed to read from clipboard: HostProvider not setup. Call HostProvider.initialize() first.
  at readTextFromClipboard (/Users/sjf/cline/out/src/utils/env.js:39:15)
  at getLatestTerminalOutput (/Users/sjf/cline/out/src/integrations/terminal/get-latest-output.js:35:69)
  at TerminalProcess.emitCurrentTerminalContents (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:26:92)
  at TerminalProcess.runWithoutShellIntegration (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:366:20)
  at async TerminalProcess.run (/Users/sjf/cline/out/src/integrations/terminal/TerminalProcess.js:47:13)
      ✔ should execute a command with quotes
  ```

* Create brown-papayas-protect.md

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 16:55:21 -07:00
yuvalman ef4d11df19 fix: circular dependency that affect the github workflow Tests / test (pull_request) (#5317)
* fix: circular dependency that affect test env

* fix: circular dependency that affect test env
2025-08-04 00:38:41 +01:00
github-actions[bot] 23dec509bc v3.20.6 Release Notes (#5326)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

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: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 16:24:15 -07:00
celestial-vault 07ab6b19b8 check auth after initialize cacheservice (#5325)
* initialize cachService in controller constructor; remove authService as a class level variable on Controller

* changeset
2025-08-03 16:19:40 -07:00
Bee 0ddef94d1f feat: use auth callback handling with custom AuthHandler (#5223)
* feat: use auth callback handling with custom AuthHandler

- Add AuthHandler class to manage OAuth flow with local HTTP server
- Move callback logic from extension.ts to SharingUriHandler, making that shared between the original and new authentication ways
- Enabling Custom HTTP for "core only" environments
- Async starting and stopping HTTP server
2025-08-02 15:10:16 -07:00
Bee b9ae83b1cd fix: standalone navbar style with chat layout refactor (#5308)
* fix: standalone navbar style with chat layout refactor

* Update webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-02 14:17:38 -07:00
Sarah Fortune e4eaf34827 test: Fix and re-enable unit tests (#5298)
* test: Fix and re-enable unit tests

Re-enable unit tests in CI workflow that were previously disabled

The cline-api test requires VSCode SDK which cannot be easily mocked in unit tests,
so it has been moved to integration tests where the full VSCode environment is available.

The @google/genai module is ES6-only which causes issues when running integration tests
compiled to CommonJS. A mock implementation has been added and the module resolution
is intercepted in test-setup.js to use the mock instead.

The bedrock unit tests for getModelId() functionality are removed as they were failing
and fixing them is out of scope for this PR.

- Move cline-api.test.ts from exports to test directory as it depends on VSCode SDK
- Add gemini-mock.test.ts to mock @google/genai ES6 module for CommonJS compatibility
- Add module interception in test-setup.js to redirect @google/genai to mock
- Remove failing bedrock unit tests introduced in PR #4209 (out of scope)

* Update src/api/providers/__tests__/bedrock.test.ts

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

* Formatting

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-08-02 01:47:27 +01:00
github-actions[bot] 6d3ed43c74 v3.20.5 Release Notes (#5297)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.20.5

---------

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: pashpashpash <nik@cline.bot>
2025-08-01 16:50:04 -07:00
celestial-vault cbb67b48f2 fix secrets persistence (#5296) 2025-08-01 16:41:14 -07:00
Sarah Fortune a5f6a97be8 Fix eslint unit tests (#5295) 2025-08-01 23:16:18 +01:00
github-actions[bot] f309b062e7 v3.20.4 Release Notes
v3.20.4 Release Notes
2025-08-01 13:20:27 -07:00
canvrno 768df130ab Fix for delete task popup (#5260)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-01 13:05:21 -07:00
Toshii 9980cb0938 fix grok browser_user (#5278) 2025-08-01 10:14:19 -07:00
Ara aca4f842fa Update Cerebras models (#5282)
* Update Cerebras models

* Add changeset

* Modify completion token limits

* Split qwen3 coder into free/paid

* Change -paid to base model name

* Update Cerebras models

* Update Cerebras models

* Update Cerebras models

* Update api.ts

* Update Cerebras models

---------

Co-authored-by: Kevin Taylor <kevin.taylor@cerebras.net>
2025-08-01 01:11:53 -07:00
Bee 3fc91e2afe fix: E2E test stability by reordering sidebar and notification setup (#5279)
* fix: E2E test stability by reordering sidebar and notification setup

- Extract editor menu locator to variable for better readability
- Move sidebar opening to page fixture to ensure it's available earlier
- Wait for chat input visibility before disabling notifications
- Prevents race conditions in test initialization

* fix
2025-07-31 18:03:14 -07:00
celestial-vault 5f4700ce95 Move apiconfiguration to cache layer (#5210)
* remove chatSettings object

* use cache for apiCongfiguration state

* add state persistence debounced, batch state updates, make setters synchronous

* fix types after merge conflicts

* fix global state reset

* remove clearCache; make dispose function private; remove vscode api dependency; call reInitialize in reset functions instead of dispose/initialize
2025-07-31 16:58:47 -07:00
Jim Tang dbaf5e3ee3 Update system.ts for formating the code. (#5270) 2025-07-31 16:19:01 -07:00
Toshii 576176c24f add grok4 to advanced list (#5276) 2025-07-31 14:54:45 -07:00
Akshay Raj Gollahalli c8abcbfdf9 Do not ignore pkg folder (#4483) (#4505) 2025-07-31 12:11:31 -07:00
celestial-vault 8e984f2d98 clean up getStateToPostToWebview in preparation for migration to StateManager service (#5266) 2025-07-31 11:47:06 -07:00
github-actions[bot] 81564faa4e v3.20.3 Release Notes (#5185)
* changeset version bump

* Updating CHANGELOG.md format

* releaseee

---------

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: pashpashpash <nik@cline.bot>
2025-07-30 21:49:57 -07:00
pashpashpash f8b5f1fd72 adding redirectUrl to credits purchasing experience (#5158) 2025-07-30 17:43:04 -07:00
celestial-vault 2eb57384ab remove useEffect (#5261) 2025-07-30 17:11:01 -07:00
Sarah Fortune c80bae504a Add a flag to build the webview without minification, compact, etc. (#5262)
When the webview is built wuth build:test:
* don't compact the compiled code
* don't minify
* use inline source maps (the embedded JCEF browser can't load source maps from .map files).
2025-07-30 19:53:36 -04:00
Sarah Fortune 80f955be9e Add vscode.workspace.findFiles to no-direct-vscode-api eslint rule. (#5263)
Add `vscode.workspace.findFiles` to the list of the Vscode API calls that should not be re-introduced to the extension unintentionally.
2025-07-30 19:49:15 -04:00
wangyijing130 7435ffcd2f fix: use Uri.from to generate valid diff URI (#4882)
* fix: use Uri.from to generate valid diff URI

* fix the conflicts for VscodeDiffViewProvider.ts has been moved

---------

Co-authored-by: wangyj20 <wangyj20@asiainfo.com>
2025-07-30 10:42:19 -07:00
Bee a05d438612 refactor: setup e2e tests to use shared mock server (#5245)
* refactor: e2e test setup to use Playwright projects with global server

- Replace globalSetup/globalTeardown with Playwright projects configuration
- Rename setup.ts to global.setup.ts and teardown.ts to global.teardown.ts
- Convert ClineApiServerMock to use shared global server instance
- Add proper dependency management between setup, tests, and cleanup phases
- Improve server connection tracking and cleanup handling

* Rename Playwright test project names to match

* IS_DEV

* update helpers
2025-07-30 00:16:08 -07:00
115 changed files with 5183 additions and 1355 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Clear errors from UI when retrying current task
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix input box positioning issue in chat view.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix Global Rules directory documentation for Linux/WSL systems
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
DeepSeek R1 0528 support under Hugging Face
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
remove duplicate tool registration for claude4-experimental
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add Huawei Cloud MaaS Provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixed token counting when using VSCode LM API provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Added Baseten Provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
fix: only focus on editor panel that is visible and active to stop input field stealing issue
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add Cerebras Qwen 3 235B instruct
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
trim input value for URL fields
+12 -15
View File
@@ -96,16 +96,15 @@ jobs:
- name: Build Tests and Extension
run: npm run pretest
# Unit Tests disabled due to module system conflicts between backend and webview-ui
# - name: Unit Tests
# run: npm run test:unit
- name: Unit Tests
run: npm run test:unit
# Run extension tests with coverage
- name: Extension Tests with Coverage
- name: Extension Integration Tests with Coverage
id: extension_coverage
continue-on-error: true
run: |
node ./scripts/test-ci.js > extension_coverage.txt 2>&1
node ./scripts/test-ci.js 2>&1 | tee extension_coverage.txt
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage extension_coverage.txt --type=extension --github-output --verbose
@@ -117,7 +116,7 @@ jobs:
cd webview-ui
# Ensure coverage dependency is installed
npm install --no-save @vitest/coverage-v8
npm run test:coverage > webview_coverage.txt 2>&1
npm run test:coverage 2>&1 | tee webview_coverage.txt
cd ..
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage webview-ui/webview_coverage.txt --type=webview --github-output --verbose
@@ -132,21 +131,19 @@ jobs:
path: |
extension_coverage.txt
webview-ui/webview_coverage.txt
retention-period: workflow # Artifacts are automatically deleted when the workflow completes
# Set the check as failed if any of the tests failed
- name: Print test results and check for failures
- name: Check for test failures
run: |
echo "Extension Tests Result: ${{ steps.extension_coverage.outcome }}"
cat extension_coverage.txt
echo "Webview Tests Result: ${{ steps.webview_coverage.outcome }}"
cat webview-ui/webview_coverage.txt
# Check if any of the test steps failed
# https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/accessing-contextual-information-about-workflow-runs#steps-context
if [ "${{ steps.extension_coverage.outcome }}" != "success" ]; then
echo "Extension Integration Tests failed, see previous step for test output."
fi
if [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
echo "Webview Tests failed, see previous step for test output."
fi
if [ "${{ steps.extension_coverage.outcome }}" != "success" ] || [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
echo "Tests failed."
exit 1
fi
+33
View File
@@ -1,5 +1,38 @@
# Changelog
## [3.20.8]
- Add navbar tooltips on hover
## [3.20.7]
- Fix circular dependency that affect the github workflow Tests / test (pull_request)
## [3.20.6]
- Fix login check on extension restart
## [3.20.5]
- Fix authentication persistence issues that could cause users to be logged out unexpectedly
## [3.20.4]
- Add new Cerebras models
- Update rate limits for existing Cerebras models
- Fix for delete task dialog
## [3.20.3]
- Add Huawei Cloud MaaS Provider (Thanks @ddling!)
- Add Cerebras Qwen 3 235B instruct model (Thanks @kevint-cerebras!)
- Add DeepSeek R1 0528 support under Hugging Face (Thanks @0ne0rZer0!)
- Fix Global Rules directory documentation for Linux/WSL systems
- Fix token counting when using VSCode LM API provider
- Fix input field stealing focus issue by only focusing on visible and active editor panels
- Fix duplicate tool registration for claude4-experimental
- Trim input value for URL fields
## [3.20.2]
- Fixed issue with sap ai core client credentials storage
@@ -34,25 +34,30 @@ directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, {
},
// Should allow other vscode API calls
{
code: `vscode.window.showInformationMessage("Hello")`,
filename: "test.ts",
code: `vscode.commands.registerCommand("Hello")`,
filename: "/foo/bar.ts",
},
// Should allow postMessage calls on other objects
{
code: `window.postMessage({ type: "test" }, "*")`,
filename: "test.ts",
filename: "/foo/bar.ts",
},
// Should allow variables named vscode but not calling postMessage
{
code: `const vscode = { other: "method" }; vscode.other()`,
filename: "test.ts",
filename: "/foo/bar.ts",
},
// Should allow vscode.postMessage in test files
{
code: `vscode.postMessage({ type: "newTask", text: message.text })`,
filename: "/foo/bar.test.ts",
},
],
invalid: [
// Should disallow vscode.postMessage in regular files
{
code: `vscode.postMessage({ type: "test", data: {} })`,
filename: "test.ts",
filename: "/foo/bar.ts",
errors: [
{
messageId: "useGrpcClient",
@@ -69,23 +74,13 @@ directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, {
},
],
},
// Should disallow vscode.postMessage in test files
{
code: `vscode.postMessage({ type: "newTask", text: message.text })`,
filename: "test.test.ts",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow property access for disallowed APIs
{
code: `const folders = vscode.workspace.workspaceFolders;`,
filename: "workspace.ts",
errors: [
{
messageId: "useHostBridge",
messageId: "useHostBridgeWorkspace",
},
],
},
+17 -7
View File
@@ -35,18 +35,24 @@ const disallowedApis = {
"vscode.env.openExternal": {
messageId: "useUtils",
},
// "vscode.window.showWarningMessage": {
// messageId: "useHostBridgeShowMessage",
// },
"vscode.window.showWarningMessage": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showOpenDialog": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showErrorMessage": {
messageId: "useHostBridgeShowMessage",
},
// "vscode.window.showInformationMessage": {
// messageId: "useHostBridgeShowMessage",
// },
"vscode.window.showInformationMessage": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showInputBox": {
messageId: "useHostBridge",
},
"vscode.workspace.findFiles": {
messageId: "useNative",
},
}
module.exports = createRule({
@@ -87,6 +93,10 @@ module.exports = createRule({
"Use utilities in @/utils instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useNative:
"Use a native Javascript API instead of calling the vscode API.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
},
schema: [],
},
@@ -187,7 +197,7 @@ module.exports = createRule({
if (filename.includes("/standalone/runtime-files/")) {
return true
}
// Skip unit tests
// Skip checking test files
if (filename.endsWith(".test.ts")) {
return true
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "claude-dev",
"version": "3.20.1",
"version": "3.20.5",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "claude-dev",
"version": "3.20.1",
"version": "3.20.5",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.37.0",
+3 -2
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.20.2",
"version": "3.20.8",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -119,7 +119,8 @@
{
"type": "webview",
"id": "claude-dev.SidebarProvider",
"name": ""
"name": "",
"icon": "assets/icons/icon.svg"
}
]
},
+16 -2
View File
@@ -13,6 +13,20 @@ export default defineConfig({
},
fullyParallel: true,
reporter: isCI ? [["github"], ["list"]] : [["list"]],
globalSetup: require.resolve("./src/test/e2e/utils/setup"),
globalTeardown: require.resolve("./src/test/e2e/utils/teardown"),
projects: [
{
name: "setup test environment",
testMatch: /global\.setup\.ts/,
},
{
name: "e2e tests",
testMatch: /.*\.test\.ts/,
dependencies: ["setup test environment"],
},
{
name: "cleanup test environment",
testMatch: /global\.teardown\.ts/,
dependencies: ["e2e tests"],
},
],
})
+8
View File
@@ -27,6 +27,8 @@ service ModelsService {
rpc updateApiConfigurationProto(UpdateApiConfigurationRequest) returns (Empty);
// Refreshes and returns Groq models
rpc refreshGroqModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns Baseten models
rpc refreshBasetenModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
}
// List of VS Code LM models
@@ -130,6 +132,7 @@ enum ApiProvider {
MOONSHOT = 27;
HUGGINGFACE = 28;
HUAWEI_CLOUD_MAAS = 29;
BASETEN = 30;
}
// Model info for OpenAI-compatible models
@@ -231,6 +234,7 @@ message ModelsApiConfiguration {
optional string groq_api_key = 59;
optional string hugging_face_api_key = 60;
optional string huawei_cloud_maas_api_key = 61;
optional string baseten_api_key = 62;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
@@ -259,6 +263,8 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo plan_mode_hugging_face_model_info = 123;
optional string plan_mode_huawei_cloud_maas_model_id = 124;
optional OpenRouterModelInfo plan_mode_huawei_cloud_maas_model_info = 125;
optional string plan_mode_baseten_model_id = 126;
optional OpenRouterModelInfo plan_mode_baseten_model_info = 127;
// Act mode configurations
optional ApiProvider act_mode_api_provider = 200;
@@ -287,6 +293,8 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo act_mode_hugging_face_model_info = 223;
optional string act_mode_huawei_cloud_maas_model_id = 224;
optional OpenRouterModelInfo act_mode_huawei_cloud_maas_model_info = 225;
optional string act_mode_baseten_model_id = 226;
optional OpenRouterModelInfo act_mode_baseten_model_info = 227;
repeated string favorited_model_ids = 300;
}
+1
View File
@@ -110,6 +110,7 @@ message UpdateSettingsRequest {
optional PlanActMode mode = 13;
optional string preferred_language = 14;
optional string openai_reasoning_effort = 15;
optional bool strict_plan_mode_enabled = 16;
}
// Complete API Configuration message
+4 -1
View File
@@ -84,6 +84,8 @@ message ShowSaveDialogRequest {
message ShowSaveDialogOptions {
optional string default_path = 1;
// A map of file types to extensions, e.g
// "Text Files": { "extensions": ["txt", "md"] }
map<string, FileExtensionList> filters = 2;
}
@@ -92,6 +94,7 @@ message FileExtensionList {
}
message ShowSaveDialogResponse {
// If the user cancelled the dialog, this will be empty.
optional string selected_path = 1;
}
@@ -129,4 +132,4 @@ message GetVisibleTabsRequest {
message GetVisibleTabsResponse {
repeated string paths = 1;
}
}
+48 -4
View File
@@ -10,8 +10,12 @@ import "cline/common.proto";
service WorkspaceService {
// Returns a list of the top level directories of the workspace.
rpc getWorkspacePaths(GetWorkspacePathsRequest) returns (GetWorkspacePathsResponse);
// Saves an open document if it's dirty
rpc saveOpenDocumentIfDirty(SaveOpenDocumentIfDirtyRequest) returns (cline.Empty);
// Saves an open document if it's open in the editor and has unsaved changes.
// Returns true if the document was saved, returns false if the document was not found, or did not
// need to be saved.
rpc saveOpenDocumentIfDirty(SaveOpenDocumentIfDirtyRequest) returns (SaveOpenDocumentIfDirtyResponse);
// Get diagnostics from the workspace.
rpc getDiagnostics(GetDiagnosticsRequest) returns (GetDiagnosticsResponse);
}
message GetWorkspacePathsRequest {
@@ -28,6 +32,46 @@ message GetWorkspacePathsResponse {
}
message SaveOpenDocumentIfDirtyRequest {
cline.Metadata metadata = 1;
string file_path = 2;
optional string file_path = 2;
}
message SaveOpenDocumentIfDirtyResponse {
// Returns true if the document was saved.
optional bool was_saved = 1;
}
message GetDiagnosticsRequest {
optional cline.Metadata metadata = 1;
}
message GetDiagnosticsResponse {
repeated FileDiagnostics file_diagnostics = 1;
}
message FileDiagnostics {
string file_path = 1;
repeated Diagnostic diagnostics = 2;
}
message Diagnostic {
string message = 1;
DiagnosticRange range = 2;
DiagnosticSeverity severity = 3;
optional string source = 4;
}
message DiagnosticRange {
DiagnosticPosition start = 1;
DiagnosticPosition end = 2;
}
message DiagnosticPosition {
int32 line = 1;
int32 character = 2;
}
enum DiagnosticSeverity {
DIAGNOSTIC_ERROR = 0;
DIAGNOSTIC_WARNING = 1;
DIAGNOSTIC_INFORMATION = 2;
DIAGNOSTIC_HINT = 3;
}
Regular → Executable
+1
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env node
const { execSync } = require("child_process")
const esbuild = require("esbuild")
+2 -2
View File
@@ -40,11 +40,11 @@ async function generateWebviewProtobusClients(protobusServices) {
}
if (!rpc.responseStream) {
rpcs.push(` static async ${rpcName}(request: ${requestType}): Promise<${responseType}> {
return this.makeRequest("${rpcName}", request)
return this.makeUnaryRequest("${rpcName}", request, ${requestType}.toJSON, ${responseType}.fromJSON)
}`)
} else {
rpcs.push(` static ${rpcName}(request: ${requestType}, callbacks: Callbacks<${responseType}>): ()=>void {
return this.makeStreamingRequest("${rpcName}", request, callbacks)
return this.makeStreamingRequest("${rpcName}", request, ${requestType}.toJSON, ${responseType}.fromJSON, callbacks)
}`)
}
}
Regular → Executable
View File
+8
View File
@@ -32,6 +32,7 @@ import { GroqHandler } from "./providers/groq"
import { Mode } from "@shared/storage/types"
import { HuggingFaceHandler } from "./providers/huggingface"
import { HuaweiCloudMaaSHandler } from "./providers/huawei-cloud-maas"
import { BasetenHandler } from "./providers/baseten"
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
@@ -257,6 +258,13 @@ function createHandlerForProvider(
groqModelInfo: mode === "plan" ? options.planModeGroqModelInfo : options.actModeGroqModelInfo,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "baseten":
return new BasetenHandler({
basetenApiKey: options.basetenApiKey,
basetenModelId: mode === "plan" ? options.planModeBasetenModelId : options.actModeBasetenModelId,
basetenModelInfo: mode === "plan" ? options.planModeBasetenModelInfo : options.actModeBasetenModelInfo,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "sapaicore":
return new SapAiCoreHandler({
sapAiCoreClientId: options.sapAiCoreClientId,
+85 -84
View File
@@ -612,101 +612,102 @@ describe("AwsBedrockHandler", () => {
})
})
describe("getModelId", () => {
it("should return raw model ID for custom models", async () => {
const customOptions: ApiHandlerOptions = {
...mockOptions,
actModeAwsBedrockCustomSelected: true,
actModeApiModelId:
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
}
const customHandler = new AwsBedrockHandler(customOptions)
// TODO: Re-enable or remove these tests.
// describe("getModelId", () => {
// it("should return raw model ID for custom models", async () => {
// const customOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId:
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// }
// const customHandler = new AwsBedrockHandler(customOptions)
const modelId = await customHandler.getModelId()
modelId.should.equal(
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
)
})
// const modelId = await customHandler.getModelId()
// modelId.should.equal(
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// )
// })
it("should not encode custom model IDs with slashes", async () => {
const customOptions: ApiHandlerOptions = {
...mockOptions,
actModeAwsBedrockCustomSelected: true,
actModeApiModelId: "my-namespace/my-custom-model",
}
const customHandler = new AwsBedrockHandler(customOptions)
// it("should not encode custom model IDs with slashes", async () => {
// const customOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId: "my-namespace/my-custom-model",
// }
// const customHandler = new AwsBedrockHandler(customOptions)
const modelId = await customHandler.getModelId()
modelId.should.equal("my-namespace/my-custom-model")
modelId.should.not.match(/%2F/)
})
// const modelId = await customHandler.getModelId()
// modelId.should.equal("my-namespace/my-custom-model")
// modelId.should.not.match(/%2F/)
// })
it("should apply cross-region prefix for non-custom models when enabled", async () => {
const crossRegionOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "us-west-2",
}
const crossRegionHandler = new AwsBedrockHandler(crossRegionOptions)
// it("should apply cross-region prefix for non-custom models when enabled", async () => {
// const crossRegionOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "us-west-2",
// }
// const crossRegionHandler = new AwsBedrockHandler(crossRegionOptions)
const modelId = await crossRegionHandler.getModelId()
modelId.should.equal("us.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await crossRegionHandler.getModelId()
// modelId.should.equal("us.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should apply EU cross-region prefix", async () => {
const euOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "eu-central-1",
}
const euHandler = new AwsBedrockHandler(euOptions)
// it("should apply EU cross-region prefix", async () => {
// const euOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "eu-central-1",
// }
// const euHandler = new AwsBedrockHandler(euOptions)
const modelId = await euHandler.getModelId()
modelId.should.equal("eu.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await euHandler.getModelId()
// modelId.should.equal("eu.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should apply APAC cross-region prefix", async () => {
const apacOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "ap-northeast-1",
}
const apacHandler = new AwsBedrockHandler(apacOptions)
// it("should apply APAC cross-region prefix", async () => {
// const apacOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "ap-northeast-1",
// }
// const apacHandler = new AwsBedrockHandler(apacOptions)
const modelId = await apacHandler.getModelId()
modelId.should.equal("apac.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await apacHandler.getModelId()
// modelId.should.equal("apac.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should not apply cross-region prefix for custom models even when enabled", async () => {
const customCrossRegionOptions: ApiHandlerOptions = {
...mockOptions,
actModeAwsBedrockCustomSelected: true,
actModeApiModelId: "arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model",
awsUseCrossRegionInference: true,
}
const customCrossRegionHandler = new AwsBedrockHandler(customCrossRegionOptions)
// it("should not apply cross-region prefix for custom models even when enabled", async () => {
// const customCrossRegionOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId: "arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model",
// awsUseCrossRegionInference: true,
// }
// const customCrossRegionHandler = new AwsBedrockHandler(customCrossRegionOptions)
const modelId = await customCrossRegionHandler.getModelId()
modelId.should.equal("arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model")
})
// const modelId = await customCrossRegionHandler.getModelId()
// modelId.should.equal("arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model")
// })
it("should handle UltraThink model ARN correctly", async () => {
const ultraThinkOptions: ApiHandlerOptions = {
...mockOptions,
actModeAwsBedrockCustomSelected: true,
actModeApiModelId:
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
actModeAwsBedrockCustomModelBaseId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
}
const ultraThinkHandler = new AwsBedrockHandler(ultraThinkOptions)
// it("should handle UltraThink model ARN correctly", async () => {
// const ultraThinkOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId:
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// actModeAwsBedrockCustomModelBaseId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
// }
// const ultraThinkHandler = new AwsBedrockHandler(ultraThinkOptions)
const modelId = await ultraThinkHandler.getModelId()
// Should return the raw ARN without any encoding
modelId.should.equal(
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
)
modelId.should.not.match(/%2F/)
modelId.should.not.match(/%3A/)
})
})
// const modelId = await ultraThinkHandler.getModelId()
// // Should return the raw ARN without any encoding
// modelId.should.equal(
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// )
// modelId.should.not.match(/%2F/)
// modelId.should.not.match(/%3A/)
// })
// })
})
+165
View File
@@ -0,0 +1,165 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { BasetenModelId, ModelInfo, basetenDefaultModelId, basetenModels } from "@shared/api"
import { calculateApiCostOpenAI } from "../../utils/cost"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
interface BasetenHandlerOptions {
basetenApiKey?: string
basetenModelId?: string
basetenModelInfo?: ModelInfo
apiModelId?: string // For backward compatibility
}
export class BasetenHandler implements ApiHandler {
private options: BasetenHandlerOptions
private client: OpenAI | undefined
constructor(options: BasetenHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.basetenApiKey) {
throw new Error("Baseten API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://inference.baseten.co/v1",
apiKey: this.options.basetenApiKey,
})
} catch (error) {
throw new Error(`Error creating Baseten client: ${error.message}`)
}
}
return this.client
}
/**
* Gets the optimal max_tokens based on model capabilities
*/
private getOptimalMaxTokens(model: { id: BasetenModelId; info: ModelInfo }): number {
// Use model-specific max tokens if available
if (model.info.maxTokens && model.info.maxTokens > 0) {
return model.info.maxTokens
}
// Default fallback
return 8192
}
getModel(): { id: BasetenModelId; info: ModelInfo } {
// First priority: basetenModelId and basetenModelInfo
const basetenModelId = this.options.basetenModelId
const basetenModelInfo = this.options.basetenModelInfo
if (basetenModelId && basetenModelInfo) {
return { id: basetenModelId as BasetenModelId, info: basetenModelInfo }
}
// Second priority: basetenModelId with static model info
if (basetenModelId && basetenModelId in basetenModels) {
const id = basetenModelId as BasetenModelId
return { id, info: basetenModels[id] }
}
// Third priority: apiModelId (for backward compatibility)
const apiModelId = this.options.apiModelId
if (apiModelId && apiModelId in basetenModels) {
const id = apiModelId as BasetenModelId
return { id, info: basetenModels[id] }
}
// Default fallback
return {
id: basetenDefaultModelId,
info: basetenModels[basetenDefaultModelId],
}
}
private async *yieldUsage(modelInfo: ModelInfo, usage: any): ApiStream {
if (usage.prompt_tokens || usage.completion_tokens) {
const cost = calculateApiCostOpenAI(modelInfo, usage.prompt_tokens || 0, usage.completion_tokens || 0)
yield {
type: "usage",
inputTokens: usage.prompt_tokens || 0,
outputTokens: usage.completion_tokens || 0,
cacheWriteTokens: 0,
cacheReadTokens: 0,
totalCost: cost,
}
}
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const maxTokens = this.getOptimalMaxTokens(model)
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const stream = await client.chat.completions.create({
model: model.id,
max_tokens: maxTokens,
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature: 0,
})
let didOutputUsage = false
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
// Handle reasoning field if present (for reasoning models with parsed output)
if ((delta as any)?.reasoning) {
const reasoningContent = (delta as any).reasoning as string
yield {
type: "reasoning",
reasoning: reasoningContent,
}
continue
}
// Handle content field
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
// Handle usage information - only output once
if (!didOutputUsage && chunk.usage) {
yield* this.yieldUsage(model.info, chunk.usage)
didOutputUsage = true
}
}
}
/**
* Checks if the current model supports vision/images
*/
supportsImages(): boolean {
const model = this.getModel()
return model.info.supportsImages === true
}
/**
* Checks if the current model supports tools
*/
supportsTools(): boolean {
const model = this.getModel()
// Baseten models support tools via OpenAI-compatible API
return true
}
}
+10 -3
View File
@@ -102,6 +102,7 @@ export class CerebrasHandler implements ApiHandler {
messages: cerebrasMessages,
temperature: 0,
stream: true,
max_tokens: this.getModel().info.maxTokens,
})
// Handle streaming response
@@ -175,9 +176,15 @@ export class CerebrasHandler implements ApiHandler {
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in cerebrasModels) {
const id = modelId as CerebrasModelId
const originalModelId = this.options.apiModelId
let apiModelId = originalModelId
if (originalModelId === "qwen-3-coder-480b-free") {
apiModelId = "qwen-3-coder-480b"
return { id: apiModelId, info: cerebrasModels[originalModelId as CerebrasModelId] }
}
if (originalModelId && originalModelId in cerebrasModels) {
const id = originalModelId as CerebrasModelId
return { id, info: cerebrasModels[id] }
}
return {
+53
View File
@@ -0,0 +1,53 @@
// Mock for @google/genai module to avoid ESM compatibility issues in tests
export class GoogleGenAI {
constructor(options: any) {
// Mock constructor
}
models = {
generateContentStream: async (params: any) => {
// Mock implementation that returns an async iterator
return {
async *[Symbol.asyncIterator]() {
yield {
text: "Mock response",
candidates: [],
usageMetadata: {
promptTokenCount: 100,
candidatesTokenCount: 50,
thoughtsTokenCount: 0,
cachedContentTokenCount: 0,
},
}
},
}
},
countTokens: async (params: any) => {
// Mock token counting
return {
totalTokens: 100,
}
},
}
}
// Export mock types
export interface GenerateContentConfig {
httpOptions?: any
systemInstruction?: string
temperature?: number
thinkingConfig?: any
}
export interface GenerateContentResponseUsageMetadata {
promptTokenCount?: number
candidatesTokenCount?: number
thoughtsTokenCount?: number
cachedContentTokenCount?: number
}
export interface Part {
thought?: boolean
text?: string
}
+13 -71
View File
@@ -252,77 +252,19 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
}
private async countTokens(text: string | vscode.LanguageModelChatMessage): Promise<number> {
// For Claude models, use character-to-token ratio instead of VSCode LM's inaccurate counting
if (this.isClaudeModel()) {
const textContent = typeof text === "string" ? text : this.extractTextFromMessage(text)
// Use 4 character-to-token ratio for Claude models
return Math.ceil(textContent.length / 4)
}
// Check for required dependencies
if (!this.client) {
console.warn("Cline <Language Model API>: No client available for token counting")
return 0
}
if (!this.currentRequestCancellation) {
console.warn("Cline <Language Model API>: No cancellation token available for token counting")
return 0
}
// Validate input
if (!text) {
console.debug("Cline <Language Model API>: Empty text provided for token counting")
return 0
}
try {
// Handle different input types
let tokenCount: number
if (typeof text === "string") {
tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
} else if (text instanceof vscode.LanguageModelChatMessage) {
// For chat messages, ensure we have content
if (!text.content || (Array.isArray(text.content) && text.content.length === 0)) {
console.debug("Cline <Language Model API>: Empty chat message content")
return 0
}
tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
} else {
console.warn("Cline <Language Model API>: Invalid input type for token counting")
return 0
}
// Validate the result
if (typeof tokenCount !== "number") {
console.warn("Cline <Language Model API>: Non-numeric token count received:", tokenCount)
return 0
}
if (tokenCount < 0) {
console.warn("Cline <Language Model API>: Negative token count received:", tokenCount)
return 0
}
return tokenCount
} catch (error) {
// Handle specific error types
if (error instanceof vscode.CancellationError) {
console.debug("Cline <Language Model API>: Token counting cancelled by user")
return 0
}
const errorMessage = error instanceof Error ? error.message : "Unknown error"
console.warn("Cline <Language Model API>: Token counting failed:", errorMessage)
// Log additional error details if available
if (error instanceof Error && error.stack) {
console.debug("Token counting error stack:", error.stack)
}
return 0 // Fallback to prevent stream interruption
}
/**
* NOTE (intentional trade-off):
* We use a coarse chars/4 heuristic here instead of a real tokenizer (e.g., js-tiktoken with o200k_base).
* Rationale:
* - Avoid pulling multiMB rank files and increasing the extension install/download size.
* - Eliminate encoder lifecycle/memory concerns in long-running sessions.
* Consequences:
* - This is not model-accurate and can under/over-estimate tokens, especially with tool/function calls.
* - It is “good enough” for budgeting/context checks, and we accept the inaccuracy by design.
* If precise accounting becomes a requirement, reintroduce a tokenizer behind a feature flag or backend-only path.
*/
const textContent = typeof text === "string" ? text : this.extractTextFromMessage(text)
return Math.ceil((textContent || "").length / 4)
}
private async calculateTotalInputTokens(vsCodeLmMessages: vscode.LanguageModelChatMessage[]): Promise<number> {
+412
View File
@@ -0,0 +1,412 @@
import { describe, it, beforeEach, afterEach } from "mocha"
import { expect } from "chai"
import * as sinon from "sinon"
import { handleGrpcRequest, handleGrpcRequestCancel, getRequestRegistry } from "./grpc-handler"
import { Controller } from "@core/controller"
import { GrpcRequest, GrpcCancel } from "@shared/WebviewMessage"
import { serviceHandlers } from "@generated/hosts/vscode/protobus-services"
describe("grpc-handler", () => {
let sandbox: sinon.SinonSandbox
let mockController: sinon.SinonStubbedInstance<Controller>
let mockUnaryHandler: sinon.SinonStub
let mockUnaryFailingHandler: sinon.SinonStub
let mockStreamingHandler: sinon.SinonStub
let mockStreamingFailingHandler: sinon.SinonStub
const serviceName = "cline.TestService"
const mockResponse = { result: "result-1234" }
beforeEach(() => {
sandbox = sinon.createSandbox()
// Create a mock controller
mockController = {
postMessageToWebview: sandbox.stub().resolves(),
} as any
// Create mock service handlers
mockUnaryHandler = sandbox.stub().resolves(mockResponse)
mockStreamingHandler = sandbox.stub().resolves()
mockUnaryFailingHandler = sandbox.stub().rejects(new Error("Test error unary"))
mockStreamingFailingHandler = sandbox.stub().rejects(new Error("Stream error"))
serviceHandlers[serviceName] = {
testUnary: mockUnaryHandler,
testUnaryFailing: mockUnaryFailingHandler,
testStreaming: mockStreamingHandler,
testStreamingFailing: mockStreamingFailingHandler,
}
})
afterEach(() => {
sandbox.restore()
})
describe("handleGrpcRequest", () => {
describe("Unary requests", () => {
it("should handle successful unary requests", async () => {
const request: GrpcRequest = {
service: serviceName,
method: "testUnary",
message: { input: "test" },
request_id: "test-123",
is_streaming: false,
}
await handleGrpcRequest(mockController as any, request)
// Verify the handler was called
expect(mockUnaryHandler.calledOnce).to.be.true
expect(mockUnaryHandler.firstCall.args[0]).to.equal(mockController)
expect(mockUnaryHandler.firstCall.args[1]).to.deep.equal({ input: "test" })
// Verify the response was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: mockResponse,
request_id: "test-123",
},
})
})
it("should handle errors in unary requests", async () => {
const request: GrpcRequest = {
service: serviceName,
method: "testUnaryFailing",
message: { input: "test" },
request_id: "test-456",
is_streaming: false,
}
await handleGrpcRequest(mockController as any, request)
// Verify the error response was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage).to.deep.equal({
type: "grpc_response",
grpc_response: {
error: "Test error unary",
request_id: "test-456",
is_streaming: false,
},
})
})
it("should handle unknown service errors", async () => {
const request: GrpcRequest = {
service: "UnknownService",
method: "someMethod",
message: {},
request_id: "test-789",
is_streaming: false,
}
await handleGrpcRequest(mockController as any, request)
// Verify the error response was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage.type).to.equal("grpc_response")
expect(sentMessage.grpc_response?.error).to.include("Unknown service: UnknownService")
expect(sentMessage.grpc_response?.request_id).to.equal("test-789")
})
it("should handle unknown method errors", async () => {
const request: GrpcRequest = {
service: serviceName,
method: "unknownMethod",
message: {},
request_id: "test-999",
is_streaming: false,
}
await handleGrpcRequest(mockController as any, request)
// Verify the error response was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage.type).to.equal("grpc_response")
expect(sentMessage.grpc_response?.error).to.include("Unknown rpc: cline.TestService.unknownMethod")
expect(sentMessage.grpc_response?.request_id).to.equal("test-999")
})
})
describe("Streaming requests", () => {
it("should handle successful streaming requests", async () => {
// Set up a streaming handler that sends multiple responses
const request: GrpcRequest = {
service: serviceName,
method: "testStreaming",
message: { input: "stream" },
request_id: "stream-123",
is_streaming: true,
}
// Reset the mock and set up the handler using callsFake
mockStreamingHandler.reset()
mockStreamingHandler.callsFake(async (controller: any, message: any, responseStream: any, requestId: string) => {
// Simulate streaming multiple messages
await responseStream({ value: 1 }, false, 0)
await responseStream({ value: 2 }, false, 1)
await responseStream({ value: 3 }, true, 2) // Last message
})
await handleGrpcRequest(mockController as any, request)
// Verify the handler was called
expect(mockStreamingHandler.calledOnce).to.be.true
expect(mockStreamingHandler.firstCall.args[0]).to.equal(mockController)
expect(mockStreamingHandler.firstCall.args[1]).to.deep.equal({ input: "stream" })
expect(mockStreamingHandler.firstCall.args[3]).to.equal("stream-123")
// Verify all streaming responses were sent
expect(mockController.postMessageToWebview.callCount).to.equal(3)
// Check all responses
expect(mockController.postMessageToWebview.firstCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { value: 1 },
request_id: "stream-123",
is_streaming: true,
sequence_number: 0,
},
})
expect(mockController.postMessageToWebview.secondCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { value: 2 },
request_id: "stream-123",
is_streaming: true,
sequence_number: 1,
},
})
expect(mockController.postMessageToWebview.thirdCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { value: 3 },
request_id: "stream-123",
is_streaming: false, // Last message has is_streaming: false
sequence_number: 2,
},
})
})
it("should handle errors in streaming requests", async () => {
const request: GrpcRequest = {
service: serviceName,
method: "testStreamingFailing",
message: { input: "stream" },
request_id: "stream-456",
is_streaming: true,
}
await handleGrpcRequest(mockController as any, request)
// Verify the error response was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage).to.deep.equal({
type: "grpc_response",
grpc_response: {
error: "Stream error",
request_id: "stream-456",
is_streaming: false,
},
})
})
it("should handle streaming with message, error, then another message", async () => {
// This test simulates a scenario where:
// 1. First message is sent successfully
// 2. An error occurs
// 3. Another message is attempted (which should not be sent after error)
const request: GrpcRequest = {
service: serviceName,
method: "testStreaming",
message: { input: "stream-with-error" },
request_id: "stream-error-mid",
is_streaming: true,
}
// Reset the mock and set up the handler to throw an error after being called
mockStreamingHandler.reset()
mockStreamingHandler.callsFake(async (controller: any, message: any, responseStream: any, requestId: string) => {
// Send first message successfully
await responseStream({ value: "first" }, false, 0)
// Throw an error
throw new Error("Mid-stream error")
})
await handleGrpcRequest(mockController as any, request)
// Verify the handler was called
expect(mockStreamingHandler.calledOnce).to.be.true
// Verify that we got the first message and then the error
expect(mockController.postMessageToWebview.callCount).to.equal(2)
// Check first message was sent successfully
expect(mockController.postMessageToWebview.firstCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { value: "first" },
request_id: "stream-error-mid",
is_streaming: true,
sequence_number: 0,
},
})
// Check error response was sent
expect(mockController.postMessageToWebview.secondCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
error: "Mid-stream error",
request_id: "stream-error-mid",
is_streaming: false,
},
})
// Try to send another message after the error (simulating what might happen
// if the handler tried to continue after an error)
const responseStream = mockStreamingHandler.firstCall.args[2]
// This should still work as the responseStream function is still valid
await responseStream({ value: "after-error" }, false, 1)
// Verify we now have 3 total calls (first message, error, after-error message)
expect(mockController.postMessageToWebview.callCount).to.equal(3)
// Verify the message after error was still sent
// (In a real scenario, the handler would have stopped due to the error,
// but this tests that the responseStream function itself still works)
expect(mockController.postMessageToWebview.thirdCall.args[0]).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { value: "after-error" },
request_id: "stream-error-mid",
is_streaming: true,
sequence_number: 1,
},
})
})
})
describe("handleGrpcRequestCancel", () => {
it("should cancel an active request", async () => {
// Register a request in the registry
const registry = getRequestRegistry()
const cleanupStub = sandbox.stub()
registry.registerRequest("cancel-123", cleanupStub)
const cancelRequest: GrpcCancel = {
request_id: "cancel-123",
}
await handleGrpcRequestCancel(mockController as any, cancelRequest)
// Verify the cleanup was called
expect(cleanupStub.calledOnce).to.be.true
// Verify the cancellation confirmation was sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
const sentMessage = mockController.postMessageToWebview.firstCall.args[0]
expect(sentMessage).to.deep.equal({
type: "grpc_response",
grpc_response: {
message: { cancelled: true },
request_id: "cancel-123",
is_streaming: false,
},
})
// Verify the request was removed from the registry
expect(registry.hasRequest("cancel-123")).to.be.false
})
it("should handle cancellation of non-existent request", async () => {
const cancelRequest: GrpcCancel = {
request_id: "non-existent",
}
await handleGrpcRequestCancel(mockController as any, cancelRequest)
// Verify no message was sent (request not found)
expect(mockController.postMessageToWebview.called).to.be.false
})
it("should handle cleanup errors gracefully", async () => {
// Register a request with a failing cleanup
const registry = getRequestRegistry()
const cleanupStub = sandbox.stub().throws(new Error("Cleanup failed"))
registry.registerRequest("cancel-error", cleanupStub)
const cancelRequest: GrpcCancel = {
request_id: "cancel-error",
}
// Should not throw
await handleGrpcRequestCancel(mockController as any, cancelRequest)
// Verify the cleanup was attempted
expect(cleanupStub.calledOnce).to.be.true
// Verify the cancellation confirmation was still sent
expect(mockController.postMessageToWebview.calledOnce).to.be.true
// Verify the request was removed despite the error
expect(registry.hasRequest("cancel-error")).to.be.false
})
})
describe("Concurrent requests", () => {
it("should handle concurrent requests", async () => {
// Set up handlers
mockUnaryHandler.resolves({ result: "unary" })
mockStreamingHandler.callsFake(async (controller: any, message: any, responseStream: any) => {
await responseStream({ value: "stream1" }, false, 0)
await responseStream({ value: "stream2" }, true, 1)
})
// Send multiple requests concurrently
const requests = [
handleGrpcRequest(mockController as any, {
service: serviceName,
method: "testUnary",
message: { id: 1 },
request_id: "concurrent-1",
is_streaming: false,
}),
handleGrpcRequest(mockController as any, {
service: serviceName,
method: "testStreaming",
message: { id: 2 },
request_id: "concurrent-2",
is_streaming: true,
}),
handleGrpcRequest(mockController as any, {
service: serviceName,
method: "testUnary",
message: { id: 3 },
request_id: "concurrent-3",
is_streaming: false,
}),
]
await Promise.all(requests)
// Verify all handlers were called
expect(mockUnaryHandler.callCount).to.equal(2)
expect(mockStreamingHandler.callCount).to.equal(1)
// Verify all responses were sent (2 unary + 2 streaming)
expect(mockController.postMessageToWebview.callCount).to.equal(4)
})
})
})
})
+81 -153
View File
@@ -1,6 +1,7 @@
import { Controller } from "./index"
import { serviceHandlers } from "@generated/hosts/vscode/protobus-services"
import { GrpcRequestRegistry } from "./grpc-request-registry"
import { GrpcCancel, GrpcRequest } from "@/shared/WebviewMessage"
/**
* Type definition for a streaming response handler
@@ -12,153 +13,34 @@ export type StreamingResponseHandler<TResponse> = (
) => Promise<void>
/**
* Handles gRPC requests from the webview
* Handles a gRPC request from the webview.
*/
export class GrpcHandler {
constructor(private controller: Controller) {}
/**
* Handle a gRPC request from the webview
* @param service The service name
* @param method The method name
* @param message The request message
* @param requestId The request ID for response correlation
* @param isStreaming Whether this is a streaming request
* @returns The response message or error for unary requests, void for streaming requests
*/
async handleRequest(
service: string,
method: string,
message: any,
requestId: string,
isStreaming: boolean = false,
): Promise<{
message?: any
error?: string
request_id: string
} | void> {
try {
// If this is a streaming request, use the streaming handler
if (isStreaming) {
await this.handleStreamingRequest(service, method, message, requestId)
return
}
// Get the service handler from the config
const handler = getHandler(service, method)
// Handle unary request
return {
message: await handler(this.controller, message),
request_id: requestId,
}
} catch (error) {
console.log("Protobus error:", error)
return {
error: error instanceof Error ? error.message : String(error),
request_id: requestId,
}
}
}
/**
* Handle a streaming gRPC request
* @param service The service name
* @param method The method name
* @param message The request message
* @param requestId The request ID for response correlation
*/
private async handleStreamingRequest(service: string, method: string, message: any, requestId: string): Promise<void> {
// Create a response stream function
const responseStream: StreamingResponseHandler<any> = async (
response: any,
isLast: boolean = false,
sequenceNumber?: number,
) => {
await this.controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
message: response,
request_id: requestId,
is_streaming: !isLast,
sequence_number: sequenceNumber,
},
})
}
try {
// Get the service handler from the config
const handler = getHandler(service, method)
// Handle streaming request and pass the requestId to all streaming handlers
await handler(this.controller, message, responseStream, requestId)
// Don't send a final message here - the stream should stay open for future updates
// The stream will be closed when the client disconnects or when the service explicitly ends it
} catch (error) {
// Send error response
console.log("Protobus error:", error)
await this.controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
error: error instanceof Error ? error.message : String(error),
request_id: requestId,
is_streaming: false,
},
})
}
export async function handleGrpcRequest(controller: Controller, request: GrpcRequest): Promise<void> {
if (request.is_streaming) {
await handleStreamingRequest(controller, request)
} else {
await handleUnaryRequest(controller, request)
}
}
// Registry to track active gRPC requests and their cleanup functions
const requestRegistry = new GrpcRequestRegistry()
/**
* Handle a gRPC request from the webview
* @param controller The controller instance
* @param request The gRPC request
* Handles a gRPC unary request from the webview.
*
* Calls the handler using the service and method name, and then posts the result back to the webview.
*/
export async function handleGrpcRequest(
controller: Controller,
request: {
service: string
method: string
message: any
request_id: string
is_streaming?: boolean
},
) {
async function handleUnaryRequest(controller: Controller, request: GrpcRequest): Promise<void> {
try {
const grpcHandler = new GrpcHandler(controller)
// For streaming requests, handleRequest handles sending responses directly
if (request.is_streaming) {
try {
await grpcHandler.handleRequest(request.service, request.method, request.message, request.request_id, true)
} finally {
// Note: We don't automatically clean up here anymore
// The request will be cleaned up when it completes or is cancelled
}
return
}
// For unary requests, we get a response and send it back
const response = (await grpcHandler.handleRequest(
request.service,
request.method,
request.message,
request.request_id,
false,
)) as {
message?: any
error?: string
request_id: string
}
// Send the response back to the webview
// Get the service handler from the config
const handler = getHandler(request.service, request.method)
// Handle unary request
const response = await handler(controller, request.message)
// Send response to the webview
await controller.postMessageToWebview({
type: "grpc_response",
grpc_response: response,
grpc_response: {
message: response,
request_id: request.request_id,
},
})
} catch (error) {
// Send error response
@@ -168,22 +50,65 @@ export async function handleGrpcRequest(
grpc_response: {
error: error instanceof Error ? error.message : String(error),
request_id: request.request_id,
is_streaming: false,
},
})
}
}
/**
* Handle a gRPC request cancellation from the webview
* Handle a streaming gRPC request from the webview.
*
* Calls the handler using the service and method name, and creates a streaming response handler
* which posts results back to the webview.
*/
async function handleStreamingRequest(controller: Controller, request: GrpcRequest): Promise<void> {
// Create a response stream function
const responseStream: StreamingResponseHandler<any> = async (
response: any,
isLast: boolean = false,
sequenceNumber?: number,
) => {
await controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
message: response,
request_id: request.request_id,
is_streaming: !isLast,
sequence_number: sequenceNumber,
},
})
}
try {
// Get the service handler from the config
const handler = getHandler(request.service, request.method)
// Handle streaming request and pass the requestId to all streaming handlers
await handler(controller, request.message, responseStream, request.request_id)
// Don't send a final message here - the stream should stay open for future updates
// The stream will be closed when the client disconnects or when the service explicitly ends it
} catch (error) {
// Send error response
console.log("Protobus error:", error)
await controller.postMessageToWebview({
type: "grpc_response",
grpc_response: {
error: error instanceof Error ? error.message : String(error),
request_id: request.request_id,
is_streaming: false,
},
})
}
}
/**
* Handles a gRPC request cancellation from the webview.
* @param controller The controller instance
* @param request The cancellation request
*/
export async function handleGrpcRequestCancel(
controller: Controller,
request: {
request_id: string
},
) {
export async function handleGrpcRequestCancel(controller: Controller, request: GrpcCancel) {
const cancelled = requestRegistry.cancelRequest(request.request_id)
if (cancelled) {
@@ -201,6 +126,17 @@ export async function handleGrpcRequestCancel(
}
}
// Registry to track active gRPC requests and their cleanup functions
const requestRegistry = new GrpcRequestRegistry()
/**
* Get the request registry instance
* This allows other parts of the code to access the registry
*/
export function getRequestRegistry(): GrpcRequestRegistry {
return requestRegistry
}
function getHandler(serviceName: string, methodName: string): any {
// Get the service handler from the config
const serviceConfig = serviceHandlers[serviceName]
@@ -213,11 +149,3 @@ function getHandler(serviceName: string, methodName: string): any {
}
return handler
}
/**
* Get the request registry instance
* This allows other parts of the code to access the registry
*/
export function getRequestRegistry(): GrpcRequestRegistry {
return requestRegistry
}
+113 -109
View File
@@ -30,11 +30,13 @@ import * as path from "path"
import * as vscode from "vscode"
import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk"
import { getAllExtensionState, getGlobalState, getWorkspaceState, storeSecret, updateGlobalState } from "../storage/state"
import { CacheService, PersistenceErrorEvent } from "../storage/CacheService"
import { Task } from "../task"
import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler"
import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendAddToInputEvent } from "./ui/subscribeToAddToInput"
import { getLatestAnnouncementId } from "@/utils/announcements"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@@ -52,10 +54,7 @@ export class Controller {
workspaceTracker: WorkspaceTracker
mcpHub: McpHub
accountService: ClineAccountService
authService: AuthService
get latestAnnouncementId(): string {
return this.context.extension?.packageJSON?.version?.split(".").slice(0, 2).join(".") ?? ""
}
readonly cacheService: CacheService
constructor(
readonly context: vscode.ExtensionContext,
@@ -66,17 +65,45 @@ export class Controller {
HostProvider.get().logToChannel("ClineProvider instantiated")
this.postMessage = postMessage
this.accountService = ClineAccountService.getInstance()
this.cacheService = new CacheService(context)
const authService = AuthService.getInstance(this)
// Initialize cache service asynchronously - critical for extension functionality
this.cacheService
.initialize()
.then(() => {
authService.restoreRefreshTokenAndRetrieveAuthInfo()
})
.catch((error) => {
console.error("CRITICAL: Failed to initialize CacheService - extension may not function properly:", error)
})
// Set up persistence error recovery
this.cacheService.onPersistenceError = async ({ error }: PersistenceErrorEvent) => {
console.error("Cache persistence failed, recovering:", error)
try {
await this.cacheService.reInitialize()
await this.postStateToWebview()
HostProvider.window.showMessage({
type: ShowMessageType.WARNING,
message: "Saving settings to storage failed.",
})
} catch (recoveryError) {
console.error("Cache recovery failed:", recoveryError)
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
message: "Failed to save settings. Please restart the extension.",
})
}
}
this.workspaceTracker = new WorkspaceTracker()
this.mcpHub = new McpHub(
() => ensureMcpServersDirectoryExists(),
() => ensureSettingsDirectoryExists(this.context),
(msg) => this.postMessageToWebview(msg),
this.context.extension?.packageJSON?.version ?? "1.0.0",
)
this.accountService = ClineAccountService.getInstance()
this.authService = AuthService.getInstance(context)
this.authService.restoreRefreshTokenAndRetrieveAuthInfo()
// Clean up legacy checkpoints
cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath).catch((error) => {
@@ -111,12 +138,18 @@ export class Controller {
async handleSignOut() {
try {
// TODO: update to clineAccountId and then move clineApiKey to a clear function.
await storeSecret(this.context, "clineAccountId", undefined)
this.cacheService.setSecret("clineAccountId", undefined)
await updateGlobalState(this.context, "userInfo", undefined)
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", "openrouter"),
updateGlobalState(this.context, "actModeApiProvider", "openrouter"),
])
// Update API providers through cache service
const apiConfiguration = this.cacheService.getApiConfiguration()
const updatedConfig = {
...apiConfiguration,
planModeApiProvider: "openrouter" as ApiProvider,
actModeApiProvider: "openrouter" as ApiProvider,
}
this.cacheService.setApiConfiguration(updatedConfig)
await this.postStateToWebview()
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
@@ -136,8 +169,11 @@ export class Controller {
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
// Get API configuration from cache for immediate access
const apiConfiguration = this.cacheService.getApiConfiguration()
const {
apiConfiguration,
autoApprovalSettings,
browserSettings,
preferredLanguage,
@@ -150,6 +186,7 @@ export class Controller {
enableCheckpointsSetting,
isNewUser,
taskHistory,
strictPlanModeEnabled,
} = await getAllExtensionState(this.context)
const NEW_USER_TASK_COUNT_THRESHOLD = 10
@@ -181,12 +218,14 @@ export class Controller {
preferredLanguage,
openaiReasoningEffort,
mode,
strictPlanModeEnabled ?? false,
shellIntegrationTimeout,
terminalReuseEnabled ?? true,
terminalOutputLineLimit ?? 500,
defaultTerminalProfile ?? "default",
enableCheckpointsSetting ?? true,
await getCwd(getDesktopDir()),
this.cacheService,
task,
images,
files,
@@ -214,10 +253,6 @@ export class Controller {
*/
async handleWebviewMessage(message: WebviewMessage) {
switch (message.type) {
case "fetchMcpMarketplace": {
await this.fetchMcpMarketplace(message.bool)
break
}
case "grpc_request": {
if (message.grpc_request) {
await handleGrpcRequest(this, message.grpc_request)
@@ -230,9 +265,9 @@ export class Controller {
}
break
}
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
default: {
console.error("Received unhandled WebviewMessage type:", JSON.stringify(message))
}
}
}
@@ -254,14 +289,14 @@ export class Controller {
// Update API handler with new mode (buildApiHandler now selects provider based on mode)
if (this.task) {
const { apiConfiguration } = await getAllExtensionState(this.context)
const apiConfiguration = this.cacheService.getApiConfiguration()
this.task.api = buildApiHandler({ ...apiConfiguration, taskId: this.task.taskId }, modeToSwitchTo)
}
await this.postStateToWebview()
if (this.task) {
this.task.mode = modeToSwitchTo
this.task.updateMode(modeToSwitchTo)
if (this.task.taskState.isAwaitingPlanResponse && didSwitchToActMode) {
this.task.taskState.didRespondToPlanAskBySwitchingMode = true
// Use chatContent if provided, otherwise use default message
@@ -313,7 +348,7 @@ export class Controller {
async handleAuthCallback(customToken: string, provider: string | null = null) {
try {
await this.authService.handleAuthCallback(customToken, provider ? provider : "google")
await AuthService.getInstance(this).handleAuthCallback(customToken, provider ? provider : "google")
const clineProvider: ApiProvider = "cline"
@@ -321,27 +356,26 @@ export class Controller {
const { planActSeparateModelsSetting } = await getAllExtensionState(this.context)
const currentMode = await this.getCurrentMode()
// Get current API configuration from cache
const currentApiConfiguration = this.cacheService.getApiConfiguration()
let updatedConfig = { ...currentApiConfiguration }
if (planActSeparateModelsSetting) {
// Only update the current mode's provider
if (currentMode === "plan") {
await updateGlobalState(this.context, "planModeApiProvider", clineProvider)
updatedConfig.planModeApiProvider = clineProvider
} else {
await updateGlobalState(this.context, "actModeApiProvider", clineProvider)
updatedConfig.actModeApiProvider = clineProvider
}
} else {
// Update both modes to keep them in sync
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", clineProvider),
updateGlobalState(this.context, "actModeApiProvider", clineProvider),
])
updatedConfig.planModeApiProvider = clineProvider
updatedConfig.actModeApiProvider = clineProvider
}
// Get the updated API configuration (now includes the updated providers)
const { apiConfiguration } = await getAllExtensionState(this.context)
const updatedConfig = {
...apiConfiguration,
apiProvider: clineProvider,
}
// Update the API configuration through cache service
this.cacheService.setApiConfiguration(updatedConfig)
// Mark welcome view as completed since user has successfully logged in
await updateGlobalState(this.context, "welcomeViewCompleted", true)
@@ -460,31 +494,6 @@ export class Controller {
}
}
private async fetchMcpMarketplace(forceRefresh: boolean = false) {
try {
// Check if we have cached data
const cachedCatalog = (await getGlobalState(this.context, "mcpMarketplaceCatalog")) as
| McpMarketplaceCatalog
| undefined
if (!forceRefresh && cachedCatalog?.items) {
await sendMcpMarketplaceCatalogEvent(cachedCatalog)
return
}
const catalog = await this.fetchMcpMarketplaceFromApi(false)
if (catalog) {
await sendMcpMarketplaceCatalogEvent(catalog)
}
} catch (error) {
console.error("Failed to handle cached MCP marketplace:", error)
const errorMessage = error instanceof Error ? error.message : "Failed to handle cached MCP marketplace"
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
message: errorMessage,
})
}
}
// OpenRouter
async handleOpenRouterCallback(code: string) {
@@ -503,21 +512,20 @@ export class Controller {
const openrouter: ApiProvider = "openrouter"
const currentMode = await this.getCurrentMode()
await Promise.all([
updateGlobalState(this.context, "planModeApiProvider", openrouter),
updateGlobalState(this.context, "actModeApiProvider", openrouter),
])
await storeSecret(this.context, "openRouterApiKey", apiKey)
// Update API configuration through cache service
const currentApiConfiguration = this.cacheService.getApiConfiguration()
const updatedConfig = {
...currentApiConfiguration,
planModeApiProvider: openrouter,
actModeApiProvider: openrouter,
openRouterApiKey: apiKey,
}
this.cacheService.setApiConfiguration(updatedConfig)
await this.postStateToWebview()
if (this.task) {
// Get the updated API configuration (now includes the updated providers)
const { apiConfiguration } = await getAllExtensionState(this.context)
const updatedConfig = {
...apiConfiguration,
openRouterApiKey: apiKey,
taskId: this.task.taskId,
}
this.task.api = buildApiHandler(updatedConfig, currentMode)
this.task.api = buildApiHandler({ ...updatedConfig, taskId: this.task.taskId }, currentMode)
}
// await this.postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) // bad ux if user is on welcome
}
@@ -691,8 +699,10 @@ export class Controller {
}
async getStateToPostToWebview(): Promise<ExtensionState> {
// Get API configuration from cache for immediate access
const apiConfiguration = this.cacheService.getApiConfiguration()
const {
apiConfiguration,
lastShownAnnouncementId,
taskHistory,
autoApprovalSettings,
@@ -700,6 +710,7 @@ export class Controller {
preferredLanguage,
openaiReasoningEffort,
mode,
strictPlanModeEnabled,
userInfo,
mcpMarketplaceEnabled,
mcpDisplayMode,
@@ -715,44 +726,51 @@ export class Controller {
welcomeViewCompleted,
mcpResponsesCollapsed,
terminalOutputLineLimit,
localClineRulesToggles,
localWindsurfRulesToggles,
localCursorRulesToggles,
localWorkflowToggles,
} = await getAllExtensionState(this.context)
const localClineRulesToggles =
((await getWorkspaceState(this.context, "localClineRulesToggles")) as ClineRulesToggles) || {}
const currentTaskItem = this.task?.taskId ? (taskHistory || []).find((item) => item.id === this.task?.taskId) : undefined
const checkpointTrackerErrorMessage = this.task?.taskState.checkpointTrackerErrorMessage
const clineMessages = this.task?.messageStateHandler.getClineMessages() || []
const localWindsurfRulesToggles =
((await getWorkspaceState(this.context, "localWindsurfRulesToggles")) as ClineRulesToggles) || {}
const processedTaskHistory = (taskHistory || [])
.filter((item) => item.ts && item.task)
.sort((a, b) => b.ts - a.ts)
.slice(0, 100) // for now we're only getting the latest 100 tasks, but a better solution here is to only pass in 3 for recent task history, and then get the full task history on demand when going to the task history view (maybe with pagination?)
const localCursorRulesToggles =
((await getWorkspaceState(this.context, "localCursorRulesToggles")) as ClineRulesToggles) || {}
const localWorkflowToggles = ((await getWorkspaceState(this.context, "workflowToggles")) as ClineRulesToggles) || {}
const latestAnnouncementId = getLatestAnnouncementId(this.context)
const shouldShowAnnouncement = lastShownAnnouncementId !== latestAnnouncementId
const platform = process.platform as Platform
const distinctId = telemetryService.distinctId
const version = this.context.extension?.packageJSON?.version ?? ""
const uriScheme = vscode.env.uriScheme
return {
version: this.context.extension?.packageJSON?.version ?? "",
version,
apiConfiguration,
uriScheme: vscode.env.uriScheme,
currentTaskItem: this.task?.taskId ? (taskHistory || []).find((item) => item.id === this.task?.taskId) : undefined,
checkpointTrackerErrorMessage: this.task?.taskState.checkpointTrackerErrorMessage,
clineMessages: this.task?.messageStateHandler.getClineMessages() || [],
taskHistory: (taskHistory || [])
.filter((item) => item.ts && item.task)
.sort((a, b) => b.ts - a.ts)
.slice(0, 100), // for now we're only getting the latest 100 tasks, but a better solution here is to only pass in 3 for recent task history, and then get the full task history on demand when going to the task history view (maybe with pagination?)
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
platform: process.platform as Platform,
uriScheme,
currentTaskItem,
checkpointTrackerErrorMessage,
clineMessages,
taskHistory: processedTaskHistory,
shouldShowAnnouncement,
platform,
autoApprovalSettings,
browserSettings,
preferredLanguage,
openaiReasoningEffort,
mode,
strictPlanModeEnabled,
userInfo,
mcpMarketplaceEnabled,
mcpDisplayMode,
telemetrySetting,
planActSeparateModelsSetting,
enableCheckpointsSetting: enableCheckpointsSetting ?? true,
distinctId: telemetryService.distinctId,
distinctId,
globalClineRulesToggles: globalClineRulesToggles || {},
localClineRulesToggles: localClineRulesToggles || {},
localWindsurfRulesToggles: localWindsurfRulesToggles || {},
@@ -827,18 +845,4 @@ export class Controller {
await updateGlobalState(this.context, "taskHistory", history)
return history
}
// private async clearState() {
// this.context.workspaceState.keys().forEach((key) => {
// this.context.workspaceState.update(key, undefined)
// })
// this.context.globalState.keys().forEach((key) => {
// this.context.globalState.update(key, undefined)
// })
// this.context.secrets.delete("apiKey")
// }
// secrets
// dev
}
@@ -0,0 +1,234 @@
import { Controller } from ".."
import { EmptyRequest } from "@shared/proto/cline/common"
import { OpenRouterCompatibleModelInfo, OpenRouterModelInfo } from "@shared/proto/cline/models"
import { getAllExtensionState } from "../../storage/state"
import { basetenModels } from "../../../shared/api"
import axios from "axios"
import path from "path"
import fs from "fs/promises"
import { fileExistsAtPath } from "@utils/fs"
import { GlobalFileNames } from "@core/storage/disk"
/**
* Refreshes the Baseten models and returns the updated model list
* @param controller The controller instance
* @param request Empty request object
* @returns Response containing the Baseten models
*/
export async function refreshBasetenModels(
controller: Controller,
request: EmptyRequest,
): Promise<OpenRouterCompatibleModelInfo> {
console.log("=== refreshBasetenModels called ===")
const basetenModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.basetenModels)
// Get the Baseten API key from the controller's state
const { apiConfiguration } = await getAllExtensionState(controller.context)
const basetenApiKey = apiConfiguration?.basetenApiKey
let models: Record<string, Partial<OpenRouterModelInfo>> = {}
try {
if (!basetenApiKey) {
console.log("No Baseten API key found, using static models as fallback")
// Don't throw an error, just use static models
for (const [modelId, modelInfo] of Object.entries(basetenModels)) {
models[modelId] = {
maxTokens: modelInfo.maxTokens,
contextWindow: modelInfo.contextWindow,
supportsImages: modelInfo.supportsImages,
supportsPromptCache: modelInfo.supportsPromptCache,
inputPrice: modelInfo.inputPrice,
outputPrice: modelInfo.outputPrice,
cacheWritesPrice: (modelInfo as any).cacheWritesPrice || 0,
cacheReadsPrice: (modelInfo as any).cacheReadsPrice || 0,
description: (modelInfo as any).description || `${modelId} model`,
}
}
} else {
// Ensure the API key is properly formatted
const cleanApiKey = basetenApiKey.trim()
if (!cleanApiKey) {
throw new Error("Invalid Baseten API key format")
}
console.log("Fetching Baseten models with API key:", cleanApiKey.substring(0, 10) + "...")
const response = await axios.get("https://inference.baseten.co/v1/models", {
headers: {
Authorization: `Bearer ${cleanApiKey}`,
"Content-Type": "application/json",
"User-Agent": "Cline-VSCode-Extension",
},
timeout: 10000, // 10 second timeout
})
if (response.data?.data) {
const rawModels = response.data.data
for (const rawModel of rawModels) {
// Filter out non-chat models and validate model capabilities
if (!isValidChatModel(rawModel)) {
continue
}
// Only include models that are listed in the static basetenModels
if (!(rawModel.id in basetenModels)) {
console.log(`Skipping model ${rawModel.id} - not in static basetenModels list`)
continue
}
// Check if we have static pricing information for this model
const staticModelInfo = basetenModels[rawModel.id as keyof typeof basetenModels]
const modelInfo: Partial<OpenRouterModelInfo> = {
maxTokens: staticModelInfo?.maxTokens || 8192,
contextWindow: staticModelInfo?.contextWindow || 8192,
supportsImages: staticModelInfo?.supportsImages || false,
supportsPromptCache: staticModelInfo?.supportsPromptCache || false,
inputPrice: staticModelInfo?.inputPrice || 0,
outputPrice: staticModelInfo?.outputPrice || 0,
cacheWritesPrice: staticModelInfo?.cacheWritesPrice || 0,
cacheReadsPrice: staticModelInfo?.cacheReadsPrice || 0,
description: generateModelDescription(rawModel, staticModelInfo),
}
models[rawModel.id] = modelInfo
}
} else {
console.error("Invalid response from Baseten API")
}
await fs.writeFile(basetenModelsFilePath, JSON.stringify(models))
console.log("Baseten models fetched and saved:", Object.keys(models))
}
} catch (error) {
console.error("Error fetching Baseten models:", error)
// Provide more specific error messages
let errorMessage = "Unknown error occurred"
if (axios.isAxiosError(error)) {
if (error.response?.status === 401) {
errorMessage = "Invalid Baseten API key. Please check your API key in settings."
} else if (error.response?.status === 403) {
errorMessage = "Access forbidden. Please verify your Baseten API key has the correct permissions."
} else if (error.response?.status === 429) {
errorMessage = "Rate limit exceeded. Please try again later."
} else if (error.code === "ECONNABORTED") {
errorMessage = "Request timeout. Please check your internet connection."
} else {
errorMessage = `API request failed: ${error.response?.status || error.code || "Unknown error"}`
}
} else if (error instanceof Error) {
errorMessage = error.message
}
console.error("Baseten API Error:", errorMessage)
// If we failed to fetch models, try to read cached models first
const cachedModels = await readBasetenModels(controller)
if (cachedModels && Object.keys(cachedModels).length > 0) {
console.log("Using cached Baseten models")
// Filter cached models to only include those in static basetenModels
for (const [modelId, modelInfo] of Object.entries(cachedModels)) {
if (modelId in basetenModels) {
models[modelId] = modelInfo
}
}
} else {
// Fall back to static models from shared/api.ts
console.log("Using static Baseten models as fallback")
for (const [modelId, modelInfo] of Object.entries(basetenModels)) {
models[modelId] = {
maxTokens: modelInfo.maxTokens,
contextWindow: modelInfo.contextWindow,
supportsImages: modelInfo.supportsImages,
supportsPromptCache: modelInfo.supportsPromptCache,
inputPrice: modelInfo.inputPrice,
outputPrice: modelInfo.outputPrice,
cacheWritesPrice: (modelInfo as any).cacheWritesPrice || 0,
cacheReadsPrice: (modelInfo as any).cacheReadsPrice || 0,
description: (modelInfo as any).description || `${modelId} model`,
}
}
}
}
// Convert the Record<string, Partial<OpenRouterModelInfo>> to Record<string, OpenRouterModelInfo>
// by filling in any missing required fields with defaults
const typedModels: Record<string, OpenRouterModelInfo> = {}
for (const [key, model] of Object.entries(models)) {
typedModels[key] = {
maxTokens: model.maxTokens ?? 8192,
contextWindow: model.contextWindow ?? 8192,
supportsImages: model.supportsImages ?? false,
supportsPromptCache: model.supportsPromptCache ?? false,
inputPrice: model.inputPrice ?? 0,
outputPrice: model.outputPrice ?? 0,
cacheWritesPrice: model.cacheWritesPrice ?? 0,
cacheReadsPrice: model.cacheReadsPrice ?? 0,
description: model.description ?? "",
tiers: model.tiers ?? [],
}
}
return OpenRouterCompatibleModelInfo.create({ models: typedModels })
}
/**
* Ensures the cache directory exists and returns its path
*/
async function ensureCacheDirectoryExists(controller: Controller): Promise<string> {
const cacheDir = path.join(controller.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
/**
* Reads cached Baseten models from disk
*/
async function readBasetenModels(controller: Controller): Promise<Record<string, Partial<OpenRouterModelInfo>> | undefined> {
const basetenModelsFilePath = path.join(await ensureCacheDirectoryExists(controller), GlobalFileNames.basetenModels)
const fileExists = await fileExistsAtPath(basetenModelsFilePath)
if (fileExists) {
try {
const fileContents = await fs.readFile(basetenModelsFilePath, "utf8")
return JSON.parse(fileContents)
} catch (error) {
console.error("Error reading cached Baseten models:", error)
return undefined
}
}
return undefined
}
/**
* Validates if a model is suitable for chat completions
*/
function isValidChatModel(rawModel: any): boolean {
// Filter out non-chat models (whisper, TTS, guard models, etc.)
if (rawModel.id.includes("whisper") || rawModel.id.includes("tts") || rawModel.id.includes("embedding")) {
return false
}
// Check if model supports chat completions
if (rawModel.object === "model" && rawModel.id) {
return true
}
return false
}
/**
* Generates a descriptive name for the model
*/
function generateModelDescription(rawModel: any, staticModelInfo?: any): string {
// Use static description if available
if (staticModelInfo?.description) {
return staticModelInfo.description
}
// Generate description based on model characteristics
const modelId = rawModel.id
const ownedBy = rawModel.owned_by || "Unknown"
return `${ownedBy} model: ${modelId}`
}
@@ -1,7 +1,6 @@
import type { Controller } from "../index"
import { Empty } from "@shared/proto/cline/common"
import { UpdateApiConfigurationRequest } from "@shared/proto/cline/models"
import { updateApiConfiguration } from "../../storage/state"
import { buildApiHandler } from "@api/index"
import { convertProtoToApiConfiguration } from "@shared/proto-conversions/models/api-configuration-conversion"
@@ -25,7 +24,7 @@ export async function updateApiConfigurationProto(
const appApiConfiguration = convertProtoToApiConfiguration(request.apiConfiguration)
// Update the API configuration in storage
await updateApiConfiguration(controller.context, appApiConfiguration)
controller.cacheService.setApiConfiguration(appApiConfiguration)
// Update the task's API handler if there's an active task
if (controller.task) {
+2 -2
View File
@@ -19,13 +19,13 @@ export async function resetState(controller: Controller, request: ResetStateRequ
type: ShowMessageType.INFORMATION,
message: "Resetting global state...",
})
await resetGlobalState(controller.context)
await resetGlobalState(controller)
} else {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Resetting workspace state...",
})
await resetWorkspaceState(controller.context)
await resetWorkspaceState(controller)
}
if (controller.task) {
@@ -16,11 +16,7 @@ export async function toggleFavoriteModel(controller: Controller, request: Strin
}
const modelId = request.value
const { apiConfiguration } = await controller.getStateToPostToWebview()
if (!apiConfiguration) {
throw new Error("API configuration not found")
}
const apiConfiguration = controller.cacheService.getApiConfiguration()
const favoritedModelIds = apiConfiguration.favoritedModelIds || []
@@ -29,7 +25,12 @@ export async function toggleFavoriteModel(controller: Controller, request: Strin
? favoritedModelIds.filter((id) => id !== modelId)
: [...favoritedModelIds, modelId]
await updateGlobalState(controller.context, "favoritedModelIds", updatedFavorites)
// Update the complete API configuration through cache service
const updatedApiConfiguration = {
...apiConfiguration,
favoritedModelIds: updatedFavorites,
}
controller.cacheService.setApiConfiguration(updatedApiConfiguration)
// Capture telemetry for model favorite toggle
const isFavorited = !favoritedModelIds.includes(modelId)
+13 -6
View File
@@ -1,11 +1,10 @@
import { Controller } from ".."
import { Empty } from "@shared/proto/cline/common"
import { PlanActMode, UpdateSettingsRequest } from "@shared/proto/cline/state"
import { updateApiConfiguration } from "../../storage/state"
import { buildApiHandler } from "../../../api"
import { convertProtoApiConfigurationToApiConfiguration } from "@shared/proto-conversions/state/settings-conversion"
import { TelemetrySetting } from "@shared/TelemetrySetting"
import { OpenaiReasoningEffort } from "@shared/storage/types"
import { convertProtoApiConfigurationToApiConfiguration } from "../../../shared/proto-conversions/state/settings-conversion"
import { TelemetrySetting } from "@/shared/TelemetrySetting"
import { OpenaiReasoningEffort } from "@/shared/storage/types"
/**
* Updates multiple extension settings in a single request
@@ -18,7 +17,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett
// Update API configuration
if (request.apiConfiguration) {
const apiConfiguration = convertProtoApiConfigurationToApiConfiguration(request.apiConfiguration)
await updateApiConfiguration(controller.context, apiConfiguration)
controller.cacheService.setApiConfiguration(apiConfiguration)
if (controller.task) {
const currentMode = await controller.getCurrentMode()
@@ -59,7 +58,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett
if (request.mode !== undefined) {
const mode = request.mode === PlanActMode.PLAN ? "plan" : "act"
if (controller.task) {
controller.task.mode = mode
controller.task.updateMode(mode)
}
await controller.context.globalState.update("mode", request.mode)
}
@@ -93,6 +92,14 @@ export async function updateSettings(controller: Controller, request: UpdateSett
await controller.context.globalState.update("terminalOutputLineLimit", Number(request.terminalOutputLineLimit))
}
// Update strict plan mode setting
if (request.strictPlanModeEnabled !== undefined) {
if (controller.task) {
controller.task.updateStrictPlanMode(request.strictPlanModeEnabled)
}
await controller.context.globalState.update("strictPlanModeEnabled", request.strictPlanModeEnabled)
}
// Post updated state to webview
await controller.postStateToWebview()
@@ -30,7 +30,7 @@ export async function deleteTasksWithIds(controller: Controller, request: String
options: { modal: true, items: ["Delete"] },
})
if (userChoice === undefined) {
if (userChoice.selectedOption !== "Delete") {
return Empty.create()
}
+62 -8
View File
@@ -9,6 +9,7 @@ import { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
import { McpMarketplaceCatalog } from "@shared/mcp"
import { refreshOpenRouterModels } from "../models/refreshOpenRouterModels"
import { refreshGroqModels } from "../models/refreshGroqModels"
import { refreshBasetenModels } from "../models/refreshBasetenModels"
/**
* Initialize webview when it launches
@@ -32,7 +33,8 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
refreshOpenRouterModels(controller, EmptyRequest.create()).then(async (response) => {
if (response && response.models) {
// Update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration, planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const apiConfiguration = controller.cacheService.getApiConfiguration()
const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const currentMode = await controller.getCurrentMode()
if (planActSeparateModelsSetting) {
@@ -42,26 +44,32 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
const modelId = apiConfiguration[modelIdField]
if (modelId && response.models[modelId]) {
await updateGlobalState(controller.context, modelInfoField, response.models[modelId])
const updatedConfig = {
...apiConfiguration,
[modelInfoField]: response.models[modelId],
}
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
} else {
// Shared models: update both plan and act modes
const planModelId = apiConfiguration.planModeOpenRouterModelId
const actModelId = apiConfiguration.actModeOpenRouterModelId
let updatedConfig = { ...apiConfiguration }
// Update plan mode model info if we have a model ID
if (planModelId && response.models[planModelId]) {
await updateGlobalState(controller.context, "planModeOpenRouterModelInfo", response.models[planModelId])
updatedConfig.planModeOpenRouterModelInfo = response.models[planModelId]
}
// Update act mode model info if we have a model ID
if (actModelId && response.models[actModelId]) {
await updateGlobalState(controller.context, "actModeOpenRouterModelInfo", response.models[actModelId])
updatedConfig.actModeOpenRouterModelInfo = response.models[actModelId]
}
// Post state update if we updated any model info
if ((planModelId && response.models[planModelId]) || (actModelId && response.models[actModelId])) {
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
}
@@ -71,7 +79,8 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
refreshGroqModels(controller, EmptyRequest.create()).then(async (response) => {
if (response && response.models) {
// Update model info in state for Groq (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration, planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const apiConfiguration = controller.cacheService.getApiConfiguration()
const { planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const currentMode = await controller.getCurrentMode()
if (planActSeparateModelsSetting) {
@@ -81,22 +90,67 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
const modelId = apiConfiguration[modelIdField]
if (modelId && response.models[modelId]) {
await updateGlobalState(controller.context, modelInfoField, response.models[modelId])
const updatedConfig = {
...apiConfiguration,
[modelInfoField]: response.models[modelId],
}
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
} else {
// Shared models: update both plan and act modes
const planModelId = apiConfiguration.planModeGroqModelId
const actModelId = apiConfiguration.actModeGroqModelId
let updatedConfig = { ...apiConfiguration }
// Update plan mode model info if we have a model ID
if (planModelId && response.models[planModelId]) {
await updateGlobalState(controller.context, "planModeGroqModelInfo", response.models[planModelId])
updatedConfig.planModeGroqModelInfo = response.models[planModelId]
}
// Update act mode model info if we have a model ID
if (actModelId && response.models[actModelId]) {
await updateGlobalState(controller.context, "actModeGroqModelInfo", response.models[actModelId])
updatedConfig.actModeGroqModelInfo = response.models[actModelId]
}
// Post state update if we updated any model info
if ((planModelId && response.models[planModelId]) || (actModelId && response.models[actModelId])) {
controller.cacheService.setApiConfiguration(updatedConfig)
await controller.postStateToWebview()
}
}
}
})
refreshBasetenModels(controller, EmptyRequest.create()).then(async (response) => {
if (response && response.models) {
// Update model info in state for Baseten (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration, planActSeparateModelsSetting } = await getAllExtensionState(controller.context)
const currentMode = await controller.getCurrentMode()
if (planActSeparateModelsSetting) {
// Separate models: update only current mode
const modelIdField = currentMode === "plan" ? "planModeBasetenModelId" : "actModeBasetenModelId"
const modelInfoField = currentMode === "plan" ? "planModeBasetenModelInfo" : "actModeBasetenModelInfo"
const modelId = apiConfiguration[modelIdField]
if (modelId && response.models[modelId]) {
await updateGlobalState(controller.context, modelInfoField, response.models[modelId])
await controller.postStateToWebview()
}
} else {
// Shared models: update both plan and act modes
const planModelId = apiConfiguration.planModeBasetenModelId
const actModelId = apiConfiguration.actModeBasetenModelId
// Update plan mode model info if we have a model ID
if (planModelId && response.models[planModelId]) {
await updateGlobalState(controller.context, "planModeBasetenModelInfo", response.models[planModelId])
}
// Update act mode model info if we have a model ID
if (actModelId && response.models[actModelId]) {
await updateGlobalState(controller.context, "actModeBasetenModelInfo", response.models[actModelId])
}
// Post state update if we updated any model info
@@ -2,6 +2,7 @@ import type { EmptyRequest } from "@shared/proto/cline/common"
import { Boolean } from "@shared/proto/cline/common"
import type { Controller } from "../index"
import { updateGlobalState } from "../../storage/state"
import { getLatestAnnouncementId } from "@/utils/announcements"
/**
* Marks the current announcement as shown
@@ -12,8 +13,9 @@ import { updateGlobalState } from "../../storage/state"
*/
export async function onDidShowAnnouncement(controller: Controller, _request: EmptyRequest): Promise<Boolean> {
try {
const latestAnnouncementId = getLatestAnnouncementId(controller.context)
// Update the lastShownAnnouncementId to the current latestAnnouncementId
await updateGlobalState(controller.context, "lastShownAnnouncementId", controller.latestAnnouncementId)
await updateGlobalState(controller.context, "lastShownAnnouncementId", latestAnnouncementId)
return Boolean.create({ value: false })
} catch (error) {
console.error("Failed to acknowledge announcement:", error)
+421
View File
@@ -0,0 +1,421 @@
import { expect } from "chai"
import * as sinon from "sinon"
import * as path from "path"
import { parseMentions } from "../index"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker"
import * as extractTextModule from "@integrations/misc/extract-text"
import * as isBinaryFileModule from "isbinaryfile"
import * as terminalModule from "@integrations/terminal/get-latest-output"
import * as gitModule from "@utils/git"
import { DiffViewProviderCreator, HostProvider, WebviewProviderCreator } from "@/hosts/host-provider"
import * as fs from "fs"
import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client"
describe("parseMentions", () => {
let sandbox: sinon.SinonSandbox
let urlContentFetcherStub: sinon.SinonStubbedInstance<UrlContentFetcher>
let fileContextTrackerStub: sinon.SinonStubbedInstance<FileContextTracker>
let fsStatStub: sinon.SinonStub
let fsReaddirStub: sinon.SinonStub
let extractTextStub: sinon.SinonStub
let isBinaryFileStub: sinon.SinonStub
let getLatestTerminalOutputStub: sinon.SinonStub
let getWorkingStateStub: sinon.SinonStub
let getCommitInfoStub: sinon.SinonStub
let showMessageStub: sinon.SinonStub
const cwd = "/test/project"
beforeEach(() => {
sandbox = sinon.createSandbox()
HostProvider.reset()
HostProvider.initialize(
((_) => {}) as WebviewProviderCreator,
(() => {}) as DiffViewProviderCreator,
vscodeHostBridgeClient,
(_) => {},
)
// Create stubs for dependencies
urlContentFetcherStub = {
launchBrowser: sandbox.stub().resolves(),
closeBrowser: sandbox.stub().resolves(),
urlToMarkdown: sandbox.stub().resolves("# Example Website\n\nContent here"),
} as any
fileContextTrackerStub = {
trackFileContext: sandbox.stub().resolves(),
} as any
// Stub file system operations using fs.promises
fsStatStub = sandbox.stub(fs.promises, "stat")
fsReaddirStub = sandbox.stub(fs.promises, "readdir")
// Stub other modules
extractTextStub = sandbox.stub(extractTextModule, "extractTextFromFile")
isBinaryFileStub = sandbox.stub(isBinaryFileModule, "isBinaryFile")
getLatestTerminalOutputStub = sandbox.stub(terminalModule, "getLatestTerminalOutput")
getWorkingStateStub = sandbox.stub(gitModule, "getWorkingState")
getCommitInfoStub = sandbox.stub(gitModule, "getCommitInfo")
showMessageStub = sandbox.stub(HostProvider.window, "showMessage")
})
afterEach(() => {
sandbox.restore()
})
describe("File mentions", () => {
it("should handle simple file mention", async () => {
const text = "Check @/src/index.ts for details"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.resolves("console.log('Hello World');")
const result = await parseMentions(text, cwd, urlContentFetcherStub, fileContextTrackerStub)
const expectedOutput = `Check 'src/index.ts' (see below for file content) for details
<file_content path="src/index.ts">
console.log('Hello World');
</file_content>`
expect(result).to.equal(expectedOutput)
expect(fileContextTrackerStub.trackFileContext.calledWith("src/index.ts", "file_mentioned")).to.be.true
})
it("should handle quoted file paths with spaces", async () => {
const text = 'Open @"/path with spaces/file.txt"'
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.resolves("console.log('Hello World');")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Open 'path with spaces/file.txt' (see below for file content)
<file_content path="path with spaces/file.txt">
console.log('Hello World');
</file_content>`
expect(result).to.equal(expectedOutput)
})
it("should handle binary files", async () => {
const text = "Check @/image.png"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(true)
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'image.png' (see below for file content)
<file_content path="image.png">
(Binary file, unable to display content)
</file_content>`
expect(result).to.equal(expectedOutput)
})
it("should handle file read errors", async () => {
const text = "Check @/missing.txt"
fsStatStub.rejects(new Error("ENOENT: no such file or directory"))
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'missing.txt' (see below for file content)
<file_content path="missing.txt">
Error fetching content: Failed to access path "missing.txt": ENOENT: no such file or directory
</file_content>`
expect(result).to.equal(expectedOutput)
})
})
describe("Folder mentions", () => {
it("should handle folder mention", async () => {
const text = "Look in @/src/ folder"
fsStatStub.resolves({ isFile: () => false, isDirectory: () => true })
fsReaddirStub.resolves([
{ name: "index.ts", isFile: () => true, isDirectory: () => false },
{ name: "utils", isFile: () => false, isDirectory: () => true },
{ name: "README.md", isFile: () => true, isDirectory: () => false },
])
// Set up file content stubs
isBinaryFileStub.resolves(false)
extractTextStub.withArgs(path.resolve(cwd, "src/index.ts")).resolves("export const main = () => {};")
extractTextStub.withArgs(path.resolve(cwd, "src/README.md")).resolves("# Source Code")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Look in 'src/' (see below for folder content) folder
<folder_content path="src/">
├── index.ts
├── utils/
└── README.md
<file_content path="src/index.ts">
export const main = () => {};
</file_content>
<file_content path="src/README.md">
# Source Code
</file_content>
</folder_content>`
expect(result).to.equal(expectedOutput)
})
})
describe("URL mentions", () => {
it("should handle URL mention", async () => {
const text = "Visit @https://example.com for info"
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Visit 'https://example.com' (see below for site content) for info
<url_content url="https://example.com">
# Example Website
Content here
</url_content>`
expect(result).to.equal(expectedOutput)
expect(urlContentFetcherStub.launchBrowser.called).to.be.true
expect(urlContentFetcherStub.urlToMarkdown.calledWith("https://example.com")).to.be.true
expect(urlContentFetcherStub.closeBrowser.called).to.be.true
})
it("should handle browser launch errors", async () => {
const text = "Visit @https://example.com"
urlContentFetcherStub.launchBrowser.rejects(new Error("Browser launch failed"))
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Visit 'https://example.com' (see below for site content)
<url_content url="https://example.com">
Error fetching content: Browser launch failed
</url_content>`
expect(result).to.equal(expectedOutput)
expect(showMessageStub.called).to.be.true
})
it("should handle URL fetch errors", async () => {
const text = "Visit @https://example.com"
urlContentFetcherStub.urlToMarkdown.rejects(new Error("Network error"))
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Visit 'https://example.com' (see below for site content)
<url_content url="https://example.com">
Error fetching content: Network error
</url_content>`
expect(result).to.equal(expectedOutput)
expect(showMessageStub.called).to.be.true
})
})
describe("Special mentions", () => {
it("should handle @terminal mention", async () => {
const text = "See @terminal output"
getLatestTerminalOutputStub.resolves("$ npm test\nAll tests passed!")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `See Terminal Output (see below for output) output
<terminal_output>
$ npm test
All tests passed!
</terminal_output>`
expect(result).to.equal(expectedOutput)
})
it("should handle @git-changes mention", async () => {
const text = "Review @git-changes"
getWorkingStateStub.resolves("M src/index.ts\nA src/new-file.ts")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Review Working directory changes (see below for details)
<git_working_state>
M src/index.ts
A src/new-file.ts
</git_working_state>`
expect(result).to.equal(expectedOutput)
})
it("should handle git commit hash mention", async () => {
const text = "See commit @abcdef1234567890"
getCommitInfoStub.resolves("commit abcdef1234567890\nAuthor: Test\nDate: 2024-01-01\n\nInitial commit")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `See commit Git commit 'abcdef1234567890' (see below for commit info)
<git_commit hash="abcdef1234567890">
commit abcdef1234567890
Author: Test
Date: 2024-01-01
Initial commit
</git_commit>`
expect(result).to.equal(expectedOutput)
})
})
describe("Multiple mentions", () => {
it("should handle multiple mentions in order", async () => {
const text = "Check @/file1.txt and @/file2.txt"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.withArgs(path.resolve(cwd, "file1.txt")).resolves("Content 1")
extractTextStub.withArgs(path.resolve(cwd, "file2.txt")).resolves("Content 2")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'file1.txt' (see below for file content) and 'file2.txt' (see below for file content)
<file_content path="file1.txt">
Content 1
</file_content>
<file_content path="file2.txt">
Content 2
</file_content>`
expect(result).to.equal(expectedOutput)
})
it("should handle duplicate mentions only once", async () => {
const text = "Check @/file.txt and again @/file.txt"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.resolves("Content")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'file.txt' (see below for file content) and again 'file.txt' (see below for file content)
<file_content path="file.txt">
Content
</file_content>`
expect(result).to.equal(expectedOutput)
})
it("should handle mixed mention types", async () => {
const text = "Check @/file.txt, and @https://example.com"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.resolves("File content")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'file.txt' (see below for file content), and 'https://example.com' (see below for site content)
<file_content path="file.txt">
File content
</file_content>
<url_content url="https://example.com">
# Example Website
Content here
</url_content>`
expect(result).to.equal(expectedOutput)
})
})
describe("Error handling", () => {
it("should handle errors for each mention type gracefully", async () => {
const text = "@/error.txt @terminal @git-changes @abc1234567"
fsStatStub.rejects(new Error("File error"))
getLatestTerminalOutputStub.rejects(new Error("Terminal error"))
getWorkingStateStub.rejects(new Error("Git state error"))
getCommitInfoStub.rejects(new Error("Commit error"))
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `'error.txt' (see below for file content) Terminal Output (see below for output) Working directory changes (see below for details) Git commit 'abc1234567' (see below for commit info)
<file_content path="error.txt">
Error fetching content: Failed to access path "error.txt": File error
</file_content>
<terminal_output>
Error fetching terminal output: Terminal error
</terminal_output>
<git_working_state>
Error fetching working state: Git state error
</git_working_state>
<git_commit hash="abc1234567">
Error fetching commit info: Commit error
</git_commit>`
expect(result).to.equal(expectedOutput)
})
})
describe("Edge cases", () => {
it("should handle text with no mentions", async () => {
const text = "This is plain text without any mentions"
const result = await parseMentions(text, cwd, urlContentFetcherStub)
expect(result).to.equal(text)
})
it("should handle empty text", async () => {
const result = await parseMentions("", cwd, urlContentFetcherStub)
expect(result).to.equal("")
})
it("should handle mentions with trailing punctuation", async () => {
const text = "Check @/file.txt!"
fsStatStub.resolves({ isFile: () => true, isDirectory: () => false })
isBinaryFileStub.resolves(false)
extractTextStub.resolves("Content")
const result = await parseMentions(text, cwd, urlContentFetcherStub)
const expectedOutput = `Check 'file.txt' (see below for file content)!
<file_content path="file.txt">
Content
</file_content>`
expect(result).to.equal(expectedOutput)
})
})
})
+21 -14
View File
@@ -6,7 +6,7 @@ import { mentionRegexGlobal } from "@shared/context-mentions"
import fs from "fs/promises"
import { extractTextFromFile } from "@integrations/misc/extract-text"
import { isBinaryFile } from "isbinaryfile"
import { diagnosticsToProblemsString } from "@integrations/diagnostics"
import { getWorkspaceProblemsString } from "@/integrations/diagnostics"
import { getLatestTerminalOutput } from "@integrations/terminal/get-latest-output"
import { getCommitInfo } from "@utils/git"
import { getWorkingState } from "@utils/git"
@@ -14,7 +14,7 @@ import { FileContextTracker } from "../context/context-tracking/FileContextTrack
import { getCwd } from "@/utils/path"
import { openExternal } from "@utils/env"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window"
import { ShowMessageType } from "@/shared/proto/host/window"
export async function openMention(mention?: string): Promise<void> {
if (!mention) {
@@ -26,8 +26,8 @@ export async function openMention(mention?: string): Promise<void> {
return
}
if (mention.startsWith("/")) {
const relPath = mention.slice(1)
if (isFileMention(mention)) {
const relPath = getFilePathFromMention(mention)
const absPath = path.resolve(cwd, relPath)
if (mention.endsWith("/")) {
vscode.commands.executeCommand("revealInExplorer", vscode.Uri.file(absPath))
@@ -54,8 +54,8 @@ export async function parseMentions(
mentions.add(mention)
if (mention.startsWith("http")) {
return `'${mention}' (see below for site content)`
} else if (mention.startsWith("/")) {
const mentionPath = mention.slice(1) // Remove the leading '/'
} else if (isFileMention(mention)) {
const mentionPath = getFilePathFromMention(mention)
return mentionPath.endsWith("/")
? `'${mentionPath}' (see below for folder content)`
: `'${mentionPath}' (see below for file content)`
@@ -106,8 +106,8 @@ export async function parseMentions(
}
}
parsedText += `\n\n<url_content url="${mention}">\n${result}\n</url_content>`
} else if (mention.startsWith("/")) {
const mentionPath = mention.slice(1)
} else if (isFileMention(mention)) {
const mentionPath = getFilePathFromMention(mention)
try {
const content = await getFileOrFolderContent(mentionPath, cwd)
if (mention.endsWith("/")) {
@@ -225,10 +225,17 @@ async function getFileOrFolderContent(mentionPath: string, cwd: string): Promise
}
async function getWorkspaceProblems(): Promise<string> {
const diagnostics = vscode.languages.getDiagnostics()
const result = diagnosticsToProblemsString(diagnostics, [vscode.DiagnosticSeverity.Error, vscode.DiagnosticSeverity.Warning])
if (!result) {
return "No errors or warnings detected."
}
return result
return await getWorkspaceProblemsString()
}
function isFileMention(mention: string): boolean {
return mention.startsWith("/") || mention.startsWith('"/')
}
function getFilePathFromMention(mention: string): string {
// Remove quotes
const match = mention.match(/^"(.*)"$/)
const filePath = match ? match[1] : mention
// Remove leading slash
return filePath.slice(1)
}
+4 -6
View File
@@ -5,7 +5,7 @@ import { McpHub } from "@services/mcp/McpHub"
import { BrowserSettings } from "@shared/BrowserSettings"
import { SYSTEM_PROMPT_CLAUDE4_EXPERIMENTAL } from "@core/prompts/model_prompts/claude4-experimental"
import { SYSTEM_PROMPT_CLAUDE4 } from "@core/prompts/model_prompts/claude4"
import { USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "@core/task/index";
import { USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "@core/task/index"
export const SYSTEM_PROMPT = async (
cwd: string,
@@ -14,14 +14,13 @@ export const SYSTEM_PROMPT = async (
browserSettings: BrowserSettings,
isNextGenModel: boolean = false,
) => {
if (isNextGenModel && USE_EXPERIMENTAL_CLAUDE4_FEATURES) {
return SYSTEM_PROMPT_CLAUDE4_EXPERIMENTAL(cwd, supportsBrowserUse, mcpHub, browserSettings)
}
if (isNextGenModel) {
return SYSTEM_PROMPT_CLAUDE4(cwd, supportsBrowserUse, mcpHub, browserSettings)
}
if (isNextGenModel) {
return SYSTEM_PROMPT_CLAUDE4(cwd, supportsBrowserUse, mcpHub, browserSettings)
}
return `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
@@ -650,7 +649,6 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
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(
globalClineRulesFileInstructions?: string,
localClineRulesFileInstructions?: string,
+960
View File
@@ -0,0 +1,960 @@
import { ApiConfiguration } from "@shared/api"
import { updateGlobalState, updateWorkspaceState, getAllExtensionState, storeSecret } from "./state"
import { SecretKey, GlobalStateKey, LocalStateKey } from "./state-keys"
import { CACHE_SERVICE_NOT_INITIALIZED } from "./error-messages"
import type { ExtensionContext } from "vscode"
/**
* Interface for persistence error event data
*/
export interface PersistenceErrorEvent {
error: Error
}
/**
* In-memory cache service for fast state access
* Provides immediate reads/writes with async disk persistence
*/
export class CacheService {
private globalStateCache: Map<GlobalStateKey, any> = new Map()
private secretsCache: Map<SecretKey, string | undefined> = new Map()
private workspaceStateCache: Map<LocalStateKey, any> = new Map()
private context: ExtensionContext
private isInitialized = false
// Debounced persistence state
private pendingGlobalState = new Set<GlobalStateKey>()
private pendingSecrets = new Set<SecretKey>()
private pendingWorkspaceState = new Set<LocalStateKey>()
private persistenceTimeout: NodeJS.Timeout | null = null
private readonly PERSISTENCE_DELAY_MS = 500
// Callback for persistence errors
onPersistenceError?: (event: PersistenceErrorEvent) => void
constructor(context: ExtensionContext) {
this.context = context
}
/**
* Initialize the cache by loading data from disk
*/
async initialize(): Promise<void> {
try {
// Load API configuration and populate cache with component keys
const { apiConfiguration } = await getAllExtensionState(this.context)
if (apiConfiguration) {
// Populate the caches with the API configuration component keys
// Use populate method to avoid triggering persistence during initialization
this.populateApiConfigurationCache(apiConfiguration)
}
this.isInitialized = true
console.log("CacheService initialized successfully")
} catch (error) {
console.error("Failed to initialize CacheService:", error)
throw error
}
}
/**
* Set method for global state keys - updates cache immediately and schedules debounced persistence
*/
setGlobalState<T>(key: GlobalStateKey, value: T): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.globalStateCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingGlobalState.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for global state keys - updates cache immediately and schedules debounced persistence
*/
setGlobalStateBatch(updates: Partial<Record<GlobalStateKey, any>>): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for all keys
Object.entries(updates).forEach(([key, value]) => {
this.globalStateCache.set(key as GlobalStateKey, value)
this.pendingGlobalState.add(key as GlobalStateKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Set method for secret keys - updates cache immediately and schedules debounced persistence
*/
setSecret(key: SecretKey, value: string | undefined): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.secretsCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingSecrets.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for secret keys - updates cache immediately and schedules debounced persistence
*/
setSecretsBatch(updates: Partial<Record<SecretKey, string | undefined>>): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for all keys
Object.entries(updates).forEach(([key, value]) => {
this.secretsCache.set(key as SecretKey, value)
this.pendingSecrets.add(key as SecretKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Set method for workspace state keys - updates cache immediately and schedules debounced persistence
*/
setWorkspaceState<T>(key: LocalStateKey, value: T): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for instant access
this.workspaceStateCache.set(key, value)
// Add to pending persistence set and schedule debounced write
this.pendingWorkspaceState.add(key)
this.scheduleDebouncedPersistence()
}
/**
* Batch set method for workspace state keys - updates cache immediately and schedules debounced persistence
*/
setWorkspaceStateBatch(updates: Partial<Record<LocalStateKey, any>>): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Update cache immediately for all keys
Object.entries(updates).forEach(([key, value]) => {
this.workspaceStateCache.set(key as LocalStateKey, value)
this.pendingWorkspaceState.add(key as LocalStateKey)
})
// Schedule debounced persistence
this.scheduleDebouncedPersistence()
}
/**
* Convenience method for getting API configuration
* Ensures cache is initialized if not already done
*/
getApiConfiguration(): ApiConfiguration {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
// Construct API configuration from cached component keys
return this.constructApiConfigurationFromCache()
}
/**
* Convenience method for setting API configuration
*/
setApiConfiguration(apiConfiguration: ApiConfiguration): void {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
basetenApiKey,
huggingFaceApiKey,
requestTimeoutMs,
// Plan mode configurations
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configurations
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
} = apiConfiguration
// Batch update global state keys
this.setGlobalStateBatch({
// Plan mode configuration updates
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configuration updates
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
// Global state updates
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
})
// Batch update secrets
this.setSecretsBatch({
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
basetenApiKey,
huggingFaceApiKey,
})
}
/**
* Get method for global state keys - reads from in-memory cache
*/
getGlobalStateKey<T>(key: GlobalStateKey): T | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.globalStateCache.get(key) as T | undefined
}
/**
* Get method for secret keys - reads from in-memory cache
*/
getSecretKey(key: SecretKey): string | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.secretsCache.get(key)
}
/**
* Get method for workspace state keys - reads from in-memory cache
*/
getWorkspaceStateKey<T>(key: LocalStateKey): T | undefined {
if (!this.isInitialized) {
throw new Error(CACHE_SERVICE_NOT_INITIALIZED)
}
return this.workspaceStateCache.get(key) as T | undefined
}
/**
* Reinitialize the cache service by clearing all state and reloading from disk
* Used for error recovery when write operations fail
*/
async reInitialize(): Promise<void> {
// Clear all cached data and pending state
this.dispose()
// Reinitialize from disk
await this.initialize()
}
/**
* Dispose of the cache service
*/
private dispose(): void {
if (this.persistenceTimeout) {
clearTimeout(this.persistenceTimeout)
this.persistenceTimeout = null
}
this.pendingGlobalState.clear()
this.pendingSecrets.clear()
this.pendingWorkspaceState.clear()
this.globalStateCache.clear()
this.secretsCache.clear()
this.workspaceStateCache.clear()
this.isInitialized = false
}
/**
* Schedule debounced persistence - simple timeout-based persistence
*/
private scheduleDebouncedPersistence(): void {
// Clear existing timeout if one is pending
if (this.persistenceTimeout) {
clearTimeout(this.persistenceTimeout)
}
// Schedule a new timeout to persist pending changes
this.persistenceTimeout = setTimeout(async () => {
try {
await Promise.all([
this.persistGlobalStateBatch(this.pendingGlobalState),
this.persistSecretsBatch(this.pendingSecrets),
this.persistWorkspaceStateBatch(this.pendingWorkspaceState),
])
// Clear pending sets on successful persistence
this.pendingGlobalState.clear()
this.pendingSecrets.clear()
this.pendingWorkspaceState.clear()
this.persistenceTimeout = null
} catch (error) {
console.error("Failed to persist pending changes:", error)
this.persistenceTimeout = null
// Call persistence error callback for error recovery
this.onPersistenceError?.({ error: error as Error })
}
}, this.PERSISTENCE_DELAY_MS)
}
/**
* Private method to batch persist global state keys with Promise.all
*/
private async persistGlobalStateBatch(keys: Set<GlobalStateKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.globalStateCache.get(key)
return this.context.globalState.update(key, value)
}),
)
} catch (error) {
console.error("Failed to persist global state batch:", error)
throw error
}
}
/**
* Private method to batch persist secrets with Promise.all
*/
private async persistSecretsBatch(keys: Set<SecretKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.secretsCache.get(key)
if (value) {
return this.context.secrets.store(key, value)
} else {
return this.context.secrets.delete(key)
}
}),
)
} catch (error) {
console.error("Failed to persist secrets batch:", error)
throw error
}
}
/**
* Private method to batch persist workspace state keys with Promise.all
*/
private async persistWorkspaceStateBatch(keys: Set<LocalStateKey>): Promise<void> {
try {
await Promise.all(
Array.from(keys).map((key) => {
const value = this.workspaceStateCache.get(key)
return this.context.workspaceState.update(key, value)
}),
)
} catch (error) {
console.error("Failed to persist workspace state batch:", error)
throw error
}
}
/**
* Private method to populate API configuration cache without triggering persistence
* Used during initialization
*/
private populateApiConfigurationCache(apiConfiguration: ApiConfiguration): void {
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
basetenApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
huggingFaceApiKey,
requestTimeoutMs,
// Plan mode configurations
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configurations
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
} = apiConfiguration
// Directly populate global state cache without triggering persistence
const globalStateUpdates = {
// Plan mode configuration updates
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
// Act mode configuration updates
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
// Global state updates
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
}
// Populate global state cache directly
Object.entries(globalStateUpdates).forEach(([key, value]) => {
this.globalStateCache.set(key as GlobalStateKey, value)
})
// Directly populate secrets cache without triggering persistence
const secretsUpdates = {
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
basetenApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
huggingFaceApiKey,
}
// Populate secrets cache directly
Object.entries(secretsUpdates).forEach(([key, value]) => {
this.secretsCache.set(key as SecretKey, value)
})
}
/**
* Construct API configuration from cached component keys
*/
private constructApiConfigurationFromCache(): ApiConfiguration {
return {
// Secrets
apiKey: this.secretsCache.get("apiKey"),
openRouterApiKey: this.secretsCache.get("openRouterApiKey"),
clineAccountId: this.secretsCache.get("clineAccountId"),
awsAccessKey: this.secretsCache.get("awsAccessKey"),
awsSecretKey: this.secretsCache.get("awsSecretKey"),
awsSessionToken: this.secretsCache.get("awsSessionToken"),
awsBedrockApiKey: this.secretsCache.get("awsBedrockApiKey"),
openAiApiKey: this.secretsCache.get("openAiApiKey"),
geminiApiKey: this.secretsCache.get("geminiApiKey"),
openAiNativeApiKey: this.secretsCache.get("openAiNativeApiKey"),
deepSeekApiKey: this.secretsCache.get("deepSeekApiKey"),
requestyApiKey: this.secretsCache.get("requestyApiKey"),
togetherApiKey: this.secretsCache.get("togetherApiKey"),
qwenApiKey: this.secretsCache.get("qwenApiKey"),
doubaoApiKey: this.secretsCache.get("doubaoApiKey"),
mistralApiKey: this.secretsCache.get("mistralApiKey"),
liteLlmApiKey: this.secretsCache.get("liteLlmApiKey"),
fireworksApiKey: this.secretsCache.get("fireworksApiKey"),
asksageApiKey: this.secretsCache.get("asksageApiKey"),
xaiApiKey: this.secretsCache.get("xaiApiKey"),
sambanovaApiKey: this.secretsCache.get("sambanovaApiKey"),
cerebrasApiKey: this.secretsCache.get("cerebrasApiKey"),
groqApiKey: this.secretsCache.get("groqApiKey"),
basetenApiKey: this.secretsCache.get("basetenApiKey"),
moonshotApiKey: this.secretsCache.get("moonshotApiKey"),
nebiusApiKey: this.secretsCache.get("nebiusApiKey"),
sapAiCoreClientId: this.secretsCache.get("sapAiCoreClientId"),
sapAiCoreClientSecret: this.secretsCache.get("sapAiCoreClientSecret"),
huggingFaceApiKey: this.secretsCache.get("huggingFaceApiKey"),
// Global state
awsRegion: this.globalStateCache.get("awsRegion"),
awsUseCrossRegionInference: this.globalStateCache.get("awsUseCrossRegionInference"),
awsBedrockUsePromptCache: this.globalStateCache.get("awsBedrockUsePromptCache"),
awsBedrockEndpoint: this.globalStateCache.get("awsBedrockEndpoint"),
awsProfile: this.globalStateCache.get("awsProfile"),
awsUseProfile: this.globalStateCache.get("awsUseProfile"),
awsAuthentication: this.globalStateCache.get("awsAuthentication"),
vertexProjectId: this.globalStateCache.get("vertexProjectId"),
vertexRegion: this.globalStateCache.get("vertexRegion"),
openAiBaseUrl: this.globalStateCache.get("openAiBaseUrl"),
openAiHeaders: this.globalStateCache.get("openAiHeaders") || {},
ollamaBaseUrl: this.globalStateCache.get("ollamaBaseUrl"),
ollamaApiOptionsCtxNum: this.globalStateCache.get("ollamaApiOptionsCtxNum"),
lmStudioBaseUrl: this.globalStateCache.get("lmStudioBaseUrl"),
anthropicBaseUrl: this.globalStateCache.get("anthropicBaseUrl"),
geminiBaseUrl: this.globalStateCache.get("geminiBaseUrl"),
azureApiVersion: this.globalStateCache.get("azureApiVersion"),
openRouterProviderSorting: this.globalStateCache.get("openRouterProviderSorting"),
liteLlmBaseUrl: this.globalStateCache.get("liteLlmBaseUrl"),
liteLlmUsePromptCache: this.globalStateCache.get("liteLlmUsePromptCache"),
qwenApiLine: this.globalStateCache.get("qwenApiLine"),
moonshotApiLine: this.globalStateCache.get("moonshotApiLine"),
asksageApiUrl: this.globalStateCache.get("asksageApiUrl"),
favoritedModelIds: this.globalStateCache.get("favoritedModelIds"),
requestTimeoutMs: this.globalStateCache.get("requestTimeoutMs"),
fireworksModelMaxCompletionTokens: this.globalStateCache.get("fireworksModelMaxCompletionTokens"),
fireworksModelMaxTokens: this.globalStateCache.get("fireworksModelMaxTokens"),
sapAiCoreBaseUrl: this.globalStateCache.get("sapAiCoreBaseUrl"),
sapAiCoreTokenUrl: this.globalStateCache.get("sapAiCoreTokenUrl"),
sapAiResourceGroup: this.globalStateCache.get("sapAiResourceGroup"),
claudeCodePath: this.globalStateCache.get("claudeCodePath"),
// Plan mode configurations
planModeApiProvider: this.globalStateCache.get("planModeApiProvider"),
planModeApiModelId: this.globalStateCache.get("planModeApiModelId"),
planModeThinkingBudgetTokens: this.globalStateCache.get("planModeThinkingBudgetTokens"),
planModeReasoningEffort: this.globalStateCache.get("planModeReasoningEffort"),
planModeVsCodeLmModelSelector: this.globalStateCache.get("planModeVsCodeLmModelSelector"),
planModeAwsBedrockCustomSelected: this.globalStateCache.get("planModeAwsBedrockCustomSelected"),
planModeAwsBedrockCustomModelBaseId: this.globalStateCache.get("planModeAwsBedrockCustomModelBaseId"),
planModeOpenRouterModelId: this.globalStateCache.get("planModeOpenRouterModelId"),
planModeOpenRouterModelInfo: this.globalStateCache.get("planModeOpenRouterModelInfo"),
planModeOpenAiModelId: this.globalStateCache.get("planModeOpenAiModelId"),
planModeOpenAiModelInfo: this.globalStateCache.get("planModeOpenAiModelInfo"),
planModeOllamaModelId: this.globalStateCache.get("planModeOllamaModelId"),
planModeLmStudioModelId: this.globalStateCache.get("planModeLmStudioModelId"),
planModeLiteLlmModelId: this.globalStateCache.get("planModeLiteLlmModelId"),
planModeLiteLlmModelInfo: this.globalStateCache.get("planModeLiteLlmModelInfo"),
planModeRequestyModelId: this.globalStateCache.get("planModeRequestyModelId"),
planModeRequestyModelInfo: this.globalStateCache.get("planModeRequestyModelInfo"),
planModeTogetherModelId: this.globalStateCache.get("planModeTogetherModelId"),
planModeFireworksModelId: this.globalStateCache.get("planModeFireworksModelId"),
planModeSapAiCoreModelId: this.globalStateCache.get("planModeSapAiCoreModelId"),
planModeGroqModelId: this.globalStateCache.get("planModeGroqModelId"),
planModeGroqModelInfo: this.globalStateCache.get("planModeGroqModelInfo"),
planModeBasetenModelId: this.globalStateCache.get("planModeBasetenModelId"),
planModeBasetenModelInfo: this.globalStateCache.get("planModeBasetenModelInfo"),
planModeHuggingFaceModelId: this.globalStateCache.get("planModeHuggingFaceModelId"),
planModeHuggingFaceModelInfo: this.globalStateCache.get("planModeHuggingFaceModelInfo"),
// Act mode configurations
actModeApiProvider: this.globalStateCache.get("actModeApiProvider"),
actModeApiModelId: this.globalStateCache.get("actModeApiModelId"),
actModeThinkingBudgetTokens: this.globalStateCache.get("actModeThinkingBudgetTokens"),
actModeReasoningEffort: this.globalStateCache.get("actModeReasoningEffort"),
actModeVsCodeLmModelSelector: this.globalStateCache.get("actModeVsCodeLmModelSelector"),
actModeAwsBedrockCustomSelected: this.globalStateCache.get("actModeAwsBedrockCustomSelected"),
actModeAwsBedrockCustomModelBaseId: this.globalStateCache.get("actModeAwsBedrockCustomModelBaseId"),
actModeOpenRouterModelId: this.globalStateCache.get("actModeOpenRouterModelId"),
actModeOpenRouterModelInfo: this.globalStateCache.get("actModeOpenRouterModelInfo"),
actModeOpenAiModelId: this.globalStateCache.get("actModeOpenAiModelId"),
actModeOpenAiModelInfo: this.globalStateCache.get("actModeOpenAiModelInfo"),
actModeOllamaModelId: this.globalStateCache.get("actModeOllamaModelId"),
actModeLmStudioModelId: this.globalStateCache.get("actModeLmStudioModelId"),
actModeLiteLlmModelId: this.globalStateCache.get("actModeLiteLlmModelId"),
actModeLiteLlmModelInfo: this.globalStateCache.get("actModeLiteLlmModelInfo"),
actModeRequestyModelId: this.globalStateCache.get("actModeRequestyModelId"),
actModeRequestyModelInfo: this.globalStateCache.get("actModeRequestyModelInfo"),
actModeTogetherModelId: this.globalStateCache.get("actModeTogetherModelId"),
actModeFireworksModelId: this.globalStateCache.get("actModeFireworksModelId"),
actModeSapAiCoreModelId: this.globalStateCache.get("actModeSapAiCoreModelId"),
actModeGroqModelId: this.globalStateCache.get("actModeGroqModelId"),
actModeGroqModelInfo: this.globalStateCache.get("actModeGroqModelInfo"),
actModeBasetenModelId: this.globalStateCache.get("actModeBasetenModelId"),
actModeBasetenModelInfo: this.globalStateCache.get("actModeBasetenModelInfo"),
actModeHuggingFaceModelId: this.globalStateCache.get("actModeHuggingFaceModelId"),
actModeHuggingFaceModelInfo: this.globalStateCache.get("actModeHuggingFaceModelInfo"),
} as ApiConfiguration
}
}
+1
View File
@@ -14,6 +14,7 @@ export const GlobalFileNames = {
uiMessages: "ui_messages.json",
openRouterModels: "openrouter_models.json",
groqModels: "groq_models.json",
basetenModels: "baseten_models.json",
mcpSettings: "cline_mcp_settings.json",
clineRules: ".clinerules",
workflows: ".clinerules/workflows",
+1
View File
@@ -0,0 +1 @@
export const CACHE_SERVICE_NOT_INITIALIZED = "CacheService must be initialized before attempting to access state."
+6
View File
@@ -29,6 +29,7 @@ export type SecretKey =
| "sapAiCoreClientSecret"
| "groqApiKey"
| "huaweiCloudMaasApiKey"
| "basetenApiKey"
export type GlobalStateKey =
| "awsRegion"
@@ -83,6 +84,7 @@ export type GlobalStateKey =
| "sapAiCoreBaseUrl"
| "sapAiResourceGroup"
| "claudeCodePath"
| "strictPlanModeEnabled"
// Settings around plan/act and ephemeral model configuration
| "preferredLanguage"
| "openaiReasoningEffort"
@@ -110,6 +112,8 @@ export type GlobalStateKey =
| "planModeSapAiCoreModelId"
| "planModeGroqModelId"
| "planModeGroqModelInfo"
| "planModeBasetenModelId"
| "planModeBasetenModelInfo"
| "planModeHuggingFaceModelId"
| "planModeHuggingFaceModelInfo"
| "planModeHuaweiCloudMaasModelId"
@@ -137,6 +141,8 @@ export type GlobalStateKey =
| "actModeSapAiCoreModelId"
| "actModeGroqModelId"
| "actModeGroqModelInfo"
| "actModeBasetenModelId"
| "actModeBasetenModelInfo"
| "actModeHuggingFaceModelId"
| "actModeHuggingFaceModelInfo"
| "actModeHuaweiCloudMaasModelId"
+40 -258
View File
@@ -12,6 +12,7 @@ import { UserInfo } from "@shared/UserInfo"
import { ClineRulesToggles } from "@shared/cline-rules"
import { DEFAULT_MCP_DISPLAY_MODE, McpDisplayMode } from "@shared/McpDisplayMode"
import { migrateEnableCheckpointsSetting, migrateMcpMarketplaceEnableSetting } from "./state-migrations"
import { Controller } from "../controller"
/*
Storage
https://dev.to/kompotkot/how-to-use-secretstorage-in-your-vscode-extensions-2hco
@@ -166,6 +167,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
basetenApiKey,
moonshotApiKey,
nebiusApiKey,
huggingFaceApiKey,
@@ -246,6 +248,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getSecret(context, "sambanovaApiKey") as Promise<string | undefined>,
getSecret(context, "cerebrasApiKey") as Promise<string | undefined>,
getSecret(context, "groqApiKey") as Promise<string | undefined>,
getSecret(context, "basetenApiKey") as Promise<string | undefined>,
getSecret(context, "moonshotApiKey") as Promise<string | undefined>,
getSecret(context, "nebiusApiKey") as Promise<string | undefined>,
getSecret(context, "huggingFaceApiKey") as Promise<string | undefined>,
@@ -271,12 +274,18 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getSecret(context, "huaweiCloudMaasApiKey") as Promise<string | undefined>,
])
const localClineRulesToggles = (await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles
const [localClineRulesToggles, localWindsurfRulesToggles, localCursorRulesToggles, localWorkflowToggles] = await Promise.all([
getWorkspaceState(context, "localClineRulesToggles") as Promise<ClineRulesToggles | undefined>,
getWorkspaceState(context, "localWindsurfRulesToggles") as Promise<ClineRulesToggles | undefined>,
getWorkspaceState(context, "localCursorRulesToggles") as Promise<ClineRulesToggles | undefined>,
getWorkspaceState(context, "workflowToggles") as Promise<ClineRulesToggles | undefined>,
])
const [
preferredLanguage,
openaiReasoningEffort,
mode,
strictPlanModeEnabled,
// Plan mode configurations
planModeApiProvider,
planModeApiModelId,
@@ -300,6 +309,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
planModeHuaweiCloudMaasModelId,
@@ -327,6 +338,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
actModeHuaweiCloudMaasModelId,
@@ -335,6 +348,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getGlobalState(context, "preferredLanguage") as Promise<string | undefined>,
getGlobalState(context, "openaiReasoningEffort") as Promise<OpenaiReasoningEffort | undefined>,
getGlobalState(context, "mode") as Promise<Mode | undefined>,
getGlobalState(context, "strictPlanModeEnabled") as Promise<boolean | undefined>,
// Plan mode configurations
getGlobalState(context, "planModeApiProvider") as Promise<ApiProvider | undefined>,
getGlobalState(context, "planModeApiModelId") as Promise<string | undefined>,
@@ -358,6 +372,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getGlobalState(context, "planModeSapAiCoreModelId") as Promise<string | undefined>,
getGlobalState(context, "planModeGroqModelId") as Promise<string | undefined>,
getGlobalState(context, "planModeGroqModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "planModeBasetenModelId") as Promise<string | undefined>,
getGlobalState(context, "planModeBasetenModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "planModeHuggingFaceModelId") as Promise<string | undefined>,
getGlobalState(context, "planModeHuggingFaceModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "planModeHuaweiCloudMaasModelId") as Promise<string | undefined>,
@@ -385,6 +401,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getGlobalState(context, "actModeSapAiCoreModelId") as Promise<string | undefined>,
getGlobalState(context, "actModeGroqModelId") as Promise<string | undefined>,
getGlobalState(context, "actModeGroqModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "actModeBasetenModelId") as Promise<string | undefined>,
getGlobalState(context, "actModeBasetenModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "actModeHuggingFaceModelId") as Promise<string | undefined>,
getGlobalState(context, "actModeHuggingFaceModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "actModeHuaweiCloudMaasModelId") as Promise<string | undefined>,
@@ -478,6 +496,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
basetenApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
@@ -512,6 +531,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeBasetenModelId,
planModeBasetenModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
planModeHuaweiCloudMaasModelId,
@@ -539,6 +560,8 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeBasetenModelId,
actModeBasetenModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
actModeHuaweiCloudMaasModelId,
@@ -550,11 +573,11 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
taskHistory,
autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
globalClineRulesToggles: globalClineRulesToggles || {},
localClineRulesToggles: localClineRulesToggles || {},
browserSettings: { ...DEFAULT_BROWSER_SETTINGS, ...browserSettings }, // this will ensure that older versions of browserSettings (e.g. before remoteBrowserEnabled was added) are merged with the default values (false for remoteBrowserEnabled)
preferredLanguage: preferredLanguage || "English",
openaiReasoningEffort: (openaiReasoningEffort as OpenaiReasoningEffort) || "medium",
mode: mode || "act",
strictPlanModeEnabled: strictPlanModeEnabled ?? false,
userInfo,
mcpMarketplaceEnabled: mcpMarketplaceEnabled,
mcpDisplayMode: mcpDisplayMode ?? DEFAULT_MCP_DISPLAY_MODE,
@@ -567,266 +590,25 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
terminalOutputLineLimit: terminalOutputLineLimit ?? 500,
defaultTerminalProfile: defaultTerminalProfile ?? "default",
globalWorkflowToggles: globalWorkflowToggles || {},
localClineRulesToggles: localClineRulesToggles || {},
localWindsurfRulesToggles: localWindsurfRulesToggles || {},
localCursorRulesToggles: localCursorRulesToggles || {},
localWorkflowToggles: localWorkflowToggles || {},
}
}
export async function updateApiConfiguration(context: vscode.ExtensionContext, apiConfiguration: ApiConfiguration) {
const {
apiKey,
openRouterApiKey,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsBedrockApiKey,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiApiKey,
openAiHeaders,
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiApiKey,
geminiBaseUrl,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmApiKey,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiKey,
asksageApiUrl,
xaiApiKey,
clineAccountId,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
favoritedModelIds,
fireworksApiKey,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreClientId,
sapAiCoreClientSecret,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
huggingFaceApiKey,
huaweiCloudMaasApiKey,
// Plan mode configurations
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
planModeHuaweiCloudMaasModelId,
planModeHuaweiCloudMaasModelInfo,
// Act mode configurations
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
actModeHuaweiCloudMaasModelId,
actModeHuaweiCloudMaasModelInfo,
} = apiConfiguration
export async function resetWorkspaceState(controller: Controller) {
const context = controller.context
await Promise.all(context.workspaceState.keys().map((key) => controller.context.workspaceState.update(key, undefined)))
// OPTIMIZED: Batch all global state updates into 2 operations instead of 47
const batchedGlobalUpdates = {
// Plan mode configuration updates
planModeApiProvider,
planModeApiModelId,
planModeThinkingBudgetTokens,
planModeReasoningEffort,
planModeVsCodeLmModelSelector,
planModeAwsBedrockCustomSelected,
planModeAwsBedrockCustomModelBaseId,
planModeOpenRouterModelId,
planModeOpenRouterModelInfo,
planModeOpenAiModelId,
planModeOpenAiModelInfo,
planModeOllamaModelId,
planModeLmStudioModelId,
planModeLiteLlmModelId,
planModeLiteLlmModelInfo,
planModeRequestyModelId,
planModeRequestyModelInfo,
planModeTogetherModelId,
planModeFireworksModelId,
planModeSapAiCoreModelId,
planModeGroqModelId,
planModeGroqModelInfo,
planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo,
planModeHuaweiCloudMaasModelId,
planModeHuaweiCloudMaasModelInfo,
// Act mode configuration updates
actModeApiProvider,
actModeApiModelId,
actModeThinkingBudgetTokens,
actModeReasoningEffort,
actModeVsCodeLmModelSelector,
actModeAwsBedrockCustomSelected,
actModeAwsBedrockCustomModelBaseId,
actModeOpenRouterModelId,
actModeOpenRouterModelInfo,
actModeOpenAiModelId,
actModeOpenAiModelInfo,
actModeOllamaModelId,
actModeLmStudioModelId,
actModeLiteLlmModelId,
actModeLiteLlmModelInfo,
actModeRequestyModelId,
actModeRequestyModelInfo,
actModeTogetherModelId,
actModeFireworksModelId,
actModeSapAiCoreModelId,
actModeGroqModelId,
actModeGroqModelInfo,
actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo,
actModeHuaweiCloudMaasModelId,
actModeHuaweiCloudMaasModelInfo,
// Global state updates (27 keys)
awsRegion,
awsUseCrossRegionInference,
awsBedrockUsePromptCache,
awsBedrockEndpoint,
awsProfile,
awsUseProfile,
awsAuthentication,
vertexProjectId,
vertexRegion,
openAiBaseUrl,
openAiHeaders: openAiHeaders || {},
ollamaBaseUrl,
ollamaApiOptionsCtxNum,
lmStudioBaseUrl,
anthropicBaseUrl,
geminiBaseUrl,
azureApiVersion,
openRouterProviderSorting,
liteLlmBaseUrl,
liteLlmUsePromptCache,
qwenApiLine,
moonshotApiLine,
asksageApiUrl,
favoritedModelIds,
requestTimeoutMs: apiConfiguration.requestTimeoutMs,
fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens,
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
claudeCodePath,
}
// OPTIMIZED: Batch all secret updates into 1 operation instead of 23
const batchedSecretUpdates = {
apiKey,
openRouterApiKey,
clineAccountId,
awsAccessKey,
awsSecretKey,
awsSessionToken,
awsBedrockApiKey,
openAiApiKey,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
requestyApiKey,
togetherApiKey,
qwenApiKey,
doubaoApiKey,
mistralApiKey,
liteLlmApiKey,
fireworksApiKey,
asksageApiKey,
xaiApiKey,
sambanovaApiKey,
cerebrasApiKey,
groqApiKey,
moonshotApiKey,
nebiusApiKey,
sapAiCoreClientId,
sapAiCoreClientSecret,
huggingFaceApiKey,
huaweiCloudMaasApiKey,
}
// Execute batched operations in parallel for maximum performance
await Promise.all([updateGlobalStateBatch(context, batchedGlobalUpdates), updateSecretsBatch(context, batchedSecretUpdates)])
await controller.cacheService.reInitialize()
}
export async function resetWorkspaceState(context: vscode.ExtensionContext) {
for (const key of context.workspaceState.keys()) {
await context.workspaceState.update(key, undefined)
}
}
export async function resetGlobalState(context: vscode.ExtensionContext) {
export async function resetGlobalState(controller: Controller) {
// TODO: Reset all workspace states?
for (const key of context.globalState.keys()) {
await context.globalState.update(key, undefined)
}
const context = controller.context
await Promise.all(context.globalState.keys().map((key) => context.globalState.update(key, undefined)))
const secretKeys: SecretKey[] = [
"apiKey",
"openRouterApiKey",
@@ -851,12 +633,12 @@ export async function resetGlobalState(context: vscode.ExtensionContext) {
"sambanovaApiKey",
"cerebrasApiKey",
"groqApiKey",
"basetenApiKey",
"moonshotApiKey",
"nebiusApiKey",
"huggingFaceApiKey",
"huaweiCloudMaasApiKey",
]
for (const key of secretKeys) {
await storeSecret(context, key, undefined)
}
await Promise.all(secretKeys.map((key) => storeSecret(context, key, undefined)))
await controller.cacheService.reInitialize()
}
+38 -9
View File
@@ -35,7 +35,7 @@ import { ClineAskResponse } from "@shared/WebviewMessage"
import { extractFileContent, FileContentResult } from "@integrations/misc/extract-file-content"
import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences"
import { fileExistsAtPath } from "@utils/fs"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily, isGrok4ModelFamily, modelDoesntSupportWebp } from "@utils/model-utils"
import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import os from "os"
@@ -50,7 +50,7 @@ import { ContextManager } from "../context/context-management/ContextManager"
import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation"
import { formatResponse } from "../prompts/responses"
import { ensureTaskDirectoryExists } from "../storage/disk"
import { getGlobalState, getWorkspaceState } from "../storage/state"
import { CacheService } from "../storage/CacheService"
import { TaskState } from "./TaskState"
import { MessageStateHandler } from "./message-state"
import { AutoApprove } from "./tools/autoApprove"
@@ -86,6 +86,7 @@ export class ToolExecutor {
private clineIgnoreController: ClineIgnoreController,
private workspaceTracker: WorkspaceTracker,
private contextManager: ContextManager,
private cacheService: CacheService,
// Configuration & Settings
private autoApprovalSettings: AutoApprovalSettings,
@@ -93,6 +94,7 @@ export class ToolExecutor {
private cwd: string,
private taskId: string,
private mode: Mode,
private strictPlanModeEnabled: boolean,
// Callbacks to the Task (Entity)
private say: (
@@ -123,8 +125,25 @@ export class ToolExecutor {
this.autoApprover.updateSettings(settings)
}
/**
* Defines the tools which should be restricted in plan mode
*/
private isPlanModeToolRestricted(toolName: ToolUseName): boolean {
const planModeRestrictedTools: ToolUseName[] = ["write_to_file", "replace_in_file"]
return planModeRestrictedTools.includes(toolName)
}
public updateMode(mode: Mode): void {
this.mode = mode
}
public updateStrictPlanModeEnabled(strictPlanModeEnabled: boolean): void {
this.strictPlanModeEnabled = strictPlanModeEnabled
}
private pushToolResult = (content: ToolResponse, block: ToolUse) => {
const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api)
const isNextGenModel =
isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api) || isGrok4ModelFamily(this.api)
if (typeof content === "string") {
const resultText = content || "(tool did not return anything)"
@@ -435,6 +454,15 @@ export class ToolExecutor {
return
}
// Logic for plan-model tool call restrictions
if (this.strictPlanModeEnabled && this.mode === "plan" && block.name && this.isPlanModeToolRestricted(block.name)) {
const errorMessage = `Tool '${block.name}' is not available in PLAN MODE. This tool is restricted to ACT MODE for file modifications. Only use tools available for PLAN MODE when in that mode.`
await this.say("error", errorMessage)
this.pushToolResult(formatResponse.toolError(errorMessage), block)
await this.saveCheckpoint()
return
}
if (block.name !== "browser_action") {
await this.browserSession.closeBrowser()
}
@@ -489,7 +517,8 @@ export class ToolExecutor {
const currentFullJson = block.params.diff
// Check if we should use streaming (e.g., for specific models)
const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api)
const isNextGenModel =
isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api) || isGrok4ModelFamily(this.api)
// Going through claude family of models
if (isNextGenModel && USE_EXPERIMENTAL_CLAUDE4_FEATURES && currentFullJson) {
const streamingResult = await this.handleStreamingJsonReplacement(block, relPath, currentFullJson)
@@ -1182,7 +1211,9 @@ export class ToolExecutor {
// Re-make browserSession to make sure latest settings apply
if (this.context) {
await this.browserSession.dispose()
this.browserSession = new BrowserSession(this.context, this.browserSettings)
let useWebp = this.api ? !modelDoesntSupportWebp(this.api) : true
this.browserSession = new BrowserSession(this.context, this.browserSettings, useWebp)
} else {
console.warn("no controller context available for browserSession")
}
@@ -1927,10 +1958,8 @@ export class ToolExecutor {
vscode.extensions.getExtension("saoudrizwan.claude-dev")?.packageJSON.version || "Unknown"
const systemInfo = `VSCode: ${vscode.version}, Node.js: ${process.version}, Architecture: ${os.arch()}`
const currentMode = this.mode
const apiProvider =
currentMode === "plan"
? await getGlobalState(this.context, "planModeApiProvider")
: await getGlobalState(this.context, "actModeApiProvider")
const apiConfig = this.cacheService.getApiConfiguration()
const apiProvider = currentMode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider
const providerAndModel = `${apiProvider} / ${this.api.getModel().id}`
// Ask user for confirmation
+48 -17
View File
@@ -77,7 +77,7 @@ import { processFilesIntoText } from "@integrations/misc/extract-text"
import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker"
import { McpHub } from "@services/mcp/McpHub"
import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily, isGrok4ModelFamily } from "@utils/model-utils"
import { isInTestMode } from "../../services/test/TestMode"
import { ensureLocalClineDirExists } from "../context/instructions/user-instructions/rule-helpers"
import { refreshWorkflowToggles } from "../context/instructions/user-instructions/workflows"
@@ -85,6 +85,7 @@ import { MessageStateHandler } from "./message-state"
import { TaskState } from "./TaskState"
import { ToolExecutor } from "./ToolExecutor"
import { updateApiReqMsg } from "./utils"
import { CacheService } from "../storage/CacheService"
import { Mode, OpenaiReasoningEffort } from "@shared/storage/types"
import { ShowMessageType } from "@/shared/proto/index.host"
@@ -130,6 +131,9 @@ export class Task {
private reinitExistingTaskFromId: (taskId: string) => Promise<void>
private cancelTask: () => Promise<void>
// Cache service
private cacheService: CacheService
// User chat state
autoApprovalSettings: AutoApprovalSettings
browserSettings: BrowserSettings
@@ -153,12 +157,14 @@ export class Task {
preferredLanguage: string,
openaiReasoningEffort: OpenaiReasoningEffort,
mode: Mode,
strictPlanModeEnabled: boolean,
shellIntegrationTimeout: number,
terminalReuseEnabled: boolean,
terminalOutputLineLimit: number,
defaultTerminalProfile: string,
enableCheckpointsSetting: boolean,
cwd: string,
cacheService: CacheService,
task?: string,
images?: string[],
files?: string[],
@@ -202,6 +208,7 @@ export class Task {
this.mode = mode
this.enableCheckpoints = enableCheckpointsSetting
this.cwd = cwd
this.cacheService = cacheService
// Set up MCP notification callback for real-time notifications
this.mcpHub.setNotificationCallback(async (serverName: string, level: string, message: string) => {
@@ -236,7 +243,7 @@ export class Task {
this.modelContextTracker = new ModelContextTracker(context, this.taskId)
// Prepare effective API configuration
let effectiveApiConfiguration: ApiConfiguration = {
const effectiveApiConfiguration: ApiConfiguration = {
...apiConfiguration,
taskId: this.taskId,
onRetryAttempt: async (attempt: number, maxRetries: number, delay: number, error: any) => {
@@ -318,11 +325,13 @@ export class Task {
this.clineIgnoreController,
this.workspaceTracker,
this.contextManager,
this.cacheService,
this.autoApprovalSettings,
this.browserSettings,
cwd,
this.taskId,
this.mode,
strictPlanModeEnabled,
this.say.bind(this),
this.ask.bind(this),
this.saveCheckpoint.bind(this),
@@ -333,6 +342,15 @@ export class Task {
)
}
public updateMode(mode: Mode): void {
this.mode = mode
this.toolExecutor.updateMode(mode)
}
public updateStrictPlanMode(strictPlanModeEnabled: boolean): void {
this.toolExecutor.updateStrictPlanModeEnabled(strictPlanModeEnabled)
}
// While a task is ref'd by a controller, it will always have access to the extension context
// This error is thrown if the controller derefs the task after e.g., aborting the task
private getContext(): vscode.ExtensionContext {
@@ -456,7 +474,7 @@ export class Task {
if (!didWorkspaceRestoreFail) {
switch (restoreType) {
case "task":
case "taskAndWorkspace":
case "taskAndWorkspace": {
this.taskState.conversationHistoryDeletedRange = message.conversationHistoryDeletedRange
const apiConversationHistory = this.messageStateHandler.getApiConversationHistory()
const newConversationHistory = apiConversationHistory.slice(0, (message.conversationHistoryIndex || 0) + 2) // +1 since this index corresponds to the last user message, and another +1 since slice end index is exclusive
@@ -499,6 +517,7 @@ export class Task {
} satisfies ClineApiReqInfo),
)
break
}
case "workspace":
break
}
@@ -1025,9 +1044,9 @@ export class Task {
this.taskState.isInitialized = true
let imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
const imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
let userContent: UserContent = [
const userContent: UserContent = [
{
type: "text",
text: `<task>\n${task}\n</task>`,
@@ -1154,7 +1173,7 @@ export class Task {
throw new Error("Unexpected: No existing API conversation history")
}
let newUserContent: UserContent = [...modifiedOldUserContent]
const newUserContent: UserContent = [...modifiedOldUserContent]
const agoText = (() => {
const timestamp = lastClineMessage?.ts ?? Date.now()
@@ -1610,7 +1629,7 @@ export class Task {
// grouping command_output messages despite any gaps anyways)
await setTimeoutPromise(50)
let result = this.terminalManager.processOutput(outputLines)
const result = this.terminalManager.processOutput(outputLines)
if (userFeedback) {
await this.say("user_feedback", userFeedback.text, userFeedback.images, userFeedback.files)
@@ -1661,10 +1680,8 @@ export class Task {
private async getCurrentProviderInfo(): Promise<{ modelId: string; providerId: string }> {
const modelId = this.api.getModel()?.id
const providerId =
this.mode === "plan"
? ((await getGlobalState(this.getContext(), "planModeApiProvider")) as string)
: ((await getGlobalState(this.getContext(), "actModeApiProvider")) as string)
const apiConfig = this.cacheService.getApiConfiguration()
const providerId = (this.mode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider) as string
return { modelId, providerId }
}
@@ -1682,7 +1699,8 @@ export class Task {
const supportsBrowserUse = modelSupportsBrowserUse && !disableBrowserTool // only enable browser use if the model supports it and the user hasn't disabled it
const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api)
const isNextGenModel =
isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api) || isGrok4ModelFamily(this.api)
let systemPrompt = await SYSTEM_PROMPT(this.cwd, supportsBrowserUse, this.mcpHub, this.browserSettings, isNextGenModel)
const preferredLanguage = getLanguageKey(this.preferredLanguage as LanguageDisplay)
@@ -1746,7 +1764,7 @@ export class Task {
// saves task history item which we use to keep track of conversation history deleted range
}
let stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory)
const stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory)
const iterator = stream[Symbol.asyncIterator]()
@@ -1851,12 +1869,24 @@ export class Task {
throw new Error("API request failed")
}
// Do not retry automatically again if currently unauthenticated
if (clineError.isErrorType(ClineErrorType.Auth)) {
return
// Clear streamingFailedMessage when user manually retries
const manualRetryApiReqIndex = findLastIndex(
this.messageStateHandler.getClineMessages(),
(m) => m.say === "api_req_started",
)
if (manualRetryApiReqIndex !== -1) {
const clineMessages = this.messageStateHandler.getClineMessages()
const currentApiReqInfo: ClineApiReqInfo = JSON.parse(clineMessages[manualRetryApiReqIndex].text || "{}")
delete currentApiReqInfo.streamingFailedMessage
await this.messageStateHandler.updateClineMessage(manualRetryApiReqIndex, {
text: JSON.stringify(currentApiReqInfo),
})
}
await this.say("api_req_retried")
// Reset the automatic retry flag so the request can proceed
this.taskState.didAutomaticallyRetryFailedApiRequest = false
}
// delegate generator output from the recursive call
yield* this.attemptApiRequest(previousApiReqIndex)
@@ -2315,7 +2345,7 @@ export class Task {
await this.say("reasoning", reasoningMessage, undefined, undefined, true)
}
break
case "text":
case "text": {
if (reasoningMessage && assistantMessage.length === 0) {
// complete reasoning message
await this.say("reasoning", reasoningMessage, undefined, undefined, false)
@@ -2336,6 +2366,7 @@ export class Task {
// present content to user
this.presentAssistantMessage()
break
}
}
if (this.taskState.abort) {
+5 -10
View File
@@ -18,7 +18,6 @@ export abstract class WebviewProvider {
public static readonly tabPanelId = "claude-dev.TabPanelProvider"
private static activeInstances: Set<WebviewProvider> = new Set()
private static clientIdMap = new Map<WebviewProvider, string>()
protected disposables: vscode.Disposable[] = []
controller: Controller
private clientId: string
@@ -30,6 +29,8 @@ export abstract class WebviewProvider {
WebviewProvider.activeInstances.add(this)
this.clientId = uuidv4()
WebviewProvider.clientIdMap.set(this, this.clientId)
// Create controller with cache service
this.controller = new Controller(context, (message) => this.postMessageToWebview(message), this.clientId)
}
@@ -44,12 +45,6 @@ export abstract class WebviewProvider {
}
async dispose() {
while (this.disposables.length) {
const x = this.disposables.pop()
if (x) {
x.dispose()
}
}
await this.controller.dispose()
WebviewProvider.activeInstances.delete(this)
// Remove from client ID map
@@ -262,8 +257,8 @@ export abstract class WebviewProvider {
try {
await axios.get(`http://${localServerUrl}`)
} catch (error) {
// Only show the error message if not in development mode.
if (!process.env.IS_DEV) {
// Only show the error message when in development mode.
if (process.env.IS_DEV) {
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
message:
@@ -304,7 +299,7 @@ export abstract class WebviewProvider {
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://localhost:8097"></script>
${process.env.IS_DEV ? '<script src="http://localhost:8097"></script>' : ""}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta http-equiv="Content-Security-Policy" content="${csp.join("; ")}">
+10 -39
View File
@@ -38,6 +38,8 @@ import { VscodeWebviewProvider } from "./hosts/vscode/VscodeWebviewProvider"
import { GitCommitGenerator } from "./integrations/git/commit-message-generator"
import { AuthService } from "./services/auth/AuthService"
import { ShowMessageType } from "./shared/proto/host/window"
import { SharedUriHandler } from "./services/uri/SharedUriHandler"
import { getLatestAnnouncementId } from "./utils/announcements"
/*
Built using https://github.com/microsoft/vscode-webview-ui-toolkit
@@ -91,7 +93,7 @@ export async function activate(context: vscode.ExtensionContext) {
// Use the same condition as announcements: focus when there's a new announcement to show
const lastShownAnnouncementId = context.globalState.get<string>("lastShownAnnouncementId")
const latestAnnouncementId = context.extension?.packageJSON?.version?.split(".").slice(0, 2).join(".") ?? ""
const latestAnnouncementId = getLatestAnnouncementId(context)
if (lastShownAnnouncementId !== latestAnnouncementId) {
// Focus Cline when there's a new announcement to show (major/minor updates or fresh installs)
@@ -265,44 +267,10 @@ export async function activate(context: vscode.ExtensionContext) {
})()
context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(DIFF_VIEW_URI_SCHEME, diffContentProvider))
// URI Handler
const handleUri = async (uri: vscode.Uri) => {
console.log("URI Handler called with:", {
path: uri.path,
query: uri.query,
scheme: uri.scheme,
})
const path = uri.path
const query = new URLSearchParams(uri.query.replace(/\+/g, "%2B"))
const visibleWebview = WebviewProvider.getVisibleInstance()
if (!visibleWebview) {
return
}
switch (path) {
case "/openrouter": {
const code = query.get("code")
if (code) {
await visibleWebview?.controller.handleOpenRouterCallback(code)
}
break
}
case "/auth": {
console.log("Auth callback received:", uri.toString())
const token = query.get("idToken")
const provider = query.get("provider")
console.log("Auth callback received:", { provider })
if (token) {
await visibleWebview?.controller.handleAuthCallback(token, provider)
// await authService.handleAuthCallback(token)
}
break
}
default:
break
const success = await SharedUriHandler.handleUri(uri)
if (!success) {
console.warn("Extension URI handler: Failed to process URI:", uri.toString())
}
}
context.subscriptions.push(vscode.window.registerUriHandler({ handleUri }))
@@ -664,7 +632,10 @@ export async function activate(context: vscode.ExtensionContext) {
if (event.key === "clineAccountId") {
// Check if the secret was removed (logout) or added/updated (login)
const secretValue = await context.secrets.get("clineAccountId")
const authService = AuthService.getInstance(context)
const activeWebviewProvider = WebviewProvider.getVisibleInstance()
const controller = activeWebviewProvider?.controller
const authService = AuthService.getInstance(controller)
if (secretValue) {
// Secret was added or updated - restore auth info (login from another window)
authService?.restoreRefreshTokenAndRetrieveAuthInfo()
+276
View File
@@ -0,0 +1,276 @@
import type { IncomingMessage, Server, ServerResponse } from "node:http"
import http from "node:http"
import type { AddressInfo } from "node:net"
import { clineEnvConfig } from "@/config"
import { openExternal } from "@/utils/env"
import { SharedUriHandler } from "@/services/uri/SharedUriHandler"
const SERVER_TIMEOUT = 10 * 60 * 1000 // 10 minutes
/**
* Handles OAuth authentication flow by creating a local server to receive tokens.
*/
export class AuthHandler {
private static instance: AuthHandler | null = null
private port = 0
private server: Server | null = null
private serverCreationPromise: Promise<void> | null = null
private timeoutId: NodeJS.Timeout | null = null
private enabled: boolean = false
private constructor() {}
/**
* Gets the singleton instance of AuthHandler
* @returns The singleton AuthHandler instance
*/
public static getInstance(): AuthHandler {
if (!AuthHandler.instance) {
AuthHandler.instance = new AuthHandler()
}
return AuthHandler.instance
}
public setEnabled(enabled: boolean): void {
this.enabled = enabled
}
public async getCallbackUri(): Promise<string | undefined> {
try {
if (!this.enabled) {
return undefined
}
if (!this.server) {
// If server creation is already in progress, wait for it
if (this.serverCreationPromise) {
await this.serverCreationPromise
} else {
// Start server creation and track the promise
this.serverCreationPromise = this.createServer()
await this.serverCreationPromise
}
} else {
this.updateTimeout()
}
return `http://127.0.0.1:${this.port}`
} catch (error) {
console.error("AuthHandler.getCallbackUri error:", error)
return undefined
}
}
private async createServer(): Promise<void> {
return new Promise((resolve, reject) => {
try {
const server = http.createServer(this.handleRequest.bind(this))
// Use callback to ensure server is ready before getting address
server.listen(0, "127.0.0.1", () => {
const address = server.address()
if (!address) {
console.error("AuthHandler: Failed to get server address")
this.server = null
this.port = 0
this.serverCreationPromise = null
reject(new Error("Failed to get server address"))
return
}
// Get the assigned port and set up the server
this.port = (address as AddressInfo).port
this.server = server
console.log("AuthHandler: Server started on port", this.port)
this.updateTimeout()
this.serverCreationPromise = null
resolve()
})
server.on("error", (error) => {
console.error("AuthHandler: Server error", error)
this.server = null
this.port = 0
this.serverCreationPromise = null
reject(error)
})
} catch (error) {
console.error("AuthHandler: Failed to create server", error)
this.server = null
this.port = 0
this.serverCreationPromise = null
reject(error)
}
})
}
private updateTimeout(): void {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
}
this.timeoutId = setTimeout(() => this.stop(), SERVER_TIMEOUT)
}
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
console.log("AuthHandler: Received request", req.url)
if (!req.url) {
this.sendResponse(res, 404, "text/plain", "Not found")
return
}
try {
// Convert HTTP URL to vscode.Uri and use shared handler directly
const fullUrl = `http://127.0.0.1:${this.port}${req.url}`
const uri = SharedUriHandler.convertHttpUrlToUri(fullUrl)
// Use SharedUriHandler directly - it handles all validation and processing
const success = await SharedUriHandler.handleUri(uri)
if (success) {
this.sendResponse(res, 200, "text/html", TOKEN_REQUEST_VIEW)
} else {
this.sendResponse(res, 400, "text/plain", "Bad request")
}
} catch (error) {
console.error("AuthHandler: Error processing request", error)
this.sendResponse(res, 400, "text/plain", "Bad request")
} finally {
// Stop the server after handling any request (success or failure)
this.stop()
}
}
private sendResponse(res: ServerResponse, status: number, type: string, content: string): void {
res.writeHead(status, { "Content-Type": type })
res.end(content)
}
private async openBrowser(callbackUrl: URL): Promise<void> {
await openExternal(callbackUrl.toString())
}
public stop(): void {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = null
}
if (this.server) {
this.server.close()
this.server = null
}
this.serverCreationPromise = null
this.port = 0
}
public dispose(): void {
this.stop()
}
}
const TOKEN_REQUEST_VIEW = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cline - Authentication Success</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Azeret+Mono:wght@300;400;700&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Azeret Mono', monospace;
background-color: #ffffff;
color: #333333;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
line-height: 1.25;
}
.container {
text-align: center;
padding: 32px;
background-color: #f8f8f8;
border: 1px solid #e1e1e1;
border-radius: 6px;
max-width: 480px;
width: 90%;
}
.checkmark {
width: 48px;
height: 48px;
border-radius: 50%;
background-color: #73c991;
margin: 0 auto 24px;
display: flex;
align-items: center;
justify-content: center;
}
.checkmark::after {
content: '✓';
font-size: 24px;
color: #ffffff;
font-weight: bold;
}
h1 {
font-size: 1.5rem;
margin-bottom: 16px;
font-weight: 400;
color: #333333;
}
p {
font-size: 0.875rem;
line-height: 1.5;
margin-bottom: 24px;
color: #666666;
}
.countdown {
font-size: 0.8125rem;
color: #666666;
background-color: #ffffff;
border: 1px solid #d1d1d1;
padding: 8px 16px;
border-radius: 4px;
display: inline-block;
}
@media (max-width: 480px) {
.container {
padding: 24px 16px;
}
h1 {
font-size: 1.25rem;
}
p {
font-size: 0.8125rem;
}
}
</style>
</head>
<body>
<div class="container">
<div class="checkmark"></div>
<h1>Authentication Successful</h1>
<p>Your authentication token has been securely sent back to your IDE. You can now return to your development environment to continue working.</p>
<div class="countdown">Feel free to close this window and continue in your IDE</div>
</div>
</body>
</html>`
+22 -2
View File
@@ -1,5 +1,6 @@
import { HostProvider } from "@/hosts/host-provider"
import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider"
import { DiagnosticSeverity } from "@/shared/proto/host/workspace"
import { status } from "@grpc/grpc-js"
export class ExternalDiffViewProvider extends DiffViewProvider {
@@ -78,8 +79,27 @@ export class ExternalDiffViewProvider extends DiffViewProvider {
}
protected override async getNewDiagnosticProblems(): Promise<string> {
console.log(`Called ExternalDiffViewProvider.getNewDiagnosticProblems() stub`)
return ""
// Get diagnostics using the HostBridge workspace service
const response = await HostProvider.workspace.getDiagnostics({})
if (response.fileDiagnostics.length === 0) {
return ""
}
let result = ""
for (const fileDiagnostics of response.fileDiagnostics) {
const errors = fileDiagnostics.diagnostics.filter((d) => d.severity === DiagnosticSeverity.DIAGNOSTIC_ERROR)
if (errors.length > 0) {
result += `\n\n${fileDiagnostics.filePath}`
for (const diagnostic of errors) {
const line = (diagnostic.range?.start?.line || 0) + 1 // Proto lines are 0-indexed
const source = diagnostic.source ? `${diagnostic.source} ` : ""
result += `\n- [${source}Error] Line ${line}: ${diagnostic.message}`
}
}
}
return result.trim()
}
protected override async closeDiffView(): Promise<void> {
+4 -2
View File
@@ -3,7 +3,7 @@ import * as path from "path"
import * as vscode from "vscode"
import { DecorationController } from "@/hosts/vscode/DecorationController"
import { DiffViewProvider } from "@integrations/editor/DiffViewProvider"
import { diagnosticsToProblemsString, getNewDiagnostics } from "@/integrations/diagnostics"
import { diagnosticsToProblemsString, getNewDiagnostics } from "./diagnostics"
export const DIFF_VIEW_URI_SCHEME = "cline-diff"
@@ -68,7 +68,9 @@ export class VscodeDiffViewProvider extends DiffViewProvider {
})
vscode.commands.executeCommand(
"vscode.diff",
vscode.Uri.parse(`${DIFF_VIEW_URI_SCHEME}:${fileName}`).with({
vscode.Uri.from({
scheme: DIFF_VIEW_URI_SCHEME,
path: fileName,
query: Buffer.from(this.originalContent ?? "").toString("base64"),
}),
uri,
+8 -1
View File
@@ -14,7 +14,8 @@ https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/c
*/
export class VscodeWebviewProvider extends WebviewProvider implements vscode.WebviewViewProvider {
public webview?: vscode.WebviewView | vscode.WebviewPanel
private webview?: vscode.WebviewView | vscode.WebviewPanel
private disposables: vscode.Disposable[] = []
constructor(context: vscode.ExtensionContext, providerType: WebviewProviderType) {
super(context, providerType)
@@ -166,6 +167,12 @@ export class VscodeWebviewProvider extends WebviewProvider implements vscode.Web
if (this.webview && "dispose" in this.webview) {
this.webview.dispose()
}
while (this.disposables.length) {
const x = this.disposables.pop()
if (x) {
x.dispose()
}
}
super.dispose()
}
}
+109
View File
@@ -0,0 +1,109 @@
import * as vscode from "vscode"
import * as path from "path"
import deepEqual from "fast-deep-equal"
import { getCwd } from "@/utils/path"
export function getNewDiagnostics(
oldDiagnostics: [vscode.Uri, vscode.Diagnostic[]][],
newDiagnostics: [vscode.Uri, vscode.Diagnostic[]][],
): [vscode.Uri, vscode.Diagnostic[]][] {
const newProblems: [vscode.Uri, vscode.Diagnostic[]][] = []
const oldMap = new Map(oldDiagnostics)
for (const [uri, newDiags] of newDiagnostics) {
const oldDiags = oldMap.get(uri) || []
const newProblemsForUri = newDiags.filter((newDiag) => !oldDiags.some((oldDiag) => deepEqual(oldDiag, newDiag)))
if (newProblemsForUri.length > 0) {
newProblems.push([uri, newProblemsForUri])
}
}
return newProblems
}
// Usage:
// const oldDiagnostics = // ... your old diagnostics array
// const newDiagnostics = // ... your new diagnostics array
// const newProblems = getNewDiagnostics(oldDiagnostics, newDiagnostics);
// Example usage with mocks:
//
// // Mock old diagnostics
// const oldDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [
// [vscode.Uri.file("/path/to/file1.ts"), [
// new vscode.Diagnostic(new vscode.Range(0, 0, 0, 10), "Old error in file1", vscode.DiagnosticSeverity.Error)
// ]],
// [vscode.Uri.file("/path/to/file2.ts"), [
// new vscode.Diagnostic(new vscode.Range(5, 5, 5, 15), "Old warning in file2", vscode.DiagnosticSeverity.Warning)
// ]]
// ];
//
// // Mock new diagnostics
// const newDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [
// [vscode.Uri.file("/path/to/file1.ts"), [
// new vscode.Diagnostic(new vscode.Range(0, 0, 0, 10), "Old error in file1", vscode.DiagnosticSeverity.Error),
// new vscode.Diagnostic(new vscode.Range(2, 2, 2, 12), "New error in file1", vscode.DiagnosticSeverity.Error)
// ]],
// [vscode.Uri.file("/path/to/file2.ts"), [
// new vscode.Diagnostic(new vscode.Range(5, 5, 5, 15), "Old warning in file2", vscode.DiagnosticSeverity.Warning)
// ]],
// [vscode.Uri.file("/path/to/file3.ts"), [
// new vscode.Diagnostic(new vscode.Range(1, 1, 1, 11), "New error in file3", vscode.DiagnosticSeverity.Error)
// ]]
// ];
//
// const newProblems = getNewDiagnostics(oldDiagnostics, newDiagnostics);
//
// console.log("New problems:");
// for (const [uri, diagnostics] of newProblems) {
// console.log(`File: ${uri.fsPath}`);
// for (const diagnostic of diagnostics) {
// console.log(`- ${diagnostic.message} (${diagnostic.range.start.line}:${diagnostic.range.start.character})`);
// }
// }
//
// // Expected output:
// // New problems:
// // File: /path/to/file1.ts
// // - New error in file1 (2:2)
// // File: /path/to/file3.ts
// // - New error in file3 (1:1)
// will return empty string if no problems with the given severity are found
export async function diagnosticsToProblemsString(
diagnostics: [vscode.Uri, vscode.Diagnostic[]][],
severities: vscode.DiagnosticSeverity[],
): Promise<string> {
const cwd = await getCwd()
let result = ""
for (const [uri, fileDiagnostics] of diagnostics) {
const problems = fileDiagnostics.filter((d) => severities.includes(d.severity))
if (problems.length > 0) {
result += `\n\n${path.relative(cwd, uri.fsPath).toPosix()}`
for (const diagnostic of problems) {
let label: string
switch (diagnostic.severity) {
case vscode.DiagnosticSeverity.Error:
label = "Error"
break
case vscode.DiagnosticSeverity.Warning:
label = "Warning"
break
case vscode.DiagnosticSeverity.Information:
label = "Information"
break
case vscode.DiagnosticSeverity.Hint:
label = "Hint"
break
default:
label = "Diagnostic"
}
const line = diagnostic.range.start.line + 1 // VSCode lines are 0-indexed
const source = diagnostic.source ? `${diagnostic.source} ` : ""
result += `\n- [${source}${label}] Line ${line}: ${diagnostic.message}`
}
}
}
return result.trim()
}
@@ -2,6 +2,7 @@
import { describe, it, beforeEach, afterEach } from "mocha"
import { strict as assert } from "assert"
import * as vscode from "vscode"
import pWaitFor from "p-wait-for"
import { getOpenTabs } from "@/hosts/vscode/hostbridge/window/getOpenTabs"
import { GetOpenTabsRequest } from "@/shared/proto/host/window"
@@ -54,8 +55,18 @@ describe("Hostbridge - Window - getOpenTabs", () => {
await createAndOpenTestDocument(1, vscode.ViewColumn.One)
await createAndOpenTestDocument(2, vscode.ViewColumn.Two)
// Wait a bit for tabs to be fully created
await new Promise((resolve) => setTimeout(resolve, 100))
// Wait for tabs to be fully created
await pWaitFor(
async () => {
const request = GetOpenTabsRequest.create({})
const response = await getOpenTabs(request)
return response.paths.length === 2
},
{
timeout: 2000,
interval: 50,
},
)
const request = GetOpenTabsRequest.create({})
const response = await getOpenTabs(request)
@@ -74,8 +85,18 @@ describe("Hostbridge - Window - getOpenTabs", () => {
await createAndOpenTestDocument(2, vscode.ViewColumn.One)
await createAndOpenTestDocument(3, vscode.ViewColumn.One)
// Wait a bit for tabs to be fully created
await new Promise((resolve) => setTimeout(resolve, 100))
// Wait for tabs to be fully created
await pWaitFor(
async () => {
const request = GetOpenTabsRequest.create({})
const response = await getOpenTabs(request)
return response.paths.length === 3
},
{
timeout: 2000,
interval: 50,
},
)
const request = GetOpenTabsRequest.create({})
const response = await getOpenTabs(request)
@@ -0,0 +1,69 @@
import * as vscode from "vscode"
import {
GetDiagnosticsRequest,
GetDiagnosticsResponse,
FileDiagnostics,
Diagnostic,
DiagnosticRange,
DiagnosticPosition,
DiagnosticSeverity,
} from "@/shared/proto/host/workspace"
export async function getDiagnostics(request: GetDiagnosticsRequest): Promise<GetDiagnosticsResponse> {
// Get all diagnostics from VS Code
const vscodeAllDiagnostics = vscode.languages.getDiagnostics()
const fileDiagnostics: FileDiagnostics[] = []
for (const [uri, diagnostics] of vscodeAllDiagnostics) {
if (diagnostics.length > 0) {
const convertedDiagnostics: Diagnostic[] = diagnostics.map((vsDiagnostic) => {
// Convert VS Code severity to proto severity
let severity: DiagnosticSeverity
switch (vsDiagnostic.severity) {
case vscode.DiagnosticSeverity.Error:
severity = DiagnosticSeverity.DIAGNOSTIC_ERROR
break
case vscode.DiagnosticSeverity.Warning:
severity = DiagnosticSeverity.DIAGNOSTIC_WARNING
break
case vscode.DiagnosticSeverity.Information:
severity = DiagnosticSeverity.DIAGNOSTIC_INFORMATION
break
case vscode.DiagnosticSeverity.Hint:
severity = DiagnosticSeverity.DIAGNOSTIC_HINT
break
default:
severity = DiagnosticSeverity.DIAGNOSTIC_ERROR
}
return Diagnostic.create({
message: vsDiagnostic.message,
range: DiagnosticRange.create({
start: DiagnosticPosition.create({
line: vsDiagnostic.range.start.line,
character: vsDiagnostic.range.start.character,
}),
end: DiagnosticPosition.create({
line: vsDiagnostic.range.end.line,
character: vsDiagnostic.range.end.character,
}),
}),
severity: severity,
source: vsDiagnostic.source || undefined,
})
})
fileDiagnostics.push(
FileDiagnostics.create({
filePath: uri.fsPath,
diagnostics: convertedDiagnostics,
}),
)
}
}
return GetDiagnosticsResponse.create({
fileDiagnostics: fileDiagnostics,
})
}
@@ -0,0 +1,187 @@
import { describe, it, before, after, beforeEach } from "mocha"
import { expect } from "chai"
import * as vscode from "vscode"
import * as path from "path"
import * as fs from "fs/promises"
import * as os from "os"
import { saveOpenDocumentIfDirty } from "@/hosts/vscode/hostbridge/workspace/saveOpenDocumentIfDirty"
import { SaveOpenDocumentIfDirtyRequest } from "@/shared/proto/index.host"
describe("saveOpenDocumentIfDirty Integration Test", () => {
let testWorkspaceRoot: string
let testFilePath: string
let testFileUri: vscode.Uri
before(async () => {
// Use a temporary directory for tests
testWorkspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), "cline-test-"))
// Create a test file path
testFilePath = path.join(testWorkspaceRoot, "test-save-document.txt")
testFileUri = vscode.Uri.file(testFilePath)
})
after(async () => {
// Clean up: close all editors and delete test directory
await vscode.commands.executeCommand("workbench.action.closeAllEditors")
try {
await fs.rm(testWorkspaceRoot, { recursive: true, force: true })
} catch (error) {
// Directory might not exist, ignore
}
})
beforeEach(async () => {
// Close all editors before each test
await vscode.commands.executeCommand("workbench.action.closeAllEditors")
})
it("should save a dirty document and return wasSaved: true", async () => {
// Create a test file with initial content
await fs.writeFile(testFilePath, "Initial content")
// Open the document in VSCode
const document = await vscode.workspace.openTextDocument(testFileUri)
const editor = await vscode.window.showTextDocument(document)
// Make the document dirty by editing it
await editor.edit((editBuilder) => {
editBuilder.insert(new vscode.Position(0, 0), "Modified ")
})
// Verify the document is dirty
expect(document.isDirty).to.be.true
// Call saveOpenDocumentIfDirty
const request = SaveOpenDocumentIfDirtyRequest.create({
filePath: testFilePath,
})
const response = await saveOpenDocumentIfDirty(request)
// Verify the response
expect(response.wasSaved).to.be.true
// Verify the document is no longer dirty
expect(document.isDirty).to.be.false
// Verify the file content was saved
const savedContent = await fs.readFile(testFilePath, "utf-8")
expect(savedContent).to.equal("Modified Initial content")
})
it("should not save a clean document and return empty response", async () => {
// Create a test file
await fs.writeFile(testFilePath, "Clean content")
// Open the document in VSCode
const document = await vscode.workspace.openTextDocument(testFileUri)
await vscode.window.showTextDocument(document)
// Verify the document is not dirty
expect(document.isDirty).to.be.false
// Call saveOpenDocumentIfDirty
const request = SaveOpenDocumentIfDirtyRequest.create({
filePath: testFilePath,
})
const response = await saveOpenDocumentIfDirty(request)
// Verify the response
expect(response.wasSaved).to.be.undefined
// Verify the document is still not dirty
expect(document.isDirty).to.be.false
})
it("should return empty response when document is not open", async () => {
// Ensure no documents are open
await vscode.commands.executeCommand("workbench.action.closeAllEditors")
// Call saveOpenDocumentIfDirty with a non-existent file
const request = SaveOpenDocumentIfDirtyRequest.create({
filePath: path.join(testWorkspaceRoot, "non-existent-file.txt"),
})
const response = await saveOpenDocumentIfDirty(request)
// Verify the response
expect(response.wasSaved).to.be.undefined
})
it("should handle multiple open documents and save only the specified one", async () => {
// Create multiple test files
const testFile1 = path.join(testWorkspaceRoot, "test-file-1.txt")
const testFile2 = path.join(testWorkspaceRoot, "test-file-2.txt")
const testFile3 = path.join(testWorkspaceRoot, "test-file-3.txt")
await fs.writeFile(testFile1, "File 1 content")
await fs.writeFile(testFile2, "File 2 content")
await fs.writeFile(testFile3, "File 3 content")
try {
// Open all documents
const doc1 = await vscode.workspace.openTextDocument(vscode.Uri.file(testFile1))
const doc2 = await vscode.workspace.openTextDocument(vscode.Uri.file(testFile2))
const doc3 = await vscode.workspace.openTextDocument(vscode.Uri.file(testFile3))
// Edit all documents to make them dirty
const editor1 = await vscode.window.showTextDocument(doc1)
await editor1.edit((editBuilder) => {
editBuilder.insert(new vscode.Position(0, 0), "Modified ")
})
const editor2 = await vscode.window.showTextDocument(doc2)
await editor2.edit((editBuilder) => {
editBuilder.insert(new vscode.Position(0, 0), "Modified ")
})
const editor3 = await vscode.window.showTextDocument(doc3)
await editor3.edit((editBuilder) => {
editBuilder.insert(new vscode.Position(0, 0), "Modified ")
})
// Verify all documents are dirty
expect(doc1.isDirty).to.be.true
expect(doc2.isDirty).to.be.true
expect(doc3.isDirty).to.be.true
// Save only the second document
const request = SaveOpenDocumentIfDirtyRequest.create({
filePath: testFile2,
})
const response = await saveOpenDocumentIfDirty(request)
// Verify the response
expect(response.wasSaved).to.be.true
// Verify only doc2 was saved
expect(doc1.isDirty).to.be.true
expect(doc2.isDirty).to.be.false
expect(doc3.isDirty).to.be.true
// Verify the file content
const savedContent = await fs.readFile(testFile2, "utf-8")
expect(savedContent).to.equal("Modified File 2 content")
} finally {
// Clean up
await fs.unlink(testFile1).catch(() => {})
await fs.unlink(testFile2).catch(() => {})
await fs.unlink(testFile3).catch(() => {})
}
})
it("should handle empty file path gracefully", async () => {
const request = SaveOpenDocumentIfDirtyRequest.create({
filePath: "",
})
const response = await saveOpenDocumentIfDirty(request)
expect(response.wasSaved).to.be.undefined
})
it("should handle undefined file path gracefully", async () => {
const request = SaveOpenDocumentIfDirtyRequest.create({})
const response = await saveOpenDocumentIfDirty(request)
expect(response.wasSaved).to.be.undefined
})
})
@@ -1,14 +1,12 @@
import { SaveOpenDocumentIfDirtyRequest } from "@/shared/proto/index.host"
import { Empty } from "@shared/proto/cline/common"
import { SaveOpenDocumentIfDirtyRequest, SaveOpenDocumentIfDirtyResponse } from "@/shared/proto/index.host"
import * as vscode from "vscode"
import { arePathsEqual } from "@utils/path"
export async function saveOpenDocumentIfDirty(request: SaveOpenDocumentIfDirtyRequest): Promise<Empty> {
export async function saveOpenDocumentIfDirty(request: SaveOpenDocumentIfDirtyRequest): Promise<SaveOpenDocumentIfDirtyResponse> {
const existingDocument = vscode.workspace.textDocuments.find((doc) => arePathsEqual(doc.uri.fsPath, request.filePath))
if (existingDocument && existingDocument.isDirty) {
await existingDocument.save()
return { wasSaved: true }
}
return Empty.create({})
return {}
}
@@ -96,7 +96,6 @@ function getBuildArtifactPatterns(): string[] {
"node_modules/",
"obj/",
"out/",
"pkg/",
"pycache/",
"target/dependency/",
"temp/",
+26 -82
View File
@@ -1,105 +1,49 @@
import * as vscode from "vscode"
import * as path from "path"
import deepEqual from "fast-deep-equal"
import { getCwd } from "@/utils/path"
import { HostProvider } from "@/hosts/host-provider"
import { GetDiagnosticsRequest, DiagnosticSeverity } from "@/shared/proto/host/workspace"
import { Metadata } from "@/shared/proto/cline/common"
export function getNewDiagnostics(
oldDiagnostics: [vscode.Uri, vscode.Diagnostic[]][],
newDiagnostics: [vscode.Uri, vscode.Diagnostic[]][],
): [vscode.Uri, vscode.Diagnostic[]][] {
const newProblems: [vscode.Uri, vscode.Diagnostic[]][] = []
const oldMap = new Map(oldDiagnostics)
/**
* Host-agnostic function to get workspace problems as a formatted string
* Used by @problems mention for cross-host compatibility
*/
export async function getWorkspaceProblemsString(): Promise<string> {
const response = await HostProvider.workspace.getDiagnostics(
GetDiagnosticsRequest.create({
metadata: Metadata.create({}),
}),
)
for (const [uri, newDiags] of newDiagnostics) {
const oldDiags = oldMap.get(uri) || []
const newProblemsForUri = newDiags.filter((newDiag) => !oldDiags.some((oldDiag) => deepEqual(oldDiag, newDiag)))
if (newProblemsForUri.length > 0) {
newProblems.push([uri, newProblemsForUri])
}
if (response.fileDiagnostics.length === 0) {
return "No errors or warnings detected."
}
return newProblems
}
// Usage:
// const oldDiagnostics = // ... your old diagnostics array
// const newDiagnostics = // ... your new diagnostics array
// const newProblems = getNewDiagnostics(oldDiagnostics, newDiagnostics);
// Example usage with mocks:
//
// // Mock old diagnostics
// const oldDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [
// [vscode.Uri.file("/path/to/file1.ts"), [
// new vscode.Diagnostic(new vscode.Range(0, 0, 0, 10), "Old error in file1", vscode.DiagnosticSeverity.Error)
// ]],
// [vscode.Uri.file("/path/to/file2.ts"), [
// new vscode.Diagnostic(new vscode.Range(5, 5, 5, 15), "Old warning in file2", vscode.DiagnosticSeverity.Warning)
// ]]
// ];
//
// // Mock new diagnostics
// const newDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [
// [vscode.Uri.file("/path/to/file1.ts"), [
// new vscode.Diagnostic(new vscode.Range(0, 0, 0, 10), "Old error in file1", vscode.DiagnosticSeverity.Error),
// new vscode.Diagnostic(new vscode.Range(2, 2, 2, 12), "New error in file1", vscode.DiagnosticSeverity.Error)
// ]],
// [vscode.Uri.file("/path/to/file2.ts"), [
// new vscode.Diagnostic(new vscode.Range(5, 5, 5, 15), "Old warning in file2", vscode.DiagnosticSeverity.Warning)
// ]],
// [vscode.Uri.file("/path/to/file3.ts"), [
// new vscode.Diagnostic(new vscode.Range(1, 1, 1, 11), "New error in file3", vscode.DiagnosticSeverity.Error)
// ]]
// ];
//
// const newProblems = getNewProblems(oldDiagnostics, newDiagnostics);
//
// console.log("New problems:");
// for (const [uri, diagnostics] of newProblems) {
// console.log(`File: ${uri.fsPath}`);
// for (const diagnostic of diagnostics) {
// console.log(`- ${diagnostic.message} (${diagnostic.range.start.line}:${diagnostic.range.start.character})`);
// }
// }
//
// // Expected output:
// // New problems:
// // File: /path/to/file1.ts
// // - New error in file1 (2:2)
// // File: /path/to/file3.ts
// // - New error in file3 (1:1)
// will return empty string if no problems with the given severity are found
export async function diagnosticsToProblemsString(
diagnostics: [vscode.Uri, vscode.Diagnostic[]][],
severities: vscode.DiagnosticSeverity[],
): Promise<string> {
const cwd = await getCwd()
let result = ""
for (const [uri, fileDiagnostics] of diagnostics) {
const problems = fileDiagnostics.filter((d) => severities.includes(d.severity))
for (const fileDiagnostics of response.fileDiagnostics) {
const problems = fileDiagnostics.diagnostics.filter(
(d) => d.severity === DiagnosticSeverity.DIAGNOSTIC_ERROR || d.severity === DiagnosticSeverity.DIAGNOSTIC_WARNING,
)
if (problems.length > 0) {
result += `\n\n${path.relative(cwd, uri.fsPath).toPosix()}`
result += `\n\n${fileDiagnostics.filePath}`
for (const diagnostic of problems) {
let label: string
switch (diagnostic.severity) {
case vscode.DiagnosticSeverity.Error:
case DiagnosticSeverity.DIAGNOSTIC_ERROR:
label = "Error"
break
case vscode.DiagnosticSeverity.Warning:
case DiagnosticSeverity.DIAGNOSTIC_WARNING:
label = "Warning"
break
case vscode.DiagnosticSeverity.Information:
case DiagnosticSeverity.DIAGNOSTIC_INFORMATION:
label = "Information"
break
case vscode.DiagnosticSeverity.Hint:
case DiagnosticSeverity.DIAGNOSTIC_HINT:
label = "Hint"
break
default:
label = "Diagnostic"
}
const line = diagnostic.range.start.line + 1 // VSCode lines are 0-indexed
const line = (diagnostic.range?.start?.line || 0) + 1 // Proto lines are 0-indexed
const source = diagnostic.source ? `${diagnostic.source} ` : ""
result += `\n- [${source}${label}] Line ${line}: ${diagnostic.message}`
}
+12 -8
View File
@@ -1,5 +1,6 @@
import * as vscode from "vscode"
import { openExternal } from "@utils/env"
import { HostProvider } from "@hosts/host-provider"
import { ShowMessageType } from "@shared/proto/host/window"
/**
* Detects potential AI-generated code omissions in the given file content.
@@ -41,13 +42,16 @@ function detectCodeOmission(originalFileContent: string, newFileContent: string)
*/
export function showOmissionWarning(originalFileContent: string, newFileContent: string): void {
if (detectCodeOmission(originalFileContent, newFileContent)) {
vscode.window
.showWarningMessage(
"Potential code truncation detected. This happens when the AI reaches its max output limit.",
"Follow this guide to fix the issue",
)
.then((selection) => {
if (selection === "Follow this guide to fix the issue") {
HostProvider.window
.showMessage({
type: ShowMessageType.WARNING,
message: "Potential code truncation detected. This happens when the AI reaches its max output limit.",
options: {
items: ["Follow this guide to fix the issue"],
},
})
.then((response) => {
if (response.selectedOption === "Follow this guide to fix the issue") {
openExternal(
"https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Cline-Deleting-Code-with-%22Rest-of-Code-Here%22-Comments",
)
@@ -4,6 +4,8 @@ import * as sinon from "sinon"
import { TerminalProcess } from "./TerminalProcess"
import * as vscode from "vscode"
import { TerminalRegistry } from "./TerminalRegistry"
import { DiffViewProviderCreator, HostProvider, WebviewProviderCreator } from "@/hosts/host-provider"
import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client"
declare module "vscode" {
// https://github.com/microsoft/vscode/blob/f0417069c62e20f3667506f4b7e53ca0004b4e3e/src/vscode-dts/vscode.d.ts#L7442
@@ -36,6 +38,13 @@ describe("TerminalProcess (Integration Tests)", () => {
beforeEach(() => {
sandbox = sinon.createSandbox({ useFakeTimers: true })
HostProvider.reset()
HostProvider.initialize(
((_) => {}) as WebviewProviderCreator,
(() => {}) as DiffViewProviderCreator,
vscodeHostBridgeClient,
(s: string) => console.log(s),
)
process = new TerminalProcess()
})
@@ -1,7 +1,6 @@
import { EventEmitter } from "events"
import { stripAnsi } from "./ansiUtils"
import * as vscode from "vscode"
import { Logger } from "@services/logging/Logger"
import { getLatestTerminalOutput } from "./get-latest-output"
export interface TerminalProcessEvents {
@@ -28,9 +27,6 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
private gracePeriodTimer: NodeJS.Timeout | null = null
private hasEmittedCompleted: boolean = false
// constructor() {
// super()
private async emitCurrentTerminalContents(): Promise<void> {
try {
const terminalSnapshot = await getLatestTerminalOutput()
+19 -16
View File
@@ -6,6 +6,7 @@ import { storeSecret } from "@/core/storage/state"
import { telemetryService } from "@services/posthog/telemetry/TelemetryService"
import { AuthState, UserInfo } from "@shared/proto/cline/account"
import { type EmptyRequest, String } from "@shared/proto/cline/common"
import { AuthHandler } from "@/hosts/external/AuthHandler"
import { FirebaseAuthProvider } from "./providers/FirebaseAuthProvider"
import { openExternal } from "@/utils/env"
@@ -56,7 +57,7 @@ export class AuthService {
protected _clineAuthInfo: ClineAuthInfo | null = null
protected _provider: { provider: FirebaseAuthProvider } | null = null
protected _activeAuthStatusUpdateSubscriptions = new Set<[Controller, StreamingResponseHandler<AuthState>]>()
protected _context: vscode.ExtensionContext
protected _controller: Controller
/**
* Creates an instance of AuthService.
@@ -64,7 +65,7 @@ export class AuthService {
* @param authProvider - Optional authentication provider to use.
* @param controller - Optional reference to the Controller instance.
*/
protected constructor(context: vscode.ExtensionContext, config: ServiceConfig, authProvider?: any) {
protected constructor(controller: Controller, config: ServiceConfig, authProvider?: any) {
const providerName = authProvider || "firebase"
this._config = Object.assign({ URI: DefaultClineAccountURI }, config)
@@ -95,7 +96,7 @@ export class AuthService {
this._setProvider(authProviders.find((authProvider) => authProvider.name === providerName).name)
this._context = context
this._controller = controller
}
/**
@@ -105,29 +106,29 @@ export class AuthService {
* @param controller - Optional reference to the Controller instance.
* @returns The singleton instance of AuthService.
*/
public static getInstance(context?: vscode.ExtensionContext, config?: ServiceConfig, authProvider?: any): AuthService {
public static getInstance(controller?: Controller, config?: ServiceConfig, authProvider?: any): AuthService {
if (!AuthService.instance) {
if (!context) {
if (!controller) {
console.warn("Extension context was not provided to AuthService.getInstance, using default context")
context = {} as vscode.ExtensionContext
controller = {} as Controller
}
if (process.env.E2E_TEST) {
// Use require instead of import to avoid circular dependency issues
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { AuthServiceMock } = require("./AuthServiceMock")
AuthService.instance = AuthServiceMock.getInstance(context, config || {}, authProvider)
AuthService.instance = AuthServiceMock.getInstance(controller, config || {}, authProvider)
} else {
AuthService.instance = new AuthService(context, config || {}, authProvider)
AuthService.instance = new AuthService(controller, config || {}, authProvider)
}
}
if (context !== undefined && AuthService.instance) {
AuthService.instance.context = context
if (controller !== undefined && AuthService.instance) {
AuthService.instance.controller = controller
}
return AuthService.instance!
}
set context(context: vscode.ExtensionContext) {
this._context = context
set controller(controller: Controller) {
this._controller = controller
}
get authProvider(): any {
@@ -195,7 +196,9 @@ export class AuthService {
throw new Error("Authentication URI is not configured")
}
const callbackUrl = `${vscode.env.uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`
const callbackHost =
(await AuthHandler.getInstance().getCallbackUri()) || `${vscode.env.uriScheme || "vscode"}://saoudrizwan.claude-dev`
const callbackUrl = `${callbackHost}/auth`
// Use URL object for more graceful query construction
const authUrl = new URL(this._config.URI)
@@ -228,7 +231,7 @@ export class AuthService {
}
try {
this._clineAuthInfo = await this._provider.provider.signIn(this._context, token, provider)
this._clineAuthInfo = await this._provider.provider.signIn(this._controller, token, provider)
this._authenticated = true
if (this._clineAuthInfo) {
@@ -248,7 +251,7 @@ export class AuthService {
* This is typically called when the user logs out.
*/
async clearAuthToken(): Promise<void> {
await storeSecret(this._context, "clineAccountId", undefined)
this._controller.cacheService.setSecret("clineAccountId", undefined)
}
/**
@@ -261,7 +264,7 @@ export class AuthService {
}
try {
this._clineAuthInfo = await this._provider.provider.retrieveClineAuthInfo(this._context)
this._clineAuthInfo = await this._provider.provider.retrieveClineAuthInfo(this._controller)
if (this._clineAuthInfo) {
this._authenticated = true
telemetryService.identifyAccount(this._clineAuthInfo.userInfo)
+11 -14
View File
@@ -4,10 +4,11 @@ import { clineEnvConfig } from "@/config"
import { WebviewProvider } from "@/core/webview"
import type { UserResponse } from "@/shared/ClineAccount"
import { AuthService, type ServiceConfig } from "./AuthService"
import { Controller } from "@/core/controller"
export class AuthServiceMock extends AuthService {
protected constructor(context: vscode.ExtensionContext, config: ServiceConfig, authProvider?: any) {
super(context, config, authProvider)
protected constructor(controller: Controller, config: ServiceConfig, authProvider?: any) {
super(controller, config, authProvider)
if (process?.env?.CLINE_ENVIRONMENT !== "local") {
throw new Error("AuthServiceMock should only be used in local environment for testing purposes.")
@@ -18,26 +19,22 @@ export class AuthServiceMock extends AuthService {
const providerName = "firebase"
this._setProvider(providerName)
this._context = context
this._controller = controller
}
/**
* Gets the singleton instance of AuthServiceMock.
*/
public static override getInstance(
context?: vscode.ExtensionContext,
config?: ServiceConfig,
authProvider?: any,
): AuthServiceMock {
public static override getInstance(controller?: Controller, config?: ServiceConfig, authProvider?: any): AuthServiceMock {
if (!AuthServiceMock.instance) {
if (!context) {
console.warn("Extension context was not provided to AuthServiceMock.getInstance, using default context")
context = {} as vscode.ExtensionContext
if (!controller) {
console.error("Extension controller was not provided to AuthServiceMock.getInstance")
throw new Error("Extension controller was not provided to AuthServiceMock.getInstance")
}
AuthServiceMock.instance = new AuthServiceMock(context, config || {}, authProvider)
AuthServiceMock.instance = new AuthServiceMock(controller, config || {}, authProvider)
}
if (context !== undefined) {
AuthServiceMock.instance.context = context
if (controller !== undefined) {
AuthServiceMock.instance.controller = controller
}
return AuthServiceMock.instance
}
@@ -7,6 +7,7 @@ import { ExtensionContext } from "vscode"
import { ClineAccountUserInfo, ClineAuthInfo } from "../AuthService"
import { jwtDecode } from "jwt-decode"
import { clineEnvConfig } from "@/config"
import { Controller } from "@/core/controller"
export class FirebaseAuthProvider {
private _config: any
@@ -41,8 +42,8 @@ export class FirebaseAuthProvider {
* @returns {Promise<User>} A promise that resolves with the authenticated user.
* @throws {Error} Throws an error if the restoration fails.
*/
async retrieveClineAuthInfo(context: ExtensionContext): Promise<ClineAuthInfo | null> {
const userRefreshToken = await getSecret(context, "clineAccountId")
async retrieveClineAuthInfo(controller: Controller): Promise<ClineAuthInfo | null> {
const userRefreshToken = controller.cacheService.getSecretKey("clineAccountId")
if (!userRefreshToken) {
console.error("No stored authentication credential found.")
return null
@@ -100,7 +101,7 @@ export class FirebaseAuthProvider {
* @returns {Promise<User>} A promise that resolves with the authenticated user.
* @throws {Error} Throws an error if the sign-in fails.
*/
async signIn(context: ExtensionContext, token: string, provider: string): Promise<ClineAuthInfo | null> {
async signIn(controller: Controller, token: string, provider: string): Promise<ClineAuthInfo | null> {
try {
let credential
switch (provider) {
@@ -123,7 +124,7 @@ export class FirebaseAuthProvider {
// store the long-lived refresh token in secret storage
try {
await storeSecret(context, "clineAccountId", userCredential.refreshToken)
controller.cacheService.setSecret("clineAccountId", userCredential.refreshToken)
} catch (error) {
ErrorService.logMessage("Firebase store token error", "error")
ErrorService.logException(error)
@@ -131,7 +132,7 @@ export class FirebaseAuthProvider {
}
// userCredential = await this._signInWithCredential(context, credential)
return await this.retrieveClineAuthInfo(context)
return await this.retrieveClineAuthInfo(controller)
} catch (error) {
ErrorService.logMessage("Firebase sign-in error", "error")
ErrorService.logException(error)
+8 -4
View File
@@ -41,15 +41,17 @@ export class BrowserSession {
private lastConnectionAttempt: number = 0
browserSettings: BrowserSettings
private isConnectedToRemote: boolean = false
private useWebp: boolean
// Telemetry tracking properties
private sessionStartTime: number = 0
private browserActions: string[] = []
private taskId?: string
constructor(context: vscode.ExtensionContext, browserSettings: BrowserSettings) {
constructor(context: vscode.ExtensionContext, browserSettings: BrowserSettings, useWebp: boolean = true) {
this.context = context
this.browserSettings = browserSettings
this.useWebp = useWebp
}
// Tests remote browser connection
@@ -487,14 +489,16 @@ export class BrowserSession {
// },
}
const screenshotType = this.useWebp ? "webp" : "png"
let screenshotBase64 = await this.page.screenshot({
...options,
type: "webp",
type: screenshotType,
})
let screenshot = `data:image/webp;base64,${screenshotBase64}`
let screenshot = `data:image/${screenshotType};base64,${screenshotBase64}`
if (!screenshotBase64) {
console.info("webp screenshot failed, trying png")
// choosing to try screenshot again, regardless of the initial type
console.info(`${screenshotType} screenshot failed, trying png`)
screenshotBase64 = await this.page.screenshot({
...options,
type: "png",
-1
View File
@@ -18,7 +18,6 @@ const DEFAULT_IGNORE_DIRECTORIES = [
"tmp",
"temp",
"deps",
"pkg",
"Pods",
]
+17 -34
View File
@@ -1,8 +1,11 @@
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/host/window"
import { sendMcpServersUpdate } from "@core/controller/mcp/subscribeToMcpServers"
import { GlobalFileNames } from "@core/storage/disk"
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import ReconnectingEventSource from "reconnecting-eventsource"
import {
CallToolResultSchema,
ListResourcesResultSchema,
@@ -10,16 +13,7 @@ import {
ListToolsResultSchema,
ReadResourceResultSchema,
} from "@modelcontextprotocol/sdk/types.js"
import { sendMcpServersUpdate } from "@core/controller/mcp/subscribeToMcpServers"
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import chokidar, { FSWatcher } from "chokidar"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import deepEqual from "fast-deep-equal"
import * as fs from "fs/promises"
import * as path from "path"
import * as vscode from "vscode"
import { z } from "zod"
import { FileChangeEvent_ChangeType, SubscribeToFileRequest } from "../../shared/proto/host/watch"
import { ExtensionMessage } from "@shared/ExtensionMessage"
import {
DEFAULT_MCP_TIMEOUT_SECONDS,
McpResource,
@@ -30,19 +24,24 @@ import {
McpToolCallResponse,
MIN_MCP_TIMEOUT_SECONDS,
} from "@shared/mcp"
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { fileExistsAtPath } from "@utils/fs"
import { secondsToMs } from "@utils/time"
import { GlobalFileNames } from "@core/storage/disk"
import { ExtensionMessage } from "@shared/ExtensionMessage"
import chokidar, { FSWatcher } from "chokidar"
import deepEqual from "fast-deep-equal"
import * as fs from "fs/promises"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import * as path from "path"
import ReconnectingEventSource from "reconnecting-eventsource"
import * as vscode from "vscode"
import { z } from "zod"
import { FileChangeEvent_ChangeType, SubscribeToFileRequest } from "../../shared/proto/host/watch"
import { DEFAULT_REQUEST_TIMEOUT_MS } from "./constants"
import { BaseConfigSchema, McpSettingsSchema, ServerConfigSchema } from "./schemas"
import { McpConnection, McpServerConfig, Transport } from "./types"
import { BaseConfigSchema, ServerConfigSchema, McpSettingsSchema } from "./schemas"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/host/window"
export class McpHub {
getMcpServersPath: () => Promise<string>
private getSettingsDirectoryPath: () => Promise<string>
private postMessageToWebview: (message: ExtensionMessage) => Promise<void>
private clientVersion: string
private disposables: vscode.Disposable[] = []
@@ -65,12 +64,10 @@ export class McpHub {
constructor(
getMcpServersPath: () => Promise<string>,
getSettingsDirectoryPath: () => Promise<string>,
postMessageToWebview: (message: ExtensionMessage) => Promise<void>,
clientVersion: string,
) {
this.getMcpServersPath = getMcpServersPath
this.getSettingsDirectoryPath = getSettingsDirectoryPath
this.postMessageToWebview = postMessageToWebview
this.clientVersion = clientVersion
this.watchMcpSettingsFile()
this.initializeMcpServers()
@@ -398,20 +395,6 @@ export class McpHub {
timestamp: Date.now(),
})
}
// Forward to webview if available
if (this.postMessageToWebview) {
await this.postMessageToWebview({
type: "mcpNotification",
serverName: name,
notification: {
level,
data,
logger,
timestamp: Date.now(),
},
} as any)
}
})
console.log(`[MCP Debug] Successfully set notifications/message handler for ${name}`)
@@ -1,6 +1,8 @@
import { PostHog } from "posthog-node"
import * as vscode from "vscode"
import { version as extensionVersion } from "../../../../package.json"
import { HostProvider } from "@hosts/host-provider"
import { ShowMessageType } from "@shared/proto/host/window"
import type { TaskFeedbackType } from "@shared/WebviewMessage"
import type { BrowserSettings } from "@shared/BrowserSettings"
@@ -135,13 +137,17 @@ class TelemetryService {
} else {
// Only show warning if user has opted in to Cline telemetry but VS Code telemetry is disabled
if (didUserOptIn) {
void vscode.window
.showWarningMessage(
"Anonymous Cline error and usage reporting is enabled, but VSCode telemetry is disabled. To enable error and usage reporting for this extension, enable VSCode telemetry in settings.",
"Open Settings",
)
.then((selection) => {
if (selection === "Open Settings") {
void HostProvider.window
.showMessage({
type: ShowMessageType.WARNING,
message:
"Anonymous Cline error and usage reporting is enabled, but VSCode telemetry is disabled. To enable error and usage reporting for this extension, enable VSCode telemetry in settings.",
options: {
items: ["Open Settings"],
},
})
.then((response) => {
if (response.selectedOption === "Open Settings") {
void vscode.commands.executeCommand("workbench.action.openSettings", "telemetry.telemetryLevel")
}
})
+14 -16
View File
@@ -5,21 +5,15 @@ import { execa } from "execa"
import { Logger } from "@services/logging/Logger"
import { WebviewProvider } from "@core/webview"
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
import { TaskServiceClient } from "webview-ui/src/services/grpc-client"
import { validateWorkspacePath, initializeGitRepository, getFileChanges, calculateToolSuccessRate } from "./GitHelper"
import {
updateGlobalState,
getAllExtensionState,
updateApiConfiguration,
storeSecret,
updateWorkspaceState,
} from "@core/storage/state"
import { updateGlobalState, getAllExtensionState, storeSecret } from "@core/storage/state"
import { ClineAsk, ExtensionMessage } from "@shared/ExtensionMessage"
import { ApiProvider } from "@shared/api"
import { HistoryItem } from "@shared/HistoryItem"
import { getSavedClineMessages, getSavedApiConversationHistory } from "@core/storage/disk"
import { AskResponseRequest } from "@shared/proto/cline/task"
import { getCwd } from "@/utils/path"
import { askResponse } from "@core/controller/task/askResponse"
/**
* Creates a tracker to monitor tool calls and failures during task execution
@@ -268,14 +262,17 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server
}
// Store the API key securely
await storeSecret(visibleWebview.controller.context, "clineAccountId", apiKey)
visibleWebview.controller.cacheService.setSecret("clineAccountId", apiKey)
// Update the API configuration
await updateApiConfiguration(visibleWebview.controller.context, updatedConfig)
visibleWebview.controller.cacheService.setApiConfiguration(updatedConfig)
// Update global state to use cline provider
await updateGlobalState(visibleWebview.controller.context, "planModeApiProvider", "cline")
await updateGlobalState(visibleWebview.controller.context, "actModeApiProvider", "cline")
// Update cache service to use cline provider
const currentConfig = visibleWebview.controller.cacheService.getApiConfiguration()
visibleWebview.controller.cacheService.setApiConfiguration({
...currentConfig,
planModeApiProvider: "cline",
actModeApiProvider: "cline",
})
// Post state to webview to reflect changes
await visibleWebview.controller.postStateToWebview()
@@ -624,9 +621,10 @@ async function autoRespondToAsk(webviewProvider: WebviewProvider, askType: Cline
// we use the default "yesButtonClicked" to approve the action
}
// Send the response message
// Send the response message using the backend controller method
try {
await TaskServiceClient.askResponse(
await askResponse(
webviewProvider.controller,
AskResponseRequest.create({
responseType,
text: responseText,
+71
View File
@@ -0,0 +1,71 @@
import * as vscode from "vscode"
import { WebviewProvider } from "@/core/webview"
/**
* Shared URI handler that processes both VSCode URI events and HTTP server callbacks
*/
export class SharedUriHandler {
/**
* Processes a URI and routes it to the appropriate handler
* @param uri The URI to process (can be from VSCode or converted from HTTP)
* @returns Promise<boolean> indicating success (true) or failure (false)
*/
public static async handleUri(uri: vscode.Uri): Promise<boolean> {
console.log("SharedUriHandler: Processing URI:", {
path: uri.path,
query: uri.query,
scheme: uri.scheme,
})
const path = uri.path
const query = new URLSearchParams(uri.query.replace(/\+/g, "%2B"))
const visibleWebview = WebviewProvider.getVisibleInstance()
if (!visibleWebview) {
console.warn("SharedUriHandler: No visible webview found")
return false
}
try {
switch (path) {
case "/openrouter": {
const code = query.get("code")
if (code) {
await visibleWebview.controller.handleOpenRouterCallback(code)
return true
}
console.warn("SharedUriHandler: Missing code parameter for OpenRouter callback")
return false
}
case "/auth": {
console.log("SharedUriHandler: Auth callback received:", { path: uri.path, provider: query.get("provider") })
const token = query.get("idToken")
const provider = query.get("provider")
if (token) {
await visibleWebview.controller.handleAuthCallback(token, provider)
return true
}
console.warn("SharedUriHandler: Missing idToken parameter for auth callback")
return false
}
default:
console.warn(`SharedUriHandler: Unknown path: ${path}`)
return false
}
} catch (error) {
console.error("SharedUriHandler: Error processing URI:", error)
return false
}
}
/**
* Converts an HTTP URL to a vscode.Uri for unified processing
* @param httpUrl The HTTP URL to convert
* @returns vscode.Uri representation of the URL
*/
public static convertHttpUrlToUri(httpUrl: string): vscode.Uri {
return vscode.Uri.parse(httpUrl)
}
}
+9 -7
View File
@@ -12,14 +12,15 @@ import { McpDisplayMode } from "./McpDisplayMode"
// webview will hold state
export interface ExtensionMessage {
type: "grpc_response" // New type for gRPC responses
grpc_response?: GrpcResponse
}
grpc_response?: {
message?: any // JSON serialized protobuf message
request_id: string // Same ID as the request
error?: string // Optional error message
is_streaming?: boolean // Whether this is part of a streaming response
sequence_number?: number // For ordering chunks in streaming responses
}
export type GrpcResponse = {
message?: any // JSON serialized protobuf message
request_id: string // Same ID as the request
error?: string // Optional error message
is_streaming?: boolean // Whether this is part of a streaming response
sequence_number?: number // For ordering chunks in streaming responses
}
export type Platform = "aix" | "darwin" | "freebsd" | "linux" | "openbsd" | "sunos" | "win32" | "unknown"
@@ -62,6 +63,7 @@ export interface ExtensionState {
localCursorRulesToggles: ClineRulesToggles
localWindsurfRulesToggles: ClineRulesToggles
mcpResponsesCollapsed?: boolean
strictPlanModeEnabled?: boolean
}
export interface ClineMessage {
+13 -65
View File
@@ -1,71 +1,19 @@
import { ApiConfiguration } from "./api"
import { BrowserSettings } from "./BrowserSettings"
import { UserInfo } from "./UserInfo"
import { ChatContent } from "./ChatContent"
import { TelemetrySetting } from "./TelemetrySetting"
import { McpViewTab } from "./mcp"
export interface WebviewMessage {
type:
| "requestVsCodeLmModels"
| "fetchMcpMarketplace"
| "searchCommits"
| "telemetrySetting"
| "grpc_request"
| "grpc_request_cancel"
type: "grpc_request" | "grpc_request_cancel"
grpc_request?: GrpcRequest
grpc_request_cancel?: GrpcCancel
}
text?: string
disabled?: boolean
apiConfiguration?: ApiConfiguration
images?: string[]
files?: string[]
bool?: boolean
number?: number
browserSettings?: BrowserSettings
chatContent?: ChatContent
mcpId?: string
timeout?: number
tab?: McpViewTab
// For toggleToolAutoApprove
serverName?: string
serverUrl?: string
toolNames?: string[]
autoApprove?: boolean
export type GrpcRequest = {
service: string
method: string
message: any // JSON serialized protobuf message
request_id: string // For correlating requests and responses
is_streaming: boolean // Whether this is a streaming request
}
// For auth
user?: UserInfo | null
customToken?: string
planActSeparateModelsSetting?: boolean
enableCheckpointsSetting?: boolean
mcpMarketplaceEnabled?: boolean
mcpResponsesCollapsed?: boolean
telemetrySetting?: TelemetrySetting
mcpRichDisplayEnabled?: boolean
mentionsRequestId?: string
query?: string
// For toggleFavoriteModel
modelId?: string
grpc_request?: {
service: string
method: string
message: any // JSON serialized protobuf message
request_id: string // For correlating requests and responses
is_streaming?: boolean // Whether this is a streaming request
}
grpc_request_cancel?: {
request_id: string // ID of the request to cancel
}
// For cline rules and workflows
isGlobal?: boolean
rulePath?: string
workflowPath?: string
enabled?: boolean
filename?: string
offset?: number
shellIntegrationTimeout?: number
terminalReuseEnabled?: boolean
defaultTerminalProfile?: string
export type GrpcCancel = {
request_id: string // ID of the request to cancel
}
export type ClineAskResponse = "yesButtonClicked" | "noButtonClicked" | "messageResponse"
@@ -47,6 +47,11 @@ describe("Mention Regex", () => {
assertMatch(result)
})
})
it("handles unquoted paths with spaces correctly", () => {
// Should stop at the space
const match = mentionRegex.exec("@/path with spaces/file.txt")
expect(match?.[0]).to.equal("@/path")
})
})
describe("Existing Functionality", () => {
@@ -107,6 +112,7 @@ describe("Mention Regex", () => {
["C:\\folder\\file.txt", null],
["@", null],
["@ C:\\file.txt", null],
["@'/path/file.tar.gz'", null],
]
cases.forEach(([input, expected]) => {
@@ -188,4 +194,228 @@ describe("Mention Regex", () => {
})
})
})
describe("Git Hash Edge Cases", () => {
it("matches git hashes of various valid lengths", () => {
const cases: Array<[string, string | null]> = [
// Valid lengths (7-40 characters)
["@abcdef1", "@abcdef1"], // 7 chars (minimum)
["@abcdef12", "@abcdef12"], // 8 chars
["@abcdef1234567890", "@abcdef1234567890"], // 16 chars
["@abcdef1234567890abcdef1234567890abcdef12", "@abcdef1234567890abcdef1234567890abcdef12"], // 40 chars (maximum)
// Invalid lengths
["@abcdef", null], // 6 chars (too short)
["@abcdef1234567890abcdef1234567890abcdef123", null], // 41 chars (too long, but would match first 40)
// Invalid characters
["@ghijklm", null], // Contains non-hex characters
["@ABCDEF1", null], // Uppercase not allowed
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
const actual = match ? match[0] : null
if (expected && expected.includes("41 chars")) {
// Special case: should match first 40 chars
expect(actual).to.equal("@abcdef1234567890abcdef1234567890abcdef12")
} else {
expect(actual).to.equal(expected)
}
})
})
})
describe("Punctuation at Boundaries", () => {
it("excludes all types of trailing punctuation", () => {
const cases: Array<[string, string]> = [
["@/path/file.txt.", "@/path/file.txt"],
["@problems:", "@problems"],
["@terminal;", "@terminal"],
["@/path/file.txt!", "@/path/file.txt"],
["@/path/file.txt?", "@/path/file.txt"],
["@git-changes,", "@git-changes"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
it("handles multiple punctuation marks", () => {
const cases: Array<[string, string]> = [
["@/path/file.txt!?", "@/path/file.txt"],
["@problems...", "@problems"],
["@terminal!!", "@terminal"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
it("doesn't match trailing punctuation in context", () => {
const cases: Array<[string, string[]]> = [
["Check the file at @/C:\\folder\\file.txt! for details.", ["@/C:\\folder\\file.txt"]],
["Review @problems, and @git-changes.", ["@problems", "@git-changes"]],
["Multiple: @/file1.txt, and @/C:\\file2.txt; and @terminal?", ["@/file1.txt", "@/C:\\file2.txt", "@terminal"]],
]
cases.forEach(([input, expected]) => {
const matches = input.match(mentionRegexGlobal)
expect(matches).deep.eq(expected)
})
})
})
describe("URL Protocol Variations", () => {
it("matches various URL protocols", () => {
const cases: Array<[string, string]> = [
["@file://localhost/path/to/file", "@file://localhost/path/to/file"],
["@custom://app/resource", "@custom://app/resource"],
["@app://settings", "@app://settings"],
["@ssh://git@github.com/repo", "@ssh://git@github.com/repo"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
it("matches URLs with complex structures", () => {
const cases: Array<[string, string]> = [
["@https://example.com?q=test&p=1", "@https://example.com?q=test&p=1"],
["@https://example.com#section", "@https://example.com#section"],
["@http://localhost:3000", "@http://localhost:3000"],
["@https://user:pass@example.com", "@https://user:pass@example.com"],
["@https://example.com/", "@https://example.com/"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
describe("End of String Handling", () => {
it("matches mentions at end of string", () => {
const cases: Array<[string, string]> = [
["Check @/path/file.txt", "@/path/file.txt"],
["Review @problems", "@problems"],
["Open @terminal", "@terminal"],
["See @git-changes", "@git-changes"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
describe("Complex Real-World Scenarios", () => {
it("handles mentions in markdown-like text", () => {
const text = "See @/docs/README.md, check @problems, and visit @https://example.com."
const matches = text.match(mentionRegexGlobal)
expect(matches).to.deep.equal(["@/docs/README.md", "@problems", "@https://example.com"])
})
it("handles mentions in code comments", () => {
const text = "// TODO: Fix @problems in @/src/index.js (see @git-changes)"
const matches = text.match(mentionRegexGlobal)
expect(matches).to.deep.equal(["@problems", "@/src/index.js", "@git-changes"])
})
})
describe("Quoted file paths", () => {
it("handles quoted paths correctly", () => {
const cases: Array<[string, string]> = [
['@"/path with space.txt"', '@"/path with space.txt"'],
['@"/path/ends/with-space "', '@"/path/ends/with-space "'],
['@"/ path-starts-with-space.txt"', '@"/ path-starts-with-space.txt"'],
['@"/path with space.txt!"', '@"/path with space.txt!"'],
['@"/path with space.txt!"!', '@"/path with space.txt!"'],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
it("handles quotes inside file paths correctly", () => {
const cases: Array<[string, string]> = [
['@/"path/file.txt', '@/"path/file.txt'],
['@/path"/file".tar.gz', '@/path"/file".tar.gz'],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
describe("Path Edge Cases", () => {
it("matches various path structures", () => {
const cases: Array<[string, string]> = [
["@/", "@/"], // root directory
['@"/"', '@"/"'], // quoted root directory
["@/path/to/.hidden/file", "@/path/to/.hidden/file"],
["@/path/file...txt", "@/path/file...txt"],
["@/path/file.tar.gz", "@/path/file.tar.gz"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
describe("Whitespace Handling", () => {
it("stops at various whitespace characters", () => {
const cases: Array<[string, string]> = [
["@/path/file.txt\trest", "@/path/file.txt"],
["@/path/file.txt\nrest", "@/path/file.txt"],
["@/path/file.txt\rrest", "@/path/file.txt"],
["@/path/file.txt rest", "@/path/file.txt"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
describe("Keyword Boundaries", () => {
it("only matches exact keywords", () => {
const cases: Array<[string, string | null]> = [
["@problemsolver", null], // Should not match
["@terminals", null], // Should not match
["@git-changeset", null], // Should not match
["@problem", null], // Should not match
["@git-change", null], // Should not match
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
const actual = match ? match[0] : null
expect(actual).to.equal(expected)
})
})
it("matches keywords with trailing punctuation", () => {
const cases: Array<[string, string]> = [
["@problems!", "@problems"],
["@terminal.", "@terminal"],
["@git-changes,", "@git-changes"],
]
cases.forEach(([input, expected]) => {
const match = mentionRegex.exec(input)
expect(match?.[0]).to.equal(expected)
})
})
})
})
+117 -4
View File
@@ -31,6 +31,7 @@ export type ApiProvider =
| "groq"
| "huggingface"
| "huawei-cloud-maas"
| "baseten"
export interface ApiHandlerOptions {
// Global configuration (not mode-specific)
@@ -87,6 +88,7 @@ export interface ApiHandlerOptions {
sambanovaApiKey?: string
cerebrasApiKey?: string
groqApiKey?: string
basetenApiKey?: string
requestTimeoutMs?: number
sapAiCoreClientId?: string
sapAiCoreClientSecret?: string
@@ -117,6 +119,8 @@ export interface ApiHandlerOptions {
planModeSapAiCoreModelId?: string
planModeGroqModelId?: string
planModeGroqModelInfo?: ModelInfo
planModeBasetenModelId?: string
planModeBasetenModelInfo?: ModelInfo
planModeHuggingFaceModelId?: string
planModeHuggingFaceModelInfo?: ModelInfo
planModeHuaweiCloudMaasModelId?: string
@@ -144,6 +148,8 @@ export interface ApiHandlerOptions {
actModeSapAiCoreModelId?: string
actModeGroqModelId?: string
actModeGroqModelInfo?: ModelInfo
actModeBasetenModelId?: string
actModeBasetenModelInfo?: ModelInfo
actModeHuggingFaceModelId?: string
actModeHuggingFaceModelInfo?: ModelInfo
actModeHuaweiCloudMaasModelId?: string
@@ -2480,8 +2486,28 @@ export const sambanovaModels = {
// Cerebras
// https://inference-docs.cerebras.ai/api-reference/models
export type CerebrasModelId = keyof typeof cerebrasModels
export const cerebrasDefaultModelId: CerebrasModelId = "qwen-3-235b-a22b-instruct-2507"
export const cerebrasDefaultModelId: CerebrasModelId = "qwen-3-coder-480b-free"
export const cerebrasModels = {
"qwen-3-coder-480b-free": {
maxTokens: 40000,
contextWindow: 64000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description:
"SOTA coding model with ~2000 tokens/s ($0 free tier)\n\n• Use this if you don't have a Cerebras subscription\n• 64K context window\n• Rate limits: 150K TPM, 1M TPH/TPD, 10 RPM, 100 RPH/RPD\n\nUpgrade for higher limits: [https://cloud.cerebras.ai/?utm=cline](https://cloud.cerebras.ai/?utm=cline)",
},
"qwen-3-coder-480b": {
maxTokens: 40000,
contextWindow: 128000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
description:
"SOTA coding model with ~2000 tokens/s ($50/$250 paid tiers)\n\n• Use this if you have a Cerebras subscription\n• 131K context window with higher rate limits",
},
"qwen-3-235b-a22b-instruct-2507": {
maxTokens: 64000,
contextWindow: 64000,
@@ -2509,9 +2535,9 @@ export const cerebrasModels = {
outputPrice: 0,
description: "SOTA coding performance with ~2500 tokens/s",
},
"qwen-3-235b-a22b": {
maxTokens: 40000,
contextWindow: 40000,
"qwen-3-235b-a22b-thinking-2507": {
maxTokens: 32000,
contextWindow: 65000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
@@ -2864,3 +2890,90 @@ export const huaweiCloudMaasModels = {
},
},
} as const satisfies Record<string, ModelInfo>
// Baseten
// https://baseten.co/products/model-apis/
export const basetenModels = {
"deepseek-ai/DeepSeek-R1-0528": {
maxTokens: 131072,
contextWindow: 163840,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 2.55,
outputPrice: 5.95,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description:
"DeepSeek R1 0528 - A state-of-the-art 671B-parameter MoE LLM with o1-style reasoning licensed for commercial use.",
},
"deepseek-ai/DeepSeek-V3-0324": {
maxTokens: 131072,
contextWindow: 163840,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.77,
outputPrice: 0.77,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description: "DeepSeek V3 0324 - A state-of-the-art 671B-parameter MoE LLM licensed for commercial use.",
},
"meta-llama/Llama-4-Maverick-17B-128E-Instruct": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.19,
outputPrice: 0.72,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description: "Meta's Llama 4 Maverick - A SOTA mixture-of-experts multi-modal LLM with 400 billion total parameters.",
},
"meta-llama/Llama-4-Scout-17B-16E-Instruct": {
maxTokens: 8192,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.13,
outputPrice: 0.5,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description: "Meta's Llama 4 Scout - A SOTA mixture-of-experts multi-modal LLM with 109 billion total parameters.",
},
"moonshotai/Kimi-K2-Instruct": {
maxTokens: 131072,
contextWindow: 131072,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.6,
outputPrice: 2.5,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description: "Moonshot AI's Kimi K2 - The world's first 1 trillion parameter open source model.",
},
"Qwen/Qwen3-235B-A22B-Instruct-2507": {
maxTokens: 163800,
contextWindow: 163800,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.22,
outputPrice: 0.8,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description:
"Qwen3-235B-A22B-Instruct-2507 is a multilingual, instruction-tuned mixture-of-experts language model based on the Qwen3-235B architecture, with 22B active parameters per forward pass.",
},
"Qwen/Qwen3-Coder-480B-A35B-Instruct": {
maxTokens: 163800,
contextWindow: 163800,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1.7,
outputPrice: 1.7,
cacheWritesPrice: 0,
cacheReadsPrice: 0,
description:
"Qwen3-Coder-480B-A35B-Instruct is a 480B parameter, instruction-tuned, agentic coding model that excels at function calling, tool use, and long-context reasoning over repositories.",
},
} as const satisfies Record<string, ModelInfo>
export type BasetenModelId = keyof typeof basetenModels
export const basetenDefaultModelId = "moonshotai/Kimi-K2-Instruct" satisfies BasetenModelId
+15 -5
View File
@@ -29,10 +29,10 @@ Mention regex:
- **Exact Word ('terminal')**: Matches the exact word 'terminal'.
- **Word Boundary (`\b`)**: Ensures that 'terminal' is matched as a whole word and not as part of another word (e.g., 'terminals').
- `(?=[.,;:!?]?(?=[\s\r\n]|$))`:
- `(?=[.,;:!?()]*(?=[\s\r\n]|$))`:
- **Positive Lookahead (`(?=...)`)**: Ensures that the match is followed by specific patterns without including them in the match.
- `[.,;:!?]?`:
- **Optional Punctuation (`[.,;:!?]?`)**: Matches zero or one of the specified punctuation marks.
- `[.,;:!?()]*`:
- **Optional Punctuation (`[.,;:!?()]*`)**: Matches zero or more of the specified punctuation marks (including parentheses).
- `(?=[\s\r\n]|$)`:
- **Nested Positive Lookahead (`(?=[\s\r\n]|$)`)**: Ensures that the punctuation (if present) is followed by a whitespace character, a line break, or the end of the string.
@@ -49,6 +49,16 @@ Mention regex:
- `mentionRegexGlobal`: Creates a global version of the `mentionRegex` to find all matches within a given string.
*/
export const mentionRegex =
/@((?:\/|\w+:\/\/)[^\s]+?|[a-f0-9]{7,40}\b|problems\b|terminal\b|git-changes\b)(?=[.,;:!?]?(?=[\s\r\n]|$))/
export const mentionRegex = new RegExp(
`@(` +
`/[^\\s]*?` + // Simple file paths (can't contain)
`|"\\/[^"]*?"` + // Quoted file paths which can contain spaces
`|(?:\\w+:\\/\\/)[^\\s]+?` + // URLs
`|[a-f0-9]{7,40}\\b` + // Git commit hashes
`|problems\\b` + // Exact word 'problems'
`|terminal\\b` + // Exact word 'terminal'
`|git-changes\\b` + // Exact word 'git-changes'
`)` +
`(?=[.,;:!?()]*(?=[\\s\\r\\n]|$))`, // Lookahead for trailing punctuation (multiple allowed)
)
export const mentionRegexGlobal = new RegExp(mentionRegex.source, "g")
@@ -240,6 +240,8 @@ function convertApiProviderToProto(provider: string | undefined): ProtoApiProvid
return ProtoApiProvider.CEREBRAS
case "groq":
return ProtoApiProvider.GROQ
case "baseten":
return ProtoApiProvider.BASETEN
case "sapaicore":
return ProtoApiProvider.SAPAICORE
case "claude-code":
@@ -308,6 +310,8 @@ function convertProtoToApiProvider(provider: ProtoApiProvider): ApiProvider {
return "cerebras"
case ProtoApiProvider.GROQ:
return "groq"
case ProtoApiProvider.BASETEN:
return "baseten"
case ProtoApiProvider.SAPAICORE:
return "sapaicore"
case ProtoApiProvider.CLAUDE_CODE:
@@ -376,6 +380,7 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA
sambanovaApiKey: config.sambanovaApiKey,
cerebrasApiKey: config.cerebrasApiKey,
groqApiKey: config.groqApiKey,
basetenApiKey: config.basetenApiKey,
requestTimeoutMs: config.requestTimeoutMs,
sapAiCoreClientId: config.sapAiCoreClientId,
sapAiCoreClientSecret: config.sapAiCoreClientSecret,
@@ -406,6 +411,8 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA
planModeFireworksModelId: config.planModeFireworksModelId,
planModeGroqModelId: config.planModeGroqModelId,
planModeGroqModelInfo: convertModelInfoToProtoOpenRouter(config.planModeGroqModelInfo),
planModeBasetenModelId: config.planModeBasetenModelId,
planModeBasetenModelInfo: convertModelInfoToProtoOpenRouter(config.planModeBasetenModelInfo),
planModeHuggingFaceModelId: config.planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo: convertModelInfoToProtoOpenRouter(config.planModeHuggingFaceModelInfo),
planModeSapAiCoreModelId: config.planModeSapAiCoreModelId,
@@ -434,6 +441,8 @@ export function convertApiConfigurationToProto(config: ApiConfiguration): ProtoA
actModeFireworksModelId: config.actModeFireworksModelId,
actModeGroqModelId: config.actModeGroqModelId,
actModeGroqModelInfo: convertModelInfoToProtoOpenRouter(config.actModeGroqModelInfo),
actModeBasetenModelId: config.actModeBasetenModelId,
actModeBasetenModelInfo: convertModelInfoToProtoOpenRouter(config.actModeBasetenModelInfo),
actModeHuggingFaceModelId: config.actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo: convertModelInfoToProtoOpenRouter(config.actModeHuggingFaceModelInfo),
actModeSapAiCoreModelId: config.actModeSapAiCoreModelId,
@@ -502,6 +511,7 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio
sambanovaApiKey: protoConfig.sambanovaApiKey,
cerebrasApiKey: protoConfig.cerebrasApiKey,
groqApiKey: protoConfig.groqApiKey,
basetenApiKey: protoConfig.basetenApiKey,
requestTimeoutMs: protoConfig.requestTimeoutMs,
sapAiCoreClientId: protoConfig.sapAiCoreClientId,
sapAiCoreClientSecret: protoConfig.sapAiCoreClientSecret,
@@ -535,6 +545,8 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio
planModeFireworksModelId: protoConfig.planModeFireworksModelId,
planModeGroqModelId: protoConfig.planModeGroqModelId,
planModeGroqModelInfo: convertProtoToModelInfo(protoConfig.planModeGroqModelInfo),
planModeBasetenModelId: protoConfig.planModeBasetenModelId,
planModeBasetenModelInfo: convertProtoToModelInfo(protoConfig.planModeBasetenModelInfo),
planModeHuggingFaceModelId: protoConfig.planModeHuggingFaceModelId,
planModeHuggingFaceModelInfo: convertProtoToModelInfo(protoConfig.planModeHuggingFaceModelInfo),
planModeSapAiCoreModelId: protoConfig.planModeSapAiCoreModelId,
@@ -564,6 +576,8 @@ export function convertProtoToApiConfiguration(protoConfig: ProtoApiConfiguratio
actModeFireworksModelId: protoConfig.actModeFireworksModelId,
actModeGroqModelId: protoConfig.actModeGroqModelId,
actModeGroqModelInfo: convertProtoToModelInfo(protoConfig.actModeGroqModelInfo),
actModeBasetenModelId: protoConfig.actModeBasetenModelId,
actModeBasetenModelInfo: convertProtoToModelInfo(protoConfig.actModeBasetenModelInfo),
actModeHuggingFaceModelId: protoConfig.actModeHuggingFaceModelId,
actModeHuggingFaceModelInfo: convertProtoToModelInfo(protoConfig.actModeHuggingFaceModelInfo),
actModeSapAiCoreModelId: protoConfig.actModeSapAiCoreModelId,
+7
View File
@@ -1,5 +1,6 @@
import { activate } from "@/extension"
import { Controller } from "@core/controller"
import { CacheService } from "@core/storage/CacheService"
import { ExternalDiffViewProvider } from "@hosts/external/ExternalDiffviewProvider"
import { ExternalWebviewProvider } from "@hosts/external/ExternalWebviewProvider"
import { ExternalHostBridgeClientManager } from "@hosts/external/host-bridge-client-manager"
@@ -9,6 +10,7 @@ import { v4 as uuidv4 } from "uuid"
import { log } from "./utils"
import { extensionContext, postMessage } from "./vscode-context"
import { startProtobusService } from "./protobus-service"
import { AuthHandler } from "@/hosts/external/AuthHandler"
import { WebviewProvider } from "@/core/webview"
import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider"
@@ -21,8 +23,13 @@ async function main() {
setupGlobalErrorHandlers()
activate(extensionContext)
// Create and initialize cache service
// Create controller with cache service
const controller = new Controller(extensionContext, postMessage, uuidv4())
startProtobusService(controller)
AuthHandler.getInstance().setEnabled(true)
}
function setupHostProvider() {
+2 -1
View File
@@ -11,7 +11,8 @@ const log = (...args: unknown[]) => {
function getPackageDefinition() {
// Load service definitions.
const descriptorSet = fs.readFileSync("proto/descriptor_set.pb")
const descriptorDefs = protoLoader.loadFileDescriptorSetFromBuffer(descriptorSet)
const options = { longs: Number } // Encode int64 fields as numbers
const descriptorDefs = protoLoader.loadFileDescriptorSetFromBuffer(descriptorSet, options)
const healthDef = protoLoader.loadSync(health.protoPath)
const packageDefinition = { ...descriptorDefs, ...healthDef }
return packageDefinition
@@ -1,12 +1,11 @@
import type { DiffViewProviderCreator, WebviewProviderCreator } from "@/hosts/host-provider"
import { HostProvider } from "@/hosts/host-provider"
import { HostBridgeClientProvider } from "@/hosts/host-provider-types"
import * as stateModule from "@core/storage/state"
import { afterEach, beforeEach, describe, it } from "mocha"
import { describe, it, beforeEach, afterEach } from "mocha"
import * as should from "should"
import * as sinon from "sinon"
import type { ClineAPI } from "../cline"
import { createClineAPI } from "../index"
import type { ClineAPI } from "../exports/cline"
import { DiffViewProviderCreator, HostProvider, WebviewProviderCreator } from "@/hosts/host-provider"
import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client"
import * as stateModule from "@core/storage/state"
import { createClineAPI } from "@/exports"
describe("ClineAPI Core Functionality", () => {
let api: ClineAPI
@@ -15,15 +14,16 @@ describe("ClineAPI Core Functionality", () => {
let sandbox: sinon.SinonSandbox
let getGlobalStateStub: sinon.SinonStub
beforeEach(() => {
beforeEach(async () => {
sandbox = sinon.createSandbox()
// Create mock log function
mockLogToChannel = sandbox.stub<[string], void>()
HostProvider.reset()
HostProvider.initialize(
((_) => {}) as WebviewProviderCreator,
(() => {}) as DiffViewProviderCreator,
{} as HostBridgeClientProvider,
vscodeHostBridgeClient,
mockLogToChannel,
)
// Stub the getGlobalState function from the state module
@@ -33,6 +33,7 @@ describe("ClineAPI Core Functionality", () => {
// Create a mock controller that matches what the real createClineAPI expects
// We don't import the real Controller to avoid the webview dependencies
mockController = {
id: "test-controller-id",
context: {
globalState: {
get: sandbox.stub(),
@@ -73,10 +74,6 @@ describe("ClineAPI Core Functionality", () => {
// 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"
+56 -16
View File
@@ -11,6 +11,9 @@ const E2E_API_SERVER_PORT = 7777
export const MOCK_CLINE_API_SERVER_URL = `http://localhost:${E2E_API_SERVER_PORT}`
export class ClineApiServerMock {
static globalSharedServer: ClineApiServerMock | null = null
static globalSockets: Set<Socket> = new Set()
private currentUser: UserResponse | null = null
private userBalance = 100.5 // Default sufficient balance
private orgBalance = 500.0
@@ -101,8 +104,12 @@ export class ClineApiServerMock {
return { matched: false }
}
// Runs a mock Cline API server for testing
public static async run<T>(around: (server: ClineApiServerMock) => Promise<T>): Promise<T> {
// Starts the global shared server
public static async startGlobalServer(): Promise<ClineApiServerMock> {
if (ClineApiServerMock.globalSharedServer) {
return ClineApiServerMock.globalSharedServer
}
const server = createServer((req: IncomingMessage, res: ServerResponse) => {
// Parse URL and method
const parsedUrl = parse(req.url || "", true)
@@ -151,14 +158,19 @@ export class ClineApiServerMock {
// Authenticate the token and set current user
if (isAuthRequired && authToken) {
console.log(`Authenticating token: ${authToken}`)
const user = controller.API_USER.getUserByToken(authToken)
const user = ClineApiServerMock.globalSharedServer!.API_USER.getUserByToken(authToken)
if (!user) {
return sendApiError("Invalid token", 401)
}
controller.setCurrentUser(user)
ClineApiServerMock.globalSharedServer!.setCurrentUser(user)
}
console.log("Received %s request for %s query %s", method, path, JSON.stringify(query))
console.log("=== MOCK SERVER REQUEST ===")
console.log("Method:", method)
console.log("Path:", path)
console.log("Query:", JSON.stringify(query))
console.log("Headers:", JSON.stringify(req.headers))
console.log("===============")
// Route handling
const handleRequest = async () => {
@@ -170,6 +182,7 @@ export class ClineApiServerMock {
}
const { baseRoute, endpoint, params = {} } = routeMatch
const controller = ClineApiServerMock.globalSharedServer!
// Health check endpoints
if (baseRoute === "/health") {
@@ -332,7 +345,7 @@ export class ClineApiServerMock {
}
res.write(`data: ${JSON.stringify(chunk)}\n\n`)
chunkIndex++
setTimeout(sendChunk, 20)
setTimeout(sendChunk, 50)
} else {
const finalChunk = {
id: generationId,
@@ -452,20 +465,47 @@ export class ClineApiServerMock {
// Initialize the controller after the server is created
const controller = new ClineApiServerMock(server)
server.listen(E2E_API_SERVER_PORT)
ClineApiServerMock.globalSharedServer = controller
// Track connections for proper cleanup
const sockets = new Set<Socket>()
server.on("connection", (socket) => sockets.add(socket))
server.on("connection", (socket) => {
ClineApiServerMock.globalSockets.add(socket)
socket.on("close", () => {
ClineApiServerMock.globalSockets.delete(socket)
})
})
const result = await around(controller)
await new Promise<void>((resolve, reject) => {
server.listen(E2E_API_SERVER_PORT, (error?: Error) => {
if (error) {
console.error(`Failed to start server on port ${E2E_API_SERVER_PORT}:`, error)
reject(error)
} else {
console.log(`ClineApiServerMock listening on port ${E2E_API_SERVER_PORT}`)
resolve()
}
})
})
// Clean shutdown
const serverClosed = new Promise((resolve) => server.close(resolve))
sockets.forEach((socket) => socket.destroy())
await serverClosed
return controller
}
return result
// Stops the global shared server
public static async stopGlobalServer(): Promise<void> {
if (!ClineApiServerMock.globalSharedServer) {
return
}
const server = ClineApiServerMock.globalSharedServer.server
// Clean shutdown - destroy all socket connections first
ClineApiServerMock.globalSockets.forEach((socket) => socket.destroy())
ClineApiServerMock.globalSockets.clear()
await new Promise<void>((resolve) => {
server.close(() => resolve())
})
ClineApiServerMock.globalSharedServer = null
}
}
+27
View File
@@ -0,0 +1,27 @@
import { rmSync } from "node:fs"
import { test as setup } from "@playwright/test"
import { getResultsDir } from "./helpers"
setup("setup test environment", async () => {
try {
const path = getResultsDir()
const options = { recursive: true, force: true }
const maxAttempts = 2
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
rmSync(path, options)
return
} catch (error) {
if (attempt === maxAttempts) {
throw new Error(`Failed to rmSync ${path} after ${maxAttempts} attempts: ${error}`)
}
console.error(`Failed to rmSync ${path} after ${attempt} attempts: ${error}`)
await new Promise((resolve) => setTimeout(resolve, 50 * attempt)) // Progressive delay
}
}
} catch (error) {
console.error(`Error during setup: ${error}`)
}
})
@@ -1,9 +1,10 @@
import fs from "node:fs/promises"
import path from "node:path"
import type { FullConfig } from "playwright/test"
import { test as teardown } from "@playwright/test"
import { ClineApiServerMock } from "../fixtures/server"
import { getResultsDir, rmForRetries } from "./helpers"
export default async function (_: FullConfig) {
teardown("cleanup test environment", async () => {
const assetsDir = getResultsDir()
try {
@@ -21,10 +22,12 @@ export default async function (_: FullConfig) {
}
}),
)
await ClineApiServerMock.stopGlobalServer()
console.log("ClineApiServerMock stopped successfully.")
} catch (error) {
// Silently handle case where assets directory doesn't exist
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error
}
}
}
})
+19 -14
View File
@@ -124,12 +124,12 @@ export class E2ETestHelper {
}
public static async runCommandPalette(page: Page, command: string): Promise<void> {
await page.locator("li").filter({ hasText: "[Extension Development Host]" }).first().click()
const editorMenu = page.locator("li").filter({ hasText: "[Extension Development Host]" }).first()
await editorMenu.click({ delay: 100 })
const editorSearchBar = page.getByRole("textbox", {
name: "Search files by name (append",
})
await expect(editorSearchBar).toBeVisible()
await editorSearchBar.click()
await editorSearchBar.click({ delay: 100 }) // Ensure focus
await editorSearchBar.fill(`>${command}`)
await page.keyboard.press("Enter")
}
@@ -151,7 +151,7 @@ export class E2ETestHelper {
* @extends test - Base Playwright test with multiple fixture extensions
*
* Fixtures provided:
* - `server`: ClineApiServerMock instance for API mocking
* - `server`: Shared ClineApiServerMock instance for API mocking (reused across all tests)
* - `workspaceDir`: Path to the test workspace directory
* - `userDataDir`: Temporary directory for VS Code user data
* - `extensionsDir`: Temporary directory for VS Code extensions
@@ -187,13 +187,19 @@ export class E2ETestHelper {
* - Configures VS Code with disabled updates, workspace trust, and welcome screens
*/
export const e2e = test
.extend<{ server: ClineApiServerMock }>({
server: [
async ({}, use) => {
ClineApiServerMock.run(async (server) => await use(server))
},
{ auto: true },
],
.extend<{ server: ClineApiServerMock | null }>({
server: async ({}, use) => {
console.log("=== SERVER FIXTURE CALLED ===")
// Start server if it doesn't exist
if (!ClineApiServerMock.globalSharedServer) {
console.log("Starting global server...")
await ClineApiServerMock.startGlobalServer()
console.log("Global server started successfully")
} else {
console.log("Using existing global server")
}
await use(ClineApiServerMock.globalSharedServer)
},
})
.extend<E2ETestDirectories>({
workspaceDir: async ({}, use) => {
@@ -267,13 +273,12 @@ export const e2e = test
.extend({
page: async ({ app }, use) => {
const page = await app.firstWindow()
await E2ETestHelper.runCommandPalette(page, "notifications: toggle do not disturb")
await E2ETestHelper.openClineSidebar(page)
await use(page)
},
})
.extend<{ sidebar: Frame }>({
sidebar: async ({ page, helper }, use) => {
sidebar: async ({ page, helper, server }, use) => {
await E2ETestHelper.openClineSidebar(page)
const sidebar = await helper.getSidebar(page)
await use(sidebar)
},
-22
View File
@@ -1,22 +0,0 @@
import { rmSync } from "node:fs"
import { getResultsDir } from "./helpers"
export default async function (): Promise<void> {
const path = getResultsDir()
const options = { recursive: true, force: true }
const maxAttempts = 2
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
rmSync(path, options)
return
} catch (error) {
if (attempt === maxAttempts) {
throw new Error(`Failed to rmSync ${path} after ${maxAttempts} attempts: ${error}`)
}
console.error(`Failed to rmSync ${path} after ${attempt} attempts: ${error}`)
await new Promise((resolve) => setTimeout(resolve, 50 * attempt)) // Progressive delay
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import * as vscode from "vscode"
/**
* Gets the latest announcement ID based on the extension version
* Uses major.minor version format (e.g., "1.2" from "1.2.3")
*
* @param context The VSCode extension context
* @returns The announcement ID string (major.minor version) or empty string if unavailable
*/
export function getLatestAnnouncementId(context: vscode.ExtensionContext): string {
return context.extension?.packageJSON?.version?.split(".").slice(0, 2).join(".") ?? ""
}
+12 -8
View File
@@ -13,11 +13,12 @@
* fields containing special characters.
*/
import * as vscode from "vscode"
import * as cp from "child_process"
import * as os from "os"
import * as util from "util"
import { writeTextToClipboard, openExternal } from "@/utils/env"
import { HostProvider } from "@hosts/host-provider"
import { ShowMessageType } from "@shared/proto/host/window"
/**
* Creates a properly encoded GitHub issue URL.
@@ -152,13 +153,16 @@ export async function openUrlInBrowser(url: string): Promise<void> {
console.error(`Error with openExternal utility: ${openExternalError}`)
// Last fallback: Show a message with instructions
vscode.window
.showInformationMessage(
"Couldn't open the URL automatically. It has been copied to your clipboard.",
"Copy URL Again",
)
.then((selection) => {
if (selection === "Copy URL Again") {
HostProvider.window
.showMessage({
type: ShowMessageType.INFORMATION,
message: "Couldn't open the URL automatically. It has been copied to your clipboard.",
options: {
items: ["Copy URL Again"],
},
})
.then((response) => {
if (response.selectedOption === "Copy URL Again") {
writeTextToClipboard(url)
}
})
+12
View File
@@ -14,6 +14,18 @@ export function isGemini2dot5ModelFamily(api: ApiHandler): boolean {
return modelId.includes("gemini-2.5")
}
export function isGrok4ModelFamily(api: ApiHandler): boolean {
const model = api.getModel()
const modelId = model.id.toLowerCase()
return modelId.includes("grok-4")
}
export function modelDoesntSupportWebp(api: ApiHandler): boolean {
const model = api.getModel()
const modelId = model.id.toLowerCase()
return modelId.includes("grok")
}
/**
* Determines if reasoning content should be skipped for a given model
* Currently skips reasoning for Grok-4 models since they only display "thinking" without useful information
+14
View File
@@ -1,6 +1,7 @@
const tsConfigPaths = require("tsconfig-paths")
const fs = require("fs")
const path = require("path")
const Module = require("module")
const baseUrl = path.resolve(__dirname)
@@ -23,3 +24,16 @@ tsConfigPaths.register({
baseUrl: baseUrl,
paths: outPaths,
})
// Mock the @google/genai module to avoid ESM compatibility issues in tests
// The module is ES6 only, but the integration tests are compiled to commonJS.
const originalRequire = Module.prototype.require
Module.prototype.require = function (id) {
// Intercept requires for @google/genai
if (id === "@google/genai") {
// Return the mock instead
const mockPath = path.join(baseUrl, "out/src/api/providers/gemini-mock.test.js")
return originalRequire.call(this, mockPath)
}
return originalRequire.call(this, id)
}
+1 -1
View File
@@ -6,7 +6,7 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:test": "tsc -b && vite build",
"build:test": "tsc -b && vite build -- --dev-build",
"preview": "vite preview",
"lint": "eslint . --ext .ts,.tsx",
"test": "vitest run",
+1 -1
View File
@@ -58,7 +58,7 @@ const AppContent = () => {
}
return (
<div className="flex h-full w-full">
<div className="flex h-screen w-full flex-col">
{showSettings && <SettingsView onDone={hideSettings} />}
{showHistory && <HistoryView onDone={hideHistory} />}
{showMcp && <McpView initialTab={mcpTab} onDone={closeMcpView} />}
+42 -40
View File
@@ -28,6 +28,7 @@ import {
useScrollBehavior,
WelcomeSection,
} from "./chat-view"
import AutoApproveBar from "./auto-approve-menu/AutoApproveBar"
interface ChatViewProps {
isHidden: boolean
@@ -198,8 +199,6 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
// Use message handlers hook
const messageHandlers = useMessageHandlers(messages, chatState, isStreaming)
const { handleSendMessage, handlePrimaryButtonClick, handleSecondaryButtonClick, handleTaskCloseButtonClick } =
messageHandlers
const { selectedModelInfo } = useMemo(() => {
return normalizeApiConfiguration(apiConfiguration, mode)
@@ -323,33 +322,32 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
return (
<ChatLayout isHidden={isHidden}>
{IS_STANDALONE && <Navbar />}
{task ? (
<TaskSection
task={task}
apiMetrics={apiMetrics}
selectedModelInfo={{
supportsPromptCache: selectedModelInfo.supportsPromptCache,
supportsImages: selectedModelInfo.supportsImages || false,
}}
lastApiReqTotalTokens={lastApiReqTotalTokens}
messageHandlers={messageHandlers}
scrollBehavior={scrollBehavior}
/>
) : (
<WelcomeSection
telemetrySetting={telemetrySetting}
showAnnouncement={showAnnouncement}
version={version}
hideAnnouncement={hideAnnouncement}
shouldShowQuickWins={shouldShowQuickWins}
taskHistory={taskHistory}
showHistoryView={showHistoryView}
/>
)}
{task && (
<>
<div className="flex flex-col flex-1 overflow-hidden">
{IS_STANDALONE && <Navbar />}
{task ? (
<TaskSection
task={task}
apiMetrics={apiMetrics}
selectedModelInfo={{
supportsPromptCache: selectedModelInfo.supportsPromptCache,
supportsImages: selectedModelInfo.supportsImages || false,
}}
lastApiReqTotalTokens={lastApiReqTotalTokens}
messageHandlers={messageHandlers}
scrollBehavior={scrollBehavior}
/>
) : (
<WelcomeSection
telemetrySetting={telemetrySetting}
showAnnouncement={showAnnouncement}
version={version}
hideAnnouncement={hideAnnouncement}
shouldShowQuickWins={shouldShowQuickWins}
taskHistory={taskHistory}
showHistoryView={showHistoryView}
/>
)}
{task && (
<MessagesArea
task={task}
groupedMessages={groupedMessages}
@@ -358,6 +356,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
chatState={chatState}
messageHandlers={messageHandlers}
/>
)}
</div>
<footer className="bg-[var(--vscode-sidebar-background)]" style={{ gridRow: "2" }}>
<AutoApproveBar />
{task && (
<ActionButtons
chatState={chatState}
messageHandlers={messageHandlers}
@@ -368,17 +371,16 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
showScrollToBottom: scrollBehavior.showScrollToBottom,
}}
/>
</>
)}
<InputSection
chatState={chatState}
messageHandlers={messageHandlers}
scrollBehavior={scrollBehavior}
placeholderText={placeholderText}
shouldDisableFilesAndImages={shouldDisableFilesAndImages}
selectFilesAndImages={selectFilesAndImages}
/>
)}
<InputSection
chatState={chatState}
messageHandlers={messageHandlers}
scrollBehavior={scrollBehavior}
placeholderText={placeholderText}
shouldDisableFilesAndImages={shouldDisableFilesAndImages}
selectFilesAndImages={selectFilesAndImages}
/>
</footer>
</ChatLayout>
)
}
@@ -2,6 +2,9 @@ import VSCodeButtonLink from "@/components/common/VSCodeButtonLink"
import { TaskServiceClient } from "@/services/grpc-client"
import { AskResponseRequest } from "@shared/proto/cline/task"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useExtensionState } from "@/context/ExtensionStateContext"
import React from "react"
interface CreditLimitErrorProps {
@@ -19,6 +22,12 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({
message = "You have run out of credit.",
buyCreditsUrl = "https://app.cline.bot/dashboard/account?tab=credits&redirect=true",
}) => {
const { uriScheme } = useExtensionState()
const callbackUrl = `${uriScheme || "vscode"}://saoudrizwan.claude-dev`
const fullPurchaseUrl = new URL(buyCreditsUrl)
fullPurchaseUrl.searchParams.set("callback_url", callbackUrl)
// We have to divide because the balance is stored in microcredits
return (
<div className="p-2 border-none rounded-md mb-2 bg-[var(--vscode-textBlockQuote-background)]">
@@ -34,7 +43,7 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({
</div>
<VSCodeButtonLink
href={buyCreditsUrl}
href={fullPurchaseUrl.toString()}
style={{
width: "100%",
marginBottom: "8px",
@@ -1,4 +1,4 @@
import React from "react"
import type React from "react"
import styled from "styled-components"
interface ChatLayoutProps {
@@ -11,18 +11,30 @@ interface ChatLayoutProps {
* Provides the fixed positioning and flex layout structure
*/
export const ChatLayout: React.FC<ChatLayoutProps> = ({ isHidden, children }) => {
return <ChatLayoutContainer isHidden={isHidden}>{children}</ChatLayoutContainer>
return (
<ChatLayoutContainer isHidden={isHidden}>
<MainContent>{children}</MainContent>
</ChatLayoutContainer>
)
}
const ChatLayoutContainer = styled.div.withConfig({
shouldForwardProp: (prop) => !["isHidden"].includes(prop),
})<{ isHidden: boolean }>`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: ${(props) => (props.isHidden ? "none" : "flex")};
display: ${(props) => (props.isHidden ? "none" : "grid")};
grid-template-rows: 1fr auto;
overflow: hidden;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
min-height: 100vh;
position: relative;
`
const MainContent = styled.div`
display: flex;
flex-direction: column;
overflow: hidden;
grid-row: 1;
`

Some files were not shown because too many files have changed in this diff Show More