Compare commits

...

57 Commits

Author SHA1 Message Date
celestial-vault a94f3b3ba9 merge conflicts 2025-09-30 11:13:45 -07:00
kvyb 15f713d26a Pass host telemetry requests (#6444)
* feat: add ideId to headers

* Add IDE-id to telemetry and request headers

* feat: send X-IDE-ID/X-IDE-VERSION headers; cache host version in EnvService

* feat: send X-IDE-ID/X-IDE-VERSION/X-CLIENT-VERSION

* Address PR feedback: single RPC call, remove cache, use ExtensionRegistryInfo, remove redundant ide_id

* feat: align headers with backend

* fix: PR feedback; EnvUtils and aligned headers with backend;
2025-09-29 22:52:06 -07:00
kvyb 5babd9e061 fix: keep fuzzy search active in chat input after selecting Add File/… (#6078)
* fix: keep fuzzy search active in chat input after selecting Add File/Folder

* fix: mentions, strip leading '/' and enforce file/folder-only results

* fix: improve readability of filteredDynamic

* fix: improve readability of selectedTypeValue
2025-09-30 07:47:58 +03:00
celestial-vault ba12672600 Remove open in editor button (#6462)
* first pass of removing all related code

# Conflicts:
#	src/hosts/external/ExternalWebviewProvider.ts
#	src/hosts/vscode/VscodeWebviewProvider.ts

* remove more things

* rename all sidebarWebviews to webview

* remove null from getInstance and remove null checks

* remove client id logic and update RPC subscriptions to match this

* add back extension.test.ts without irrelevant webview panel tests

* Refresh CI cache - fix proto compilation

* add comment to try to invalidate CI cache

* add clean script to test.yml for test-platform-integration

* remove clean script didn't work

* finally found the error in the code - linter wasn't highlighting it

* Don't delete unrelated tests in this PR

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-09-29 21:15:17 -07:00
Sarah Fortune 163bf77677 Add a way for cline-core to get the version of the client. (#6553)
Add fields to the getHostVersion RPC that return the version of the cline-core client (e.g. the extension or plugin version).
2025-09-29 21:08:30 -07:00
Saoud Rizwan edf5ea00f6 Change task timeline item hover style 2025-09-29 20:18:47 -07:00
github-actions[bot] c3c80ffc4d v3.32.5 Release Notes (#6552)
* 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-09-29 18:17:17 -07:00
Saoud Rizwan f14ed8506d Use state to manage NewModelBanner presentation 2025-09-29 18:17:17 -07:00
Saoud Rizwan 41202df74e Add prompt to encourage Sonnet 4.5 to use multiple search/replace blocks in a diff edit call rather than as separate requests 2025-09-29 18:17:14 -07:00
Saoud Rizwan ab88599e05 Add ContextWindowSwitcher component to easily switch between 200k and 1m context models 2025-09-29 16:03:23 -07:00
celestial-vault c2dc0e531c make task constructor typed object (#6558) 2025-09-29 15:45:17 -07:00
Juan Pablo Flores 246b0fa999 Add documentation for changes introduced in 3.30 (#6512)
* docs: update what-is-cline to use generic IDE references

Updated documentation to replace VS Code-specific references with generic "IDE" terms, making it applicable to modern IDEs beyond VS Code for broader compatibility.

* docs: expand Cline installation guide with comprehensive setup instructions

- Add prerequisites section with account creation and editor compatibility
- Include detailed installation steps for VS Code/Cursor and JetBrains IDEs
- Add troubleshooting sections for common installation issues
- Expand editor support information and setup guidance
- Improve documentation structure with tabs and accordions for better UX

* docs: remove font weight and reorder getting started pages

- Remove font weight property from fonts configuration
- Reorder getting started pages to place installation before model selection guide

* fixes title font-weight to original values

* docs: improve JetBrains plugin installation link text

Replace generic URL text with descriptive "JetBrains Marketplace" link text for better user experience and accessibility in the Cline installation guide.

* docs: add voice mode feature documentation and cross-references

Add comprehensive documentation for Voice Mode feature including setup instructions, use cases, and technical requirements. Also add cross-reference tip in plan-and-act.mdx to promote voice mode usage during planning discussions.

* docs: rename voice-mode to dictation for clarity

Rename voice-mode.mdx to dictation.mdx and update all references throughout the documentation to use "Dictation" instead of "Voice Mode" for more accurate terminology and better user understanding.

* feat(docs): add YOLO mode documentation

Add comprehensive documentation for YOLO mode feature, covering auto-approval functionality, safety warnings, use cases, and best practices for autonomous operation.

* docs: reorganize navigation structure and add redirect for JetBrains install page

- Remove JetBrains installation page from getting-started section
- Reorder Features section with @ Mentions first, followed by alphabetically sorted individual features
- Move Slash Commands group after individual features and add workflows page
- Add yolo-mode feature to the end
- Add redirect from old JetBrains install path to main installation guide

* docs: improve JetBrains logo visibility and simplify dictation instructions

- Remove Frame wrapper around JetBrains logo for cleaner markup
- Add CSS styling to ensure JetBrains logo visibility in dark mode with background, border, and hover effects
- Simplify dictation instructions by removing redundant recording state description
2025-09-29 15:33:48 -07:00
Nick Baumann 6c099fbe12 docs: update documentation for Claude Sonnet 4.5 release (#6556)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-29 15:33:29 -07:00
lcs-bdr 00bf05c26c Fix repeated API error 400 in SAP AI Core provider (#6537)
* only add reasoning_details if available

* add changeset

* simplify patch
2025-09-29 15:28:24 -07:00
Walter Korman da99e2bf4b fix: update vercel provider cost note and sign-up url (#6551) 2025-09-29 15:27:31 -07:00
nihar-oracle 963e2c00eb fix: Fixing refresh logic (#6542)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-29 15:26:37 -07:00
Jose Castelli 9355d61bc1 updating .github codeowners (#6539) 2025-09-29 15:26:01 -07:00
Saoud Rizwan a9e17fee57 Fix thinking slider starting at min rather than 0 2025-09-29 15:22:51 -07:00
Saoud Rizwan 3e8548a341 Improve thinking budget slider UI to take up less space 2025-09-29 14:58:09 -07:00
Saoud Rizwan 76b86ff0c0 v3.32.4 Release Notes 2025-09-29 14:15:02 -07:00
Saoud Rizwan 684438b44c Add Sonnet 4.5 to GCP Vertex 2025-09-29 14:15:02 -07:00
AJ Juaire 3c84388fb2 feat: Add Amazon Bedrock us-west-1 support. (#6550)
docs: https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html
2025-09-29 14:01:33 -07:00
Saoud Rizwan b0f86201d2 Add prompt caching support for OpenRouter's anthropic/claude-4.5-sonnet model 2025-09-29 13:56:35 -07:00
Jose Castelli d1fc59758e Reduce Test Workflow Time by 45% and Enable Qlty Coverage on Main (#6374)
* improving test workflow

* testing pipeline improvement

* testing new run

* adding missing protos

* adding previous cache + restoring dev dep version

* restoring webview package lock

* scripts update

* fixing old flaky test

* fixing old flaky test

* changeset update

* adding test-platform-integration again

* adding quality check for integration platform
2025-09-29 13:50:56 -07:00
Saoud Rizwan 87c9f58902 Add 1m context window support to Sonnet 4.5 2025-09-29 13:49:31 -07:00
Saoud Rizwan cda3eb8236 fix: task timeline showing text and reasoning items 2025-09-29 12:31:41 -07:00
John Costa 3c21d2be1f fix: returning undefined when URL is not valid (#6377)
* fix: returning undefined when URL is not valid

This can happen when the user is typing, and once it was set there was
no way of changing it.

* adding change set
2025-09-29 12:19:23 -07:00
Saoud Rizwan f3adf68775 v3.32.3 Release Notes 2025-09-29 11:50:11 -07:00
Saoud Rizwan 6bd3181133 Add Sonnet 4.5 to Bedrock; add model banner announcing Sonnet 4.5; modify bug report 2025-09-29 11:38:02 -07:00
github-actions[bot] dd3a234a69 v3.32.2 Release Notes (#6511)
* 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-09-29 10:53:49 -07:00
Saoud Rizwan c496f8a90d Fix OpenRouter model id 2025-09-29 10:47:00 -07:00
Saoud Rizwan 25b1cf91fc Add fixed Sonnet 4.5 support 2025-09-29 10:40:15 -07:00
Saoud Rizwan b54e2043fe Revert "Add Claude Sonnet 4.5 (#6544)"
This reverts commit 98e5ccc547.
2025-09-29 10:26:31 -07:00
Saoud Rizwan 98e5ccc547 Add Claude Sonnet 4.5 (#6544) 2025-09-29 10:10:04 -07:00
Sarah Fortune 813a9589d0 Replace VSCode API with the host bridge. (#6529)
Add a method to the host bridge to open and focus the terminal panel.
2025-09-28 19:12:09 -07:00
Sarah Fortune 64eb66d49a Move getGlobalStorageDir out of the HostProvider into disk.ts (#6530) 2025-09-28 19:11:59 -07:00
Sarah Fortune 8c17d864c8 Replace VSCode API with Host Provider (#6527)
VSCode API doesn't work cross-platform, this should use the host provider instead.
2025-09-28 18:18:55 -07:00
Sarah Fortune 4f931c2d9d Handle quotes and other special chars in the curl request (#6525)
This workflow didn't work if the PR title contained quotes, e.g.
https://github.com/cline/cline/pull/6523 - Don't show VS Code LM provider on non-VSCode platforms
2025-09-28 17:50:46 -07:00
Sarah Fortune 5836db3093 [disk.ts] Replace uses of context.globalStorageUri with HostProvider.get().globalStorageFsPath (#6507)
* Fix ellipsis warning

# Conflicts:
#	src/services/test/TestServer.ts

* [disk.ts] Replace uses of context.globalStorageUri with HostProvider.get().globalStorageFsPath

This is part of removing dependencies on the VSCode API fom the codebase except for in platform specific code in src/hosts/vscode and src/extension.ts.

Remove unused vscode context param.

* Remove constructors that just call super()
2025-09-28 17:39:19 -07:00
Sarah Fortune 18879edf9f Don't include VS Code LM API for non-VSCode platforms (#6523) 2025-09-28 17:38:52 -07:00
celestial-vault 1cc702c8b9 remove getCurrentMode function in favor of state manager (#6418) 2025-09-28 15:34:52 -07:00
Saoud Rizwan c8caa6f9b9 fix: command execution not sending output to webview and incorrectly showing 'Proceed while Running' when finished (#6522) 2025-09-28 15:29:21 -07:00
Saoud Rizwan 01f61b6765 Make first checkpoint async to unblock UI 2025-09-28 12:20:47 -07:00
Saoud Rizwan b8dd6abe61 Add /task deep link handler (#6513)
* Add /task deep link handler

* Add deep link handler for /task
2025-09-28 02:23:09 -07:00
github-actions[bot] fb7f0e36fe v3.32.1 Release Notes (#6488)
* 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-09-28 00:00:26 -07:00
Saoud Rizwan 403a32b69c Disable TaskFeedbackButtons 2025-09-27 23:18:22 -07:00
Saoud Rizwan ee6daed7bb Change task timeline items border radius 2025-09-27 23:13:30 -07:00
Saoud Rizwan 55ffe9e5dd Update task timeline colors 2025-09-27 23:07:16 -07:00
Saoud Rizwan c2ec5fd17d Update Settings design and 'About' section 2025-09-27 22:59:07 -07:00
Saoud Rizwan 5a84cb1145 Use SlidersHorizontal icon for API Configuration tab in Settings 2025-09-27 22:41:09 -07:00
Saoud Rizwan aec2fd5a7b fix: planActSeparateModelsSetting defaulting to true for new users after reload 2025-09-27 22:33:57 -07:00
Tomás Barreiro 5826cb584e fix: cline accounts using stale id token at refresh response (#6509) 2025-09-27 22:16:25 -07:00
Sarah Fortune 76232639c3 [Tasks directory] Replace uses of context.globalStorageUri with HostProvider.get().globalStorageFsPath (#6420)
* Replace uses of context.globalStorageUri with HostProvider.get().globalStorageFsPath for task directory

This is part of removing dependencies on the VSCode API fom the codebase except for in platform specific code in src/hosts/vscode and src/extension.ts.

Remove unused vscode context param.

* Fix test ModelContextTracker.test.ts

* Fix test FileContextTracker.test.ts
2025-09-27 17:47:27 -07:00
celestial-vault c751cff677 merge conflicts 2025-09-27 16:41:31 -07:00
celestial-vault 3173483c0f remove task class enable checkpoints variable and directly use statemanager (#6491) 2025-09-27 16:38:23 -07:00
celestial-vault 67e0d9883c consolidate statemanager calls to use variables 2025-09-27 10:28:05 -07:00
celestial-vault 8964561b9e remove task class enable checkpoints variable and directly use statemanager 2025-09-26 16:37:31 -07:00
142 changed files with 3441 additions and 1973 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
fix: automatically retry on rate limit errors with SAP AI Core provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
feat: preserve reasoning traces for cline/openrouter/anthropic providers to maintain conversation integrity
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Empty Pr to bump changeset
+1 -1
View File
@@ -1,3 +1,3 @@
/docs/
/.github/ @saoudrizwan
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
+2 -2
View File
@@ -5,7 +5,7 @@ body:
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude Sonnet 4. Cline uses complex prompts so less capable models may not work as expected.
**Important:** All bug reports must be reproducible using Claude Sonnet 4.5. Cline uses complex prompts so less capable models may not work as expected.
- type: dropdown
id: plugin-type
attributes:
@@ -49,7 +49,7 @@ body:
attributes:
label: Provider/Model
description: What provider and model were you using when the issue occurred?
placeholder: 'e.g., cline:anthropic/claude-sonnet-4, gemini:gemini-2.5-pro-exp-03-25'
placeholder: 'e.g., cline:anthropic/claude-sonnet-4.5, gemini:gemini-2.5-pro-exp-03-25'
validations:
required: false
- type: textarea
+82 -151
View File
@@ -1,6 +1,9 @@
name: Tests
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
branches:
@@ -14,7 +17,45 @@ permissions:
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
quality-checks:
runs-on: ubuntu-latest
name: Quality Checks
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Run Quality Checks (Parallel)
run: npm run ci:check-all
test:
needs: quality-checks
strategy:
fail-fast: false
matrix:
@@ -33,18 +74,6 @@ jobs:
with:
node-version: 22
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -52,7 +81,6 @@ jobs:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
@@ -68,60 +96,60 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install xvfb on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Set up NPM on Windows
if: runner.os == 'Windows'
run: |
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
- name: Type Check
run: npm run check-types
- name: Lint Check
run: npm run lint
- name: Format Check
run: npm run format
# Build the extension before running tests
# Build the extension and tests (without redundant checks)
- name: Build Tests and Extension
run: npm run pretest
run: npm run ci:build
- name: Unit Tests (with coverage on Linux)
run: |
if [ "${{ runner.os }}" = "Linux" ]; then
npm install --no-save nyc
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
else
npm run test:unit
fi
# Run extension tests with coverage
- name: Extension Integration Tests with Coverage
id: extension_coverage
- name: Unit Tests with coverage - Linux
id: unit_tests_linux
continue-on-error: true
if: runner.os == 'Linux'
run: |
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
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
- name: Unit Tests - Non-Linux
id: unit_tests_non_linux
continue-on-error: true
if: runner.os != 'Linux'
run: |
npm run test:unit
- name: Extension Integration Tests - Linux
id: integration_tests_linux
continue-on-error: true
if: runner.os == 'Linux'
run: xvfb-run -a npm run test:coverage
- name: Extension Integration Tests - Non-Linux
id: integration_tests_non_linux
continue-on-error: true
if: runner.os != 'Linux'
run: npm run test:integration
# Run webview tests with coverage
- name: Webview Tests with Coverage
id: webview_coverage
id: webview_tests
continue-on-error: true
run: |
cd webview-ui
# Ensure coverage dependency is installed
npm install --no-save @vitest/coverage-v8
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
npm run test:coverage
- name: Check Test Results
if: always()
run: |
failed=""
[[ "${{ steps.unit_tests_linux.outcome }}" == "failure" && "${{ runner.os }}" == "Linux" ]] && failed="$failed unit_tests_linux"
[[ "${{ steps.unit_tests_non_linux.outcome }}" == "failure" && "${{ runner.os }}" != "Linux" ]] && failed="$failed unit_tests_non_linux"
[[ "${{ steps.integration_tests_linux.outcome }}" == "failure" && "${{ runner.os }}" == "Linux" ]] && failed="$failed integration_tests_linux"
[[ "${{ steps.integration_tests_non_linux.outcome }}" == "failure" && "${{ runner.os }}" != "Linux" ]] && failed="$failed integration_tests_non_linux"
[[ "${{ steps.webview_tests.outcome }}" == "failure" ]] && failed="$failed webview_tests"
[[ -n "$failed" ]] && { echo "❌ The following test suites failed:$failed"; exit 1; }
echo "✅ All tests passed"
# Save coverage reports as artifacts (workflow-scoped)
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
@@ -129,27 +157,11 @@ jobs:
with:
name: pr-coverage-reports
path: |
extension_coverage.txt
webview-ui/webview_coverage.txt
coverage-unit/lcov.info
webview-ui/coverage/lcov.info
# Set the check as failed if any of the tests failed
- name: Check for test failures
run: |
# 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
exit 1
fi
test-platform-integration:
needs: quality-checks
runs-on: ubuntu-latest
steps:
- name: Checkout code
@@ -159,7 +171,7 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -212,85 +224,6 @@ jobs:
name: test-platform-integration-core-coverage
path: coverage/**/lcov.info
coverage:
needs: test
runs-on: ubuntu-latest
# Only run on PRs to main branch
if: github.event_name == 'pull_request' && github.base_ref == 'main'
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for accurate comparison
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
# Build the extension before running tests
- name: Build Extension
run: npm run compile
# Download coverage artifacts from test job
- name: Download Coverage Reports
uses: actions/download-artifact@v4
with:
name: pr-coverage-reports
path: . # Download to root directory to match expected paths
# Process coverage workflow
- name: Process coverage workflow
id: coverage
run: |
# Extract PR number from GITHUB_REF
PR_NUMBER=$(echo "$GITHUB_REF" | sed -e 's/refs\/pull\///' -e 's/\/merge//')
# Run the coverage workflow from root directory
PYTHONPATH=.github/scripts python -m coverage_check process-workflow \
--base-branch ${{ github.base_ref }} \
--pr-number $PR_NUMBER \
--repo $GITHUB_REPOSITORY \
--token ${{ secrets.GITHUB_TOKEN }} \
--verbose
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
qlty:
needs: [test, test-platform-integration]
runs-on: ubuntu-latest
@@ -298,8 +231,6 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for accurate comparison
- name: Download unit tests coverage reports
uses: actions/download-artifact@v4
+13 -11
View File
@@ -30,17 +30,19 @@ jobs:
-H "User-Agent: cline-pr-trigger" \
-H "Content-Type: application/json" \
https://api.github.com/repos/cline/intellij-plugin/dispatches \
-d '{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"action": "${{ github.event.action }}",
"sha": "${{ github.event.pull_request.head.sha }}",
"pr_title": "${{ github.event.pull_request.title }}",
"pr_url": "${{ github.event.pull_request.html_url }}"
}
}'
-d @- <<EOF
{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"action": "${{ github.event.action }}",
"sha": "${{ github.event.pull_request.head.sha }}",
"pr_title": ${{ toJSON(github.event.pull_request.title) }},
"pr_url": "${{ github.event.pull_request.html_url }}"
}
}
EOF
- name: Log trigger details
run: |
+32 -1
View File
@@ -1,9 +1,40 @@
# Changelog
## [3.32.5]
- Improve thinking budget slider UI to take up less space
- Fix Vercel provider cost note and sign-up url
- Fix repeated API error 400 in SAP AI Core provider
- Add us-west-1 to Amazon Bedrock regions
- Fix OCA provider refresh logic
## [3.32.4]
- Add 1m context window support to Claude Sonnet 4.5
- Add Claude Sonnet 4.5 to GCP Vertex
- Add prompt caching support for OpenRouter accidental `anthropic/claude-4.5-sonnet` model ID
## [3.32.3]
- Add Claude Sonnet 4.5 to Bedrock provider
- Add Alert banner for new Claude Sonnet 4.5 model
## [3.32.2]
- Add Claude Sonnet 4.5 to Cline/OpenRouter/Anthropic providers
- Add /task deep link handler
## [3.32.1]
- Preserve reasoning traces for Cline/OpenRouter/Anthropic providers to maintain conversation integrity
- Add automatically retry on rate limit errors with SAP AI Core provider
- Fix Cline accounts using stale id token at refresh response
- Minor UI improvements to Settings and Task Header
## [3.32.0]
- Added the new code-supernova-1-million stealth model, available for free and delivering a 1 million token context window
- Changes to inform Cline about commands that are available on your system
- Changes to inform Cline about commands that are available on your system
## [3.31.1]
-1
View File
@@ -74,7 +74,6 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
4. Testing
- Run `npm run test` to run tests locally.
- Before submitting PR, run `npm run format:fix` to format your code
- Run `npm run test:ci` to run tests locally
### Extension
+32 -26
View File
@@ -25,15 +25,15 @@
},
"styling": {
"eyebrows": "breadcrumbs",
"codeblocks": "system"
"codeblocks": "system",
"css": "styles.css"
},
"appearance": {
"default": "system",
"strict": false
},
"fonts": {
"family": "Roboto",
"weight": 400
"family": "Roboto"
},
"navbar": {
"links": [
@@ -58,9 +58,8 @@
"group": "Getting Started",
"pages": [
"getting-started/what-is-cline",
"getting-started/model-selection-guide",
"getting-started/installing-cline",
"getting-started/installing-cline-jetbrains",
"getting-started/model-selection-guide",
"getting-started/task-management",
"getting-started/understanding-context-management",
{
@@ -82,16 +81,6 @@
{
"group": "Features",
"pages": [
"features/auto-approve",
"features/checkpoints",
"features/cline-rules",
"features/drag-and-drop",
"features/plan-and-act",
"features/slash-commands/workflows",
"features/focus-chain",
"features/auto-compact",
"features/editing-messages",
"features/dictation",
{
"group": "@ Mentions",
"pages": [
@@ -103,16 +92,10 @@
"features/at-mentions/url-mentions"
]
},
{
"group": "Slash Commands",
"pages": [
"features/slash-commands/new-task",
"features/slash-commands/new-rule",
"features/slash-commands/smol",
"features/slash-commands/report-bug",
"features/slash-commands/deep-planning"
]
},
"features/auto-approve",
"features/auto-compact",
"features/checkpoints",
"features/cline-rules",
{
"group": "Commands & Shortcuts",
"pages": [
@@ -129,7 +112,24 @@
"features/customization/opening-cline-in-sidebar",
"features/customization/disable-terminal-pagers"
]
}
},
"features/dictation",
"features/drag-and-drop",
"features/editing-messages",
"features/focus-chain",
"features/plan-and-act",
{
"group": "Slash Commands",
"pages": [
"features/slash-commands/new-task",
"features/slash-commands/new-rule",
"features/slash-commands/smol",
"features/slash-commands/report-bug",
"features/slash-commands/deep-planning"
]
},
"features/slash-commands/workflows",
"features/yolo-mode"
]
},
{
@@ -232,6 +232,12 @@
"url": "getting-started/what-is-cline"
}
],
"redirects": [
{
"source": "/getting-started/installing-cline-jetbrains",
"destination": "/getting-started/installing-cline"
}
],
"search": {
"prompt": "Search Cline documentation..."
},
@@ -21,7 +21,6 @@ While Cline has only a few default keyboard shortcuts, you can assign your own s
| Command ID | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`cline.openInNewTab`](/features/commands-and-shortcuts/overview) | Opens Cline in a new editor tab |
| [`cline.addToChat`](/features/commands-and-shortcuts/code-commands) | Adds selected code to Cline chat |
| [`cline.addTerminalOutputToChat`](/features/commands-and-shortcuts/terminal-integration) | Adds terminal output to Cline |
| `cline.focusChatInput` | Focuses the Cline chat input field |
+121 -32
View File
@@ -1,60 +1,149 @@
---
title: Dictation
description:
title: "Dictation"
description: "Communicate with Cline using your voice for faster, more natural AI collaboration"
---
Cline lets you transcribe speech to text in an easy, built-in service
Dictation transforms how you work with AI. Instead of typing out complex thoughts, you speak naturally and share your complete intent. This isn't just about speed - though voice is faster - it's about unlocking the kind of fluid collaboration that typing can't match.
## Get Started
## Why Voice Changes Everything
1. **Enable Dictation** in Feature Settings.
2. **Click the microphone** in the chat input area.
3. **Speak** - the button turns red while recording.
4. **Click Stop Recording** when done.
5. **Wait for transcription** - "[Transcribing...]" will appear and then the finished transcription will appear.
When you type, you edit yourself. You simplify complex ideas, skip context, and lose nuance. When you speak, you share everything on your mind - the full problem, the constraints, the edge cases you're worried about.
## Settings
Use Dictation constantly in [Plan mode](/features/plan-and-act) for rapid back-and-forth discussions. Instead of typing careful, structured prompts, think about a problem. Cline asks clarifying questions, respond immediately, and iterate until having a solid plan.
Enable or disable dictation in Feature Settings by toggling "Enable Dictation." You can also change the transcription language to one of the supported languages.
The friction of typing was holding back real collaboration. Voice removes that friction.
## Requirements
## Getting Started
Cline uses FFmpeg to capture your voice across all platforms:
**Enable Dictation:**
1. Go to Settings → Features → Dictation
2. Toggle "Enable Dictation" on
3. Sign into your Cline account when prompted
4. Install FFmpeg if you haven't already (Cline will guide you)
- **macOS**: FFmpeg (via Homebrew: `brew install ffmpeg`)
- **Linux**: FFmpeg (via apt: `sudo apt-get install ffmpeg`)
- **Windows**: FFmpeg (via winget: `winget install Gyan.FFmpeg`)
Once enabled, you'll see a microphone button in the chat input area.
**Using Dictation:**
- Click the microphone button to start recording
- Speak naturally
- Click again to stop recording
- Wait for transcription to appear in the chat
<Tip>
Dictation works with any AI model you've configured. The transcription happens through Cline's service, but your conversation continues with whatever model you're using.
</Tip>
## System Requirements
Dictation uses FFmpeg to capture your voice across all platforms:
- **macOS**: FFmpeg (via Homebrew: `brew install ffmpeg`)
- **Linux**: FFmpeg (via apt: `sudo apt-get install ffmpeg`)
- **Windows**: FFmpeg (via winget: `winget install Gyan.FFmpeg`)
If you don't have FFmpeg installed, Cline will automatically detect this and prompt you to install it with a single click.
## Technical Details
## Where Dictation Shines
### Independent from Chat Provider
### Plan Mode Conversations
The voice transcription feature works completely independently from whatever chat provider you're using. You can use Claude, GPT-4, or any other model for your conversations, and voice transcription will always use Cline's own transcription service. As long as you have a valid Cline account with enough credits, dictation will work regardless of your chat model choice.
Dictation is perfect for [Plan mode](/features/plan-and-act) discussions. Instead of carefully crafting prompts, you can:
### Audio Format
- Dictate your entire problem context in one go
- Respond to Cline's questions immediately
- Iterate on ideas without typing friction
- Think out loud while Cline listens
Voice recordings are captured in WebM format using the Opus codec for optimal compression. The system records in mono (single channel) at a 16kHz sample rate, which is specifically optimized for voice recognition. The bitrate is set to 32kbps to keep file sizes efficient while maintaining good audio quality.
Start a planning session by speaking for 2-3 minutes straight, explaining the full context of what you're trying to build, the constraints you're working with, and the specific challenges you're facing.
### Privacy & Security
### Complex Problem Explanation
Your audio is recorded locally on your machine and only the audio file itself is sent to Cline's transcription service for processing. No audio is stored anywhere after transcription is complete, and all temporary files are automatically cleaned up to protect your privacy.
Some problems are hard to type out. When you're dealing with:
- Multi-step workflows with edge cases
- Integration challenges across multiple systems
- Performance issues with specific reproduction steps
- UI/UX problems that need detailed context
Speaking lets you explain the full situation naturally, including all the "oh, and also..." details that matter.
### Code Review and Debugging
When reviewing code or explaining bugs, voice lets you walk through your thought process:
- "This function looks fine, but I'm worried about what happens when..."
- "The issue might be in this section, or possibly this other area..."
- "I tried X and Y, but neither worked because..."
You can share your complete debugging journey instead of just the final question.
## Technical Requirements
**System Requirements:**
- FFmpeg installed on your system
- Active internet connection
- Cline account with transcription credits
**Audio Quality:**
- Records in WebM format with Opus codec
- Mono audio at 16kHz sample rate
- Optimized for voice recognition
**Privacy:**
- Audio recorded locally on your machine
- Only audio files sent for transcription
- No audio stored after transcription
- Temporary files automatically cleaned up
## Cost and Credits
Voice transcription costs $0.006 per minute through your Cline account. For most users, this works out to pennies per session.
A typical 5-minute planning conversation costs about 3 cents. Even heavy voice users rarely spend more than a few dollars per month.
<Note>
Pricing is experimental and may change as we refine the service.
</Note>
## Best Practices
**Speak Naturally**
Don't try to speak like you type. Use your normal conversational tone and don't worry about perfect grammar.
**Give Context First**
Start with the big picture, then drill down into specifics. "I'm building a React app that needs to handle real-time data, and I'm running into performance issues with the WebSocket connection..."
**Use Voice for Exploration**
Dictation is perfect for exploratory conversations where you're not sure exactly what you need. Start talking through the problem and let the conversation evolve.
**Combine with Text**
You don't have to use voice for everything. Use voice for complex explanations and context, then switch to text for quick follow-ups or code snippets.
## Troubleshooting
`Failed to start recording` - Audio recording tools aren't installed. Cline will prompt you to install FFmpeg - just follow the chat instructions.
**Microphone Not Working**
- Check your IDE permissions for microphone access
- Ensure FFmpeg is properly installed
- Try refreshing VSCode/your editor
`Invalid audio format or request data` - Usually an audio recording issue. Make sure FFmpeg is properly installed and working.
**Poor Transcription Quality**
- Speak clearly and at normal volume
- Reduce background noise if possible
- Check your microphone settings
`Authentication failed` - You need to reauthenticate your Cline account. Sign out and back in, then check your internet connection.
**Connection Issues**
- Verify internet connection
- Check if firewall is blocking Cline's servers
- Try signing out and back into your Cline account
`Insufficient credits for transcription service` - Your Cline account doesn't have enough credits. Check your balance and purchase more if needed.
**Authentication Issues**
- Sign out and back into your Cline account if you see authentication errors
- Check that your account has sufficient transcription credits
- Verify your internet connection is stable
`Cannot connect to transcription service` - Connection issue. Check your internet connection and firewall settings aren't blocking Cline's servers.
**Audio Recording Issues**
- Ensure FFmpeg is properly installed and accessible
- Check that your browser/IDE has microphone permissions
- Try restarting your editor if audio capture fails
## API Usage
## The Future of AI Collaboration
Voice transcription uses Cline's transcription service, which requires credits from your Cline account. Currently, voice transcription is billed at $0.006 per minute of audio.
**Note:** We are still experimenting with this feature and pricing may change in the future.
When you can speak your thoughts as fast as you think them, you stop self-editing. You share the full context, the edge cases, the "what if" scenarios that matter. This leads to better solutions and fewer back-and-forth clarifications.
+4
View File
@@ -24,6 +24,10 @@ Plan mode is where you and Cline figure out what you're trying to build and how
- Focuses on understanding requirements and creating a strategy
- Helps identify potential issues before you write a single line of code
<Tip>
Try [Dictation](/features/dictation) in Plan mode - instead of typing out complex requirements, you can speak naturally and share your complete thought process. It's perfect for rapid back-and-forth planning discussions.
</Tip>
#### Act Mode: Build It
Once you've got a plan, you switch to Act mode. Now Cline:
+83
View File
@@ -0,0 +1,83 @@
---
title: "YOLO Mode"
sidebarTitle: "YOLO Mode"
---
YOLO mode is exactly what it sounds like - Cline auto-approves everything. Check the box in feature settings and he'll execute file changes, terminal commands, even transitions from Plan to Act mode without asking.
Think of it as [Auto Approve](/features/auto-approve) on steroids - instead of granular permissions, YOLO mode gives Cline complete autonomy.
<Note>
**Warning: This is dangerous.** YOLO mode disables all safety checks. Cline will execute whatever he decides without asking permission.
</Note>
## What Gets Auto-Approved
When YOLO mode is enabled, Cline automatically approves:
- **All file operations** - reading, writing, and modifying files anywhere on your system
- **All terminal commands** - including potentially destructive operations
- **Browser actions** - web scraping, form submissions, navigation
- **MCP server tools** - external integrations and API calls
- **Mode transitions** - automatic switching from Plan to Act mode
Essentially, every safety guardrail is removed. Cline operates with complete autonomy.
## How to Enable YOLO Mode
Navigate to Cline Settings → Features and check the "YOLO Mode" box. That's it - no confirmation dialogs, no additional warnings. Once enabled, Cline will start auto-approving all actions immediately.
To disable it, simply uncheck the box. Any pending actions will still require your approval once YOLO mode is turned off.
## When You Might Use This
YOLO mode was built primarily for our upcoming scriptable CLI where fully autonomous execution makes sense. In the GUI, you might consider it for:
**Rapid prototyping** where you want zero friction and don't care about potential mistakes. Perfect for throwaway experiments or exploring new ideas quickly.
**Trusted, repetitive tasks** where you've already validated Cline's approach and want to eliminate approval overhead. Think routine refactoring or well-established patterns.
**Demonstration purposes** where you want to show Cline's capabilities without constant interruptions.
## What Could Go Wrong
Since YOLO mode removes all safety checks, Cline could:
- Delete important files without warning
- Execute commands that modify system settings
- Make network requests to external services
- Overwrite configuration files
- Install or uninstall software packages
- Commit and push changes to version control
The risk level depends entirely on what you ask Cline to do. Simple tasks remain relatively safe, but complex requests can have unpredictable consequences.
## Best Practices
If you decide to use YOLO mode:
**Start with isolated environments.** Use it in throwaway projects or sandboxed environments first. Never enable it on production codebases until you understand the risks.
**Be specific with requests.** Vague instructions combined with unlimited permissions can lead to unexpected results. The clearer your requirements, the more predictable Cline's actions.
**Monitor the output.** Even though Cline doesn't ask for permission, he still shows you what he's doing. Watch the terminal output and file changes as they happen.
**Keep version control handy.** Make sure you can easily revert changes if something goes wrong. Git becomes your safety net when YOLO mode is your workflow.
## Inspiration: What Becomes Possible
With YOLO mode enabled, you can:
**Build entire applications** from a single prompt. Describe what you want and let Cline handle everything - file creation, dependency installation, configuration setup, even deployment scripts.
**Automate complex workflows** that normally require dozens of approval clicks. Data processing pipelines, build system setup, or multi-step refactoring operations become seamless.
**Rapid iteration cycles** where you can quickly test ideas without approval friction. Perfect for exploring different approaches or experimenting with new technologies.
**Live demonstrations** where you can show Cline's full capabilities without stopping to approve every action. Great for presentations or teaching scenarios.
The key is understanding that YOLO mode transforms Cline from an interactive assistant into an autonomous agent. Use that power wisely.
---
Questions or feedback? Reach us in our [Discord](https://discord.gg/cline) or [r/cline](https://reddit.com/r/cline).
@@ -1,129 +0,0 @@
---
title: "Installing Cline for JetBrains"
description: "Install Cline in your favorite JetBrains IDE with the same powerful AI assistance you know from VSCode."
---
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-logo.svg"
alt="JetBrains logo"
style={{ width: "200px", height: "auto", margin: "0 auto 20px auto", display: "block" }}
/>
</Frame>
Cline for JetBrains works almost identically to Cline in VSCode. All the core features work properly: diff editing, using tools, logging in with different providers, MCP servers, Cline rules and workflows, and more.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-demo-hifi.gif"
alt="Cline running in JetBrains IDE showing AI assistance"
/>
</Frame>
Cline is now available on the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/28247-cline). Works in IntelliJ IDEA, PyCharm, WebStorm, DataSpell, PhpStorm, and all other JetBrains IDEs.
## Installation
**Method 1: Direct from your IDE**
1. Open your JetBrains IDE
2. Press `Ctrl+Alt+S` (Windows/Linux) or `Cmd+,` (macOS)
3. Go to Plugins → Marketplace tab
4. Search "Cline" and click Install
5. Restart your IDE
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-marketplace-search.png"
alt="JetBrains marketplace showing Cline plugin search results"
/>
</Frame>
**Method 2: Browser install**
Visit [plugins.jetbrains.com/plugin/28247-cline](https://plugins.jetbrains.com/plugin/28247-cline) and click the "Install to IDE" button. Your IDE will open and prompt you to install.
<details>
<summary>Method 3: Manual installation</summary>
Download the plugin from the [marketplace page](https://plugins.jetbrains.com/plugin/28247-cline), then:
1. Go to Settings → Plugins
2. Click the gear icon → Install Plugin from Disk
3. Select the downloaded `.zip` file
4. Restart your IDE
</details>
## Getting Started with Cline
After installation, you'll find Cline in your IDE. Look for the Cline tool window (usually on the right side) or go to **View** → **Tool Windows** → **Cline**.
Sign in is optional - you can also bring your own API key. If you want to sign in, click **Sign In** in the Cline panel. You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account. No credit card needed to get started with free credits.
Try this first prompt: "Hey Cline! Can you help me create a simple Hello World program in this project?"
## Key Differences from VSCode
The terminal integration works differently in JetBrains. Unlike VSCode where terminal output streams directly to the chat, JetBrains shows command output in a collapsible section. Commands still execute successfully - you just need to expand the **Command Output** section to see results.
## What Works
Everything else works exactly like VSCode. Cline can read, write, and edit files with the same precision. All his tools work identically - file operations, web browsing, you name it.
You get full support for:
- API providers (Anthropic, OpenAI, local models)
- MCP servers and custom tools
- Cline rules and workflows
- @ mentions for files, folders, and problems
- Drag & drop for files and images
## Tips for JetBrains Users
Cline automatically understands your project structure, just like in VSCode. He works with any language your JetBrains IDE supports - Java, Python, JavaScript, Go, whatever you're building.
I find it helpful to share error messages and stack traces directly in the chat when debugging. You can also ask him to review your code changes before committing.
## Troubleshooting
### Plugin Installation Issues
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your IDE version is compatible (2023.1 or later recommended)
If installation fails:
- Restart your IDE and try again
- Check your internet connection
- Try installing from disk as an alternative
### Plugin Not Appearing
If you don't see the Cline tool window after installation:
- Restart your IDE completely (File → Exit and reopen)
- Check **View** → **Tool Windows** → **Cline**
- Verify the plugin is enabled in **Settings** → **Plugins** → **Installed** tab
- Look for the Cline icon in your IDE's tool window bar (usually on the right side)
### Common Issues
**Plugin appears to be installed but doesn't work:**
- Ensure you've restarted your IDE after installation
- Check if there are any error messages in the IDE's event log
- Try disabling and re-enabling the plugin in Settings
**Performance or compatibility issues:**
- Make sure you're using a supported JetBrains IDE version
- Check for IDE updates that might improve compatibility
- Consider allocating more memory to your IDE if needed
Having other issues? Join our [Discord community](https://discord.gg/cline) for help from the team and other users.
## Next Steps
Now that you have Cline installed, you might want to:
- Learn about [model selection](/getting-started/model-selection-guide) to choose the best AI provider
- Explore [@ mentions](/features/at-mentions/overview) to reference files and context efficiently
- Set up [Cline rules](/features/cline-rules) for your specific workflow
- Try [MCP servers](/mcp/mcp-overview) to extend Cline's capabilities
+226 -53
View File
@@ -1,81 +1,254 @@
---
title: "Installing Cline"
description: "Cline brings AI-powered coding assistance to your editor. Available for VS Code and JetBrains IDEs."
description: "Get Cline set up in your editor and start building projects with AI assistance."
---
## Prerequisites
Before installing Cline, make sure you have the following:
### Create a Cline Account
Create a Cline account for the best experience. Creating a Cline account is completely free and you can [sign up here](https://app.cline.bot/signup). A Cline account provides:
- Access to multiple AI models including stealth models
- Seamless setup without needing to manage API keys
- At times, we partner with model providers to offer inferencing at no cost through your Cline account
### Compatible Editor
Cline works with the following IDEs:
- **VS Code** - Microsoft's popular code editor
- **Cursor** - AI-powered code editor based on VS Code
- **JetBrains IDEs** - IntelliJ IDEA, PyCharm, WebStorm, DataSpell, PhpStorm, and other JetBrains products
- **VSCodium** - Open-source version of VS Code
- **Windsurf** - VS Code-compatible editor
Make sure you have one of these editors installed before proceeding with the Cline installation.
## Choose Your Editor
Cline works across multiple development environments:
Cline works across multiple IDEs. Select your preferred editor below for installation instructions:
- **VS Code/Cursor:** Install from VS Code Marketplace (most popular)
- **JetBrains IDEs:** Install from JetBrains Marketplace - works in IntelliJ IDEA, PyCharm, WebStorm, and more
- **VSCodium/Windsurf:** Install from Open VSX Registry
<Tabs>
<Tab title="VS Code/Cursor" icon="code">
### Installation Steps
## VS Code Installation
1. **Open VS Code** and navigate to the Extensions view (`Ctrl/Cmd + Shift + X`)
2. **Search for "Cline"** in the Extensions marketplace
3. **Click Install** on the Cline extension
### VS Code Marketplace: Step-by-Step Setup
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
Follow these steps to get Cline up and running:
4. **Access Cline** after installation:
- Click the Cline icon in the Activity Bar, or
- Use Command Palette (`Ctrl/Cmd + Shift + P`) → "Cline: Open In New Tab"
1. **Open VS Code:** Launch the VS Code application.
> **Note:** If VS Code shows "Running extensions might..." dialog, click "Allow". If you don't see the Cline icon, restart VS Code.
> **Note:** If VS Code shows "Running extensions might...", click "Allow".
<Accordion title="Troubleshooting">
2. **Open Your Cline Folder:** In VS Code, open the Cline folder you created in Documents.
3. **Navigate to Extensions:** Click on the Extensions icon in the Activity Bar on the side of VS Code (`Ctrl + Shift + X` or `Cmd + Shift + X`).
4. **Search for 'Cline':** In the Extensions search bar, type `Cline`.
**Plugin Installation Issues**
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your VS Code version is compatible
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
2. **Open Cline:**
- Click the Cline icon in the Activity Bar.
- Or, use the command palette (`Ctrl/Cmd + Shift + P`) and type "Cline: Open In New Tab" for a better view.
3. **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
If installation fails:
- Restart your VS Code and try again
- Check your internet connection
- Try installing from VSIX file as an alternative
> **Pro Tip:** You should see the Cline chat window appear in your VS Code editor!
**Plugin Not Appearing**
### Open VSX Registry
If you don't see the Cline tool window after installation:
- Restart VS Code completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
For VS Code-compatible editors without Marketplace access (like VSCodium and Windsurf):
**Common Issues**
1. Open your editor.
2. Access the Extensions view.
3. Search for "Cline".
4. Select "Cline" by saoudrizwan and click **Install**.
5. Reload if prompted.
Plugin appears to be installed but doesn't work:
- Ensure you've restarted VS Code after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
## JetBrains Installation
Performance or compatibility issues:
- Make sure you're using a supported VS Code version
- Check for VS Code updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
For IntelliJ IDEA, PyCharm, WebStorm, DataSpell, and other JetBrains IDEs:
Need help? Join our [Discord community](https://discord.gg/cline).
1. Open your JetBrains IDE
2. Press `Ctrl+Alt+S` (Windows/Linux) or `Cmd+,` (macOS) to open Settings
3. Go to Plugins → Marketplace tab
4. Search "Cline" and click Install
5. Restart your IDE
</Accordion>
</Tab>
<Tab title="JetBrains IDEs" icon="brain">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-logo.svg"
alt="JetBrains logo"
style={{ width: "200px", height: "auto", margin: "0 auto 20px auto", display: "block" }}
/>
**Need more help?** See our [complete JetBrains installation guide](/getting-started/installing-cline-jetbrains) for screenshots and troubleshooting.
Cline for JetBrains works almost identically to Cline in VSCode. All the core features work properly: diff editing, using tools, logging in with different providers, MCP servers, Cline rules and workflows, and more.
### Creating Your Cline Account
Now that you have Cline installed, let's get you set up with your account:
### Installation Steps
**Method 1: From IDE (Recommended)**
1. Open your JetBrains IDE
2. Go to **Settings** (`Ctrl+Alt+S` on Windows/Linux, `Cmd+,` on macOS)
3. Navigate to **Plugins** → **Marketplace**
4. Search for "Cline" and click **Install**
5. Restart your IDE
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-marketplace-search.png"
alt="JetBrains marketplace showing Cline plugin search results"
/>
</Frame>
**Method 2: Browser Install**
Visit the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/28247-cline) and click **Install to IDE**.
<Accordion title="Method 3: Manual Installation">
1. Download the plugin from the [marketplace page](https://plugins.jetbrains.com/plugin/28247-cline)
2. Go to **Settings** → **Plugins**
3. Click the gear icon → **Install Plugin from Disk**
4. Select the downloaded `.zip` file
5. Restart your IDE
</Accordion>
### Using the Plugin
After installation, youll find Cline in your IDE. Look for the Cline tool window (usually on the right side) or go to View → Tool Windows → Cline.
### Key Features
Cline for JetBrains includes all core features:
- Diff editing and file modifications
- Multiple API providers (Anthropic, OpenAI, local models)
- MCP servers and custom tools
- Cline rules and workflows
- @ mentions for files, folders, and problems
- Drag & drop support
> **Note:** Terminal output appears in collapsible sections rather than streaming directly to chat.
### Key Differences from VSCode
The terminal integration works differently in JetBrains. Unlike VSCode where terminal output streams directly to the chat, JetBrains shows command output in a collapsible section. Commands still execute successfully - you just need to expand the Command Output section to see results.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your IDE version is compatible (2023.1 or later recommended)
If installation fails:
- Restart your IDE and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your IDE completely (File → Exit and reopen)
- Check **View** → **Tool Windows** → **Cline**
- Verify the plugin is enabled in **Settings** → **Plugins** → **Installed** tab
- Look for the Cline icon in your IDE's tool window bar (usually on the right side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your IDE after installation
- Check if there are any error messages in the IDE's event log
- Try disabling and re-enabling the plugin in Settings
Performance or compatibility issues:
- Make sure you're using a supported JetBrains IDE version
- Check for IDE updates that might improve compatibility
- Consider allocating more memory to your IDE if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
<Tab title="VSCodium/Windsurf" icon="terminal">
### Installation Steps
For VS Code-compatible editors using Open VSX Registry:
1. **Open your editor** (VSCodium, Windsurf, etc.)
2. **Navigate to Extensions view** (`Ctrl/Cmd + Shift + X`)
3. **Search for "Cline"** in the marketplace
4. **Select "Cline" by saoudrizwan** and click **Install**
5. **Reload** if prompted
> **Note:** These editors use the Open VSX Registry instead of the VS Code Marketplace.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your editor version is compatible
If installation fails:
- Restart your editor and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your editor completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your editor after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
Performance or compatibility issues:
- Make sure you're using a supported editor version
- Check for editor updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
</Tabs>
### Sign In to Your Cline Account
Now that you have Cline installed, sign in to access your account:
1. **Open Cline** in your editor (click the Cline icon in the Activity Bar or Tool Windows)
2. **Click "Sign In"** - you'll see this button in the Cline interface
3. **Complete authentication** - you'll be redirected to [app.cline.bot](https://app.cline.bot) to sign in
4. **Return to your editor** - once signed in, you'll be automatically redirected back
1. **Sign In to Cline:**
- Click the **Sign In** button in the Cline extension.
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account.
2. **Start with Free Credits:**
- No credit card needed!
3. **Available AI Models:**
- Anthropic Claude 3.5-Sonnet (recommended for coding)
- DeepSeek Chat (cost-effective alternative)
- Google Gemini 2.0 Flash
- And more — all through your Cline account.
### Your First Interaction with Cline
@@ -96,4 +269,4 @@ Hey Cline! Could you help me create a new project folder called "hello-world" in
### Still Struggling?
Join our Discord community and engage with our team and other Cline users directly.
Join our [Discord community](https://discord.gg/cline) and engage with our team and other Cline users directly.
@@ -9,7 +9,7 @@ New models drop constantly, so this guide focuses on what's working well with Cl
| Model | Context Window | Input Price* | Output Price* | Best For |
|-------|---------------|--------------|---------------|----------|
| **Claude Sonnet 4** | 1M tokens | $3-6 | $15-22.50 | Reliable tool usage, complex codebases |
| **Claude Sonnet 4.5** | 1M tokens | $3-6 | $15-22.50 | Reliable tool usage, complex codebases |
| **Qwen3 Coder** | 256K tokens | $0.20 | $0.80 | Coding tasks, open source flexibility |
| **Gemini 2.5 Pro** | 1M+ tokens | TBD | TBD | Large codebases, document analysis |
| **GPT-5** | 400K tokens | $1.25 | $10 | Latest OpenAI tech, three modes |
@@ -57,9 +57,9 @@ New models drop constantly, so this guide focuses on what's working well with Cl
| If you want... | Use this |
|----------------|----------|
| Something that just works | Claude Sonnet 4 |
| Something that just works | Claude Sonnet 4.5 |
| To save money | DeepSeek V3 or Qwen3 variants |
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4 |
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4.5 |
| Open source | Qwen3 Coder, Z AI GLM 4.5, or Kimi K2 |
| Latest tech | GPT-5 |
| Speed | Qwen3 Coder on Cerebras (fastest available) |
@@ -74,6 +74,6 @@ Cline automatically handles context limits with [auto-compact](/features/auto-co
## The Bottom Line
Start with **Claude Sonnet 4** if you want reliability. Experiment with **open source options** once you're comfortable to find the best fit for your workflow and budget.
Start with **Claude Sonnet 4.5** if you want reliability. Experiment with **open source options** once you're comfortable to find the best fit for your workflow and budget.
The landscape moves fast - these recommendations reflect what's working now, but keep an eye on new releases.
@@ -53,7 +53,7 @@ Think of context like a whiteboard you and Cline share:
- **Context Window** is the size of the whiteboard itself:
- Measured in tokens (1 token ≈ 3/4 of an English word)
- Each model has a fixed size:
- Claude Sonnet 4: 1,000,000 tokens
- Claude Sonnet 4.5: 1,000,000 tokens
- Qwen3 Coder: 256,000 tokens
- Gemini 2.5 Pro: 1,000,000+ tokens
- GPT-5: 400,000 tokens
@@ -77,7 +77,7 @@ Cline provides a visual way to monitor your context window usage through a progr
- ↑ shows input tokens (what you've sent to the LLM)
- ↓ shows output tokens (what the LLM has generated)
- The progress bar visualizes how much of your context window you've used
- The total shows your model's maximum capacity (e.g., 1M for Claude Sonnet 4)
- The total shows your model's maximum capacity (e.g., 1M for Claude Sonnet 4.5)
### When to Watch the Bar
+3 -3
View File
@@ -1,9 +1,9 @@
---
title: "What is Cline?"
description: "An introduction to Cline, your AI-powered development assistant in VS Code."
description: "An introduction to Cline, your AI-powered development assistant for modern IDEs."
---
Cline is an open source AI coding agent that brings frontier AI models directly to your VS Code editor. Unlike autocomplete tools, Cline is a true coding agent that can understand entire codebases, plan complex changes, and execute multi-step tasks.
Cline is an open source AI coding agent that brings frontier AI models directly to your IDE. Unlike autocomplete tools, Cline is a true coding agent that can understand entire codebases, plan complex changes, and execute multi-step tasks.
## Open Source AI Coding, Uncompromised
@@ -69,4 +69,4 @@ Define project-specific instructions that Cline follows including coding standar
## Getting Started
Ready to experience AI coding without limits? [Install Cline](/getting-started/installing-cline) and start with our [Model Selection Guide](/getting-started/model-selection-guide) to choose the right AI model for your needs.
Ready to experience AI coding without limits? [Install Cline](/getting-started/installing-cline) for your preferred IDE and start with our [Model Selection Guide](/getting-started/model-selection-guide) to choose the right AI model for your needs.
+3 -6
View File
@@ -18,11 +18,8 @@ Cline supports the following Anthropic Claude models:
- `claude-opus-4-1-20250805`
- `claude-opus-4-20250514`
- `claude-opus-4-20250514:thinking` (Extended Thinking variant)
- `claude-sonnet-4-20250514` (Recommended)
- `claude-sonnet-4-20250514:thinking` (Extended Thinking variant)
- `anthropic/claude-sonnet-4.5` (Recommended)
- `claude-3-7-sonnet-20250219`
- `claude-3-7-sonnet-20250219:thinking` (Extended Thinking variant)
- `claude-3-5-sonnet-20241022`
- `claude-3-5-haiku-20241022`
- `claude-3-opus-20240229`
@@ -47,8 +44,8 @@ Cline users can leverage this by checking the `Enable Extended Thinking` box bel
**Key Aspects of Extended Thinking:**
- **Supported Models:** This feature is available for select models, including variants of Claude Opus 4, Claude Sonnet 4, and Claude Sonnet 3.7. The specific models listed in the "Supported Models" section above with the `:thinking` suffix are pre-configured in Cline to utilize this.
- **Summarized Thinking (Claude 4):** For Claude 4 models, the API returns a summary of the full thinking process to balance insight with efficiency and prevent misuse. You are billed for the full thinking tokens, not just the summary.
- **Supported Models:** This feature is available for select models, including Claude Opus 4, Claude Sonnet 4.5, and Claude Sonnet 3.7.
- **Summarized Thinking (Claude 4):** For Claude 4 and 4.5 models, the API returns a summary of the full thinking process to balance insight with efficiency and prevent misuse. You are billed for the full thinking tokens, not just the summary.
- **Streaming:** Extended thinking responses, including the `thinking` blocks, can be streamed.
- **Tool Use & Prompt Caching:** Extended thinking interacts with tool use (requiring thinking blocks to be passed back) and prompt caching (with specific behaviors around cache invalidation and context).
+47
View File
@@ -0,0 +1,47 @@
/* Custom styles for Cline documentation */
/* Make h1 titles lighter in font weight */
h1 {
font-weight: 500 !important;
}
/* Also apply to any h1 elements within content areas */
.content h1,
.markdown h1,
article h1,
main h1 {
font-weight: 500 !important;
}
/* JetBrains logo visibility fix for dark mode */
/* Add a subtle background and border to ensure visibility in both light and dark modes */
img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 12px;
transition: all 0.3s ease;
}
/* Dark mode specific styling */
[data-theme="dark"] img[alt="JetBrains logo"],
.dark img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
/* Media query for system dark mode preference */
@media (prefers-color-scheme: dark) {
img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
}
/* Hover effect for better interactivity */
img[alt="JetBrains logo"]:hover {
transform: scale(1.02);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
-17
View File
@@ -148,11 +148,6 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
command: "workbench.view.extension.saoudrizwan.claude-dev-ActivityBar",
when: "viewContainer.workbench.view.extension.saoudrizwan.claude-dev-ActivityBar.enabled",
},
{
key: "alt+shift+c",
command: "cline.openInNewTab",
when: "viewContainer.workbench.view.extension.saoudrizwan.claude-dev-ActivityBar.enabled",
},
]
fs.writeFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2))
console.log(`Created keybindings.json to help with Cline activation`)
@@ -187,11 +182,6 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
setTimeout(() => {
// Try to open Cline in the sidebar
require('vscode').commands.executeCommand('workbench.view.extension.saoudrizwan.claude-dev-ActivityBar');
// Also try to open Cline in a tab as a fallback
setTimeout(() => {
require('vscode').commands.executeCommand('cline.openInNewTab');
}, 5000);
}, 5000);
`
fs.writeFileSync(startupScriptPath, startupScript)
@@ -288,13 +278,6 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
// Wait a moment for the sidebar to initialize
await new Promise(resolve => setTimeout(resolve, 2000));
// Also open Cline in a tab as a fallback
console.log('Opening Cline in a tab...');
await vscode.commands.executeCommand('cline.openInNewTab');
// Wait a moment for the tab to initialize
await new Promise(resolve => setTimeout(resolve, 2000));
// Create the test server if it doesn't exist
console.log('Creating test server...');
+1526 -3
View File
File diff suppressed because it is too large Load Diff
+4 -49
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.32.0",
"version": "3.32.5",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -133,11 +133,6 @@
"title": "History",
"icon": "$(history)"
},
{
"command": "cline.popoutButtonClicked",
"title": "Open in Editor",
"icon": "$(link-external)"
},
{
"command": "cline.accountButtonClicked",
"title": "Account",
@@ -148,11 +143,6 @@
"title": "Settings",
"icon": "$(settings-gear)"
},
{
"command": "cline.openInNewTab",
"title": "Open In New Tab",
"category": "Cline"
},
{
"command": "cline.dev.createTestTasks",
"title": "Create Test Tasks",
@@ -246,11 +236,6 @@
"group": "navigation@3",
"when": "view == claude-dev.SidebarProvider"
},
{
"command": "cline.popoutButtonClicked",
"group": "navigation@4",
"when": "view == claude-dev.SidebarProvider"
},
{
"command": "cline.accountButtonClicked",
"group": "navigation@5",
@@ -262,38 +247,6 @@
"when": "view == claude-dev.SidebarProvider"
}
],
"editor/title": [
{
"command": "cline.plusButtonClicked",
"group": "navigation@1",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.mcpButtonClicked",
"group": "navigation@2",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.historyButtonClicked",
"group": "navigation@3",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.popoutButtonClicked",
"group": "navigation@4",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.accountButtonClicked",
"group": "navigation@5",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.settingsButtonClicked",
"group": "navigation@6",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
}
],
"editor/context": [
{
"command": "cline.addToChat",
@@ -356,9 +309,10 @@
"format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
"format:fix": "biome check --changed --no-errors-on-unmatched --files-ignore-unknown=true --write",
"fix:all": "biome check --no-errors-on-unmatched --files-ignore-unknown=true --write --diagnostic-level=error --unsafe",
"ci:check-all": "npm-run-all -p check-types lint format",
"ci:build": "npm run protos && npm run build:webview && node esbuild.mjs && npm run compile-tests",
"pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint",
"test": "npm-run-all test:unit test:integration",
"test:ci": "node scripts/test-ci.js",
"test:integration": "vscode-test",
"test:unit": "TS_NODE_PROJECT='./tsconfig.unit-test.json' mocha",
"test:coverage": "vscode-test --coverage",
@@ -418,6 +372,7 @@
"lint-staged": "^16.1.0",
"minimatch": "^3.0.3",
"npm-run-all": "^4.1.5",
"nyc": "^17.1.0",
"prebuild-install": "^7.1.3",
"protoc-gen-ts": "^0.8.7",
"proxyquire": "^2.1.3",
+1
View File
@@ -19,6 +19,7 @@ service StateService {
rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty);
rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty);
rpc updateInfoBannerVersion(Int64Request) returns (Empty);
rpc updateModelBannerVersion(Int64Request) returns (Empty);
}
message DictationSettings {
bool feature_enabled = 1;
+6 -18
View File
@@ -5,18 +5,6 @@ import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
// Enum for webview provider types
enum WebviewProviderType {
SIDEBAR = 0;
TAB = 1;
}
// Define a new message type for webview provider info
message WebviewProviderTypeRequest {
Metadata metadata = 1;
WebviewProviderType provider_type = 2;
}
// Enum for ClineMessage type
enum ClineMessageType {
ASK = 0;
@@ -229,13 +217,13 @@ service UiService {
rpc onDidShowAnnouncement(EmptyRequest) returns (Boolean);
// Subscribe to addToInput events (when user adds content via context menu)
rpc subscribeToAddToInput(StringRequest) returns (stream String);
rpc subscribeToAddToInput(EmptyRequest) returns (stream String);
// Subscribe to MCP button clicked events
rpc subscribeToMcpButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
rpc subscribeToMcpButtonClicked(EmptyRequest) returns (stream Empty);
// Subscribe to history button click events
rpc subscribeToHistoryButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
rpc subscribeToHistoryButtonClicked(EmptyRequest) returns (stream Empty);
// Subscribe to chat button clicked events (when the chat button is clicked in VSCode)
rpc subscribeToChatButtonClicked(EmptyRequest) returns (stream Empty);
@@ -244,7 +232,7 @@ service UiService {
rpc subscribeToAccountButtonClicked(EmptyRequest) returns (stream Empty);
// Subscribe to settings button clicked events
rpc subscribeToSettingsButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
rpc subscribeToSettingsButtonClicked(EmptyRequest) returns (stream Empty);
// Subscribe to partial message updates (streaming Cline messages as they're built)
rpc subscribeToPartialMessage(EmptyRequest) returns (stream ClineMessage);
@@ -255,8 +243,8 @@ service UiService {
// Subscribe to relinquish control events
rpc subscribeToRelinquishControl(EmptyRequest) returns (stream Empty);
// Subscribe to focus chat input events with client ID
rpc subscribeToFocusChatInput(StringRequest) returns (stream Empty);
// Subscribe to focus chat input events
rpc subscribeToFocusChatInput(EmptyRequest) returns (stream Empty);
// Subscribe to webview visibility change events
rpc subscribeToDidBecomeVisible(EmptyRequest) returns (stream Empty);
+8 -2
View File
@@ -34,10 +34,16 @@ service EnvService {
}
message GetHostVersionResponse {
// The name of the host platform, e.g VSCode
// The name of the host platform, e.g VSCode, IntelliJ Ultimate Edition, etc.
optional string platform = 1;
// The version of the host platform, e.g. 1.103.0
// The version of the host platform, e.g. 1.103.0 for VSCode, or 2025.1.1.1 for JetBrains IDEs.
optional string version = 2;
// The type of the cline host environment, e.g. 'VSCode Extension', 'Cline for JetBrains', 'CLI'
// This is different from the platform because there are many JetBrains IDEs, but they all use the same
// plugin.
optional string cline_type = 3;
// The version of the cline host environment, e.g. 33.2.10 for extension, or 1.0.6 for JetBrains.
optional string cline_version = 4;
}
enum Setting {
+5 -3
View File
@@ -27,6 +27,9 @@ service WorkspaceService {
// Opens and focuses the Cline sidebar panel in the host IDE.
rpc openClineSidebarPanel(OpenClineSidebarPanelRequest) returns (OpenClineSidebarPanelResponse);
// Opens and focuses the terminal panel.
rpc openTerminalPanel(OpenTerminalRequest) returns (OpenTerminalResponse);
}
message GetWorkspacePathsRequest {
@@ -82,12 +85,11 @@ message SearchWorkspaceItemsResponse {
message OpenProblemsPanelRequest {}
message OpenProblemsPanelResponse {}
message OpenInFileExplorerPanelRequest {
string path = 1;
}
message OpenInFileExplorerPanelResponse {}
// Request/response for opening the Cline sidebar
message OpenClineSidebarPanelRequest {}
message OpenClineSidebarPanelResponse {}
message OpenTerminalRequest {}
message OpenTerminalResponse {}
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env node
const { execSync } = require("child_process")
const process = require("process")
try {
if (process.platform === "linux") {
console.log("Detected Linux environment.")
execSync("which xvfb-run", { stdio: "ignore" })
console.log("xvfb-run is installed. Running tests with xvfb-run...")
execSync("xvfb-run -a npm run test:coverage", { stdio: "inherit" })
} else {
console.log("Non-Linux environment detected. Running tests normally.")
execSync("npm run test:integration", { stdio: "inherit" })
}
} catch (error) {
if (process.platform === "linux") {
console.error(
`Error: xvfb-run is not installed.\n` +
`Please install it using the following command:\n` +
` Debian/Ubuntu: sudo apt install xvfb\n` +
` RHEL/CentOS: sudo yum install xvfb\n` +
` Arch Linux: sudo pacman -S xvfb`,
)
} else {
console.error("Error running tests:", error.message)
}
process.exit(1)
}
+2 -3
View File
@@ -7,7 +7,6 @@ import {
} from "./core/storage/state-migrations"
import { WebviewProvider } from "./core/webview"
import { Logger } from "./services/logging/Logger"
import { WebviewProviderType } from "./shared/webview/types"
import "./utils/path" // necessary to have access to String.prototype.toPosix
import { HostProvider } from "@/hosts/host-provider"
@@ -53,13 +52,13 @@ export async function initialize(context: vscode.ExtensionContext): Promise<Webv
// Clean up orphaned file context warnings (startup cleanup)
await FileContextTracker.cleanupOrphanedWarnings(context)
const sidebarWebview = HostProvider.get().createWebviewProvider(WebviewProviderType.SIDEBAR)
const webview = HostProvider.get().createWebviewProvider()
await showVersionUpdateAnnouncement(context)
telemetryService.captureExtensionActivated()
return sidebarWebview
return webview
}
async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
+8 -6
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
@@ -44,16 +44,18 @@ export class AnthropicHandler implements ApiHandler {
const model = this.getModel()
let stream: AnthropicStream<Anthropic.RawMessageStreamEvent>
const modelId = model.id.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
? model.id.slice(0, -CLAUDE_SONNET_4_1M_SUFFIX.length)
: model.id
const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
const modelId = model.id.endsWith(CLAUDE_SONNET_1M_SUFFIX) ? model.id.slice(0, -CLAUDE_SONNET_1M_SUFFIX.length) : model.id
const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_1M_SUFFIX)
const budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = !!((modelId.includes("3-7") || modelId.includes("4-")) && budget_tokens !== 0)
const reasoningOn = !!(
(modelId.includes("3-7") || modelId.includes("4-") || modelId.includes("4-5")) &&
budget_tokens !== 0
)
switch (modelId) {
// 'latest' alias does not support cache_control
case "claude-sonnet-4-5-20250929":
case "claude-sonnet-4-20250514":
case "claude-3-7-sonnet-20250219":
case "claude-3-5-sonnet-20241022":
+8 -5
View File
@@ -9,7 +9,7 @@ import {
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime"
import { fromNodeProviderChain } from "@aws-sdk/credential-providers"
import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api"
import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -119,11 +119,11 @@ export class AwsBedrockHandler implements ApiHandler {
// cross region inference requires prefixing the model id with the region
const rawModelId = await this.getModelId()
const modelId = rawModelId.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
? rawModelId.slice(0, -CLAUDE_SONNET_4_1M_SUFFIX.length)
const modelId = rawModelId.endsWith(CLAUDE_SONNET_1M_SUFFIX)
? rawModelId.slice(0, -CLAUDE_SONNET_1M_SUFFIX.length)
: rawModelId
const enable1mContextWindow = rawModelId.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
const enable1mContextWindow = rawModelId.endsWith(CLAUDE_SONNET_1M_SUFFIX)
const model = this.getModel()
@@ -741,7 +741,10 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private shouldEnableReasoning(baseModelId: string, budgetTokens: number): boolean {
return (
(baseModelId.includes("3-7") || baseModelId.includes("sonnet-4") || baseModelId.includes("opus-4")) &&
(baseModelId.includes("3-7") ||
baseModelId.includes("sonnet-4") ||
baseModelId.includes("opus-4") ||
baseModelId.includes("sonnet-4-5")) &&
budgetTokens !== 0
)
}
+16 -11
View File
@@ -6,8 +6,8 @@ import OpenAI from "openai"
import { clineEnvConfig } from "@/config"
import { ClineAccountService } from "@/services/account/ClineAccountService"
import { AuthService } from "@/services/auth/AuthService"
import { buildClineExtraHeaders } from "@/services/EnvUtils"
import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount"
import { version as extensionVersion } from "../../../../package.json"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { createOpenRouterStream } from "../transform/openrouter-stream"
@@ -46,15 +46,17 @@ export class ClineHandler implements ApiHandler {
}
if (!this.client) {
try {
const defaultHeaders: Record<string, string> = {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
"X-Task-ID": this.options.ulid || "",
}
Object.assign(defaultHeaders, await buildClineExtraHeaders())
this.client = new OpenAI({
baseURL: `${this._baseUrl}/api/v1`,
apiKey: clineAccountAuthToken,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
"X-Task-ID": this.options.ulid || "",
"X-Cline-Version": extensionVersion,
},
defaultHeaders,
// Capture real HTTP request ID from initial streaming response headers
fetch: async (...args: Parameters<typeof fetch>): Promise<Awaited<ReturnType<typeof fetch>>> => {
const [input, init] = args
@@ -204,11 +206,14 @@ export class ClineHandler implements ApiHandler {
if (!clineAccountAuthToken) {
throw new Error(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE)
}
const headers: Record<string, string> = {
// Align with backend auth expectations
Authorization: `Bearer ${clineAccountAuthToken}`,
}
Object.assign(headers, await buildClineExtraHeaders())
const response = await axios.get(`${this.clineAccountService.baseUrl}/generation?id=${this.lastGenerationId}`, {
headers: {
// Align with backend auth expectations
Authorization: `Bearer ${clineAccountAuthToken}`,
},
headers,
timeout: 15_000, // this request hangs sometimes
})
+40 -19
View File
@@ -1,8 +1,13 @@
import { describe, it } from "mocha"
import "should"
import sinon from "sinon"
import { withRetry } from "./retry"
describe("Retry Decorator", () => {
afterEach(() => {
sinon.restore()
})
describe("withRetry", () => {
it("should not retry on success", async () => {
let callCount = 0
@@ -73,9 +78,11 @@ describe("Retry Decorator", () => {
it("should respect retry-after header with delta seconds", async () => {
let callCount = 0
const startTime = Date.now()
const setTimeoutSpy = sinon.spy(global, "setTimeout")
const baseDelay = 1000
class TestClass {
@withRetry({ maxRetries: 2, baseDelay: 1000 }) // Use large baseDelay to ensure header takes precedence
@withRetry({ maxRetries: 2, baseDelay }) // Use large baseDelay to ensure header takes precedence
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -94,19 +101,23 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
duration.should.be.approximately(10, 10) // Allow 10ms variance
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(0)
result.should.deepEqual(["success after retry"])
})
it("should respect retry-after header with Unix timestamp", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const startTime = Date.now()
const retryTimestamp = Math.floor(Date.now() / 1000) + 0.01 // 10ms in the future
const fixedDate = new Date("2010-01-01T00:00:00.000Z")
const retryTimestamp = Math.floor(fixedDate.getTime() / 1000) + 0.01 // 10ms in the future
const baseDelay = 1000
class TestClass {
@withRetry({ maxRetries: 2, baseDelay: 1000 }) // Use large baseDelay to ensure header takes precedence
@withRetry({ maxRetries: 2, baseDelay }) // Use large baseDelay to ensure header takes precedence
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -125,17 +136,22 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
duration.should.be.approximately(10, 10) // Allow 10ms variance
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(fixedDate.getTime())
result.should.deepEqual(["success after retry"])
})
it("should use exponential backoff when no retry-after header", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const startTime = Date.now()
const baseDelay = 10
class TestClass {
@withRetry({ maxRetries: 2, baseDelay: 10, maxDelay: 100 })
@withRetry({ maxRetries: 2, baseDelay, maxDelay: 100 })
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -153,18 +169,22 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
// First retry should be after baseDelay (10ms)
duration.should.be.approximately(10, 10)
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(baseDelay)
result.should.deepEqual(["success after retry"])
})
it("should respect maxDelay", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const startTime = Date.now()
const baseDelay = 50
const maxDelay = 10
class TestClass {
@withRetry({ maxRetries: 3, baseDelay: 50, maxDelay: 10 })
@withRetry({ maxRetries: 3, baseDelay, maxDelay })
async *failMethod() {
callCount++
if (callCount < 3) {
@@ -182,10 +202,11 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
// Both retries should be capped at maxDelay (10ms each)
duration.should.be.approximately(20, 20)
callCount.should.equal(3)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(maxDelay)
result.should.deepEqual(["success after retries"])
})
+1 -1
View File
@@ -151,7 +151,7 @@ export function convertToOpenAiMessages(
// Cannot be an empty array. API expects an array with minimum length 1, and will respond with an error if it's empty
tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
// @ts-ignore-next-line
reasoning_details: reasoningDetails,
reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined,
})
}
}
+16 -5
View File
@@ -1,5 +1,10 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo, openRouterClaudeSonnet41mModelId } from "@shared/api"
import {
CLAUDE_SONNET_1M_SUFFIX,
ModelInfo,
openRouterClaudeSonnet41mModelId,
openRouterClaudeSonnet451mModelId,
} from "@shared/api"
import OpenAI from "openai"
import { convertToOpenAiMessages } from "./openai-format"
import { convertToR1Format } from "./r1-format"
@@ -19,16 +24,18 @@ export async function createOpenRouterStream(
...convertToOpenAiMessages(messages),
]
const isClaudeSonnet41m = model.id === openRouterClaudeSonnet41mModelId
if (isClaudeSonnet41m) {
const isClaudeSonnet1m = model.id === openRouterClaudeSonnet41mModelId || model.id === openRouterClaudeSonnet451mModelId
if (isClaudeSonnet1m) {
// remove the custom :1m suffix, to create the model id openrouter API expects
model.id = model.id.slice(0, -CLAUDE_SONNET_4_1M_SUFFIX.length)
model.id = model.id.slice(0, -CLAUDE_SONNET_1M_SUFFIX.length)
}
// prompt caching: https://openrouter.ai/docs/prompt-caching
// this was initially specifically for claude models (some models may 'support prompt caching' automatically without this)
// handles direct model.id match logic
switch (model.id) {
case "anthropic/claude-sonnet-4.5":
case "anthropic/claude-4.5-sonnet": // OpenRouter accidentally included this in model list for a brief moment, and users may be using this model id. And to support prompt caching, we need to add it here.
case "anthropic/claude-sonnet-4":
case "anthropic/claude-opus-4.1":
case "anthropic/claude-opus-4":
@@ -88,6 +95,8 @@ export async function createOpenRouterStream(
// (models usually default to max tokens allowed)
let maxTokens: number | undefined
switch (model.id) {
case "anthropic/claude-sonnet-4.5":
case "anthropic/claude-4.5-sonnet":
case "anthropic/claude-sonnet-4":
case "anthropic/claude-opus-4.1":
case "anthropic/claude-opus-4":
@@ -124,6 +133,8 @@ export async function createOpenRouterStream(
let reasoning: { max_tokens: number } | undefined
switch (model.id) {
case "anthropic/claude-sonnet-4.5":
case "anthropic/claude-4.5-sonnet":
case "anthropic/claude-sonnet-4":
case "anthropic/claude-opus-4.1":
case "anthropic/claude-opus-4":
@@ -169,7 +180,7 @@ export async function createOpenRouterStream(
? { provider: { order: ["groq", "together", "baseten", "parasail", "novita", "deepinfra"], allow_fallbacks: false } }
: {}),
// limit providers to only those that support the 1m context window
...(isClaudeSonnet41m ? { provider: { order: ["anthropic", "amazon-bedrock"], allow_fallbacks: false } } : {}),
...(isClaudeSonnet1m ? { provider: { order: ["anthropic", "google-vertex/global"], allow_fallbacks: false } } : {}),
})
return stream
+12 -23
View File
@@ -1,10 +1,4 @@
import {
ensureTaskDirectoryExists,
getSavedClineMessages,
getTaskMetadata,
readTaskHistoryFromState,
writeTaskHistoryToState,
} from "@core/storage/disk"
import { getSavedClineMessages, getTaskMetadata, readTaskHistoryFromState, writeTaskHistoryToState } from "@core/storage/disk"
import { HostProvider } from "@hosts/host-provider"
import { ClineMessage } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
@@ -12,7 +6,6 @@ import { ShowMessageType } from "@shared/proto/host/window"
import { fileExistsAtPath } from "@utils/fs"
import * as path from "path"
import { ulid } from "ulid"
import * as vscode from "vscode"
interface TaskReconstructionResult {
totalTasks: number
@@ -24,7 +17,7 @@ interface TaskReconstructionResult {
/**
* Reconstructs task history from existing task folders
*/
export async function reconstructTaskHistory(context: vscode.ExtensionContext): Promise<void> {
export async function reconstructTaskHistory(): Promise<void> {
try {
// Show confirmation dialog using HostProvider
const proceed = await HostProvider.window.showMessage({
@@ -46,7 +39,7 @@ export async function reconstructTaskHistory(context: vscode.ExtensionContext):
message: "Reconstructing task history...",
})
const result = await performTaskHistoryReconstruction(context)
const result = await performTaskHistoryReconstruction()
// Show results
if (result.errors.length > 0) {
@@ -71,7 +64,7 @@ export async function reconstructTaskHistory(context: vscode.ExtensionContext):
}
}
async function performTaskHistoryReconstruction(context: vscode.ExtensionContext): Promise<TaskReconstructionResult> {
async function performTaskHistoryReconstruction(): Promise<TaskReconstructionResult> {
const result: TaskReconstructionResult = {
totalTasks: 0,
reconstructedTasks: 0,
@@ -80,11 +73,10 @@ async function performTaskHistoryReconstruction(context: vscode.ExtensionContext
}
// Backup existing task history
await backupExistingTaskHistory(context)
await backupExistingTaskHistory()
// Get tasks directory
const globalStoragePath = context.globalStorageUri.fsPath
const tasksDir = path.join(globalStoragePath, "tasks")
const tasksDir = path.join(HostProvider.get().globalStorageFsPath, "tasks")
// Check if tasks directory exists
if (!(await fileExistsAtPath(tasksDir))) {
@@ -104,7 +96,7 @@ async function performTaskHistoryReconstruction(context: vscode.ExtensionContext
for (const taskId of taskIds) {
try {
const historyItem = await reconstructTaskHistoryItem(context, taskId)
const historyItem = await reconstructTaskHistoryItem(taskId)
if (historyItem) {
reconstructedItems.push(historyItem)
result.reconstructedTasks++
@@ -127,11 +119,11 @@ async function performTaskHistoryReconstruction(context: vscode.ExtensionContext
return result
}
async function backupExistingTaskHistory(context: vscode.ExtensionContext): Promise<void> {
async function backupExistingTaskHistory(): Promise<void> {
try {
const existingHistory = await readTaskHistoryFromState()
if (existingHistory.length > 0) {
const backupPath = path.join(context.globalStorageUri.fsPath, "state", `taskHistory.backup.${Date.now()}.json`)
const backupPath = path.join(HostProvider.get().globalStorageFsPath, "state", `taskHistory.backup.${Date.now()}.json`)
// Ensure state directory exists
const fs = await import("fs/promises")
@@ -158,19 +150,16 @@ async function scanTaskDirectories(tasksDir: string): Promise<string[]> {
}
}
async function reconstructTaskHistoryItem(context: vscode.ExtensionContext, taskId: string): Promise<HistoryItem | null> {
async function reconstructTaskHistoryItem(taskId: string): Promise<HistoryItem | null> {
try {
// Get task directory
const taskDir = await ensureTaskDirectoryExists(context, taskId)
// Load UI messages to extract task info
const clineMessages = await getSavedClineMessages(context, taskId)
const clineMessages = await getSavedClineMessages(taskId)
if (clineMessages.length === 0) {
return null // Skip empty tasks
}
// Load task metadata for token usage
const metadata = await getTaskMetadata(context, taskId)
const metadata = await getTaskMetadata(taskId)
// Extract task information
const taskInfo = extractTaskInformation(clineMessages, metadata)
@@ -6,19 +6,19 @@ import * as path from "path"
import * as sinon from "sinon"
import * as vscode from "vscode"
import { Controller } from "@/core/controller"
import { HostProvider } from "@/hosts/host-provider"
import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils"
import type { FileMetadataEntry, TaskMetadata } from "./ContextTrackerTypes"
import { FileContextTracker } from "./FileContextTracker"
describe("FileContextTracker", () => {
const filePath = "src/test-file.ts"
const taskId = "test-task-id"
let sandbox: sinon.SinonSandbox
let mockController: Controller
let _mockWorkspace: sinon.SinonStub
let mockFileSystemWatcher: any
let chokidarWatchStub: sinon.SinonStub
let tracker: FileContextTracker
let taskId: string
let mockTaskMetadata: TaskMetadata
let getTaskMetadataStub: sinon.SinonStub
let saveTaskMetadataStub: sinon.SinonStub
@@ -46,11 +46,6 @@ describe("FileContextTracker", () => {
// Stub chokidar.watch to return our mock watcher
chokidarWatchStub = sandbox.stub(chokidar, "watch").returns(mockFileSystemWatcher as any)
// Mock controller and context
mockController = {
context: {} as vscode.ExtensionContext,
} as unknown as Controller
// Mock disk module functions
mockTaskMetadata = { files_in_context: [], model_usage: [] }
getTaskMetadataStub = sandbox.stub(diskModule, "getTaskMetadata").resolves(mockTaskMetadata)
@@ -59,29 +54,24 @@ describe("FileContextTracker", () => {
setVscodeHostProviderMock()
// Create tracker instance
taskId = "test-task-id"
tracker = new FileContextTracker(mockController, taskId)
tracker = new FileContextTracker({} as Controller, taskId)
})
afterEach(() => {
sandbox.restore()
// Reset HostProvider after each test to ensure clean state
HostProvider.reset()
})
it("should add a record when a file is read by a tool", async () => {
const filePath = "src/test-file.ts"
await tracker.trackFileContext(filePath, "read_tool")
// Verify getTaskMetadata was called
expect(getTaskMetadataStub.calledOnce).to.be.true
expect(getTaskMetadataStub.firstCall.args[1]).to.equal(taskId)
expect(getTaskMetadataStub.firstCall.args[0]).to.equal(taskId)
// Verify saveTaskMetadata was called with the correct data
expect(saveTaskMetadataStub.calledOnce).to.be.true
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
expect(savedMetadata.files_in_context.length).to.equal(1)
const fileEntry = savedMetadata.files_in_context[0]
@@ -93,13 +83,11 @@ describe("FileContextTracker", () => {
})
it("should add a record when a file is edited by Cline", async () => {
const filePath = "src/test-file.ts"
await tracker.trackFileContext(filePath, "cline_edited")
// Verify saveTaskMetadata was called with the correct data
expect(saveTaskMetadataStub.calledOnce).to.be.true
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
// Check that we have at least one entry in files_in_context
expect(savedMetadata.files_in_context).to.be.an("array").that.is.not.empty
@@ -121,12 +109,10 @@ describe("FileContextTracker", () => {
})
it("should add a record when a file is mentioned", async () => {
const filePath = "src/test-file.ts"
await tracker.trackFileContext(filePath, "file_mentioned")
// Verify saveTaskMetadata was called with the correct data
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
const fileEntry = savedMetadata.files_in_context[0]
expect(fileEntry.path).to.equal(filePath)
@@ -137,12 +123,10 @@ describe("FileContextTracker", () => {
})
it("should add a record when a file is edited by the user", async () => {
const filePath = "src/test-file.ts"
await tracker.trackFileContext(filePath, "user_edited")
// Verify saveTaskMetadata was called with the correct data
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
const fileEntry = savedMetadata.files_in_context[0]
expect(fileEntry.path).to.equal(filePath)
@@ -156,8 +140,6 @@ describe("FileContextTracker", () => {
})
it("should mark existing entries as stale when adding a new entry for the same file", async () => {
const filePath = "src/test-file.ts"
// Add an initial entry
mockTaskMetadata.files_in_context = [
{
@@ -174,7 +156,7 @@ describe("FileContextTracker", () => {
await tracker.trackFileContext(filePath, "cline_edited")
// Verify the metadata now has two entries - one stale and one active
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
expect(savedMetadata.files_in_context.length).to.equal(2)
// First entry should be marked as stale
@@ -187,8 +169,6 @@ describe("FileContextTracker", () => {
})
it("should setup a file watcher for tracked files", async () => {
const filePath = "src/test-file.ts"
await tracker.trackFileContext(filePath, "read_tool")
// Verify chokidar.watch was called
@@ -199,8 +179,6 @@ describe("FileContextTracker", () => {
})
it("should track user edits when file watcher detects changes", async () => {
const filePath = "src/test-file.ts"
// First track the file to set up the watcher
await tracker.trackFileContext(filePath, "read_tool")
@@ -226,8 +204,6 @@ describe("FileContextTracker", () => {
})
it("should not track Cline edits as user edits", async () => {
const filePath = "src/test-file.ts"
// First track the file to set up the watcher
await tracker.trackFileContext(filePath, "read_tool")
@@ -256,8 +232,6 @@ describe("FileContextTracker", () => {
})
it("should dispose file watchers when dispose is called", async () => {
const filePath = "src/test-file.ts"
// Track a file to set up the watcher
await tracker.trackFileContext(filePath, "read_tool")
@@ -90,7 +90,7 @@ export class FileContextTracker {
}
// Add file to metadata
await this.addFileToFileContextTracker(this.controller.context, this.taskId, filePath, operation)
await this.addFileToFileContextTracker(this.taskId, filePath, operation)
// Set up file watcher for this file
await this.setupFileWatcher(filePath)
@@ -104,14 +104,9 @@ export class FileContextTracker {
* This handles the business logic of determining if the file is new, stale, or active.
* It also updates the metadata with the latest read/edit dates.
*/
async addFileToFileContextTracker(
context: vscode.ExtensionContext,
taskId: string,
filePath: string,
source: FileMetadataEntry["record_source"],
) {
async addFileToFileContextTracker(taskId: string, filePath: string, source: FileMetadataEntry["record_source"]) {
try {
const metadata = await getTaskMetadata(context, taskId)
const metadata = await getTaskMetadata(taskId)
const now = Date.now()
// Mark existing entries for this file as stale
@@ -160,7 +155,7 @@ export class FileContextTracker {
}
metadata.files_in_context.push(newEntry)
await saveTaskMetadata(context, taskId, metadata)
await saveTaskMetadata(taskId, metadata)
} catch (error) {
console.error("Failed to add file to metadata:", error)
}
@@ -200,7 +195,7 @@ export class FileContextTracker {
try {
// Check task metadata for files that were edited by Cline or users after the message timestamp
const taskMetadata = await getTaskMetadata(this.controller.context, this.taskId)
const taskMetadata = await getTaskMetadata(this.taskId)
if (taskMetadata?.files_in_context) {
for (const fileEntry of taskMetadata.files_in_context) {
@@ -2,15 +2,13 @@ import * as diskModule from "@core/storage/disk"
import { expect } from "chai"
import { afterEach, beforeEach, describe, it } from "mocha"
import * as sinon from "sinon"
import * as vscode from "vscode"
import type { TaskMetadata } from "./ContextTrackerTypes"
import { ModelContextTracker } from "./ModelContextTracker"
describe("ModelContextTracker", () => {
const taskId = "test-task-id"
let sandbox: sinon.SinonSandbox
let mockContext: vscode.ExtensionContext
let tracker: ModelContextTracker
let taskId: string
let mockTaskMetadata: TaskMetadata
let getTaskMetadataStub: sinon.SinonStub
let saveTaskMetadataStub: sinon.SinonStub
@@ -18,19 +16,13 @@ describe("ModelContextTracker", () => {
beforeEach(() => {
sandbox = sinon.createSandbox()
// Mock controller and context
mockContext = {
globalStorageUri: { fsPath: "/mock/storage" },
} as unknown as vscode.ExtensionContext
// Mock disk module functions
mockTaskMetadata = { files_in_context: [], model_usage: [] }
getTaskMetadataStub = sandbox.stub(diskModule, "getTaskMetadata").resolves(mockTaskMetadata)
saveTaskMetadataStub = sandbox.stub(diskModule, "saveTaskMetadata").resolves()
// Create tracker instance
taskId = "test-task-id"
tracker = new ModelContextTracker(mockContext, taskId)
tracker = new ModelContextTracker(taskId)
})
afterEach(() => {
@@ -53,13 +45,13 @@ describe("ModelContextTracker", () => {
// Verify getTaskMetadata was called with correct parameters
expect(getTaskMetadataStub.calledOnce).to.be.true
expect(getTaskMetadataStub.firstCall.args[1]).to.equal(taskId)
expect(getTaskMetadataStub.firstCall.args[0]).to.equal(taskId)
// Verify saveTaskMetadata was called with the correct data
expect(saveTaskMetadataStub.calledOnce).to.be.true
// Extract the saved metadata from the call arguments
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
// Verify model_usage array has one entry
expect(savedMetadata.model_usage.length).to.equal(1)
@@ -105,7 +97,7 @@ describe("ModelContextTracker", () => {
expect(saveTaskMetadataStub.calledOnce).to.be.true
// Extract the saved metadata
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
// Verify model_usage array now has two entries
expect(savedMetadata.model_usage.length).to.equal(2)
@@ -166,7 +158,7 @@ describe("ModelContextTracker", () => {
expect(saveTaskMetadataStub.calledOnce).to.be.true
// Get the saved metadata
const savedMetadata = saveTaskMetadataStub.firstCall.args[2]
const savedMetadata = saveTaskMetadataStub.firstCall.args[1]
// Since we reset the array for each call, we should always have 1 entry
expect(savedMetadata.model_usage.length).to.equal(1)
@@ -1,17 +1,14 @@
import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk"
import * as vscode from "vscode"
export class ModelContextTracker {
readonly taskId: string
private context: vscode.ExtensionContext
constructor(context: vscode.ExtensionContext, taskId: string) {
this.context = context
constructor(taskId: string) {
this.taskId = taskId
}
async recordModelUsage(apiProviderId: string, modelId: string, mode: string) {
const metadata = await getTaskMetadata(this.context, this.taskId)
const metadata = await getTaskMetadata(this.taskId)
if (!metadata.model_usage) {
metadata.model_usage = []
@@ -35,6 +32,6 @@ export class ModelContextTracker {
mode: mode,
})
await saveTaskMetadata(this.context, this.taskId, metadata)
await saveTaskMetadata(this.taskId, metadata)
}
}
@@ -19,7 +19,7 @@ export async function discoverBrowser(controller: Controller, _request: EmptyReq
// This way we don't override the user's preference
// Test the connection to get the endpoint
const browserSession = new BrowserSession(controller.context, controller.stateManager)
const browserSession = new BrowserSession(controller.stateManager)
const result = await browserSession.testConnection(discoveredHost)
return BrowserConnection.create({
@@ -11,7 +11,7 @@ import { Controller } from "../index"
*/
export async function getDetectedChromePath(controller: Controller, _: EmptyRequest): Promise<ChromePath> {
try {
const browserSession = new BrowserSession(controller.context, controller.stateManager)
const browserSession = new BrowserSession(controller.stateManager)
const result = await browserSession.getDetectedChromePath()
return ChromePath.create({
@@ -10,7 +10,7 @@ import { Controller } from "../index"
*/
export async function relaunchChromeDebugMode(controller: Controller, _: EmptyRequest): Promise<StringMessage> {
try {
const browserSession = new BrowserSession(controller.context, controller.stateManager)
const browserSession = new BrowserSession(controller.stateManager)
// Relaunch Chrome in debug mode
await browserSession.relaunchChromeDebugMode(controller)
@@ -12,7 +12,7 @@ import { Controller } from "../index"
*/
export async function testBrowserConnection(controller: Controller, request: StringRequest): Promise<BrowserConnection> {
try {
const browserSession = new BrowserSession(controller.context, controller.stateManager)
const browserSession = new BrowserSession(controller.stateManager)
const text = request.value || ""
// If no text is provided, try auto-discovery
+2 -6
View File
@@ -1,10 +1,9 @@
import { getFileMentionFromPath } from "@/core/mentions"
import { WebviewProvider } from "@/core/webview"
import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
import { telemetryService } from "@/services/telemetry"
import { CommandContext, Empty } from "@/shared/proto/index.cline"
import { Controller } from "../index"
import { sendAddToInputEventToClient } from "../ui/subscribeToAddToInput"
import { sendAddToInputEvent } from "../ui/subscribeToAddToInput"
// 'Add to Cline' context menu in editor and code action
// Inserts the selected code into the chat.
@@ -22,10 +21,7 @@ export async function addToCline(controller: Controller, request: CommandContext
input += `\nProblems:\n${problemsString}`
}
const lastActiveWebview = WebviewProvider.getLastActiveInstance()
if (lastActiveWebview) {
await sendAddToInputEventToClient(lastActiveWebview.getClientId(), input)
}
await sendAddToInputEvent(input)
console.log("addToCline", request.selectedText, filePath, request.language)
telemetryService.captureButtonClick("codeAction_addToChat", controller.task?.ulid)
@@ -31,9 +31,7 @@ async function handleInstallWithCline(
* Handles copying the installation command to clipboard
*/
async function handleCopyCommand(installCommand: string): Promise<void> {
const vscode = await import("vscode")
await vscode.env.clipboard.writeText(installCommand)
await HostProvider.env.clipboardWriteText({ value: installCommand })
await HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: `Installation command copied to clipboard: ${installCommand}`,
@@ -32,7 +32,7 @@ export async function openFocusChainFile(controller: Controller, request: String
}
}
const focusChainFilePath = await ensureFocusChainFile(controller.context, taskId, initialFocusChainContent)
const focusChainFilePath = await ensureFocusChainFile(taskId, initialFocusChainContent)
telemetryService.captureFocusChainListOpened(taskId)
await openFileIntegration(focusChainFilePath)
+28 -31
View File
@@ -44,6 +44,7 @@ import { Task } from "../task"
import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog"
import { appendClineStealthModels } from "./models/refreshOpenRouterModels"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendChatButtonClickedEvent } from "./ui/subscribeToChatButtonClicked"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@@ -52,7 +53,6 @@ https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/c
*/
export class Controller {
readonly id: string
task?: Task
mcpHub: McpHub
@@ -64,11 +64,7 @@ export class Controller {
// NEW: Add workspace manager (optional initially)
private workspaceManager?: WorkspaceRootManager
constructor(
readonly context: vscode.ExtensionContext,
id: string,
) {
this.id = id
constructor(readonly context: vscode.ExtensionContext) {
PromptRegistry.getInstance() // Ensure prompts and tools are registered
HostProvider.get().logToChannel("ClineProvider instantiated")
this.stateManager = new StateManager(context)
@@ -118,21 +114,17 @@ export class Controller {
this.mcpHub = new McpHub(
() => ensureMcpServersDirectoryExists(),
() => ensureSettingsDirectoryExists(this.context),
() => ensureSettingsDirectoryExists(),
ExtensionRegistryInfo.version,
telemetryService,
)
// Clean up legacy checkpoints
cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath).catch((error) => {
cleanupLegacyCheckpoints().catch((error) => {
console.error("Failed to cleanup legacy checkpoints:", error)
})
}
async getCurrentMode(): Promise<Mode> {
return this.stateManager.getGlobalSettingsKey("mode")
}
/*
VSCode extensions use the disposable pattern to clean up resources when the sidebar/editor tab is closed by the user or system. This applies to event listening, commands, interacting with the UI, etc.
- https://vscode-docs.readthedocs.io/en/stable/extensions/patterns-and-principles/
@@ -203,7 +195,6 @@ export class Controller {
const terminalReuseEnabled = this.stateManager.getGlobalStateKey("terminalReuseEnabled")
const terminalOutputLineLimit = this.stateManager.getGlobalSettingsKey("terminalOutputLineLimit")
const defaultTerminalProfile = this.stateManager.getGlobalSettingsKey("defaultTerminalProfile")
const enableCheckpointsSetting = this.stateManager.getGlobalSettingsKey("enableCheckpointsSetting")
const isNewUser = this.stateManager.getGlobalStateKey("isNewUser")
const taskHistory = this.stateManager.getGlobalStateKey("taskHistory")
@@ -231,26 +222,25 @@ export class Controller {
const cwd = this.workspaceManager?.getPrimaryRoot()?.path || (await getCwd(getDesktopDir()))
this.task = new Task(
this,
this.mcpHub,
(historyItem) => this.updateTaskHistory(historyItem),
() => this.postStateToWebview(),
(taskId) => this.reinitExistingTaskFromId(taskId),
() => this.cancelTask(),
this.task = new Task({
controller: this,
mcpHub: this.mcpHub,
updateTaskHistory: (historyItem) => this.updateTaskHistory(historyItem),
postStateToWebview: () => this.postStateToWebview(),
reinitExistingTaskFromId: (taskId) => this.reinitExistingTaskFromId(taskId),
cancelTask: () => this.cancelTask(),
shellIntegrationTimeout,
terminalReuseEnabled ?? true,
terminalOutputLineLimit ?? 500,
defaultTerminalProfile ?? "default",
enableCheckpointsSetting ?? true,
terminalReuseEnabled: terminalReuseEnabled ?? true,
terminalOutputLineLimit: terminalOutputLineLimit ?? 500,
defaultTerminalProfile: defaultTerminalProfile ?? "default",
cwd,
this.stateManager,
this.workspaceManager,
stateManager: this.stateManager,
workspaceManager: this.workspaceManager,
task,
images,
files,
historyItem,
)
})
// Load task settings after task creation
if (this.task.taskId) {
@@ -370,7 +360,7 @@ export class Controller {
// Get current settings to determine how to update providers
const planActSeparateModelsSetting = this.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await this.getCurrentMode()
const currentMode = this.stateManager.getGlobalSettingsKey("mode")
// Get current API configuration from cache
const currentApiConfiguration = this.stateManager.getApiConfiguration()
@@ -421,7 +411,7 @@ export class Controller {
// Get current settings to determine how to update providers
const planActSeparateModelsSetting = this.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await this.getCurrentMode()
const currentMode = this.stateManager.getGlobalSettingsKey("mode")
// Get current API configuration from cache
const currentApiConfiguration = this.stateManager.getApiConfiguration()
@@ -463,6 +453,11 @@ export class Controller {
}
}
async handleTaskCreation(prompt: string) {
await sendChatButtonClickedEvent()
await this.initTask(prompt)
}
// MCP Marketplace
private async fetchMcpMarketplaceFromApi(silent: boolean = false): Promise<McpMarketplaceCatalog | undefined> {
try {
@@ -578,7 +573,7 @@ export class Controller {
}
const openrouter: ApiProvider = "openrouter"
const currentMode = await this.getCurrentMode()
const currentMode = this.stateManager.getGlobalSettingsKey("mode")
// Update API configuration through cache service
const currentApiConfiguration = this.stateManager.getApiConfiguration()
@@ -682,7 +677,7 @@ export class Controller {
async postStateToWebview() {
const state = await this.getStateToPostToWebview()
await sendStateUpdate(this.id, state)
await sendStateUpdate(state)
}
async getStateToPostToWebview(): Promise<ExtensionState> {
@@ -720,6 +715,7 @@ export class Controller {
const terminalOutputLineLimit = this.stateManager.getGlobalSettingsKey("terminalOutputLineLimit")
const favoritedModelIds = this.stateManager.getGlobalStateKey("favoritedModelIds")
const lastDismissedInfoBannerVersion = this.stateManager.getGlobalStateKey("lastDismissedInfoBannerVersion") || 0
const lastDismissedModelBannerVersion = this.stateManager.getGlobalStateKey("lastDismissedModelBannerVersion") || 0
const localClineRulesToggles = this.stateManager.getWorkspaceStateKey("localClineRulesToggles")
const localWindsurfRulesToggles = this.stateManager.getWorkspaceStateKey("localWindsurfRulesToggles")
@@ -800,6 +796,7 @@ export class Controller {
featureFlag: featureFlagsService.getMultiRootEnabled(),
},
lastDismissedInfoBannerVersion,
lastDismissedModelBannerVersion,
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont
// Initialize task and show chat view
await controller.initTask(task)
await sendChatButtonClickedEvent(controller.id)
await sendChatButtonClickedEvent()
// Return the download details directly
return McpDownloadResponse.create({
@@ -80,7 +80,7 @@ export async function refreshOcaModels(controller: Controller, request: StringRe
// Which mode(s) to update?
const planActSeparateModelsSetting = controller.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = (await controller.getCurrentMode?.()) ?? "plan"
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
const planModeSelectedModelId =
apiConfiguration?.planModeOcaModelId && models[apiConfiguration.planModeOcaModelId]
? apiConfiguration.planModeOcaModelId
@@ -5,7 +5,12 @@ import axios from "axios"
import cloneDeep from "clone-deep"
import fs from "fs/promises"
import path from "path"
import { CLAUDE_SONNET_4_1M_TIERS, clineCodeSupernovaModelInfo, openRouterClaudeSonnet41mModelId } from "@/shared/api"
import {
CLAUDE_SONNET_1M_TIERS,
clineCodeSupernovaModelInfo,
openRouterClaudeSonnet41mModelId,
openRouterClaudeSonnet451mModelId,
} from "@/shared/api"
import { Controller } from ".."
type OpenRouterSupportedParams =
@@ -108,6 +113,8 @@ export async function refreshOpenRouterModels(
})
switch (rawModel.id) {
case "anthropic/claude-sonnet-4.5":
case "anthropic/claude-4.5-sonnet":
case "anthropic/claude-sonnet-4":
// NOTE: we artificially restrict the context window to 200k to keep costs low for users, and have a :1m model variant created below for users that want to use the full 1m.
modelInfo.contextWindow = 200_000
@@ -213,11 +220,14 @@ export async function refreshOpenRouterModels(
models[rawModel.id] = modelInfo
// add custom :1m model variant
if (rawModel.id === "anthropic/claude-sonnet-4") {
const claudeSonnet41mModelInfo = cloneDeep(modelInfo)
claudeSonnet41mModelInfo.contextWindow = 1_000_000 // limiting providers to those that support 1m context window
claudeSonnet41mModelInfo.tiers = CLAUDE_SONNET_4_1M_TIERS
models[openRouterClaudeSonnet41mModelId] = claudeSonnet41mModelInfo
if (rawModel.id === "anthropic/claude-sonnet-4" || rawModel.id === "anthropic/claude-sonnet-4.5") {
const claudeSonnet1mModelInfo = cloneDeep(modelInfo)
claudeSonnet1mModelInfo.contextWindow = 1_000_000 // limiting providers to those that support 1m context window
claudeSonnet1mModelInfo.tiers = CLAUDE_SONNET_1M_TIERS
// sonnet 4
models[openRouterClaudeSonnet41mModelId] = claudeSonnet1mModelInfo
// sonnet 4.5
models[openRouterClaudeSonnet451mModelId] = claudeSonnet1mModelInfo
}
}
} else {
@@ -24,7 +24,11 @@ export async function refreshRequestyModels(controller: Controller, _: EmptyRequ
const baseUrl = controller.stateManager.getGlobalSettingsKey("requestyBaseUrl")
const resolvedUrl = toRequestyServiceUrl(baseUrl)
const url = new URL(`${resolvedUrl.pathname}/models`, resolvedUrl).toString()
const url = resolvedUrl != null ? new URL(`${resolvedUrl.pathname}/models`, resolvedUrl).toString() : undefined
if (url == null) {
throw new Error("URL is not valid.")
}
const headers = {
Authorization: `Bearer ${apiKey}`,
@@ -28,7 +28,7 @@ export async function updateApiConfigurationProto(
// Update the task's API handler if there's an active task
if (controller.task) {
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
controller.task.api = buildApiHandler({ ...appApiConfiguration, ulid: controller.task.ulid }, currentMode)
}
+1 -1
View File
@@ -39,7 +39,7 @@ export async function resetState(controller: Controller, request: ResetStateRequ
})
await controller.postStateToWebview()
await sendChatButtonClickedEvent(controller.id)
await sendChatButtonClickedEvent()
return Empty.create()
} catch (error) {
+39 -37
View File
@@ -4,8 +4,8 @@ import { ExtensionState } from "@/shared/ExtensionMessage"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active state subscriptions by controller ID
const activeStateSubscriptions = new Map<string, StreamingResponseHandler<State>>()
// Keep track of active state subscriptions
const activeStateSubscriptions = new Set<StreamingResponseHandler<State>>()
/**
* Subscribe to state updates
@@ -20,59 +20,61 @@ export async function subscribeToState(
responseStream: StreamingResponseHandler<State>,
requestId?: string,
): Promise<void> {
const controllerId = controller.id
// Send the initial state
const initialState = await controller.getStateToPostToWebview()
const initialStateJson = JSON.stringify(initialState)
//console.log(`[DEBUG] set up state subscription for controller ${controllerId}`)
await responseStream({
stateJson: initialStateJson,
})
// Add this subscription to the active subscriptions with the controller ID
activeStateSubscriptions.set(controllerId, responseStream)
// Add this subscription to the active subscriptions
activeStateSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeStateSubscriptions.delete(controllerId)
//console.log(`[DEBUG] Cleaned up state subscription for controller ${controllerId}`)
activeStateSubscriptions.delete(responseStream)
//console.log(`[DEBUG] Cleaned up state subscription`)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "state_subscription" }, responseStream)
}
}
/**
* Send a state update to a specific controller's subscription
* @param controllerId The ID of the controller to send the state to
* @param state The state to send
*/
export async function sendStateUpdate(controllerId: string, state: ExtensionState): Promise<void> {
// Get the subscription for this specific controller
const responseStream = activeStateSubscriptions.get(controllerId)
// Send the initial state
const initialState = await controller.getStateToPostToWebview()
const initialStateJson = JSON.stringify(initialState)
if (!responseStream) {
console.log(`[DEBUG] No active state subscription for controller ${controllerId}`)
return
}
//console.log(`[DEBUG] set up state subscription`)
try {
const stateJson = JSON.stringify(state)
await responseStream(
{
stateJson,
stateJson: initialStateJson,
},
false, // Not the last message
)
//console.log(`[DEBUG] sending followup state to controller ${controllerId}`, stateJson.length, "chars")
} catch (error) {
console.error(`Error sending state update to controller ${controllerId}:`, error)
// Remove the subscription if there was an error
activeStateSubscriptions.delete(controllerId)
console.error("Error sending initial state:", error)
activeStateSubscriptions.delete(responseStream)
}
}
/**
* Send a state update to all active subscribers
* @param state The state to send
*/
export async function sendStateUpdate(state: ExtensionState): Promise<void> {
// Send the state to all active subscribers
const promises = Array.from(activeStateSubscriptions).map(async (responseStream) => {
try {
const stateJson = JSON.stringify(state)
await responseStream(
{
stateJson,
},
false, // Not the last message
)
//console.log(`[DEBUG] sending followup state`, stateJson.length, "chars")
} catch (error) {
console.error("Error sending state update:", error)
// Remove the subscription if there was an error
activeStateSubscriptions.delete(responseStream)
}
})
await Promise.all(promises)
}
@@ -0,0 +1,17 @@
import { Empty, Int64Request } from "@shared/proto/cline/common"
import { Controller } from ".."
/**
* Updates the model banner version to track which version the user has dismissed
* @param controller The controller instance
* @param request The request containing the version number
* @returns Empty response
*/
export async function updateModelBannerVersion(controller: Controller, request: Int64Request): Promise<Empty> {
const version = Number(request.value)
controller.stateManager.setGlobalState("lastDismissedModelBannerVersion", version)
await controller.postStateToWebview()
return Empty.create()
}
+1 -1
View File
@@ -43,7 +43,7 @@ export async function updateSettings(controller: Controller, request: UpdateSett
controller.stateManager.setApiConfiguration(convertedApiConfigurationFromProto)
if (controller.task) {
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
const apiConfigForHandler = {
...convertedApiConfigurationFromProto,
ulid: controller.task.ulid,
+2 -2
View File
@@ -23,7 +23,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
await controller.initTask(undefined, undefined, undefined, historyItem)
// Send UI update to show the chat view
await sendChatButtonClickedEvent(controller.id)
await sendChatButtonClickedEvent()
// Return task data for gRPC response
return TaskResponse.create({
@@ -47,7 +47,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
await controller.initTask(undefined, undefined, undefined, fetchedItem)
// Send UI update to show the chat view
await sendChatButtonClickedEvent(controller.id)
await sendChatButtonClickedEvent()
return TaskResponse.create({
id: fetchedItem.id,
+2 -5
View File
@@ -9,9 +9,6 @@ import type { Controller } from "../index"
* resolved through `resolveWebviewView()`.
*/
export async function getWebviewHtml(_controller: Controller, _: EmptyRequest): Promise<String> {
const webviewProvider = WebviewProvider.getLastActiveInstance()
if (!webviewProvider) {
throw new Error("No active webview")
}
return Promise.resolve(String.create({ value: webviewProvider.getHtmlContent() }))
const webview = WebviewProvider.getInstance()
return Promise.resolve(String.create({ value: webview.getHtmlContent() }))
}
+4 -4
View File
@@ -30,7 +30,7 @@ export async function initializeWebview(controller: Controller, _request: EmptyR
// 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 = controller.stateManager.getApiConfiguration()
const planActSeparateModelsSetting = controller.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
if (planActSeparateModelsSetting) {
// Separate models: update only current mode
@@ -76,7 +76,7 @@ export async function initializeWebview(controller: Controller, _request: EmptyR
// 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 = controller.stateManager.getApiConfiguration()
const planActSeparateModelsSetting = controller.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
if (planActSeparateModelsSetting) {
// Separate models: update only current mode
@@ -123,7 +123,7 @@ export async function initializeWebview(controller: Controller, _request: EmptyR
const apiConfiguration = controller.stateManager.getApiConfiguration()
const planActSeparateModelsSetting = controller.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
if (planActSeparateModelsSetting) {
// Separate models: update only current mode
@@ -164,7 +164,7 @@ export async function initializeWebview(controller: Controller, _request: EmptyR
// Update model info in state for Vercel AI Gateway (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 = controller.stateManager.getApiConfiguration()
const planActSeparateModelsSetting = controller.stateManager.getGlobalSettingsKey("planActSeparateModelsSetting")
const currentMode = await controller.getCurrentMode()
const currentMode = controller.stateManager.getGlobalSettingsKey("mode")
if (planActSeparateModelsSetting) {
// Separate models: update only current mode
@@ -2,8 +2,8 @@ import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Track subscriptions by controller ID
const activeSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
// Keep track of active account button clicked subscriptions
const activeAccountButtonClickedSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to account button clicked events
@@ -13,43 +13,45 @@ const activeSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
* @param requestId The request ID for cleanup
*/
export async function subscribeToAccountButtonClicked(
controller: Controller,
_controller: Controller,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const controllerId = controller.id
console.log(`[DEBUG] set up accountButtonClicked subscription`)
// Store subscription with controller ID
activeSubscriptions.set(controllerId, responseStream)
// Add this subscription to the active subscriptions
activeAccountButtonClickedSubscriptions.add(responseStream)
// Register cleanup
// Register cleanup when the connection is closed
const cleanup = () => {
activeSubscriptions.delete(controllerId)
activeAccountButtonClickedSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
if (requestId) {
getRequestRegistry().registerRequest(requestId, cleanup, { type: "account_button_subscription" }, responseStream)
getRequestRegistry().registerRequest(requestId, cleanup, { type: "accountButtonClicked_subscription" }, responseStream)
}
}
/**
* Send account button clicked event to a specific controller
* @param controllerId The ID of the controller to send the event to
* Send an account button clicked event to all active subscribers
*/
export async function sendAccountButtonClickedEvent(controllerId: string): Promise<void> {
const responseStream = activeSubscriptions.get(controllerId)
export async function sendAccountButtonClickedEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeAccountButtonClickedSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending accountButtonClicked event:", error)
// Remove the subscription if there was an error
activeAccountButtonClickedSubscriptions.delete(responseStream)
}
})
if (!responseStream) {
console.log(`No active subscription for controller ${controllerId}`)
return
}
try {
const event: Empty = Empty.create({})
await responseStream(event, false)
} catch (error) {
console.error(`Error sending account button clicked event to controller ${controllerId}:`, error)
activeSubscriptions.delete(controllerId)
}
await Promise.all(promises)
}
@@ -1,42 +1,32 @@
import type { String as ProtoString, StringRequest } from "@shared/proto/cline/common"
import type { EmptyRequest, String as ProtoString } from "@shared/proto/cline/common"
import { getRequestRegistry, type StreamingResponseHandler } from "../grpc-handler"
import type { Controller } from "../index"
// Keep track of active addToInput subscriptions
const activeAddToInputSubscriptions = new Set<StreamingResponseHandler<ProtoString>>()
// Map client IDs to their subscription handlers for targeted sending
const addToInputSubscriptions = new Map<string, StreamingResponseHandler<ProtoString>>()
/**
* Subscribe to addToInput events
* @param controller The controller instance
* @param request The request containing the client ID
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToAddToInput(
_controller: Controller,
request: StringRequest,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<ProtoString>,
requestId?: string,
): Promise<void> {
const clientId = request.value
if (!clientId) {
throw new Error("Client ID is required for addToInput subscription")
}
console.log("[DEBUG] set up addToInput subscription")
console.log("[DEBUG] set up addToInput subscription for client:", clientId)
// Add this subscription to both the general set and the client-specific map
// Add this subscription to the active subscriptions
activeAddToInputSubscriptions.add(responseStream)
addToInputSubscriptions.set(clientId, responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeAddToInputSubscriptions.delete(responseStream)
addToInputSubscriptions.delete(clientId)
console.log("[DEBUG] Cleaned up addToInput subscription for client:", clientId)
console.log("[DEBUG] Cleaned up addToInput subscription")
}
// Register the cleanup function with the request registry if we have a requestId
@@ -70,33 +60,3 @@ export async function sendAddToInputEvent(text: string): Promise<void> {
await Promise.all(promises)
}
/**
* Send an addToInput event to a specific webview by client ID
* @param clientId The ID of the client to send the event to
* @param text The text to add to the input
*/
export async function sendAddToInputEventToClient(clientId: string, text: string): Promise<void> {
const responseStream = addToInputSubscriptions.get(clientId)
if (!responseStream) {
console.warn(`No addToInput subscription found for client ID: ${clientId}`)
return
}
try {
const event: ProtoString = {
value: text,
}
await responseStream(
event,
false, // Not the last message
)
console.log("[DEBUG] sending addToInput event to client", clientId, ":", text.length, "chars")
} catch (error) {
console.error(`Error sending addToInput event to client ${clientId}:`, error)
// Remove the subscription if there was an error
addToInputSubscriptions.delete(clientId)
// Also remove from the general set
activeAddToInputSubscriptions.delete(responseStream)
}
}
@@ -2,8 +2,8 @@ import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active chatButtonClicked subscriptions by controller ID
const activeChatButtonClickedSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
// Keep track of active chatButtonClicked subscriptions
const activeChatButtonClickedSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to chatButtonClicked events
@@ -13,20 +13,19 @@ const activeChatButtonClickedSubscriptions = new Map<string, StreamingResponseHa
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToChatButtonClicked(
controller: Controller,
_controller: Controller,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const controllerId = controller.id
console.log(`[DEBUG] set up chatButtonClicked subscription for controller ${controllerId}`)
console.log(`[DEBUG] set up chatButtonClicked subscription`)
// Add this subscription to the active subscriptions with the controller ID
activeChatButtonClickedSubscriptions.set(controllerId, responseStream)
// Add this subscription to the active subscriptions
activeChatButtonClickedSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeChatButtonClickedSubscriptions.delete(controllerId)
activeChatButtonClickedSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
@@ -36,27 +35,23 @@ export async function subscribeToChatButtonClicked(
}
/**
* Send a chatButtonClicked event to a specific controller's subscription
* @param controllerId The ID of the controller to send the event to
* Send a chatButtonClicked event to all active subscribers
*/
export async function sendChatButtonClickedEvent(controllerId: string): Promise<void> {
// Get the subscription for this specific controller
const responseStream = activeChatButtonClickedSubscriptions.get(controllerId)
export async function sendChatButtonClickedEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeChatButtonClickedSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending chatButtonClicked event:", error)
// Remove the subscription if there was an error
activeChatButtonClickedSubscriptions.delete(responseStream)
}
})
if (!responseStream) {
console.log(`[DEBUG] No active subscription for controller ${controllerId}`)
return
}
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error(`Error sending chatButtonClicked event to controller ${controllerId}:`, error)
// Remove the subscription if there was an error
activeChatButtonClickedSubscriptions.delete(controllerId)
}
await Promise.all(promises)
}
@@ -2,8 +2,8 @@ import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active didBecomeVisible subscriptions by controller ID
const activeDidBecomeVisibleSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
// Keep track of active didBecomeVisible subscriptions
const activeDidBecomeVisibleSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to didBecomeVisible events
@@ -13,20 +13,19 @@ const activeDidBecomeVisibleSubscriptions = new Map<string, StreamingResponseHan
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToDidBecomeVisible(
controller: Controller,
_controller: Controller,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const controllerId = controller.id
console.log(`[DEBUG] set up didBecomeVisible subscription for controller ${controllerId}`)
console.log(`[DEBUG] set up didBecomeVisible subscription`)
// Add this subscription to the active subscriptions with the controller ID
activeDidBecomeVisibleSubscriptions.set(controllerId, responseStream)
// Add this subscription to the active subscriptions
activeDidBecomeVisibleSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeDidBecomeVisibleSubscriptions.delete(controllerId)
activeDidBecomeVisibleSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
@@ -36,27 +35,23 @@ export async function subscribeToDidBecomeVisible(
}
/**
* Send a didBecomeVisible event to a specific controller's subscription
* @param controllerId The ID of the controller to send the event to
* Send a didBecomeVisible event to all active subscribers
*/
export async function sendDidBecomeVisibleEvent(controllerId: string): Promise<void> {
// Get the subscription for this specific controller
const responseStream = activeDidBecomeVisibleSubscriptions.get(controllerId)
export async function sendDidBecomeVisibleEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeDidBecomeVisibleSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending didBecomeVisible event:", error)
// Remove the subscription if there was an error
activeDidBecomeVisibleSubscriptions.delete(responseStream)
}
})
if (!responseStream) {
console.log(`[DEBUG] No active subscription for controller ${controllerId}`)
return
}
try {
const event: Empty = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error(`Error sending didBecomeVisible event to controller ${controllerId}:`, error)
// Remove the subscription if there was an error
activeDidBecomeVisibleSubscriptions.delete(controllerId)
}
await Promise.all(promises)
}
@@ -1,34 +1,29 @@
import { Empty, StringRequest } from "@shared/proto/cline/common"
import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import type { Controller } from "../index"
// Map client IDs to their subscription handlers
const focusChatInputSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
// Keep track of active focus chat input subscriptions
const focusChatInputSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to focus chat input events
* @param controller The controller instance
* @param request The request containing the client ID
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request
*/
export async function subscribeToFocusChatInput(
_controller: Controller,
request: StringRequest,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const clientId = request.value
if (!clientId) {
throw new Error("Client ID is required for focusChatInput subscription")
}
// Store this subscription with its client ID
focusChatInputSubscriptions.set(clientId, responseStream)
// Add this subscription to the active subscriptions
focusChatInputSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
focusChatInputSubscriptions.delete(clientId)
focusChatInputSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
@@ -38,25 +33,23 @@ export async function subscribeToFocusChatInput(
}
/**
* Send a focus chat input event to a specific webview by client ID
* @param clientId The ID of the client to send the event to
* Send a focus chat input event to all active subscribers
*/
export async function sendFocusChatInputEvent(clientId: string): Promise<void> {
const responseStream = focusChatInputSubscriptions.get(clientId)
if (!responseStream) {
console.warn(`No subscription found for client ID: ${clientId}`)
return
}
export async function sendFocusChatInputEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(focusChatInputSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending focus chat input event:", error)
// Remove the subscription if there was an error
focusChatInputSubscriptions.delete(responseStream)
}
})
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error(`Error sending focus chat input event to client ${clientId}:`, error)
// Remove the subscription if there was an error
focusChatInputSubscriptions.delete(clientId)
}
await Promise.all(promises)
}
@@ -1,30 +1,25 @@
import { Empty } from "@shared/proto/cline/common"
import { WebviewProviderType, WebviewProviderTypeRequest } from "@shared/proto/cline/ui"
import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active subscriptions with their provider type
const activeHistoryButtonClickedSubscriptions = new Map<StreamingResponseHandler<Empty>, WebviewProviderType>()
// Keep track of active history button clicked subscriptions
const activeHistoryButtonClickedSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to history button clicked events
* @param controller The controller instance
* @param request The webview provider type request
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToHistoryButtonClicked(
_controller: Controller,
request: WebviewProviderTypeRequest,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
// Extract the provider type from the request
const providerType = request.providerType
console.log(`[DEBUG] set up history button subscription for ${WebviewProviderType[providerType]} webview`)
// Add this subscription to the active subscriptions with its provider type
activeHistoryButtonClickedSubscriptions.set(responseStream, providerType)
// Add this subscription to the active subscriptions
activeHistoryButtonClickedSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
@@ -39,16 +34,10 @@ export async function subscribeToHistoryButtonClicked(
/**
* Send a history button clicked event to all active subscribers
* @param webviewType Optional filter to send only to a specific webview type
*/
export async function sendHistoryButtonClickedEvent(webviewType?: WebviewProviderType): Promise<void> {
// Send the event to all active subscribers matching the webview type (if specified)
const promises = Array.from(activeHistoryButtonClickedSubscriptions.entries()).map(async ([responseStream, providerType]) => {
// Skip subscribers of different types if webview type is specified
if (webviewType !== undefined && webviewType !== providerType) {
return
}
export async function sendHistoryButtonClickedEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeHistoryButtonClickedSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
@@ -56,7 +45,7 @@ export async function sendHistoryButtonClickedEvent(webviewType?: WebviewProvide
false, // Not the last message
)
} catch (error) {
console.error(`Error sending history button clicked event to ${WebviewProviderType[providerType]}:`, error)
console.error("Error sending history button clicked event:", error)
// Remove the subscription if there was an error
activeHistoryButtonClickedSubscriptions.delete(responseStream)
}
@@ -2,8 +2,8 @@ import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import { Controller } from "../index"
// Keep track of active mcpButtonClicked subscriptions by controller ID
const activeMcpButtonClickedSubscriptions = new Map<string, StreamingResponseHandler<Empty>>()
// Keep track of active mcpButtonClicked subscriptions
const activeMcpButtonClickedSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to mcpButtonClicked events
@@ -13,20 +13,19 @@ const activeMcpButtonClickedSubscriptions = new Map<string, StreamingResponseHan
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToMcpButtonClicked(
controller: Controller,
_controller: Controller,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const controllerId = controller.id
console.log(`[DEBUG] set up mcpButtonClicked subscription for controller ${controllerId}`)
console.log(`[DEBUG] set up mcpButtonClicked subscription`)
// Add this subscription to the active subscriptions with the controller ID
activeMcpButtonClickedSubscriptions.set(controllerId, responseStream)
// Add this subscription to the active subscriptions
activeMcpButtonClickedSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
activeMcpButtonClickedSubscriptions.delete(controllerId)
activeMcpButtonClickedSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
@@ -36,27 +35,23 @@ export async function subscribeToMcpButtonClicked(
}
/**
* Send a mcpButtonClicked event to a specific controller's subscription
* @param controllerId The ID of the controller to send the event to
* Send a mcpButtonClicked event to all active subscribers
*/
export async function sendMcpButtonClickedEvent(controllerId: string): Promise<void> {
// Get the subscription for this specific controller
const responseStream = activeMcpButtonClickedSubscriptions.get(controllerId)
export async function sendMcpButtonClickedEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeMcpButtonClickedSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error("Error sending mcpButtonClicked event:", error)
// Remove the subscription if there was an error
activeMcpButtonClickedSubscriptions.delete(responseStream)
}
})
if (!responseStream) {
console.error(`[DEBUG] No active subscription for controller ${controllerId}`)
return
}
try {
const event = Empty.create({})
await responseStream(
event,
false, // Not the last message
)
} catch (error) {
console.error(`Error sending mcpButtonClicked event to controller ${controllerId}:`, error)
// Remove the subscription if there was an error
activeMcpButtonClickedSubscriptions.delete(controllerId)
}
await Promise.all(promises)
}
@@ -1,33 +1,29 @@
import { Empty } from "@shared/proto/cline/common"
import { WebviewProviderType, WebviewProviderTypeRequest } from "@shared/proto/cline/ui"
import { Empty, EmptyRequest } from "@shared/proto/cline/common"
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
import type { Controller } from "../index"
// Track subscriptions with their provider type
const subscriptions = new Map<StreamingResponseHandler<Empty>, WebviewProviderType>()
// Keep track of active settings button clicked subscriptions
const activeSettingsButtonClickedSubscriptions = new Set<StreamingResponseHandler<Empty>>()
/**
* Subscribe to settings button clicked events
* @param controller The controller instance
* @param request The request with provider type
* @param request The empty request
* @param responseStream The streaming response handler
* @param requestId The ID of the request (passed by the gRPC handler)
*/
export async function subscribeToSettingsButtonClicked(
_controller: Controller,
request: WebviewProviderTypeRequest,
_request: EmptyRequest,
responseStream: StreamingResponseHandler<Empty>,
requestId?: string,
): Promise<void> {
const providerType = request.providerType
console.log(`[DEBUG] set up settings button subscription for ${WebviewProviderType[providerType]} webview`)
// Store the subscription with its provider type
subscriptions.set(responseStream, providerType)
// Add this subscription to the active subscriptions
activeSettingsButtonClickedSubscriptions.add(responseStream)
// Register cleanup when the connection is closed
const cleanup = () => {
subscriptions.delete(responseStream)
activeSettingsButtonClickedSubscriptions.delete(responseStream)
}
// Register the cleanup function with the request registry if we have a requestId
@@ -37,23 +33,17 @@ export async function subscribeToSettingsButtonClicked(
}
/**
* Send a settings button clicked event to active subscribers of matching provider type
* @param webviewType The type of webview that triggered the event
* Send a settings button clicked event to all active subscribers
*/
export async function sendSettingsButtonClickedEvent(webviewType?: WebviewProviderType): Promise<void> {
// Process all subscriptions, filtering based on the source
const promises = Array.from(subscriptions.entries()).map(async ([responseStream, providerType]) => {
// If webviewType is provided, only send to subscribers of the same type
if (webviewType !== undefined && webviewType !== providerType) {
return // Skip subscribers of different types
}
export async function sendSettingsButtonClickedEvent(): Promise<void> {
// Send the event to all active subscribers
const promises = Array.from(activeSettingsButtonClickedSubscriptions).map(async (responseStream) => {
try {
const event = Empty.create({})
await responseStream(event, false) // Not the last message
} catch (error) {
console.error(`Error sending settings button clicked event to ${WebviewProviderType[providerType]}:`, error)
subscriptions.delete(responseStream)
console.error("Error sending settings button clicked event:", error)
activeSettingsButtonClickedSubscriptions.delete(responseStream)
}
})
+1 -2
View File
@@ -9,7 +9,6 @@ import { getCommitInfo, getWorkingState } from "@utils/git"
import fs from "fs/promises"
import { isBinaryFile } from "isbinaryfile"
import * as path from "path"
import * as vscode from "vscode"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/host/window"
import { DiagnosticSeverity } from "@/shared/proto/index.cline"
@@ -38,7 +37,7 @@ export async function openMention(mention?: string): Promise<void> {
} else if (mention === "problems") {
await HostProvider.workspace.openProblemsPanel({})
} else if (mention === "terminal") {
vscode.commands.executeCommand("workbench.action.terminal.focus")
await HostProvider.workspace.openTerminalPanel({})
} else if (mention.startsWith("http")) {
await openExternal(mention)
}
@@ -697,8 +697,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -555,8 +555,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -521,8 +521,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -496,8 +496,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -535,8 +535,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -537,8 +537,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -503,8 +503,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -480,8 +480,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -517,8 +517,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
====
@@ -70,8 +70,9 @@ You have access to two tools for working with files: **write_to_file** and **rep
1. Before editing, assess the scope of your changes and decide which tool to use.
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
3. For major overhauls or initial file creation, rely on write_to_file.
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
4. For major overhauls or initial file creation, rely on write_to_file.
5. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.`
export async function getEditingFilesSection(variant: PromptVariant, context: SystemPromptContext): Promise<string> {
+2 -2
View File
@@ -165,7 +165,7 @@ export class StateManager {
}
try {
const taskSettings = await readTaskSettingsFromStorage(this.context, taskId)
const taskSettings = await readTaskSettingsFromStorage(taskId)
// Populate task cache with loaded settings
Object.assign(this.taskStateCache, taskSettings)
} catch (error) {
@@ -785,7 +785,7 @@ export class StateManager {
try {
await Promise.all(
Array.from(keys).map((key) => {
return writeTaskSettingsToStorage(this.context, taskId, { [key]: this.taskStateCache[key] })
return writeTaskSettingsToStorage(taskId, { [key]: this.taskStateCache[key] })
}),
)
} catch (error) {
+29 -45
View File
@@ -7,7 +7,6 @@ import { fileExistsAtPath } from "@utils/fs"
import fs from "fs/promises"
import os from "os"
import * as path from "path"
import * as vscode from "vscode"
import { HostProvider } from "@/hosts/host-provider"
import { GlobalState } from "./state-keys"
@@ -64,11 +63,8 @@ export async function getDocumentsPath(): Promise<string> {
return path.join(os.homedir(), "Documents")
}
export async function ensureTaskDirectoryExists(context: vscode.ExtensionContext, taskId: string): Promise<string> {
const globalStoragePath = context.globalStorageUri.fsPath
const taskDir = path.join(globalStoragePath, "tasks", taskId)
await fs.mkdir(taskDir, { recursive: true })
return taskDir
export async function ensureTaskDirectoryExists(taskId: string): Promise<string> {
return getGlobalStorageDir("tasks", taskId)
}
export async function ensureRulesDirectoryExists(): Promise<string> {
@@ -104,17 +100,12 @@ export async function ensureMcpServersDirectoryExists(): Promise<string> {
return mcpServersDir
}
export async function ensureSettingsDirectoryExists(context: vscode.ExtensionContext): Promise<string> {
const settingsDir = path.join(context.globalStorageUri.fsPath, "settings")
await fs.mkdir(settingsDir, { recursive: true })
return settingsDir
export async function ensureSettingsDirectoryExists(): Promise<string> {
return getGlobalStorageDir("settings")
}
export async function getSavedApiConversationHistory(
context: vscode.ExtensionContext,
taskId: string,
): Promise<Anthropic.MessageParam[]> {
const filePath = path.join(await ensureTaskDirectoryExists(context, taskId), GlobalFileNames.apiConversationHistory)
export async function getSavedApiConversationHistory(taskId: string): Promise<Anthropic.MessageParam[]> {
const filePath = path.join(await ensureTaskDirectoryExists(taskId), GlobalFileNames.apiConversationHistory)
const fileExists = await fileExistsAtPath(filePath)
if (fileExists) {
return JSON.parse(await fs.readFile(filePath, "utf8"))
@@ -122,13 +113,9 @@ export async function getSavedApiConversationHistory(
return []
}
export async function saveApiConversationHistory(
context: vscode.ExtensionContext,
taskId: string,
apiConversationHistory: Anthropic.MessageParam[],
) {
export async function saveApiConversationHistory(taskId: string, apiConversationHistory: Anthropic.MessageParam[]) {
try {
const filePath = path.join(await ensureTaskDirectoryExists(context, taskId), GlobalFileNames.apiConversationHistory)
const filePath = path.join(await ensureTaskDirectoryExists(taskId), GlobalFileNames.apiConversationHistory)
await fs.writeFile(filePath, JSON.stringify(apiConversationHistory))
} catch (error) {
// in the off chance this fails, we don't want to stop the task
@@ -136,13 +123,13 @@ export async function saveApiConversationHistory(
}
}
export async function getSavedClineMessages(context: vscode.ExtensionContext, taskId: string): Promise<ClineMessage[]> {
const filePath = path.join(await ensureTaskDirectoryExists(context, taskId), GlobalFileNames.uiMessages)
export async function getSavedClineMessages(taskId: string): Promise<ClineMessage[]> {
const filePath = path.join(await ensureTaskDirectoryExists(taskId), GlobalFileNames.uiMessages)
if (await fileExistsAtPath(filePath)) {
return JSON.parse(await fs.readFile(filePath, "utf8"))
} else {
// check old location
const oldPath = path.join(await ensureTaskDirectoryExists(context, taskId), "claude_messages.json")
const oldPath = path.join(await ensureTaskDirectoryExists(taskId), "claude_messages.json")
if (await fileExistsAtPath(oldPath)) {
const data = JSON.parse(await fs.readFile(oldPath, "utf8"))
await fs.unlink(oldPath) // remove old file
@@ -152,9 +139,9 @@ export async function getSavedClineMessages(context: vscode.ExtensionContext, ta
return []
}
export async function saveClineMessages(context: vscode.ExtensionContext, taskId: string, uiMessages: ClineMessage[]) {
export async function saveClineMessages(taskId: string, uiMessages: ClineMessage[]) {
try {
const taskDir = await ensureTaskDirectoryExists(context, taskId)
const taskDir = await ensureTaskDirectoryExists(taskId)
const filePath = path.join(taskDir, GlobalFileNames.uiMessages)
await fs.writeFile(filePath, JSON.stringify(uiMessages))
} catch (error) {
@@ -162,8 +149,8 @@ export async function saveClineMessages(context: vscode.ExtensionContext, taskId
}
}
export async function getTaskMetadata(context: vscode.ExtensionContext, taskId: string): Promise<TaskMetadata> {
const filePath = path.join(await ensureTaskDirectoryExists(context, taskId), GlobalFileNames.taskMetadata)
export async function getTaskMetadata(taskId: string): Promise<TaskMetadata> {
const filePath = path.join(await ensureTaskDirectoryExists(taskId), GlobalFileNames.taskMetadata)
try {
if (await fileExistsAtPath(filePath)) {
return JSON.parse(await fs.readFile(filePath, "utf8"))
@@ -174,9 +161,9 @@ export async function getTaskMetadata(context: vscode.ExtensionContext, taskId:
return { files_in_context: [], model_usage: [] }
}
export async function saveTaskMetadata(context: vscode.ExtensionContext, taskId: string, metadata: TaskMetadata) {
export async function saveTaskMetadata(taskId: string, metadata: TaskMetadata) {
try {
const taskDir = await ensureTaskDirectoryExists(context, taskId)
const taskDir = await ensureTaskDirectoryExists(taskId)
const filePath = path.join(taskDir, GlobalFileNames.taskMetadata)
await fs.writeFile(filePath, JSON.stringify(metadata, null, 2))
} catch (error) {
@@ -185,13 +172,17 @@ export async function saveTaskMetadata(context: vscode.ExtensionContext, taskId:
}
export async function ensureStateDirectoryExists(): Promise<string> {
const stateDir = path.join(HostProvider.get().globalStorageFsPath, "state")
await fs.mkdir(stateDir, { recursive: true })
return stateDir
return getGlobalStorageDir("state")
}
export async function ensureCacheDirectoryExists(): Promise<string> {
return HostProvider.getGlobalStorageDir("cache")
return getGlobalStorageDir("cache")
}
async function getGlobalStorageDir(...subdirs: string[]) {
const fullPath = path.resolve(HostProvider.get().globalStorageFsPath, ...subdirs)
await fs.mkdir(fullPath, { recursive: true })
return fullPath
}
export async function getTaskHistoryStateFilePath(): Promise<string> {
@@ -233,12 +224,9 @@ export async function writeTaskHistoryToState(items: HistoryItem[]): Promise<voi
}
}
export async function readTaskSettingsFromStorage(
context: vscode.ExtensionContext,
taskId: string,
): Promise<Partial<GlobalState>> {
export async function readTaskSettingsFromStorage(taskId: string): Promise<Partial<GlobalState>> {
try {
const taskDirectoryFilePath = await ensureTaskDirectoryExists(context, taskId)
const taskDirectoryFilePath = await ensureTaskDirectoryExists(taskId)
const settingsFilePath = path.join(taskDirectoryFilePath, "settings.json")
if (await fileExistsAtPath(settingsFilePath)) {
@@ -254,13 +242,9 @@ export async function readTaskSettingsFromStorage(
}
}
export async function writeTaskSettingsToStorage(
context: vscode.ExtensionContext,
taskId: string,
settings: Partial<GlobalState>,
) {
export async function writeTaskSettingsToStorage(taskId: string, settings: Partial<GlobalState>) {
try {
const taskDirectoryFilePath = await ensureTaskDirectoryExists(context, taskId)
const taskDirectoryFilePath = await ensureTaskDirectoryExists(taskId)
const settingsFilePath = path.join(taskDirectoryFilePath, "settings.json")
let existingSettings = {}
+1
View File
@@ -41,6 +41,7 @@ export interface GlobalState {
primaryRootIndex: number
multiRootEnabled: boolean
lastDismissedInfoBannerVersion: number
lastDismissedModelBannerVersion: number
}
export interface Settings {
+6 -7
View File
@@ -238,6 +238,9 @@ export async function readGlobalStateFromDisk(context: ExtensionContext): Promis
context.globalState.get<GlobalStateAndSettings["mcpMarketplaceCatalog"]>("mcpMarketplaceCatalog")
const lastDismissedInfoBannerVersion =
context.globalState.get<GlobalStateAndSettings["lastDismissedInfoBannerVersion"]>("lastDismissedInfoBannerVersion")
const lastDismissedModelBannerVersion = context.globalState.get<
GlobalStateAndSettings["lastDismissedModelBannerVersion"]
>("lastDismissedModelBannerVersion")
const qwenCodeOauthPath = context.globalState.get<GlobalStateAndSettings["qwenCodeOauthPath"]>("qwenCodeOauthPath")
const customPrompt = context.globalState.get<GlobalStateAndSettings["customPrompt"]>("customPrompt")
const autoCondenseThreshold =
@@ -396,13 +399,8 @@ export async function readGlobalStateFromDisk(context: ExtensionContext): Promis
if (planActSeparateModelsSettingRaw === true || planActSeparateModelsSettingRaw === false) {
planActSeparateModelsSetting = planActSeparateModelsSettingRaw
} else {
// default to true for existing users
if (planModeApiProvider) {
planActSeparateModelsSetting = true
} else {
// default to false for new users
planActSeparateModelsSetting = false
}
// default to false
planActSeparateModelsSetting = false
}
const taskHistory = await readTaskHistoryFromState()
@@ -562,6 +560,7 @@ export async function readGlobalStateFromDisk(context: ExtensionContext): Promis
customPrompt,
autoCondenseThreshold: autoCondenseThreshold || 0.75, // default to 0.75 if not set
lastDismissedInfoBannerVersion: lastDismissedInfoBannerVersion ?? 0,
lastDismissedModelBannerVersion: lastDismissedModelBannerVersion ?? 0,
// Multi-root workspace support
workspaceRoots,
primaryRootIndex: primaryRootIndex ?? 0,
+4 -9
View File
@@ -218,15 +218,10 @@ export class ToolExecutor {
* Updates the browser settings
*/
public async applyLatestBrowserSettings() {
if (this.context) {
await this.browserSession.dispose()
const apiHandlerModel = this.api.getModel()
const useWebp = this.api ? !modelDoesntSupportWebp(apiHandlerModel) : true
this.browserSession = new BrowserSession(this.context, this.stateManager, useWebp)
} else {
console.warn("no controller context available for browserSession")
}
await this.browserSession.dispose()
const apiHandlerModel = this.api.getModel()
const useWebp = this.api ? !modelDoesntSupportWebp(apiHandlerModel) : true
this.browserSession = new BrowserSession(this.stateManager, useWebp)
return this.browserSession
}
+2 -7
View File
@@ -1,7 +1,6 @@
import { isFocusChainItem } from "@shared/focus-chain-utils"
import * as fs from "fs/promises"
import * as path from "path"
import * as vscode from "vscode"
import { ensureTaskDirectoryExists } from "../../storage/disk"
/**
@@ -49,12 +48,8 @@ export function extractFocusChainListFromText(text: string): string | null {
* Ensure a focusChain file exists, creating it with provided content if it doesn't exist
* Returns the file path
*/
export async function ensureFocusChainFile(
context: vscode.ExtensionContext,
taskId: string,
initialFocusChainContent?: string,
): Promise<string> {
const taskDir = await ensureTaskDirectoryExists(context, taskId)
export async function ensureFocusChainFile(taskId: string, initialFocusChainContent?: string): Promise<string> {
const taskDir = await ensureTaskDirectoryExists(taskId)
const focusChainFilePath = getFocusChainFilePath(taskDir, taskId)
// Check if file exists
+3 -7
View File
@@ -1,7 +1,6 @@
import { FocusChainSettings } from "@shared/FocusChainSettings"
import * as chokidar from "chokidar"
import * as fs from "fs/promises"
import * as vscode from "vscode"
import { telemetryService } from "@/services/telemetry"
import { ClineSay } from "../../../shared/ExtensionMessage"
import { Mode } from "../../../shared/storage/types"
@@ -21,7 +20,6 @@ export interface FocusChainDependencies {
taskId: string
taskState: TaskState
mode: Mode
context: vscode.ExtensionContext
stateManager: StateManager
postStateToWebview: () => Promise<void>
say: (type: ClineSay, text?: string, images?: string[], files?: string[], partial?: boolean) => Promise<number | undefined>
@@ -31,7 +29,6 @@ export interface FocusChainDependencies {
export class FocusChainManager {
private taskId: string
private taskState: TaskState
private context: vscode.ExtensionContext
private stateManager: StateManager
private postStateToWebview: () => Promise<void>
private say: (
@@ -49,7 +46,6 @@ export class FocusChainManager {
constructor(dependencies: FocusChainDependencies) {
this.taskId = dependencies.taskId
this.taskState = dependencies.taskState
this.context = dependencies.context
this.stateManager = dependencies.stateManager
this.postStateToWebview = dependencies.postStateToWebview
this.say = dependencies.say
@@ -64,7 +60,7 @@ export class FocusChainManager {
*/
public async setupFocusChainFileWatcher() {
try {
const taskDir = await ensureTaskDirectoryExists(this.context, this.taskId)
const taskDir = await ensureTaskDirectoryExists(this.taskId)
const focusChainFilePath = getFocusChainFilePath(taskDir, this.taskId)
// Initialize chokidar watcher
@@ -312,7 +308,7 @@ ${listInstrunctionsReminder}\n`
*/
private async readFocusChainFromDisk(): Promise<string | null> {
try {
const taskDir = await ensureTaskDirectoryExists(this.context, this.taskId)
const taskDir = await ensureTaskDirectoryExists(this.taskId)
const todoFilePath = getFocusChainFilePath(taskDir, this.taskId)
const markdownContent = await fs.readFile(todoFilePath, "utf8")
const todoList = extractFocusChainListFromText(markdownContent)
@@ -340,7 +336,7 @@ ${listInstrunctionsReminder}\n`
*/
private async writeFocusChainToDisk(todoList: string): Promise<void> {
try {
const taskDir = await ensureTaskDirectoryExists(this.context, this.taskId)
const taskDir = await ensureTaskDirectoryExists(this.taskId)
const todoFilePath = getFocusChainFilePath(taskDir, this.taskId)
const fileContent = createFocusChainMarkdownContent(this.taskId, todoList)
await writeFile(todoFilePath, fileContent, "utf8")
+90 -74
View File
@@ -85,6 +85,26 @@ import { detectAvailableCliTools, updateApiReqMsg } from "./utils"
export type ToolResponse = string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam>
type UserContent = Array<Anthropic.ContentBlockParam>
type TaskParams = {
controller: Controller
mcpHub: McpHub
updateTaskHistory: (historyItem: HistoryItem) => Promise<HistoryItem[]>
postStateToWebview: () => Promise<void>
reinitExistingTaskFromId: (taskId: string) => Promise<void>
cancelTask: () => Promise<void>
shellIntegrationTimeout: number
terminalReuseEnabled: boolean
terminalOutputLineLimit: number
defaultTerminalProfile: string
cwd: string
stateManager: StateManager
workspaceManager?: WorkspaceRootManager
task?: string
images?: string[]
files?: string[]
historyItem?: HistoryItem
}
export class Task {
// Core task variables
readonly taskId: string
@@ -95,9 +115,6 @@ export class Task {
taskState: TaskState
// Task configuration
private enableCheckpoints: boolean
// Core dependencies
private controller: Controller
private mcpHub: McpHub
@@ -135,26 +152,27 @@ export class Task {
// Workspace manager
workspaceManager?: WorkspaceRootManager
constructor(
controller: Controller,
mcpHub: McpHub,
updateTaskHistory: (historyItem: HistoryItem) => Promise<HistoryItem[]>,
postStateToWebview: () => Promise<void>,
reinitExistingTaskFromId: (taskId: string) => Promise<void>,
cancelTask: () => Promise<void>,
shellIntegrationTimeout: number,
terminalReuseEnabled: boolean,
terminalOutputLineLimit: number,
defaultTerminalProfile: string,
enableCheckpointsSetting: boolean,
cwd: string,
stateManager: StateManager,
workspaceManager?: WorkspaceRootManager,
task?: string,
images?: string[],
files?: string[],
historyItem?: HistoryItem,
) {
constructor(params: TaskParams) {
const {
controller,
mcpHub,
updateTaskHistory,
postStateToWebview,
reinitExistingTaskFromId,
cancelTask,
shellIntegrationTimeout,
terminalReuseEnabled,
terminalOutputLineLimit,
defaultTerminalProfile,
cwd,
stateManager,
workspaceManager,
task,
images,
files,
historyItem,
} = params
this.taskInitializationStartTime = performance.now()
this.taskState = new TaskState()
this.controller = controller
@@ -183,10 +201,9 @@ export class Task {
this.terminalManager.setDefaultTerminalProfile(defaultTerminalProfile)
this.urlContentFetcher = new UrlContentFetcher(controller.context)
this.browserSession = new BrowserSession(controller.context, stateManager)
this.browserSession = new BrowserSession(stateManager)
this.contextManager = new ContextManager()
this.diffViewProvider = HostProvider.get().createDiffViewProvider()
this.enableCheckpoints = enableCheckpointsSetting
this.cwd = cwd
this.stateManager = stateManager
this.workspaceManager = workspaceManager
@@ -214,7 +231,6 @@ export class Task {
}
this.messageStateHandler = new MessageStateHandler({
context: controller.context,
taskId: this.taskId,
ulid: this.ulid,
taskState: this.taskState,
@@ -224,7 +240,7 @@ export class Task {
// Initialize file context tracker
this.fileContextTracker = new FileContextTracker(controller, this.taskId)
this.modelContextTracker = new ModelContextTracker(controller.context, this.taskId)
this.modelContextTracker = new ModelContextTracker(this.taskId)
// Initialize focus chain manager only if enabled
const focusChainSettings = this.stateManager.getGlobalSettingsKey("focusChainSettings")
@@ -233,7 +249,6 @@ export class Task {
taskId: this.taskId,
taskState: this.taskState,
mode: this.stateManager.getGlobalSettingsKey("mode"),
context: this.getContext(),
stateManager: this.stateManager,
postStateToWebview: this.postStateToWebview,
say: this.say.bind(this),
@@ -241,16 +256,16 @@ export class Task {
})
}
const enableCheckpoints = this.stateManager.getGlobalSettingsKey("enableCheckpointsSetting")
// Initialize checkpoint manager based on workspace configuration
try {
this.checkpointManager = buildCheckpointManager({
taskId: this.taskId,
enableCheckpoints: enableCheckpointsSetting,
messageStateHandler: this.messageStateHandler,
fileContextTracker: this.fileContextTracker,
diffViewProvider: this.diffViewProvider,
taskState: this.taskState,
context: controller.context,
workspaceManager: this.workspaceManager,
updateTaskHistory: this.updateTaskHistory,
say: this.say.bind(this),
@@ -258,13 +273,14 @@ export class Task {
postStateToWebview: this.postStateToWebview,
initialConversationHistoryDeletedRange: this.taskState.conversationHistoryDeletedRange,
initialCheckpointManagerErrorMessage: this.taskState.checkpointManagerErrorMessage,
stateManager: this.stateManager,
})
// If multi-root, kick off non-blocking initialization
if (
shouldUseMultiRoot({
workspaceManager: this.workspaceManager,
enableCheckpoints: enableCheckpointsSetting,
enableCheckpoints: enableCheckpoints,
isMultiRootEnabled: featureFlagsService.getMultiRootEnabled(),
})
) {
@@ -275,7 +291,7 @@ export class Task {
}
} catch (error) {
console.error("Failed to initialize checkpoint manager:", error)
if (enableCheckpointsSetting) {
if (enableCheckpoints) {
const errorMessage = error instanceof Error ? error.message : "Unknown error"
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
@@ -397,16 +413,6 @@ export class Task {
this.taskState.consecutiveAutoApprovedRequestsCount = 0
}
// 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 {
const context = this.controller.context
if (!context) {
throw new Error("Unable to access extension context")
}
return context
}
// Communicate with webview
// partial has three valid states true (partial message), false (completion of partial message), undefined (individual complete message)
@@ -718,7 +724,7 @@ export class Task {
// Optionally, inform the user or handle the error appropriately
}
const savedClineMessages = await getSavedClineMessages(this.getContext(), this.taskId)
const savedClineMessages = await getSavedClineMessages(this.taskId)
// Remove any resume messages that may have been added before
const lastRelevantMessageIndex = findLastIndex(
@@ -740,18 +746,16 @@ export class Task {
}
await this.messageStateHandler.overwriteClineMessages(savedClineMessages)
this.messageStateHandler.setClineMessages(await getSavedClineMessages(this.getContext(), this.taskId))
this.messageStateHandler.setClineMessages(await getSavedClineMessages(this.taskId))
// Now present the cline messages to the user and ask if they want to resume (NOTE: we ran into a bug before where the apiconversationhistory wouldn't be initialized when opening a old task, and it was because we were waiting for resume)
// This is important in case the user deletes messages without resuming the task first
const context = this.getContext()
const savedApiConversationHistory = await getSavedApiConversationHistory(context, this.taskId)
const savedApiConversationHistory = await getSavedApiConversationHistory(this.taskId)
this.messageStateHandler.setApiConversationHistory(savedApiConversationHistory)
// load the context history state
const _taskDir = await ensureTaskDirectoryExists(context, this.taskId)
await this.contextManager.initializeContextHistory(await ensureTaskDirectoryExists(this.getContext(), this.taskId))
await ensureTaskDirectoryExists(this.taskId)
await this.contextManager.initializeContextHistory(await ensureTaskDirectoryExists(this.taskId))
const lastClineMessage = this.messageStateHandler
.getClineMessages()
@@ -783,7 +787,6 @@ export class Task {
// need to make sure that the api conversation history can be resumed by the api, even if it goes out of sync with cline messages
const existingApiConversationHistory: Anthropic.Messages.MessageParam[] = await getSavedApiConversationHistory(
this.getContext(),
this.taskId,
)
@@ -1044,16 +1047,15 @@ export class Task {
let outputBuffer: string[] = []
let outputBufferSize: number = 0
let chunkTimer: NodeJS.Timeout | null = null
let chunkEnroute = false
// Track if buffer gets stuck
// Track if buffer gets stuck (correlated with PROCESS_WHILE_RUNNING to indicate genuine technical issues)
let bufferStuckTimer: NodeJS.Timeout | null = null
const BUFFER_STUCK_TIMEOUT_MS = 6000 // 6 seconds
const flushBuffer = async (force = false) => {
if (chunkEnroute || outputBuffer.length === 0) {
if (force && !chunkEnroute && outputBuffer.length > 0) {
// If force is true and no chunkEnroute, flush anyway
if (outputBuffer.length === 0) {
if (force) {
// If force is true, flush anyway
} else {
return
}
@@ -1061,7 +1063,6 @@ export class Task {
const chunk = outputBuffer.join("\n")
outputBuffer = []
outputBufferSize = 0
chunkEnroute = true
// Start timer to detect if buffer gets stuck
bufferStuckTimer = setTimeout(() => {
@@ -1083,19 +1084,21 @@ export class Task {
}
didContinue = true
process.continue()
// If more output accumulated, flush again
if (outputBuffer.length > 0) {
await flushBuffer()
}
} catch {
Logger.error("Error while asking for command output")
} finally {
// If the command finishes execution before the 'command_output' ask promise resolves (in other words before the user responded to the ask, which is expected when the command finishes execution first), this block is reached. This is expected and safe to ignore, as no further handling is required.
// Clear the stuck timer
if (bufferStuckTimer) {
clearTimeout(bufferStuckTimer)
bufferStuckTimer = null
}
chunkEnroute = false
// If more output accumulated while chunkEnroute, flush again
if (outputBuffer.length > 0) {
await flushBuffer()
}
}
}
@@ -1291,7 +1294,7 @@ export class Task {
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.contextManager.triggerApplyStandardContextTruncationNoticeChange(
Date.now(),
await ensureTaskDirectoryExists(this.getContext(), this.taskId),
await ensureTaskDirectoryExists(this.taskId),
apiConversationHistory,
)
@@ -1380,7 +1383,7 @@ export class Task {
this.api,
this.taskState.conversationHistoryDeletedRange,
previousApiReqIndex,
await ensureTaskDirectoryExists(this.getContext(), this.taskId),
await ensureTaskDirectoryExists(this.taskId),
this.stateManager.getGlobalSettingsKey("useAutoCondense"),
)
@@ -1736,10 +1739,12 @@ export class Task {
}),
)
const enableCheckpoints = this.stateManager.getGlobalSettingsKey("enableCheckpointsSetting")
// Initialize checkpointManager first if enabled and it's the first request
if (
isFirstRequest &&
this.enableCheckpoints &&
enableCheckpoints &&
this.checkpointManager && // TODO REVIEW: may be able to implement a replacement for the 15s timer
!this.taskState.checkpointManagerErrorMessage
) {
@@ -1758,24 +1763,35 @@ export class Task {
// Now, if it's the first request AND checkpoints are enabled AND tracker was successfully initialized,
// then say "checkpoint_created" and perform the commit.
if (isFirstRequest && this.enableCheckpoints && this.checkpointManager) {
const commitHash = await this.checkpointManager.commit() // Actual commit
if (isFirstRequest && enableCheckpoints && this.checkpointManager) {
await this.say("checkpoint_created") // Now this is conditional
const lastCheckpointMessageIndex = findLastIndex(
this.messageStateHandler.getClineMessages(),
(m) => m.say === "checkpoint_created",
)
if (lastCheckpointMessageIndex !== -1) {
await this.messageStateHandler.updateClineMessage(lastCheckpointMessageIndex, {
lastCheckpointHash: commitHash,
})
// saveClineMessagesAndUpdateHistory will be called later after API response,
// so no need to call it here unless this is the only modification to this message.
// For now, assuming it's handled later.
this.checkpointManager
?.commit()
.then(async (commitHash) => {
if (commitHash) {
await this.messageStateHandler.updateClineMessage(lastCheckpointMessageIndex, {
lastCheckpointHash: commitHash,
})
// saveClineMessagesAndUpdateHistory will be called later after API response,
// so no need to call it here unless this is the only modification to this message.
// For now, assuming it's handled later.
}
})
.catch((error) => {
console.error(
`[TaskCheckpointManager] Failed to create checkpoint commit for task ${this.taskId}:`,
error,
)
})
}
} else if (
isFirstRequest &&
this.enableCheckpoints &&
enableCheckpoints &&
!this.checkpointManager &&
this.taskState.checkpointManagerErrorMessage
) {
@@ -1904,7 +1920,7 @@ export class Task {
// Capture task initialization timing telemetry for the first API request
if (isFirstRequest) {
const durationMs = Math.round(performance.now() - this.taskInitializationStartTime)
telemetryService.captureTaskInitialization(this.ulid, this.taskId, durationMs, this.enableCheckpoints)
telemetryService.captureTaskInitialization(this.ulid, this.taskId, durationMs, enableCheckpoints)
}
// since we sent off a placeholder api_req_started message to update the webview while waiting to actually start the API request (to load potential details for example), we need to update the text of that message
+4 -10
View File
@@ -1,7 +1,6 @@
import Anthropic from "@anthropic-ai/sdk"
import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker"
import getFolderSize from "get-folder-size"
import * as vscode from "vscode"
import { findLastIndex } from "@/shared/array"
import { combineApiRequests } from "@/shared/combineApiRequests"
import { combineCommandSequences } from "@/shared/combineCommandSequences"
@@ -13,7 +12,6 @@ import { ensureTaskDirectoryExists, saveApiConversationHistory, saveClineMessage
import { TaskState } from "./TaskState"
interface MessageStateHandlerParams {
context: vscode.ExtensionContext
taskId: string
ulid: string
taskIsFavorited?: boolean
@@ -27,21 +25,17 @@ export class MessageStateHandler {
private clineMessages: ClineMessage[] = []
private taskIsFavorited: boolean
private checkpointTracker: CheckpointTracker | undefined
private checkpointManagerErrorMessage: string | undefined
private updateTaskHistory: (historyItem: HistoryItem) => Promise<HistoryItem[]>
private context: vscode.ExtensionContext
private taskId: string
private ulid: string
private taskState: TaskState
constructor(params: MessageStateHandlerParams) {
this.context = params.context
this.taskId = params.taskId
this.ulid = params.ulid
this.taskState = params.taskState
this.taskIsFavorited = params.taskIsFavorited ?? false
this.updateTaskHistory = params.updateTaskHistory
this.checkpointManagerErrorMessage = this.taskState.checkpointManagerErrorMessage
}
setCheckpointTracker(tracker: CheckpointTracker | undefined) {
@@ -66,7 +60,7 @@ export class MessageStateHandler {
async saveClineMessagesAndUpdateHistory(): Promise<void> {
try {
await saveClineMessages(this.context, this.taskId, this.clineMessages)
await saveClineMessages(this.taskId, this.clineMessages)
// combined as they are in ChatView
const apiMetrics = getApiMetrics(combineApiRequests(combineCommandSequences(this.clineMessages.slice(1))))
@@ -78,7 +72,7 @@ export class MessageStateHandler {
(message) => !(message.ask === "resume_task" || message.ask === "resume_completed_task"),
)
]
const taskDir = await ensureTaskDirectoryExists(this.context, this.taskId)
const taskDir = await ensureTaskDirectoryExists(this.taskId)
let taskDirSize = 0
try {
// getFolderSize.loose silently ignores errors
@@ -112,12 +106,12 @@ export class MessageStateHandler {
async addToApiConversationHistory(message: Anthropic.MessageParam) {
this.apiConversationHistory.push(message)
await saveApiConversationHistory(this.context, this.taskId, this.apiConversationHistory)
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
}
async overwriteApiConversationHistory(newHistory: Anthropic.MessageParam[]): Promise<void> {
this.apiConversationHistory = newHistory
await saveApiConversationHistory(this.context, this.taskId, this.apiConversationHistory)
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
}
async addToClineMessages(message: ClineMessage) {
@@ -70,7 +70,7 @@ export class CondenseHandler implements IToolHandler, IPartialBlockHandler {
await config.messageState.saveClineMessagesAndUpdateHistory()
await config.services.contextManager.triggerApplyStandardContextTruncationNoticeChange(
Date.now(),
await ensureTaskDirectoryExists(config.context, config.taskId),
await ensureTaskDirectoryExists(config.taskId),
apiConversationHistory,
)
@@ -56,7 +56,7 @@ export class SummarizeTaskHandler implements IToolHandler, IPartialBlockHandler
await config.messageState.saveClineMessagesAndUpdateHistory()
await config.services.contextManager.triggerApplyStandardContextTruncationNoticeChange(
Date.now(),
await ensureTaskDirectoryExists(config.context, config.taskId),
await ensureTaskDirectoryExists(config.taskId),
apiConversationHistory,
)
+15 -95
View File
@@ -1,108 +1,42 @@
import path from "node:path"
import { Controller } from "@core/controller/index"
import { findLast } from "@shared/array"
import axios from "axios"
import { readFile } from "fs/promises"
import { v4 as uuidv4 } from "uuid"
import * as vscode from "vscode"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/host/window"
import { WebviewProviderType } from "@/shared/webview/types"
import { getNonce } from "./getNonce"
export abstract class WebviewProvider {
private static activeInstances: Set<WebviewProvider> = new Set()
private static clientIdMap = new Map<WebviewProvider, string>()
private static instance: WebviewProvider | null = null
controller: Controller
private clientId: string
private static lastActiveControllerId: string | null = null
constructor(
readonly context: vscode.ExtensionContext,
private readonly providerType: WebviewProviderType,
) {
WebviewProvider.activeInstances.add(this)
this.clientId = uuidv4()
WebviewProvider.clientIdMap.set(this, this.clientId)
constructor(readonly context: vscode.ExtensionContext) {
WebviewProvider.instance = this
// Create controller with cache service
this.controller = new Controller(context, this.clientId)
WebviewProvider.setLastActiveControllerId(this.controller.id)
}
// Add a method to get the client ID
public getClientId(): string {
return this.clientId
}
// Add a static method to get the client ID for a specific instance
public static getClientIdForInstance(instance: WebviewProvider): string | undefined {
return WebviewProvider.clientIdMap.get(instance)
this.controller = new Controller(context)
}
async dispose() {
await this.controller.dispose()
WebviewProvider.activeInstances.delete(this)
// Remove from client ID map
WebviewProvider.clientIdMap.delete(this)
WebviewProvider.instance = null
}
public static getInstance(): WebviewProvider {
if (!WebviewProvider.instance) {
throw new Error("WebviewProvider instance not initialized. Make sure to create a WebviewProvider instance first.")
}
return WebviewProvider.instance
}
public static getVisibleInstance(): WebviewProvider | undefined {
return findLast(Array.from(WebviewProvider.activeInstances), (instance) => instance.isVisible() === true)
}
public static getActiveInstance(): WebviewProvider | undefined {
return Array.from(WebviewProvider.activeInstances).find((instance) => instance.isActive())
}
protected abstract isActive(): boolean
public static getAllInstances(): WebviewProvider[] {
return Array.from(WebviewProvider.activeInstances)
}
public static getSidebarInstance() {
return Array.from(WebviewProvider.activeInstances).find(
(instance) => instance.providerType === WebviewProviderType.SIDEBAR,
)
}
public static getTabInstances(): WebviewProvider[] {
return Array.from(WebviewProvider.activeInstances).filter((instance) => instance.providerType === WebviewProviderType.TAB)
}
public static getLastActiveInstance(): WebviewProvider | undefined {
const lastActiveId = WebviewProvider.getLastActiveControllerId()
if (!lastActiveId) {
return undefined
}
return Array.from(WebviewProvider.activeInstances).find((instance) => instance.controller.id === lastActiveId)
}
/**
* Gets the last active controller ID with performance optimization
* @returns The last active controller ID or null
*/
public static getLastActiveControllerId(): string | null {
return WebviewProvider.lastActiveControllerId || WebviewProvider.getSidebarInstance()?.controller.id || null
}
/**
* Sets the last active controller ID with validation and performance optimization
* @param controllerId The controller ID to set as last active
*/
public static setLastActiveControllerId(controllerId: string | null): void {
// Only update if the value is actually different to avoid unnecessary operations
if (WebviewProvider.lastActiveControllerId !== controllerId) {
WebviewProvider.lastActiveControllerId = controllerId
}
return WebviewProvider.instance?.isVisible() ? WebviewProvider.instance : undefined
}
public static async disposeAllInstances() {
const instances = Array.from(WebviewProvider.activeInstances)
for (const instance of instances) {
await instance.dispose()
if (WebviewProvider.instance) {
await WebviewProvider.instance.dispose()
}
}
@@ -186,13 +120,6 @@ export abstract class WebviewProvider {
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" nonce="${nonce}">
// Inject the provider type
window.WEBVIEW_PROVIDER_TYPE = ${JSON.stringify(this.providerType)};
// Inject the client ID
window.clineClientId = "${this.clientId}";
</script>
<script type="module" nonce="${nonce}" src="${scriptUrl}"></script>
<script src="http://localhost:8097"></script>
</body>
@@ -292,13 +219,6 @@ export abstract class WebviewProvider {
</head>
<body>
<div id="root"></div>
<script type="text/javascript" nonce="${nonce}">
// Inject the provider type
window.WEBVIEW_PROVIDER_TYPE = ${JSON.stringify(this.providerType)};
// Inject the client ID
window.clineClientId = "${this.clientId}";
</script>
${reactRefresh}
<script type="module" src="${scriptUrl}"></script>
</body>
+1 -1
View File
@@ -11,7 +11,7 @@ import { ShowMessageType } from "@/shared/proto/host/window"
* Registers development-only commands for task manipulation.
* These are only activated in development mode.
*/
export function registerTaskCommands(context: vscode.ExtensionContext, controller: Controller): vscode.Disposable[] {
export function registerTaskCommands(controller: Controller): vscode.Disposable[] {
return [
vscode.commands.registerCommand("cline.dev.createTestTasks", async () => {
const count = (
+1 -1
View File
@@ -10,7 +10,7 @@ export function createClineAPI(sidebarController: Controller): ClineAPI {
await sidebarController.clearTask()
await sidebarController.postStateToWebview()
await sendChatButtonClickedEvent(sidebarController.id)
await sendChatButtonClickedEvent()
await sidebarController.initTask(task, images)
HostProvider.get().logToChannel(
`Task started with message: ${task ? `"${task}"` : "undefined"} and ${images?.length || 0} image(s)`,
+39 -173
View File
@@ -2,9 +2,7 @@
// Import the module and reference it with the alias vscode in your code below
import assert from "node:assert"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider"
import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui"
import * as vscode from "vscode"
import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked"
import { sendChatButtonClickedEvent } from "./core/controller/ui/subscribeToChatButtonClicked"
@@ -15,7 +13,6 @@ import { WebviewProvider } from "./core/webview"
import { createClineAPI } from "./exports"
import { Logger } from "./services/logging/Logger"
import { cleanupTestMode, initializeTestMode } from "./services/test/TestMode"
import { WebviewProviderType } from "./shared/webview/types"
import "./utils/path" // necessary to have access to String.prototype.toPosix
import path from "node:path"
@@ -55,18 +52,18 @@ https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/framewo
export async function activate(context: vscode.ExtensionContext) {
setupHostProvider(context)
const sidebarWebview = (await initialize(context)) as VscodeWebviewProvider
const webview = (await initialize(context)) as VscodeWebviewProvider
Logger.log("Cline extension activated")
const testModeWatchers = await initializeTestMode(sidebarWebview)
const testModeWatchers = await initializeTestMode(webview)
// Initialize test mode and add disposables to context
context.subscriptions.push(...testModeWatchers)
vscode.commands.executeCommand("setContext", "cline.isDevMode", IS_DEV && IS_DEV === "true")
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(VscodeWebviewProvider.SIDEBAR_ID, sidebarWebview, {
vscode.window.registerWebviewViewProvider(VscodeWebviewProvider.SIDEBAR_ID, webview, {
webviewOptions: { retainContextWhenHidden: true },
}),
)
@@ -74,146 +71,52 @@ export async function activate(context: vscode.ExtensionContext) {
const { commands } = ExtensionRegistryInfo
context.subscriptions.push(
vscode.commands.registerCommand(commands.PlusButton, async (webview: any) => {
console.log("[DEBUG] plusButtonClicked", webview)
// Pass the webview type to the event sender
const isSidebar = !webview
vscode.commands.registerCommand(commands.PlusButton, async () => {
console.log("[DEBUG] plusButtonClicked")
const openChat = async (instance: WebviewProvider) => {
await instance?.controller.clearTask()
await instance?.controller.postStateToWebview()
await sendChatButtonClickedEvent(instance.controller.id)
}
if (isSidebar) {
const sidebarInstance = WebviewProvider.getSidebarInstance()
if (sidebarInstance) {
openChat(sidebarInstance)
// Send event to the sidebar instance
}
} else {
const tabInstances = WebviewProvider.getTabInstances()
for (const instance of tabInstances) {
openChat(instance)
}
}
const sidebarInstance = WebviewProvider.getInstance()
await sidebarInstance.controller.clearTask()
await sidebarInstance.controller.postStateToWebview()
await sendChatButtonClickedEvent()
}),
)
context.subscriptions.push(
vscode.commands.registerCommand(commands.McpButton, (webview: any) => {
console.log("[DEBUG] mcpButtonClicked", webview)
const activeInstance = WebviewProvider.getActiveInstance()
const isSidebar = !webview
if (isSidebar) {
const sidebarInstance = WebviewProvider.getSidebarInstance()
const sidebarInstanceId = sidebarInstance?.getClientId()
if (sidebarInstanceId) {
sendMcpButtonClickedEvent(sidebarInstanceId)
} else {
console.error("[DEBUG] No sidebar instance found, cannot send MCP button event")
}
} else {
const activeInstanceId = activeInstance?.getClientId()
if (activeInstanceId) {
sendMcpButtonClickedEvent(activeInstanceId)
} else {
console.error("[DEBUG] No active instance found, cannot send MCP button event")
}
}
}),
)
const openClineInNewTab = async () => {
Logger.log("Opening Cline in new tab")
// (this example uses webviewProvider activation event which is necessary to deserialize cached webview, but since we use retainContextWhenHidden, we don't need to use that event)
// https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
const tabWebview = HostProvider.get().createWebviewProvider(WebviewProviderType.TAB) as VscodeWebviewProvider
const lastCol = Math.max(...vscode.window.visibleTextEditors.map((editor) => editor.viewColumn || 0))
// Check if there are any visible text editors, otherwise open a new group to the right
const hasVisibleEditors = vscode.window.visibleTextEditors.length > 0
if (!hasVisibleEditors) {
await vscode.commands.executeCommand("workbench.action.newGroupRight")
}
const targetCol = hasVisibleEditors ? Math.max(lastCol + 1, 1) : vscode.ViewColumn.Two
const panel = vscode.window.createWebviewPanel(VscodeWebviewProvider.TAB_PANEL_ID, "Cline", targetCol, {
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: [vscode.Uri.file(HostProvider.get().extensionFsPath)],
})
// TODO: use better svg icon with light and dark variants (see https://stackoverflow.com/questions/58365687/vscode-extension-iconpath)
panel.iconPath = {
light: vscode.Uri.joinPath(context.extensionUri, "assets", "icons", "robot_panel_light.png"),
dark: vscode.Uri.joinPath(context.extensionUri, "assets", "icons", "robot_panel_dark.png"),
}
tabWebview.resolveWebviewView(panel)
// Lock the editor group so clicking on files doesn't open them over the panel
await setTimeoutPromise(100)
await vscode.commands.executeCommand("workbench.action.lockEditorGroup")
return tabWebview
}
context.subscriptions.push(vscode.commands.registerCommand(commands.PopoutButton, openClineInNewTab))
context.subscriptions.push(vscode.commands.registerCommand(commands.OpenInNewTab, openClineInNewTab))
context.subscriptions.push(
vscode.commands.registerCommand(commands.SettingsButton, (webview: any) => {
const isSidebar = !webview
const webviewType = isSidebar ? WebviewProviderTypeEnum.SIDEBAR : WebviewProviderTypeEnum.TAB
sendSettingsButtonClickedEvent(webviewType)
vscode.commands.registerCommand(commands.McpButton, () => {
sendMcpButtonClickedEvent()
}),
)
context.subscriptions.push(
vscode.commands.registerCommand(commands.HistoryButton, async (webview: any) => {
console.log("[DEBUG] historyButtonClicked", webview)
// Pass the webview type to the event sender
const isSidebar = !webview
const webviewType = isSidebar ? WebviewProviderTypeEnum.SIDEBAR : WebviewProviderTypeEnum.TAB
vscode.commands.registerCommand(commands.SettingsButton, () => {
sendSettingsButtonClickedEvent()
}),
)
context.subscriptions.push(
vscode.commands.registerCommand(commands.HistoryButton, async () => {
// Send event to all subscribers using the gRPC streaming method
await sendHistoryButtonClickedEvent(webviewType)
await sendHistoryButtonClickedEvent()
}),
)
context.subscriptions.push(
vscode.commands.registerCommand(commands.AccountButton, (webview: any) => {
console.log("[DEBUG] accountButtonClicked", webview)
const isSidebar = !webview
if (isSidebar) {
const sidebarInstance = WebviewProvider.getSidebarInstance()
if (sidebarInstance) {
// Send event to sidebar controller
sendAccountButtonClickedEvent(sidebarInstance.controller.id)
}
} else {
// Send to all tab instances
const tabInstances = WebviewProvider.getTabInstances()
for (const instance of tabInstances) {
sendAccountButtonClickedEvent(instance.controller.id)
}
}
vscode.commands.registerCommand(commands.AccountButton, () => {
// Send event to all subscribers using the gRPC streaming method
sendAccountButtonClickedEvent()
}),
)
/*
We use the text document content provider API to show the left side for diff view by creating a
virtual document for the original content. This makes it readonly so users know to edit the right
We use the text document content provider API to show the left side for diff view by creating a
virtual document for the original content. This makes it readonly so users know to edit the right
side if they want to keep their changes.
- This API allows you to create readonly documents in VSCode from arbitrary sources, and works by
claiming an uri-scheme for which your provider then returns text contents. The scheme must be
- This API allows you to create readonly documents in VSCode from arbitrary sources, and works by
claiming an uri-scheme for which your provider then returns text contents. The scheme must be
provided when registering a provider and cannot change afterwards.
- Note how the provider doesn't create uris for virtual documents - its role is to provide contents
given such an uri. In return, content providers are wired into the open document logic so that
given such an uri. In return, content providers are wired into the open document logic so that
providers are always considered.
https://code.visualstudio.com/api/extension-guides/virtual-documents
*/
@@ -238,7 +141,7 @@ export async function activate(context: vscode.ExtensionContext) {
// Use dynamic import to avoid loading the module in production
import("./dev/commands/tasks")
.then((module) => {
const devTaskCommands = module.registerTaskCommands(context, sidebarWebview.controller)
const devTaskCommands = module.registerTaskCommands(webview.controller)
context.subscriptions.push(...devTaskCommands)
Logger.log("Cline dev task commands registered")
})
@@ -428,54 +331,17 @@ export async function activate(context: vscode.ExtensionContext) {
// Register the focusChatInput command handler
context.subscriptions.push(
vscode.commands.registerCommand(commands.FocusChatInput, async () => {
// Fast path: check for existing active instance
let activeWebview = WebviewProvider.getLastActiveInstance() as VscodeWebviewProvider
const webview = WebviewProvider.getInstance() as VscodeWebviewProvider
if (activeWebview) {
// Instance exists - just reveal and focus it
const webview = activeWebview.getWebview()
if (webview) {
if (webview && "reveal" in webview) {
webview.reveal()
} else if ("show" in webview) {
webview.show()
}
}
} else {
// No active instance - need to find or create one
WebviewProvider.setLastActiveControllerId(null)
// Check for existing tab instances first (cheaper than focusing sidebar)
const tabInstances = WebviewProvider.getTabInstances() as VscodeWebviewProvider[]
if (tabInstances.length > 0) {
activeWebview = tabInstances[tabInstances.length - 1]
} else {
// Try to focus sidebar via hostbridge
await HostProvider.workspace.openClineSidebarPanel({})
// Small delay for focus to complete
await new Promise((resolve) => setTimeout(resolve, 200))
activeWebview = WebviewProvider.getSidebarInstance() as VscodeWebviewProvider
if (!activeWebview) {
// Last resort: create new tab
activeWebview = (await openClineInNewTab()) as VscodeWebviewProvider
}
}
// Show the webview
const webviewView = webview.getWebview()
if (webviewView) {
webviewView.show()
}
// Send focus event
const clientId = activeWebview?.getClientId()
if (!clientId) {
console.error("FocusChatInput: Could not find or activate a Cline webview to focus.")
HostProvider.window.showMessage({
type: ShowMessageType.ERROR,
message: "Could not activate Cline view. Please try opening it manually from the Activity Bar.",
})
return
}
sendFocusChatInputEvent(clientId)
telemetryService.captureButtonClick("command_focusChatInput", activeWebview.controller?.task?.ulid)
sendFocusChatInputEvent()
telemetryService.captureButtonClick("command_focusChatInput", webview.controller?.task?.ulid)
}),
)
@@ -491,7 +357,7 @@ export async function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand(commands.ReconstructTaskHistory, async () => {
const { reconstructTaskHistory } = await import("./core/commands/reconstructTaskHistory")
await reconstructTaskHistory(context)
await reconstructTaskHistory()
telemetryService.captureButtonClick("command_reconstructTaskHistory")
}),
)
@@ -511,8 +377,8 @@ 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 activeWebviewProvider = WebviewProvider.getVisibleInstance()
const controller = activeWebviewProvider?.controller
const activeWebview = WebviewProvider.getVisibleInstance()
const controller = activeWebview?.controller
const authService = AuthService.getInstance(controller)
if (secretValue) {
@@ -526,13 +392,13 @@ export async function activate(context: vscode.ExtensionContext) {
}),
)
return createClineAPI(sidebarWebview.controller)
return createClineAPI(webview.controller)
}
function setupHostProvider(context: ExtensionContext) {
console.log("Setting up vscode host providers...")
const createWebview = (type: WebviewProviderType) => new VscodeWebviewProvider(context, type)
const createWebview = () => new VscodeWebviewProvider(context)
const createDiffView = () => new VscodeDiffViewProvider()
const outputChannel = vscode.window.createOutputChannel("Cline")
context.subscriptions.push(outputChannel)
-9
View File
@@ -1,15 +1,9 @@
import * as vscode from "vscode"
import { WebviewProvider } from "@/core/webview"
import { WebviewProviderType } from "@/shared/webview/types"
export class ExternalWebviewProvider extends WebviewProvider {
// This hostname cannot be changed without updating the external webview handler.
private RESOURCE_HOSTNAME: string = "internal.resources"
constructor(context: vscode.ExtensionContext, providerType: WebviewProviderType) {
super(context, providerType)
}
override getWebviewUrl(path: string) {
const url = new URL(`https://${this.RESOURCE_HOSTNAME}/`)
url.pathname = path
@@ -21,7 +15,4 @@ export class ExternalWebviewProvider extends WebviewProvider {
override isVisible() {
return true
}
protected override isActive(): boolean {
return true
}
}
+1 -19
View File
@@ -1,8 +1,5 @@
import fs from "fs/promises"
import path from "path"
import { WebviewProvider } from "@/core/webview"
import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider"
import { WebviewProviderType } from "@/shared/webview/types"
import { HostBridgeClientProvider } from "./host-provider-types"
/**
* Singleton class that manages host-specific providers for dependency injection.
@@ -127,27 +124,12 @@ export class HostProvider {
public static get diff() {
return HostProvider.get().hostBridge.diffClient
}
/**
* Returns the global storage directory for the extension, or a sub-directory of the global storage dir.
* If the directory does not exist, it is created.
* @param subdirs
* @returns
*/
public static async getGlobalStorageDir(subdirs?: string) {
if (!subdirs) {
return HostProvider.get().globalStorageFsPath
}
const fullPath = path.resolve(HostProvider.get().globalStorageFsPath, subdirs)
await fs.mkdir(fullPath, { recursive: true })
return fullPath
}
}
/**
* A function that creates WebviewProvider instances
*/
export type WebviewProviderCreator = (providerType: WebviewProviderType) => WebviewProvider
export type WebviewProviderCreator = () => WebviewProvider
/**
* A function that creates DiffViewProvider instances
+20 -51
View File
@@ -6,7 +6,6 @@ import { HostProvider } from "@/hosts/host-provider"
import { ExtensionRegistryInfo } from "@/registry"
import type { ExtensionMessage } from "@/shared/ExtensionMessage"
import { WebviewMessage } from "@/shared/WebviewMessage"
import type { WebviewProviderType } from "@/shared/webview/types"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@@ -17,15 +16,10 @@ export class VscodeWebviewProvider extends WebviewProvider implements vscode.Web
// Used in package.json as the view's id. This value cannot be changed due to how vscode caches
// views based on their id, and updating the id would break existing instances of the extension.
public static readonly SIDEBAR_ID = ExtensionRegistryInfo.views.Sidebar
public static readonly TAB_PANEL_ID = ExtensionRegistryInfo.views.TabPanel
private webview?: vscode.WebviewView | vscode.WebviewPanel
private webview?: vscode.WebviewView
private disposables: vscode.Disposable[] = []
constructor(context: vscode.ExtensionContext, providerType: WebviewProviderType) {
super(context, providerType)
}
override getWebviewUrl(path: string) {
if (!this.webview) {
throw new Error("Webview not initialized")
@@ -41,28 +35,21 @@ export class VscodeWebviewProvider extends WebviewProvider implements vscode.Web
return this.webview.webview.cspSource
}
protected isActive() {
if (this.webview && this.webview.viewType === VscodeWebviewProvider.TAB_PANEL_ID && "active" in this.webview) {
return this.webview.active === true
}
return false
}
override isVisible() {
return this.webview?.visible || false
}
public getWebview(): vscode.WebviewView | vscode.WebviewPanel | undefined {
public getWebview(): vscode.WebviewView | undefined {
return this.webview
}
/**
* Initializes and sets up the webview when it's first created.
*
* @param webviewView - The webview view or panel instance to be resolved
* @param webviewView - The sidebar webview view instance to be resolved
* @returns A promise that resolves when the webview has been fully initialized
*/
public async resolveWebviewView(webviewView: vscode.WebviewView | vscode.WebviewPanel): Promise<void> {
public async resolveWebviewView(webviewView: vscode.WebviewView): Promise<void> {
this.webview = webviewView
webviewView.webview.options = {
@@ -83,43 +70,26 @@ export class VscodeWebviewProvider extends WebviewProvider implements vscode.Web
// Logs show up in bottom panel > Debug Console
//console.log("registering listener")
// Listen for when the panel becomes visible
// Listen for when the sidebar becomes visible
// https://github.com/microsoft/vscode-discussions/discussions/840
if ("onDidChangeViewState" in webviewView) {
// WebviewView and WebviewPanel have all the same properties except for this visibility listener
// panel
webviewView.onDidChangeViewState(
async (e) => {
if (e?.webviewPanel?.visible && e.webviewPanel?.active) {
WebviewProvider.setLastActiveControllerId(this.controller.id)
// Only send the event if the webview is active (focused)
await sendDidBecomeVisibleEvent(this.controller.id)
}
},
null,
this.disposables,
)
} else if ("onDidChangeVisibility" in webviewView) {
// sidebar
webviewView.onDidChangeVisibility(
async () => {
if (this.webview?.visible) {
WebviewProvider.setLastActiveControllerId(this.controller.id)
await sendDidBecomeVisibleEvent(this.controller.id)
}
},
null,
this.disposables,
)
}
// onDidChangeVisibility is only available on the sidebar webview
// Otherwise WebviewView and WebviewPanel have all the same properties except for this visibility listener
// WebviewPanel is not currently used in the extension
webviewView.onDidChangeVisibility(
async () => {
if (this.webview?.visible) {
await sendDidBecomeVisibleEvent()
}
},
null,
this.disposables,
)
// Listen for when the view is disposed
// This happens when the user closes the view or when the view is closed programmatically
webviewView.onDidDispose(
async () => {
if (WebviewProvider.getLastActiveControllerId() === this.controller.id) {
WebviewProvider.setLastActiveControllerId(null)
}
await this.dispose()
},
null,
@@ -219,9 +189,8 @@ export class VscodeWebviewProvider extends WebviewProvider implements vscode.Web
}
override async dispose() {
if (this.webview && "dispose" in this.webview) {
this.webview.dispose()
}
// WebviewView doesn't have a dispose method, it's managed by VSCode
// We just need to clean up our disposables
while (this.disposables.length) {
const x = this.disposables.pop()
if (x) {
+4 -15
View File
@@ -1,4 +1,3 @@
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import { ExtensionRegistryInfo } from "@/registry"
import { CommandContext } from "@/shared/proto/index.cline"
@@ -23,10 +22,7 @@ export async function getContextForCommand(
}
> {
const activeWebview = await focusChatInput()
if (!activeWebview) {
return
}
// Use the controller from the last active instance
// Use the controller from the active instance
const controller = activeWebview.controller
const editor = vscode.window.activeTextEditor
@@ -50,16 +46,9 @@ export async function getContextForCommand(
return { controller, commandContext }
}
export async function focusChatInput(): Promise<WebviewProvider | undefined> {
export async function focusChatInput(): Promise<WebviewProvider> {
await vscode.commands.executeCommand(ExtensionRegistryInfo.commands.FocusChatInput)
// Wait for a webview instance to become available after focusing
await pWaitFor(() => !!WebviewProvider.getLastActiveInstance())
const activeWebview = WebviewProvider.getLastActiveInstance()
if (!activeWebview) {
console.error("No active webview to receive command")
return
}
return activeWebview
// At this point, the instance is guaranteed to exist due to the FocusChatInput command
return WebviewProvider.getInstance()
}
+7 -1
View File
@@ -1,7 +1,13 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import * as vscode from "vscode"
import { ExtensionRegistryInfo } from "@/registry"
import { GetHostVersionResponse } from "@/shared/proto/index.host"
export async function getHostVersion(_: EmptyRequest): Promise<GetHostVersionResponse> {
return { platform: "VSCode", version: vscode.version }
return {
platform: vscode.env.appName,
version: vscode.version,
clineType: "VSCode Extension",
clineVersion: ExtensionRegistryInfo.version,
}
}

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