Compare commits

...

419 Commits

Author SHA1 Message Date
celestial-vault b5c9899837 remove useEffect 2025-07-30 15:48:51 -07:00
Daniel Steigman b4b7512d9f Improve Cline accounts support telemetry (#5242)
* fixed linter rule and added identified telemtry stuff

* Updated the error handling

* fixed error handling
2025-07-29 17:23:50 -07:00
Toshii e08c65618e read_file can read images (png, jpg, jpeg, webp) (#4411)
* base

* throw

* chat ui

Co-authored-by: Ding Fei <fding@feysh.com>

* chat row logic for image file reads

* dim check change

---------

Co-authored-by: Ding Fei <fding@feysh.com>
2025-07-29 15:41:31 -07:00
Bee d653f1cc27 test: update Playwright test timeouts (#5241)
- Rename isGitHubAction to isCI for broader CI detection
- Adjust timeout logic to use CI or Windows conditions
- Reduce expect timeout from 40s/20s to 5s/2s for faster feedback
- Decrease streaming chunk delay from 50ms to 20ms in server mock
2025-07-29 15:27:46 -07:00
Bee c3a97c3eda e2e test: add mock service for cline API & new test for diff editor (#5196)
* Add mock api service and E2E test infrastructure

- Create AuthServiceMock for testing with mock user data and API responses
- Add AuthProvider interface to standardize authentication providers
- Implement E2E test fixtures with mock server and workspace setup
- Add comprehensive E2E tests for authentication and core functionality
- Export DEFAULT_CLINE_APP_URL config and make getEnvironmentConfig more flexible
- Update AuthService to use mock implementation during E2E tests

* format

* import

* refactor mock server

* rename data

* wait for text

* wait for edit

* increase timeout for windows

* clean up

* rename test and add orgs
2025-07-29 12:39:49 -07:00
celestial-vault 0e56272d65 remove chatSettings object (#5178)
* remove chatSettings object

* fix types after merge conflicts
2025-07-29 12:31:52 -07:00
Kevin Taylor fdc2e2655a Add Cerebras model Qwen 3 235b instruct (#5236) 2025-07-29 11:55:48 -07:00
Wintertee 6050413b8b fix: remove duplicate tool registration for claude4-experimental (#4748) 2025-07-29 10:48:41 -07:00
Bee c54f0da737 feat: adds navigation bar component and restructure app layout (#5220) 2025-07-29 13:05:01 -04:00
Sarah Fortune 6cbfb2b8b0 Remove duplication define property in esbuild.json (#5234) 2025-07-29 08:54:12 -07:00
Sarah Fortune 22788f0f12 Move the OutputChannel to the HostProvider (#5189)
* Move the OutputChannel to the HostProvider

Replace `OutputChannel.appendLine` with `HostProvider.logToChannel`.

Remove places where the cline OutputChannel was being passed around. Now it is stored in the HostProvider, so we don't need to do this.

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

* Dont log the timestamp in logger.ts, the cline-core logger already outputs the timestamp

* Fix imports
2025-07-28 22:56:43 -07:00
DongDong Ling 708b785a97 Add Huawei Cloud MaaS Provider (#5071)
* Add Huawei Cloud MaaS Provider

* Fix case error

* Add missing modelid

* add huawei specific modelId and modelInfo

* add huawei specific model id and model info in state.proto

* more huawei maas specific change
2025-07-28 21:47:21 -07:00
Jose R. Perez 099bc44d42 docs: fix Global Rules directory location for Linux/WSL systems (#5219) 2025-07-28 23:54:03 -04:00
Toshii b9f4678dba add try-catch handling (#5227) 2025-07-28 20:21:51 -07:00
Bee f7d17384f6 refactor & fix: improve account view with better states management (#5182)
* refactor & fix: improve account view with better states management

The previous AccountView implementation suffered from several critical state management issues:

- Incorrect info on display: The active account is not ready when component is mounted because the fetching only start on mount but doesn't get reset correctly
- Excessive re-renders: All data was fetched on component mount, causing cascading state updates
- Race conditions: Multiple concurrent API calls and state dependencies created unpredictable behavior, e.g. 403 rate limits errors
- Monolithic state management: All account data, organizations, and auth state was managed in a single massive component
- Poor user experience: Users saw empty states and loading flickers when switching between organizations
- Tight coupling: User and org info logic was deeply embedded within the account view that cause Effect dependency loops

Solution: Centralized Authentication Context

- Extracted auth logic into dedicated ClineAuthContext with organizations state management
- Eliminated prop drilling by providing clineUser, organizations, and activeOrganization at the context level
- Reduced component re-renders by managing auth state separately from UI state
- Performed authentication guard at higher level and only displays user account to authenticated user. The component will get dismounted when user is not autheticated.
- Move handleSignIn and handleSignout into individual functions instead as they are regular functions with no state dependency

* 60secs

* Optimize state updates in AccountView to prevent unnecessary re-renders

Remove conditional checks before setState calls and use functional updates
with deep equality comparison to avoid redundant state changes and
dependency array bloat in useCallback hooks.

* add docs

* fix format

* fix error test

* setuser on logout
2025-07-28 15:46:23 -07:00
Sarah Fortune bb5a64afb3 Quiet spammy MCP debug logs (#5224) 2025-07-28 15:44:38 -07:00
Sarah Fortune 61224734f8 Change timeout, token budget and line limit fields in the ProtoBus from int64 to int32. (#5221) 2025-07-28 17:40:15 -04:00
Bee a28b995ab1 Fix styled-components prop warnings (#5181)
* Fix styled-components prop warnings

- Fix styled-components shouldForwardProp warnings by filtering non-DOM props
- Clean up unused imports in ChatTextArea and other components

* use mjs

* later

* remove unused imports
2025-07-28 11:19:32 -07:00
Bee a91878efc6 Fix: webview panel state change steals focus (#5193)
* Fix: webview panel state change steals focus

Fix webview visibility detection to check both visible and active states before taking focus. If a panel is visible but not active (focused), it should not steals editor focus.

Also removes unused import & add type imports

* add changeset
2025-07-28 10:59:00 -07:00
Jonathan Barazany 65c21e7b7d Bug fix: VSCode LM API token counting for Claude models (#5051)
* Improve token counting for Claude models in VSCode LM provider

- Reorder imports for better organization
- Add extractTextFromMessage helper method
- Add isClaudeModel detection method
- Use 4:1 character-to-token ratio for Claude models instead of VSCode's inaccurate counting
- Fallback to existing VSCode LM token counting for non-Claude models

* Update version to 3.18.3-r1 and refactor token calculation in VsCodeLmHandler

* 3.19.5-r1

* Add smart jobs impress changeset for VSCode LM API token counting fix

---------

Co-authored-by: Jonathan Barazany <jbarazany@microsoft.com>
2025-07-28 02:09:40 -07:00
Sarah Fortune 56e388c90f Add a check to the proto scripts to warn about using int64 types. (#5174)
* Add a check to the proto scripts to warn about using int64 types.

Javascript cannot represent the full range of int64. So, when the protos are deserialized from JSON int64's are converted to strings. The typescript code is expecting a number and not a string, and this causes errors.

This was noticed before now because in the vscode protobus and hostbridge, the proto messages are not serialized and deserialized, they are just passed around as JS objects.

However, in IntelliJ the protos are serialized when they are sent through the ProtoBus. When the response messages contains and int64, it is deserialized to a string instead of a number for safety. This is causes parts of Cline to fail in IntelliJ, e.g. the task history view won't load because `Task.getTotalTasksSize()` returns a string when it is expecting a number.

* Make checkProtos shorter

* Update scripts/build-proto.mjs

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

* Update scripts/build-proto.mjs

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

* Update scripts/build-proto.mjs

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

* Fix typo

* Fix typo

* Fix bad merge

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-27 22:02:12 -04:00
pashpashpash 586d804a01 Revert "Spruce up HistoryPreview (#4101)" (#5207)
This reverts commit cdfffb8464.
2025-07-27 16:48:49 -07:00
Saoud Rizwan 85fbbcbe3f Revise contributing guidelines and fix PR template link to feature requests board (#5195)
* Revise contributing guidelines and fix PR template link to feature requests board

* Fix wording
2025-07-26 12:43:59 -07:00
ZhangZhiheng 25c5310383 Fix url no trim (#4641)
* fix: trim input value for URL fields in BaseUrlField and DebouncedTextField components (#4051)

* chore: add changeset
2025-07-26 12:23:09 -07:00
Saoud Rizwan 19ef843d4f Revert "feat: update Gemini models - remove deprecated and add 2.5 Flash-Lite…" (#5194)
This reverts commit f6273e0661.
2025-07-26 11:53:06 -07:00
dependabot[bot] 2b3dd14271 Bump the npm_and_yarn group with 3 updates (#4186)
Bumps the npm_and_yarn group with 3 updates: [brace-expansion](https://github.com/juliangruber/brace-expansion), [tar-fs](https://github.com/mafintosh/tar-fs) and [undici](https://github.com/nodejs/undici).


Updates `brace-expansion` from 1.1.11 to 1.1.12
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/1.1.11...v1.1.12)

Updates `tar-fs` from 3.0.8 to 3.0.9
- [Commits](https://github.com/mafintosh/tar-fs/compare/v3.0.8...v3.0.9)

Updates `undici` from 6.21.1 to 6.21.3
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v6.21.1...v6.21.3)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.12
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: tar-fs
  dependency-version: 3.0.9
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: undici
  dependency-version: 6.21.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-26 08:03:48 -07:00
Karan Vaidya 721e7ae305 Add Composio to adding-mcp-servers-from-github.mdx (#4624)
* Add Composio to adding-mcp-servers-from-github.mdx

* Update adding-mcp-servers-from-github.mdx
2025-07-26 07:52:27 -07:00
Eugene Demkin f6273e0661 feat: update Gemini models - remove deprecated and add 2.5 Flash-Lite (#4681)
- Remove deprecated experimental models:
  - gemini-1.5-flash-8b-exp-0827
  - gemini-1.5-flash-exp-0827
  - gemini-1.5-pro-exp-0827
- Add gemini-2.5-flash-lite-preview-06-17 with latest pricing
2025-07-26 07:45:29 -07:00
CellenLee 68d0af2afc feat: moonshot provider ui polish (#5034) 2025-07-26 07:21:50 -07:00
Saoud Rizwan 4286f301d2 Remove feature_contribution issue type (#5184) 2025-07-26 06:18:41 -07:00
dependabot[bot] 28536084bf Bump form-data in /webview-ui in the npm_and_yarn group (#5095)
---
updated-dependencies:
- dependency-name: form-data
  dependency-version: 4.0.4
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-26 06:07:58 -07:00
Utkarsh dfbac3eefd Support for Deepseek R1 0528 (#3903) (#5183) 2025-07-26 05:45:31 -07:00
Saoud Rizwan 04f0710a03 Update bug report template to make system information and logs fields optional (#5159) 2025-07-26 01:58:48 -07:00
kvyb 195e15db32 Move vscode.commands.executeCommand("vscode.open") to Hostbridge (#5173)
* feat: add openFile host bridge for vscode.open command

* fix: simplify openFile hostbridge to follow gRPC best practices:
- Remove success boolean field from OpenFileResponse proto
- Use gRPC exceptions for error handling instead of success/failure booleans
- Simplify hostbridge implementation to just move existing vscode.open code

* fix: remove create wrapper from openFile call

* fix proto merge conflict
2025-07-26 04:19:03 -04:00
Sarah Fortune 19cb70de55 Use npm moduleopen to open URLs in the external browser (instead of the host bridge) (#5013)
* Use npm `open` to open URLs in the external browser

# Conflicts:
#	src/utils/env.ts

# Conflicts:
#	src/utils/env.ts

* Change log statement

* Use the simple-open-url module to open URLs in the system browser.

Log failures of ProtoBus RPCs

* Remove vscode hostbridge handler for openExternal

* Rm unused imports

* Switch back to `open` module.

Update esbuild.js to ES6 and move to esbuild.mjs

* Update src/utils/env.ts

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

* remove IS_DEV from e2e setup build

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-26 04:06:53 -04:00
github-actions[bot] e2a2ecde44 v3.20.2 Release Notes (#5155)
* 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-07-26 00:00:19 -07:00
Saoud Rizwan 1a466c0a44 Fix cursor state after restoring files to be disabled after checked out (#5179)
* Fix cursor state after restoring files to be disabled after checked out

* Create silver-llamas-pretend.md
2025-07-25 23:51:34 -07:00
Sarah Fortune 31cbf489c4 Fix launch configuration for the cline-core (#5170) 2025-07-26 02:38:38 -04:00
Saoud Rizwan c667d34f27 Fix issue where checkpointing blocked UI (#5177)
* Fix issue where checkpointing blocked UI

* Create wet-fishes-study.md
2025-07-25 23:24:39 -07:00
Sarah Fortune a1bf1f95a3 refactor(proto): Align proto directory structure with package names to follow best practices (#5171)
* Reorganized proto directory structure to match package naming convention

Moved cline package protos from the proto directory to proto/cline/ directory
Host package protos remain in proto/host/ directory

Updated all import statements across codebase to reflect new proto paths

Removed proto linter exception for package/directory mismatch rule

Fix Vscode proto indexing errors by setting the proto path in the Vscode settings.

* Update imports to use new package

Update imports from @shared/proto/<thing> to @share/proto/cline/<thing>
2025-07-26 00:58:16 -04:00
Bee 5da75af616 Fix Qwen API options inconsistency (#5162)
* Fix Qwen API option inconsistency

Refactor Qwen API region handling with enum and improved type safety

Changes:

- Replace string literals with QwenApiRegions enum for better type safety
- Add default region initialization in QwenHandler constructor
- Extract useChinaApi() method for cleaner conditional logic
- Update UI dropdown to use enum values with proper memoization
- Improve code maintainability and reduce magic strings

* changeset added

* Apply suggestions from code review

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

* fix type with conversion

* Refactor Qwen model defaults to use first model dynamically

Move type definitions and enums after model objects and set default
models by selecting the first key from each model object instead of
hardcoding specific model IDs.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-25 11:15:01 -07:00
Sarah Fortune 38babe12f7 Replace vscode show message API calls with the host bridge (#5161) 2025-07-25 11:48:16 -04:00
Sarah Fortune 66fb8835a4 Add an RPC to the host bridge to scroll the diff viewer. (#5151) 2025-07-24 23:09:33 -04:00
Bee 214e157360 Fix organization state reset when switching between accounts (#5154)
* Fix organization state reset when switching between accounts

Move user authentication check into getUserOrganizations callback to properly reset state when switching between personal and organization accounts. This prevents stale organization data from persisting across account switches.

* add changeset

* Add error handling and refactor credit display components

Fix issues with balance display out of sync on org change or when API calls received 405 (rate limited) error

- Add error handling for failed API calls in getUserCredits and getOrganizationCredits
- Extract animated credit display logic into reusable StyledCreditDisplay component
- Simplify AccountView by removing inline credit animation code
- Improve organization state management and loading behavior

* Apply suggestions from code review

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

* format

* reset on mount

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-24 19:59:42 -07:00
Igor Tceglevskii 7a9dce4f86 Moved open and visible tab retrieval to a separate hostbridge module (#5150) 2025-07-24 17:46:31 -07:00
Tomás Barreiro af7e3a4d20 Change the CLAUDE_CODE_MAX_OUTPUT_TOKENS (#5142)
* Change the CLAUDE_CODE_MAX_OUTPUT_TOKENS

* Add changeset

* Add comment and variable to explain the changes
2025-07-24 09:24:30 -07:00
schardosin 3abdc9ad0f Fixed issue affecting first-time credential entry for SAP AI Core (#5132)
* removed the reduced mask, which was making the client secret to fail in the first save

* added changeset
2025-07-23 22:19:47 -07:00
Ara 28b15d8b9b Adding gitbash terminal support and docs for solving windows terminal issues (#5110)
* Adding gitbash terminal support and docs for solving windows terminal issues

* Update docs/troubleshooting/terminal-integration-guide.mdx

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-23 14:07:02 -07:00
github-actions[bot] bc6b3e54be v3.20.1 Release Notes (#5128)
* 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-07-23 11:46:55 -07:00
canvrno 9fad0aa4ae Fix file deletion bug (#5125)
* Fix for files being deleted when switching modes or closing tasks

* changeset

* Added check to see if we are waiting for API response

* More targetted fix

* Create hot-onions-promise.md

* Delete .changeset/hot-onions-promise.md

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-23 11:44:24 -07:00
Ara 23fea0e16b Stop auto focus of Cline window on Every update (#5117) 2025-07-23 04:03:28 -07:00
Bee e8aaa61494 Improve auth state management for account view (#5107)
- Fix AccountView state management when user is not authenticated or is authenticated after the webview is loaded
- Add proper loading state reset and conditional data fetching
2025-07-22 20:00:14 -07:00
github-actions[bot] d93080304c v3.20.0 Release Notes (#5096)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and version for 3.20.0 release

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-22 19:52:16 -07:00
Ara 1ce5f72bc1 Updating the new release announcement note (#5101)
* Updating the new release announcement note

* Adding gitbash terminal support and docs for solving windows terminal issues
2025-07-22 19:37:44 -07:00
Saoud Rizwan fb676add2e Fix hugging face model description (#5105) 2025-07-22 19:06:51 -07:00
Ara 31cda0ce5e Adding support for new models Qwen 3 models on Qwen provider (#5106) 2025-07-22 19:00:49 -07:00
Ara e173dad69c Updating the ordering to move cerebras provider upwards in the list of providers (#5102) 2025-07-22 16:22:52 -07:00
Toshii 92f32522c5 devtral medium (#5100) 2025-07-22 16:07:00 -07:00
Bee 7817d5f261 Host bridge migration: showInputBox (#4747)
* Update showInputBox

* Simplify

* Remove undefined handler for ShowInputBoxResponse
2025-07-22 13:13:03 -07:00
Bee db6d288efa Display credit balance for all accounts (#4992)
* Display credit balance for all accounts

The credit balance display was previously only shown for personal accounts. This change removes the check for `activeOrganization === null` and displays the credit balance and "Add Credits" button for all account types, including organization accounts. A divider is added above the balance section for visual separation once the backend change is deployed.

* changeset

* Improve refresh logic

Refactors the `AccountView` component to properly display and manage credits for both user and organization accounts. It introduces the `getOrganizationCredits` API call to fetch organization-specific credits and updates the UI accordingly. The refresh logic has also been improved to ensure data consistency and prevent unnecessary API calls.

Key changes:

- Implemented `getOrganizationCredits` to fetch credits for the active organization.
- Modified the credit display to show organization credits when an organization is active.
- Updated the refresh logic to use `useCallback` and `debounce` for better performance and to prevent race conditions.
- Added a periodic refresh to update account data every 30 seconds.
- Improved error handling and loading state management.
- Removed the interval ref and replaced it with a simpler useEffect for periodic refresh.
- Added last fetch time to the UI.

* clean up

* deepEqual

* org management

* prevent race condition
2025-07-22 12:03:37 -07:00
github-actions[bot] 87ff00d87e v3.19.8 Release Notes (#5022)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for v3.19.8 release

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-22 11:35:39 -07:00
Sarah Fortune e602efc7a6 Dont export the protobus handlers from the grpc-client protobus-services.ts (#5091) 2025-07-22 01:30:01 -07:00
kvyb e6462af336 automate announcement display for major.minor releases (#5081)
* automate announcement display for major.minor releases

* fix: simplify onDidShowAnnouncement
2025-07-21 23:35:27 -07:00
Sarah Fortune d2521a8abb Remove compiled files that were committed by mistake (#5082)
* Remove compiled files that were committed by mistake

* Don't JSON encode the grpc message request.

The original grpc-client-base.ts encoded the request message using
```
function encodeRequest(request: any): any {
  if (request === null || request === undefined) {
    return {}
  } else if (typeof request.toJSON === "function") {
    return request.toJSON()
  } else if (typeof request === "object") {
    return { ...request }
  } else {
    return { value: request }
  }
```
But the request object don't have a .toJSON method, so it was not actually converting them
to JSON properly.

Don't JSON encode request to keeo the same behaviour as before.

* Update gitignore
2025-07-21 23:22:25 -07:00
celestial-vault ad2923cd74 migrate save textDocument (#5088) 2025-07-21 23:12:31 -07:00
Sarah Fortune 1ecb24544f fix: Generate type-safe code for the Vscode Protobus service (#5077)
* fix: Generate type-safe code for the Vscode Protobus service

This commit establishes a fully type-safe ProtoBus system by fixing the streaming
response handler type definitions and completing the protobuf-driven architecture.

Key improvements:

• **Complete type safety**: ProtoBus is now completely type-safe with compile-time
  validation of all gRPC service definitions, request/response types, and handler
  signatures

• **Simplified message creation**: No longer need to manually call `Message.create({...})`
  - the generated code handles message instantiation automatically

• **Automated proto parsing**: Eliminated manual parsing of proto files - the build
  system now automatically generates TypeScript definitions from protobuf schemas

• **Proto files as source of truth**: Service names, method names, and message types
  are now definitively controlled by the proto files, ensuring consistency across
  the entire codebase

• **Handler type checking**: ProtoBus handlers are fully type-checked including:
  - Request and response type validation
  - Handler method name verification against proto definitions
  - Streaming vs unary handler signature enforcement

This establishes a robust, type-safe foundation for all gRPC communication between
the extension host and webview components.

* Remove commented out code in script

* Just call handlers directly
2025-07-21 18:40:28 -07:00
celestial-vault 58465d2e32 migrate showSaveDialog hostBridge (#5080)
* migrate showSaveDialog hostBridge

* rework proto type

* update proto type names
2025-07-21 18:20:52 -07:00
Toshii 35c0ced254 launch buttons (#5078) 2025-07-21 16:13:17 -07:00
Ara 63f3b40ef1 Change available Cerebras models + modify context window (#5076)
* Change context length for Cerebras Qwen 3 32b to 64k

* changeset

* changeset

* Create changeset

* Add Cerebras Qwen 3 235B a22b

* Change available Cerebras models

llama-3.3-70b
qwen-3-32b
qwen-3-235b-a22b

* Add changeset

---------

Co-authored-by: Kevin Taylor <kevin.taylor@cerebras.net>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-21 14:03:45 -07:00
Bee 827d002ea6 Fix CLINE_ENVIRONMENT configuration not being passed to webview (#5029)
* Fix CLINE_ENVIRONMENT configuration not being passed to webview

## Problem

The CLINE_ENVIRONMENT configuration set in launch.json was not being properly passed to the webview, causing the webview to break when trying to access environment-specific configurations.

This resulted in:

Webview using incorrect API URLs (always defaulting to production)
Broken authentication flows in development/staging environments
Inconsistent behavior between the main extension and webview components

## Root Cause

The issue occurred because:

Duplicate Configuration Logic: The webview had its own separate config.ts file that was trying to read process.env.CLINE_ENVIRONMENT directly
Environment Variable Propagation: While Vite was configured to pass CLINE_ENVIRONMENT to the build process, the webview's runtime code couldn't access this environment variable properly
Configuration Mismatch: The main extension and webview were using different configuration sources, leading to inconsistent environment settings

* fix credit uri

* replace apiBaseUrl with appBaseUrl

* local option

* fallback changed to app

* change to app url

* merge fixes

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-07-21 13:58:04 -07:00
celestial-vault c040db6d71 Fix options to buildApiHandler (#5064)
* add missing taskId to buildApiHandler

* remove console log
2025-07-21 13:56:32 -07:00
Sarah Fortune 8d5985c8fd refactor(hosts): Simplify the host provider interface for callers (#5057)
* refactor(hosts): Simplify the host provider interface for callers

- Streamline API to reduce complexity for consuming code
- Update all references across core, controller, and integration modules
- Consolidate provider patterns for easier usage
- Rename host-providers.ts to host-provider.ts

# Conflicts:
#	src/core/controller/index.ts
#	src/extension.ts
#	src/integrations/git/commit-message-generator.ts

* Add comment

* In the tests, reset the HostProvider to prevent it complaining that it is being reinitialized

* Update comment

* Fix imports
2025-07-21 12:20:50 -07:00
Bee c970b8030e Refactor: Git commit message generation as a module (#5031)
* Refactor: Git commit message generation as a module

Implement Git commit message generation as a module

Refactors the Git commit message generation functionality into a separate module for better organization and maintainability.

The changes include:

- Moving the commit message generation logic from `src/core/controller/index.ts` to a new module `src/integrations/git/commit-message-generator.ts`.
- Adding a command to abort commit message generation.
- Updating the `cline.generateGitCommitMessage` command to use the new module.
- Adding a context key to disable the generate commit message button when a commit is generating.

This refactoring improves the codebase by:

- Separating concerns: The commit message generation logic is now isolated in its own module, making it easier to understand and maintain.
- Improving testability: The new module can be tested independently of the controller.
- Promoting code reuse: The commit message generation logic can be reused in other parts of the application if needed.

* clean up

* changeset added
2025-07-21 10:43:14 -07:00
Sarah Fortune e7ce38bd85 Generate typed clients for the ProtoBus API (#5063) 2025-07-21 10:09:02 -07:00
Sarah Fortune 600a6e33ed Move duplicated code for loading the protobuf descriptor set into a shared util file. (#5059)
* Move duplicated code for laoding the protobuf descriptor set into a shared util file.

* Formatting

* Update comment
2025-07-20 17:57:22 -07:00
Sarah Fortune caf0d8aee2 Add better error handling the DiffViewProvider.saveDocument() (#5041) 2025-07-19 23:58:46 -07:00
celestial-vault ee33e84c48 Speed up E2E tests (#5045)
* cache vscode and playwright downloads

* remove extra logs

* change cache path to check for vscode

* empty commit

* use optimized e2e script
2025-07-19 21:57:36 -07:00
Sarah Fortune 280138b259 Improve HostBridge error handling and logging robustness (#5037) 2025-07-19 20:54:42 -07:00
Sarah Fortune 924f235c31 Change the script scripts/runclinecore.sh to only install and run cline-core (#5049)
-and not build the zip file.
2025-07-19 17:03:06 -07:00
Tomás Barreiro 06d5bc56bc Use --system-prompt-file to pass the system prompt to Claude Code (#5024)
* Pass the system prompt through a file when using Claude Code

* Support older versions and return better errors

* Add tests

* Add changeset

* Remove outdated docs

* Use a unique file name and clean the file

* Address comments
2025-07-19 12:41:21 -07:00
canvrno b1d82e163c Robust Checkpoints timeout, error handling (#5015)
* Diable checkpoints on tasks where the init timed out, fix settings link

* early warning message

* Added checkpointTrackerErrorMessage to HistoryItem

* Updated some comments related to checkpoints timeouts

* changeset, timer cleanup

* timer cleanup
2025-07-19 12:14:41 -07:00
celestial-vault 9f73cde5e9 fix stale state in model picker searchTerm (#5044) 2025-07-19 11:48:18 -07:00
Ara be2d416359 Updating Mintlify version (#5030)
* Updating Mintlify version

* clean up and ignore docs workspace for lint (#5032)

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-07-18 19:29:28 -07:00
celestial-vault 42ffc30324 Separate plan act model settings (#4827)
* add provider handler options types and only pass those fields when building

* use separate fields for plan and act mode for ephemeral model settings

* post merge issues fixed: bedrock and cline api build handlers; current mode reading in controller/index.ts; adding a couple fields to welcomeView migration

* add in moonshotApiKey to settings-conversion after main merge

* fix type errors

* fix frontend types

* fix code after merge conflicts; switch groq provider to plan/act paradigm

* consolidate to Mode type

* remove promise resolve

* move huggingface provider into the new schema

* add new providers to migration function

* use normalizeApiConfiguration for settings menu provider value to avoid undefined state error
2025-07-18 14:14:31 -07:00
Sarah Fortune b0c67e9f83 Fix clean up part of the build-proto script (#5027) 2025-07-18 13:30:04 -07:00
Sarah Fortune fd366208a1 Fix the structure for the hosts package (#5020)
* Fix the structure for the hosts package.

Right now we support two host platforms: vscode using the internal host bridge service (inside the same process), and other platforms using the external host bridge (using gRPC over local sockets).

The structure of the two packages should mirror each other

```
hosts/
  vscode/
    VscodeDiffViewProvider
    VscodeWebViewProvider
    etc ...
  external/
    ExternalDiffViewProvider
    ExternalWebViewProvider
    etc ...
```

* Fix imports

* Fix imports

* Fix imports
2025-07-18 13:22:23 -07:00
Sarah Fortune 6c7bc58215 Move remaining platform specific code out of the diff view provider. (#5009)
* .

* Move the DecorationController into the hosts/vscode package.
2025-07-18 13:16:19 -07:00
Sarah Fortune f69a378ff4 Add eslint checks for more vscode API calls (#5023)
* Add eslint check for more vscode API calls

Add eslint checks to prevent vscode API calls from being reintroduced after they were switched to the host bridge.

The ones that are not enabled are not completely migrated, so they are not turned on because it would cause too many warnings, and make developers used to ignoring them.

* Update eslint-rules/no-direct-vscode-api.js

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

* Update warning message text

* Move the check for if the file is being included in the linter check or not into its own function

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-18 13:08:13 -07:00
Sarah Fortune 309e3bd85c Fix import in McpHub (#5021) 2025-07-18 11:59:07 -07:00
Daniel Campos Olivares eb6eb371e4 fix: Add documentation to nav menu (#5014) 2025-07-18 11:25:40 -07:00
Mohan Raj Rajamanickam 419e3e4677 fix: mcp servers are not started when disabled (#4501)
* fix: disabled servers should not be started

* refactor to dedupe

* add changeset

* Update moody-crabs-relate.md

* minor comment tweaks

* use unknown instead of any
2025-07-18 10:35:19 -07:00
Sarah Fortune e95eecd65f Just shut up already (#5011)
Don't display a notification when the MCP servers have updated.
2025-07-17 23:32:10 -07:00
Sarah Fortune e83e71cc6d Remove class that is unused, and other class that is totally commented out. (#5010) 2025-07-17 23:00:29 -07:00
Sarah Fortune a9e526e99b Move save() and getDocument() to the platform specific diff classes (#5008)
* Move logic to save the diff document and get the diff content to the platform specific diff view providers.

Add getDocumentText to the diff service.

The ExternalDiffViewProvider should be using its activeDiffEditorId (not the activeDiffEditor, which is the vscode Editor object)

* Check activeDiffEditorId

* Update src/integrations/editor/DiffViewProvider.ts

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

* Use await with this.saveDocument()

* Remove test file

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-17 18:06:54 -10:00
Sarah Fortune 72f16a8c30 Don't need to use Message.create({...}) with the host bridge (#4999)
* Use await when calling async function showMessage.

Use await when calling `windowClient.showMessage`, otherwise the caller doesn't wait for the request to complete and any exceptions are lost.

For the host bridge RPCs, you don't need to do `ShowMessageRequest.create({...})`, you can just pass the request directly like: `{...}. The Message.create() was needed for the ProtoBus because of the way it was implemented, it couldn't be type-checked by the compiled. It's not needed elsewhere.

* Dont use await, because it blocks until the message is dismissed

* Dont need `?.selectedOption`, the response cannot be null

* Dont use await
2025-07-17 20:15:42 -07:00
Toshii 1a3ec9f024 move environment setting to launch & publish (#5002)
* move env setting to launch & publish

* change env name

* Update webview-ui/vite.config.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* update env location

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-07-17 18:49:36 -07:00
Sarah Fortune b3fa3ad0d3 Add new RPCs to the host bridge diff service (#4997)
* Add truncate document to the hostbridge diff service.

# Conflicts:
#	src/standalone/ExternalDiffviewProvider.ts

* Fix typo

* Add host bridge rpcs for the diff service

* Add saveDocument and closeDiff to the host bridge.

* Formatting

* Use the host bridge in ExternalDiffviewProvider

* Make comments less verbose
2025-07-17 18:36:43 -07:00
github-actions[bot] 45241fcccf v3.19.7 Release Notes (#4983)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.19.7

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-17 18:19:36 -07:00
pashpashpash 2a3f0e9418 Adding huggingface provider (#4952)
Co-authored-by: arafatkatze <arafat.da.khan@gmail.com>
2025-07-17 18:00:28 -07:00
Toshii 4334764903 remove warning (#5003) 2025-07-17 17:53:25 -07:00
Bee b3a10243b8 Unify error handling and display logic (#4984)
* Unify error handling and display

Several improvements to error handling and reporting within the Cline extension, focusing on providing more informative error messages to the user and improving telemetry data.

- **Error Handling:**
  - Introduces a `ClineError` class to encapsulate Cline-specific errors, providing structured data about the error (status code, request ID, etc.).
  - The `ErrorService` now creates and logs `ClineError` instances, improving error reporting to Sentry and telemetry.
  - Removes redundant error formatting logic from `src/core/task/utils.ts`, relying on the `ClineError` class for consistent error representation.
  - The Cline API handler now throws the raw error, allowing the `ClineError` class to handle the error formatting.

- **UI Improvements:**
  - Introduces new UI components (`ErrorRow`, `ErrorBlockTitle`) to display error messages in a more user-friendly format within the chat interface.
  - Displays credit limit errors with detailed information and a link to purchase credits.
  - Improves the display of rate limit errors and authentication errors.
  - Adds specific handling for PowerShell-related errors, providing a link to a troubleshooting guide.

- **Telemetry:**
  - Captures provider API errors using `ClineError` data, providing more detailed information about the error in telemetry reports.

- **Other Changes:**
  - Fixes an import path in `src/services/posthog/PostHogClientProvider.ts`.
  - Adds tests for the new UI components.
  - Adds `error` field to `ClineMessage` to transport `ClineError` instances to the webview.

These changes aim to provide a better user experience by displaying more informative error messages and improving the overall reliability of the Cline extension.

* include provider id

* includes model and provider id

* fix test

* return gracefully for empty response
2025-07-17 16:21:18 -07:00
Bee 8e95c136a6 Handle auth state changes in all extension windows (#4987)
* Handle auth state changes in all extension windows

Addresses an issue where authentication state changes (login/logout) were not being properly propagated across all extension windows.

The `onDidChange` event handler for `clineAccountId` secret now checks if the secret was added/updated (login) or removed (logout).

- If the secret exists, `restoreRefreshTokenAndRetrieveAuthInfo` is called to restore auth info (login from another window).
- If the secret is removed, `handleDeauth` is called to handle logout for all windows.

This ensures that all extension windows are kept in sync with the current authentication state.

* changeset
2025-07-17 15:40:30 -07:00
Daniel Campos Olivares 0b66faa1dd chore: Introduce SAP AI Core documentation (#4961)
* feat: Introduce SAP AI Core documentation

* fix: Markdown lint

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>

* fix: Typo

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>

---------

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>
2025-07-17 14:10:30 -07:00
Sarah Fortune 3d2dc1c5c4 Move platform specific code out of the DiffViewProvider and into the VscodeDiffViewProvider (#4980)
* Add a way to reset state for the platform specific diff view providers.

Add the abstract method `resetDiffView()` to the DiffViewProvider.

On Vscode it reset the active diff editor and decorations.

On External diff view providers, it reset the diff editor ID.

* Add a way to truncate the document to the platform specific diff view providers.

This is used when the last update is recieved to remove any content from the bottom of the document.

* Move `closeDiffView` to the platform specific diff view classes.

* Update comment

* Use await for async function

* Move setting the cursor position into replaceText
2025-07-17 12:35:48 -07:00
Andrei Eternal 028412579b Standalone Terminal Manager & remove other vscode-impls (now covered by host bridge) (#4993)
* Revert "experimental vscode impls & build-proto cleanup (#4493)"

This reverts commit f00c5f4ecc.

* leave terminal impls

* terminal manager switch for standalone

* Export standaloneTerminalManager to global

* clean up standalone terminal switch

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-07-17 12:11:45 -07:00
Sarah Fortune f04788c2ec Move the logic to scroll the diff editor window into the platform specific classes (#4977)
* Move the logic to scroll the diff editor window into the platform specific classes.

Move the current logic into the VscodeDiffViewProvider.

The ExternalDiffViewProvider will use the host bridge to scroll the editor tab. But for now it doesn't do anything.

* Add comment

* Remove log messages
2025-07-17 11:26:40 -07:00
Toshii 5fba39f886 move to simple config for setting env details of backend (#4978)
* backend env

* frontend env config

* rename config

* preview update

* separate mcp link

* mcp url updated

* config change to local

* webview config to local
2025-07-16 22:53:08 -07:00
Toshii 9a4e3655b3 remove import (#4981) 2025-07-16 19:40:43 -07:00
Tomás Barreiro b18ad77539 Improve Claude Code errors and create Docs (#4968)
* Create docs

* Improve the Claude Code error messages

* Replace with remote image
2025-07-16 18:22:01 -07:00
github-actions[bot] c50fce8101 v3.19.6 Release Notes (#4976)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.19.6

* more modifications

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-16 17:21:22 -07:00
Sarah Fortune 47f84d7c2c Improve generated code that registers the vscode host bridge handlers. (#4972) 2025-07-16 17:14:37 -07:00
Ara 17c57162cd Refactoring terminal process logic and edge cases for simplicity (#4673)
* Refactor terminal output capture for better reliability

- Extract emitCurrentTerminalContents() as a private method for reusability
- Improve handling of commands with no/delayed output by capturing actual terminal contents instead of generic messages
- Add multiple fallback attempts (100ms, 1s, 3s) for terminals without shell integration
- Enhance timeout comments to clarify the 3-second delay purpose
- Add .tool-versions file (likely for version management)

* Refactor TerminalProcess run method into smaller functions

Split the monolithic run() method into focused helper methods for better
maintainability and readability. Extracted initialization, shell integration
execution, stream processing, and cleanup logic into separate private methods.
This improves code organization without changing functionality.

* Fixing the handling of echo commands and changing the wording of the terminal capture line

* fix: Embracing the ffmpeg for opus support
2025-07-16 16:33:01 -07:00
Toshii 0f1f3d84f7 add auto refresh to accounts page (#4901)
* add auto refresh to accounts page

* update

* 10 sec
2025-07-16 16:14:18 -07:00
Saoud Rizwan 0c5832b7a2 Fix kimi k2 provider sorting (#4975)
* Fix kimi2 provider sorting

* Create smart-flies-eat.md
2025-07-16 16:11:12 -07:00
celestial-vault 11c4c58ed3 update the current task's consecutiveAutoApprovedRequestsCount on max request change (#4955) 2025-07-16 16:07:01 -07:00
pashpashpash 27bf78ddbd swapping latest diff algo as default (#4412)
* swapping latest diff algo as default

* updating

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-16 15:59:48 -07:00
pashpashpash c3161567d3 removing unneeded docs section (#4974) 2025-07-16 15:50:08 -07:00
pashpashpash 516d7bccc9 adding documentation workflow (#4598)
* adding documentation workflow

* Update .clinerules/workflows/writing-documentation.md

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

* good example

* good example

* language

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-16 15:37:24 -07:00
pashpashpash e91c8208a3 fix streamlit dashboard to be compatible with both old and new versions of streamlit (#4922) 2025-07-16 15:28:02 -07:00
Sarah Fortune 0fb40527c8 Add a script to run the standalone service. (#4966)
* Add a script to run the standalone service.

Remove spammy log statements.

* Add comment

* Fix some vscode stubs

* Update scripts/runstandalone.sh

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

* Update scripts/runstandalone.sh

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

* Update scripts/runstandalone.sh

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

* Remove old script

* Add comment

* Add comment

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-16 15:12:52 -07:00
Sarah Fortune 8a2e90084d Change the port numbers for the ProtoBus service and HostBridge. (#4969)
Don't use the default gRPC port number because it's more likely to already be in use.
2025-07-16 11:28:07 -07:00
Sarah Fortune 4c3384988c open-file calls vscode.workspace.openTextDocument but doesn't use the result. (#4960) 2025-07-16 03:01:25 -07:00
Daniel Steigman 8539bdce24 Upgraded telemetry to capture each message turn separately (#4954)
* refactor: Ugraded telemetry to capture each message turn seperatly

* go back to the correct posthog key oops
2025-07-15 22:49:35 -07:00
Bee cd7f3ef6a7 Disable recording webview click events (#4709)
* Disable recording webview click events

Introduces a temporary measure to disable the recording of webview click events in PostHog. This is achieved by adding a `temporaryDisabled` flag that, when true, prevents the initialization of PostHog and stops the identification of users.

This change is intended to be temporary and should be reverted in a future commit by removing the `temporaryDisabled` flag.

* Use separate PostHog config for development environment

This commit introduces a separate PostHog project for the development environment. This allows us to track events in the development environment without polluting the production data.

The `posthogConfig` now uses `posthogDevEnvConfig` when `process.env.isDev` is true, and `posthogProdConfig` otherwise.

* process.env.IS_DEV

* Update src/shared/services/config/posthog-config.ts

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

* fix format

---------

Co-authored-by: Beatrix Woo <beatrix@cline.bot>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-15 22:46:58 -07:00
github-actions[bot] 80fbcda03b v3.19.5 Release Notes (#4941)
-   Add Groq as a new API provider with support for all Groq models including Kimi-K2
-   Add user role display in organization UI for Cline account users
-   Fix message dialogs not showing option buttons properly
-   Fix authentication issues when using multiple VSCode windows
2025-07-15 21:49:06 -07:00
pashpashpash cef79e06db not showing request id when insufficient balance (#4953)
* not showing request id when insufficient balance

* whoops

* betterrr
2025-07-15 21:38:11 -07:00
Ara 5dddbef65c Adding Groq provider (#4943) 2025-07-15 19:47:56 -07:00
Bee b6f6358d4a Set up E2E tests with Playwright (#4721)
* Add Playwright E2E tests

Adding end-to-end (E2E) testing capabilities using Playwright. It also updates the `@vscode/test-electron` dependency.

The changes include:

- Adding Playwright as a dev dependency.
- Adding `e2e` and `e2e:build` scripts to `package.json` for running E2E tests.
- Adding `@playwright/test` to the list of dependencies.
- Updating `@vscode/test-electron` from `2.4.1` to `2.5.2`.
- Adding `test-results` to `.gitignore` to exclude test result files.

* wip: github workflow

Adding a new GitHub Actions workflow for running end-to-end (E2E) tests using Playwright. The workflow is triggered on push to the main branch, pull requests, and manual workflow dispatch.

The workflow defines a matrix strategy to run tests on different runners (Ubuntu and Windows) and shards. It also uploads Playwright recordings as artifacts if the tests fail.

* add @vscode/vsce as dev dep

* update workflow

* apply feedback

* fix test workflows

* add command palette helper

This commit improves the reliability and efficiency of the end-to-end tests by:

- Adding a delay to the "Let's go!" button click in the auth test to ensure the action is properly registered.
- Adding an expectation to ensure the "Get Started for Free" button is no longer visible after API key submission.
- Caching the "Use your own API key" button to avoid redundant lookups.
- Introducing a `runCommandPalette` helper function to streamline command execution within the VS Code environment.
- Disabling notifications before running the tests to prevent interference.

* state change

* set TEMP_PROFILE

* v3.18.7 Release Notes

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.7

---------

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

* Remove optimistic loading from organization dropdown (#4746)

* update build script to javascript

* fix match

* Add mode switching to chat test

* expected

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
2025-07-16 07:29:58 +05:30
Bee e607d02ab2 Fix: pass items to showMessage in VS Code host bridge (#4949) 2025-07-15 18:14:30 -07:00
Nick Baumann b5e2916bd6 docs: Update Claude Code documentation to include Pro plans alongside Max plans (#4948) 2025-07-15 17:00:45 -07:00
Sarah Fortune 371db77007 Move the vscode specific classes into the hosts/vscode package. (#4947)
* Move the vscode specific classes into the `hosts/vscode` package.

Move the vscode specific classes VscodeDiffViewProvider and VscodeWebviewProvider in the `hosts/vscode` package.

I am doing this so that the vscode-specific code is contained in one package instead of being mixed with the code that is meant to be platform-agnostic.

This also makes it easier for us to see which parts of the codebase are still using the vscode APIs and need to be migrated, and for the linter rules
that check that vscode API calls are not reintroduced after they are migrated to the host bridge.

* Use absolute imports instead of relative
2025-07-15 16:46:58 -07:00
Sarah Fortune 80f2e9f6ea Fix bad merge (#4946) 2025-07-15 16:26:12 -07:00
celestial-vault b46d396de2 add webview type checking to check-types (#4944) 2025-07-15 16:20:07 -07:00
Sarah Fortune 8683980c90 Move the vscode hostbridge handlers into their own package (#4945)
* Move the generated files for the host bridge into the 'src/generated' directory

Move the generated index.ts and methods.ts files for the host bridge into the 'src/generated' directory

I'm doing this because when all the generated files are one in location its a) easier to see from the import statement that the code is generated, b) it's easier to change the package(s) of the generated files, and c) easier to reset/clean the build state.

* Update import path

* Move the hostbridge handlers in the a hostbridge packge.

Move the hostbridge handlers out of the top level of the vscode package into their own subpackage.
I have to move all the vscode specific code into the `hosts/vscode` package, and I want the hostbridge handlers to be grouped together, not mixed in with things like the VscodeDiffViewProvider, VscodeWebviewProvider etc.
2025-07-15 16:12:48 -07:00
Bee b916e495e6 Remove credit validation from request (#4903)
Removes the credit validation check from the `createMessage` function in `src/api/providers/cline.ts`. The `validateRequest` function, which checks if the user has sufficient credits, has also been removed from `src/services/account/ClineAccountService.ts`.

The credit validation is no longer performed before sending a message to the Cline API.

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-15 16:08:08 -07:00
Sarah Fortune d45077c4c5 Move the generated files for the host bridge into the 'src/generated' (#4942)
* Move the generated files for the host bridge into the 'src/generated' directory

Move the generated index.ts and methods.ts files for the host bridge into the 'src/generated' directory

I'm doing this because when all the generated files are one in location its a) easier to see from the import statement that the code is generated, b) it's easier to change the package(s) of the generated files, and c) easier to reset/clean the build state.

* Update import path
2025-07-15 16:00:02 -07:00
Bee 6ced4472d3 Capture provider API errors (#4936)
* Capture provider API errors

Introduces a new telemetry event to capture errors returned by API providers. This will allow us to better monitor the reliability and performance of different providers and identify potential issues.

The following changes were made:

- Added a `captureProviderApiError` method to the `TelemetryService` to record provider API errors.
- Added a new `PROVIDER_API_ERROR` event to the `TelemetryService.EVENTS.TASK` enum.
- Modified the `Task` class to capture and report provider API errors, including the error message, status code, and request ID.
- Added `extractErrorDetails` to extract the status code, message, and request ID from an error object.
- Updated `formatErrorWithStatusCode` to use `extractErrorDetails`.

* clean up

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-15 15:37:25 -07:00
Bee dcb39a77f2 Display user role in organization (#4937)
* Display user role in organization

Adds a new feature to the Account View that displays the user's role within the currently selected organization.

- Added a `getMainRole` function to determine the user's primary role (Owner, Admin, or Member) based on the roles array.
- Display a VSCodeTag component showing the user's role next to the organization dropdown.
- Updated the organization dropdown to use className instead of style for width.

* changeset

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-15 15:36:47 -07:00
Sarah Fortune 3301577934 Add diff.replaceText to the host bridge. (#4879)
Update the diff service to use a unique id to track open diff editor in external platforms.
Store the diff Id in the ExternalDiffViewEditor when the diff is opened. It will serve the same purpose as the activeDiffEditor property on vscode, it can be used to manipulate the diff editor tab.
Add the implementation of replaceText in the ExternalDiffViewEditor.
2025-07-15 14:50:23 -07:00
Bee a36c11eb97 Remove state parameter from auth callback (#4845)
* Remove state parameter from auth callback

Removes the state parameter that contains auth nonce and the associated logic.

The state parameter which contains the auth nonce in the auth callback doesn't work with multi-windows as each window contains its own nonce. As the provider parameter is sufficient to identify the auth provider we could remove the auth nonce to avoid complications.

* remove authNonce

* changeset

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-16 01:20:51 +05:30
Sarah Fortune 7d1f199883 Move the generated file hosts/vscode/host-grpc-service-config.ts in the src/generated directory. (#4938)
Rename some of the methods in the build-protos script to be more readable.
2025-07-15 12:39:21 -07:00
Sarah Fortune 6a1e0e518b Move the build-proto script into the scripts directory (#4935)
* Move the build-protos script into the scripts directory.

* Reorder imports
2025-07-15 12:04:04 -07:00
pashpashpash 004b313d20 Update diff edit evals README.md (#4920)
* Update README.md

* Update README.md
2025-07-16 00:17:14 +05:30
Saoud Rizwan bf37bfa7a3 Add vision capability to moonshot v1 (#4926) 2025-07-15 04:15:39 -07:00
github-actions[bot] e6dbde70a9 v3.19.4 Release Notes (#4925)
* 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-07-15 03:57:26 -07:00
Saoud Rizwan cb9a339442 Add ability to choose chinese endpoint for Moonshot provider (#4924)
* Add ability to choose chinese endpoint for Moonshot provider

* Create fluffy-planes-prove.md
2025-07-15 03:33:17 -07:00
github-actions[bot] 47b5df14d7 v3.19.3 Release Notes (#4917)
* 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-07-15 01:32:06 -07:00
Saoud Rizwan 4ecbecb1e2 Add Moonshot AI provider (#4913)
* Add Moonshot AI provider

* Create little-pens-switch.md
2025-07-15 01:16:45 -07:00
github-actions[bot] fadaf00835 v3.19.2 Release Notes (#4910)
* 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-07-14 22:19:20 -07:00
Bee 575cfd48cc Includes request ID in error returned by Cline API (#4909)
* Includes request ID in error returned by Cline API

Adding the request ID to error messages to aid in debugging for users.

* Use constant for auth error message; revert change from previous PR

* Fix webview auth status if null/undefined user is passed in auth status message

* Create nasty-parents-play.md

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-14 22:16:50 -07:00
Saoud Rizwan a0787e3d36 Release Version v3.19.1 (#4908) 2025-07-14 21:51:24 -07:00
Nidelson Gimenez c9b922009f docs: improve documentation (#4863)
* docs: fix typo

* improved clarity in the local development instructions

* Update CONTRIBUTING.md

* Create wise-hairs-grow.md

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-14 21:42:06 -07:00
github-actions[bot] 2d6ff38e69 v3.18.15 Release Notes (#4890)
* 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-07-14 21:01:12 -07:00
Saoud Rizwan 3069e27413 Add groq to kimi providers (#4906)
* Add groq to kimi providers

* Create fair-glasses-lick.md
2025-07-14 20:54:34 -07:00
Saoud Rizwan 57c8b8120d Revert "pass linter errors with read_file (#4159)" (#4905)
This reverts commit 5e2b199377.
2025-07-14 20:18:19 -07:00
Saoud Rizwan 5243f0b9b1 Set default kimi provider to together (#4904) 2025-07-14 19:49:45 -07:00
celestial-vault c014060275 remove unused ExtensionStateContext setters (#4865) 2025-07-14 18:35:54 -07:00
celestial-vault d790ce86a0 Add markdown parsing to MCP responses (#4862)
* refactor out useEffect logic

* add markdown parsing to mcp response

* add display mode to global state; simplify state flow

* fix imports after merge conflicts
2025-07-14 18:17:14 -07:00
celestial-vault 5e2b199377 pass linter errors with read_file (#4159)
* pass linter errors with read_file

* changeset

* add code back after merge with main
2025-07-14 16:49:37 -07:00
celestial-vault 9234d0cdc4 [McpResponseDisplay] Refactor out useEffect logic to helper function (#4852)
* refactor out useEffect logic

* refactor: memoize renderSegment with useCallback
2025-07-14 15:29:50 -07:00
Sarah Fortune db1db8c95d Change the name of the cline core script from standalone.js to cline-core.js (#4894)
Update the name of the script so that you can tell from the process name what it is,
standalone.js is too vague to be able to associate it with cline.
2025-07-14 15:22:11 -07:00
Sarah Fortune f53af72643 Update the vscode usages script to separate out vscode.commands.executeCommand calls. (#4891)
vscode.commands.executeCommand runs other vscode commands, so we need the know which commands are being run.
2025-07-14 15:21:27 -07:00
Massimiliano Angelino 260e0d5f8e feat: adding Bedrock Api Keys support (#4728) 2025-07-15 00:19:58 +05:30
celestial-vault 5b68ee5523 Add kimi-k2 as trending model (#4889)
* add kimi k2 as trending model

* changeset

* adjust wording
2025-07-14 11:21:26 -07:00
Ara 3e5abd5e72 Removing reasoning UX for Grok 4 models and correct pricing (#4849)
* Removing reasoning UX for Grok 4 models and correct pricing

* More resiliency
2025-07-13 17:36:41 -07:00
Sarah Fortune 1ba5873454 DiffViewProvider refactoring for the host bridge (#4877)
* DiffViewProvider refactoring.

Move the platform specific logic for updating the diff out of DiffViewProvider and into VscodeDiffViewProvider.replaceText().
Add a stub handler for replaceText in the ExternalDiffviewProvider.

* Add comment to replaceText()

* Update src/integrations/editor/DiffViewProvider.ts

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-13 16:28:09 -07:00
Sarah Fortune 1bdaf8ef6f Implement openDiffEditor in the ExternalDiffViewProvider (#4875)
Use the host bridge to open the diff view.
2025-07-13 14:43:33 -07:00
pashpashpash 7f6038c74e better balance display (#4867) 2025-07-12 20:36:19 -07:00
Sarah Fortune 2fd9635b97 Add a vscode specific DiffViewProvider, and one for external platforms. (#4866)
* Add a vscode specific DiffViewProvider, and one for external platforms.

Make the DiffViewProvider class abstract, with two implementations the VscodeDiffViewProvider and the ExternalDiffViewProvider.
Move the vscode specific code to open the diff view into VscodeDiffViewProvider.openDiffEditor. The ExternalDiffViewProvider will use the host bridge to open the diff view.
Add a way to get the correct DiffViewProvider for the platform to the host provider.

Right now, there is only platform specific logic for `open`, the other functions like `scroll` and `replaceText` will be added in a follow up PR. The end-state will look like [this](https://github.com/cline/cline/compare/main...sjf-gg), but it's easier to test and review each part separately.

* In the VscodeDiffViewProvider, use the previous way of getting the open diff editor, before it was switched to the host bridge.

Using the host bridge doesn't help here, because we really need a reference to the actual vscode text editor document, which the host bridge can't return. So, it was doing openDocument, and then immediately using the vscode SDK to get the editor reference. When, really the diff editor was already open, and we only need the editor reference.
2025-07-12 12:45:57 -07:00
Sarah Fortune 568b834338 Add DiffService to the host bridge. (#4841)
* Add DiffService to the host bridge.

Add a new diff service with a method to open the diff view for a file.
On vscode, we will not use the hostbridge for opening the diff editor, so the vscode handler just throws an error.

* Update diff.proto

* Fix proto import
2025-07-12 12:43:55 -07:00
github-actions[bot] 381e9b9d1f v3.18.14 Release Notes (#4857)
* 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-07-12 02:47:50 -07:00
Saoud Rizwan d86861629d Fix re-sign in flow (#4856)
* Fix re-sign in flow

* Fix AuthState user representation to webview to fix issue where invalid auth was still showing as logged in

* Fix comments

* Create stale-peas-give.md
2025-07-12 02:45:18 -07:00
github-actions[bot] 7fb10ba053 v3.18.13 Release Notes (#4846)
* 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-07-12 02:03:43 -07:00
Saoud Rizwan b7ca95ed57 Replace firebase user object session logic with google endpoint to get id token and custom jwt validation (#4853)
* Replace firebase user object session logic with google endpoint to get id token and custom jwt validation

* Add comments

* Update src/services/account/ClineAccountService.ts

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

* Create green-drinks-rest.md

* Remove signOut

* Ensure that refresh token is passed properly in params

* Name function better and add comment; fix org switch logic

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-12 02:00:52 -07:00
Saoud Rizwan 6bd8726dd6 Saoudrizwan/show resignin button (#4855)
* Show sign in button when cline account shows auth error

* Add comment
2025-07-12 01:00:42 -07:00
Saoud Rizwan 347d4f48da Remove cancelReason when retrying request to show the proper animation in ChatRow (#4854) 2025-07-12 00:59:44 -07:00
canvrno baa5aaa0a7 git branch analysis workflow (#4717) 2025-07-11 17:46:46 -07:00
Bee 16f066dcbf Host bridge migration: showErrorMessage, showInformationMessage, showWarningMessage (#4745)
* host bridge migration: showErrorMessage & showInformationMessage & showWarningMessage

Introduces the `showMessage` host API to the VS Code extension, allowing the host to display informational, warning, and error messages to the user.

The changes include:

- A new `ShowMessageRequest` and `SelectedResponse` message definition in `proto/host/window.proto` to define the request and response structure for showing messages.
- A new file `src/hosts/vscode/window/showMessage.ts` that implements the `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` functions. These functions use the VS Code API to display messages based on the `ShowMessageRequest`.
- Replace all current call sites with the new implementations

* define the request structure

This commit introduces the `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` host APIs to the VS Code extension. These APIs allow the host to display informational, warning, and error messages to the user.

The changes include:

- Added `ShowErrorMessageRequest`, `ShowInformationMessageRequest`, and `ShowWarningMessageRequest` message definitions in `proto/host/window.proto` to define the request structure for showing messages.
- Added new files `src/hosts/vscode/window/showErrorMessage.ts`, `src/hosts/vscode/window/showInformationMessage.ts`, and `src/hosts/vscode/window/showWarningMessage.ts` that implement the corresponding functions. These functions use the VS Code API to display messages based on the provided message and options.

* Simplify showMessage functions and use options array

The `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` functions in `src/hosts/vscode/window/` have been refactored for simplification.

- The functions now directly destructure the `modal`, `detail`, and `items` properties from the input object.
- The VS Code API calls now directly pass the `modal` and `detail` options, and use the spread operator to pass the `items.options` array as additional arguments. This removes the need for conditional logic to construct the options object.

* wip: apply feedback

* Update src/integrations/git/commit-message-generator.ts

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

* merge conflict

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-11 17:29:01 -07:00
celestial-vault 59f42c7a81 [AccountView] - Default balance to dashes (#4844)
* default balance to dashes

* changeset

* add balance formatter
2025-07-12 05:55:47 +05:30
celestial-vault 3a86938a56 pass extension version in headers (#4843) 2025-07-11 16:16:23 -07:00
Sarah Fortune 042bf359a9 DiffViewProvider refactoring for the host bridge (#4836)
* DiffViewProvider refactoring

Move the vscode specific code to setup and open the diff view editor into `openDiffEditor`.

* Change openDiffEditor to return void instead of returning a vscode specific editor type
2025-07-11 14:18:26 -07:00
Bee 17200740a8 Trigger auth status update on secret storage change (#4837)
* Trigger auth status update on secret storage change

The auth status should be updated when the clineAccountId secret changes. This commit adds a listener to the secrets.onDidChange event and calls sendAuthStatusUpdate when the clineAccountId secret changes. This ensures that the auth status is always up-to-date.

* restore

* afgain

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-11 12:53:24 -07:00
Sarah Fortune c38f443ec4 DiffViewProvider clean-up (#4835)
* In the DiffViewProvider, store the absolutePath instead of the cwd.

Remove unused var `scrollListener`.

* Remove cwd param

* Don't call getCwd in a loop
2025-07-11 10:49:13 -07:00
github-actions[bot] 13f1f0d44b v3.18.12 Release Notes (#4819)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.12

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-10 19:50:20 -07:00
pashpashpash 30a169e0c3 supporting buy_credits_url response from backend (#4823) 2025-07-10 19:33:25 -07:00
Ara 77ab7f8ef9 Fix the flaky Cline provider switching toggle (#4791)
* Fix Flaky Cline provider toggle

* More resiliency
2025-07-10 19:32:19 -07:00
akfoster 6d5ea98026 fix: insufficient credits display (#4821)
* fix: insufficient credits display

* add changeset

* Update src/api/providers/cline.ts

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-10 19:21:59 -07:00
Sarah Fortune 1879798b68 Remove unused vars from the DiffViewProvider (#4818)
Remove `lastFirstVisibleLine`, this value is set, but never read.
Remove `shouldAutoScroll`, this is always true.
2025-07-10 16:10:13 -07:00
Bee 3ed47fba17 Request validation and remove credit balance for cline team (#4817)
* Fix: Ensure Cline client is initialized with the latest auth token

The Cline client was not being re-initialized with the latest authentication token after the user signs in. This resulted in the client using an outdated or non-existent token, leading to authentication errors when making API requests.

This commit ensures that the Cline client is initialized with the most recent authentication token by setting the `apiKey` property of the `OpenAI` client instance to the current auth token retrieved from `AuthService` before every request. This guarantees that the client always uses the valid and up-to-date token for authentication.

* changeset

* move this._authService.getAuthToken() to ensureClient

* Request validation and remove credit balance for cline team

Add request validation for Cline API requests and fix the user interface for displaying credit-related information in UI.

The changes include:

- **Credit Balance Validation:** Implemented `validateRequest` method in `ClineAccountService` to check user's credit balance before making API requests.  Requests from active organizations are skipped. An error is thrown if the balance is insufficient.
- **Error Handling:** Improved error handling in `ClineHandler` to provide more informative error messages to the user.
- **UI Enhancements:**
    - Updated `CreditLimitError` component to display the current balance that matches the account view balance format (4 decimal places).
    - Modified `ChatRow` to parse error messages and display the `CreditLimitError` component when applicable.
    - Updated `AccountView` to only display credit balance for user accounts, not organization accounts.
    - Removed unused props from `CreditLimitError` component. Context: https://cline-space.slack.com/archives/C08KYBFL9DJ/p1752182278852399?thread_ts=1752164726.247429&cid=C08KYBFL9DJ
- **Dependencies:** Updated dependencies in `webview-ui` to include `tailwindcss` and configured `tailwind.config.js` to support VSCode theme variables.

* changeset

* Update src/api/providers/cline.ts

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

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-10 15:58:13 -07:00
Sarah Fortune 439e99d8d1 Fix script that packages the standalone zip. (#4816)
The vscode packager VCE has different logic that the npm module `ignore`, so it was not including the same files as VCE.

Just copy how VCE uses the .vscodeignore file in the packaging script.

Fix the ignore for demo.gif, it was still getting included because it was only matching demo.gif at the top level.
Also ignore .github and .husky.
2025-07-10 15:57:22 -07:00
github-actions[bot] 8de99c90a6 v3.18.11 Release Notes (#4814) 2025-07-10 13:49:09 -07:00
Bee 5b475fe88c Fix: Ensure Cline client is initialized with the latest auth token (#4813)
* Fix: Ensure Cline client is initialized with the latest auth token

The Cline client was not being re-initialized with the latest authentication token after the user signs in. This resulted in the client using an outdated or non-existent token, leading to authentication errors when making API requests.

This commit ensures that the Cline client is initialized with the most recent authentication token by setting the `apiKey` property of the `OpenAI` client instance to the current auth token retrieved from `AuthService` before every request. This guarantees that the client always uses the valid and up-to-date token for authentication.

* changeset

* move this._authService.getAuthToken() to ensureClient

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-10 13:13:30 -07:00
Bee 190d3bd2dc Fix: Improve auth flow and state validation (#4786)
Improves the authentication flow and state validation process.  We no longer reset the auth nounce after each sign in as AuthService is a singleton and there is no risk of nonce collision between different users as only one user can be signed in at a time.

Changes:
    - The `authNonce` is now generated once during `AuthService` instantiation and stored as a read-only property. This ensures that the nonce remains consistent throughout the authentication process.
    - The `resetAuthNonce` method has been removed, as the nonce is no longer meant to be reset.
    - The `createAuthRequest` method now uses the URL object for more graceful query construction.
- **Controller:**
    - The `validateAuthState` method has been simplified to directly compare the provided state with the stored `authNonce`.
- **Extension:**
    - The extension now prompts the user for confirmation if the state parameter in the auth callback does not match the stored `authNonce`. This allows sign-ins initiated from outside the extension (e.g., Cline web) to be handled correctly.

Issue: The issue is that the authNonce is being reset in the validateAuthState method in the Controller, but the extension.ts is directly accessing authService.authNonce without going through the validation method. This creates a race condition where:

User initiates auth, nonce is generated
Auth callback comes back with the state
If there are multiple auth attempts or the callback is processed multiple times, the nonce might be reset before the validation in extension.ts happens
User gets "Invalid auth state" error

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-10 21:53:36 +05:30
github-actions[bot] d0069eb7cb Changeset version bump (#4785)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.9 with improved descriptions

* changeset version bump

* Updating CHANGELOG.md format

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

* ahugosaia'ohs'gasgh

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-10 00:05:06 -07:00
pashpashpash 268bbec7f1 recommend grok 4 (#4798)
* recommend grok 4

* changeset
2025-07-09 23:42:04 -07:00
pashpashpash 192cd2602e Pashpashpash/grok 4 (#4793)
* grok 4

* numbers
2025-07-09 23:36:06 -07:00
Andrei Eternal c724edd118 Replace use of vscode.fs.writeFile with node equivalent (#4790)
* Replace use of vscode.fs.writeFile with node equivalent

* format fix

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-07-09 18:11:47 -07:00
celestial-vault 0eaf350d87 Provider handler param types (#4729)
* add provider handler options types and only pass those fields when building

* field was removed in merge, remove it
2025-07-09 16:33:27 -07:00
Ara 398bc87a64 Adding Thinking Token Config to Gemini 2.5 pro model and adding gemini 2.5 flash preview (#4668)
* Adding Thinking Token Config to Gemini 2.5 pro model

* Adding Thinking Token Config to Gemini 2.5 pro model

* Adding console logs

* Adding console logs

* Adding console logs
2025-07-10 03:42:07 +05:30
github-actions[bot] 0ec447c992 v3.18.9 Release Notes (#4783)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.9 with improved descriptions

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-09 14:44:25 -07:00
pashpashpash ba41131b36 Pashpashpash/enabling streaming cline (#4784)
* grok 4

* fixing streaming in cline provider

* removing grok promo from cline provider

* changeset

* oopsie

* oopsie
2025-07-09 14:33:55 -07:00
Bee 0042230acd Handle authentication errors for Cline provider (#4781)
* Fix: Cline authentication errors

This commit improves error handling for Cline authentication. It adds checks for the presence of a Cline account authentication token before making API requests. If the token is missing, it throws an "Unauthorized" error, prompting the user to sign in. Additionally, it catches `ERR_BAD_REQUEST` or 401 errors from the Cline API and throws the same "Unauthorized" error, providing a more user-friendly experience when authentication fails.

* add changeset

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-10 02:15:27 +05:30
ncrypted | Oliver 9ff705ffc0 Remove: Pricing for SAP AI Core Provider (#4778)
* remove: pricing for sapaicore

* add: model description hint regarding capacity unit pricing
2025-07-09 10:38:16 -07:00
Dennise Bartlett dea016408c Update Changelog and Versions (#4751) 2025-07-08 20:13:37 -07:00
Frostbourne bf82444aec grok 3 cache pricing (#4750) 2025-07-08 19:59:17 -07:00
github-actions[bot] 988b65f1ad v3.18.7 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.7

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-08 18:41:16 -07:00
Dennise Bartlett d838bcdc34 Fix account buttons (#4742)
* Update links for account buttons

* add dashboard url

* setup links for future changes

---------

Co-authored-by: frostbournesb <frostbournesb@protonmail.com>
2025-07-08 17:56:38 -07:00
pashpashpash ff1e3297a8 ending grok promo in UI (#4740)
* ending grok promo in UI

* changeset
2025-07-08 17:30:06 -07:00
github-actions[bot] 2428389620 v3.18.6 Release Notes
v3.18.6 Release Notes
2025-07-08 16:16:52 -07:00
Dennise Bartlett 6f8627bb5f Organization Accounts added to Extension. Refactor Auth components for Accounts
* Working organization and personal inference, account switching, and usage/credit reporting.

* Organization dropdown tweaks (#4710)

* organization dropdown tweaks

* reverted AuthService

* Update Firebase Provider and Auth Service to support re-hydration of the user credentials

* Add Github Auth Flow

* Fix merge conflicts

* Fix some dumb typing

* recreate dropdown value when initialized (#4716)

* added changeset

* Update urls to production and handle some PR concerns

* Get user credits when signing in (#4736)

* get user balance when signing in instead of when there is no active org

* swapped order of getUserCredits, made calls async

* async changes continued, moved setIsLoading to finally

---------

Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-08 15:59:08 -07:00
Bee 1e81d98abf Fix fresh install mode launch config (#4732)
* Fix fresh install mode launch config

Updates the launch configuration in `.vscode/launch.json` to include a temporary profile and user data directory. This fixes the issue where the launch config does not start in fresh install mode for extension development. This change prevents  interference from existing settings and extensions. The `--user-data-dir=/tmp/cline/user` argument specifies a temporary directory for user data, while `--profile-temp` ensures a clean profile is used for each launch. Also, `--sync=off` is added to disable settings sync.

* update name

* tmp dir

* Implement in-memory storage for temporary profiles

Adds in-memory storage for global state, workspace state, and secrets when running in a temporary profile. This is determined by the `TEMP_PROFILE` environment variable being set to "true". When active, the `updateGlobalState`, `getGlobalState`, `updateGlobalStateBatch`, `updateSecretsBatch`, `storeSecret`, `getSecret`, `updateWorkspaceState`, and `getWorkspaceState` functions will use `Map` objects to store and retrieve data instead of VS Code's `globalState`, `secrets`, and `workspaceState` APIs. This ensures that no data is persisted to disk when using a temporary profile, providing a clean environment for testing and development.

* Refactor tmp user directory for dev launch config

This commit refactors the temporary user directory used in the development launch configuration.

- Updates `.vscode/launch.json` to use `${workspaceFolder}/dist/tmp/user` for the `--user-data-dir` argument, ensuring the temporary profile is located within the workspace.
- Adds `TEMP_PROFILE: "true"` to the environment variables in `.vscode/launch.json` to enable in-memory storage for temporary profiles.
- Renames the `clean-sandbox` task in `.vscode/tasks.json` to `clean-tmp-user` and modifies its command to remove and recreate the `${workspaceFolder}/dist/tmp/user` directory. This ensures a clean environment for each launch.

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-08 15:05:11 -07:00
Sarah Fortune 267170920a Update the packaging script for the standalone app to include the same files as the extension in the zip (#4708)
* Package the same files for the standalone app and the extension

When packaging the standalone app use the same .vscodeignore that the vscode packager uses to decide which files to include.
Exclude extra files from the vscode extension that aren't needed: dist-standalone, old_docs and eslint-rules.

* Ignore the whole directory, not just the contents.

* Don't package .DS_Store files

* Update comment
2025-07-08 11:16:49 -07:00
Sarah Fortune 386c78c114 Update the no-vscode-postmessage eslint rule to check for any of the vscode SDK calls that have been replaced (#4715)
* Update the no-vscode-postmessage eslint rule to check for all the vscode SDK calls that have been replaced.

Expand the rule to check for all of the vscode SDK calls that have been
switched to the host bridge or replaced with native functions.

* Remove redundant messages
2025-07-08 10:50:10 -07:00
Sarah Fortune 265a56391a Replace vscode.workspace.fs.stat with fs.stat (#4714)
Use the util function that already exists isDirectory from utils/fs.ts
Use the same function in getRelativePaths
2025-07-08 10:49:56 -07:00
canvrno ff4bab22fb host bridge migration - openExternal (#4502) 2025-07-08 10:47:12 -07:00
tjandy98 bc468707a6 Add header for SAP AI Core Tracking (#4696)
* Add support for Gemini 2.5 Pro and Flash models

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

* Create calm-ads-glow.md

* Update request header

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

Add ai-client-type header for tracking

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

Create little-lions-joke.md

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

update changeset

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

update

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
2025-07-07 21:09:41 -07:00
Sarah Fortune 0a6a565d41 Replace vscode.workspace.asRelativePath with the host bridge. (#4712)
* Replace vscode.workspace.asRelativePath with the host bridge.

Add a util function asRelativePath to path.ts that does the same thing as the vcode API (returns the path relative to the workspace directory).
In the getRelativePaths protobus handler, don't allow @mentions for files outside the workspace, they do not work in cline, so just prevent them from being added at all.
If the fs.stat fails for a file, don't @mention it either, if stat() fails it means the file doesn't exist or is unreadable.

* Update src/core/controller/file/getRelativePaths.ts

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

* Update src/core/controller/file/getRelativePaths.ts

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-07 19:40:14 -07:00
github-actions[bot] d30e4d0194 v3.18.5 Release Notes (#4704)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.5

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-07 19:12:41 -07:00
Ara d453eed582 feat: Globally persist plan/act mode across sessions and ensure proper workspace level persistance of chatsettings(for language) (#4646)
* feat: Persist plan/act mode across sessions

- Add mode persistence to global state storage
- Load saved mode on controller initialization
- Update state keys to include 'mode' as a valid global state key
- Ensures user's selected mode (plan/act) is maintained between VS Code sessions

* Split chat settings storage between global and workspace state
- Move mode setting to global state for cross-workspace persistence
- Store other chat settings in workspace state for project-specific configuration
- Update state retrieval logic to merge global mode with workspace settings
- Add chatSettings to LocalStateKey type definitions

* Code Cleanup

* Code Cleanup

* Get the chatsettings back to global

* Get the chatsettings back to global

* Get the chatsettings back to global

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-07 18:23:41 -07:00
Ara 7e32314c0b Optimize provider switching performance with batched storage operations (#4676)
* Optimize provider switching performance with batched storage operations

* Optimize provider switching performance with batched storage operations
2025-07-07 18:20:55 -07:00
Ara cce8f09ae5 Fixing bug on accepting tool response (#4675) 2025-07-07 18:19:50 -07:00
Bee 0262e13ac4 Capture token usage for conversation turns in telementry (#4703)
Adds capture of token usage data for conversation turns in the telemetry service. This includes tokensIn, tokensOut, cacheWriteTokens, cacheReadTokens, and totalCost.

The changes involve:

- Modifying the `captureConversationTurnEvent` method in `TelemetryService.ts` to accept and include token usage data in the captured event properties.
- Updating the `Task` class in `src/core/task/index.ts` to pass token usage information when capturing conversation turn events. This ensures that token usage is tracked for both regular and cached responses.
- Refactor capture event to use object destructuring for easier readability

Co-authored-by: Beatrix Woo <beatrix@cline.bot>
2025-07-08 04:54:06 +05:30
celestial-vault 6d2cf55fc5 migrate download MCP response to proto (#4682) 2025-07-07 14:58:49 -07:00
Sarah Fortune 3577c2efa9 Remove uri service from the host bridge. (#4660)
It is being replaced with the npm module vscode-uri.
2025-07-07 14:27:19 -07:00
Sarah Fortune f97ef745d9 Replace vscode.workspace.getWorkspaceFolder() with the host bridge (#4659)
* Replace vscode.workspace.getWorkspaceFolder() with the host bridge

Use the hostbridge getWorkspacePaths() and use the result to
check for the workspaceFolder of the current file open in the IDE.

* Organize imports

* Update isLocatedInWorkspace() to check all the workspace directories, not just the first.

Add utility function to check if a path is inside a directory instead of duplicating the logic.

* Remove stubs for workspaceFolders that are not needed anymore.
2025-07-07 14:23:26 -07:00
schardosin 4e27e06670 SAP AI Core small bug fix and reorder models (#4686)
* small fix to avoid exception and removed log of returned data

* reorganized sapaicore models to be grouped in logical groups

* updated changese with changes in SAP AI Core

* removed additional received data log sections
2025-07-07 15:44:27 -05:00
github-actions[bot] ef02d6b0b2 Changeset version bump (#4685)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

* Update CHANGELOG.md

* Update package.json

---------

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-07-07 13:26:11 -07:00
celestial-vault 7ab6189595 mark welcomeViewCompleted as true after auth redirect (#4699)
* mark welcomeViewCompleted as true after auth redirect

* Create real-ravens-nail.md

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-07 13:14:48 -07:00
celestial-vault 4beaa2a086 sync local search state after timeout (#4698) 2025-07-07 11:16:08 -07:00
Ara 5f90018ab5 Revert "remove blur (#4664)" (#4677) 2025-07-06 12:05:30 -06:00
celestial-vault 9e761cd1f0 lazily initialize provider sdks with error catching (#4661) 2025-07-06 11:41:16 -05:00
吴天一 e84f2ff962 remove blur (#4664) 2025-07-06 00:13:23 -05:00
tjandy98 1842254c57 Add support for Gemini 2.5 Pro and Flash models to SAP AI Core Provider (#4655)
* Add support for Gemini 2.5 Pro and Flash models

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>

* Create calm-ads-glow.md

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
2025-07-05 12:10:00 -05:00
pashpashpash 4a2dad4552 showOpenDialogue host bridge migration (#4651)
* showOpenDialogue host bridge migration

* addressing comments

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-03 22:55:19 -07:00
Sarah Fortune 3248c37358 Replace uses of vscode workspaceFolders with host bridge (#4649)
* Instead of getting the cwd from the workspaceFolders use the host bridge util getCwd()

Replace uses in integrations/claude-code/run.ts

* Organize imports
2025-07-03 15:53:53 -07:00
Sarah Fortune 172b46f1b0 Remove unused files *.bak (#4648)
* Remove unused file Checkpoint-test-utils.ts.bak

* Remove all .bak files from src/integrations
2025-07-03 15:36:21 -07:00
Sarah Fortune 9578d7cde1 Instead of getting the cwd from the workspaceFolders use the host bridge util getCwd() (#4647)
Remove top-level property cwd task, await can't be used at the top level.
Make cwd a class property, and pass the cwd into the constructor of task (await can't be used in the constructor either).
2025-07-03 15:36:08 -07:00
Sarah Fortune 2979d47e01 Replace cwd from the workspaceFolders with the host bridge. (#4645)
Don't export cwd from task/index.ts. This top-level property cwd will be removed in a following PR because await cannot be used at the top-level.
Use the hostbridge util getCwd() in createRuleFile.ts and refreshRules.ts instead of import the cwd from `task`.
Add a util function to get the desktop directory instead of constructing it multiple places, update uses with the new function getDesktopDir()
Replace function getCwd in FileContextTracker.ts with just getCwd from paths.ts.
2025-07-03 15:08:52 -07:00
github-actions[bot] 4569300f00 v3.18.3 Release Notes (#4644)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.3

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-03 15:06:57 -07:00
Toshii 36e3f4cdd3 add log + run options (#4630)
* log + options

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-03 14:54:10 -07:00
Tomás Barreiro bc5225ce52 Improve Claude Code handling (#4619)
* Prevent filling the chat with error messages

* Improve env variables and remove the magic number

* Add changeset

* refactor

* Update run.ts

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-07-03 14:41:59 -07:00
Kevin Taylor 50dc89b551 Strip thinking tokens from Cerebras reasoning model inputs (#4635)
* Strip thinking tokens from Cerebras reasoning model inputs

Filter out thinking tokens in message history

* changeset

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-03 14:40:58 -07:00
celestial-vault d576b68cca Move plan/act model settings to global storage (#4636)
* move model settings to global storage

* cleanup

* only run migration if globalState key is undefined
2025-07-03 16:24:14 -05:00
github-actions[bot] 6c2c0780ee v3.18.2 Release Notes (#4581) 2025-07-02 22:15:45 -07:00
pashpashpash 021a014012 setting claude 4 as best model (#4637)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-02 21:45:30 -07:00
Ara ef1a68b5e3 Adding a troubleshooting guide for terminal problems (#4592) 2025-07-02 19:08:42 -07:00
Tomás Barreiro 72029fe205 feat: Introduce Thinking Budget customization for Claude Code (#4618) 2025-07-03 06:37:32 +05:30
celestial-vault 2af151e736 [SettingsView] [ApiConfig Section] save on change (#4554)
* refactor out apiconfig section

* add general settings section

* duplicate import

* move terminal, browser, and feature settings

* move files to sections folder

* refactor out debug section

* pull out about section

* implement save on change and remove confirmation modals for api config section

* add doc strings to new hook functions

* add debounced text field for smooth typing

* use context value directly for apiProvider dropdown value; remove unecessary memo; remove keys from ApiOptions

* add welcomeViewCompleted state boolean to control welcome view showing

* refactor other sections to save-on-change; remove form diff calculation logic

* cleanup

* remove memo

* make welcomeViewCompleted context value initial value false
2025-07-02 19:39:49 -05:00
canvrno 64963c4e9c confirmation popup when deleting tasks (#4627) 2025-07-01 22:41:58 -07:00
Toshii 52571ccee8 base (#4600) 2025-07-01 17:08:28 -07:00
Saoud Rizwan 87322feeb7 Fall back to getting current terminal content when shell integration API fails to return output (#4605)
* Revert to when terminal process worked more reliably

* Get last terminal output if no output is retrieved

* Fix getting terminal output for when shell integration unavailable

* Apply suggestions from code review

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

* Revert removing previous changes

* Update TerminalProcess to emit current terminal contents instead of a silent command completion message

* Revert when first chunk fails message

* Revert error title

* Fixing tests with fake timers

---------

Co-authored-by: Dennise Bartlett <bartlett.dc.1@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-01 16:57:36 -07:00
kevinneung 27f8372c5b add cline.walkthrough to command handler (#4621)
added cline.walkthrough to command handler, since it would throw an error otherwise
2025-07-02 05:20:02 +05:30
Sarah Fortune b3d3e9861f Use the host bridge to get the cwd in autoApprove.ts (#4601)
Update the ToolExecutor to use await because the approval is now async.
2025-07-01 16:01:33 -07:00
pashpashpash 01178909ee adding unique remote git urls to context on first message env variables (#4622)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-01 15:15:10 -07:00
Sarah Fortune c982216113 Cleanup: Remove unused property and param postMessage from ClineAccountService (#4620)
* Remove unused property and param postMessage

* Remove unused property and param postMessage

Remove unused import.
2025-07-01 14:44:41 -07:00
Sarah Fortune da6f705df2 Remove unused file get-python-env.ts (#4604) 2025-07-01 14:06:14 -07:00
Ara c7548a7f52 Fixing Bugs in ChatView with Primary/Secondary Buttons and related issues (#4553)
* Splitting chat view into multiple modular files

* Adding Comments and removing redundancies

* Fixing Bugs in ChatView with Primary/Secondary Buttons and related issues

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-01 12:58:18 -07:00
Tomás Barreiro e5f78a0456 Do not read auth variables from the user env when using Claude Code (#4591) 2025-07-01 12:09:58 +05:30
Sarah Fortune 4b5b090b29 Remove unused param cwd (#4602) 2025-06-30 20:28:40 -07:00
Sarah Fortune 559eba5dd1 Cleanup: Remove unused params from the ToolExecutor constructor. (#4588)
Organize imports.
2025-06-30 18:55:19 -07:00
Andrei Eternal c013b4f329 [PROTOBUS] showTextDocument host bridge (#4586)
* showTextDocument host bridge

* format fix

* sjf review cleanups

* prefer paths over URI based on chats with sjf

* also document_uri -> document_path

* remove unused metadata import

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-06-30 18:39:09 -07:00
Jorge García Rey dcf91b081e [LiteLLM] Group multiple requests into a single session using litellm_session_id parameter (#4457)
* feat: add litellm_session_id as part of chat completion request

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

* chore: add changeset

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

---------

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>
2025-06-30 17:55:22 -07:00
pashpashpash 9ab0cc7648 deleting mermaid prompts (#4596)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-30 17:52:25 -07:00
pashpashpash add572cc12 fixing closing telemetry banner (#4597)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-30 17:37:28 -07:00
pashpashpash 307b92862b deprecating latex support (#4595)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-30 17:06:58 -07:00
Toshii 020ae3006e adding distance metric safety check to the block-apply, for eval (#4477)
* diff apply add

Co-authored-by: chi.cat <git@chi.cat>

* fname

* integrate

* optionally save locally

* other cli

* name

* default

* return replacements with match type

* baseline -1

* baseline for evals

* work

* more info

---------

Co-authored-by: chi.cat <git@chi.cat>
2025-06-30 16:11:31 -07:00
Sarah Fortune c6d91be721 Replace vscode workspaceFolders with getCwd which uses the host bridge. (#4593) 2025-06-30 16:07:48 -07:00
Sarah Fortune 4d2fec787e Replace uses of workspaceFolders from the vscode SDK with the host bridge (#4589)
* Switch openMention to use getCwd instead of using the vscode SDK directly.

* Use getCwd in services/test/TestServer.ts instead of using the vscode SDK.

Don't get the cwd from the controller extension context global state,
use the workspace folder as the rest of the codebase is doing.

Replace GitHelper.getWorkspacePath with utils.getCwd()

* Use host bridge getWorkspacePaths in services/test/TestMode.ts

-instead of using the vscode SDK.
Remove unsed param `context`

* Remove unused file CheckpointTracker-old.ts

* Use hostbridge getCwd in CheckpointUtils.ts and message-state.ts
2025-06-30 14:54:36 -07:00
Sarah Fortune c8b05cdf9c Remove unused property postMessageToWebview from Task (#4587)
Cleanup imports.
2025-06-30 14:03:41 -07:00
Ara 9e69576fb0 Splitting chat view into multiple modular files (#4569)
* Splitting chat view into multiple modular files

* Adding Comments and removing redundancies

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-30 13:55:25 -07:00
Toshii e6760ed6cc race (#4583) 2025-06-30 11:33:00 -07:00
celestial-vault 27a531c86a [SettingsView.tsx] Extract About Section (#4537)
* refactor out apiconfig section

* add general settings section

* duplicate import

* move terminal, browser, and feature settings

* move files to sections folder

* refactor out debug section

* pull out about section
2025-06-30 10:47:18 -07:00
Lize Cai 09c773bd5f Add Claude 4 model to SAP AI Core Provider (#4418)
* add claude 4 support to sap aicore

Signed-off-by: Lize Cai <lize.cai@sap.com>

* add changelog

Signed-off-by: Lize Cai <lize.cai@sap.com>

* update model-utils to capture other naming for claude 4.

Signed-off-by: Lize Cai <lize.cai@sap.com>

* add claude 4 opus as well

Signed-off-by: Lize Cai <lize.cai@sap.com>

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
2025-06-30 10:24:45 -07:00
github-actions[bot] 037a781a6d v3.18.1 Release Notes
-   Add support for Claude 4 Sonnet in SAP AI Core provider (Thanks @GTxx!)
-   Fix ENAMETOOLONG error when using Claude Code provider with long conversation histories (Thanks @BarreiroT!)
-   Remove Gemini CLI provider because Google asked us to
-   Fix bug with "Delete All Tasks" functionality
2025-06-28 18:38:32 -07:00
Ara 968b46a179 Revert "Adding Gemini CLI Provider with Oauth support (#4472)" (#4556)
* Revert "Adding Gemini CLI Provider with Oauth support (#4472)"

This reverts commit 890148407a.

* revert

* revert

* revert

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-28 18:20:32 -07:00
Toshii 5a777f28b6 fix browser row in chat view to prevent constant rerendering (#4542)
* base

* browser 2
2025-06-28 10:12:51 -07:00
Toshii fe9e5bff74 base (#4539) 2025-06-28 00:27:13 -07:00
celestial-vault e65605535a [SettingsView.tsx] Extract Debug Section (#4536)
* refactor out apiconfig section

* add general settings section

* duplicate import

* move terminal, browser, and feature settings

* move files to sections folder

* refactor out debug section
2025-06-27 16:04:28 -07:00
celestial-vault 3d100d835a [SettingsView.tsx] Extract Browser, Terminal, and Feature Sections (#4533)
* refactor out apiconfig section

* add general settings section

* duplicate import

* move terminal, browser, and feature settings

* move files to sections folder
2025-06-27 15:44:31 -07:00
celestial-vault b9d3814355 [SettingsView.tsx] Extract GeneralSettings Section (#4529)
* refactor out apiconfig section

* add general settings section

* duplicate import

* add missing type
2025-06-27 15:14:12 -07:00
xiongxiong 12fbc48629 feat. support anthropic--claude-4-sonnet in SAP AI Core provider (#4448) 2025-06-27 14:44:54 -07:00
Sarah Fortune d2f1e0cde0 Replace vscode.workspace.workspaceFolders with host bridge getWorkspacePaths (#4443)
* Use the host bridge in utils/path.ts

Update utils/path.ts to use the host bridge to get the workspace folders, instead of the vscode SDK.
Update callers to use await as the functions are now async.

* Replace vscode workspaceFolders in WorkspaceTracker

Make the cwd an instance property because await cannot be used at the top level.

* Use the host bridge getWorkspacePaths in FileContextTracker

Replace the vscode SDK getWorkspaceFolders with the util function getCwd (this is already switched to the host bridge).

* Fix test failure

Update the rootDir for the tests to be "." instead of "src". The changes to path.ts pull in new dependencies from the extension, which indirectly include files from the webview-ui.

```
Run npm run pretest

> claude-dev@3.18.0 pretest
> npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint

> claude-dev@3.18.0 compile-tests
> node ./scripts/build-tests.js

node:child_process:957
    throw err;
    ^

Error: Command failed: tsc -p ./tsconfig.test.json --outDir out
    at genericNodeError (node:internal/errors:983:15)
    at wrappedFn (node:internal/errors:537:14)
    at checkExecSyncError (node:child_process:882:11)
    at execSync (node:child_process:954:15)
    at Object.<anonymous> (/home/runner/work/cline/cline/scripts/build-tests.js:55:1)
    at Module._compile (node:internal/modules/cjs/loader:1730:14)
    at Object..js (node:internal/modules/cjs/loader:1895:10)
    at Module.load (node:internal/modules/cjs/loader:1465:32)
    at Function._load (node:internal/modules/cjs/loader:1282:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14) {
  status: 2,
  signal: null,
  output: [
    null,
    "src/services/test/TestServer.ts(8,35): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" +
      "webview-ui/src/services/grpc-client-base.ts(1,24): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/utils/vscode.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" +
      "webview-ui/src/services/grpc-client.ts(4,34): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client-base.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n",
    ''
  ],
  pid: 2496,
  stdout: "src/services/test/TestServer.ts(8,35): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" +
    "webview-ui/src/services/grpc-client-base.ts(1,24): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/utils/vscode.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n" +
    "webview-ui/src/services/grpc-client.ts(4,34): error TS6059: File '/home/runner/work/cline/cline/webview-ui/src/services/grpc-client-base.ts' is not under 'rootDir' '/home/runner/work/cline/cline/src'. 'rootDir' is expected to contain all source files.\n",
  stderr: ''
}
```

* Build the protos before compiling the tests.

The tests depend on generated files now, so compile the extension before the tests so that the protos are built.

* Set up the host providers in the integration test FileContextTracker.test.ts

* Reduce the amount of logging in grpc-service.ts

Just log the service registration, instead of every rpc.

* In the `clean` build target, also remove the compiled test code.

* Correct the alias mapping for the compiled test files.
2025-06-27 11:51:02 -07:00
celestial-vault efe2388e4a refactor out apiconfig section (#4528) 2025-06-27 10:57:54 -07:00
celestial-vault 247552fcb5 remove unused function (#4518) 2025-06-27 09:35:02 -07:00
Toshii 656e3276c6 lite llm provider ui (#4517)
* base 2

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* base 3

* base

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-26 22:51:12 -07:00
Toshii 0e29f05e28 refactor nebius and remove unused logic (#4515)
* base 2

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* base 3

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-26 22:39:56 -07:00
celestial-vault 985cb51c39 refactor lmstudio (#4514)
* refactor lmstudio

* merge conflict deleted stuff
2025-06-26 22:34:14 -07:00
celestial-vault abccde0e2a refactor out vscode lm (#4513) 2025-06-26 21:55:37 -07:00
celestial-vault ca984609ca refactor out cline (#4512) 2025-06-26 21:41:35 -07:00
celestial-vault 6690d392cd refactor out bedrock (#4510) 2025-06-26 21:29:27 -07:00
Toshii 40244f09fe base (#4511) 2025-06-26 21:23:43 -07:00
Toshii 9563a71c8a base (#4509) 2025-06-26 21:14:00 -07:00
celestial-vault c13e749eed refactor out sap ai core settings (#4508) 2025-06-26 21:05:29 -07:00
Toshii 8c3fd8ba55 refactor cerebras provider menu ui (#4507)
* xai

* base
2025-06-26 20:53:58 -07:00
celestial-vault 8bfa7daa28 refactor ollama settings to different component (#4506) 2025-06-26 20:45:30 -07:00
Toshii 7cd4be7a68 xai (#4504) 2025-06-26 20:34:34 -07:00
Toshii ab9f1a0785 refactor request and fireworks provider ui (#4499)
* requesty

* fireworks
2025-06-26 20:11:15 -07:00
canvrno 68b84f3df4 Fix for delete all bug, refactored deleteAll logic (#4497) 2025-06-26 17:53:44 -07:00
kevinneung 16da0f1e06 Fix telemetry source code link path (#4476)
Update the source code link in telemetry documentation to point to the correct file location: src/services/posthog/telemetry/TelemetryService.ts
2025-06-26 16:54:28 -07:00
Daniel Steigman e898bd8825 Updated best model to be gemini (#4500) 2025-06-26 16:47:34 -07:00
canvrno b7b0e96cc7 Add env host bridge service, migrate clipboard read/write calls (#4496)
* host bridge migration - clipboard

* changeset

* removed dev logging

* switched to empty return on clipboard write

* Moved new hostServiceNameMap entry to new proto configs
2025-06-26 16:18:29 -07:00
Andrei Eternal f00c5f4ecc experimental vscode impls & build-proto cleanup (#4493)
* experimental vscode impls

* weird errors

* add workspace host config

* format

---------

Co-authored-by: Andrei Eternal <eternal@cline.bot>
2025-06-26 16:07:21 -07:00
Tomás Barreiro 2709ccefcd fix: ENAMETOOLONG on Claude Code - write to stdin instead of including the messages in the prompt (#4494)
* Write to stdin instead of including the messages in the prompt

* Add changeset
2025-06-27 04:13:58 +05:30
Toshii c8f0324536 remove gemini free text for 2.5 models (#4492)
* gemini text

* remove
2025-06-26 15:43:24 -07:00
Toshii 937cebc7de refactor vertex and doubao provider ui (#4474)
* doubao

* vertex

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* ui

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-26 15:01:31 -07:00
canvrno d4d5a49e67 Refactor autoApprove out of task class (#4233)
* Refactor auto approve out of task class

* Rebase fixes

* cleanup

* reorg
2025-06-26 10:40:37 -07:00
SmileFisher 01d3afe0c5 Consider adding a pronunciation guide, since many Chinese developers tend to pronounce it as "C line". (#3635)
* Update README.md

add pronunciation

* Update README.md

---------

Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
2025-06-25 18:57:45 -07:00
github-actions[bot] 7bdab5613b v3.18.0 Release Notes
-   Optimized Cline to work with the Claude 4 family of models, resulting in improved performance, reliability, and new capabilities
-   Added a new Gemini CLI provider that allows you to use your local Gemini CLI authentication to access Gemini models for free (Thanks @google-gemini!)
-   Optimized Cline to work with the Gemini 2.5 family of models
-   Updated the default and recommended model to Claude 4 Sonnet for the best performance
-   Fix race condition in Plan/Act mode switching
-   Improve robustness of search and replace parsing
2025-06-25 17:39:46 -07:00
Ara d79722bec0 Fix: Solving race condition in the Plan/Act mode switching functionality (#4421)
* type fix

* markdown fix

* markdown fix

* Fix settings on switch

* Fix settings on switch

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 16:58:48 -07:00
Saoud Rizwan 06af720d85 Show placeholder while first response loads (#4475) 2025-06-25 16:55:55 -07:00
Ara b80ef25a33 fix: Solving Context window counting issues in gemini model family in openrouter and cline provider (#4314)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 16:54:30 -07:00
Ara 1996543eb0 Raise errors properly when OpenRouter stream cuts midway (#4398)
* Raise error on openrouter stream termination midway

* Raise error on openrouter stream termination midway

* type fix

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 16:42:12 -07:00
Ara d9dfd57da5 Settings fix (#4405)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 16:41:25 -07:00
Ara 890148407a Adding Gemini CLI Provider with Oauth support (#4472)
* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* Adding Gemini CLI direct oauth

* language

* themes instead of hardcorded colors

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 16:40:31 -07:00
pashpashpash 8d6a948478 Updating default and recommended model to claude4 sonnet (#4470)
* updating default recommended models to claude4

* changeset

* more copy

* language

* fix link

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 15:54:47 -07:00
pashpashpash 98e7fac400 updating diff evals with new algorithm + some nice dashboard updates (#4473)
* updating diff evals with new algorithm + some nice dashboard updates

* Update evals/diff-edits/dashboard/app.py

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

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-06-25 15:47:34 -07:00
canvrno 090bddbcea Fix: Accept trailing ">" on search and replace blocks (#4427)
* Modified regex to account for trailing > characters in search and replace blocks

* added check back to other regex's

* Re-ordered regex consts for readability
2025-06-25 14:43:26 -07:00
pashpashpash 5b41cf7af4 Gemini 2.5 using Claude4 system prompt (#4468)
* gemini 2.5 using claude4 prompt now

* changeset

* more lenient claude4 family check

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 14:39:49 -07:00
pashpashpash a2f86bde9b claude 4 prompt improvements (#4467)
* claude 4 prompt improvements

* optimizing claude4 system prompt

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 14:37:42 -07:00
celestial-vault 176f591ba3 organize migrations into separate file (#4461)
* organize migrations into separate file

* forgot to add extension.ts
2025-06-25 14:01:16 -07:00
pashpashpash 6f5ff1b407 accurate pricing displayed when BYOK is used for openrouter and cline providers (#4466)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-25 13:40:26 -07:00
Toshii ae076e2506 refactor gemini provider ui and open ai (#4464)
* base open ai

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* gemini

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-25 13:40:09 -07:00
Sarah Fortune 046d674b85 Add activeTabs stub (#4463) 2025-06-25 13:19:29 -07:00
Sarah Fortune e41e80aaf5 Add workspace service to the host bridge. (#4438)
* Add workspace service to the host bridge.

Add a service for workspaces to the host bridge.
The service has one rpc getWorkspacePaths that will replace vscode.workspace.workspaceFolders

* Add the vscode host implementation of getWorkspaceFolders

* Update src/hosts/vscode/workspace/getWorkspacePaths.ts

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-06-25 08:53:56 -10:00
pashpashpash 14ed98ae87 Revert "simplify is (#4404)" (#4446)
This reverts commit 1dd164f482.
2025-06-25 10:37:30 -07:00
Toshii f8667f8a9d base (#4441) 2025-06-24 21:08:50 -07:00
Toshii 077561fb71 refactor Anthropic, AskSage provider ui (#4428)
* anthropic provider

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* base

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-24 21:07:28 -07:00
Toshii 97fd1daec6 base (#4440) 2025-06-24 21:06:09 -07:00
Toshii 5c6e1d2ce9 fix thinking budget slider ui for gemini (#4435)
* fix

* remove some models
2025-06-24 21:05:29 -07:00
pashpashpash ec4d515d28 claude code docs (#4437)
* claude code docs

* Update docs/provider-config/claude-code.mdx

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

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-06-24 17:14:48 -07:00
celestial-vault 59efda3e22 fix link by calling grpc (#4422) 2025-06-24 16:07:19 -07:00
canvrno 936923d334 [PROTOBUS] Move telemetrySetting to protobus (#3711)
* telemtrySetting protobus migration

* merge conflcit fix

* Updated telemetrySettingRequest to use create

* rebase/merge fixes
2025-06-24 16:05:07 -07:00
celestial-vault 0a57ec3b7d remove remaining postMessage calls (#4432) 2025-06-24 15:52:36 -07:00
canvrno 670f3a1d62 [PROTOBUS] Move clearAllTaskHistory to protobus (#3674)
* clearAllTaskHistory protobus migration

* changset

* Fixed protobuf object literal usage

* cleanup

* remove old methods + return zero when user tries to delete favorites but none exist

* Removed deleteTaskWithId from controller and removed legacy claude_messages.json code
2025-06-24 14:30:59 -07:00
github-actions[bot] 8104f18f5a Changeset version bump (#4344)
* changeset version bump

* Updating CHANGELOG.md format

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

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-24 12:38:22 -07:00
canvrno 4de7790fa1 pretty (#4307) 2025-06-24 11:43:05 -07:00
celestial-vault adfb5a2b6e add eslint rule banning postMessage in webview (#4414) 2025-06-24 07:54:23 -10:00
pashpashpash d55a23448d fixing case in dashboard where no valid results (#4408)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-23 21:04:53 -07:00
celestial-vault 1dd164f482 simplify is (#4404)
streaming boolean to just use lastMessage.partial
2025-06-23 18:29:13 -07:00
pashpashpash 50b43c0559 Diff Evals - Replay feature (#4407)
* wip

* ok replays

* replays cooking

* docs

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-23 18:25:26 -07:00
Sarah Fortune 943c52f0b3 Update scripts/get-vscode-usages.sh (#4402) 2025-06-23 16:19:14 -07:00
Tomás Barreiro b84084936b fix: Handle long Claude code messages (#4287)
* Handle partial messages

* Parse chunks separately

* Add changeset

* refactor

* disallow tools

* Handle incomplete chunks

* Do not log costs when using a subscription, improve error handling and refactor rl usage

* Improve output handling. Prefer returning partial data to nothing.

* Set the total cost to 0 instead of leaving it undefined

* Fix the model infos and stop supporting images

* Reduce timeout to 10 minutes

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-24 03:09:21 +05:30
Sarah Fortune 014910deb9 Add clean script to package.json (#4326)
Add a script to remove build artifacts.
2025-06-23 14:24:08 -07:00
celestial-vault a30cefa595 Move mode to controller (#4343)
* you know what im talking about

* store mode in controller and target sendStateUpdate by controller ID
2025-06-23 14:23:20 -07:00
Daniel Steigman 620f402f36 Added protobuf development rule file (#4401)
* added protobuf development rule file

* new UI based example
2025-06-23 14:10:57 -07:00
Sarah Fortune 22ff68565b Add content security policy for external webview provider. (#4337)
Replace placeholder with correct csp source.
2025-06-23 11:51:05 -07:00
Sarah Fortune 3e1565da59 In the reflection output the standalone service should only show the Protobus services (#4339)
* The standalone service should only show the Protobus services in the reflection output.

The proto descriptor set is including all the proto services, allowlist the services in the cline and health packages.

* Remove debug code

* Fix variable name
2025-06-23 11:35:09 -07:00
Ara f8a284c6fe Fixing the contributor flow for Cline to force users to make issues first (#4324)
* Fixing the contributor flow for Cline to force users to make issues first

* Fixing the contributor flow for Cline to force users to make issues first

* Fixing the contributor flow for Cline to force users to make issues first

* Fixing the contributor flow for Cline to force users to make issues first

* Update feature_contribution.yml

Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
2025-06-22 08:11:01 -07:00
Anthony Gentile 39718cc521 #3775 remove deps clsx tailwind merge (#4147)
* v3.17.12 Release Notes

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.17.12

* changelog language

* changelog language

* attribution

---------

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

* #3720 first pass remove clsx / tailwind-merge and replace with template literals

* package-lock.json changes

* update changeset for 3720, remove clsx & tailwind-merge deps and replace with template literals

* #3775 Handle empty or null className

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-21 13:39:15 -07:00
Jorge García Rey e945a45102 feat: Add taskIdas metadata to use from LiteLLM (#3696)
* feat: add cline_task_id metatada to use in LiteLLM

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

* refactor: remove comment

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

* docs: add changeset

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

* refactor: apply suggestions type

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

* fix: format

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>

---------

Signed-off-by: Jorge García Rey <jorgegar@inditex.com>
2025-06-21 11:17:31 -07:00
celestial-vault e2f9c38902 Migrate fetchUserCreditsData protobus (#3801)
* migrate fetchUserCreditsData

* changeset

* remove parseInt

* linter error

* change proto fields to snake case

* syntax error

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-06-21 11:06:09 -07:00
Toshii 447a6ba4d5 update stale workflow (#4340) 2025-06-20 21:01:00 -07:00
Toshii 3f914f5092 refactor open ai compatible and sambanova providers (#4338)
* open ai compatible

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* Sambanova

* order

* reusable components

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-20 20:29:20 -07:00
celestial-vault b26997abc0 Migrate authStateChanged protobus (#3835)
* migrate authStateChanges

* changeset

* fix types and linter errors:

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-06-20 19:46:23 -07:00
Andrew Hood 560c79b885 Add new regions to available Bedrock options (#4056)
* Update ApiOptions.tsx

Added eu-south-1 (Milan) and eu-south-2 (Spain) to selection menu

* Update ApiOptions.tsx

Fixed names of eu-south-1 and eu-south-2 in settings menu
2025-06-20 18:24:30 -07:00
celestial-vault 77cc05c843 Create tool executor class (#4323)
* move apiConversationHistory to MessageStateHandler

* move clineMessages state to MessageStateManager class

* remove unused imports

* reorganize task class state variables and refactor out utility functions in recursivelyMakeClineRequests

* move task ephemeral state to state class

* extract tool logic into tool executor class

* integrate ToolExecutor into task class
2025-06-20 14:53:28 -07:00
Sarah Fortune 7db8c6ae4c Support external webview (#4336)
* Add ui.getWebviewHtml to the protobus

This will return the HTML content for external clients.

* Add getUri to ExternalWebviewProvider

Change getUri to return URIs for files in an appropriate format for the external web view.
Use URI from npm module in ExternalWebviewProvider.
Use a default value for the cline dir, ~/.cline
Turn off gRPC debugging

* Include node modules used as assets in the standalone package.

* Throw an error if trying to recreate webview panel in standalone app.
2025-06-20 13:44:22 -07:00
github-actions[bot] 6400901821 v3.17.15 Release Notes
v3.17.15 Release Notes
2025-06-20 12:38:29 -07:00
Toshii 07c354314a deepseek and together refactor (#4325)
Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-20 11:51:38 -07:00
pashpashpash 430074d0c2 diff evals (#4154)
* cleaning up a bit

* cleaning up some more

* readme

* added max limit

* making it portable

* ignore

* committing plans for now

* strealit hooked up, multi model runs, better db torage

* docs

* VALID attempts

* logging

* more stability

* strategy

* cleaning deps

* docs

* streamlit dashboard work

* dashboard showing bad cases

* better parallelization pt1

* global worker pool for even better more robust parallelization

* bumping up default max parallel requests from 20 -> 80

* better devx

* better docs

* docs

* better devx

* better docs

* better presentation

* dark mode

* removed unused import

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-20 11:41:16 -07:00
Toshii 0eec3b928b suggestion (#4305) 2025-06-20 11:40:31 -07:00
Toshii cb525ee588 gemini ga (#4304) 2025-06-20 11:40:13 -07:00
Yukio Nozawa 1b700805b6 Fix: Add role and aria-checked attributes to plan / act mode switch so that screen readers can tell its state ( Resolves #4244 ) (#4263)
* Fix: Screen readers now report plan / act mode switch state

* Create changeset
2025-06-20 11:39:56 -07:00
rikaaa0928 584c0da4ad fix: preferred language setting (#4282) 2025-06-20 11:39:17 -07:00
Ramy Ben Aroya c54cf38974 fix: omit undefined MCP server name when command is missing (#3840)
* fix: omit undefined MCP server name when command is missing

* apply to all prompts

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-06-20 11:38:57 -07:00
Ryan Nauman f79d1b9c02 chore: add run instructions to CONTRIBUTING.md (#3779) 2025-06-20 11:38:22 -07:00
celestial-vault 0876b3f335 Fix tab menu buttons affecting other tabs (#4329) 2025-06-19 22:06:22 -07:00
Charles Xu e46980e40f Fix Timeline tooltips for followup messages and consolidated color retrieval code. (#4164)
* fix: timeline message description

* refactor: merge the timeline's color method to eliminate code duplication.

* add changeset
2025-06-19 15:38:56 -07:00
Sarah Fortune 7cb3bd9f85 Create a vscode specific webview provider, and an a generic webview provider class for the standalone service. (#4320)
* Create a vscode specific webview provider, and an a generic webview provider class.

Move all the vscode specific parts in the VscodeWebviewProvider.
Create a ExternalWeviewProvider for the standalone service.
Update extension.ts to use the generic webview provider class.

* Add doc comments

* Add .create() to VscodeWebviewProvider
2025-06-19 15:26:50 -07:00
canvrno b74fdfe527 remove package.json from webview package.json (#4309) 2025-06-19 13:26:29 -07:00
Tomás Barreiro 288f1bf7f8 fix: Clear the input only after creating a message (#4288)
* Return if the message was sent when toggling plan act mode to properly clear the input

* Add changeset

* Use a common value instead of a unique response
2025-06-19 14:01:22 -06:00
Sarah Fortune 8aa6935cbb Refactoring: Move webprovider getUri into the WebViewProvider class. (#4306)
This refactor is part of the prep for making WebViewProvider host agnostic.
2025-06-19 12:19:32 -07:00
Toshii dd0aa2619b beginning of refactoring the providers ui to be more modular (#4222)
* base

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* base or

* base 2

* import

* mistral base

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* nits

* ModelInfoView replication

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* readme + helpers

Co-authored-by: StvLz <lizarazo.steven@gmail.com>

* nit

---------

Co-authored-by: StvLz <lizarazo.steven@gmail.com>
2025-06-19 12:04:45 -07:00
Sarah Fortune a4390f7dd8 Add a host-provider that will provide access to all host specific things (#4318)
* Add a host-provider that will provide access to all host specific things.

Right now it only has the host bridge clients, I will add a host specific web view provider in a second PR.
Check if the host provider has been set up properly when accessing the host bridge clients.

* Fix imports.

Don't generate hosts/vscode/client/host-grpc-client.ts, the code to generate this file is larger than the file; there will never be a large number of services in the host bridge.

* Fix imports
2025-06-19 12:00:11 -07:00
celestial-vault 8e131bbcc1 Migrate requestyModels protobus (#4083)
* migrate apiConfiguration

* migrate requestyModels protobus and clean up old messages

* fix models.proto types

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-06-19 11:09:45 -07:00
Sarah Fortune d92de54645 Update get-vscode-usages script to exclude types, only count methods (#4299) 2025-06-18 16:33:34 -07:00
Sarah Fortune febe795af4 Use the generated client impls for the external host bridge. (#4298)
* .

* Remove unused imports
2025-06-18 15:38:46 -07:00
celestial-vault bb6d02df83 Migrate didBecomeVisible protobus (#3996)
* migrate chatButtonClicked

* changeset

* send targeted event to the controller

* prettier

* migrate didBecomeVisible

* changeset

* fix proto linter issue

* add back event listener

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-06-18 14:46:41 -07:00
Sarah Fortune 72471f5677 In build-protos, create the directories while writing the files. (#4296)
* In build-protos, create the directories while writing the files.

* Update proto/build-proto.js

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

* Update proto/build-proto.js

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

* Update proto/build-proto.js

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

* .

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-06-18 14:44:06 -07:00
Sarah Fortune 3550486d4b Move StreamingHandlers type into a common location (#4293)
This type is used by all host bridge clients, move it out of the vscode directory.
2025-06-18 13:51:00 -07:00
Sarah Fortune 30344befe9 Add a script to generate type safe clients for the host bridge (#4269)
* Generate client interfaces and impls. Use the interfaces for the vscode and external clients

* Use interfaces
2025-06-18 12:39:52 -07:00
celestial-vault bf5e2785c3 Reorganize task state and refactor out small functions (#4267)
* move apiConversationHistory to MessageStateHandler

* move clineMessages state to MessageStateManager class

* remove unused imports

* reorganize task class state variables and refactor out utility functions in recursivelyMakeClineRequests

* move task ephemeral state to state class (#4273)
2025-06-18 12:36:01 -07:00
wangyijing130 a4a7caff01 Fix the error when submitting remote service form (#3579)
* Fix the error when submitting remote service form

Fix the exception caused by data structure errors when submitting remote service forms.

* fix for Prettier

* typing

---------

Co-authored-by: wangyj20 <wangyj20@asiainfo.com>
Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
2025-06-18 11:31:59 -07:00
Ara d2cdf7ce18 Fixing the context window jump issue for gemini family of models (#4266) 2025-06-18 19:37:04 +02:00
celestial-vault befc5adf70 Migrate cline messages to message state handler (#4237)
* move apiConversationHistory to MessageStateHandler

* move clineMessages state to MessageStateManager class

* remove unused imports

* remove redundant line
2025-06-18 10:34:20 -07:00
Yukio Nozawa b62f61fbc6 Fix: Make some of the buttons on the task header accessible to screen readers (#4246)
* Fix: The button which closes the currently displayed task is is now accessible with screen readers

* Fix: The button which deletes the currently displayed task is now accessible with screen readers

* Create changeset
2025-06-18 09:31:28 +02:00
Toshii 6dd0bbdd79 env (#4260) 2025-06-18 08:45:05 +02:00
Sam b92a280f51 fix: respect selected litellm model IDs for plan & act (#4193) 2025-06-18 08:44:04 +02:00
watany cecf7304e1 fix(bedrock): remove custom Model encode (#4209)
* fix(bedrock): without any encoding

* fallback for custom model

* changeset

* Update src/api/providers/bedrock.ts

---------

Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
2025-06-18 08:43:17 +02:00
Tomás Barreiro c5eccfe5d6 fix: Prevent reading env variables from the users environment (#4243)
* Do not destructure env variables

* Add changeset

* Do not set IS_DEV to true in tests

* Do not define values if it is not a production build

* Add eslint rule to prevent destructuring process.env
2025-06-18 08:42:24 +02:00
மனோஜ்குமார் பழனிச்சாமி 1fc796020d remove the MCP notification pop up (#4251)
* remove the MCP notification pop up

* Update src/services/mcp/McpHub.ts

---------

Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
2025-06-18 08:41:45 +02:00
Sarah Fortune c39a74048a Fix windows build (#4270) 2025-06-17 17:25:29 -07:00
github-actions[bot] c294b86524 v3.17.14 Release Notes
v3.17.14 Release Notes
2025-06-17 16:53:43 -07:00
pashpashpash 8d133d9031 supporting legacy search and replace blocks too (#4264)
* supporting legacy search and replace blocks too

* changeset

* Handle legacy search/replace chars for first/last partial lines

* error recovery + fixing

* throwing error if malformed search block - previously this would cause entire file to be deleted

* Update cyan-books-cry.md

* fixing broken test

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-06-18 01:14:28 +02:00
Ramesh 1adf19a873 update star alignment (#3935) 2025-06-17 16:07:48 -07:00
canvrno 60d9bd46c5 Fix: Race condition leading to task restoration, checkpoints issues (#4226)
* Fixed race condition where clineAsk was undefined, leading to task restoration and other downstream issues

* changeset
2025-06-18 01:25:58 +05:30
Tomás Barreiro 689afc62eb feat: Integrate Claude Code (#4111)
* Integrate Claude Code

* Add changeset

* handle exits gracefully, select models and update the path

* limit the claude-code models and update message

* expose the claudeCodePath in the apiConfiguration and proto

* remove log

* Update proto settings and properly map the provider
2025-06-18 00:51:07 +05:30
Tomás Barreiro d8e29263df fix: Clear the input when the user changes mode within a task (#4242)
* Clear the input when the user changes mode within a task

* Add changeset

* rename prop
2025-06-17 17:44:52 +02:00
canvrno 189b91ca36 Fix: clineMessages not storing all checkpoints commitHashes (#4225)
* Fixed issue where checkpoint commitHash was not being saved to every clineMessage in state, added handling in case checkpointTracker was not initialized (resumed tasks)

* changeset

* prettier
2025-06-17 11:35:56 +05:30
Ara 7172eb194d Fixing terminal Blocked issue (#4217)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-17 06:02:21 +05:30
Sarah Fortune 97838fe349 Generate promise-based TS clients with nice-grpc. (#4259)
Add a manager class to hold all the instances of the clients. They need to be reused, unlike the vscode clients which are just static method calls.

Move the generated file src/standalone/server-setup.ts into src/generated/ directory.

Add the host bridge address env var to the vscode launch.json

In build-proto.js: path.join will normalize slashes in file paths, so use path.join(x, "a/b/c") instead of path.join(x, "a", "b", "c").
2025-06-16 15:15:35 -07:00
canvrno e8e8eac820 Feat: Reduce diff edit errors when restoring tasks w/o checkpoints (#4232)
* Added file context warnings to reduce diff edit errors when resuming a task after it has been restored

* changeset

* Prompt tweak
2025-06-16 12:48:02 -07:00
canvrno 54a7fed77b Exclune clinerules from checkpoints (#4236) 2025-06-16 11:57:41 -07:00
Sarah Fortune ddbe3f47bd Add fixes for the grpc handler and client for the host bridge service (#4221)
* Fix error handling for unary handler in the host bridge grpc handler for vscode.

The unary request handler was return a struct like {message: ..., error: ..., requestId: ...}
But the caller was only looking at the message field, not the error.
Simplify the unary handler and just return the response message or throw if there was an error. The caller already has the request id, it doesn't need it to be returned from handler.

* Update comments

* Return early from cancelRequest if request wasn't cancelled to reduce indent level/complexity.

* Fix bug in cancelRequest in the host bridge grpc handler where cancel message is never sent to the client.

When a request is cancelled it is removed from the registery. The cancel handler was cancelling the request, and then trying to retrieve it again to get the stream handler, but it was already removed from the active request, so the cancel message was never sent to the client.

Fix this by retrieving the stream handler first, and then cancelling the request.
2025-06-15 22:22:10 -07:00
Toshii a9dfc5d0b6 fix sap provider (#4240)
* fix

* proto nit
2025-06-15 13:49:47 -07:00
canvrno 31de5053f3 Fix: Checkmark control menu improvements (#4218)
* Better debounce on checkmark control menu

* Fix issue where Restore Files button was disabled after first use
2025-06-15 11:48:04 -07:00
celestial-vault 5a66cb7819 catch error more broadly (#4235) 2025-06-15 10:15:32 -07:00
Dennise Bartlett 5d4594e82e Update developer reset to allow for resetting workspace settings. (#4229)
* Update developer reset to allow for resetting workspace settings.

* Add Changeset

* Add Metadata field to ResetStateRequest
2025-06-14 23:14:51 -07:00
schardosin c3326973c7 SAP AI Core as a Provider (#3980)
* added changes over a the latest from upstream

* cleanup some comments

* fixed message mispelling and variable naming convention

* added changeset for addition of SAP AI Core provider

* fixed mispelled expires_at

* added sapAiCoreClientId to hasKey

* retrigger tests

* removed bedrock-format.ts, added smal function for message formatting in sapaicore, removed models lazy loading, simplifying the code

* reverted src/core/webview/index.ts to upstream version, once all the tailored implementation for sapaicore were removed

* removed duplicated and not used interfaces

* removed the deployments logic from ApiOptions.tsx, now it loads the list of models available only

* removed references for deployments once it is not in use anymore

* removed unused sapConfig from WebviewMessage and ExtensionMessage

* moved previous state variable according to the request'

* removed supportsComputerUse from sapaicore sonnet

* added grpc fields and updated conversion methods for sap ai core
2025-06-14 17:37:34 -07:00
Ara b0de6390f4 Fix MCP Schema support (#4166)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-06-14 14:27:46 +05:30
Toshii a6c33afb11 add terminal setting to allow users to constrain terminal output (#4150)
* base

* grpc

* grpc

* base 3

* settings stuff

* changeset

* nit

* format

* smol
2025-06-13 17:28:31 -07:00
Derek Gaston ec26a912bc Increase the number of retries for Bedrock. Refs #213 (#4114)
* Increase the number of retries for Bedrock. Refs #213

* bump

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-06-13 13:55:24 -07:00
watany 6a11c78288 chore(bedrock): remove @anthropic-ai/bedrock-sdk (#4162)
* remove @anthropic-ai/bedrock-sdk

* changeset
2025-06-13 11:53:58 -07:00
Vladimir d27b199cea Mcp rich display setting (#4029)
* + Adding a global setting for mcp rich display in features settings, storing it in global storage, and using it as the starting value for each new session to still allow local toggle of mcp rich display on the tab, but let users keep the base stored default

* + adding changest

* + fxing linting post conflict merge

* fix

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-06-13 11:51:52 -07:00
Sarah Fortune 7ba4c9e15e Add a linter for proto files (#4179)
* Add a protobuf linter

Enforce the standard lint rules: snake case field names, snake case file names, pascal case service names etc.

Add exceptions for the lint rules we are already not following.

Fix linter failures, this only changes the proto file The generated TS types are the same, so the ts files don't need to be updated.

* Formatting
2025-06-13 08:28:05 -10:00
Toshii 802e72f1bf new feature github template + readme (#4211)
* constributing

* nit

* nit
2025-06-13 11:02:00 -07:00
Alberto Valiña Lema 10a223f27d Terminal profile setting (#4079)
* feat: Added a configurable default terminal profile setting

* chore: format

* refactor: migrate terminal profiles to gRPC and remove legacy message handling

- rename AvailableTerminalProfilesResponse to TerminalProfiles in proto
- remove duplicate TerminalProfile type from terminal_types.ts
- update all imports to use TerminalProfile from proto/state
- remove legacy availableTerminalProfiles message handling from ExtensionStateContext
- clean up ExtensionMessage type by removing unused availableTerminalProfiles
- translate Spanish comment to English in TerminalSettingsSection
- update server-side getAvailableTerminalProfiles to use new proto type

* chore: lint

* fix: merge main

* fix: resolve errors

* chore: notify terminal profile settings

* chore: merge main

* feat: improve default terminal profile changes

* fix: update changes on save
2025-06-13 20:51:24 +05:30
Sarah Fortune 0fade12e8e Format files before commit (#4155)
Instead of doing a prettier check in the pre-commit, just format the staged changes.
Use the package lint-stage to handle only formatting staged changes.
2025-06-12 13:28:39 -07:00
Sarah Fortune a4bf34f73b Generate grpc-js services and clients (#4199)
* Generate clientImpls and services for grpc-js.

Generate grpc-js services and clients (as opposed to the generic service definition)
The grpc-js clients are needed to connet to external gRPC services, ie the host bridge.
Switch the standalone gRPC service to use the grpc-js service defintions, these have the correct serialize/deserialize methods and fix the camel/snake case issue.

* Formatting
2025-06-12 12:49:36 -07:00
622 changed files with 53433 additions and 56408 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Fix list_files tool to return files if the targeted directory is a hidden directory
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix Global Rules directory documentation for Linux/WSL systems
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
DeepSeek R1 0528 support under Hugging Face
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
remove duplicate tool registration for claude4-experimental
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add Huawei Cloud MaaS Provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
update the copy button functionality
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fixed token counting when using VSCode LM API provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix: only focus on editor panel that is visible and active to stop input field stealing issue
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add Cerebras Qwen 3 235B instruct
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
trim input value for URL fields
+1 -1
View File
@@ -716,7 +716,7 @@ The Controller class manages MCP servers through the McpHub service:
class Controller {
mcpHub?: McpHub
constructor(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, webviewProvider: WebviewProvider) {
constructor(context: vscode.ExtensionContext, webviewProvider: WebviewProvider) {
this.mcpHub = new McpHub(this)
}
+89
View File
@@ -0,0 +1,89 @@
# Cline Protobuf Development Guide
This guide outlines how to add new gRPC endpoints for communication between the webview (frontend) and the extension host (backend).
## Overview
Cline uses [Protobuf](https://protobuf.dev/) to define a strongly-typed API, ensuring efficient and type-safe communication. All definitions are in the `/proto` directory. The compiler and plugins are included as project dependencies, so no manual installation is needed.
## Key Concepts & Best Practices
- **File Structure**: Each feature domain should have its own `.proto` file (e.g., `account.proto`, `task.proto`).
- **Message Design**:
- For simple, single-value data, use the shared types in `proto/common.proto` (e.g., `StringRequest`, `Empty`, `Int64Request`). This promotes consistency.
- For complex data structures, define custom messages within the feature's `.proto` file (see `task.proto` for examples like `NewTaskRequest`).
- **Naming Conventions**:
- Services: `PascalCaseService` (e.g., `AccountService`).
- RPCs: `camelCase` (e.g., `accountEmailIdentified`).
- Messages: `PascalCase` (e.g., `StringRequest`).
- **Streaming**: For server-to-client streaming, use the `stream` keyword on the response type. See `subscribeToAuthCallback` in `account.proto` for an example.
---
## 4-Step Development Workflow
Heres how to add a new RPC, using `scrollToSettings` as an example.
### 1. Define the RPC in a `.proto` File
Add your service method to the appropriate file in the `proto/` directory.
**File: `proto/ui.proto`**
```proto
service UiService {
// ... other RPCs
// Scrolls to a specific settings section in the settings view
rpc scrollToSettings(StringRequest) returns (KeyValuePair);
}
```
Here, we use the common `StringRequest` and `KeyValuePair` types.
### 2. Compile Definitions
After editing a `.proto` file, regenerate the TypeScript code. From the project root, run:
```bash
npm run protos
```
This command compiles all `.proto` files and outputs the generated code to `src/generated/` and `src/shared/`. Do not edit these generated files manually.
### 3. Implement the Backend Handler
Create the RPC implementation in the backend. Handlers are located in `src/core/controller/[service-name]/`.
**File: `src/core/controller/ui/scrollToSettings.ts`**
```typescript
import { Controller } from ".."
import { StringRequest, KeyValuePair } from "../../../shared/proto/common"
/**
* Executes a scroll to settings action
* @param controller The controller instance
* @param request The request containing the ID of the settings section to scroll to
* @returns KeyValuePair with action and value fields for the UI to process
*/
export async function scrollToSettings(controller: Controller, request: StringRequest): Promise<KeyValuePair> {
return KeyValuePair.create({
key: "scrollToSettings",
value: request.value || "",
})
}
```
### 4. Call the RPC from the Webview
Call the new RPC from a React component in `webview-ui/`. The generated client makes this simple.
**File: `webview-ui/src/components/browser/BrowserSettingsMenu.tsx`** (Example)
```tsx
import { UiServiceClient } from "../../../services/grpc"
import { StringRequest } from "../../../../shared/proto/common"
// ... inside a React component
const handleMenuClick = async () => {
try {
await UiServiceClient.scrollToSettings(StringRequest.create({ value: "browser" }))
} catch (error) {
console.error("Error scrolling to browser settings:", error)
}
}
```
@@ -0,0 +1,75 @@
# Git Diff Analysis Workflow
## Objective
Analyze the current branch's changes against main to provide informed insights and context for development decisions.
## Step 1: Gather Git Information
<important>Do not return any text or conversation other than what is necessary to run these commands</important>
**First, check the expected output size:**
```shell
(git branch --show-current && echo "=== STATUS ===" && git status --porcelain | cat && echo "=== COMMIT MESSAGES ===" && git log main..HEAD --oneline | cat && echo "=== CHANGED FILES ===" && git diff main --name-only | cat && echo "=== FULL DIFF ===" && git diff main | cat) | wc -l
```
**If the expected line count is greater than 500 lines, use the file-based approach:**
```shell
git branch --show-current > cline-git-analysis.temp && echo "=== STATUS ===" >> cline-git-analysis.temp && git status --porcelain >> cline-git-analysis.temp && echo "=== COMMIT MESSAGES ===" >> cline-git-analysis.temp && git log main..HEAD --oneline >> cline-git-analysis.temp && echo "=== CHANGED FILES ===" >> cline-git-analysis.temp && git diff main --name-only >> cline-git-analysis.temp && echo "=== FULL DIFF ===" >> cline-git-analysis.temp && git diff main >> cline-git-analysis.temp
```
Then, read the file using the read_file tool. After you have read the file but before you proceed with subsequent steps, delete it:
```shell
rm cline-git-analysis.temp
```
**If the expected line count is 500 lines or fewer, use the direct approach:**
```shell
git branch --show-current && echo "=== STATUS ===" && git status --porcelain | cat && echo "=== COMMIT MESSAGES ===" && git log main..HEAD --oneline | cat && echo "=== CHANGED FILES ===" && git diff main --name-only | cat && echo "=== FULL DIFF ===" && git diff main | cat
```
<important>If using the direct approach, pipe outputs through `cat` to avoid interactive terminals. If the user's shell is not bash/zsh, adjust the command and chaining
syntax accordingly.</important>
## Step 2: Silent, Structured Analysis Phase
- Analyze all git output without providing commentary or narration
- Read the full diff to understand the scope and nature of changes
- Identify patterns, architectural modifications, or potential impacts
- Use `read_file` to examine any related files providing additional context on the changes you have observed
## Step 3: Context Gathering
- Analyze related code without providing commentary or narration
- Read relevant related source files if needed for complete understanding
- Check dependencies, imports, or cross-references spanning the changes
- Understand the broader codebase context around modifications
- This additional context gathering should include related backend code, as well as related ui/frontend code
- You will typically need to analyze at least several files, potentially many, in order to fully complete this step
- You should not continue reading additional context if you have exhausted more than 60% of your available context window
- If you have exhausted less than 40% of your context window, you should continue reviewing additional context
## Step 4: Ready for User Interaction
**Only after completing the full analysis:**
- Engage with the user based on comprehensive understanding
- Provide insights about specific modifications and their impacts
- If you are certain they exist, note potential breaking changes or compatibility issues
- Answer questions with informed context from the complete change set and context gathering
- If the user has not provided a question, or the question is insufficient to provide a quality response, ask brief (one sentence) clarifying questions.
- Only offer recommendations if they are applicable to the user's request and relevant to the changes that you have observed
## Key Rules
- **No prose or conversation during git research phase**
- **No prose or conversation during context gathering phase**
- **Complete all analysis before any user interaction**
- **Use gathered information for all subsequent questions and insights**
- **Focus on understanding the complete picture before discussing**
## Optional: Additional Analysis Commands
For deeper investigation when needed:
```shell
# Detailed commit history with author info
git log main..HEAD --format="%h %s (%an)" | cat
# Change statistics
git diff main --stat | cat
# Specific file type changes
git diff main --name-only | grep -E '\.(ts|js|tsx|jsx|py|md)$' | cat
@@ -0,0 +1,392 @@
# General writing guide
# How I want you to write
I'm gonna write something technical.
It's often less about the nitty-gritty details of the tech stuff and more about learning something new or getting a solution handed to me on a silver platter.
Look, when I read, I want something out of it. So when I write, I gotta remember that my readers want something too. This whole piece? It's about cluing in anyone who writes for me, or wants me to write for them, on how I see this whole writing product thing.
I'm gonna lay out a checklist of stuff I'd like to have. It'll make the whole writing gig a bit smoother, you know?
## Crafting Compelling Titles
I often come across titles like "How to do X with Y,Z technology." These don't excite me because X or Y are usually unfamiliar unless they're already well-known. Its rarely the dream to use X unless X is the dream.
My dream isnt to use instructor, its to do something valueble with the data it extracts
An effective title should:
- Evoke an emotional response
- Highlight someone's goal
- Offer a dream or aspiration
- Challenge or comment on a belief
- Address someone's problems
I believe it's more impactful to write about specific problems. If this approach works, you can replicate it across various scenarios rather than staying too general.
- Time management for everyone can be a 15$ ebook
- Time management for executives is a 2000$ workshop
Aim for titles that answer questions you think everyone is asking, or address thoughts people have but can't quite articulate.
Instead of "How I do something" or "How to do something," frame it from the reader's perspective with "How you can do something." This makes the title more engaging. Just make sure the difference is advisory if the content is subjective. “How I made a million dollars” might be more reasonable than “How to make a million dollars” since you are the subject and the goal might be to share your story in hopes of helping others.
This approach ultimately trains the reader to have a stronger emotional connection to your content.
- "How I do X"
- "How You Can do X"
Between these two titles, it's obvious which one resonates more emotionally.
You can take it further by adding specific conditions. For instance, you could target a particular audience or set a timeframe:
- How to set up Braintrust
- How to set up Braintrust in 5 minutes
## NO adjectiives
I want you to almost always avoid adjectives and try to use evidence instead. Instead of saying "production ready," you can write something like "scaling this to 100 servers or 1 million documents per second." Numbers like that will tell you exactly what the specificity of your product is. If you have to use adjectives rather than evidence, you are probably making something up.
There's no reason to say something like "blazingly fast" unless those things are already known phrases.
Instead, say "200 times faster" or "30% faster." A 30% improvement in recommendation system speed is insane.
There's a 200 times performance improvement because we went from one programming language to another. It's just something that's a little bit more expected and understandable.
Another test that I really like using recently is tracking whether or not the statements you make can be:
- Visualized
- Proven false
- Said only by you
If you can nail all three, the claim you make will be more likely to resonate with an audience because only you can say it.
Earlier this year, I had an example where I embedded all of Wikipedia in 17 minutes with 20 bucks, and it got half a million views. All we posted was a video of me kicking off the job, and then you can see all the log lines go through. You see the number of containers go from 1 out of 50 to 50 out of 50.
It was easy to visualize and could have been proven false by being unreproducible. Lastly, Modal is the only company that could do that in such an effortless way, which made it unique.
## Keep It Digestible
- Aim for 5-minute reads
- Write at a Grade 10 reading level
- Break up long paragraphs
- Use headers and bullet points
## Make It Scannable
- Bold key points
- Use subheadings every 3-4 paragraphs
- Include plenty of white space
- Add relevant examples
This structure works whether you're writing a tweet thread or a full blog post. The key is making complex ideas accessible.
# Guide to Writing Cline Documentation
## Some general principles for explaining features
If you're talking about a feature, it's helpful to start with a human-readable explanations that cover what the feature is in simple terms. Skip jargon and explain it like you're talking to someone who's never seen it before. This sets the foundation for everything that follows.
Combine location and usage into one flowing section. Tell users exactly where to find the feature and how to use it, but weave the instructions into natural prose with a good balance of bullet points, numbered lists, code examples (if applicable), mintlify components, and headers/subheaders. Users shouldn't have to jump between separate "where is it" and "how do I use it" sections.
Show the feature in action with real examples like actual files, workflows, or code. Users need to see concrete implementations, not just abstract descriptions. This is where understanding turns into practical knowledge.
When talking about a feature, include an inspiration section that sparks imagination. This section pushes people from understanding to action by showing them what becomes possible when they use this feature creatively. It's what separates good documentation from great documentation.
## Writing Principles That Actually Work
### Write for Action, Not Just Understanding
Documentation should motivate users to try things. Instead of just explaining how something works, focus on what users can accomplish with it. The inspiration section is crucial - it's what transforms passive readers into active users.
### Create a Natural Story Flow
It should feel like a conversation that naturally progresses from "what is this?" to "how do I use it?" to "here's a real example" to "imagine what you could do with this."
### Show Real Examples, Not Toy Demos
Provide actual workflow files, real code snippets, and concrete implementations that users can copy and adapt. Abstract examples don't help anyone - users want to see exactly what they'll be working with.
### Keep It Scannable But Not Fragmented
Write in prose that flows naturally when read completely, but structure it so users can quickly find specific information when they're troubleshooting. Avoid dense walls of text, but also avoid over-formatting with excessive bullet points and bold headers. There should be a nice visual heirarchy of balance between all elements, so you can quickly scan the page and find what you're looking for.
## Language and Tone Guidelines
Write clearly without dumbing things down. Use simple language when possible, but don't avoid technical terms that users need to know. Explain concepts in terms of what users can achieve rather than how the software works internally.
Make your writing conversational and encouraging. Phrases like "you can also try" or "when that works" feel more natural than rigid instructional language. Help users feel confident about trying new things.
Keep content concise and purposeful. Every sentence should either help users understand something or help them do something. If it doesn't serve one of those purposes, cut it.
Build in context and reasoning. Users want to understand why they're doing something, not just what to do. This builds confidence and helps them troubleshoot when things don't work exactly as expected.
## Practical Implementation
Structure each feature page consistently with the four-section approach, but let the content flow naturally within that structure. Use visual assets like videos and screenshots to complement the written content - they often communicate more effectively than paragraphs of description.
Link generously to related resources, examples, and deeper documentation. Users should never feel stuck or wonder where to go next. Maintain a repository of real examples that users can reference and adapt to their own needs.
The goal is documentation that feels more like helpful guidance from an experienced colleague than a technical manual. Users should finish reading feeling excited about what they can accomplish, not just informed about what the feature does.
## Balance Structure with Flexibility
While they discuss having consistent documentation structure, there's also mention of making content feel less rigid and more natural. The writing should follow guidelines while still feeling conversational and engaging.
## Bad examples
I personally hate this pattern of bullet point **Bold Text** colon and then more text:
<bad_example_of_writing>
#### macOS
1. **Switch to bash**: Go to Cline Settings → Terminal → Default Terminal Profile → Select "bash"
2. **Disable Oh-My-Zsh temporarily**: If using zsh, try `mv ~/.zshrc ~/.zshrc.backup` and restart VSCode
3. **Set environment**: Add to your shell config: `export TERM=xterm-256color`
#### Windows
1. **Use PowerShell 7**: Install from Microsoft Store, then select it in Cline settings
2. **Disable Windows ConPTY**: VSCode Settings → Terminal Integrated: Windows Enable Conpty → Uncheck
3. **Try Command Prompt**: Sometimes simpler is better - switch to cmd.exe
#### Linux
1. **Use bash**: Most reliable option - select in Cline settings
2. **Check permissions**: Ensure VSCode has terminal access permissions
3. **Disable custom prompts**: Comment out prompt customizations in `.bashrc`
</bad_example_of_writing>
We should instead strive to write beautiful docs that read well. We can use bullet points and numbered lists but it should read naturally and be delightful to look at hierachally when scanning through the doc. There should be a good balance between blocks of text, code snippets, paragraphs, numbered lists, and bullet points. When scanning the documentation visually, you should feel like you're adminiring a tasteful art piece.
<good_example_of_writing>
#### macOS
The most common fix is switching to bash. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown.
If you're still having issues, Oh-My-Zsh might be interfering with terminal integration. Try temporarily disabling it:
- Run `mv ~/.zshrc ~/.zshrc.backup`
- Restart VSCode
You can also add `export TERM=xterm-256color` to your shell configuration file to improve compatibility.
#### Windows
PowerShell 7 provides the most reliable experience. Install it from the Microsoft Store, then select it in your Cline settings.
Still seeing problems? Try these solutions:
- Disable Windows ConPTY: VSCode Settings → Terminal Integrated: Windows Enable Conpty → uncheck
- Switch to Command Prompt (cmd.exe) - sometimes simpler shells work better
#### Linux
Bash is your most dependable option. Select it in Cline settings if you haven't already.
Check these common issues:
- Ensure VSCode has terminal access permissions
- Temporarily comment out custom prompt configurations in your `.bashrc`
</good_example_of_writing>
This is much more natural to read. Writing this way creates a conversational flow, and bullet points are used idiomatically.
# Using Mintlify Components Idiomatically
Mintlify's custom components can transform basic documentation into engaging, scannable content that users actually want to read. Here's how to use them effectively.
## Visual Content with Frames
Videos and images should be wrapped in `<Frame>` components rather than using raw HTML or markdown. This creates consistent styling and proper responsive behavior.
For videos, embed them directly rather than linking externally. Users are much more likely to watch a 30-second demonstration than click through to another platform:
```jsx
<Frame>
<iframe
style={{ width: "100%", aspectRatio: "16/9" }}
src="https://www.youtube.com/embed/your-video-id"
title="Feature demonstration"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
/>
</Frame>
```
Screenshots work similarly - the frame provides visual polish and consistency:
```jsx
<Frame>
<img src="/path/to/screenshot.png" alt="Descriptive alt text" />
</Frame>
```
## Cards for Navigation and Overview
Cards excel at creating scannable overviews that link to detailed documentation. They're perfect for feature listings, getting started guides, or any section where users need to choose their path.
Use the two-column layout for related features:
```jsx
<Columns cols={2}>
<Card title="Feature Name" icon="relevant-icon" href="/link/to/docs">
Brief description that explains what this feature does and why someone would use it.
</Card>
<Card title="Related Feature" icon="another-icon" href="/another/link">
Another concise explanation that helps users understand the value proposition.
</Card>
</Columns>
```
The key is writing card descriptions that are informative enough to help users decide whether to click through, but concise enough to scan quickly. Each card should answer "what does this do?" and "why would I need this?"
## Tips and Notes for Context
Use `<Tip>` components for helpful information that enhances the main content without cluttering it:
```jsx
<Tip>
Pro tip: You can combine multiple @ mentions in a single message to give Cline
comprehensive context about your issue.
</Tip>
```
`<Note>` components work well for important caveats or technical limitations:
```jsx
<Note>
Due to VS Code limitations, some features require specific settings to work properly.
</Note>
```
`<Info>` is also cool:
<Info>
**Quick Fix**: If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings.
This resolves 90% of terminal integration problems.
</Info>
**Never** fall into that awful **Bold Text** - description pattern that we specifically identified as bad writing. The content should flow naturally as connected thoughts rather than feeling like a templated AI response with forced formatting.
## When to Use Bullet Points and Numbered Lists Strategically
Bullet points serve functional purposes - use them for:
**Sequential actions or troubleshooting steps** where users need to follow a specific order:
1. Install the extension
2. Restart VSCode
3. Check the settings panel
**Lists of related options** where users need to choose one approach:
- Try PowerShell 7 for the most reliable experience
- Switch to Command Prompt if you're still having issues
- Use WSL Bash for Linux compatibility
**Quick reference items** that users might need to scan quickly when problem-solving.
**Improving Visual Hierarchy** when there's a wall of text - that's a good time to introduce bullet points or numbered lists.
Each bulleted item or numbered list should be a discrete action or piece of information that benefits from being visually separated. This is a key weapon you can employ when going for that artwork experience I mentioned earlier.
<good_example_of_bullet_points>
## Finding and Configuring Terminal Settings
You can access Cline's terminal settings by clicking the settings icon in the Cline sidebar, then navigating to the Terminal section. These settings control how Cline interacts with your system's terminal.
- The **Default Terminal Profile** setting determines which shell Cline uses for executing commands. If you're experiencing issues, this is usually the first thing to change. I personally keep this set to `bash` on all my systems because it's the most reliable option, even though I use `zsh` for my regular terminal work.
- **Shell Integration Timeout** controls how long Cline waits for the terminal to become ready. The default is 4 seconds, but if you have a heavy shell configuration (lots of plugins, slow startup scripts), you might need to increase this to 10 or even 15 seconds. I've found that WSL environments and SSH connections often need longer timeouts.
- The **Enable Aggressive Terminal Reuse** setting determines whether Cline tries to reuse existing terminals even when they're not in the correct directory. When this causes problems (commands running in the wrong directory, virtual environment issues), disabling it creates more terminal instances but ensures each command runs in a clean state.
- **Terminal Output Line Limit** sets how many lines of output Cline will read from commands. The default of 500 lines works for most cases, but you might need to adjust it. For verbose build outputs, increase it. For commands with progress bars that spam thousands of lines, decrease it to around 100 to avoid consuming too many tokens.
</good_example_of_bullet_points>
## Write Like a Human, Not an AI
Keep it short and direct. If you can say something in fewer words, do it. Long explanations often confuse more than they help.
Use normal sentence lengths. Mix short and long sentences naturally, like you would when talking to someone. Avoid those meandering compound sentences that go on forever.
Cut the corporate speak. Instead of "utilize," say "use." Instead of "in order to," just say "to." Write like you're explaining something to a colleague, not drafting a press release.
Don't over-explain obvious things. If users are reading documentation, they probably understand basic concepts. Respect their intelligence.
## Never use em dashes or emojis
That's pretty much it. Never use them. Only AI writes with em dashes or emojis.
# Anthropomorphizing Cline
When referring to Cline, always call him a "him" not an "it".
Bad example:
- When Cline cant execute commands or read their output, you lose access to one of its most powerful capabilities.
Good Example:
- When Cline cant execute commands or read their output, you lose access to one of his most powerful capabilities.
# Using "I" when sharing your workflow
Adding a personal touch goes a long way. There are great examples in the docs currently where I use "I" to share how I personally use cline, from dev to dev. It's a great technique.
# Crosslinking relevant documentation pages
Make sure you crosslink when you're done writing the docs. If there are relevant docs, just link to them.
# Brevity is the soul of wit
Don't ramble if you don't need to. Use bullet points and numbered lists. Keep things easy to read.
<bad_example>
When Cline can't execute commands or read their output, you lose access to one of his most powerful capabilities. Terminal integration problems are frustrating, but they're usually fixable with a few simple changes.
## The Most Common Problem: Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline isn't getting command output, the issue is almost always your shell configuration. Complex shell setups with custom prompts, plugins, and fancy configurations can interfere with VSCode's terminal integration.
**Switch to bash first.** This fixes the problem 90% of the time. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown. Restart VSCode after making this change.
Still having issues? Try increasing the shell integration timeout. Go to Cline Settings → Terminal → Shell Integration Timeout and change it from 4 seconds to 10 seconds. Heavy shell configurations need more time to initialize properly.
If commands are running in the wrong directories or you're seeing weird behavior, disable aggressive terminal reuse. In Cline Settings → Terminal, uncheck "Enable aggressive terminal reuse." This creates more terminal instances but ensures each command runs in a clean environment.
</bad_exaxmple>
The first part is total filler, useless to any serious developer. You can tell it's written by a non technical person that doesn't value clean, straightforward information.
<good_example>
## Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline can't read command output, your shell configuration is interfering with VSCode's terminal integration.
**Switch to bash first.** Go to Cline Settings → Terminal → Default Terminal Profile and select "bash." This fixes 90% of problems.
Still broken? Try these:
- Increase shell integration timeout to 10 seconds in Cline Settings → Terminal
- Disable "aggressive terminal reuse" if commands run in wrong directories
- Restart VSCode after making changes
</good_example>
The good version cuts straight to the problem and solution. No hand-holding, no emotional language about frustration, just the facts: what's wrong, how to fix it, what to try next. Respects that developers want information, not sympathy.RetryClaude can make mistakes. Please double-check responses.
ALWAYS consider your audience. And your audience is devs who don't want their time wasted. Give them the info. I cannot stress this enough. Use bullet points and numbered lists. Prose is good, but every word should actually mean something to the dev reading it.
# Lastly, before you start writing docs
1. Internalize these guidelines. I mean it.
2. Read `docs/docs.json` and get an understanding of the structure of the docs. This will come in handly at the end when you're doing a final pass so you can cross link to docs where relevant.
3. Read some good examples that I personally wrote and am proud of:
- docs/features/slash-commands/workflows.mdx
- docs/features/slash-commands/new-task.mdx
- docs/features/at-mentions/overview.mdx
- docs/features/drag-and-drop.mdx
4. If the user specifies any other instructions make sure you follow them.
+8 -2
View File
@@ -20,8 +20,14 @@
"no-throw-literal": "warn",
"semi": "off",
"react-hooks/exhaustive-deps": "off",
"eslint-rules/no-protobuf-object-literals": "error",
"eslint-rules/no-grpc-client-object-literals": "error"
"eslint-rules/no-direct-vscode-api": "warn",
"no-restricted-syntax": [
"error",
{
"selector": "VariableDeclarator[id.type=\"ObjectPattern\"][init.object.name=\"process\"][init.property.name=\"env\"]",
"message": "Use process.env.VARIABLE_NAME directly instead of destructuring"
}
]
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
+12 -18
View File
@@ -5,7 +5,7 @@ body:
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude 3.5 Sonnet. Cline uses complex prompts so less capable models may not work as expected.
**Important:** All bug reports must be reproducible using Claude 4 Sonnet. Cline uses complex prompts so less capable models may not work as expected.
- type: textarea
id: what-happened
attributes:
@@ -24,7 +24,7 @@ body:
2.
3.
validations:
required: true
required: false
- type: textarea
id: logs
attributes:
@@ -39,20 +39,19 @@ body:
placeholder: "e.g., cline:anthropic/claude-3.7-sonnet, gemini:gemini-2.5-pro-exp-03-25"
validations:
required: true
- type: input
id: operating-system
attributes:
label: Operating System
description: What operating system are you using?
placeholder: "e.g., Windows 11, macOS Sonoma, Ubuntu 22.04"
validations:
required: true
- type: textarea
id: system-info
attributes:
label: System Info
description: What system information is relevant to the issue?
placeholder: "e.g., CPU: Intel Core i7-11700K, GPU: NVIDIA GeForce RTX 3070, RAM: 32GB DDR4"
label: System Information
description: What operating system and hardware are you using?
placeholder: |
Operating System: Windows 11, macOS Sonoma, Ubuntu 22.04, etc.
Hardware: CPU, GPU, RAM specifications if relevant
e.g.,
OS: Windows 11
CPU: Intel Core i7-11700K
GPU: NVIDIA GeForce RTX 3070
RAM: 32GB DDR4
validations:
required: true
- type: input
@@ -63,8 +62,3 @@ body:
placeholder: "e.g., 1.2.3"
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional context
description: Add any other context about the problem here, such as screenshots or related issues.
+1 -4
View File
@@ -1,4 +1,4 @@
blank_issues_enabled: true
blank_issues_enabled: false
contact_links:
- name: ✨ Feature Request
url: https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop
@@ -6,6 +6,3 @@ contact_links:
- name: 👋 Cline Discord
url: https://discord.gg/cline
about: Join our Discord community for discussions and support
- name: ❓ Other Questions?
url: https://x.com/sdrzn
about: Contact the developer on X @sdrzn for other inquiries
+10 -10
View File
@@ -1,16 +1,16 @@
<!-- ⚠️ Important: Discussion Required Before PR (Community Contributors) -->
<!--
Thank you for contributing to Cline!
**For community contributors, before submitting this PR, please ensure you have:**
⚠️ Important: Before submitting this PR, please ensure you have:
- For feature requests: Created a discussion in our Feature Requests discussions board https://github.com/cline/cline/discussions/categories/feature-requests and received approval from core maintainers before implementation
- For all changes: Link the associated issue/discussion in the "Related Issue" section below
- [ ] **Opened an issue** to discuss your proposed changes with the community
- [ ] **Received approval** from a core Cline contributor to proceed with the implementation
- [ ] **Linked the issue below** in the "Related Issue" section
Limited exceptions:
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly without prior discussion.
**Exceptions:** Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly.
**Why this requirement?** We deeply appreciate all community contributions - they are the core reason we're able to operate successfully and keep innovating! We welcome community input and want to make it as easy as possible for people to submit quality work. This process helps our core maintainers review new ideas faster and saves contributor time by ensuring you have the go-ahead before spending time on implementation.
---
Why this requirement?
We deeply appreciate all community contributions - they are essential to Cline's success! To ensure the best use of everyone's time and maintain project direction, we use our Feature Requests discussions board to gauge community interest and validate feature ideas before implementation begins. This helps us focus development efforts on features that will benefit the most users.
-->
### Related Issue
+108
View File
@@ -0,0 +1,108 @@
name: E2E Tests
on:
push:
branches:
- main
pull_request:
types: [opened, reopened, synchronize, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
matrix_prep:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- id: set-matrix
run: |
echo 'matrix=[{"runner":"ubuntu"},{"runner":"windows"},{"runner":"macos"}]' >> $GITHUB_OUTPUT
e2e:
needs: matrix_prep
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.matrix_prep.outputs.matrix) }}
runs-on: ${{ matrix.runner }}-latest
timeout-minutes: 20
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- 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') }}
# Cache VS Code installation
- name: Cache VS Code
uses: actions/cache@v4
id: vscode-cache
with:
path: .vscode-test
key: vscode-${{ runner.os }}-stable-${{ hashFiles('.vscode-test.mjs', 'package.json') }}
restore-keys: |
vscode-${{ runner.os }}-stable-
# Cache Playwright browsers
- name: Cache Playwright browsers
uses: actions/cache@v4
id: playwright-cache
with:
path: |
~/.cache/ms-playwright
~/Library/Caches/ms-playwright
~/AppData/Local/ms-playwright
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
playwright-browsers-${{ runner.os }}-
- 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: Install xvfb on Linux
if: matrix.runner == 'ubuntu'
run: sudo apt-get update && sudo apt-get install -y xvfb
# Run optimized E2E tests (eliminates redundant builds)
- name: Run E2E tests - Linux
if: matrix.runner == 'ubuntu'
run: xvfb-run -a npm run test:e2e:optimal
- name: Run E2E tests - Non-Linux
if: matrix.runner != 'ubuntu'
run: npm run test:e2e:optimal
- uses: actions/upload-artifact@v4
if: ${{ failure() }}
with:
name: playwright-recordings-${{ matrix.runner }}
path: |
test-results/playwright/
+1
View File
@@ -94,6 +94,7 @@ jobs:
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
CLINE_ENVIRONMENT: production
run: |
# Required to generate the .vsix
vsce package --out "cline-${{ steps.get_version.outputs.version }}.vsix"
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
issues: write
pull-requests: write
steps:
- uses: actions/stale@28ca103
- uses: actions/stale@v9
with:
days-before-issue-stale: 60
days-before-issue-close: 14
+4
View File
@@ -68,6 +68,10 @@ 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: Install local modules on windows
if: runner.os == 'Windows' && steps.root-cache.outputs.cache-hit == 'true'
run: |
+10 -15
View File
@@ -7,6 +7,7 @@ tmp
*.vsix
.DS_Store
.idea
pnpm-lock.yaml
@@ -14,6 +15,9 @@ pnpm-lock.yaml
.venv
.actrc
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
# Ignore coverage directories and files
coverage
# But don't ignore the coverage scripts in .github/scripts/
@@ -21,19 +25,10 @@ coverage
*evals.env
# Generated proto files
src/core/controller/*/methods.ts
src/core/controller/*/index.ts
src/core/controller/grpc-service-config.ts
# Shared
src/shared/proto/*.ts
src/shared/proto/host/*.ts
# Webview
## Generated files ##
src/generated/
src/shared/proto/
webview-ui/src/services/grpc-client.ts
# Standalone
src/standalone/server-setup.ts
# Host bridge
src/hosts/vscode/*/methods.ts
src/hosts/vscode/*/index.ts
src/hosts/vscode/client/host-grpc-client.ts
src/hosts/vscode/host-grpc-service-config.ts
# E2E Tests
test-results
+4 -4
View File
@@ -9,9 +9,9 @@ npm run lint || {
# Run Prettier
echo "Running Prettier..."
npm run format || {
echo "❌ Prettier check failed. Run 'npm run format:fix' to automatically fix formatting issues."
exit 1
}
npx lint-staged --verbose || {
echo "❌ Prettier failed. Please fix the errors and try committing again."
exit 1
}
echo "✅ All checks passed!"
+3
View File
@@ -5,3 +5,6 @@ webview-ui/build/
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
evals/
docs/
out/
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from "@vscode/test-cli"
import path from "path"
export default defineConfig({
files: "{out/**/*.test.js,src/**/*.test.js}",
files: "{out/**/*.test.js,src/**/*.test.js,!src/test/e2e/**/*.test.js,!out/src/test/e2e/**/*.test.js}",
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
+41 -12
View File
@@ -6,7 +6,7 @@
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"name": "Run Extension (production)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
@@ -14,7 +14,34 @@
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
{
"name": "Run Extension (staging)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "staging"
}
},
{
"name": "Run Extension (local)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "local"
}
},
{
@@ -23,26 +50,28 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync",
"off",
"--sync=off",
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "clean-sandbox",
"preLaunchTask": "clean-tmp-user",
"internalConsoleOptions": "openOnSessionStart",
"postDebugTask": "stop",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
"TEMP_PROFILE": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
{
"type": "node",
"request": "launch",
"name": "Run Standalone Extension",
"name": "Run cline-core service",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
@@ -50,12 +79,12 @@
"outFiles": ["${workspaceFolder}/dist-standalone/**/*.js"],
"preLaunchTask": "compile-standalone",
"env": {
"GRPC_TRACE": "all",
"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules",
"CLINE_DIR": "${userHome}/.cline-standalone"
// Turns on grpc debug log.
//"GRPC_TRACE": "all",
//"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules"
},
"program": "standalone.js"
"program": "cline-core.js"
}
]
}
+5 -1
View File
@@ -9,5 +9,9 @@
"dist": true // set this to false to include "dist" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
"typescript.tsc.autoDetect": "off",
// Protobuf settings
"protoc": {
"options": ["--proto_path=proto"]
}
}
+2 -2
View File
@@ -233,10 +233,10 @@
"type": "shell"
},
{
"label": "clean-sandbox",
"label": "clean-tmp-user",
"type": "shell",
"dependsOn": ["watch"],
"command": "rm -rf .vscode-dev"
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
}
],
"inputs": [
+26 -8
View File
@@ -1,24 +1,40 @@
# Default
.vscode/**
.vscode-test/**
out/**
node_modules/**
out/
dist-standalone/
node_modules/
src/**
standalone/**
.gitignore
.yarnrc
esbuild.js
vsc-extension-quickstart.md
**/tsconfig.json
tsconfig*.json
**/.eslintrc.json
**/*.map
**/*.ts
**/.vscode-test.*
eslint-rules/**
.github/**
.husky/**
# Custom
demo.gif
**/demo.gif
.nvmrc
.gitattributes
.prettierignore
.husky/
.github/
eslint-rules/
old_docs/
evals/
.changie.yaml
.codespellrc
.mocharc.json
buf.yaml
.changeset/
.clinerules/
# Ignore all webview-ui files except the build directory (https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/frameworks/hello-world-react-cra/.vscodeignore)
webview-ui/src/**
@@ -32,17 +48,19 @@ webview-ui/node_modules/**
# Ignore docs
docs/**
old_docs/**
# Fix issue where codicons don't get packaged (https://github.com/microsoft/vscode-extension-samples/issues/692)
!node_modules/@vscode/codicons/dist/codicon.css
!node_modules/@vscode/codicons/dist/codicon.ttf
# Include KaTeX CSS and fonts for LaTeX rendering
!webview-ui/node_modules/katex/dist/katex.min.css
!webview-ui/node_modules/katex/dist/fonts/**
# Include default themes JSON files used in getTheme
!src/integrations/theme/default-themes/**
# Include icons
!assets/icons/**
# Ignore E2E build files
e2e-build.js
e2e.vsix
test-results/
+657 -474
View File
File diff suppressed because it is too large Load Diff
+61 -4
View File
@@ -10,16 +10,74 @@ Bug reports help make Cline better for everyone! Before creating a new issue, pl
🔐 <b>Important:</b> If you discover a security vulnerability, please use the <a href="https://github.com/cline/cline/security/advisories/new">Github security tool to report it privately</a>.
</blockquote>
## Before Contributing
All contributions must begin with a GitHub Issue, unless the change is for small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality.
**For features and contributions**:
- First check the [Feature Requests discussions board](https://github.com/cline/cline/discussions/categories/feature-requests) for similar ideas
- If your idea is new, create a new feature request
- Wait for approval from core maintainers before starting implementation
- Once approved, feel free to begin working on a PR with the help of our community!
**PRs without approved issues may be closed.**
## Deciding What to Work On
Looking for a good first contribution? Check out issues labeled ["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue) or ["help wanted"](https://github.com/cline/cline/labels/help%20wanted). These are specifically curated for new contributors and areas where we'd love some help!
We also welcome contributions to our [documentation](https://github.com/cline/cline/tree/main/docs)! Whether it's fixing typos, improving existing guides, or creating new educational content - we'd love to build a community-driven repository of resources that helps everyone get the most out of Cline. You can start by diving into `/docs` and looking for areas that need improvement.
If you're planning to work on a bigger feature, please create a [feature request](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop) first so we can discuss whether it aligns with Cline's vision.
## Development Setup
### Local Development Instructions
1. Clone the repository _(Requires [git-lfs](https://git-lfs.com/))_:
```bash
git clone https://github.com/cline/cline.git
```
2. Open the project in VSCode:
```bash
code cline
```
3. Install the necessary dependencies for the extension and webview-gui:
```bash
npm run install:all
```
4. Launch by pressing `F5` (or `Run`->`Start Debugging`) to open a new VSCode window with the extension loaded. (You may need to install the [esbuild problem matchers extension](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers) if you run into issues building the project.)
### Creating a Pull Request
1. Before creating a PR, generate a changeset entry:
```bash
npm run changeset
```
This will prompt you for:
- Type of change (major, minor, patch)
- `major` → breaking changes (1.0.0 → 2.0.0)
- `minor` → new features (1.0.0 → 1.1.0)
- `patch` → bug fixes (1.0.0 → 1.0.1)
- Description of your changes
2. Commit your changes and the generated `.changeset` file
3. Push your branch and create a PR on GitHub. Our CI will:
- Run tests and checks
- Changesetbot will create a comment showing the version impact
- When merged to main, changesetbot will create a Version Packages PR
- When the Version Packages PR is merged, a new release will be published
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
1. **VS Code Extensions**
- When opening the project, VS Code will prompt you to install recommended extensions
@@ -29,6 +87,7 @@ If you're planning to work on a bigger feature, please create a [feature request
2. **Local Development**
- Run `npm run install:all` to install dependencies
- Run `npm run test` to run tests locally
- Run → Start Debugging or `>Debug: Select and Start Debugging` and wait for a new VS Code instance to open
- Before submitting PR, run `npm run format:fix` to format your code
3. **Linux-specific Setup**
@@ -73,8 +132,6 @@ If you're planning to work on a bigger feature, please create a [feature request
xvfb
```
- Run `npm run test:ci` to run tests locally
## Writing and Submitting Code
Anyone can contribute code to Cline, but we ask that you follow these guidelines to ensure your contributions can be smoothly integrated:
+2 -46
View File
@@ -30,7 +30,7 @@ English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md
</table>
</div>
Meet Cline, an AI assistant that can use your **CLI** a**N**d **E**ditor.
Meet Cline (pronounced /klaɪn/, like "Klein"), an AI assistant that can use your **CLI** a**N**d **E**ditor.
Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthropic.com/claude/sonnet), Cline can handle complex software development tasks step-by-step. With tools that let him create & edit files, explore large projects, use the browser, and execute terminal commands (after you grant permission), he can assist you in ways that go beyond code completion or tech support. Cline can even use the Model Context Protocol (MCP) to create new tools and extend his own capabilities. While autonomous AI scripts traditionally run in sandboxed environments, this extension provides a human-in-the-loop GUI to approve every file change and terminal command, providing a safe and accessible way to explore the potential of agentic AI.
@@ -51,7 +51,7 @@ Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthrop
### Use any API and Model
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, and Cerebras. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras and Groq. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
The extension also keeps track of total tokens and API usage cost for the entire task loop and individual requests, keeping you informed of spend every step of the way.
@@ -141,50 +141,6 @@ For example, when working with a local web server, you can use 'Restore Workspac
To contribute to the project, start with our [Contributing Guide](CONTRIBUTING.md) to learn the basics. You can also join our [Discord](https://discord.gg/cline) to chat with other contributors in the `#contributors` channel. If you're looking for full-time work, check out our open positions on our [careers page](https://cline.bot/join-us)!
<details>
<summary>Local Development Instructions</summary>
1. Clone the repository _(Requires [git-lfs](https://git-lfs.com/))_:
```bash
git clone https://github.com/cline/cline.git
```
2. Open the project in VSCode:
```bash
code cline
```
3. Install the necessary dependencies for the extension and webview-gui:
```bash
npm run install:all
```
4. Launch by pressing `F5` (or `Run`->`Start Debugging`) to open a new VSCode window with the extension loaded. (You may need to install the [esbuild problem matchers extension](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers) if you run into issues building the project.)
</details>
<details>
<summary>Creating a Pull Request</summary>
1. Before creating a PR, generate a changeset entry:
```bash
npm run changeset
```
This will prompt you for:
- Type of change (major, minor, patch)
- `major` → breaking changes (1.0.0 → 2.0.0)
- `minor` → new features (1.0.0 → 1.1.0)
- `patch` → bug fixes (1.0.0 → 1.0.1)
- Description of your changes
2. Commit your changes and the generated `.changeset` file
3. Push your branch and create a PR on GitHub. Our CI will:
- Run tests and checks
- Changesetbot will create a comment showing the version impact
- When merged to main, changesetbot will create a Version Packages PR
- When the Version Packages PR is merged, a new release will be published
</details>
## License
[Apache 2.0 © 2025 Cline Bot Inc.](./LICENSE)
+21
View File
@@ -0,0 +1,21 @@
version: v2
modules:
- path: proto
name: cline/cline/lint
lint:
use:
- STANDARD
except: # Add exceptions for current patterns that contradict STANDARD settings
- RPC_PASCAL_CASE # rpcs are camel case (start with lowercase)
- RPC_REQUEST_RESPONSE_UNIQUE # request messages are not unique.
- RPC_REQUEST_STANDARD_NAME # request messages dont all end with Request
- RPC_RESPONSE_STANDARD_NAME # response messages dont all end with Response
- PACKAGE_VERSION_SUFFIX # package name does not contain version.
- ENUM_VALUE_PREFIX # enum values dont start with the enum name.
- ENUM_ZERO_VALUE_SUFFIX # first value does not have to be UNSPECIFIED.
# breaking:
# use:
# - WIRE_JSON # Detect changes that break the json wire format (this is the minimum recommended level.)
+8 -2
View File
@@ -61,7 +61,6 @@
"getting-started/installing-cline",
"getting-started/installing-dev-essentials",
"getting-started/model-selection-guide",
"getting-started/our-favorite-tech-stack",
"getting-started/task-management",
"getting-started/understanding-context-management",
"getting-started/what-is-cline"
@@ -146,6 +145,8 @@
"group": "Provider Configuration",
"pages": [
"provider-config/anthropic",
"provider-config/claude-code",
"provider-config/aws-bedrock-with-apikey-authentication",
"provider-config/aws-bedrock-with-credentials-authentication",
"provider-config/aws-bedrock-with-profile-authentication",
"provider-config/gcp-vertex-ai",
@@ -158,7 +159,8 @@
"provider-config/openai",
"provider-config/openai-compatible",
"provider-config/openrouter",
"provider-config/requesty"
"provider-config/requesty",
"provider-config/sap-aicore"
]
},
{
@@ -169,6 +171,10 @@
"running-models-locally/ollama"
]
},
{
"group": "Troubleshooting",
"pages": ["troubleshooting/terminal-quick-fixes", "troubleshooting/terminal-integration-guide"]
},
{
"group": "More Info",
"pages": ["more-info/telemetry"]
@@ -14,6 +14,8 @@ Certain scenarios may warrant using local models, including handling highly sens
#### [IAM Security Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) (For administrators)
#### [AWS Bedrock setup for API Keys](/provider-config/aws-bedrock-with-apikey-authentication)
#### [AWS Bedrock setup for Legacy IAM (AWS Credentials)](/provider-config/aws-bedrock-with-credentials-authentication)
#### [AWS Bedrock setup for SSO token (AWS Profile)](/provider-config/aws-bedrock-with-profile-authentication)
@@ -120,7 +120,7 @@ Example of context window usage over 50% with a 200K context window:
# Context Window Usage
105,000 / 200,000 tokens (53%)
Model: anthropic/claude-3.7-sonnet (200K context window)
Model: anthropic/claude-sonnet-4 (200K context window)
\`\`\`
**IMPORTANT**: When you see context window usage at or above 50%, you MUST:
@@ -58,3 +58,16 @@ When you use the terminal mention in your message, here's what happens behind th
6. The AI can now "see" the complete terminal output with all formatting preserved
This process happens automatically whenever you use the terminal mention, giving the AI access to your command results, error messages, and other terminal output without you having to copy it manually.
## Troubleshooting Terminal Issues
If you're experiencing issues with terminal mentions or terminal integration in general (such as "Shell Integration Unavailable" or commands not showing output), please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
Common issues include:
- Terminal mentions not capturing output
- "Shell Integration Unavailable" messages in Cline chat
- Commands executing but output not visible to Cline
- Terminal integration working inconsistently
The troubleshooting guide provides platform-specific solutions and detailed configuration steps to resolve these issues.
+13 -1
View File
@@ -11,7 +11,19 @@ You can create a rule by clicking the `+` button in the Rules tab. This will ope
Once you save the file:
- Your rule will be stored in the `.clinerules/` directory in your project (if it's a Workspace Rule)
- Or in the `Documents/Cline/Rules` directory (if it's a Global Rule).
- Or in the Global Rules directory (if it's a Global Rule):
### Global Rules Directory Location
The location of your Global Rules directory depends on your operating system:
| Operating System | Default Location | Notes |
|------------------|------------------|-------|
| **Windows** | `Documents\Cline\Rules` | Uses system Documents folder |
| **macOS** | `~/Documents/Cline/Rules` | Uses user Documents folder |
| **Linux/WSL** | `~/Documents/Cline/Rules` | May fall back to `~/Cline/Rules` on some systems |
> **Note for Linux/WSL users**: If you don't find your global rules in `~/Documents/Cline/Rules`, check `~/Cline/Rules` as the location may vary depending on your system configuration and whether the Documents directory exists.
You can also have Cline create a rule for you by using the [`/newrule` slash command](/features/slash-commands/new-rule) in the chat.
@@ -74,8 +74,25 @@ This approach ensures that all terminal output, including colors and formatting,
- **Select specific output when needed**: By default, the integration captures all terminal content, but you can also select specific lines before right-clicking to focus on just the relevant output.
- **Combine with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature.
- **Combine terminal outputs with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature.
- **Use for build and test output**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines.
- **Contextualize build & test outputs with the terminal**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines.
Next time you're staring at a cryptic error message in your terminal, try using Cline's terminal integration instead of copying and pasting. You'll get more accurate help because Cline can see the complete terminal context with proper formatting.
## Troubleshooting Terminal Issues
If you're experiencing issues with terminal integration, such as "Shell Integration Unavailable" or commands not showing output, please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
The troubleshooting guide covers:
- Common terminal integration issues and quick fixes
- Platform-specific solutions for Windows, macOS, and Linux
- Shell-specific configurations for zsh, bash, PowerShell, and more
- Advanced debugging techniques
- Terminal settings optimization
<Tip>
**Quick Fix**: Most terminal issues can be resolved by switching to bash in the Cline settings and increasing the shell
integration timeout to 10 seconds.
</Tip>
@@ -1,238 +0,0 @@
---
title: "Our Favorite Tech Stack"
description: "A curated list of our recommended technologies and tools for building modern web applications with Cline."
---
## Recommended Stack for New Cline Users (2025)
### Your Complete Development Environment
#### Development Tools
- **VS Code** - Your code editor, [download here](https://code.visualstudio.com/)
- **GitHub** - Where your code lives, [sign up here](https://github.com)
#### Frontend
- **Next.js 14+** - React framework with App Router
- **Tailwind CSS** - Beautiful styling without writing CSS
- **TypeScript** - JavaScript, but safer and smarter
#### Backend
- **Supabase** - Your complete backend solution, [sign up with GitHub](https://supabase.com)
- PostgreSQL database
- Authentication
- File storage
- Real-time updates
#### Deployment
- **Vercel** - Where your app runs, [sign up with GitHub](https://vercel.com)
- Automatic deployments from GitHub
- Preview deployments for testing
- Production-ready CDN
#### AI Development
Choose your AI assistant based on your needs:
| Model | Input Cost (per 1M tokens) | Output Cost (per 1M tokens) | Best For |
| ----------------- | -------------------------- | --------------------------- | ------------------------------ |
| Claude 3.5 Sonnet | $3.00 | $15.00 | Production apps, complex tasks |
| DeepSeek R1 | $1.00 | $3.00 | Budget-conscious production |
| DeepSeek V3 | $0.14 | $2.20 | Budget-conscious development |
#### Free Tier Benefits
**Vercel (Hobby)**
- 100 GB data transfer/month
- 100k serverless function invocations
- 100 MB deployment size
- Automatic HTTPS & CI/CD
**Supabase (Free)**
- 500 MB database storage
- 1 GB file storage
- 50k monthly active users
- 2M real-time messages/month
**GitHub (Free)**
- Unlimited public repositories
- GitHub Actions CI/CD
- Project management tools
- Collaboration features
### Getting Started
1. Install the development essentials:
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/cline-memory-bank)
- Create an empty `cline_docs` folder in your project root
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
- Tell Cline to "initialize memory bank"
3. Add our recommended stack configuration:
- Create `.clinerules` file (see template below)
- Let Cline handle the rest!
#### Example Project Brief
```markdown
# Project Brief
## Overview
Building a [type of application] that will [main purpose].
## Core Features
- Feature 1
- Feature 2
- Feature 3
## Target Users
[Describe who will use your application]
## Technical Preferences (optional)
- Any specific technologies you want to use
- Any specific requirements or constraints
```
### .clinerules Template
```markdown
# Project Configuration
## Tech Stack
- Next.js 14+ with App Router
- Tailwind CSS for styling
- Supabase for backend
- Vercel for deployment
- GitHub for version control
## Project Structure
/src
/app # Next.js App Router pages
/components # React components
/lib # Utility functions
/types # TypeScript types
/supabase
/migrations # SQL migration files
/seed # Seed data files
/public # Static assets
## Database Migrations
SQL files in /supabase/migrations should:
- Use sequential numbering: 001, 002, etc.
- Include descriptive names
- Be reviewed by Cline before execution
Example: 001_create_users_table.sql
## Development Workflow
- Cline helps write and review code changes
- Vercel automatically deploys from main branch
- Database migrations reviewed by Cline before execution
## Security
DO NOT read or modify:
- .env files
- \*_/config/secrets._
- Any file containing API keys or credentials
```
### Learning Resources (2025)
Want to learn more about the technologies we're using? Here are some great resources:
#### Next.js and React
- [Official Learn Next.js Course](https://nextjs.org/learn) - Interactive tutorial
- [NextJS App Router: Modern Web Dev in 1 Hour](https://www.youtube.com/nextjs-modern) - Quick overview
- [Building Real-World Apps with Next.js](https://www.youtube.com/nextjs-real-world) - Practical examples
#### Supabase
- [Supabase From Scratch](https://www.udemy.com/supabase-scratch) - Comprehensive course
- [Official Quickstart Guides](https://supabase.com/docs/guides/getting-started)
- [Real-Time Apps with Next.js and Supabase](https://www.newline.co/courses/supabase-nextjs)
#### Tailwind CSS
- [Tailwind CSS Tutorial for Beginners](https://www.youtube.com/tailwind-2025)
- [Official Tailwind Documentation](https://tailwindcss.com/docs)
- Interactive course at [Scrimba Tailwind CSS Course](https://scrimba.com/learn/tailwind)
### Other Things to Know
#### Working with Git & GitHub
Git helps you track changes in your code and collaborate with others. Here are the essential commands you'll use:
**Daily Development**
```bash
# Save your changes (do this often!)
git add . # Stage all changed files
git commit -m "Add login page" # Save changes with a clear message
# Share your changes
git push origin main # Upload to GitHub
```
**Common Workflow**
1. **Start of day**: Get latest changes
```bash
git pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
git add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
git push origin main # Upload to GitHub
```
**Best Practices**
- Commit often with clear messages
- Pull before starting new work
- Push completed work to share with others
- Use `.gitignore` to avoid committing sensitive files
> **Tip**: Vercel automatically deploys when you push to main!
#### Environment Variables
- Store secrets in `.env.local` for development
- Add them to Vercel project settings for production
- Never commit `.env` files to Git
#### Getting Help
1. Use `/help` in Cline chat for immediate assistance
2. Check [Cline Documentation](https://docs.cline.bot)
3. Join our [Discord Community](https://discord.gg/cline)
4. Search GitHub issues for common problems
Remember: Cline is here to help at every step. Just ask for guidance or clarification when needed!
@@ -17,6 +17,7 @@ There are multiple places online to find MCP servers:
- [mcpservers.org](https://mcpservers.org/)
- [mcp.so](https://mcp.so/)
- [glama.ai/mcp/servers](https://glama.ai/mcp/servers)
- [mcp.composio.dev](https://mcp.composio.dev/)
These directories allow users to sort the servers by various criteria such as downloads, date, stars, and use case. Each entry provides information such as features, tools, and configuration instructions.
+6 -6
View File
@@ -4,17 +4,17 @@ title: "Telemetry"
### Overview
To help make Cline better for everyone, we collect anonymous usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience.
To help make Cline better for everyone, we collect usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience.
We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see exactly what we track.
We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/posthog/telemetry/TelemetryService.ts) to see exactly what we track.
### Tracking Policy
Privacy is our priority. All collected data is anonymized before being sent to PostHog, with no personally identifiable information (PII) included. Your code, prompts, and conversation content always remain private and are never collected.
Privacy is our priority. By default, all collected data is anonymized. If you log in with a Cline account, your telemetry data will be associated with your account to help us improve the product and provide better support when you encounter issues. Your code, prompts, and conversation content always remain private and are never collected.
### What We Track
We collect basic anonymous usage data including:
We collect basic usage data including:
**Task Interactions:** When tasks start and finish, conversation flow (without content)\
**Mode and Tool Usage:** Switches between plan/act modes, which tools are being used\
@@ -22,13 +22,13 @@ We collect basic anonymous usage data including:
**System Context:** OS type and VS Code environment details\
**UI Activity:** Navigation patterns and feature usage
For complete transparency, you can inspect our [telemetry implementation](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see the exact events we track.
For complete transparency, you can inspect our [telemetry implementation](https://github.com/cline/cline/blob/main/src/services/posthog/telemetry/TelemetryService.ts) to see the exact events we track.
### How to Opt Out
Telemetry in Cline is entirely optional:
- When you update or install our VS Code extension, you'll see a message about our anonymous telemetry
- When you update or install our VS Code extension, you'll see a message about our telemetry
- You can change your preference anytime in settings
Cline also respects VS Code's global telemetry settings. If you've disabled telemetry at the VS Code level, Cline's telemetry will automatically be disabled as well.
-10118
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -4,13 +4,15 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "mintlify dev"
"dev": "mintlify dev",
"check": "mintlify broken-links",
"rename": "mintlify rename"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"mintlify": "^4.0.538"
"mintlify": "^4.2.23"
}
}
@@ -0,0 +1,135 @@
---
title: "AWS Bedrock"
description: "Learn how to set up AWS Bedrock with Cline using credentials authentication. This guide covers AWS environment setup, regional access verification, and secure integration with the Cline VS Code extension."
---
### Overview
- **AWS Bedrock:** A fully managed service that offers access to leading generative AI models (e.g., Anthropic Claude, Amazon Nova) through AWS.\
[Learn more about AWS Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html).
- **Cline:** A VS Code extension that acts as a coding assistant by integrating with AI models—empowering developers to generate code, debug, and analyze data.
- **Developer Focus:** This guide is tailored for individual developers that want to enable access to frontier models via AWS Bedrock with a simplified setup using API Keys.
---
### Step 1: Prepare Your AWS Environment
#### 1.1 Individual user setup - Create a Bedrock API Key
For more detailed instructions check the [documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html).
1. **Sign in to the AWS Management Console:**\
[AWS Console](https://aws.amazon.com/console/)
2. **Access Bedrock Console:**
- [Bedrock Console](https://console.aws.amazon.com/bedrock)
- Create a new Long Lived API Key. This API Key will have by default the `AmazonBedrockLimitedAccess` IAM policy
[View AmazonBedrockLimitedAccess Policy Details](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html)
#### 1.2 Create or Modify the Policy
To ensure Cline can interact with AWS Bedrock, your IAM user or role needs specific permissions. While the `AmazonBedrockLimitedAccess` managed policy provides comprehensive access, for a more restricted and secure setup adhering to the principle of least privilege, the following minimal permissions are sufficient for Cline's core model invocation functionality:
- `bedrock:InvokeModel`
- `bedrock:InvokeModelWithResponseStream`
- `bedrock:CallWithBearerToken`
You can create a custom IAM policy with these permissions and attach it to your IAM user or role.
1. In the AWS IAM console, create a new policy.
2. Use the JSON editor to add the following policy document:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream", "bedrock:CallWithBearerToken"],
"Resource": "*" // For enhanced security, scope this to specific model ARNs if possible.
}
]
}
```
3. Name the policy (e.g., `ClineBedrockInvokeAccess`) and attach it to the IAM user associated with the key you created. The IAM user and the API key have the same prefix.
**Important Considerations:**
- **Model Listing in Cline:** The minimal permissions (`bedrock:InvokeModel`, `bedrock:InvokeModelWithResponseStream`) are sufficient for Cline to _use_ a model if you specify the model ID directly in Cline's settings. If you rely on Cline to dynamically list available Bedrock models, you might need additional permissions like `bedrock:ListFoundationModels`.
- **AWS Marketplace Subscriptions:** For third-party models (e.g., Anthropic Claude), the **`AmazonBedrockLimitedAccess`** policy grants you the necessary permissions to subscribe via the AWS Marketplace. There is no explicit access to be enabled. For Anthropic models you are still required to submit a First Time Use (FTU) form via the Console. If you get the following message in the Cline chat `[ERROR] Failed to process response: Model use case details have not been submitted for this account. Fill out the Anthropic use case details form before using the model.` then open the [Playground in the AWS Bedrock Console](https://console.aws.amazon.com/bedrock/home?#/text-generation-playground), select any Anthropic model and fill in the form (you might need to send a prompt first)
---
### Step 2: Verify Regional and Model Access
#### 2.1 Choose and Confirm a Region
1. **Select a Region:**\
AWS Bedrock is available in multiple regions (e.g., US East, Europe, Asia Pacific). Choose the region that meets your latency and compliance needs.\
[AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)
2. **Verify Model Access:**
- **Note:** Some models are only accessible via an [Inference Profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html). In such case check the box "Cross Region Inference".
---
### Step 3: Configure the Cline VS Code Extension
#### 3.1 Install and Open Cline
1. **Install VS Code:**\
Download from the [VS Code website](https://code.visualstudio.com/).
2. **Install the Cline Extension:**
- Open VS Code.
- Go to the Extensions Marketplace (`Ctrl+Shift+X` or `Cmd+Shift+X`).
- Search for **Cline** and install it.
#### 3.2 Configure Cline Settings
1. **Open Cline Settings:**
- Click on the settings ⚙️ to select your API Provider.
2. **Select AWS Bedrock as the API Provider:**
- From the API Provider dropdown, choose **AWS Bedrock**.
3. **Enter Your AWS API Key:**
- Input your **API Key**
- Specify the correct **AWS Region** (e.g., `us-east-1` or your enterprise-approved region).
4. **Select a Model:**
- Choose an on-demand model (e.g., **anthropic.claude-3-5-sonnet-20241022-v2:0**).
5. **Save and Test:**
- Click **Done/Save** to apply your settings.
- Test the integration by sending a simple prompt (e.g., "Generate a Python function to check if a number is prime.").
---
### Step 4: Security, Monitoring, and Best Practices
1. **Secure Access:**
- Prefer AWS SSO/federated roles over long-lived API Key when possible.
- [AWS IAM Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
2. **Enhance Network Security:**
- Consider setting up [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-services-overview.html) to securely connect to Bedrock.
3. **Monitor and Log Activity:**
- Enable AWS CloudTrail to log Bedrock API calls.
- Use CloudWatch to monitor metrics like invocation count, latency, and token usage.
- Set up alerts for abnormal activity.
4. **Handle Errors and Manage Costs:**
- Implement exponential backoff for throttling errors.
- Use AWS Cost Explorer and set billing alerts to track usage.\
[AWS Cost Management](https://docs.aws.amazon.com/cost-management/latest/userguide/what-is-aws-cost-management.html)
5. **Regular Audits and Compliance:**
- Periodically review IAM roles and CloudTrail logs.
- Follow internal data privacy and governance policies.
---
### Conclusion
By following these steps, your enterprise team can securely integrate AWS Bedrock with the Cline VS Code extension to accelerate development:
1. **Prepare Your AWS Environment:** Create or use a secure IAM role/user, attach the `AmazonBedrockLimitedAccess` policy, and ensure necessary permissions.
2. **Verify Region and Model Access:** Confirm that your selected region supports your required models.
3. **Configure Cline in VS Code:** Install and set up Cline with your AWS credentials and choose an appropriate model.
4. **Implement Security and Monitoring:** Use best practices for IAM, network security, monitoring, and cost management.
For further details, consult the [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) and coordinate with your internal cloud team. Happy coding!
---
_This guide will be updated as AWS Bedrock and Cline evolve. Always refer to the latest documentation and internal policies for up-to-date practices._
@@ -5,7 +5,7 @@ description: "Learn how to set up AWS Bedrock with Cline using credentials authe
### Overview
- **AWS Bedrock:** A fully managed service that offers access to leading generative AI models (e.g., Anthropic Claude, Amazon Titan) through AWS.\
- **AWS Bedrock:** A fully managed service that offers access to leading generative AI models (e.g., Anthropic Claude, Amazon Nova) through AWS.\
[Learn more about AWS Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html).
- **Cline:** A VS Code extension that acts as a coding assistant by integrating with AI models—empowering developers to generate code, debug, and analyze data.
- **Enterprise Focus:** This guide is tailored for organizations with established AWS environments (using IAM roles, AWS SSO, AWS Organizations, etc.) to ensure secure and compliant usage.
@@ -25,7 +25,7 @@ description: "Learn how to set up AWS Bedrock with Cline using credentials authe
#### 1.2 Attach the Required Policies
To ensure Cline can interact with AWS Bedrock, your IAM user or role needs specific permissions. While the `AmazonBedrockFullAccess` managed policy provides comprehensive access, for a more restricted and secure setup adhering to the principle of least privilege, the following minimal permissions are sufficient for Cline's core model invocation functionality:
To ensure Cline can interact with AWS Bedrock, your IAM user or role needs specific permissions. While the `AmazonBedrockLimitedAccess` managed policy provides comprehensive access, for a more restricted and secure setup adhering to the principle of least privilege, the following minimal permissions are sufficient for Cline's core model invocation functionality:
- `bedrock:InvokeModel`
- `bedrock:InvokeModelWithResponseStream`
@@ -52,8 +52,8 @@ You can create a custom IAM policy with these permissions and attach it to your
**Option 2: Using a Managed Policy (Simpler Initial Setup)**
- Alternatively, you can attach the AWS managed policy **`AmazonBedrockFullAccess`**. This grants broader permissions, including the ability to list models, manage provisioning, and other Bedrock features. This might be simpler for initial setup or if you require these wider capabilities.
[View AmazonBedrockFullAccess Policy Details](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html)
- Alternatively, you can attach the AWS managed policy **`AmazonBedrockLimitedAccess`**. This grants broader permissions, including the ability to list models, manage provisioning, and other Bedrock features. This might be simpler for initial setup or if you require these wider capabilities.
[View AmazonBedrockLimitedAccess Policy Details](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html)
**Important Considerations:**
@@ -71,8 +71,8 @@ You can create a custom IAM policy with these permissions and attach it to your
AWS Bedrock is available in multiple regions (e.g., US East, Europe, Asia Pacific). Choose the region that meets your latency and compliance needs.\
[AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)
2. **Verify Model Access:**
- In the AWS Bedrock console, confirm that the models your team requires (e.g., Anthropic Claude, Amazon Titan) are marked as "Access granted."
- **Note:** Some advanced models might require an [Inference Profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-prereq.html) if not available on-demand.
- In the AWS Bedrock console, confirm that the models your team requires (e.g., Anthropic Claude, Amazon Nova) are marked as "Access granted."
- **Note:** Some advanced models might require an [Inference Profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) if not available on-demand.
#### 2.2 Set Up AWS Marketplace Subscriptions (if needed)
@@ -138,7 +138,7 @@ You can create a custom IAM policy with these permissions and attach it to your
By following these steps, your enterprise team can securely integrate AWS Bedrock with the Cline VS Code extension to accelerate development:
1. **Prepare Your AWS Environment:** Create or use a secure IAM role/user, attach the `AmazonBedrockFullAccess` policy, and ensure necessary permissions.
1. **Prepare Your AWS Environment:** Create or use a secure IAM role/user, attach the `AmazonBedrockLimitedAccess` policy, and ensure necessary permissions.
2. **Verify Region and Model Access:** Confirm that your selected region supports your required models and subscribe via AWS Marketplace if needed.
3. **Configure Cline in VS Code:** Install and set up Cline with your AWS credentials and choose an appropriate model.
4. **Implement Security and Monitoring:** Use best practices for IAM, network security, monitoring, and cost management.
+93
View File
@@ -0,0 +1,93 @@
---
title: "Claude Code"
description: "Use your Claude Max or Pro subscription with Cline instead of paying per token. Learn how to set up and configure the Claude Code provider."
---
**Website:** [https://docs.anthropic.com/en/docs/claude-code/setup](https://docs.anthropic.com/en/docs/claude-code/setup)
The Claude Code provider lets you use your existing Claude subscription with Cline. If you have Claude Max or Pro, this means you can use Claude in Cline without paying extra API costs.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/claude-code-use-opus.gif"
alt="Using the Claude Code provider in Cline with Opus model"
/>
</Frame>
## Setup
First, you'll need to install and authenticate Claude Code on your system:
1. **Install Claude Code**: Follow Anthropic's [official setup guide](https://docs.anthropic.com/en/docs/claude-code/setup) to install and authenticate the Claude CLI.
2. **Configure in Cline**:
- Open Cline settings (⚙️ icon)
- Select **Claude Code** from the **API Provider** dropdown
- Set the path to your Claude CLI executable (usually just `claude` if it's in your PATH)
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/claude-code-setup.gif"
alt="Setting up the Claude Code provider in Cline"
/>
</Frame>
<br />
<Accordion title="Windows Setup">
Anthropic introduced full support for Claude Code on Windows. Follow the [instructions on how to set up Claude Code
normally](#setup) and make sure you have the latest Claude Code and Cline versions.
</Accordion>
### Finding your Claude Code path
If you're not sure where Claude Code is installed:
- **macOS / Linux**: Run `which claude` in your terminal
- **Windows (Command Prompt)**: Run `where claude`
- **Windows (PowerShell)**: Run `Get-Command claude`
## Supported Models
The Claude Code provider supports these models:
- `claude-sonnet-4-20250514` (Recommended)
- `claude-opus-4-20250514`
- `claude-3-7-sonnet-20250219`
- `claude-3-5-sonnet-20241022`
- `claude-3-5-haiku-20241022`
## How it works
When you use Claude Code with Cline, here's what happens behind the scenes:
Cline wraps the Claude Code CLI to handle your requests. Each time you send a message, Cline starts a new `claude` process, sends your conversation, and streams the response back. The AI reasoning comes from Claude Code, but all the actual file editing, terminal commands, and other tools are handled by Cline.
The main difference you'll notice is that responses don't stream character-by-character like other providers. Instead, Claude Code processes your full request before sending back the complete response.
## Limitations
There are a few things to keep in mind with Claude Code:
- Images in your messages get converted to text placeholders since Claude Code doesn't support image uploads through the CLI
- Prompt caching isn't available with this provider
- Responses don't stream in real-time like other providers
## Troubleshooting
If you run into issues:
**Authentication problems**: Make sure you're logged into Claude Code with your subscription account. Run `claude auth status` to check.
**Path issues**: Double-check that the Claude CLI path in Cline's settings is correct. Try running `claude --version` in your terminal to verify it's working.
**Still having trouble?** We're actively improving this integration. Report issues on our [GitHub](https://github.com/cline/cline/issues) or ask for help in our [Discord](https://discord.gg/cline).
## Usage with subscriptions
If you have a Claude Max subscription, your usage in Cline shows up as $0.00 in the billing interface since you're not paying additional API costs. Your usage still counts against your subscription limits, but you won't see per-token charges.
For more details about using Claude Code with your subscription, check out Anthropic's documentation:
- [Claude Code Setup Guide](https://docs.anthropic.com/en/docs/claude-code/setup)
- [Using Claude Code with Pro/Max Plans](https://support.anthropic.com/en/articles/11145838-using-claude-code-with-your-pro-or-max-plan)
+39
View File
@@ -0,0 +1,39 @@
---
title: "SAP AI Core"
description: "Learn how to configure and use LLM models from Generative AI Hub in SAP AI Core with Cline."
---
SAP AI Core and the generative AI hub help you to integrate LLMs and AI into new business processes in a cost-efficient manner.
**Website:** [SAP Help Portal](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/what-is-sap-ai-core)
### Getting a Service Binding
> 💡 **Information**
>
> SAP AI Core, and Generative AI Hub, are offerings from SAP BTP.
> You need an active SAP BTP contract and a existing subaccount with a SAP AI Core instance to perform these steps.
1. **Access:** Go to your subaccount via [BTP Cloud Cockpit](cockpit.btp.cloud.sap/cockpit)
2. **Create a Service Binding:** Go to "Instances and Subscriptions", select your SAP AI Core service instance and click on Service Bindings > Create.
3. **Copy the Service Binding:** Copy the service binding values.
### Supported Models
SAP AI Core supports a large and growing number of models.
Refer to the [Generative AI Hub Supported Models page](https://me.sap.com/notes/3437766) for the complete and up-to-date list.
### Configuration in Cline
1. **Open Cline Settings:** Click the settings icon (⚙️) in the Cline panel.
2. **Select Provider:** Choose "SAP AI Core" from the "API Provider" dropdown.
3. **Enter Client Id:** Add the `.clientid` field from the service binding into the "AI Core Client Id" field.
4. **Enter Client Secret:** Add the `.clientsecret` field from the service binding into the "AI Core Client Secret" field.
5. **Enter Base URL:** Add the `.serviceurls.AI_API_URL` field from the service binding into the "AI Core Base URL" field.
6. **Enter Auth URL:** Add the `.url` field from the service binding into the "AI Core Auth URL" field.
7. **Enter Resource Group:** Add the resource group where you have your model deployments. See [Create a Deployment for a Generative AI Model](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-deployment-for-generative-ai-model-in-sap-ai-core).
8. **Select Model:** Choose your desired model from the "Model" dropdown.
### Tips and Notes
- **Model Selection:** SAP AI Core offers a wide range of models. You won't be able to use the model, even if selected, if a deployment doesn't exist in the provided resource group.
@@ -0,0 +1,446 @@
---
title: "Terminal Integration Troubleshooting Guide"
sidebarTitle: "Terminal Troubleshooting"
description: "Complete guide to resolving terminal integration issues in Cline"
---
This guide helps you resolve terminal integration issues in Cline. Terminal integration is crucial for Cline to execute commands and read their output, enabling it to understand errors, test results, and command responses.
<Tip>
If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings, under "Terminal Settings"
This resolves most terminal integration problems.
</Tip>
## Quick Diagnosis Flowchart
Follow this flowchart to quickly identify your issue:
```mermaid
graph TD
A[Terminal Issue] --> B{Can Cline execute commands?}
B -->|No| C[Shell Integration Unavailable]
B -->|Yes| D{Can Cline see the output?}
D -->|No| E[Output Capture Failed]
D -->|Yes| F{Is the output corrupted?}
F -->|Yes| G[Character Filtering Issue]
F -->|No| H{Does the command hang?}
H -->|Yes| I[Long-Running Command Issue]
H -->|No| J[Check Terminal Settings]
C --> K[Try Solution 1]
E --> L[Try Solution 2]
G --> M[Try Solution 3]
I --> N[Try Solution 4]
style A fill:#f9f,stroke:#333,stroke-width:2px
style K fill:#9f9,stroke:#333,stroke-width:2px
style L fill:#9f9,stroke:#333,stroke-width:2px
style M fill:#9f9,stroke:#333,stroke-width:2px
style N fill:#9f9,stroke:#333,stroke-width:2px
```
## Common Issues & Quick Solutions
### 1. Shell Integration Unavailable
**Symptoms:**
- Message: "Shell Integration Unavailable"
- Commands execute but Cline can't read output
- Terminal works fine manually but not with Cline
**Quick Solutions:**
#### macOS
- **Switch to bash**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu
- **Disable Oh-My-Zsh temporarily**:
1. If using zsh, enter `mv ~/.zshrc ~/.zshrc.backup` into the terminal
2. Restart VSCode
- **Set environment**:
1.a For Zsh users, use one of the following Zsh commands to edit your shell profile:
- `nano ~/.zshrc`
- `vim ~/.zshrc`
- `code ~/.zshrc`
1.b For Bash users
- nano ~/.bash_profile
2. Add the following to your shell config: `export TERM=xterm-256color`
3. Save your configuration
#### Windows
- **Use PowerShell 7**
1. Install from Microsoft Store
2. Go to Cline Settings
3. Left-Click the **"Terminal Settings"** tab
4. Navigate to **"Default Terminal Profile"** and select **"PowerShell 7"** from the drop-down menu
- **Disable Windows ConPTY**
1. Navigate to your VSCode Settings
2. Enter "Integrated: Windows Enable Conpty" into the Settings searchbar
3. Uncheck the option
- **Try Command Prompt**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"Command Prompt"** from the drop-down menu
#### Linux
- **Use bash**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu
- **Check permissions**
1. Ensure VSCode has terminal access permissions
- **Disable custom prompts**
1. Comment out prompt customizations in `.bashrc`
### 2. Command Output Not Visible
**Symptoms:**
- Cline states in chat: "[Command is running but producing no output]"
- Commands complete but Cline doesn't see results
- Commands work sometimes but not consistently
**Solutions:**
- **Increase Shell Integration Timeout**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field
- **Disable Terminal Reuse**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option
- **Check for interfering extensions**
1. Disable other terminal-related VSCode extensions
### 3. Character Filtering Issues
**Symptoms:**
- Commas missing from output (JSON appears corrupted)
- Special characters stripped from terminal output
- Syntax errors that don't appear when running manually
**Solution:**
This is a known bug in output processing. Workarounds:
- Recommend AI to use file output instead
1. Tell Cline in chat or Cline rules, to use `command > output.txt` before reading the file/s
<Tip>
This family of issues is only partially solved in the latest Cline versions, so if you still face this, create a GitHub issue
if it is a persistent problem.
</Tip>
### 4. Long-Running Commands & Progress Bars
**Symptoms:**
- Docker builds never complete in Cline
- Progress bars consume thousands of tokens
- The Cline button "Proceed while running" doesn't work properly in chat
<Tip>
This family of issues has been solved in latest Cline versions but if you still face any issues, then create a GitHub issue
for this.
</Tip>
## Terminal Settings Explained
Access these in Cline by clicking the settings icon, and navigating to the "Terminal Settings" section:
### Default Terminal Profile
- **What it does**: Selects which shell Cline uses for commands
- **When to change**: If experiencing shell integration issues with your default shell
- **Recommended**: - macOS: bash (if zsh has issues) - Windows: PowerShell 7 - Linux: bash
### Shell Integration Timeout
- **What it does**: How long Cline waits for the terminal to be ready
- **Default**: 4 seconds
- **When to increase**:
- Slow shell startup (heavy .zshrc/.bashrc)
- WSL environments
- SSH connections
- **Recommended**: - Start with 10 seconds if having issues
### Enable Aggressive Terminal Reuse
- **What it does**: Reuses existing terminals even if not in the correct directory
- **When to disable**:
- Commands execute in wrong directory
- Virtual environment issues
- Terminal state corruption
- **Trade-off**: - Disabling creates more terminals but ensures clean state
### Terminal Output Line Limit
- **What it does**: Limits how many lines Cline reads from terminal output
- **Default**: 500 lines
- **When to adjust**:
- Increase for verbose build outputs
- Decrease if hitting token limits
- Set to 100 for commands with progress bars
## Platform-Specific Solutions
### macOS Issues
#### Oh-My-Zsh Conflicts
Oh-My-Zsh often interferes with shell integration. Solutions:
1. Create a minimal `.zshrc` for VSCode:
```bash
# ~/.zshrc-vscode
export TERM=xterm-256color
export PAGER=cat
# Minimal PATH and environment setup
```
2. Configure VSCode to use it:
```json
{
"terminal.integrated.env.osx": {
"ZDOTDIR": "~/.zshrc-vscode"
}
}
```
#### macOS 15+ Issues
Recent macOS versions have stricter terminal permissions:
1. System Preferences → Privacy & Security → Developer Tools
2. Add Visual Studio Code
3. Restart VSCode completely
### Windows Issues
If you're using Windows and still experiencing issues with shell integration after trying the previous steps, it's recommended you use Git Bash (or PowerShell).
### Git Bash
Git Bash is a terminal emulator that provides a Unix-like command line experience on Windows. To use Git Bash, you need to:
1. Download and run the Git for Windows installer from [https://git-scm.com/downloads/win](https://git-scm.com/downloads/win)
2. Quit and re-open VSCode
3. Press `Ctrl + Shift + P` to open the Command Palette
4. Type "Terminal: Select Default Profile" and choose it
5. Select "Git Bash"
### PowerShell
If you'd still like to use PowerShell, make sure you're using an updated version (at least v7+).
- Check your current PowerShell version by running: `$PSVersionTable.PSVersion`
- If your version is below 7, [update PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/whats-new/migrating-from-windows-powershell-51-to-powershell-7?view=powershell-7.4#installing-powershell-7).
You may also need to adjust your PowerShell execution policy. By default, PowerShell restricts script execution for security reasons.
#### Understanding PowerShell Execution Policies
PowerShell uses execution policies to determine which scripts can run on your system. Here are the most common policies:
- `Restricted`: No PowerShell scripts can run. This is the default setting.
- `AllSigned`: All scripts, including local ones, must be signed by a trusted publisher.
- `RemoteSigned`: Scripts created locally can run, but scripts downloaded from the internet must be signed.
- `Unrestricted`: No restrictions. Any script can run, though you will be warned before running internet-downloaded scripts.
For development work in VSCode, the `RemoteSigned` policy is generally recommended. It allows locally created scripts to run without restrictions while maintaining security for downloaded scripts. To learn more about PowerShell execution policies and understand the security implications of changing them, visit Microsoft's documentation: [About Execution Policies](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies).
#### Steps to Change the Execution Policy
1. Open PowerShell as an Administrator: Press `Win + X` and select "Windows PowerShell (Administrator)" or "Windows Terminal (Administrator)".
2. Check Current Execution Policy by running this command:
```powershell
Get-ExecutionPolicy
```
- If the output is already `RemoteSigned`, `Unrestricted`, or `Bypass`, you likely don't need to change your execution policy. These policies should allow shell integration to work.
- If the output is `Restricted` or `AllSigned`, you may need to change your policy to enable shell integration.
3. Change the Execution Policy by running the following command:
```powershell
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
```
- This sets the policy to `RemoteSigned` for the current user only, which is safer than changing it system-wide.
4. Confirm the Change by typing `Y` and pressing Enter when prompted.
5. Verify the Policy Change by running `Get-ExecutionPolicy` again to confirm the new setting.
6. Restart VSCode and try the shell integration again.
#### WSL Integration
For WSL issues:
1. Use WSL extension for VSCode
2. Open folder in WSL: `code .` from WSL terminal
3. Select "WSL Bash" as terminal profile in Cline
#### Path Issues
Windows path problems:
1. Use forward slashes in Cline: `C:/Users/...`
2. Quote paths with spaces: `"C:/Program Files/..."`
3. Avoid `~` - use full paths
### Linux/SSH/Container Issues
#### SSH Connections
For remote development:
1. Install Cline on the remote machine, not locally
2. Use SSH extension's integrated terminal
3. Increase timeout to 15+ seconds
#### Docker Containers
When developing in containers:
1. Install Cline in the container
2. Use Dev Containers extension
3. Ensure shell integration scripts are available
## Shell-Specific Fixes
### Zsh
```bash
# Add to ~/.zshrc
export TERM=xterm-256color
export PAGER=cat
# Disable fancy prompts for VSCode
if [[ "$TERM_PROGRAM" == "vscode" ]]; then
PS1="%n@%m %1~ %# "
fi
```
### Bash
```bash
# Add to ~/.bashrc
export TERM=xterm-256color
export PAGER=cat
# Simple prompt for VSCode
if [[ "$TERM_PROGRAM" == "vscode" ]]; then
PS1='\u@\h:\w\$ '
fi
```
### Fish
```fish
# Add to ~/.config/fish/config.fish
set -x TERM xterm-256color
set -x PAGER cat
# Disable fancy features in VSCode
if test "$TERM_PROGRAM" = "vscode"
function fish_prompt
echo (whoami)'@'(hostname)':'(pwd)'> '
end
end
```
### PowerShell
```powershell
# Add to $PROFILE
$env:PAGER = "cat"
# Disable progress bars
$ProgressPreference = 'SilentlyContinue'
```
## Advanced Troubleshooting
### Debug Mode
Enable terminal debugging to see what's happening:
1. Open VSCode Command Palette (Cmd/Ctrl+Shift+P)
2. Run: "Developer: Set Log Level..."
3. Choose "Trace"
4. Check Output panel → "Cline" for terminal logs
### Manual Shell Integration Test
Test if shell integration works at all:
```bash
# In VSCode terminal
echo $TERM_PROGRAM # Should show "vscode"
echo $VSCODE_SHELL_INTEGRATION # Should be "1"
```
## FAQ
### Why does Cline create so many terminals?
When shell integration fails, Cline can't reuse terminals safely (they might be running long processes). Enable shell integration or adjust the terminal reuse setting.
### Can I use my custom shell (nushell, xonsh, etc.)?
Cline officially supports bash, zsh, fish, and PowerShell. Custom shells may work but aren't guaranteed. Use bash as a fallback.
### Why do some commands work but others don't?
Commands that use interactive features (pagers, progress bars, curses) often fail. Set `PAGER=cat` and use non-interactive flags.
### How do I know if shell integration is working?
Working integration shows command output in Cline's chat. Failed integration shows "Shell Integration Unavailable" or "[Command is running but producing no output]".
## Still Having Issues?
If you've tried everything:
1. **Collect Debug Info**:
```bash
echo "Shell: $SHELL"
echo "Term: $TERM"
echo "VSCode: $TERM_PROGRAM"
which bash
bash --version
```
2. **Report the Issue**:
- Use `/reportbug` in Cline github issues
- Include your debug info
- Mention which solutions you tried
<Tip>
Remember: Most terminal issues are resolved by switching to bash and increasing the timeout. Start there before trying complex
solutions.
</Tip>
@@ -0,0 +1,51 @@
---
title: "Terminal Quick Fixes"
sidebarTitle: "Terminal Quick Fixes"
description: "Quick solutions for common terminal issues"
---
**Here is a list of common fixes, starting with the most applicable:**
- **Switch to bash** (solves most instances)
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down
- **Increase timeout**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field
- **Disable terminal reuse**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option
## Platform-Specific Fixes
### macOS + Oh-My-Zsh
```bash
# Create minimal config for VSCode
echo 'export TERM=xterm-256color' > ~/.zshrc-vscode
echo 'export PAGER=cat' >> ~/.zshrc-vscode
```
### Windows PowerShell
```powershell
# Run as Administrator
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
### WSL
- Open folder from WSL: `code .`
- Select **"WSL Bash"** in Cline settings, under **"Terminal Settings"**
- Increase **"Shell integration timeout (seconds)"** to **15**
## Full Guide
For detailed troubleshooting, see the [Complete Terminal Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
+27 -9
View File
@@ -1,10 +1,15 @@
const esbuild = require("esbuild")
const fs = require("fs")
const path = require("path")
import fs from "node:fs"
import * as esbuild from "esbuild"
import path from "node:path"
import { fileURLToPath } from "node:url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const production = process.argv.includes("--production")
const watch = process.argv.includes("--watch")
const standalone = process.argv.includes("--standalone")
const e2eBuild = process.argv.includes("--e2e-build")
const destDir = standalone ? "dist-standalone" : "dist"
/**
@@ -125,9 +130,9 @@ const baseConfig = {
minify: production,
sourcemap: !production,
logLevel: "silent",
define: {
"process.env.IS_DEV": JSON.stringify(!production),
},
define: production
? { "import.meta.url": "_importMetaUrl", "process.env.IS_DEV": JSON.stringify(!production) }
: { "import.meta.url": "_importMetaUrl" },
tsconfig: path.resolve(__dirname, "tsconfig.json"),
plugins: [
copyWasmFiles,
@@ -138,6 +143,9 @@ const baseConfig = {
format: "cjs",
sourcesContent: false,
platform: "node",
banner: {
js: "const _importMetaUrl=require('url').pathToFileURL(__filename)",
},
}
// Extension-specific configuration
@@ -151,15 +159,25 @@ const extensionConfig = {
// Standalone-specific configuration
const standaloneConfig = {
...baseConfig,
entryPoints: ["src/standalone/standalone.ts"],
outfile: `${destDir}/standalone.js`,
entryPoints: ["src/standalone/cline-core.ts"],
outfile: `${destDir}/cline-core.js`,
// These gRPC protos need to load files from the module directory at runtime,
// so they cannot be bundled.
external: ["vscode", "@grpc/reflection", "grpc-health-check"],
}
// E2E build script configuration
const e2eBuildConfig = {
...baseConfig,
entryPoints: ["src/test/e2e/utils/build.ts"],
outfile: `${destDir}/e2e-build.js`,
external: ["@vscode/test-electron", "execa"],
sourcemap: false,
plugins: [aliasResolverPlugin, esbuildProblemMatcherPlugin],
}
async function main() {
const config = standalone ? standaloneConfig : extensionConfig
const config = standalone ? standaloneConfig : e2eBuild ? e2eBuildConfig : extensionConfig
const extensionCtx = await esbuild.context(config)
if (watch) {
await extensionCtx.watch()
@@ -0,0 +1,123 @@
const { RuleTester: DirectApiRuleTester } = require("eslint")
const noDirectVscodeApiRule = require("../no-direct-vscode-api")
const directApiRuleTester = new DirectApiRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, {
valid: [
// Should allow vscode.postMessage in grpc-client-base.ts
{
code: `vscode.postMessage({ type: "grpc_request", data: {} })`,
filename: "grpc-client-base.ts",
},
{
code: `vscode.postMessage({ type: "grpc_request_cancel" })`,
filename: "/path/to/grpc-client-base.ts",
},
// Should allow in exception directories
{
code: `vscode.workspace.workspaceFolders`,
filename: "/src/hosts/vscode/host-bridge.ts",
},
{
code: `vscode.workspace.fs.stat(uri)`,
filename: "/standalone/runtime-files/helpers.ts",
},
// Should allow other vscode API calls
{
code: `vscode.window.showInformationMessage("Hello")`,
filename: "test.ts",
},
// Should allow postMessage calls on other objects
{
code: `window.postMessage({ type: "test" }, "*")`,
filename: "test.ts",
},
// Should allow variables named vscode but not calling postMessage
{
code: `const vscode = { other: "method" }; vscode.other()`,
filename: "test.ts",
},
],
invalid: [
// Should disallow vscode.postMessage in regular files
{
code: `vscode.postMessage({ type: "test", data: {} })`,
filename: "test.ts",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow vscode.postMessage in components
{
code: `vscode.postMessage({ type: "apiConfiguration", apiConfiguration })`,
filename: "ApiOptions.tsx",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow vscode.postMessage in test files
{
code: `vscode.postMessage({ type: "newTask", text: message.text })`,
filename: "test.test.ts",
errors: [
{
messageId: "useGrpcClient",
},
],
},
// Should disallow property access for disallowed APIs
{
code: `const folders = vscode.workspace.workspaceFolders;`,
filename: "workspace.ts",
errors: [
{
messageId: "useHostBridge",
},
],
},
// Should disallow method calls for disallowed APIs
{
code: `const relativePath = vscode.workspace.asRelativePath(filePath);`,
filename: "path-utils.ts",
errors: [
{
messageId: "usePathUtils",
},
],
},
// Should disallow nested property access
{
code: `const stats = await vscode.workspace.fs.stat(uri);`,
filename: "file-utils.ts",
errors: [
{
messageId: "useFsUtils",
},
],
},
// Should disallow getting a workspace folder
{
code: `const folder = vscode.workspace.getWorkspaceFolder(uri);`,
filename: "path-helper.ts",
errors: [
{
messageId: "usePathUtils",
},
],
},
],
})
@@ -1,174 +0,0 @@
const { RuleTester: GrpcRuleTester } = require("eslint")
const grpcRule = require("../no-grpc-client-object-literals")
const grpcRuleTester = new GrpcRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
grpcRuleTester.run("no-grpc-client-object-literals", grpcRule, {
valid: [
// Valid case: Using .create() method with gRPC client
{
code: `
import { TogglePlanActModeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: {
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
},
})
);
`,
},
// Valid case: Using .fromPartial() method with gRPC client
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.fromPartial({
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: chatSettings,
})
);
`,
},
// Valid case: Regular function call with object literal (not a gRPC client)
{
code: `
function processData(data) {
console.log(data);
}
processData({
id: 123,
name: 'test',
});
`,
},
// Valid case: Using proper nested protobuf objects
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using proper nested protobuf objects
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
const request = TogglePlanActModeRequest.create({
chatSettings: chatSettings,
});
StateServiceClient.togglePlanActMode(request);
`,
},
// Valid case: Object literal in second parameter (should not be checked)
{
code: `
import { StateSubscribeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const request = StateSubscribeRequest.create({
topics: ['apiConfig', 'tasks']
});
// Second parameter is an object literal but should not trigger the rule
StateServiceClient.subscribe(request, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
},
],
invalid: [
// Invalid case: Using object literal directly with gRPC client
{
code: `
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal with nested properties
{
code: `
import { ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 1,
preferredLanguage: 'fr',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Nested object literal in protobuf create method
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using nested object literal instead of ChatSettings.create()
const request = TogglePlanActModeRequest.create({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
StateServiceClient.togglePlanActMode(request);
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Object literal as first parameter to subscribe method
{
code: `
import { StateServiceClient } from '../services/grpc-client';
// First parameter is an object literal, which should trigger the rule
StateServiceClient.subscribe({
topics: ['apiConfig', 'tasks']
}, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
],
})
@@ -1,214 +0,0 @@
const { RuleTester } = require("eslint")
const rule = require("../no-protobuf-object-literals")
const ruleTester = new RuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
ruleTester.run("no-protobuf-object-literals", rule, {
valid: [
// Valid case: Using .create() method
{
code: `
import { State } from '@shared/proto/state';
const state = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
},
// Valid case: Using .fromPartial() method
{
code: `
import { ChatSettings } from '@shared/proto/state';
const settings = ChatSettings.fromPartial({
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
});
`,
},
// Valid case: Object literal not used with protobuf type
{
code: `
interface MyInterface {
id: number;
name: string;
}
const obj: MyInterface = {
id: 123,
name: 'test'
};
`,
},
// Valid case: Using object literal for non-protobuf import
{
code: `
import { SomeType } from '@some/other/package';
const obj: SomeType = {
id: 123,
name: 'test'
};
`,
},
// Valid case: Regular function call with object literal (should not be flagged)
{
code: `
import { State } from '@shared/proto/state';
// This should not be flagged because it's a regular function call
// not directly tied to a protobuf type
process({
id: 123,
name: 'test',
data: { nested: true }
});
`,
},
],
invalid: [
// Invalid case: Using object literal with imported protobuf type
{
code: `
import { State } from '@shared/proto/state';
const state: State = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import { State } from '@shared/proto/state';
const state: State = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal with namespaced protobuf type
{
code: `
import * as stateProto from '@shared/proto/state';
const state: stateProto.State = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import * as stateProto from '@shared/proto/state';
const state: stateProto.State = stateProto.State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethodGeneric" }],
},
// Invalid case: Using object literal in a return statement (with protobuf return type)
{
code: `
import { ChatSettings } from '@shared/proto/state';
function createSettings(): ChatSettings {
return {
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
};
}
`,
output: `
import { ChatSettings } from '@shared/proto/state';
function createSettings(): ChatSettings {
return ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
});
}
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal in a function parameter (with protobuf types imported)
{
code: `
import { ChatContent } from '@shared/proto/state';
function processContent(content: ChatContent) {
// process the content
}
processContent({
message: 'Hello, this is a test message',
images: ['image1.png', 'image2.jpg'],
files: ['file1.txt', 'file2.pdf']
});
`,
output: `
import { ChatContent } from '@shared/proto/state';
function processContent(content: ChatContent) {
// process the content
}
processContent(ChatContent.create({
message: 'Hello, this is a test message',
images: ['image1.png', 'image2.jpg'],
files: ['file1.txt', 'file2.pdf']
}));
`,
errors: [{ messageId: "useProtobufMethodGeneric" }],
},
// Invalid case: Using object literal in assignment expression
{
code: `
import { State } from '@shared/proto/state';
let state: State;
state = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import { State } from '@shared/proto/state';
let state: State;
state = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Test with custom protobufPackages option
{
code: `
import { CustomProto } from 'custom/proto/package';
const obj: CustomProto = {
field1: 'value',
field2: 123
};
`,
output: `
import { CustomProto } from 'custom/proto/package';
const obj: CustomProto = CustomProto.create({
field1: 'value',
field2: 123
});
`,
options: [{ protobufPackages: ["custom/proto"] }],
errors: [{ messageId: "useProtobufMethod" }],
},
],
})
+3 -6
View File
@@ -1,18 +1,15 @@
// eslint-rules/index.js
const noProtobufObjectLiterals = require("./no-protobuf-object-literals")
const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals")
const noDirectVscodeApi = require("./no-direct-vscode-api")
module.exports = {
rules: {
"no-protobuf-object-literals": noProtobufObjectLiterals,
"no-grpc-client-object-literals": noGrpcClientObjectLiterals,
"no-direct-vscode-api": noDirectVscodeApi,
},
configs: {
recommended: {
plugins: ["local"],
rules: {
"local/no-protobuf-object-literals": "error",
"local/no-grpc-client-object-literals": "error",
"local/no-direct-vscode-api": "warn",
},
},
},
+214
View File
@@ -0,0 +1,214 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const path = require("path")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
// Configuration of disallowed VSCode APIs and their recommended alternatives
const disallowedApis = {
"vscode.postMessage": {
messageId: "useGrpcClient",
},
"vscode.workspace.fs.stat": {
messageId: "useFsUtils",
},
"vscode.workspace.fs.writeFile": {
messageId: "useFsUtils",
},
"vscode.workspace.workspaceFolders": {
messageId: "useHostBridgeWorkspace",
},
"vscode.workspace.asRelativePath": {
messageId: "usePathUtils",
},
"vscode.workspace.getWorkspaceFolder": {
messageId: "usePathUtils",
},
"vscode.window.showTextDocument": {
messageId: "useHostBridge",
},
"vscode.workspace.applyEdit": {
messageId: "useHostBridge",
},
"vscode.window.onDidChangeActiveTextEditor": {
messageId: "useHostBridge",
},
"vscode.env.openExternal": {
messageId: "useUtils",
},
// "vscode.window.showWarningMessage": {
// messageId: "useHostBridgeShowMessage",
// },
"vscode.window.showOpenDialog": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showErrorMessage": {
messageId: "useHostBridgeShowMessage",
},
// "vscode.window.showInformationMessage": {
// messageId: "useHostBridgeShowMessage",
// },
}
module.exports = createRule({
name: "no-direct-vscode-api",
meta: {
type: "problem",
docs: {
description:
"Disallow direct VSCode API usage in favor of Cline's abstraction layers, except in src/hosts/vscode and standalone/runtime-files directories",
recommended: "error",
},
messages: {
useGrpcClient:
"Use gRPC service clients instead of vscode.postMessage().\n" +
"Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).\n" +
"Found: {{code}}",
useFsUtils:
"Use utilities in @/utils/fs instead of vscode.workspace.fs\n" +
"Example: import { isDirectory } from '@/utils/fs' or use the file system methods from the host bridge provider.\n" +
"Found: {{code}}",
usePathUtils:
"Use path utilities from @/utils/path instead of VSCode workspace path methods.\n" +
"This provides consistent path handling across different environments.\n" +
"Found: {{code}}",
useHostBridgeWorkspace:
"Use HostProvider.workspace.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useHostBridgeShowMessage:
"Use HostProvider.window.showMessage instead of the vscode.window.showMessage.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useHostBridge:
"Use the host bridge instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useUtils:
"Use utilities in @/utils instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
},
schema: [],
},
defaultOptions: [],
create(context) {
// Pattern for checking memberExpressions like vscode.workspace.fs.stat
function checkMemberExpression(node) {
if (isExcluded(context.filename)) {
// Skip if this file is being excluded.
return
}
// For handling nested properties like vscode.workspace.fs.stat
function getFullPropertyPath(node) {
if (node.type !== "MemberExpression") {
return node.name || ""
}
const objectPart = getFullPropertyPath(node.object)
const propertyPart = node.property.name || ""
return objectPart ? `${objectPart}.${propertyPart}` : propertyPart
}
// Check if the expression matches one of our disallowed patterns
if (node.object && node.object.type === "Identifier" && node.object.name === "vscode") {
const fullPath = `vscode.${node.property.name}`
checkDisallowedApi(fullPath, node)
}
// Handle nested expressions like vscode.workspace.fs.stat
else if (node.object && node.object.type === "MemberExpression") {
const fullPath = getFullPropertyPath(node)
// Only proceed if it starts with vscode
if (fullPath.startsWith("vscode.")) {
checkDisallowedApi(fullPath, node)
}
}
}
// Check if an expression matches a disallowed API and report if it does
function checkDisallowedApi(expressionPath, node) {
// Check exact matches
if (disallowedApis[expressionPath]) {
reportViolation(expressionPath, node)
return
}
// Check prefix matches (for nested properties)
for (const disallowedApi in disallowedApis) {
// For direct property access like vscode.workspace.workspaceFolders
if (expressionPath === disallowedApi) {
reportViolation(disallowedApi, node)
return
}
// For method calls like vscode.workspace.asRelativePath(...)
if (expressionPath.startsWith(`${disallowedApi}.`) || expressionPath.startsWith(`${disallowedApi}(`)) {
reportViolation(disallowedApi, node)
return
}
}
}
// Report a violation with the appropriate message
function reportViolation(disallowedApi, node) {
const sourceCode = context.sourceCode
const config = disallowedApis[disallowedApi]
// For method calls, get the whole call expression
let reportNode = node
let parentNode = sourceCode.getAncestors(node).pop()
if (parentNode && parentNode.type === "CallExpression" && parentNode.callee === node) {
reportNode = parentNode
}
const callText = sourceCode.getText(reportNode).trim()
context.report({
node: reportNode,
messageId: config.messageId,
data: {
code: callText,
},
})
}
function isExcluded(filename) {
// Check if current file is in an exception directory or is grpc-client-base.ts
if (path.basename(filename) === "grpc-client-base.ts") {
return true
}
// Skip checking files in src/hosts/vscode or standalone/runtime-files
if (filename.includes("/src/hosts/vscode/")) {
return true
}
if (filename.includes("/standalone/runtime-files/")) {
return true
}
// Skip unit tests
if (filename.endsWith(".test.ts")) {
return true
}
}
return {
// Detect basic member expressions (e.g., vscode.postMessage)
MemberExpression(node) {
checkMemberExpression(node)
},
// Detect property access through destructuring
VariableDeclarator(node) {
// Skip if this file is in an exception directory or is grpc-client-base.ts
if (isExcluded(context.filename)) {
return
}
// Destructuring pattern checks removed as developers don't use the API this way
// They always use direct imports: import * as vscode from "vscode" and direct access: vscode.thing.foo
},
}
},
})
@@ -1,216 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
module.exports = createRule({
name: "no-grpc-client-object-literals",
meta: {
type: "problem",
docs: {
description:
"Enforce using .create() or .fromPartial() for gRPC service client parameters instead of object literals",
recommended: "error",
},
messages: {
useProtobufMethod:
"Use the appropriate protobuf .create() or .fromPartial() method instead of " +
"object literal for gRPC client parameters.\n" +
"Found: {{code}}\n" +
"gRPC client methods should always receive properly created protobuf objects.",
},
schema: [],
},
defaultOptions: [],
create(context) {
// Check if a name matches the gRPC service client pattern using regex
// Must start with an uppercase letter and end with ServiceClient
const isGrpcServiceClient = (name) => {
return typeof name === "string" && /^[A-Z].*ServiceClient$/.test(name)
}
const safeObjectExpressions = new Map() // Track object expressions in create/fromPartial calls
return {
// Skip object literals inside create() or fromPartial() method calls
CallExpression(node) {
if (
node.callee &&
node.callee.type === "MemberExpression" &&
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
node.arguments.length > 0 &&
node.arguments[0].type === "ObjectExpression"
) {
// Track this object expression as being used with create/fromPartial
safeObjectExpressions.set(node.arguments[0], { isProblematic: false })
}
},
// Track create/fromPartial calls that contain nested object literals
"CallExpression[callee.type='MemberExpression'][callee.property.name=/^(create|fromPartial)$/]"(node) {
if (node.arguments.length > 0 && node.arguments[0].type === "ObjectExpression") {
// Track problematic nested object literals
const nestedObjectLiterals = new Map() // Map of object expressions to their containing property paths
// Search for nested object literals
const queue = [
...node.arguments[0].properties.map((prop) => ({
property: prop,
path: prop.key && prop.key.name ? prop.key.name : "unknown",
})),
]
while (queue.length > 0) {
const { property, path } = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// If this is an object literal, mark it as problematic
if (property.value.type === "ObjectExpression") {
nestedObjectLiterals.set(property.value, path)
// Add nested properties to queue
queue.push(
...property.value.properties.map((prop) => ({
property: prop,
path: `${path}.${prop.key && prop.key.name ? prop.key.name : "unknown"}`,
})),
)
}
}
// For each problematic nested object, track it with its path
nestedObjectLiterals.forEach((path, objectExpr) => {
safeObjectExpressions.set(objectExpr, {
isProblematic: true,
path: path,
parentNode: node,
})
})
}
},
// Check calls to gRPC service clients
"CallExpression[callee.type='MemberExpression']"(node) {
// Get the object (left side) of the member expression
const callee = node.callee
if (callee.object && callee.object.type === "Identifier") {
const objectName = callee.object.name
// Check if this is a call to one of our gRPC service clients
if (isGrpcServiceClient(objectName)) {
// Only check the first argument of gRPC service client calls
if (node.arguments.length > 0) {
const arg = node.arguments[0] // Only check the first parameter
if (arg.type === "ObjectExpression" && !safeObjectExpressions.has(arg)) {
// This is an object literal being passed directly to a gRPC client
const sourceCode = context.getSourceCode()
const callText = sourceCode.getText(node).trim()
context.report({
node: arg,
messageId: "useProtobufMethod",
data: {
code: callText,
},
})
} else if (arg.type === "ObjectExpression") {
// Search for nested object literals that aren't protected
const queue = [...arg.properties]
while (queue.length > 0) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// Check value
if (
property.value.type === "ObjectExpression" &&
!safeObjectExpressions.has(property.value)
) {
// Found a nested object literal
const sourceCode = context.getSourceCode()
const propertyText = sourceCode.getText(property).trim()
context.report({
node: property.value,
messageId: "useProtobufMethod",
data: {
code: `${objectName}.${callee.property.name}(... ${propertyText} ...)`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
} else if (arg.type === "Identifier") {
// This is a variable - check if it references a problematic protobuf object
const varName = arg.name
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
// Find the variable declaration
const variable = scope.variables.find((v) => v.name === varName)
if (variable && variable.references && variable.references.length > 0) {
// Look for definitions
const def = variable.defs.find(
(d) => d.node && d.node.type === "VariableDeclarator" && d.node.init,
)
if (
def &&
def.node.init.type === "CallExpression" &&
def.node.init.callee.type === "MemberExpression" &&
(def.node.init.callee.property.name === "create" ||
def.node.init.callee.property.name === "fromPartial")
) {
// Flag if we find problematic nested object literals in this create/fromPartial call
const callText = sourceCode.getText(node).trim()
const initCallText = sourceCode.getText(def.node.init).trim()
// Check for nested object literals in init node
let foundNestedLiteral = false
if (
def.node.init.arguments.length > 0 &&
def.node.init.arguments[0].type === "ObjectExpression"
) {
// Find any nested object literals
const queue = [...def.node.init.arguments[0].properties]
while (queue.length > 0 && !foundNestedLiteral) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
if (property.value.type === "ObjectExpression") {
foundNestedLiteral = true
context.report({
node,
messageId: "useProtobufMethod",
data: {
code: `${callText} - using request created with nested object literal at: ${property.key.name}`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
}
}
}
}
}
}
}
},
}
},
})
-556
View File
@@ -1,556 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
module.exports = createRule({
name: "no-protobuf-object-literals",
meta: {
type: "problem",
docs: {
description: "Enforce using .create() or .fromPartial() for protobuf objects instead of object literals",
recommended: "error",
},
fixable: "code",
messages: {
useProtobufMethod:
"Use {{typeName}}.create() or {{typeName}}.fromPartial() instead of " +
"object literal for protobuf type from @shared/proto\n" +
"Found: {{code}}\n Suggestion: " +
"{{typeName}}.create({{objectContent}})",
useProtobufMethodGeneric:
"Use .create() or .fromPartial() instead of object literal for protobuf " +
"type from @shared/proto\n Found: {{code}}",
},
schema: [
{
type: "object",
properties: {
protobufPackages: {
type: "array",
items: { type: "string" },
default: ["shared/proto/"],
},
},
additionalProperties: false,
},
],
},
defaultOptions: [{ protobufPackages: ["shared/proto/"] }],
create(context, [options]) {
const protobufPackages = options.protobufPackages
const protobufImports = new Set() // Set of imported protobuf types
const protobufNamespaceImports = new Set() // For namespace imports like "import * as proto"
const safeObjectExpressions = new Set() // Track object expressions in create/fromPartial calls
return {
// Skip object literals inside create() or fromPartial() method calls
CallExpression(node) {
if (
node.callee &&
node.callee.type === "MemberExpression" &&
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
node.arguments.length > 0 &&
node.arguments[0].type === "ObjectExpression"
) {
// Track this object expression as being used with create/fromPartial
safeObjectExpressions.add(node.arguments[0])
}
},
// Track imports from protobuf packages
ImportDeclaration(node) {
const packageName = node.source.value
if (matchesProtobufPackage(packageName, protobufPackages)) {
// This is a protobuf package.
node.specifiers.forEach((spec) => {
if (spec.type === "ImportSpecifier") {
// import { MyRequest } from '@shared/proto'
protobufImports.add(spec.imported.name)
} else if (spec.type === "ImportNamespaceSpecifier") {
// import * as proto from '@shared/proto'
protobufNamespaceImports.add(spec.local.name)
}
})
}
},
// Check variable declarations with type annotations
"VariableDeclarator > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// Found object literal in variable declaration
const declarator = node.parent
if (declarator.id && declarator.id.typeAnnotation) {
const typeName = getTypeName(declarator.id.typeAnnotation.typeAnnotation)
if (typeName) {
// Check if it's a direct protobuf import
if (protobufImports.has(typeName)) {
//console.log('🚨 VIOLATION: Using object literal for protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const declaratorText = sourceCode.getText(declarator)
const objectText = sourceCode.getText(node)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName,
code: declaratorText,
objectContent: objectText,
},
fix(fixer) {
// Replace the object literal with Type.create() call
return fixer.replaceText(node, `${typeName}.create(${objectText})`)
},
})
return
}
// Check if it's a namespaced protobuf type (e.g., proto.MyRequest)
if (isNamespacedProtobufType(protobufNamespaceImports, typeName)) {
//console.log('🚨 VIOLATION: Using object literal for namespaced protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const declaratorText = sourceCode.getText(declarator)
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: declaratorText },
fix(fixer) {
// For namespaced types, use the full type name to call create()
return fixer.replaceText(node, `${typeName}.create(${sourceCode.getText(node)})`)
},
})
}
}
}
},
// Check assignment expressions
"AssignmentExpression > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
const assignment = node.parent
// For assignment to variables without inline type annotation
if (assignment.left && assignment.right === node) {
let typeName = null
// Check if there's a typeAnnotation directly on the left
if (assignment.left.typeAnnotation) {
typeName = getTypeName(assignment.left.typeAnnotation.typeAnnotation)
}
// Otherwise try to infer from the variable name if it's a simple identifier
else if (assignment.left.type === "Identifier") {
const varName = assignment.left.name
// Check variable declarations in the current scope
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
const variable = scope.variables.find((v) => v.name === varName)
if (variable && variable.defs.length > 0) {
const def = variable.defs[0]
if (def.node.id && def.node.id.typeAnnotation) {
typeName = getTypeName(def.node.id.typeAnnotation.typeAnnotation)
}
}
}
if (typeName && protobufImports.has(typeName)) {
//console.log('🚨 VIOLATION: Using object literal in assignment for protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const assignmentText = sourceCode.getText(assignment.left) + " = "
const objectText = sourceCode.getText(node)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName,
code: assignmentText + "{",
objectContent: objectText,
},
fix(fixer) {
// Replace the object literal with Type.create() call in assignments
return fixer.replaceText(node, `${typeName}.create(${objectText})`)
},
})
}
}
},
// Check return statements
"ReturnStatement > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// Find the parent function to get its return type
const functionNode = findParentFunction(node)
if (!functionNode) {
return
}
// Try to get the return type using our enhanced helper
const sourceCode = context.getSourceCode()
let returnTypeName = getFunctionReturnType(functionNode, sourceCode)
// For async functions with Promise<Type> return type, extract the inner type
if (returnTypeName && returnTypeName.startsWith("Promise<") && returnTypeName.endsWith(">")) {
returnTypeName = returnTypeName.slice(8, -1)
}
// Check if the return type is a protobuf type
if (returnTypeName) {
if (protobufImports.has(returnTypeName)) {
//console.log('🚨 VIOLATION: Return type is a protobuf type:', returnTypeName);
const sourceCode = context.getSourceCode()
const returnText = sourceCode.getText(node.parent)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName: returnTypeName,
code: returnText,
objectContent: sourceCode.getText(node),
},
fix(fixer) {
// Replace the object literal with Type.create() call in return statements
return fixer.replaceText(node, `${returnTypeName}.create(${sourceCode.getText(node)})`)
},
})
return
}
// Check if it's a namespaced protobuf type
if (isNamespacedProtobufType(protobufNamespaceImports, returnTypeName)) {
const sourceCode = context.getSourceCode()
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Return type is a namespaced protobuf type:', returnTypeName);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: returnText },
fix(fixer) {
// For namespaced types in return statements, we need to extract the full type name
const objectCode = sourceCode.getText(node)
// Since we may not know the exact type, we'll use the more generic namespaced type
return fixer.replaceText(node, `${returnTypeName}.create(${objectCode})`)
},
})
return
}
}
// Final fallback - if there are any protobuf imports and the function signature
// mentions a return type that matches one of the imported types
const functionText = functionNode ? sourceCode.getText(functionNode) : ""
for (const protoType of protobufImports) {
// Use more precise regex to match return type patterns specifically
// Rather than just checking if the type name appears anywhere in the signature
const returnTypeRegex = new RegExp(
// Match arrow function return type
`=>\\s*:?\\s*${protoType}\\b|` +
// Match function declaration return type
`\\)\\s*:?\\s*${protoType}\\b|` +
// Match Promise return type
`\\)\\s*:?\\s*Promise<\\s*${protoType}\\s*>|` +
// Match function type in variable declaration
`:\\s*\\(.*\\)\\s*=>\\s*${protoType}\\b`,
)
if (returnTypeRegex.test(functionText)) {
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: regex matched protobuf type:', functionText);
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName: protoType,
code: returnText,
objectContent: sourceCode.getText(node),
},
fix(fixer) {
// Replace the object literal with Type.create() call
return fixer.replaceText(node, `${protoType}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
// Check for namespace imports too
for (const namespace of protobufNamespaceImports) {
// Similar to above, but for namespaced types
const namespaceReturnTypeRegex = new RegExp(
// Match arrow function return type
`=>\\s*:?\\s*${namespace}\\.\\w+\\b|` +
// Match function declaration return type
`\\)\\s*:?\\s*${namespace}\\.\\w+\\b|` +
// Match Promise return type
`\\)\\s*:?\\s*Promise<\\s*${namespace}\\.\\w+\\s*>|` +
// Match function type in variable declaration
`:\\s*\\(.*\\)\\s*=>\\s*${namespace}\\.\\w+\\b`,
)
if (namespaceReturnTypeRegex.test(functionText)) {
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: regex matched namespaced protobuf type:', functionText, "namespace:", namespace);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: returnText },
fix(fixer) {
// For namespaced types based on function signature patterns
// Extract the namespace and type from the function text using more precise patterns
const match = functionText.match(
new RegExp(
// Match return type patterns more precisely
`\\)\\s*:?\\s*(${namespace}\\.[\\w]+)\\b|` + // Function declaration
`=>\\s*:?\\s*(${namespace}\\.[\\w]+)\\b|` + // Arrow function
`Promise<\\s*(${namespace}\\.[\\w]+)\\s*>`, // Promise wrapped
),
)
if (match) {
const fullType = match[1] || match[2]
return fixer.replaceText(node, `${fullType}.create(${sourceCode.getText(node)})`)
}
// Fallback - we can't determine the exact type, but we know it's from the namespace
// Use a namespace-based approach
return fixer.replaceText(node, `${namespace}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
},
// Check function call arguments (more selective approach)
"CallExpression > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// We need to be more selective to avoid false positives
// Only warn if:
// 1. The function is called on a protobuf namespace
// 2. The call argument has a type annotation that matches a protobuf type
// 3. The call is to a function that we know takes a protobuf type
// Check if it's a call on a protobuf namespace
if (
node.parent.callee &&
node.parent.callee.type === "MemberExpression" &&
node.parent.callee.object.type === "Identifier"
) {
const namespace = node.parent.callee.object.name
if (protobufNamespaceImports.has(namespace)) {
const sourceCode = context.getSourceCode()
const callText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Check function call arguments object literal:', callText);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: callText },
fix(fixer) {
// For calls on a protobuf namespace
const memberExpr = node.parent.callee
// Try to determine if this is calling a method that expects a specific type
const methodName = memberExpr.property.name
// If method name looks like 'create' + Type, we can infer the type
const possibleTypeName = methodName.replace(/^create/, "")
// Check if namespace has a type with this name
// Since we can't directly check at lint time, we'll use the namespace + inferred type
if (possibleTypeName && possibleTypeName !== methodName) {
return fixer.replaceText(
node,
`${namespace}.${possibleTypeName}.create(${sourceCode.getText(node)})`,
)
}
// Fallback - use a more generic approach with namespace
return fixer.replaceText(node, `${namespace}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
// For regular function calls with object literals, check if there are protobuf imports
// and if the function might expect a protobuf type
if (node.parent.callee) {
// This is a more permissive check to catch cases like processContent({ ... })
// which might be passing a protobuf type
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
// Try to find the function definition
if (node.parent.callee.type === "Identifier") {
const functionName = node.parent.callee.name
const variable = scope.variables.find((v) => v.name === functionName)
// If we found the function and it has parameter type annotations
// that match protobuf types, flag it
if (variable && variable.defs.length > 0) {
const def = variable.defs[0]
if (def.node.params && node.parent.arguments.indexOf(node) < def.node.params.length) {
const param = def.node.params[node.parent.arguments.indexOf(node)]
if (param.typeAnnotation) {
const typeName = getTypeName(param.typeAnnotation.typeAnnotation)
if (
typeName &&
(protobufImports.has(typeName) ||
isNamespacedProtobufType(protobufNamespaceImports, typeName))
) {
const callText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Function call arguments object literal:', callText);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: callText },
fix(fixer) {
// For function calls with protobuf type parameters
return fixer.replaceText(node, `${typeName}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
}
}
}
}
},
}
},
})
// Helper functions
function getTypeName(typeAnnotation) {
if (!typeAnnotation) {
return null
}
if (typeAnnotation.type === "TSTypeReference") {
if (typeAnnotation.typeName.type === "Identifier") {
return typeAnnotation.typeName.name
} else if (typeAnnotation.typeName.type === "TSQualifiedName") {
// Handle namespaced types like proto.MyRequest
return `${typeAnnotation.typeName.left.name}.${typeAnnotation.typeName.right.name}`
}
}
return null
}
function matchesProtobufPackage(packageName, protobufPackages) {
return protobufPackages.some((protobufPackage) => {
// Remove leading and trailing @ and / from protobufPackage
const cleanedPackage = protobufPackage.replace(/^[@\/]/, "").replace(/[\/]$/, "")
const pattern = new RegExp(`(.*[@/]|)${escapeRegex(cleanedPackage)}[/].*`)
return pattern.test(packageName)
})
}
// Helper function to escape special regex characters
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
// Helper to extract function return type more reliably
function getFunctionReturnType(functionNode, sourceCode) {
// 1. Check explicit return type annotation
if (functionNode.returnType) {
return getTypeName(functionNode.returnType.typeAnnotation)
}
// 2. For variable declarations like const foo: (arg: Type) => ReturnType = ...
if (functionNode.parent && functionNode.parent.type === "VariableDeclarator") {
const declarator = functionNode.parent
if (declarator.id && declarator.id.typeAnnotation) {
const typeAnnotation = declarator.id.typeAnnotation.typeAnnotation
// Handle function type annotations
if (typeAnnotation.type === "TSFunctionType" && typeAnnotation.typeAnnotation) {
return getTypeName(typeAnnotation.typeAnnotation)
}
// Handle type references to function types
if (typeAnnotation.type === "TSTypeReference") {
// This might be a type like Promise<ReturnType>
if (
typeAnnotation.typeName.name === "Promise" &&
typeAnnotation.typeParameters &&
typeAnnotation.typeParameters.params.length > 0
) {
return getTypeName(typeAnnotation.typeParameters.params[0])
}
}
}
}
// 3. For class methods, check if it's part of an interface implementation
if (
functionNode.parent &&
functionNode.parent.type === "MethodDefinition" &&
functionNode.parent.parent &&
functionNode.parent.parent.type === "ClassBody"
) {
const className = getEnclosingClassName(functionNode)
const methodName = functionNode.parent.key.name
if (className && methodName) {
// Look for interface declarations in the scope
const scope = sourceCode.getScope(functionNode)
// This would require more complex scope analysis which is limited in ESLint
// For now, we'll return null and rely on other methods
}
}
return null
}
// Helper to get the class name for a method
function getEnclosingClassName(node) {
let current = node.parent
while (current) {
if (current.type === "ClassDeclaration" && current.id) {
return current.id.name
}
current = current.parent
}
return null
}
function isNamespacedProtobufType(protobufNamespaceImports, typeName) {
if (!typeName.includes(".")) {
return false
}
const namespace = typeName.split(".")[0]
return protobufNamespaceImports.has(namespace)
}
function findParentFunction(node) {
let current = node.parent
while (current) {
if (
current.type === "FunctionDeclaration" ||
current.type === "FunctionExpression" ||
current.type === "ArrowFunctionExpression"
) {
return current
}
current = current.parent
}
return null
}
+19 -1
View File
@@ -2,5 +2,23 @@ repositories
results/evals.db
diff-edits/cases/
diff-edits/results/
# Environment variables
.env
# backwards compatible
diff_editing/test_cases/
diff_editing/test_outputs/
diff_editing/test_outputs/
*.db
*.db-wal
*.db-shm
.cache
# Python bytecode cache
*__pycache__/
diff-edits/cases.zip
+193
View File
@@ -17,6 +17,7 @@ The evaluation system consists of two main components:
1. **Test Server**: Enhanced HTTP server in `src/services/test/TestServer.ts` that provides detailed task results
2. **CLI Tool**: Command-line interface in `evals/cli/` for orchestrating evaluations
3. **Diff Edit Benchmark**: Separate command using the CLI tool that runs a comprehensive diff editing benchmark suite on real world cases, along with a streamlit dashboard displaying the results. For more details, see the [Diff Edit Benchmark README](./diff-edits/README.md). Make sure you add a `evals/diff-edits/cases` folder with all the conversation jsons.
## Directory Structure
@@ -40,6 +41,12 @@ cline-repo/
│ │ │ └── utils/ # Utility functions
│ │ ├── package.json
│ │ └── tsconfig.json
│ ├── diff-edits/ # Diff editing evaluation suite
│ │ ├── cases/ # Test case JSON files
│ │ ├── results/ # Evaluation results
│ │ ├── diff-apply/ # Diff application logic
│ │ ├── parsing/ # Assistant message parsing
│ │ └── prompts/ # System prompts
│ ├── repositories/ # Cloned benchmark repositories
│ │ ├── exercism/ # Modified Exercism (from pashpashpash/evals)
│ │ ├── swe-bench/ # SWE-Bench repository
@@ -148,6 +155,192 @@ Freelance-style programming tasks from the SWELancer benchmark.
Multi-file software engineering tasks from the Multi-SWE-Bench repository.
## Diff Edit Evaluations
The Cline Evaluation System includes a specialized suite for evaluating how well models can make precise edits to files using the `replace_in_file` tool.
### Overview
Diff edit evaluations test a model's ability to:
1. Understand file content and identify specific sections to modify
2. Generate correct SEARCH/REPLACE blocks for targeted edits
3. Successfully apply changes without introducing errors
### Directory Structure
```
diff-edits/
├── cases/ # Test case JSON files
├── results/ # Evaluation results
├── ClineWrapper.ts # Wrapper for model interaction
├── TestRunner.ts # Main test execution logic
├── types.ts # Type definitions
├── diff-apply/ # Diff application logic
├── parsing/ # Assistant message parsing
└── prompts/ # System prompts
```
### Creating Test Cases
Test cases are defined as JSON files in the `diff-edits/cases/` directory. Each test case should include:
```json
{
"test_id": "example_test_1",
"messages": [
{
"role": "user",
"text": "Please fix the bug in this code...",
"images": []
},
{
"role": "assistant",
"text": "I'll help you fix that bug..."
}
],
"file_contents": "// Original file content here\nfunction example() {\n // Code with bug\n}",
"file_path": "src/example.js",
"system_prompt_details": {
"mcp_string": "",
"cwd_value": "/path/to/working/directory",
"browser_use": false,
"width": 900,
"height": 600,
"os_value": "macOS",
"shell_value": "/bin/zsh",
"home_value": "/Users/username",
"user_custom_instructions": ""
},
"original_diff_edit_tool_call_message": ""
}
```
### Running Diff Edit Evaluations
#### Single Model Evaluation
```bash
cd evals/cli
node dist/index.js run-diff-eval --model-ids "anthropic/claude-3-5-sonnet-20241022"
```
#### Multi-Model Evaluation
Compare multiple models in a single evaluation run:
```bash
# Compare Claude and Grok models
node dist/index.js run-diff-eval \
--model-ids "anthropic/claude-3-5-sonnet-20241022,x-ai/grok-beta" \
--max-cases 10 \
--valid-attempts-per-case 3 \
--verbose
# Compare multiple Claude variants
node dist/index.js run-diff-eval \
--model-ids "anthropic/claude-3-5-sonnet-20241022,anthropic/claude-3-5-haiku-20241022,anthropic/claude-3-opus-20240229" \
--max-cases 5 \
--valid-attempts-per-case 2 \
--parallel
```
#### Options
- `--model-ids`: Comma-separated list of model IDs to evaluate (required)
- `--system-prompt-name`: System prompt to use (default: "basicSystemPrompt")
- `--valid-attempts-per-case`: Number of attempts per test case per model (default: 1)
- `--max-cases`: Maximum number of test cases to run (default: all available)
- `--parsing-function`: Function to parse assistant messages (default: "parseAssistantMessageV2")
- `--diff-edit-function`: Function to apply diffs (default: "constructNewFileContentV2")
- `--test-path`: Path to test cases (default: diff-edits/cases)
- `--thinking-budget`: Tokens allocated for thinking (default: 0)
- `--parallel`: Run tests in parallel (flag)
- `--replay`: Use pre-recorded LLM output (flag)
- `--verbose`: Enable detailed logging (flag)
#### Examples
```bash
# Quick test with 2 models, 4 cases, 2 attempts each
node dist/index.js run-diff-eval \
--model-ids "anthropic/claude-3-5-sonnet-20241022,x-ai/grok-beta" \
--max-cases 4 \
--valid-attempts-per-case 2 \
--verbose
# Comprehensive evaluation with parallel execution
node dist/index.js run-diff-eval \
--model-ids "anthropic/claude-3-5-sonnet-20241022,anthropic/claude-3-5-haiku-20241022" \
--system-prompt-name claude4SystemPrompt \
--valid-attempts-per-case 5 \
--max-cases 20 \
--parallel \
--verbose
```
### Database Storage & Analytics
All evaluation results are automatically stored in a SQLite database (`diff-edits/evals.db`) for advanced analytics and comparison. The database includes:
- **System Prompts**: Versioned system prompt content with hashing for deduplication
- **Processing Functions**: Versioned parsing and diff-edit function configurations
- **Files**: Original and edited file content with content-based hashing
- **Runs**: Evaluation run metadata and configuration
- **Cases**: Individual test case information with context tokens
- **Results**: Detailed results with timing, cost, and success metrics
### Interactive Dashboard
Launch the Streamlit dashboard to visualize and analyze evaluation results:
```bash
cd diff-edits/dashboard
streamlit run app.py
```
The dashboard provides:
- **Model Performance Comparison**: Side-by-side comparison of success rates, latency, and costs
- **Interactive Charts**: Success rate trends, latency vs cost analysis, and performance metrics
- **Detailed Drill-Down**: Individual result analysis with file content viewing
- **Run Selection**: Browse and compare different evaluation runs
- **Real-time Updates**: Automatically refreshes with new evaluation data
#### Dashboard Features
1. **Hero Section**: Overview of current run with key metrics
2. **Model Cards**: Performance cards with grades and detailed metrics
3. **Comparison Charts**: Interactive Plotly charts for visual analysis
4. **Result Explorer**: Detailed view of individual test results including:
- Original and edited file content
- Raw model output
- Parsed tool calls
- Timing and cost metrics
- Error analysis
#### Quick Start Dashboard
```bash
# Run a quick evaluation
node cli/dist/index.js run-diff-eval \
--model-ids "anthropic/claude-3-5-sonnet-20241022,x-ai/grok-beta" \
--max-cases 4 \
--valid-attempts-per-case 2 \
--verbose
# Launch dashboard to view results
cd diff-edits/dashboard && streamlit run app.py
```
### Legacy Results
For backward compatibility, results are also saved as JSON files in the `diff-edits/results/` directory. The JSON results include:
- Success/failure status
- Extracted tool calls
- Diff edit content
- Token usage and cost metrics
## Metrics
The evaluation system collects the following metrics:
-2456
View File
File diff suppressed because it is too large Load Diff
-39
View File
@@ -1,39 +0,0 @@
{
"name": "cline-evaluation-cli",
"version": "0.1.0",
"description": "CLI tool for orchestrating Cline evaluations across multiple benchmarks",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"cline",
"evaluation",
"benchmark"
],
"author": "",
"license": "MIT",
"dependencies": {
"better-sqlite3": "^11.10.0",
"chalk": "^4.1.2",
"commander": "^9.4.1",
"execa": "^5.1.1",
"node-fetch": "^2.7.0",
"ora": "^5.4.1",
"sqlite": "^4.1.2",
"uuid": "^9.0.0",
"yargs": "^17.6.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.3",
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.12",
"@types/uuid": "^9.0.0",
"@types/yargs": "^17.0.19",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
}
}
+33 -8
View File
@@ -3,9 +3,10 @@ import chalk from "chalk"
import path from "path"
interface RunDiffEvalOptions {
modelId: string
modelIds: string
systemPromptName: string
numberOfRuns: number
validAttemptsPerCase: number
maxAttemptsPerCase?: number
parsingFunction: string
diffEditFunction: string
thinkingBudget: number
@@ -14,22 +15,26 @@ interface RunDiffEvalOptions {
testPath: string
outputPath: string
replay: boolean
replayRunId?: string
diffApplyFile?: string
saveLocally: boolean
maxCases?: number
}
export async function runDiffEvalHandler(options: RunDiffEvalOptions) {
console.log(chalk.blue("Starting diff editing evaluation..."))
// Resolve the path to the TestRunner.ts script relative to the current file
const scriptPath = path.resolve(__dirname, "../../../diff_editing/TestRunner.ts")
const scriptPath = path.resolve(__dirname, "../../../diff-edits/TestRunner.ts")
// Construct the arguments array for the execa call
const args = [
"--model-id",
options.modelId,
"--model-ids",
options.modelIds,
"--system-prompt-name",
options.systemPromptName,
"--number-of-runs",
String(options.numberOfRuns),
"--valid-attempts-per-case",
String(options.validAttemptsPerCase),
"--parsing-function",
options.parsingFunction,
"--diff-edit-function",
@@ -55,16 +60,36 @@ export async function runDiffEvalHandler(options: RunDiffEvalOptions) {
args.push("--replay")
}
if (options.replayRunId) {
args.push("--replay-run-id", options.replayRunId)
}
if (options.diffApplyFile) {
args.push("--diff-apply-file", options.diffApplyFile)
}
if (options.verbose) {
args.push("--verbose")
}
if (options.maxAttemptsPerCase) {
args.push("--max-attempts-per-case", String(options.maxAttemptsPerCase))
}
if (options.maxCases) {
args.push("--max-cases", String(options.maxCases))
}
if (options.saveLocally) {
args.push("--save-locally")
}
try {
console.log(chalk.gray(`Executing: npx tsx ${scriptPath} ${args.join(" ")}`))
// Execute the script as a child process
// We use 'inherit' to stream the stdout/stderr directly to the user's terminal
const subprocess = execa("npx", ["tsx", scriptPath, ...args], {
const subprocess = execa("npx", ["tsx", "--tsconfig", path.resolve(__dirname, "../../../tsconfig.json"), scriptPath, ...args], {
stdio: "inherit",
})
+10 -4
View File
@@ -84,22 +84,28 @@ program
.description("Run the diff editing evaluation suite")
.option("--test-path <path>", "Path to the directory containing test case JSON files")
.option("--output-path <path>", "Path to the directory to save the test output JSON files")
.option("--model-id <model_id>", "The model ID to use for the test")
.option("--model-ids <model_ids>", "Comma-separated list of model IDs to test")
.option("--system-prompt-name <name>", "The name of the system prompt to use", "basicSystemPrompt")
.option("-n, --number-of-runs <number>", "Number of times to run each test case", "1")
.option("-n, --valid-attempts-per-case <number>", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1")
.option("--max-attempts-per-case <number>", "Maximum total attempts per test case (default: 10x valid attempts)")
.option("--max-cases <number>", "Maximum number of test cases to run (limits total cases loaded)")
.option("--parsing-function <name>", "The parsing function to use", "parseAssistantMessageV2")
.option("--diff-edit-function <name>", "The diff editing function to use", "constructNewFileContentV2")
.option("--thinking-budget <tokens>", "Set the thinking tokens budget", "0")
.option("--parallel", "Run tests in parallel", false)
.option("--replay", "Run evaluation from a pre-recorded LLM output, skipping the API call", false)
.option("--replay-run-id <run_id>", "The ID of the run to replay from the database")
.option("--diff-apply-file <filename>", "The name of the diff apply file to use for the replay")
.option("--save-locally", "Save results to local JSON files in addition to database", false)
.option("-v, --verbose", "Enable verbose logging", false)
.action(async (options) => {
try {
// The logic here simplifies slightly
const fullOptions = {
...options,
numberOfRuns: parseInt(options.numberOfRuns, 10),
validAttemptsPerCase: parseInt(options.validAttemptsPerCase, 10),
maxAttemptsPerCase: options.maxAttemptsPerCase ? parseInt(options.maxAttemptsPerCase, 10) : undefined,
thinkingBudget: parseInt(options.thinkingBudget, 10),
maxCases: options.maxCases ? parseInt(options.maxCases, 10) : undefined,
}
await runDiffEvalHandler(fullOptions)
} catch (error) {
@@ -8,11 +8,13 @@ import {
parseAssistantMessageV3,
AssistantMessageContent,
} from "./parsing/parse-assistant-message-06-06-25" // "../../src/core/assistant-message"
import { constructNewFileContent as constructNewFileContentV1, constructNewFileContentV2 } from "./diff-apply/diff-06-06-25"
import { constructNewFileContent as constructNewFileContentV3 } from "../../src/core/assistant-message/diff" // this defaults to the new v1 when called
import { constructNewFileContent as constructNewFileContent_06_06_25 } from "./diff-apply/diff-06-06-25"
import { constructNewFileContent as constructNewFileContent_06_23_25 } from "./diff-apply/diff-06-23-25"
import { constructNewFileContent as constructNewFileContent_06_25_25 } from "./diff-apply/diff-06-25-25"
import { constructNewFileContent as constructNewFileContent_06_26_25 } from "./diff-apply/diff-06-26-25"
type ParseAssistantMessageFn = (message: string) => AssistantMessageContent[]
type ConstructNewFileContentFn = (diff: string, original: string, strict: boolean) => Promise<string>
type ConstructNewFileContentFn = (diff: string, original: string, strict: boolean) => Promise<string | any>
const parsingFunctions: Record<string, ParseAssistantMessageFn> = {
parseAssistantMessageV1: parseAssistantMessageV1,
@@ -21,12 +23,14 @@ const parsingFunctions: Record<string, ParseAssistantMessageFn> = {
}
const diffEditingFunctions: Record<string, ConstructNewFileContentFn> = {
constructNewFileContentV1: constructNewFileContentV1,
constructNewFileContentV2: constructNewFileContentV2,
constructNewFileContentV3: constructNewFileContentV3, // position invariant diff
"diff-06-06-25": constructNewFileContent_06_06_25,
"diff-06-23-25": constructNewFileContent_06_23_25,
"diff-06-25-25": constructNewFileContent_06_25_25,
"diff-06-26-25": constructNewFileContent_06_26_25,
}
import { TestInput, TestResult, ExtractedToolCall } from "./types"
import { log } from "./helpers"
export { TestInput, TestResult, ExtractedToolCall }
interface StreamResult {
@@ -39,16 +43,22 @@ interface StreamResult {
cacheReadTokens: number
totalCost: number
}
timing?: {
timeToFirstTokenMs: number
timeToFirstEditMs?: number
totalRoundTripMs: number
}
}
/**
* Process the stream and return full response
* Process the stream and return full response with timing data
*/
async function processStream(
handler: OpenRouterHandler,
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
): Promise<StreamResult> {
const startTime = Date.now()
const stream = handler.createMessage(systemPrompt, messages)
let assistantMessage = ""
@@ -58,12 +68,21 @@ async function processStream(
let cacheWriteTokens = 0
let cacheReadTokens = 0
let totalCost = 0
// Timing tracking
let timeToFirstTokenMs: number | null = null
let timeToFirstEditMs: number | null = null
for await (const chunk of stream) {
if (!chunk) {
continue
}
// Capture time to first token (any chunk type)
if (timeToFirstTokenMs === null) {
timeToFirstTokenMs = Date.now() - startTime
}
switch (chunk.type) {
case "usage":
inputTokens += chunk.inputTokens
@@ -79,10 +98,25 @@ async function processStream(
break
case "text":
assistantMessage += chunk.text
// Try to detect first tool call by parsing accumulated message
if (timeToFirstEditMs === null) {
try {
const parsed = parseAssistantMessageV2(assistantMessage)
const hasToolCall = parsed.some(block => block.type === "tool_use")
if (hasToolCall) {
timeToFirstEditMs = Date.now() - startTime
}
} catch {
// Parsing failed, continue accumulating
}
}
break
}
}
const totalRoundTripMs = Date.now() - startTime
return {
assistantMessage,
reasoningMessage,
@@ -93,6 +127,11 @@ async function processStream(
cacheReadTokens,
totalCost,
},
timing: {
timeToFirstTokenMs: timeToFirstTokenMs || 0,
timeToFirstEditMs: timeToFirstEditMs || undefined,
totalRoundTripMs,
},
}
}
@@ -116,6 +155,7 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
diffEditFunction,
thinkingBudgetTokens,
originalDiffEditToolCallMessage,
diffApplyFile,
} = input
const requiredParams = {
@@ -141,7 +181,7 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
}
const parseAssistantMessage = parsingFunctions[parsingFunction]
const constructNewFileContent = diffEditingFunctions[diffEditFunction]
const constructNewFileContent = diffEditingFunctions[diffApplyFile || diffEditFunction]
if (!parseAssistantMessage || !constructNewFileContent) {
return {
@@ -245,7 +285,22 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
}
// check that we are editing the correct file path
log(input.isVerbose, `Expected file path: "${originalFilePath}"`)
log(input.isVerbose, `Actual file path used: "${diffToolPath}"`)
if (diffToolPath !== originalFilePath) {
log(input.isVerbose, `❌ File path mismatch detected!`)
// Enhanced logging:
if (streamResult?.assistantMessage) {
log(input.isVerbose, ` Full model output (assistantMessage):`)
log(input.isVerbose, ` -----------------------------------------`)
log(input.isVerbose, ` ${streamResult.assistantMessage}`)
log(input.isVerbose, ` -----------------------------------------`)
}
if (toolCall) {
log(input.isVerbose, ` Parsed tool call that caused mismatch:`)
log(input.isVerbose, ` ${JSON.stringify(toolCall, null, 2)}`)
log(input.isVerbose, ` -----------------------------------------`)
}
return {
success: false,
streamResult: streamResult,
@@ -256,10 +311,18 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
// checking if the diff edit succeeds, if it failed it will throw an error
let diffSuccess = true
let replacementData: any = undefined
try {
await constructNewFileContent(diffToolContent, originalFile, true)
const result = await constructNewFileContent(diffToolContent, originalFile, true)
// Check if result is an object with replacements (new format)
if (typeof result === 'object' && result !== null && 'replacements' in result) {
replacementData = result.replacements
}
// If it's just a string, diffSuccess stays true and replacementData stays undefined
} catch (error: any) {
diffSuccess = false
log(input.isVerbose, `ERROR: ${error}`)
}
return {
@@ -268,6 +331,7 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
toolCalls: detectedToolCalls,
diffEdit: diffToolContent,
diffEditSuccess: diffSuccess,
replacementData: replacementData,
}
} catch (error: any) {
return {
+84
View File
@@ -0,0 +1,84 @@
# A Note on Cline's Diff Evaluation Setup
Hey there, this note explains what we're doing with Cline's diff evaluation (evals) system. It's all about checking how well various AI models (which users connect to Cline via their own API keys), prompts, and diffing tools can handle file changes.
## What We're Trying to Figure Out
The main idea here is to figure out which AI models (configured by users) are best at making `replace_in_file` tool calls that work correctly. This helps us understand model capabilities and also speeds up our own experiments with prompts and diffing algorithms to make Cline better over time. We want to know a few key things.
First, can the model create diffs, which are just sets of SEARCH and REPLACE blocks, that apply cleanly to a file? This is what we call `diffEditSuccess`.
Second, how do different LLMs, like Claude or Grok, stack up against each other when they try to make these diff edits? We use a standard set of real-world test cases for this.
Third, do different system prompts, say our `basicSystemPrompt` versus the `claude4SystemPrompt`, change how well a model does at diff editing?
Fourth, we're also looking at different ways to apply the diffs themselves. We have a few algorithms like `constructNewFileContentV1`, `V2`, and `V3`, and we want to see which ones are more robust when fed model-generated diffs.
Fifth, we track how fast the model starts making an edit. The `timeToFirstEditMs` metric gives us a hint about how quickly a user would see changes happening in their editor.
And finally, we keep an eye on how many tokens are used and what it costs for each model and each try. This helps us compare how efficient they are.
Right now, these evals are mostly about whether the diff *applies* correctly. That means, do the SEARCH blocks find a match, and can the REPLACE blocks be put in without an error? We're not yet deeply analyzing if the change is valid code or matches what the user *wanted* semantically. That's a problem for another day, and will require a lot more scaffolding.
## How We Run These Tests
Two prerequisites:
1. Make sure you have an `evals/.env` file with `OPENROUTER_API_KEY=<your-openrouter-key>`
2. Make sure you add a `evals/diff-edits/cases` folder with all the conversation jsons prior to running this.
Our testing strategy is based on replaying situations from actual user sessions where diff edits were tried.
It starts with our test cases. Each one is a JSON file in `./cases` that has the conversation history that led to a diff edit, the original file content and its path, and the info needed to rebuild the system prompt from that original session.
Then, for every test run, we set up a specific configuration. This includes which LLM we're testing, which system prompt it gets, which function we use to parse the model's raw output, and which function we use to actually apply the diff. Here's the command I've been using:
```bash
npm run diff-eval -- --model-ids "anthropic/claude-3-5-sonnet,x-ai/grok-3-beta,anthropic/claude-3.7-sonnet,anthropic/claude-sonnet-4,google/gemini-2.5-pro-preview,google/gemini-2.5-flash" --max-cases 5 --valid-attempts-per-case 5 --parallel --diff-edit-function diff-06-26-25 --verbose
```
This will build the eval script, run it, and then open the streamlit dashboard to show the results.
The `TestRunner.ts` script is the main coordinator. For each test case and setup, `ClineWrapper.ts` takes over and sends the conversation and system prompt to the LLM. We then watch the model's response as it streams in and parse it to find any tool calls.
We're specifically looking for the model to make a single `replace_in_file` tool call. Multiple edits in one tool call are allowed, and recorded (in case you want to filter results by number of edits in a single tool call and compare success rate for that slice across different models/system prompts/etc). If it does, and it's for the correct file, we grab the diff content it produced. Then, the chosen diff application algorithm tries to apply that diff to the original file. We record whether this worked or not as `diffEditSuccess`.
We record a bunch of data for every attempt into a database. This includes details about the model and prompt, token counts, costs, the raw output from the model, the parsed tool calls, whether it succeeded or failed, any error messages, and timing info. For a detailed explanation of the database schema, see [database.md](./database.md).
A big part of this is how we handle "valid attempts," which I'll explain next.
## Keeping it Fair with "Valid Attempts"
LLMs can be unpredictable. If we replay an old scenario, a new model, or even the same model later, might do something completely different than what happened originally. It might call another tool or ask a question instead of trying a diff edit.
Since we really want to test the *diff editing* part, we need a way to make sure we're comparing fairly. That's why we have this idea of "valid attempts."
An attempt is "valid" for this benchmark if the model actually tries to do what we're interested in. This means two things. One, it must call the `replace_in_file` tool. Two, it must target the *same file path* that was targeted in the original recorded conversation for that test case.
If the model does something else, like calling a different tool or picking the wrong file, we don't count that attempt against its diff editing score. Instead, we consider it an "invalid attempt" for *this specific benchmark* and simply re-run that test case with that model. We keep doing this until we've collected a set number of these "valid attempts."
For example, if we ask for 5 valid attempts per test case, the system will keep re-rolling for that case until the model has tried to edit the correct file using the `replace_in_file` tool 5 times. Only then do we look at how many of those 5 valid attempts actually resulted in a successful diff application (`diffEditSuccess`).
This way, if we're comparing two models and one gets a 10% success rate on its valid diff edit attempts, and another gets 90%, we have a much clearer picture of their actual diff-generating capabilities. It avoids muddying the waters with attempts where the model didn't even try to perform the specific action we're evaluating. This approach helps us isolate and measure the diff-editing skill more directly, despite the non-deterministic nature of these models.
## Replays
You can also use the replay argument to replay a previous benchmark run. This is super useful for iterating on our diffing algorithms without having to re-run expensive and time-consuming LLM calls.
When you run an evaluation, every detail is stored in the database—including the raw, unmodified output from the model. The replay feature takes advantage of this by pulling that raw output and feeding it into a *different* diffing algorithm. This lets you isolate the performance of the diffing logic itself. We can see if a new algorithm is better at applying the exact same set of diffs that a model generated in a previous run.
This process is blazingly fast and free, as it completely bypasses the need to make new API calls. It ensures a true apples-to-apples comparison between diffing strategies, since the model's output—the "ground truth" for the evaluation—remains identical.
Heres an example of how you would replay a previous run with a new diffing algorithm:
```shell
cd evals && npm run diff-eval -- --replay-run-id 9902189e-63a8-4210-a4fc-fe59e2eaf2c2 --diff-apply-file diff-06-23-25 --verbose
```
In this command:
- `--replay-run-id` specifies the original run we want to use as our ground truth.
- `--diff-apply-file` tells the script to use the new diffing logic from the `diff-06-23-25.ts` file.
The script will then create a new run in the database that mirrors the original, but with the results of applying the new diffing algorithm. This allows for a direct comparison in the dashboard, helping us quickly see which of our diffing strategies is the most robust.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
[theme]
base="dark"
[browser]
gatherUsageStats = false
[server]
headless = true
+159
View File
@@ -0,0 +1,159 @@
# 🚀 The Sickest Diff Edits Evaluation Dashboard Ever!
A beautiful, modern Streamlit dashboard for visualizing and analyzing diff editing evaluation results with deep drill-down capabilities.
## ✨ Features
### 🎯 **Smart Model Comparison**
- **Latest Run Focus**: Automatically loads and displays your most recent evaluation run
- **Beautiful Performance Cards**: Each model gets a stunning card with performance grades (A+ to C)
- **Best Performer Highlighting**: The top model gets special styling and a trophy 🏆
- **Interactive Charts**: Success rate comparisons and latency vs cost analysis
### 🔍 **Deep Drill-Down Analysis**
- **Individual Result Inspection**: Click any model to see detailed results
- **Side-by-Side File Views**: See original file content with line numbers
- **Parsed Tool Call Analysis**: View exactly what the model tried to do
- **Error Analysis**: Detailed error information for failed attempts
- **Success Metrics**: Line changes, edit counts, and timing breakdowns
### 🎨 **Aesthetic Design**
- **Modern UI**: Custom CSS with Inter font, gradients, and shadows
- **Responsive Layout**: Looks great on any screen size
- **Color-Coded Performance**: Green for excellent, yellow for good, red for poor
- **Smooth Animations**: Hover effects and transitions
- **Professional Styling**: Clean, modern design that looks amazing
### 📊 **Comprehensive Metrics**
- **Success Rates**: Color-coded percentages with performance grades
- **Timing Analysis**: First token, first edit, and round trip times
- **Cost Tracking**: Per-result and total cost analysis
- **Token Metrics**: Context tokens and completion tokens
- **Edit Statistics**: Number of edits, lines added/deleted
## 🚀 Quick Start
1. **Install dependencies**:
```bash
cd diff-edits/dashboard
pip install -r requirements.txt
```
2. **Launch the dashboard**:
```bash
streamlit run app.py
```
Or use the convenient launch script:
```bash
./launch.sh
```
3. **Open your browser** to http://localhost:8501
## 🎯 Dashboard Sections
### **Hero Section**
- Beautiful gradient header with run information
- Key metrics overview (models tested, total results, success rate, cost)
### **Model Performance Cards**
- Each model displayed as a beautiful card
- Large success rate display with color coding
- Performance grade badges (A+, A, B+, B, C+, C)
- Key metrics: latency, cost, results count, first token time
- "Drill Down" button for detailed analysis
### **Performance Analytics**
- Interactive bar chart showing success rates
- Scatter plot of latency vs cost with bubble sizes
- Hover details and zoom capabilities
### **Detailed Analysis (Drill-Down)**
- Model-specific success rate, latency, and cost metrics
- Individual result selector with status icons
- Tabbed interface for different views:
#### 📄 **File & Edits Tab**
- **Side-by-side view**: Original file content with line numbers
- **Edit analysis**: Success/failure status with detailed metrics
- **Error display**: Clear error information for failed attempts
- **Success metrics**: Lines added/deleted, number of edits
- **Parsed tool calls**: JSON view of what the model attempted
#### 🤖 **Raw Output Tab**
- Complete raw model output in a code viewer
- Monospace font for easy reading
#### 🔧 **Parsed Tool Call Tab**
- Pretty-printed JSON of parsed tool calls
- Diff block visualization for replace_in_file calls
- Error handling for malformed JSON
#### 📊 **Metrics Tab**
- Detailed timing metrics (first token, first edit, round trip)
- Token and cost information
- Context size and completion tokens
## 🛠 **Technical Features**
### **Smart Data Loading**
- Automatic latest run detection
- Efficient SQL queries with proper JOINs
- Streamlit caching for performance
- Error handling for missing data
### **Interactive Navigation**
- Session state management for drill-down views
- Back button to return to overview
- Smooth transitions between views
### **Beautiful Styling**
- Custom CSS with Google Fonts (Inter)
- Gradient backgrounds and shadows
- Hover effects and animations
- Color-coded performance indicators
- Professional card-based layout
### **Responsive Design**
- Works on desktop, tablet, and mobile
- Flexible column layouts
- Scalable text and metrics
## 🎨 **Design Philosophy**
This dashboard follows modern design principles:
- **Clarity**: Information is easy to find and understand
- **Beauty**: Visually appealing with professional styling
- **Functionality**: Deep drill-down capabilities for detailed analysis
- **Performance**: Fast loading with efficient data queries
- **Usability**: Intuitive navigation and clear visual hierarchy
## 📊 **Data Visualization**
- **Plotly Charts**: Interactive, professional-looking visualizations
- **Color Coding**: Consistent color scheme for performance levels
- **Performance Badges**: A+ to C grading system
- **Status Icons**: ✅ for success, ❌ for failure
- **Metric Cards**: Clean, card-based metric display
## 🔧 **Customization**
The dashboard is highly customizable:
- **CSS Styling**: Easy to modify colors, fonts, and layouts
- **Performance Grades**: Adjustable thresholds for A/B/C grades
- **Metrics Display**: Add or remove metrics as needed
- **Chart Types**: Easily swap chart types or add new visualizations
## 🚀 **Future Enhancements**
Potential additions:
- **Historical Trends**: Compare performance across multiple runs
- **Export Functionality**: Download results as CSV/PDF
- **Real-time Updates**: Auto-refresh for ongoing evaluations
- **Custom Filters**: Filter by date range, model type, etc.
- **Comparison Mode**: Side-by-side model comparisons
---
**This is the sickest eval dashboard ever!** 🔥 It combines beautiful design with powerful analysis capabilities, making it easy to understand model performance at a glance while providing deep drill-down capabilities for detailed investigation.
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
# Diff Edits Evaluation Dashboard Launcher
echo "🚀 Starting Diff Edits Evaluation Dashboard..."
# Check if we're in the right directory
if [ ! -f "app.py" ]; then
echo "❌ Error: app.py not found. Please run this script from the dashboard directory."
exit 1
fi
# Check if database exists
if [ ! -f "../evals.db" ]; then
echo "⚠️ Warning: Database file ../evals.db not found."
echo " Make sure you've run some evaluations first to populate the database."
echo " You can run: node ../cli/dist/index.js run-diff-eval --model-id anthropic/claude-sonnet-4 --max-cases 1"
echo ""
fi
# Check if requirements are installed
echo "📦 Checking Python dependencies..."
if ! python -c "import streamlit, plotly, pandas" 2>/dev/null; then
echo "📥 Installing required packages..."
pip install -r requirements.txt
fi
echo "🌐 Launching Streamlit dashboard..."
echo " Dashboard will open in your browser at http://localhost:8501"
echo " Press Ctrl+C to stop the dashboard"
echo ""
# Launch Streamlit
streamlit run app.py
@@ -0,0 +1,183 @@
import streamlit as st
import pandas as pd
import json
import os # Need to import os for load_case_raw_data
from utils import get_database_connection, guess_language_from_filepath # Absolute import
st.set_page_config(
page_title="Case Health Inspector",
page_icon="🧑‍⚕️",
layout="wide"
)
st.title("Case Health Inspector")
st.markdown("Identify test cases that are frequently problematic across different models and runs.")
@st.cache_data
def load_problematic_cases_summary():
conn = get_database_connection()
query = """
WITH case_attempts AS (
SELECT
c.task_id,
c.description AS case_description,
f_orig.filepath AS original_filepath, -- Get from files table
r.run_id,
r.model_id,
r.result_id,
(CASE WHEN (r.error_enum NOT IN (1, 6, 7) OR r.error_enum IS NULL) THEN 1 ELSE 0 END) AS is_valid_attempt,
(CASE WHEN (r.error_enum NOT IN (1, 6, 7) OR r.error_enum IS NULL) THEN r.succeeded ELSE NULL END) AS succeeded_on_valid
FROM cases c
JOIN results r ON c.case_id = r.case_id
LEFT JOIN files f_orig ON c.file_hash = f_orig.hash -- Join to get original filepath
),
case_summary AS (
SELECT
task_id,
case_description,
original_filepath, -- This is now f_orig.filepath
COUNT(DISTINCT run_id) AS num_benchmark_runs,
COUNT(result_id) AS total_attempts,
SUM(is_valid_attempt) AS total_valid_attempts,
SUM(succeeded_on_valid) AS total_successful_valid_attempts
FROM case_attempts
GROUP BY task_id, case_description, original_filepath -- original_filepath is f_orig.filepath
)
SELECT
task_id,
case_description,
original_filepath, -- This is f_orig.filepath from case_summary
num_benchmark_runs,
total_attempts,
total_valid_attempts,
CAST(total_valid_attempts AS REAL) * 100.0 / total_attempts AS percent_valid_attempts,
CASE
WHEN total_valid_attempts > 0 THEN CAST(total_successful_valid_attempts AS REAL) * 100.0 / total_valid_attempts
ELSE 0
END AS success_rate_on_valid
FROM case_summary
ORDER BY percent_valid_attempts ASC, success_rate_on_valid ASC;
"""
df = pd.read_sql_query(query, conn)
return df
@st.cache_data
def load_case_raw_data(task_id):
"""Loads the original JSON data for a given task_id."""
# This assumes test cases are stored in ../cases relative to this script's parent (dashboard)
# So, ../../cases from this script's location (pages/02_Bad_Cases.py)
# Correct path from this script (pages/02_Bad_Cases.py) to cases/
# os.path.dirname(__file__) -> pages
# os.path.join(..., '..') -> dashboard
# os.path.join(..., '..', '..') -> diff-edits
# os.path.join(..., '..', '..', 'cases') -> diff-edits/cases
cases_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'cases')
# The task_id is usually the filename without .json
# However, some task_ids might have suffixes or be different.
# We need a robust way to find the file. For now, assume task_id is filename base.
# This might need adjustment if task_id format varies significantly from filename.
# Try direct match first
potential_filename = f"{task_id}.json"
filepath = os.path.join(cases_dir, potential_filename)
if not os.path.exists(filepath):
# If direct match fails, list files and try to find one that starts with task_id
# This is a simple fallback, might need more robust matching if task_ids are complex
try:
for f_name in os.listdir(cases_dir):
if f_name.startswith(task_id) and f_name.endswith(".json"):
filepath = os.path.join(cases_dir, f_name)
break
else: # No break means no file found
return None # File not found
except FileNotFoundError:
return None # Cases directory itself not found
if not os.path.exists(filepath): # Check again after potential find
return None
try:
with open(filepath, 'r') as f:
return json.load(f)
except Exception as e:
st.error(f"Error loading case file {filepath}: {e}")
return None
def render_problematic_cases_page():
summary_df = load_problematic_cases_summary()
if summary_df.empty:
st.warning("No case summary data found. Run some evaluations first.")
return
st.markdown("### Cases Overview")
st.dataframe(summary_df.style.format({
"percent_valid_attempts": "{:.1f}%",
"success_rate_on_valid": "{:.1f}%"
}), use_container_width=True)
st.markdown("---")
st.markdown("### Case Drill Down")
selected_task_id = st.selectbox(
"Select a Case ID (task_id) to inspect:",
options=[""] + summary_df['task_id'].tolist() # Add a blank option
)
if selected_task_id:
case_data = summary_df[summary_df['task_id'] == selected_task_id].iloc[0]
st.subheader(f"Details for Case: {case_data['task_id']}")
st.markdown(f"**Description:** {case_data['case_description']}")
st.markdown(f"**Original Filepath:** `{case_data['original_filepath']}`")
raw_json_data = load_case_raw_data(selected_task_id)
if raw_json_data:
with st.expander("View Raw Case JSON Data", expanded=False):
st.json(raw_json_data)
if 'file_contents' in raw_json_data and raw_json_data['file_contents']:
with st.expander("View Original File Content (from Case JSON)", expanded=True):
# Prepare content for the copy button
raw_content_for_copy = raw_json_data['file_contents']
js_escaped_content = raw_content_for_copy.replace('\\', '\\\\') \
.replace('`', '\\`') \
.replace('\r\n', '\\n') \
.replace('\n', '\\n') \
.replace('\r', '\\n')
button_id = f"copyBtnCase_{selected_task_id.replace('-', '_').replace('.', '_')}"
copy_button_html = f"""
<button id="{button_id}" onclick="copyCaseContentToClipboard(`{js_escaped_content}`, '{button_id}')" style="margin-bottom: 10px; padding: 5px 10px; border-radius: 5px; border: 1px solid #ccc; cursor: pointer;">Copy File Content</button>
<script>
if (!window.copyCaseContentToClipboard) {{
window.copyCaseContentToClipboard = async function(text, buttonId) {{
try {{
await navigator.clipboard.writeText(text);
const button = document.getElementById(buttonId);
button.innerText = 'Copied!';
setTimeout(() => {{ button.innerText = 'Copy File Content'; }}, 2000);
}} catch (err) {{ console.error('Failed to copy: ', err); const button = document.getElementById(buttonId); button.innerText = 'Copy Failed!'; setTimeout(() => {{ button.innerText = 'Copy File Content'; }}, 2000); }}
}}
}}
</script>
"""
st.components.v1.html(copy_button_html, height=50)
# Prepare content for st.code
content_for_display = raw_json_data['file_contents']
content_for_display = content_for_display.replace('\\\\r\\\\n', '\r\n').replace('\\\\n', '\n')
content_for_display = content_for_display.replace('\\r\\n', '\r\n').replace('\\n', '\n')
language = guess_language_from_filepath(case_data['original_filepath'])
st.code(content_for_display, language=language, line_numbers=False)
else:
st.warning("Original file content not found in case JSON.")
else:
st.error(f"Could not load raw JSON data for case: {selected_task_id}")
# Placeholder for more detailed stats (per-model performance on this case, error breakdown)
st.markdown("*(Further per-model statistics and error breakdowns for this case can be added here.)*")
if __name__ == "__main__":
render_problematic_cases_page()
@@ -0,0 +1,4 @@
streamlit>=1.28.0
plotly>=5.17.0
pandas>=2.0.0
numpy>=1.24.0
+51
View File
@@ -0,0 +1,51 @@
import streamlit as st
import sqlite3
import pandas as pd
import os
@st.cache_resource
def get_database_connection():
# Assuming the script is run from the dashboard directory,
# evals.db is two levels up from there.
# __file__ is utils.py, its dirname is dashboard.
# os.path.dirname(__file__) -> dashboard/
# os.path.join(..., '..') -> diff-edits/
# os.path.join(..., '..', 'evals.db') -> diff-edits/evals.db
db_path = os.path.join(os.path.dirname(__file__), '..', 'evals.db')
if not os.path.exists(db_path):
st.error(f"Database not found. Expected at: {os.path.abspath(db_path)}")
st.stop()
return sqlite3.connect(db_path, check_same_thread=False)
def guess_language_from_filepath(filepath):
"""Guess the language for syntax highlighting from filepath."""
if not filepath or pd.isna(filepath):
return None
extension_map = {
'.py': 'python',
'.js': 'javascript',
'.ts': 'typescript',
'.java': 'java',
'.cs': 'csharp',
'.cpp': 'cpp',
'.c': 'c',
'.html': 'html',
'.css': 'css',
'.json': 'json',
'.sql': 'sql',
'.md': 'markdown',
'.rb': 'ruby',
'.php': 'php',
'.go': 'go',
'.rs': 'rust',
'.swift': 'swift',
'.kt': 'kotlin',
'.sh': 'bash',
'.yaml': 'yaml',
'.yml': 'yaml',
'.xml': 'xml',
}
_, ext = os.path.splitext(str(filepath)) # Ensure filepath is string
return extension_map.get(ext.lower(), None)
+96
View File
@@ -0,0 +1,96 @@
# Diff Edit Evaluation Database Schema
This document provides an overview of the SQLite database schema used for the diff edit evaluation suite. The database is designed to capture every aspect of the evaluation runs in a structured way, allowing for detailed, multi-dimensional analysis and ensuring full reproducibility of our findings.
## Data Model Overview
The database is composed of several interconnected tables that work together to provide a comprehensive picture of each evaluation. The core of the model revolves around `runs`, `cases`, and `results`.
### `runs`
A `run` represents a single, top-level execution of the evaluation script (e.g., one invocation of `npm run diff-eval`). It serves as the main container for a complete benchmark session.
- **Purpose**: To group all the results from a single benchmark execution, allowing for high-level comparison between different runs over time.
- **Key Columns**:
- `run_id`: A unique identifier for the entire run.
- `description`: A human-readable summary of the run's configuration (e.g., which models were tested, how many cases, etc.).
- `system_prompt_hash`: A foreign key that links this run to the specific system prompt that was used, ensuring we can track performance changes based on prompt modifications.
### `cases`
A `case` represents a single test scenario that is presented to a model. It corresponds to one of the JSON files in the `cases/` directory and links that static definition to a specific benchmark `run`.
- **Purpose**: To track the individual test scenarios within a given run.
- **Key Columns**:
- `case_id`: A unique identifier for the case *within* a specific run.
- `run_id`: A foreign key linking back to the parent `run`.
- `task_id`: The original, persistent identifier for the test case (typically from the JSON filename).
- `file_hash`: A foreign key linking to the original, un-edited file content for this case.
### `results`
This is the most granular and important table in the database. A `result` represents the outcome of a single attempt by a specific model on a specific case.
- **Purpose**: To store the detailed outcome of every single model attempt, providing the raw data for all quantitative and qualitative analysis.
- **Key Columns**:
- `result_id`: The primary key for the result.
- `run_id`, `case_id`, `model_id`, `processing_functions_hash`: A set of foreign keys that precisely situate this result within the context of a specific run, case, model, and set of helper functions.
- `succeeded`: A boolean indicating if the generated diff was applied successfully.
- `error_enum`: A numeric code representing the specific type of error if the attempt failed (e.g., `1` for `no_tool_calls`, `7` for `wrong_file_edited`).
- `num_edits`, `num_lines_deleted`, `num_lines_added`: Quantitative metrics about the structure of the generated diff.
- `time_to_first_token_ms`, `time_to_first_edit_ms`, `time_round_trip_ms`: High-precision timing data to measure model latency.
- `cost_usd`, `completion_tokens`: Cost and token usage metrics for efficiency analysis.
- `raw_model_output`, `file_edited_hash`, `parsed_tool_call_json`: The rich, qualitative data. This includes the model's full, raw response and the parsed tool calls, which are invaluable for debugging and understanding the model's reasoning.
---
## Supporting Tables
The following tables store versioned, deduplicated content to ensure data integrity and efficiency.
### `system_prompts`
- **Purpose**: Stores the versioned content of the system prompts used in evaluations.
- **Key Columns**:
- `hash`: A unique hash of the prompt's content, which acts as the primary key. This prevents duplicate storage of the same prompt.
- `name`: A human-readable name for the prompt (e.g., `basicSystemPrompt`, `claude4SystemPrompt`).
- `content`: The full text of the system prompt.
### `processing_functions`
- **Purpose**: Stores the versioned combinations of parsing and diff-editing functions.
- **Key Columns**:
- `hash`: A unique hash of the function combination name.
- `name`: A human-readable name (e.g., `parseV2-diffV2`).
- `parsing_function`: The name of the function used to parse the model's output.
- `diff_edit_function`: The name of the function used to apply the diff.
### `files`
- **Purpose**: Stores the content of all files involved in the tests, including the original source files and the diffs generated by the models.
- **Key Columns**:
- `hash`: A content-based hash of the file, ensuring that identical files are only stored once.
- `filepath`: The original path of the file.
- `content`: The full content of the file.
## The Bigger Picture
This relational schema provides a powerful foundation for sophisticated analysis. It moves beyond simple pass/fail metrics and allows us to explore the nuanced interactions between models, prompts, and the code they operate on. With this database, we can answer critical questions like:
- "How does prompt engineering affect not just success rate, but also latency and cost?"
- "Are certain models more prone to specific types of errors (e.g., hallucinating file paths vs. failing to call a tool)?"
- "Which of our internal diffing algorithms is the most robust against a wide range of model-generated edits?"
Ultimately, this data model enables us to move from simply *measuring* performance to truly *understanding* it, providing the insights needed to build more capable and reliable AI engineering systems.
---
## Viewing the Full Schema
To see the most up-to-date and detailed schema for the database, you can use the `sqlite3` command-line tool. From the `evals/diff-edits` directory, run the following command:
```bash
sqlite3 evals.db .schema
```
This will print the complete `CREATE TABLE` statements for all tables in the database, providing a definitive reference for the database structure.
+135
View File
@@ -0,0 +1,135 @@
import Database from 'better-sqlite3';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
export class DatabaseClient {
private static instance: DatabaseClient;
private db: Database.Database;
private dbPath: string;
private constructor() {
// Get database path from environment or use default
this.dbPath = process.env.DIFF_EVALS_DB_PATH || path.join(__dirname, '../evals.db');
// Ensure directory exists
const dbDir = path.dirname(this.dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
// Initialize database connection
this.db = new Database(this.dbPath);
// Enable WAL mode for concurrent access
this.db.pragma('journal_mode = WAL');
// Enable foreign key constraints
this.db.pragma('foreign_keys = ON');
// Initialize schema if needed
this.initializeSchema();
}
static getInstance(): DatabaseClient {
if (!DatabaseClient.instance) {
DatabaseClient.instance = new DatabaseClient();
}
return DatabaseClient.instance;
}
private initializeSchema(): void {
// Check if tables exist by trying to query one of them
try {
this.db.prepare('SELECT COUNT(*) FROM system_prompts LIMIT 1').get();
// If we get here, tables exist
return;
} catch (error) {
// Tables don't exist, create them
console.log('Initializing database schema...');
this.createTables();
}
}
private createTables(): void {
const schemaPath = path.join(__dirname, 'schema.sql');
const schema = fs.readFileSync(schemaPath, 'utf8');
// Execute the entire schema as one block
this.db.transaction(() => {
this.db.exec(schema);
})();
console.log('Database schema initialized successfully');
}
getDatabase(): Database.Database {
return this.db;
}
getDatabasePath(): string {
return this.dbPath;
}
// Utility method to generate SHA-256 hash
static generateHash(content: string): string {
return crypto.createHash('sha256').update(content).digest('hex');
}
// Utility method to generate UUID-like ID
static generateId(): string {
return crypto.randomUUID();
}
// Transaction wrapper
transaction<T>(fn: () => T): T {
return this.db.transaction(fn)();
}
// Close database connection (for cleanup)
close(): void {
if (this.db) {
this.db.close();
}
}
// Get database info
getInfo(): { path: string; size: number; tables: string[] } {
const stats = fs.statSync(this.dbPath);
const tables = this.db
.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
.all()
.map((row: any) => row.name);
return {
path: this.dbPath,
size: stats.size,
tables
};
}
// Vacuum database (cleanup and optimize)
vacuum(): void {
this.db.exec('VACUUM');
}
// Get database statistics
getStats(): { [tableName: string]: number } {
const tables = ['system_prompts', 'processing_functions', 'files', 'runs', 'cases', 'results'];
const stats: { [tableName: string]: number } = {};
for (const table of tables) {
try {
const result = this.db.prepare(`SELECT COUNT(*) as count FROM ${table}`).get() as { count: number };
stats[table] = result.count;
} catch (error) {
stats[table] = 0;
}
}
return stats;
}
}
// Export singleton instance getter
export const getDatabase = () => DatabaseClient.getInstance();
+23
View File
@@ -0,0 +1,23 @@
// Main database module exports
export { DatabaseClient, getDatabase } from './client';
export * from './types';
export * from './operations';
export * from './queries';
// Re-export commonly used functions for convenience
export {
upsertSystemPrompt,
upsertProcessingFunctions,
upsertFile,
createBenchmarkRun,
createCase,
insertResult,
getRunStats
} from './operations';
export {
getSuccessRatesByModel,
getModelComparisons,
getDatabaseSummary,
getErrorDistribution
} from './queries';
+348
View File
@@ -0,0 +1,348 @@
import { DatabaseClient } from './client';
import {
SystemPrompt,
ProcessingFunctions,
FileRecord,
BenchmarkRun,
Case,
Result,
CreateSystemPromptInput,
CreateProcessingFunctionsInput,
CreateFileInput,
CreateBenchmarkRunInput,
CreateCaseInput,
CreateResultInput
} from './types';
const db = DatabaseClient.getInstance();
// System Prompts Operations
export async function upsertSystemPrompt(input: CreateSystemPromptInput): Promise<string> {
const hash = DatabaseClient.generateHash(input.content);
const stmt = db.getDatabase().prepare(`
INSERT OR IGNORE INTO system_prompts (hash, name, content)
VALUES (?, ?, ?)
`);
stmt.run(hash, input.name, input.content);
return hash;
}
export async function getSystemPromptByHash(hash: string): Promise<SystemPrompt | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM system_prompts WHERE hash = ?
`);
const result = stmt.get(hash) as SystemPrompt | undefined;
return result || null;
}
// Processing Functions Operations
export async function upsertProcessingFunctions(input: CreateProcessingFunctionsInput): Promise<string> {
const hash = DatabaseClient.generateHash(input.parsing_function + input.diff_edit_function);
const stmt = db.getDatabase().prepare(`
INSERT OR IGNORE INTO processing_functions (hash, name, parsing_function, diff_edit_function)
VALUES (?, ?, ?, ?)
`);
stmt.run(hash, input.name, input.parsing_function, input.diff_edit_function);
return hash;
}
export async function getProcessingFunctionsByHash(hash: string): Promise<ProcessingFunctions | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM processing_functions WHERE hash = ?
`);
const result = stmt.get(hash) as ProcessingFunctions | undefined;
return result || null;
}
// Files Operations
export async function upsertFile(input: CreateFileInput): Promise<string> {
const hash = DatabaseClient.generateHash(input.content);
const stmt = db.getDatabase().prepare(`
INSERT OR IGNORE INTO files (hash, filepath, content, tokens)
VALUES (?, ?, ?, ?)
`);
stmt.run(hash, input.filepath, input.content, input.tokens || null);
return hash;
}
export async function getFileByHash(hash: string): Promise<FileRecord | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM files WHERE hash = ?
`);
const result = stmt.get(hash) as FileRecord | undefined;
return result || null;
}
// Benchmark Runs Operations
export async function createBenchmarkRun(input: CreateBenchmarkRunInput): Promise<string> {
const runId = DatabaseClient.generateId();
const stmt = db.getDatabase().prepare(`
INSERT INTO runs (run_id, description, system_prompt_hash)
VALUES (?, ?, ?)
`);
stmt.run(runId, input.description || null, input.system_prompt_hash);
return runId;
}
export async function getBenchmarkRun(runId: string): Promise<BenchmarkRun | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM runs WHERE run_id = ?
`);
const result = stmt.get(runId) as BenchmarkRun | undefined;
return result || null;
}
export async function getAllBenchmarkRuns(): Promise<BenchmarkRun[]> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM runs ORDER BY created_at DESC
`);
return stmt.all() as BenchmarkRun[];
}
// Cases Operations
export async function createCase(input: CreateCaseInput): Promise<string> {
const caseId = DatabaseClient.generateId();
const stmt = db.getDatabase().prepare(`
INSERT INTO cases (case_id, run_id, description, system_prompt_hash, task_id, tokens_in_context, file_hash)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
caseId,
input.run_id,
input.description,
input.system_prompt_hash,
input.task_id,
input.tokens_in_context,
input.file_hash || null
);
return caseId;
}
export async function getCasesByRun(runId: string): Promise<Case[]> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM cases WHERE run_id = ? ORDER BY created_at
`);
return stmt.all(runId) as Case[];
}
export async function getCaseById(caseId: string): Promise<Case | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM cases WHERE case_id = ?
`);
const result = stmt.get(caseId) as Case | undefined;
return result || null;
}
// Results Operations
export async function insertResult(input: CreateResultInput): Promise<string> {
const resultId = DatabaseClient.generateId();
const stmt = db.getDatabase().prepare(`
INSERT INTO results (
result_id, run_id, case_id, model_id, processing_functions_hash,
succeeded, error_enum, num_edits, num_lines_deleted, num_lines_added,
time_to_first_token_ms, time_to_first_edit_ms, time_round_trip_ms,
cost_usd, completion_tokens, raw_model_output, file_edited_hash,
parsed_tool_call_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
resultId,
input.run_id,
input.case_id,
input.model_id,
input.processing_functions_hash,
input.succeeded ? 1 : 0, // Convert boolean to integer
input.error_enum || null,
input.num_edits || null,
input.num_lines_deleted || null,
input.num_lines_added || null,
input.time_to_first_token_ms || null,
input.time_to_first_edit_ms || null,
input.time_round_trip_ms || null,
input.cost_usd || null,
input.completion_tokens || null,
input.raw_model_output || null,
input.file_edited_hash || null,
input.parsed_tool_call_json || null
);
return resultId;
}
export async function getResultsByRun(runId: string): Promise<Result[]> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM results WHERE run_id = ? ORDER BY created_at
`);
return stmt.all(runId) as Result[];
}
export async function getResultsByCase(caseId: string): Promise<Result[]> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM results WHERE case_id = ? ORDER BY created_at
`);
return stmt.all(caseId) as Result[];
}
export async function getResultById(resultId: string): Promise<Result | null> {
const stmt = db.getDatabase().prepare(`
SELECT * FROM results WHERE result_id = ?
`);
const result = stmt.get(resultId) as Result | undefined;
return result || null;
}
// Batch operations for performance
export async function insertResultsBatch(inputs: CreateResultInput[]): Promise<string[]> {
const stmt = db.getDatabase().prepare(`
INSERT INTO results (
result_id, run_id, case_id, model_id, processing_functions_hash,
succeeded, error_enum, num_edits, num_lines_deleted, num_lines_added,
time_to_first_token_ms, time_to_first_edit_ms, time_round_trip_ms,
cost_usd, completion_tokens, raw_model_output, file_edited_hash,
parsed_tool_call_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
return db.transaction(() => {
const resultIds: string[] = [];
for (const input of inputs) {
const resultId = DatabaseClient.generateId();
stmt.run(
resultId,
input.run_id,
input.case_id,
input.model_id,
input.processing_functions_hash,
input.succeeded ? 1 : 0, // Convert boolean to integer
input.error_enum || null,
input.num_edits || null,
input.num_lines_deleted || null,
input.num_lines_added || null,
input.time_to_first_token_ms || null,
input.time_to_first_edit_ms || null,
input.time_round_trip_ms || null,
input.cost_usd || null,
input.completion_tokens || null,
input.raw_model_output || null,
input.file_edited_hash || null,
input.parsed_tool_call_json || null
);
resultIds.push(resultId);
}
return resultIds;
});
}
export async function createCasesBatch(inputs: CreateCaseInput[]): Promise<string[]> {
const stmt = db.getDatabase().prepare(`
INSERT INTO cases (case_id, run_id, description, system_prompt_hash, task_id, tokens_in_context)
VALUES (?, ?, ?, ?, ?, ?)
`);
return db.transaction(() => {
const caseIds: string[] = [];
for (const input of inputs) {
const caseId = DatabaseClient.generateId();
stmt.run(
caseId,
input.run_id,
input.description,
input.system_prompt_hash,
input.task_id,
input.tokens_in_context
);
caseIds.push(caseId);
}
return caseIds;
});
}
// Utility functions
export async function getRunStats(runId: string): Promise<{
total_cases: number;
total_results: number;
success_rate: number;
avg_cost: number;
avg_latency: number;
}> {
const stmt = db.getDatabase().prepare(`
SELECT
COUNT(DISTINCT c.case_id) as total_cases,
COUNT(r.result_id) as total_results,
AVG(CASE WHEN r.succeeded THEN 1.0 ELSE 0.0 END) as success_rate,
AVG(r.cost_usd) as avg_cost,
AVG(r.time_round_trip_ms) as avg_latency
FROM cases c
LEFT JOIN results r ON c.case_id = r.case_id
WHERE c.run_id = ?
`);
const result = stmt.get(runId) as any;
return {
total_cases: result.total_cases || 0,
total_results: result.total_results || 0,
success_rate: result.success_rate || 0,
avg_cost: result.avg_cost || 0,
avg_latency: result.avg_latency || 0
};
}
// Count valid attempts for a specific case and model
export async function getValidAttemptCount(caseId: string, modelId: string): Promise<number> {
const stmt = db.getDatabase().prepare(`
SELECT COUNT(*) as count
FROM results
WHERE case_id = ?
AND model_id = ?
AND error_enum NOT IN (1, 6, 7) -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
`);
const result = stmt.get(caseId, modelId) as { count: number };
return result.count;
}
// Get valid results for a specific case and model (for analysis)
export async function getValidResults(caseId: string, modelId: string, limit?: number): Promise<Result[]> {
const limitClause = limit ? `LIMIT ${limit}` : '';
const stmt = db.getDatabase().prepare(`
SELECT * FROM results
WHERE case_id = ?
AND model_id = ?
AND error_enum NOT IN (1, 6, 7) -- Only valid attempts
ORDER BY created_at
${limitClause}
`);
return stmt.all(caseId, modelId) as Result[];
}
+309
View File
@@ -0,0 +1,309 @@
import { DatabaseClient } from './client';
import {
ModelSuccessRate,
ModelLatency,
CostAnalysis,
ErrorDistribution,
FailedCase,
PerformanceTrend,
ModelComparison
} from './types';
const db = DatabaseClient.getInstance();
// Performance analysis queries
export async function getSuccessRatesByModel(): Promise<ModelSuccessRate[]> {
const stmt = db.getDatabase().prepare(`
SELECT
model_id,
COUNT(*) as total_runs,
SUM(CASE WHEN succeeded THEN 1 ELSE 0 END) as successful_runs,
ROUND(AVG(CASE WHEN succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate
FROM results
WHERE error_enum NOT IN (1, 6, 7) OR error_enum IS NULL -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
GROUP BY model_id
ORDER BY success_rate DESC, total_runs DESC
`);
return stmt.all() as ModelSuccessRate[];
}
export async function getAverageLatencyByModel(): Promise<ModelLatency[]> {
const stmt = db.getDatabase().prepare(`
SELECT
model_id,
ROUND(AVG(time_to_first_token_ms), 2) as avg_time_to_first_token_ms,
ROUND(AVG(time_to_first_edit_ms), 2) as avg_time_to_first_edit_ms,
ROUND(AVG(time_round_trip_ms), 2) as avg_time_round_trip_ms
FROM results
WHERE time_to_first_token_ms IS NOT NULL
GROUP BY model_id
ORDER BY avg_time_round_trip_ms ASC
`);
return stmt.all() as ModelLatency[];
}
export async function getCostAnalysisByRun(): Promise<CostAnalysis[]> {
const stmt = db.getDatabase().prepare(`
SELECT
run_id,
model_id,
ROUND(SUM(cost_usd), 4) as total_cost_usd,
ROUND(AVG(cost_usd), 4) as avg_cost_per_case,
SUM(completion_tokens) as total_completion_tokens
FROM results
WHERE cost_usd IS NOT NULL
GROUP BY run_id, model_id
ORDER BY total_cost_usd DESC
`);
return stmt.all() as CostAnalysis[];
}
// Error analysis queries
export async function getErrorDistribution(): Promise<ErrorDistribution[]> {
const stmt = db.getDatabase().prepare(`
SELECT
error_enum,
COUNT(*) as count,
ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM results WHERE succeeded = 0), 2) as percentage
FROM results
WHERE succeeded = 0 AND error_enum IS NOT NULL
GROUP BY error_enum
ORDER BY count DESC
`);
return stmt.all() as ErrorDistribution[];
}
export async function getFailedCasesByError(errorEnum?: number): Promise<FailedCase[]> {
let query = `
SELECT
r.case_id,
r.model_id,
r.error_enum,
c.description,
r.raw_model_output
FROM results r
JOIN cases c ON r.case_id = c.case_id
WHERE r.succeeded = 0
`;
const params: any[] = [];
if (errorEnum !== undefined) {
query += ` AND r.error_enum = ?`;
params.push(errorEnum);
}
query += ` ORDER BY r.created_at DESC LIMIT 100`;
const stmt = db.getDatabase().prepare(query);
return stmt.all(...params) as FailedCase[];
}
// Trend analysis queries
export async function getPerformanceTrends(days: number = 30): Promise<PerformanceTrend[]> {
const stmt = db.getDatabase().prepare(`
SELECT
DATE(r.created_at) as date,
r.model_id,
ROUND(AVG(CASE WHEN r.succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(r.time_round_trip_ms), 2) as avg_latency_ms,
ROUND(AVG(r.cost_usd), 4) as avg_cost_usd
FROM results r
WHERE r.created_at >= datetime('now', '-' || ? || ' days')
AND (r.error_enum NOT IN (1, 6, 7) OR r.error_enum IS NULL) -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
GROUP BY DATE(r.created_at), r.model_id
ORDER BY date DESC, model_id
`);
return stmt.all(days) as PerformanceTrend[];
}
export async function getModelComparisons(): Promise<ModelComparison[]> {
const stmt = db.getDatabase().prepare(`
SELECT
model_id,
ROUND(AVG(CASE WHEN succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(time_round_trip_ms), 2) as avg_latency_ms,
ROUND(AVG(cost_usd), 4) as avg_cost_usd,
COUNT(*) as total_runs
FROM results
WHERE error_enum NOT IN (1, 6, 7) OR error_enum IS NULL -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
GROUP BY model_id
HAVING total_runs >= 10
ORDER BY success_rate DESC, avg_latency_ms ASC
`);
return stmt.all() as ModelComparison[];
}
// Advanced analysis queries
export async function getTopPerformingCases(limit: number = 10): Promise<Array<{
case_id: string;
description: string;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>> {
const stmt = db.getDatabase().prepare(`
SELECT
c.case_id,
c.description,
ROUND(AVG(CASE WHEN r.succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(r.time_round_trip_ms), 2) as avg_latency_ms,
COUNT(r.result_id) as total_runs
FROM cases c
JOIN results r ON c.case_id = r.case_id
WHERE r.error_enum NOT IN (1, 6, 7) OR r.error_enum IS NULL -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
GROUP BY c.case_id, c.description
HAVING total_runs >= 5
ORDER BY success_rate DESC, avg_latency_ms ASC
LIMIT ?
`);
return stmt.all(limit) as Array<{
case_id: string;
description: string;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>;
}
export async function getWorstPerformingCases(limit: number = 10): Promise<Array<{
case_id: string;
description: string;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>> {
const stmt = db.getDatabase().prepare(`
SELECT
c.case_id,
c.description,
ROUND(AVG(CASE WHEN r.succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(r.time_round_trip_ms), 2) as avg_latency_ms,
COUNT(r.result_id) as total_runs
FROM cases c
JOIN results r ON c.case_id = r.case_id
WHERE r.error_enum NOT IN (1, 6, 7) OR r.error_enum IS NULL -- Exclude: no_tool_calls, wrong_tool_call, wrong_file_edited
GROUP BY c.case_id, c.description
HAVING total_runs >= 5
ORDER BY success_rate ASC, avg_latency_ms DESC
LIMIT ?
`);
return stmt.all(limit) as Array<{
case_id: string;
description: string;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>;
}
export async function getModelPerformanceByTimeOfDay(): Promise<Array<{
model_id: string;
hour: number;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>> {
const stmt = db.getDatabase().prepare(`
SELECT
model_id,
CAST(strftime('%H', created_at) AS INTEGER) as hour,
ROUND(AVG(CASE WHEN succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(time_round_trip_ms), 2) as avg_latency_ms,
COUNT(*) as total_runs
FROM results
GROUP BY model_id, hour
HAVING total_runs >= 5
ORDER BY model_id, hour
`);
return stmt.all() as Array<{
model_id: string;
hour: number;
success_rate: number;
avg_latency_ms: number;
total_runs: number;
}>;
}
export async function getRunComparison(runId1: string, runId2: string): Promise<{
run1: { run_id: string; success_rate: number; avg_latency_ms: number; avg_cost_usd: number; total_cases: number };
run2: { run_id: string; success_rate: number; avg_latency_ms: number; avg_cost_usd: number; total_cases: number };
}> {
const stmt = db.getDatabase().prepare(`
SELECT
run_id,
ROUND(AVG(CASE WHEN succeeded THEN 1.0 ELSE 0.0 END) * 100, 2) as success_rate,
ROUND(AVG(time_round_trip_ms), 2) as avg_latency_ms,
ROUND(AVG(cost_usd), 4) as avg_cost_usd,
COUNT(DISTINCT case_id) as total_cases
FROM results
WHERE run_id IN (?, ?)
GROUP BY run_id
`);
const results = stmt.all(runId1, runId2) as Array<{
run_id: string;
success_rate: number;
avg_latency_ms: number;
avg_cost_usd: number;
total_cases: number;
}>;
const run1 = results.find(r => r.run_id === runId1);
const run2 = results.find(r => r.run_id === runId2);
if (!run1 || !run2) {
throw new Error('One or both runs not found');
}
return { run1, run2 };
}
// Summary statistics
export async function getDatabaseSummary(): Promise<{
total_runs: number;
total_cases: number;
total_results: number;
valid_results: number;
unique_models: number;
overall_success_rate: number;
date_range: { earliest: string; latest: string };
}> {
const stmt = db.getDatabase().prepare(`
SELECT
(SELECT COUNT(*) FROM runs) as total_runs,
(SELECT COUNT(*) FROM cases) as total_cases,
(SELECT COUNT(*) FROM results) as total_results,
(SELECT COUNT(*) FROM results WHERE error_enum NOT IN (1, 6, 7) OR error_enum IS NULL) as valid_results,
(SELECT COUNT(DISTINCT model_id) FROM results) as unique_models,
(SELECT ROUND(AVG(CASE WHEN succeeded THEN 1.0 ELSE 0.0 END) * 100, 2)
FROM results
WHERE error_enum NOT IN (1, 6, 7) OR error_enum IS NULL) as overall_success_rate,
(SELECT MIN(created_at) FROM results) as earliest,
(SELECT MAX(created_at) FROM results) as latest
FROM results
LIMIT 1
`);
const result = stmt.get() as any;
return {
total_runs: result.total_runs || 0,
total_cases: result.total_cases || 0,
total_results: result.total_results || 0,
valid_results: result.valid_results || 0,
unique_models: result.unique_models || 0,
overall_success_rate: result.overall_success_rate || 0,
date_range: {
earliest: result.earliest || '',
latest: result.latest || ''
}
};
}
+78
View File
@@ -0,0 +1,78 @@
PRAGMA foreign_keys = ON;
CREATE TABLE system_prompts (
hash TEXT PRIMARY KEY,
name TEXT NOT NULL,
content TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE processing_functions (
hash TEXT PRIMARY KEY,
name TEXT NOT NULL,
parsing_function TEXT NOT NULL,
diff_edit_function TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE files (
hash TEXT PRIMARY KEY,
filepath TEXT NOT NULL,
content TEXT NOT NULL,
tokens INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE runs (
run_id TEXT PRIMARY KEY,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
description TEXT,
system_prompt_hash TEXT NOT NULL,
FOREIGN KEY (system_prompt_hash) REFERENCES system_prompts(hash)
);
CREATE TABLE cases (
case_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
description TEXT NOT NULL,
system_prompt_hash TEXT NOT NULL,
task_id TEXT NOT NULL,
tokens_in_context INTEGER,
file_hash TEXT,
FOREIGN KEY (run_id) REFERENCES runs(run_id),
FOREIGN KEY (system_prompt_hash) REFERENCES system_prompts(hash),
FOREIGN KEY (file_hash) REFERENCES files(hash)
);
CREATE TABLE results (
result_id TEXT PRIMARY KEY,
run_id TEXT NOT NULL,
case_id TEXT NOT NULL,
model_id TEXT NOT NULL,
processing_functions_hash TEXT NOT NULL,
succeeded BOOLEAN NOT NULL,
error_enum INTEGER,
num_edits INTEGER,
num_lines_deleted INTEGER,
num_lines_added INTEGER,
time_to_first_token_ms INTEGER,
time_to_first_edit_ms INTEGER,
time_round_trip_ms INTEGER,
cost_usd REAL,
completion_tokens INTEGER,
raw_model_output TEXT,
file_edited_hash TEXT,
parsed_tool_call_json TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (run_id) REFERENCES runs(run_id),
FOREIGN KEY (case_id) REFERENCES cases(case_id),
FOREIGN KEY (processing_functions_hash) REFERENCES processing_functions(hash)
);
CREATE INDEX idx_results_run_model ON results(run_id, model_id);
CREATE INDEX idx_results_case_model ON results(case_id, model_id);
CREATE INDEX idx_results_success ON results(succeeded);
CREATE INDEX idx_cases_run ON cases(run_id);
CREATE INDEX idx_results_created_at ON results(created_at);
CREATE INDEX idx_runs_created_at ON runs(created_at);
+53
View File
@@ -0,0 +1,53 @@
// Simple test to verify database functionality
import { getDatabase } from './client';
import { upsertSystemPrompt, createBenchmarkRun, getDatabaseSummary } from './index';
async function testDatabase() {
console.log('Testing database functionality...');
try {
// Test database connection
const db = getDatabase();
console.log('✓ Database connection established');
console.log('Database path:', db.getDatabasePath());
// Test database info
const info = db.getInfo();
console.log('✓ Database info:', info);
// Test database stats
const stats = db.getStats();
console.log('✓ Database stats:', stats);
// Test system prompt creation
const systemPromptHash = await upsertSystemPrompt({
name: 'test-prompt',
content: 'This is a test system prompt for database verification.'
});
console.log('✓ System prompt created with hash:', systemPromptHash);
// Test benchmark run creation
const runId = await createBenchmarkRun({
description: 'Test run for database verification',
system_prompt_hash: systemPromptHash
});
console.log('✓ Benchmark run created with ID:', runId);
// Test database summary
const summary = await getDatabaseSummary();
console.log('✓ Database summary:', summary);
console.log('\n🎉 All database tests passed!');
} catch (error) {
console.error('❌ Database test failed:', error);
process.exit(1);
}
}
// Run test if this file is executed directly
if (require.main === module) {
testDatabase();
}
export { testDatabase };
+169
View File
@@ -0,0 +1,169 @@
// Database type definitions for diff-edits evaluation system
export interface SystemPrompt {
hash: string;
name: string;
content: string;
created_at: string;
}
export interface ProcessingFunctions {
hash: string;
name: string;
parsing_function: string;
diff_edit_function: string;
created_at: string;
}
export interface FileRecord {
hash: string;
filepath: string;
content: string;
tokens?: number;
created_at: string;
}
export interface BenchmarkRun {
run_id: string;
created_at: string;
description?: string;
system_prompt_hash: string;
}
export interface Case {
case_id: string
run_id: string
created_at: string
description: string
system_prompt_hash: string
task_id: string
tokens_in_context: number
file_hash?: string
}
export interface Result {
result_id: string;
run_id: string;
case_id: string;
model_id: string;
processing_functions_hash: string;
succeeded: boolean;
error_enum?: number;
num_edits?: number;
num_lines_deleted?: number;
num_lines_added?: number;
time_to_first_token_ms?: number;
time_to_first_edit_ms?: number;
time_round_trip_ms?: number;
cost_usd?: number;
completion_tokens?: number;
raw_model_output?: string;
file_edited_hash?: string;
parsed_tool_call_json?: string;
created_at: string;
}
// Input types for creating records
export interface CreateSystemPromptInput {
name: string;
content: string;
}
export interface CreateProcessingFunctionsInput {
name: string;
parsing_function: string;
diff_edit_function: string;
}
export interface CreateFileInput {
filepath: string;
content: string;
tokens?: number;
}
export interface CreateBenchmarkRunInput {
description?: string;
system_prompt_hash: string;
}
export interface CreateCaseInput {
run_id: string;
description: string;
system_prompt_hash: string;
task_id: string;
tokens_in_context: number;
file_hash?: string;
}
export interface CreateResultInput {
run_id: string;
case_id: string;
model_id: string;
processing_functions_hash: string;
succeeded: boolean;
error_enum?: number;
num_edits?: number;
num_lines_deleted?: number;
num_lines_added?: number;
time_to_first_token_ms?: number;
time_to_first_edit_ms?: number;
time_round_trip_ms?: number;
cost_usd?: number;
completion_tokens?: number;
raw_model_output?: string;
file_edited_hash?: string;
parsed_tool_call_json?: string;
}
// Analysis result types
export interface ModelSuccessRate {
model_id: string;
total_runs: number;
successful_runs: number;
success_rate: number;
}
export interface ModelLatency {
model_id: string;
avg_time_to_first_token_ms: number;
avg_time_to_first_edit_ms: number;
avg_time_round_trip_ms: number;
}
export interface CostAnalysis {
run_id: string;
model_id: string;
total_cost_usd: number;
avg_cost_per_case: number;
total_completion_tokens: number;
}
export interface ErrorDistribution {
error_enum: number;
count: number;
percentage: number;
}
export interface FailedCase {
case_id: string;
model_id: string;
error_enum: number;
description: string;
raw_model_output?: string;
}
export interface PerformanceTrend {
date: string;
model_id: string;
success_rate: number;
avg_latency_ms: number;
avg_cost_usd: number;
}
export interface ModelComparison {
model_id: string;
success_rate: number;
avg_latency_ms: number;
avg_cost_usd: number;
total_runs: number;
}
@@ -0,0 +1,827 @@
const SEARCH_BLOCK_START = "------- SEARCH"
const SEARCH_BLOCK_END = "======="
const REPLACE_BLOCK_END = "+++++++ REPLACE"
const SEARCH_BLOCK_CHAR = "-"
const REPLACE_BLOCK_CHAR = "+"
const LEGACY_SEARCH_BLOCK_CHAR = "<"
const LEGACY_REPLACE_BLOCK_CHAR = ">"
// Replace the exact string constants with flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/
const LEGACY_SEARCH_BLOCK_START_REGEX = /^[<]{3,} SEARCH$/
const LEGACY_REPLACE_BLOCK_END_REGEX = /^[>]{3,} REPLACE$/
// Helper functions to check if a line matches the flexible patterns
function isSearchBlockStart(line: string): boolean {
return SEARCH_BLOCK_START_REGEX.test(line) || LEGACY_SEARCH_BLOCK_START_REGEX.test(line)
}
function isSearchBlockEnd(line: string): boolean {
return SEARCH_BLOCK_END_REGEX.test(line)
}
function isReplaceBlockEnd(line: string): boolean {
return REPLACE_BLOCK_END_REGEX.test(line) || LEGACY_REPLACE_BLOCK_END_REGEX.test(line)
}
/**
* Attempts a line-trimmed fallback match for the given search content in the original content.
* It tries to match `searchContent` lines against a block of lines in `originalContent` starting
* from `lastProcessedIndex`. Lines are matched by trimming leading/trailing whitespace and ensuring
* they are identical afterwards.
*
* Returns [matchIndexStart, matchIndexEnd] if found, or false if not found.
*/
function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
// Split both contents into lines
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Trim trailing empty line if exists (from the trailing \n in searchContent)
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1 // +1 for \n
startLineNum++
}
// For each possible starting position in original content
for (let i = startLineNum; i <= originalLines.length - searchLines.length; i++) {
let matches = true
// Try to match all search lines from this position
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim()
const searchTrimmed = searchLines[j].trim()
if (originalTrimmed !== searchTrimmed) {
matches = false
break
}
}
// If we found a match, calculate the exact character positions
if (matches) {
// Find start character index
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1 // +1 for \n
}
// Find end character index
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length + 1 // +1 for \n
}
return [matchStartIndex, matchEndIndex]
}
}
return false
}
/**
* Attempts to match blocks of code by using the first and last lines as anchors.
* This is a third-tier fallback strategy that helps match blocks where we can identify
* the correct location by matching the beginning and end, even if the exact content
* differs slightly.
*
* The matching strategy:
* 1. Only attempts to match blocks of 3 or more lines to avoid false positives
* 2. Extracts from the search content:
* - First line as the "start anchor"
* - Last line as the "end anchor"
* 3. For each position in the original content:
* - Checks if the next line matches the start anchor
* - If it does, jumps ahead by the search block size
* - Checks if that line matches the end anchor
* - All comparisons are done after trimming whitespace
*
* This approach is particularly useful for matching blocks of code where:
* - The exact content might have minor differences
* - The beginning and end of the block are distinctive enough to serve as anchors
* - The overall structure (number of lines) remains the same
*
* @param originalContent - The full content of the original file
* @param searchContent - The content we're trying to find in the original file
* @param startIndex - The character index in originalContent where to start searching
* @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise
*/
function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Only use this approach for blocks of 3+ lines
if (searchLines.length < 3) {
return false
}
// Trim trailing empty line if exists
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
const firstLineSearch = searchLines[0].trim()
const lastLineSearch = searchLines[searchLines.length - 1].trim()
const searchBlockSize = searchLines.length
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1
startLineNum++
}
// Look for matching start and end anchors
for (let i = startLineNum; i <= originalLines.length - searchBlockSize; i++) {
// Check if first line matches
if (originalLines[i].trim() !== firstLineSearch) {
continue
}
// Check if last line matches at the expected position
if (originalLines[i + searchBlockSize - 1].trim() !== lastLineSearch) {
continue
}
// Calculate exact character positions
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1
}
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchBlockSize; k++) {
matchEndIndex += originalLines[i + k].length + 1
}
return [matchStartIndex, matchEndIndex]
}
return false
}
/**
* This function reconstructs the file content by applying a streamed diff (in a
* specialized SEARCH/REPLACE block format) to the original file content. It is designed
* to handle both incremental updates and the final resulting file after all chunks have
* been processed.
*
* The diff format is a custom structure that uses three markers to define changes:
*
* ------- SEARCH
* [Exact content to find in the original file]
* =======
* [Content to replace with]
* +++++++ REPLACE
*
* Behavior and Assumptions:
* 1. The file is processed chunk-by-chunk. Each chunk of `diffContent` may contain
* partial or complete SEARCH/REPLACE blocks. By calling this function with each
* incremental chunk (with `isFinal` indicating the last chunk), the final reconstructed
* file content is produced.
*
* 2. Matching Strategy (in order of attempt):
* a. Exact Match: First attempts to find the exact SEARCH block text in the original file
* b. Line-Trimmed Match: Falls back to line-by-line comparison ignoring leading/trailing whitespace
* c. Block Anchor Match: For blocks of 3+ lines, tries to match using first/last lines as anchors
* If all matching strategies fail, an error is thrown.
*
* 3. Empty SEARCH Section:
* - If SEARCH is empty and the original file is empty, this indicates creating a new file
* (pure insertion).
* - If SEARCH is empty and the original file is not empty, this indicates a complete
* file replacement (the entire original content is considered matched and replaced).
*
* 4. Applying Changes:
* - Before encountering the "=======" marker, lines are accumulated as search content.
* - After "=======" and before ">>>>>>> REPLACE", lines are accumulated as replacement content.
* - Once the block is complete (">>>>>>> REPLACE"), the matched section in the original
* file is replaced with the accumulated replacement lines, and the position in the original
* file is advanced.
*
* 5. Incremental Output:
* - As soon as the match location is found and we are in the REPLACE section, each new
* replacement line is appended to the result so that partial updates can be viewed
* incrementally.
*
* 6. Partial Markers:
* - If the final line of the chunk looks like it might be part of a marker but is not one
* of the known markers, it is removed. This prevents incomplete or partial markers
* from corrupting the output.
*
* 7. Finalization:
* - Once all chunks have been processed (when `isFinal` is true), any remaining original
* content after the last replaced section is appended to the result.
* - Trailing newlines are not forcibly added. The code tries to output exactly what is specified.
*
* Errors:
* - If the search block cannot be matched using any of the available matching strategies,
* an error is thrown.
*/
export async function constructNewFileContent(
diffContent: string,
originalContent: string,
isFinal: boolean,
version: "v1" | "v2" = "v1",
): Promise<string> {
const constructor = constructNewFileContentVersionMapping[version]
if (!constructor) {
throw new Error(`Invalid version '${version}' for file content constructor`)
}
return constructor(diffContent, originalContent, isFinal)
}
const constructNewFileContentVersionMapping: Record<
string,
(diffContent: string, originalContent: string, isFinal: boolean) => Promise<string>
> = {
v1: constructNewFileContentV1,
v2: constructNewFileContentV2,
} as const
async function constructNewFileContentV1(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let result = ""
let lastProcessedIndex = 0
let currentSearchContent = ""
let currentReplaceContent = ""
let inSearch = false
let inReplace = false
let searchMatchIndex = -1
let searchEndIndex = -1
// Track all replacements to handle out-of-order edits
let replacements: Array<{ start: number; end: number; content: string }> = []
let pendingOutOfOrderReplacement = false
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
!isSearchBlockStart(lastLine) &&
!isSearchBlockEnd(lastLine) &&
!isReplaceBlockEnd(lastLine)
) {
lines.pop()
}
for (const line of lines) {
if (isSearchBlockStart(line)) {
inSearch = true
currentSearchContent = ""
currentReplaceContent = ""
continue
}
if (isSearchBlockEnd(line)) {
inSearch = false
inReplace = true
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!currentSearchContent) {
// Empty search block
if (originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
searchMatchIndex = 0
searchEndIndex = 0
} else {
// ERROR: Empty search block with non-empty file indicates malformed SEARCH marker
throw new Error(
"Empty SEARCH block detected with non-empty file. This usually indicates a malformed SEARCH marker.\n" +
"Please ensure your SEARCH marker follows the correct format:\n" +
"- Use '------- SEARCH' (7+ dashes + space + SEARCH)\n",
)
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex)
if (exactIndex !== -1) {
searchMatchIndex = exactIndex
searchEndIndex = exactIndex + currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (lineMatch) {
;[searchMatchIndex, searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (blockMatch) {
;[searchMatchIndex, searchEndIndex] = blockMatch
} else {
// Last resort: search the entire file from the beginning
const fullFileIndex = originalContent.indexOf(currentSearchContent, 0)
if (fullFileIndex !== -1) {
// Found in the file - could be out of order
searchMatchIndex = fullFileIndex
searchEndIndex = fullFileIndex + currentSearchContent.length
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
} else {
throw new Error(
`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
}
// Check if this is an out-of-order replacement
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
// For in-order replacements, output everything up to the match location
if (!pendingOutOfOrderReplacement) {
result += originalContent.slice(lastProcessedIndex, searchMatchIndex)
}
continue
}
if (isReplaceBlockEnd(line)) {
// Finished one replace block
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset for next block
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
pendingOutOfOrderReplacement = false
continue
}
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (inSearch) {
currentSearchContent += line + "\n"
} else if (inReplace) {
currentReplaceContent += line + "\n"
// Only output replacement lines immediately for in-order replacements
if (searchMatchIndex !== -1 && !pendingOutOfOrderReplacement) {
result += line + "\n"
}
}
}
// If this is the final chunk, we need to apply all replacements and build the final result
if (isFinal) {
// Handle the case where we're still in replace mode when processing ends
// and this is the final chunk - treat it as if we encountered the REPLACE marker
if (inReplace && searchMatchIndex !== -1) {
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset state
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
pendingOutOfOrderReplacement = false
}
// end of handling missing replace marker
// Sort replacements by start position
replacements.sort((a, b) => a.start - b.start)
// Rebuild the entire result by applying all replacements
result = ""
let currentPos = 0
for (const replacement of replacements) {
// Add original content up to this replacement
result += originalContent.slice(currentPos, replacement.start)
// Add the replacement content
result += replacement.content
// Move position to after the replaced section
currentPos = replacement.end
}
// Add any remaining original content
result += originalContent.slice(currentPos)
}
return result
}
enum ProcessingState {
Idle = 0,
StateSearch = 1 << 0,
StateReplace = 1 << 1,
}
class NewFileContentConstructor {
private originalContent: string
private isFinal: boolean
private state: number
private pendingNonStandardLines: string[]
private result: string
private lastProcessedIndex: number
private currentSearchContent: string
private currentReplaceContent: string
private searchMatchIndex: number
private searchEndIndex: number
constructor(originalContent: string, isFinal: boolean) {
this.originalContent = originalContent
this.isFinal = isFinal
this.pendingNonStandardLines = []
this.result = ""
this.lastProcessedIndex = 0
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private resetForNextBlock() {
// Reset for next block
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private findLastMatchingLineIndex(regx: RegExp, lineLimit: number) {
for (let i = lineLimit; i > 0; ) {
i--
if (this.pendingNonStandardLines[i].match(regx)) {
return i
}
}
return -1
}
private updateProcessingState(newState: ProcessingState) {
const isValidTransition =
(this.state === ProcessingState.Idle && newState === ProcessingState.StateSearch) ||
(this.state === ProcessingState.StateSearch && newState === ProcessingState.StateReplace)
if (!isValidTransition) {
throw new Error(
`Invalid state transition.\n` +
"Valid transitions are:\n" +
"- Idle → StateSearch\n" +
"- StateSearch → StateReplace",
)
}
this.state |= newState
}
private isStateActive(state: ProcessingState): boolean {
return (this.state & state) === state
}
private activateReplaceState() {
this.updateProcessingState(ProcessingState.StateReplace)
}
private activateSearchState() {
this.updateProcessingState(ProcessingState.StateSearch)
this.currentSearchContent = ""
this.currentReplaceContent = ""
}
private isSearchingActive(): boolean {
return this.isStateActive(ProcessingState.StateSearch)
}
private isReplacingActive(): boolean {
return this.isStateActive(ProcessingState.StateReplace)
}
private hasPendingNonStandardLines(pendingNonStandardLineLimit: number): boolean {
return this.pendingNonStandardLines.length - pendingNonStandardLineLimit < this.pendingNonStandardLines.length
}
public processLine(line: string) {
this.internalProcessLine(line, true, this.pendingNonStandardLines.length)
}
public getResult() {
// If this is the final chunk, append any remaining original content
if (this.isFinal && this.lastProcessedIndex < this.originalContent.length) {
this.result += this.originalContent.slice(this.lastProcessedIndex)
}
if (this.isFinal && this.state !== ProcessingState.Idle) {
throw new Error("File processing incomplete - SEARCH/REPLACE operations still active during finalization")
}
return this.result
}
private internalProcessLine(
line: string,
canWritependingNonStandardLines: boolean,
pendingNonStandardLineLimit: number,
): number {
let removeLineCount = 0
if (isSearchBlockStart(line)) {
removeLineCount = this.trimPendingNonStandardTrailingEmptyLines(pendingNonStandardLineLimit)
if (removeLineCount > 0) {
pendingNonStandardLineLimit = pendingNonStandardLineLimit - removeLineCount
}
if (this.hasPendingNonStandardLines(pendingNonStandardLineLimit)) {
this.tryFixSearchReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateSearchState()
} else if (isSearchBlockEnd(line)) {
// 校验非标内容
if (!this.isSearchingActive()) {
this.tryFixSearchBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateReplaceState()
this.beforeReplace()
} else if (isReplaceBlockEnd(line)) {
if (!this.isReplacingActive()) {
this.tryFixReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.lastProcessedIndex = this.searchEndIndex
this.resetForNextBlock()
} else {
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (this.isReplacingActive()) {
this.currentReplaceContent += line + "\n"
// Output replacement lines immediately if we know the insertion point
if (this.searchMatchIndex !== -1) {
this.result += line + "\n"
}
} else if (this.isSearchingActive()) {
this.currentSearchContent += line + "\n"
} else {
let appendToPendingNonStandardLines = canWritependingNonStandardLines
if (appendToPendingNonStandardLines) {
// 处理非标内容
this.pendingNonStandardLines.push(line)
}
}
}
return removeLineCount
}
private beforeReplace() {
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!this.currentSearchContent) {
// Empty search block
if (this.originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
this.searchMatchIndex = 0
this.searchEndIndex = 0
} else {
// Complete file replacement scenario: treat the entire file as matched
this.searchMatchIndex = 0
this.searchEndIndex = this.originalContent.length
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = this.originalContent.indexOf(this.currentSearchContent, this.lastProcessedIndex)
if (exactIndex !== -1) {
this.searchMatchIndex = exactIndex
this.searchEndIndex = exactIndex + this.currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (lineMatch) {
;[this.searchMatchIndex, this.searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (blockMatch) {
;[this.searchMatchIndex, this.searchEndIndex] = blockMatch
} else {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
if (this.searchMatchIndex < this.lastProcessedIndex) {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...matched an incorrect content in the file.`,
)
}
// Output everything up to the match location
this.result += this.originalContent.slice(this.lastProcessedIndex, this.searchMatchIndex)
}
private tryFixSearchBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error("Invalid SEARCH/REPLACE block structure - no lines available to process")
}
let searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/
const searchTagIndex = this.findLastMatchingLineIndex(searchTagRegexp, lineLimit)
if (searchTagIndex !== -1) {
let fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit)
fixLines[0] = SEARCH_BLOCK_START
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, searchTagIndex)
}
} else {
throw new Error(
`Invalid REPLACE marker detected - could not find matching SEARCH block starting from line ${searchTagIndex + 1}`,
)
}
return removeLineCount
}
private tryFixReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceBeginTagRegexp = /^[=]{3,}$/
const replaceBeginTagIndex = this.findLastMatchingLineIndex(replaceBeginTagRegexp, lineLimit)
if (replaceBeginTagIndex !== -1) {
// // 校验非标内容
// if (!this.isSearchingActive()) {
// removeLineCount += this.tryFixSearchBlock(replaceBeginTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceBeginTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[0] = SEARCH_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceBeginTagIndex - removeLineCount)
}
} else {
throw new Error(`Malformed REPLACE block - missing valid separator after line ${replaceBeginTagIndex + 1}`)
}
return removeLineCount
}
private tryFixSearchReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/
const replaceEndTagIndex = this.findLastMatchingLineIndex(replaceEndTagRegexp, lineLimit)
const likeReplaceEndTag = replaceEndTagIndex === lineLimit - 1
if (likeReplaceEndTag) {
// // 校验非标内容
// if (!this.isReplacingActive()) {
// removeLineCount += this.tryFixReplaceBlock(replaceEndTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceEndTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[fixLines.length - 1] = REPLACE_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceEndTagIndex - removeLineCount)
}
} else {
throw new Error("Malformed SEARCH/REPLACE block structure: Missing valid closing REPLACE marker")
}
return removeLineCount
}
/**
* Removes trailing empty lines from the pendingNonStandardLines array
* @param lineLimit - The index to start checking from (exclusive).
* Removes empty lines from lineLimit-1 backwards.
* @returns The number of empty lines removed
*/
private trimPendingNonStandardTrailingEmptyLines(lineLimit: number): number {
let removedCount = 0
let i = Math.min(lineLimit, this.pendingNonStandardLines.length) - 1
while (i >= 0 && this.pendingNonStandardLines[i].trim() === "") {
this.pendingNonStandardLines.pop()
removedCount++
i--
}
return removedCount
}
}
export async function constructNewFileContentV2(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal)
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
lastLine !== SEARCH_BLOCK_START &&
lastLine !== SEARCH_BLOCK_END &&
lastLine !== REPLACE_BLOCK_END
) {
lines.pop()
}
for (const line of lines) {
newFileContentConstructor.processLine(line)
}
let result = newFileContentConstructor.getResult()
return result
}
@@ -0,0 +1,829 @@
const SEARCH_BLOCK_START = "------- SEARCH"
const SEARCH_BLOCK_END = "======="
const REPLACE_BLOCK_END = "+++++++ REPLACE"
const SEARCH_BLOCK_CHAR = "-"
const REPLACE_BLOCK_CHAR = "+"
const LEGACY_SEARCH_BLOCK_CHAR = "<"
const LEGACY_REPLACE_BLOCK_CHAR = ">"
// Replace the exact string constants with flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH>?$/
const LEGACY_SEARCH_BLOCK_START_REGEX = /^[<]{3,} SEARCH>?$/
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE>?$/
const LEGACY_REPLACE_BLOCK_END_REGEX = /^[>]{3,} REPLACE>?$/
// Helper functions to check if a line matches the flexible patterns
function isSearchBlockStart(line: string): boolean {
return SEARCH_BLOCK_START_REGEX.test(line) || LEGACY_SEARCH_BLOCK_START_REGEX.test(line)
}
function isSearchBlockEnd(line: string): boolean {
return SEARCH_BLOCK_END_REGEX.test(line)
}
function isReplaceBlockEnd(line: string): boolean {
return REPLACE_BLOCK_END_REGEX.test(line) || LEGACY_REPLACE_BLOCK_END_REGEX.test(line)
}
/**
* Attempts a line-trimmed fallback match for the given search content in the original content.
* It tries to match `searchContent` lines against a block of lines in `originalContent` starting
* from `lastProcessedIndex`. Lines are matched by trimming leading/trailing whitespace and ensuring
* they are identical afterwards.
*
* Returns [matchIndexStart, matchIndexEnd] if found, or false if not found.
*/
function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
// Split both contents into lines
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Trim trailing empty line if exists (from the trailing \n in searchContent)
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1 // +1 for \n
startLineNum++
}
// For each possible starting position in original content
for (let i = startLineNum; i <= originalLines.length - searchLines.length; i++) {
let matches = true
// Try to match all search lines from this position
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim()
const searchTrimmed = searchLines[j].trim()
if (originalTrimmed !== searchTrimmed) {
matches = false
break
}
}
// If we found a match, calculate the exact character positions
if (matches) {
// Find start character index
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1 // +1 for \n
}
// Find end character index
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length + 1 // +1 for \n
}
return [matchStartIndex, matchEndIndex]
}
}
return false
}
/**
* Attempts to match blocks of code by using the first and last lines as anchors.
* This is a third-tier fallback strategy that helps match blocks where we can identify
* the correct location by matching the beginning and end, even if the exact content
* differs slightly.
*
* The matching strategy:
* 1. Only attempts to match blocks of 3 or more lines to avoid false positives
* 2. Extracts from the search content:
* - First line as the "start anchor"
* - Last line as the "end anchor"
* 3. For each position in the original content:
* - Checks if the next line matches the start anchor
* - If it does, jumps ahead by the search block size
* - Checks if that line matches the end anchor
* - All comparisons are done after trimming whitespace
*
* This approach is particularly useful for matching blocks of code where:
* - The exact content might have minor differences
* - The beginning and end of the block are distinctive enough to serve as anchors
* - The overall structure (number of lines) remains the same
*
* @param originalContent - The full content of the original file
* @param searchContent - The content we're trying to find in the original file
* @param startIndex - The character index in originalContent where to start searching
* @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise
*/
function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Only use this approach for blocks of 3+ lines
if (searchLines.length < 3) {
return false
}
// Trim trailing empty line if exists
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
const firstLineSearch = searchLines[0].trim()
const lastLineSearch = searchLines[searchLines.length - 1].trim()
const searchBlockSize = searchLines.length
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1
startLineNum++
}
// Look for matching start and end anchors
for (let i = startLineNum; i <= originalLines.length - searchBlockSize; i++) {
// Check if first line matches
if (originalLines[i].trim() !== firstLineSearch) {
continue
}
// Check if last line matches at the expected position
if (originalLines[i + searchBlockSize - 1].trim() !== lastLineSearch) {
continue
}
// Calculate exact character positions
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1
}
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchBlockSize; k++) {
matchEndIndex += originalLines[i + k].length + 1
}
return [matchStartIndex, matchEndIndex]
}
return false
}
/**
* This function reconstructs the file content by applying a streamed diff (in a
* specialized SEARCH/REPLACE block format) to the original file content. It is designed
* to handle both incremental updates and the final resulting file after all chunks have
* been processed.
*
* The diff format is a custom structure that uses three markers to define changes:
*
* ------- SEARCH
* [Exact content to find in the original file]
* =======
* [Content to replace with]
* +++++++ REPLACE
*
* Behavior and Assumptions:
* 1. The file is processed chunk-by-chunk. Each chunk of `diffContent` may contain
* partial or complete SEARCH/REPLACE blocks. By calling this function with each
* incremental chunk (with `isFinal` indicating the last chunk), the final reconstructed
* file content is produced.
*
* 2. Matching Strategy (in order of attempt):
* a. Exact Match: First attempts to find the exact SEARCH block text in the original file
* b. Line-Trimmed Match: Falls back to line-by-line comparison ignoring leading/trailing whitespace
* c. Block Anchor Match: For blocks of 3+ lines, tries to match using first/last lines as anchors
* If all matching strategies fail, an error is thrown.
*
* 3. Empty SEARCH Section:
* - If SEARCH is empty and the original file is empty, this indicates creating a new file
* (pure insertion).
* - If SEARCH is empty and the original file is not empty, this indicates a complete
* file replacement (the entire original content is considered matched and replaced).
*
* 4. Applying Changes:
* - Before encountering the "=======" marker, lines are accumulated as search content.
* - After "=======" and before ">>>>>>> REPLACE", lines are accumulated as replacement content.
* - Once the block is complete (">>>>>>> REPLACE"), the matched section in the original
* file is replaced with the accumulated replacement lines, and the position in the original
* file is advanced.
*
* 5. Incremental Output:
* - As soon as the match location is found and we are in the REPLACE section, each new
* replacement line is appended to the result so that partial updates can be viewed
* incrementally.
*
* 6. Partial Markers:
* - If the final line of the chunk looks like it might be part of a marker but is not one
* of the known markers, it is removed. This prevents incomplete or partial markers
* from corrupting the output.
*
* 7. Finalization:
* - Once all chunks have been processed (when `isFinal` is true), any remaining original
* content after the last replaced section is appended to the result.
* - Trailing newlines are not forcibly added. The code tries to output exactly what is specified.
*
* Errors:
* - If the search block cannot be matched using any of the available matching strategies,
* an error is thrown.
*/
export async function constructNewFileContent(
diffContent: string,
originalContent: string,
isFinal: boolean,
version: "v1" | "v2" = "v1",
): Promise<string> {
const constructor = constructNewFileContentVersionMapping[version]
if (!constructor) {
throw new Error(`Invalid version '${version}' for file content constructor`)
}
return constructor(diffContent, originalContent, isFinal)
}
const constructNewFileContentVersionMapping: Record<
string,
(diffContent: string, originalContent: string, isFinal: boolean) => Promise<string>
> = {
v1: constructNewFileContentV1,
v2: constructNewFileContentV2,
} as const
async function constructNewFileContentV1(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let result = ""
let lastProcessedIndex = 0
let currentSearchContent = ""
let currentReplaceContent = ""
let inSearch = false
let inReplace = false
let searchMatchIndex = -1
let searchEndIndex = -1
// Track all replacements to handle out-of-order edits
let replacements: Array<{ start: number; end: number; content: string }> = []
let pendingOutOfOrderReplacement = false
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
!isSearchBlockStart(lastLine) &&
!isSearchBlockEnd(lastLine) &&
!isReplaceBlockEnd(lastLine)
) {
lines.pop()
}
for (const line of lines) {
if (isSearchBlockStart(line)) {
inSearch = true
currentSearchContent = ""
currentReplaceContent = ""
continue
}
if (isSearchBlockEnd(line)) {
inSearch = false
inReplace = true
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!currentSearchContent) {
// Empty search block
if (originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
searchMatchIndex = 0
searchEndIndex = 0
} else {
// ERROR: Empty search block with non-empty file indicates malformed SEARCH marker
throw new Error(
"Empty SEARCH block detected with non-empty file. This usually indicates a malformed SEARCH marker.\n" +
"Please ensure your SEARCH marker follows the correct format:\n" +
"- Use '------- SEARCH' (7+ dashes + space + SEARCH)\n",
)
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex)
if (exactIndex !== -1) {
searchMatchIndex = exactIndex
searchEndIndex = exactIndex + currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (lineMatch) {
;[searchMatchIndex, searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (blockMatch) {
;[searchMatchIndex, searchEndIndex] = blockMatch
} else {
// Last resort: search the entire file from the beginning
const fullFileIndex = originalContent.indexOf(currentSearchContent, 0)
if (fullFileIndex !== -1) {
// Found in the file - could be out of order
searchMatchIndex = fullFileIndex
searchEndIndex = fullFileIndex + currentSearchContent.length
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
} else {
throw new Error(
`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
}
// Check if this is an out-of-order replacement
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
// For in-order replacements, output everything up to the match location
if (!pendingOutOfOrderReplacement) {
result += originalContent.slice(lastProcessedIndex, searchMatchIndex)
}
continue
}
if (isReplaceBlockEnd(line)) {
// Finished one replace block
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset for next block
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
pendingOutOfOrderReplacement = false
continue
}
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (inSearch) {
currentSearchContent += line + "\n"
} else if (inReplace) {
currentReplaceContent += line + "\n"
// Only output replacement lines immediately for in-order replacements
if (searchMatchIndex !== -1 && !pendingOutOfOrderReplacement) {
result += line + "\n"
}
}
}
// If this is the final chunk, we need to apply all replacements and build the final result
if (isFinal) {
// Handle the case where we're still in replace mode when processing ends
// and this is the final chunk - treat it as if we encountered the REPLACE marker
if (inReplace && searchMatchIndex !== -1) {
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset state
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
pendingOutOfOrderReplacement = false
}
// end of handling missing replace marker
// Sort replacements by start position
replacements.sort((a, b) => a.start - b.start)
// Rebuild the entire result by applying all replacements
result = ""
let currentPos = 0
for (const replacement of replacements) {
// Add original content up to this replacement
result += originalContent.slice(currentPos, replacement.start)
// Add the replacement content
result += replacement.content
// Move position to after the replaced section
currentPos = replacement.end
}
// Add any remaining original content
result += originalContent.slice(currentPos)
}
return result
}
enum ProcessingState {
Idle = 0,
StateSearch = 1 << 0,
StateReplace = 1 << 1,
}
class NewFileContentConstructor {
private originalContent: string
private isFinal: boolean
private state: number
private pendingNonStandardLines: string[]
private result: string
private lastProcessedIndex: number
private currentSearchContent: string
private currentReplaceContent: string
private searchMatchIndex: number
private searchEndIndex: number
constructor(originalContent: string, isFinal: boolean) {
this.originalContent = originalContent
this.isFinal = isFinal
this.pendingNonStandardLines = []
this.result = ""
this.lastProcessedIndex = 0
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private resetForNextBlock() {
// Reset for next block
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private findLastMatchingLineIndex(regx: RegExp, lineLimit: number) {
for (let i = lineLimit; i > 0; ) {
i--
if (this.pendingNonStandardLines[i].match(regx)) {
return i
}
}
return -1
}
private updateProcessingState(newState: ProcessingState) {
const isValidTransition =
(this.state === ProcessingState.Idle && newState === ProcessingState.StateSearch) ||
(this.state === ProcessingState.StateSearch && newState === ProcessingState.StateReplace)
if (!isValidTransition) {
throw new Error(
`Invalid state transition.\n` +
"Valid transitions are:\n" +
"- Idle → StateSearch\n" +
"- StateSearch → StateReplace",
)
}
this.state |= newState
}
private isStateActive(state: ProcessingState): boolean {
return (this.state & state) === state
}
private activateReplaceState() {
this.updateProcessingState(ProcessingState.StateReplace)
}
private activateSearchState() {
this.updateProcessingState(ProcessingState.StateSearch)
this.currentSearchContent = ""
this.currentReplaceContent = ""
}
private isSearchingActive(): boolean {
return this.isStateActive(ProcessingState.StateSearch)
}
private isReplacingActive(): boolean {
return this.isStateActive(ProcessingState.StateReplace)
}
private hasPendingNonStandardLines(pendingNonStandardLineLimit: number): boolean {
return this.pendingNonStandardLines.length - pendingNonStandardLineLimit < this.pendingNonStandardLines.length
}
public processLine(line: string) {
this.internalProcessLine(line, true, this.pendingNonStandardLines.length)
}
public getResult() {
// If this is the final chunk, append any remaining original content
if (this.isFinal && this.lastProcessedIndex < this.originalContent.length) {
this.result += this.originalContent.slice(this.lastProcessedIndex)
}
if (this.isFinal && this.state !== ProcessingState.Idle) {
throw new Error("File processing incomplete - SEARCH/REPLACE operations still active during finalization")
}
return this.result
}
private internalProcessLine(
line: string,
canWritependingNonStandardLines: boolean,
pendingNonStandardLineLimit: number,
): number {
let removeLineCount = 0
if (isSearchBlockStart(line)) {
removeLineCount = this.trimPendingNonStandardTrailingEmptyLines(pendingNonStandardLineLimit)
if (removeLineCount > 0) {
pendingNonStandardLineLimit = pendingNonStandardLineLimit - removeLineCount
}
if (this.hasPendingNonStandardLines(pendingNonStandardLineLimit)) {
this.tryFixSearchReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateSearchState()
} else if (isSearchBlockEnd(line)) {
// 校验非标内容
if (!this.isSearchingActive()) {
this.tryFixSearchBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateReplaceState()
this.beforeReplace()
} else if (isReplaceBlockEnd(line)) {
if (!this.isReplacingActive()) {
this.tryFixReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.lastProcessedIndex = this.searchEndIndex
this.resetForNextBlock()
} else {
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (this.isReplacingActive()) {
this.currentReplaceContent += line + "\n"
// Output replacement lines immediately if we know the insertion point
if (this.searchMatchIndex !== -1) {
this.result += line + "\n"
}
} else if (this.isSearchingActive()) {
this.currentSearchContent += line + "\n"
} else {
let appendToPendingNonStandardLines = canWritependingNonStandardLines
if (appendToPendingNonStandardLines) {
// 处理非标内容
this.pendingNonStandardLines.push(line)
}
}
}
return removeLineCount
}
private beforeReplace() {
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!this.currentSearchContent) {
// Empty search block
if (this.originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
this.searchMatchIndex = 0
this.searchEndIndex = 0
} else {
// Complete file replacement scenario: treat the entire file as matched
this.searchMatchIndex = 0
this.searchEndIndex = this.originalContent.length
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = this.originalContent.indexOf(this.currentSearchContent, this.lastProcessedIndex)
if (exactIndex !== -1) {
this.searchMatchIndex = exactIndex
this.searchEndIndex = exactIndex + this.currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (lineMatch) {
;[this.searchMatchIndex, this.searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (blockMatch) {
;[this.searchMatchIndex, this.searchEndIndex] = blockMatch
} else {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
if (this.searchMatchIndex < this.lastProcessedIndex) {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...matched an incorrect content in the file.`,
)
}
// Output everything up to the match location
this.result += this.originalContent.slice(this.lastProcessedIndex, this.searchMatchIndex)
}
private tryFixSearchBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error("Invalid SEARCH/REPLACE block structure - no lines available to process")
}
let searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/
const searchTagIndex = this.findLastMatchingLineIndex(searchTagRegexp, lineLimit)
if (searchTagIndex !== -1) {
let fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit)
fixLines[0] = SEARCH_BLOCK_START
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, searchTagIndex)
}
} else {
throw new Error(
`Invalid REPLACE marker detected - could not find matching SEARCH block starting from line ${searchTagIndex + 1}`,
)
}
return removeLineCount
}
private tryFixReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceBeginTagRegexp = /^[=]{3,}$/
const replaceBeginTagIndex = this.findLastMatchingLineIndex(replaceBeginTagRegexp, lineLimit)
if (replaceBeginTagIndex !== -1) {
// // 校验非标内容
// if (!this.isSearchingActive()) {
// removeLineCount += this.tryFixSearchBlock(replaceBeginTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceBeginTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[0] = SEARCH_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceBeginTagIndex - removeLineCount)
}
} else {
throw new Error(`Malformed REPLACE block - missing valid separator after line ${replaceBeginTagIndex + 1}`)
}
return removeLineCount
}
private tryFixSearchReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/
const replaceEndTagIndex = this.findLastMatchingLineIndex(replaceEndTagRegexp, lineLimit)
const likeReplaceEndTag = replaceEndTagIndex === lineLimit - 1
if (likeReplaceEndTag) {
// // 校验非标内容
// if (!this.isReplacingActive()) {
// removeLineCount += this.tryFixReplaceBlock(replaceEndTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceEndTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[fixLines.length - 1] = REPLACE_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceEndTagIndex - removeLineCount)
}
} else {
throw new Error("Malformed SEARCH/REPLACE block structure: Missing valid closing REPLACE marker")
}
return removeLineCount
}
/**
* Removes trailing empty lines from the pendingNonStandardLines array
* @param lineLimit - The index to start checking from (exclusive).
* Removes empty lines from lineLimit-1 backwards.
* @returns The number of empty lines removed
*/
private trimPendingNonStandardTrailingEmptyLines(lineLimit: number): number {
let removedCount = 0
let i = Math.min(lineLimit, this.pendingNonStandardLines.length) - 1
while (i >= 0 && this.pendingNonStandardLines[i].trim() === "") {
this.pendingNonStandardLines.pop()
removedCount++
i--
}
return removedCount
}
}
export async function constructNewFileContentV2(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal)
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
lastLine !== SEARCH_BLOCK_START &&
lastLine !== SEARCH_BLOCK_END &&
lastLine !== REPLACE_BLOCK_END
) {
lines.pop()
}
for (const line of lines) {
newFileContentConstructor.processLine(line)
}
let result = newFileContentConstructor.getResult()
return result
}
@@ -0,0 +1,960 @@
const SEARCH_BLOCK_START = "------- SEARCH"
const SEARCH_BLOCK_END = "======="
const REPLACE_BLOCK_END = "+++++++ REPLACE"
const SEARCH_BLOCK_CHAR = "-"
const REPLACE_BLOCK_CHAR = "+"
const LEGACY_SEARCH_BLOCK_CHAR = "<"
const LEGACY_REPLACE_BLOCK_CHAR = ">"
// Replace the exact string constants with flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH>?$/
const LEGACY_SEARCH_BLOCK_START_REGEX = /^[<]{3,} SEARCH>?$/
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE>?$/
const LEGACY_REPLACE_BLOCK_END_REGEX = /^[>]{3,} REPLACE>?$/
// Similarity thresholds for block anchor fallback matching
const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.0
const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.0
/**
* Levenshtein distance algorithm implementation
*/
function levenshtein(a: string, b: string): number {
// Handle empty strings
if (a === "" || b === "") {
return Math.max(a.length, b.length)
}
const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
)
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
}
}
return matrix[a.length][b.length]
}
// Helper functions to check if a line matches the flexible patterns
function isSearchBlockStart(line: string): boolean {
return SEARCH_BLOCK_START_REGEX.test(line) || LEGACY_SEARCH_BLOCK_START_REGEX.test(line)
}
function isSearchBlockEnd(line: string): boolean {
return SEARCH_BLOCK_END_REGEX.test(line)
}
function isReplaceBlockEnd(line: string): boolean {
return REPLACE_BLOCK_END_REGEX.test(line) || LEGACY_REPLACE_BLOCK_END_REGEX.test(line)
}
/**
* Attempts a line-trimmed fallback match for the given search content in the original content.
* It tries to match `searchContent` lines against a block of lines in `originalContent` starting
* from `lastProcessedIndex`. Lines are matched by trimming leading/trailing whitespace and ensuring
* they are identical afterwards.
*
* Returns [matchIndexStart, matchIndexEnd] if found, or false if not found.
*/
function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
// Split both contents into lines
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Trim trailing empty line if exists (from the trailing \n in searchContent)
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1 // +1 for \n
startLineNum++
}
// For each possible starting position in original content
for (let i = startLineNum; i <= originalLines.length - searchLines.length; i++) {
let matches = true
// Try to match all search lines from this position
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim()
const searchTrimmed = searchLines[j].trim()
if (originalTrimmed !== searchTrimmed) {
matches = false
break
}
}
// If we found a match, calculate the exact character positions
if (matches) {
// Find start character index
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1 // +1 for \n
}
// Find end character index
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length + 1 // +1 for \n
}
return [matchStartIndex, matchEndIndex]
}
}
return false
}
/**
* Attempts to match blocks of code by using the first and last lines as anchors,
* with similarity checking to prevent false positives.
* This is a third-tier fallback strategy that helps match blocks where we can identify
* the correct location by matching the beginning and end, even if the exact content
* differs slightly.
*
* The matching strategy:
* 1. Only attempts to match blocks of 3 or more lines to avoid false positives
* 2. Extracts from the search content:
* - First line as the "start anchor"
* - Last line as the "end anchor"
* 3. Collects all candidate positions where both anchors match
* 4. Uses levenshtein distance to calculate similarity of middle lines
* 5. Returns match only if similarity meets threshold requirements
*
* This approach is particularly useful for matching blocks of code where:
* - The exact content might have minor differences
* - The beginning and end of the block are distinctive enough to serve as anchors
* - The overall structure (number of lines) remains the same
* - The middle content is reasonably similar (prevents false positives)
*
* @param originalContent - The full content of the original file
* @param searchContent - The content we're trying to find in the original file
* @param startIndex - The character index in originalContent where to start searching
* @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise
*/
function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number, number] | false {
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
// Only use this approach for blocks of 3+ lines
if (searchLines.length < 3) {
return false
}
// Trim trailing empty line if exists
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop()
}
const firstLineSearch = searchLines[0].trim()
const lastLineSearch = searchLines[searchLines.length - 1].trim()
const searchBlockSize = searchLines.length
// Find the line number where startIndex falls
let startLineNum = 0
let currentIndex = 0
while (currentIndex < startIndex && startLineNum < originalLines.length) {
currentIndex += originalLines[startLineNum].length + 1
startLineNum++
}
// Collect all candidate positions
const candidates: number[] = []
for (let i = startLineNum; i <= originalLines.length - searchBlockSize; i++) {
if (originalLines[i].trim() === firstLineSearch && originalLines[i + searchBlockSize - 1].trim() === lastLineSearch) {
candidates.push(i)
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return false
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const i = candidates[0]
let similarity = 0
let linesToCheck = searchBlockSize - 2
for (let j = 1; j < searchBlockSize - 1; j++) {
const originalLine = originalLines[i + j].trim()
const searchLine = searchLines[j].trim()
const maxLen = Math.max(originalLine.length, searchLine.length)
if (maxLen === 0) {
continue
}
const distance = levenshtein(originalLine, searchLine)
similarity += (1 - distance / maxLen) / linesToCheck
// Exit early when threshold is reached
if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {
break
}
}
if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1
}
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchBlockSize; k++) {
matchEndIndex += originalLines[i + k].length + 1
}
return [matchStartIndex, matchEndIndex, similarity]
}
return false
}
// Calculate similarity for multiple candidates
let bestMatchIndex = -1
let maxSimilarity = -1
for (const i of candidates) {
let similarity = 0
for (let j = 1; j < searchBlockSize - 1; j++) {
const originalLine = originalLines[i + j].trim()
const searchLine = searchLines[j].trim()
const maxLen = Math.max(originalLine.length, searchLine.length)
if (maxLen === 0) {
continue
}
const distance = levenshtein(originalLine, searchLine)
similarity += 1 - distance / maxLen
}
similarity /= searchBlockSize - 2 // Average similarity
if (similarity > maxSimilarity) {
maxSimilarity = similarity
bestMatchIndex = i
}
}
// Threshold judgment
if (maxSimilarity >= MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD) {
const i = bestMatchIndex
let matchStartIndex = 0
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1
}
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchBlockSize; k++) {
matchEndIndex += originalLines[i + k].length + 1
}
return [matchStartIndex, matchEndIndex, maxSimilarity]
}
return false
}
/**
* This function reconstructs the file content by applying a streamed diff (in a
* specialized SEARCH/REPLACE block format) to the original file content. It is designed
* to handle both incremental updates and the final resulting file after all chunks have
* been processed.
*
* The diff format is a custom structure that uses three markers to define changes:
*
* ------- SEARCH
* [Exact content to find in the original file]
* =======
* [Content to replace with]
* +++++++ REPLACE
*
* Behavior and Assumptions:
* 1. The file is processed chunk-by-chunk. Each chunk of `diffContent` may contain
* partial or complete SEARCH/REPLACE blocks. By calling this function with each
* incremental chunk (with `isFinal` indicating the last chunk), the final reconstructed
* file content is produced.
*
* 2. Matching Strategy (in order of attempt):
* a. Exact Match: First attempts to find the exact SEARCH block text in the original file
* b. Line-Trimmed Match: Falls back to line-by-line comparison ignoring leading/trailing whitespace
* c. Block Anchor Match: For blocks of 3+ lines, tries to match using first/last lines as anchors
* If all matching strategies fail, an error is thrown.
*
* 3. Empty SEARCH Section:
* - If SEARCH is empty and the original file is empty, this indicates creating a new file
* (pure insertion).
* - If SEARCH is empty and the original file is not empty, this indicates a complete
* file replacement (the entire original content is considered matched and replaced).
*
* 4. Applying Changes:
* - Before encountering the "=======" marker, lines are accumulated as search content.
* - After "=======" and before ">>>>>>> REPLACE", lines are accumulated as replacement content.
* - Once the block is complete (">>>>>>> REPLACE"), the matched section in the original
* file is replaced with the accumulated replacement lines, and the position in the original
* file is advanced.
*
* 5. Incremental Output:
* - As soon as the match location is found and we are in the REPLACE section, each new
* replacement line is appended to the result so that partial updates can be viewed
* incrementally.
*
* 6. Partial Markers:
* - If the final line of the chunk looks like it might be part of a marker but is not one
* of the known markers, it is removed. This prevents incomplete or partial markers
* from corrupting the output.
*
* 7. Finalization:
* - Once all chunks have been processed (when `isFinal` is true), any remaining original
* content after the last replaced section is appended to the result.
* - Trailing newlines are not forcibly added. The code tries to output exactly what is specified.
*
* Errors:
* - If the search block cannot be matched using any of the available matching strategies,
* an error is thrown.
*/
export async function constructNewFileContent(
diffContent: string,
originalContent: string,
isFinal: boolean,
version: "v1" | "v2" = "v1",
): Promise<any> {
const constructor = constructNewFileContentVersionMapping[version]
if (!constructor) {
throw new Error(`Invalid version '${version}' for file content constructor`)
}
return constructor(diffContent, originalContent, isFinal)
}
const constructNewFileContentVersionMapping: Record<
string,
(diffContent: string, originalContent: string, isFinal: boolean) => Promise<any>
> = {
v1: constructNewFileContentV1,
v2: constructNewFileContentV2,
} as const
async function constructNewFileContentV1(diffContent: string, originalContent: string, isFinal: boolean): Promise<{
content: string;
replacements: Array<{
start: number;
end: number;
content: string;
method: string;
similarity: number;
searchContent: string;
matchedText: string;
}>;
}> {
let result = ""
let lastProcessedIndex = 0
let currentSearchContent = ""
let currentReplaceContent = ""
let inSearch = false
let inReplace = false
let searchMatchIndex = -1
let searchEndIndex = -1
let matchMethod = ""
let similarityScore = -1.0
// Track all replacements to handle out-of-order edits
let replacements: Array<{
start: number;
end: number;
content: string;
method: string;
similarity: number;
searchContent: string;
matchedText: string;
}> = []
let pendingOutOfOrderReplacement = false
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
!isSearchBlockStart(lastLine) &&
!isSearchBlockEnd(lastLine) &&
!isReplaceBlockEnd(lastLine)
) {
lines.pop()
}
for (const line of lines) {
if (isSearchBlockStart(line)) {
inSearch = true
currentSearchContent = ""
currentReplaceContent = ""
continue
}
if (isSearchBlockEnd(line)) {
inSearch = false
inReplace = true
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!currentSearchContent) {
// Empty search block
if (originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
searchMatchIndex = 0
searchEndIndex = 0
matchMethod = "empty_new_file"
} else {
// ERROR: Empty search block with non-empty file indicates malformed SEARCH marker
throw new Error(
"Empty SEARCH block detected with non-empty file. This usually indicates a malformed SEARCH marker.\n" +
"Please ensure your SEARCH marker follows the correct format:\n" +
"- Use '------- SEARCH' (7+ dashes + space + SEARCH)\n",
)
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex)
if (exactIndex !== -1) {
searchMatchIndex = exactIndex
searchEndIndex = exactIndex + currentSearchContent.length
matchMethod = "exact_match"
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (lineMatch) {
;[searchMatchIndex, searchEndIndex] = lineMatch
matchMethod = "line_trimmed_fallback"
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (blockMatch) {
;[searchMatchIndex, searchEndIndex, similarityScore] = blockMatch
matchMethod = "block_anchor_fallback"
} else {
// Last resort: search the entire file from the beginning
const fullFileIndex = originalContent.indexOf(currentSearchContent, 0)
if (fullFileIndex !== -1) {
// Found in the file - could be out of order
searchMatchIndex = fullFileIndex
searchEndIndex = fullFileIndex + currentSearchContent.length
matchMethod = "full_file_search"
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
} else {
throw new Error(
`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
}
// Check if this is an out-of-order replacement
if (searchMatchIndex < lastProcessedIndex) {
pendingOutOfOrderReplacement = true
}
// For in-order replacements, output everything up to the match location
if (!pendingOutOfOrderReplacement) {
result += originalContent.slice(lastProcessedIndex, searchMatchIndex)
}
continue
}
if (isReplaceBlockEnd(line)) {
// Finished one replace block
if (searchMatchIndex === -1) {
throw new Error(
`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...is malformatted.`,
)
}
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
method: matchMethod,
similarity: similarityScore,
searchContent: currentSearchContent,
matchedText: originalContent.slice(searchMatchIndex, searchEndIndex),
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset for next block
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
similarityScore = -1.0
pendingOutOfOrderReplacement = false
continue
}
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (inSearch) {
currentSearchContent += line + "\n"
} else if (inReplace) {
currentReplaceContent += line + "\n"
// Only output replacement lines immediately for in-order replacements
if (searchMatchIndex !== -1 && !pendingOutOfOrderReplacement) {
result += line + "\n"
}
}
}
// If this is the final chunk, we need to apply all replacements and build the final result
if (isFinal) {
// Handle the case where we're still in replace mode when processing ends
// and this is the final chunk - treat it as if we encountered the REPLACE marker
if (inReplace && searchMatchIndex !== -1) {
// Store this replacement
replacements.push({
start: searchMatchIndex,
end: searchEndIndex,
content: currentReplaceContent,
method: matchMethod,
similarity: similarityScore,
searchContent: currentSearchContent,
matchedText: originalContent.slice(searchMatchIndex, searchEndIndex),
})
// If this was an in-order replacement, advance lastProcessedIndex
if (!pendingOutOfOrderReplacement) {
lastProcessedIndex = searchEndIndex
}
// Reset state
inSearch = false
inReplace = false
currentSearchContent = ""
currentReplaceContent = ""
searchMatchIndex = -1
searchEndIndex = -1
pendingOutOfOrderReplacement = false
}
// end of handling missing replace marker
// Sort replacements by start position
replacements.sort((a, b) => a.start - b.start)
// Rebuild the entire result by applying all replacements
result = ""
let currentPos = 0
for (const replacement of replacements) {
// Add original content up to this replacement
result += originalContent.slice(currentPos, replacement.start)
// Add the replacement content
result += replacement.content
// Move position to after the replaced section
currentPos = replacement.end
}
// Add any remaining original content
result += originalContent.slice(currentPos)
}
// For testing - return debug info
return {
content: result,
replacements: replacements
}
}
enum ProcessingState {
Idle = 0,
StateSearch = 1 << 0,
StateReplace = 1 << 1,
}
class NewFileContentConstructor {
private originalContent: string
private isFinal: boolean
private state: number
private pendingNonStandardLines: string[]
private result: string
private lastProcessedIndex: number
private currentSearchContent: string
private currentReplaceContent: string
private searchMatchIndex: number
private searchEndIndex: number
constructor(originalContent: string, isFinal: boolean) {
this.originalContent = originalContent
this.isFinal = isFinal
this.pendingNonStandardLines = []
this.result = ""
this.lastProcessedIndex = 0
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private resetForNextBlock() {
// Reset for next block
this.state = ProcessingState.Idle
this.currentSearchContent = ""
this.currentReplaceContent = ""
this.searchMatchIndex = -1
this.searchEndIndex = -1
}
private findLastMatchingLineIndex(regx: RegExp, lineLimit: number) {
for (let i = lineLimit; i > 0; ) {
i--
if (this.pendingNonStandardLines[i].match(regx)) {
return i
}
}
return -1
}
private updateProcessingState(newState: ProcessingState) {
const isValidTransition =
(this.state === ProcessingState.Idle && newState === ProcessingState.StateSearch) ||
(this.state === ProcessingState.StateSearch && newState === ProcessingState.StateReplace)
if (!isValidTransition) {
throw new Error(
`Invalid state transition.\n` +
"Valid transitions are:\n" +
"- Idle → StateSearch\n" +
"- StateSearch → StateReplace",
)
}
this.state |= newState
}
private isStateActive(state: ProcessingState): boolean {
return (this.state & state) === state
}
private activateReplaceState() {
this.updateProcessingState(ProcessingState.StateReplace)
}
private activateSearchState() {
this.updateProcessingState(ProcessingState.StateSearch)
this.currentSearchContent = ""
this.currentReplaceContent = ""
}
private isSearchingActive(): boolean {
return this.isStateActive(ProcessingState.StateSearch)
}
private isReplacingActive(): boolean {
return this.isStateActive(ProcessingState.StateReplace)
}
private hasPendingNonStandardLines(pendingNonStandardLineLimit: number): boolean {
return this.pendingNonStandardLines.length - pendingNonStandardLineLimit < this.pendingNonStandardLines.length
}
public processLine(line: string) {
this.internalProcessLine(line, true, this.pendingNonStandardLines.length)
}
public getResult() {
// If this is the final chunk, append any remaining original content
if (this.isFinal && this.lastProcessedIndex < this.originalContent.length) {
this.result += this.originalContent.slice(this.lastProcessedIndex)
}
if (this.isFinal && this.state !== ProcessingState.Idle) {
throw new Error("File processing incomplete - SEARCH/REPLACE operations still active during finalization")
}
return this.result
}
private internalProcessLine(
line: string,
canWritependingNonStandardLines: boolean,
pendingNonStandardLineLimit: number,
): number {
let removeLineCount = 0
if (isSearchBlockStart(line)) {
removeLineCount = this.trimPendingNonStandardTrailingEmptyLines(pendingNonStandardLineLimit)
if (removeLineCount > 0) {
pendingNonStandardLineLimit = pendingNonStandardLineLimit - removeLineCount
}
if (this.hasPendingNonStandardLines(pendingNonStandardLineLimit)) {
this.tryFixSearchReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateSearchState()
} else if (isSearchBlockEnd(line)) {
// 校验非标内容
if (!this.isSearchingActive()) {
this.tryFixSearchBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.activateReplaceState()
this.beforeReplace()
} else if (isReplaceBlockEnd(line)) {
if (!this.isReplacingActive()) {
this.tryFixReplaceBlock(pendingNonStandardLineLimit)
canWritependingNonStandardLines && (this.pendingNonStandardLines.length = 0)
}
this.lastProcessedIndex = this.searchEndIndex
this.resetForNextBlock()
} else {
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (this.isReplacingActive()) {
this.currentReplaceContent += line + "\n"
// Output replacement lines immediately if we know the insertion point
if (this.searchMatchIndex !== -1) {
this.result += line + "\n"
}
} else if (this.isSearchingActive()) {
this.currentSearchContent += line + "\n"
} else {
let appendToPendingNonStandardLines = canWritependingNonStandardLines
if (appendToPendingNonStandardLines) {
// 处理非标内容
this.pendingNonStandardLines.push(line)
}
}
}
return removeLineCount
}
private beforeReplace() {
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!this.currentSearchContent) {
// Empty search block
if (this.originalContent.length === 0) {
// New file scenario: nothing to match, just start inserting
this.searchMatchIndex = 0
this.searchEndIndex = 0
} else {
// Complete file replacement scenario: treat the entire file as matched
this.searchMatchIndex = 0
this.searchEndIndex = this.originalContent.length
}
} else {
// Add check for inefficient full-file search
// if (currentSearchContent.trim() === originalContent.trim()) {
// throw new Error(
// "The SEARCH block contains the entire file content. Please either:\n" +
// "1. Use an empty SEARCH block to replace the entire file, or\n" +
// "2. Make focused changes to specific parts of the file that need modification.",
// )
// }
// Exact search match scenario
const exactIndex = this.originalContent.indexOf(this.currentSearchContent, this.lastProcessedIndex)
if (exactIndex !== -1) {
this.searchMatchIndex = exactIndex
this.searchEndIndex = exactIndex + this.currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (lineMatch) {
;[this.searchMatchIndex, this.searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(
this.originalContent,
this.currentSearchContent,
this.lastProcessedIndex,
)
if (blockMatch) {
;[this.searchMatchIndex, this.searchEndIndex, /* ignore similarity */] = blockMatch
} else {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...does not match anything in the file.`,
)
}
}
}
}
if (this.searchMatchIndex < this.lastProcessedIndex) {
throw new Error(
`The SEARCH block:\n${this.currentSearchContent.trimEnd()}\n...matched an incorrect content in the file.`,
)
}
// Output everything up to the match location
this.result += this.originalContent.slice(this.lastProcessedIndex, this.searchMatchIndex)
}
private tryFixSearchBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error("Invalid SEARCH/REPLACE block structure - no lines available to process")
}
let searchTagRegexp = /^([-]{3,}|[<]{3,}) SEARCH$/
const searchTagIndex = this.findLastMatchingLineIndex(searchTagRegexp, lineLimit)
if (searchTagIndex !== -1) {
let fixLines = this.pendingNonStandardLines.slice(searchTagIndex, lineLimit)
fixLines[0] = SEARCH_BLOCK_START
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, searchTagIndex)
}
} else {
throw new Error(
`Invalid REPLACE marker detected - could not find matching SEARCH block starting from line ${searchTagIndex + 1}`,
)
}
return removeLineCount
}
private tryFixReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceBeginTagRegexp = /^[=]{3,}$/
const replaceBeginTagIndex = this.findLastMatchingLineIndex(replaceBeginTagRegexp, lineLimit)
if (replaceBeginTagIndex !== -1) {
// // 校验非标内容
// if (!this.isSearchingActive()) {
// removeLineCount += this.tryFixSearchBlock(replaceBeginTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceBeginTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[0] = SEARCH_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceBeginTagIndex - removeLineCount)
}
} else {
throw new Error(`Malformed REPLACE block - missing valid separator after line ${replaceBeginTagIndex + 1}`)
}
return removeLineCount
}
private tryFixSearchReplaceBlock(lineLimit: number): number {
let removeLineCount = 0
if (lineLimit < 0) {
lineLimit = this.pendingNonStandardLines.length
}
if (!lineLimit) {
throw new Error()
}
let replaceEndTagRegexp = /^([+]{3,}|[>]{3,}) REPLACE$/
const replaceEndTagIndex = this.findLastMatchingLineIndex(replaceEndTagRegexp, lineLimit)
const likeReplaceEndTag = replaceEndTagIndex === lineLimit - 1
if (likeReplaceEndTag) {
// // 校验非标内容
// if (!this.isReplacingActive()) {
// removeLineCount += this.tryFixReplaceBlock(replaceEndTagIndex)
// }
let fixLines = this.pendingNonStandardLines.slice(replaceEndTagIndex - removeLineCount, lineLimit - removeLineCount)
fixLines[fixLines.length - 1] = REPLACE_BLOCK_END
for (const line of fixLines) {
removeLineCount += this.internalProcessLine(line, false, replaceEndTagIndex - removeLineCount)
}
} else {
throw new Error("Malformed SEARCH/REPLACE block structure: Missing valid closing REPLACE marker")
}
return removeLineCount
}
/**
* Removes trailing empty lines from the pendingNonStandardLines array
* @param lineLimit - The index to start checking from (exclusive).
* Removes empty lines from lineLimit-1 backwards.
* @returns The number of empty lines removed
*/
private trimPendingNonStandardTrailingEmptyLines(lineLimit: number): number {
let removedCount = 0
let i = Math.min(lineLimit, this.pendingNonStandardLines.length) - 1
while (i >= 0 && this.pendingNonStandardLines[i].trim() === "") {
this.pendingNonStandardLines.pop()
removedCount++
i--
}
return removedCount
}
}
export async function constructNewFileContentV2(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let newFileContentConstructor = new NewFileContentConstructor(originalContent, isFinal)
let lines = diffContent.split("\n")
// If the last line looks like a partial marker but isn't recognized,
// remove it because it might be incomplete.
const lastLine = lines[lines.length - 1]
if (
lines.length > 0 &&
(lastLine.startsWith(SEARCH_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_SEARCH_BLOCK_CHAR) ||
lastLine.startsWith("=") ||
lastLine.startsWith(REPLACE_BLOCK_CHAR) ||
lastLine.startsWith(LEGACY_REPLACE_BLOCK_CHAR)) &&
lastLine !== SEARCH_BLOCK_START &&
lastLine !== SEARCH_BLOCK_END &&
lastLine !== REPLACE_BLOCK_END
) {
lines.pop()
}
for (const line of lines) {
newFileContentConstructor.processLine(line)
}
let result = newFileContentConstructor.getResult()
return result
}
@@ -23,3 +23,9 @@ export const formatResponse = {
return formatImagesIntoBlocks(images)
},
}
export function log(isVerbose: boolean, message: string) {
if (isVerbose) {
console.log(message)
}
}
@@ -0,0 +1,98 @@
import axios from "axios";
import path from "path";
import fs from "fs/promises";
// Minimal type for what we need from OpenRouter model info in evals
export interface EvalOpenRouterModelInfo {
id: string;
contextWindow: number;
inputPrice?: number; // Price per million tokens
outputPrice?: number; // Price per million tokens
// Add any other fields if they become necessary for evals
}
function logHelper(isVerbose: boolean, message: string) {
if (isVerbose) {
console.log(`[OpenRouterModelsHelper] ${message}`);
}
}
/**
* Ensures the cache directory exists within evals and returns its path
*/
async function ensureEvalCacheDirectoryExists(): Promise<string> {
// Cache directory within evals, e.g., evals/.cache/
const cacheDir = path.join(__dirname, "..", ".cache");
await fs.mkdir(cacheDir, { recursive: true });
return cacheDir;
}
/**
* Fetches, parses, and caches OpenRouter model data.
* Tries to read from a local cache first.
* @param isVerbose Enable verbose logging
* @returns A record of model IDs to their info.
*/
export async function loadOpenRouterModelData(isVerbose: boolean = false): Promise<Record<string, EvalOpenRouterModelInfo>> {
const cacheDir = await ensureEvalCacheDirectoryExists();
const cacheFilePath = path.join(cacheDir, "openRouterModels.json");
let models: Record<string, EvalOpenRouterModelInfo> = {};
try {
const stats = await fs.stat(cacheFilePath).catch(() => null);
// Use cache if less than 24 hours old
if (stats && (Date.now() - stats.mtimeMs < 24 * 60 * 60 * 1000)) {
logHelper(isVerbose, "Using cached OpenRouter model data.");
const fileContents = await fs.readFile(cacheFilePath, "utf8");
models = JSON.parse(fileContents);
if (Object.keys(models).length > 0) {
return models;
}
logHelper(isVerbose, "Cache was empty or invalid, fetching fresh data.");
} else if (stats) {
logHelper(isVerbose, "Cached OpenRouter model data is stale, fetching fresh data.");
} else {
logHelper(isVerbose, "No cached OpenRouter model data found, fetching fresh data.");
}
} catch (e) {
logHelper(isVerbose, `Error accessing cache, fetching fresh data: ${e}`);
}
try {
const response = await axios.get("https://openrouter.ai/api/v1/models");
if (response.data?.data) {
const rawModels = response.data.data;
const parsedModels: Record<string, EvalOpenRouterModelInfo> = {};
const parsePrice = (price: any) => price ? parseFloat(price) * 1_000_000 : undefined;
for (const rawModel of rawModels) {
parsedModels[rawModel.id] = {
id: rawModel.id,
contextWindow: rawModel.context_length ?? 0,
inputPrice: parsePrice(rawModel.pricing?.prompt),
outputPrice: parsePrice(rawModel.pricing?.completion),
};
}
await fs.writeFile(cacheFilePath, JSON.stringify(parsedModels, null, 2));
logHelper(isVerbose, `Fetched and cached ${Object.keys(parsedModels).length} OpenRouter models.`);
return parsedModels;
} else {
logHelper(isVerbose, "Invalid response structure from OpenRouter API.");
}
} catch (error) {
logHelper(isVerbose, `Error fetching OpenRouter models: ${error}. Attempting to use stale cache if available.`);
// Attempt to read stale cache as a last resort if fetching failed
try {
const fileContents = await fs.readFile(cacheFilePath, "utf8");
models = JSON.parse(fileContents);
if (Object.keys(models).length > 0) {
logHelper(isVerbose, "Successfully loaded stale cache after fetch failure.");
return models;
}
} catch (cacheError) {
logHelper(isVerbose, `Failed to read stale cache: ${cacheError}. Proceeding without OpenRouter model data.`);
}
}
// Return empty if all attempts fail, so the caller can decide how to handle it
return {};
}
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
# Get the directory of this script to make paths robust
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# The 'evals' directory is the parent of the script's directory
EVALS_DIR=$(dirname "$SCRIPT_DIR")
# Navigate to the evals directory to ensure npm commands run correctly
cd "$EVALS_DIR"
# Re-install dependencies and build the CLI
echo "Ensuring dependencies are up to date and building CLI..."
npm install && npm run build:cli
# Check if the build was successful before proceeding
if [ $? -ne 0 ]; then
echo "CLI build failed. Aborting evaluation."
exit 1
fi
# Run the evaluation script, passing all arguments from the command line
echo "Running evaluation..."
node ./cli/dist/index.js run-diff-eval "$@"
# Check the exit code of the evaluation script
if [ $? -eq 0 ]; then
# If the script succeeded, open the dashboard in the background
echo "Evaluation complete. Starting dashboard..."
(cd "$SCRIPT_DIR/dashboard" && streamlit run app.py &)
else
# If the script failed, print an error message and exit
echo "Evaluation failed. Dashboard will not be started."
exit 1
fi
@@ -29,10 +29,12 @@ export interface TestConfig {
model_id: string
system_prompt_name: string
number_of_runs: number
max_attempts_per_case: number
parsing_function: string
diff_edit_function: string
thinking_tokens_budget: number
replay: boolean
diff_apply_file?: string
}
export interface SystemPromptDetails {
@@ -61,10 +63,26 @@ export type ConstructSystemPromptFn = (
export interface TestResult {
success: boolean
streamResult?: any
streamResult?: {
assistantMessage: string
reasoningMessage: string
usage: {
inputTokens: number
outputTokens: number
cacheWriteTokens: number
cacheReadTokens: number
totalCost: number
}
timing?: {
timeToFirstTokenMs: number
timeToFirstEditMs?: number
totalRoundTripMs: number
}
}
diffEdit?: string
toolCalls?: ExtractedToolCall[]
diffEditSuccess?: boolean
replacementData?: any
error?: string
errorString?: string
}
@@ -85,4 +103,6 @@ export interface TestInput {
diffEditFunction: string
thinkingBudgetTokens: number
originalDiffEditToolCallMessage?: string
diffApplyFile?: string
isVerbose: boolean
}
-391
View File
@@ -1,391 +0,0 @@
import { runSingleEvaluation, TestInput, TestResult } from "./ClineWrapper"
import { basicSystemPrompt } from "./prompts/basicSystemPrompt-06-06-25"
import { claude4SystemPrompt } from "./prompts/claude4SystemPrompt-06-06-25"
import { formatResponse } from "./helpers"
import { Anthropic } from "@anthropic-ai/sdk"
import * as fs from "fs"
import * as path from "path"
import { Command } from "commander"
import { InputMessage, ProcessedTestCase, TestCase, TestConfig, SystemPromptDetails, ConstructSystemPromptFn } from "./types"
function log(isVerbose: boolean, message: string) {
if (isVerbose) {
console.log(message)
}
}
const systemPromptGeneratorLookup: Record<string, ConstructSystemPromptFn> = {
basicSystemPrompt: basicSystemPrompt,
claude4SystemPrompt: claude4SystemPrompt,
}
type TestResultSet = { [test_id: string]: (TestResult & { test_id?: string })[] }
class NodeTestRunner {
private apiKey: string | undefined
constructor(isReplay: boolean) {
if (!isReplay) {
this.apiKey = process.env.OPENROUTER_API_KEY
if (!this.apiKey) {
throw new Error("OPENROUTER_API_KEY environment variable not set for a non-replay run.")
}
}
}
/**
* convert our messages array into a properly formatted Anthropic messages array
*/
transformMessages(messages: InputMessage[]): Anthropic.Messages.MessageParam[] {
return messages.map((msg) => {
// Use TextBlockParam here for constructing the input message
const content: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = []
if (msg.text) {
// This object now correctly matches the TextBlockParam type
content.push({ type: "text", text: msg.text })
}
if (msg.images && Array.isArray(msg.images)) {
const imageBlocks = formatResponse.imageBlocks(msg.images)
content.push(...imageBlocks)
}
return {
role: msg.role,
content: content,
}
})
}
/**
* Generate the system prompt on the fly
*/
constructSystemPrompt(systemPromptDetails: SystemPromptDetails, systemPromptName: string) {
const systemPromptGenerator = systemPromptGeneratorLookup[systemPromptName]
const { cwd_value, browser_use, width, height, os_value, shell_value, home_value, mcp_string, user_custom_instructions } =
systemPromptDetails
const systemPrompt = systemPromptGenerator(
cwd_value,
browser_use,
width,
height,
os_value,
shell_value,
home_value,
mcp_string,
user_custom_instructions,
)
return systemPrompt
}
/**
* Loads our test cases from a directory of json files
*/
loadTestCases(testDirectoryPath: string): TestCase[] {
const testCasesArray: TestCase[] = []
const dirents = fs.readdirSync(testDirectoryPath, { withFileTypes: true })
for (const dirent of dirents) {
if (dirent.isFile() && dirent.name.endsWith(".json")) {
const testFilePath = path.join(testDirectoryPath, dirent.name)
const fileContent = fs.readFileSync(testFilePath, "utf8")
const testCase: TestCase = JSON.parse(fileContent)
// Use the filename (without extension) as the test_id if not provided
if (!testCase.test_id) {
testCase.test_id = path.parse(dirent.name).name
}
testCasesArray.push(testCase)
}
}
return testCasesArray
}
/**
* Saves the test results to the specified output directory.
*/
saveTestResults(results: TestResultSet, outputPath: string) {
// Ensure output directory exists
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
// Write each test result to its own file
for (const testId in results) {
const outputFilePath = path.join(outputPath, `${testId}.json`)
const testResult = results[testId]
fs.writeFileSync(outputFilePath, JSON.stringify(testResult, null, 2))
}
}
/**
* Run a single test example
*/
async runSingleTest(testCase: ProcessedTestCase, testConfig: TestConfig): Promise<TestResult> {
if (testConfig.replay && !testCase.original_diff_edit_tool_call_message) {
return {
success: false,
error: "missing_original_diff_edit_tool_call_message",
errorString: `Test case ${testCase.test_id} is missing 'original_diff_edit_tool_call_message' for replay.`,
}
}
const customSystemPrompt = this.constructSystemPrompt(testCase.system_prompt_details, testConfig.system_prompt_name)
// messages don't include system prompt and are everything up to the first replace_in_file tool call which results in a diff edit error
const input: TestInput = {
apiKey: this.apiKey,
systemPrompt: customSystemPrompt,
messages: testCase.messages,
modelId: testConfig.model_id,
originalFile: testCase.file_contents,
originalFilePath: testCase.file_path,
parsingFunction: testConfig.parsing_function,
diffEditFunction: testConfig.diff_edit_function,
thinkingBudgetTokens: testConfig.thinking_tokens_budget,
originalDiffEditToolCallMessage: testConfig.replay ? testCase.original_diff_edit_tool_call_message : undefined,
}
return await runSingleEvaluation(input)
}
/**
* Runs all the text examples synchonously
*/
async runAllTests(testCases: ProcessedTestCase[], testConfig: TestConfig, isVerbose: boolean): Promise<TestResultSet> {
const results: TestResultSet = {}
for (const testCase of testCases) {
results[testCase.test_id] = []
log(isVerbose, `-Running test: ${testCase.test_id}`)
for (let i = 0; i < testConfig.number_of_runs; i++) {
const result = await this.runSingleTest(testCase, testConfig)
results[testCase.test_id].push(result)
}
}
return results
}
/**
* Runs all of the text examples asynchronously, with concurrency limit
*/
async runAllTestsParallel(
testCases: ProcessedTestCase[],
testConfig: TestConfig,
isVerbose: boolean,
maxConcurrency: number = 20,
): Promise<TestResultSet> {
const results: TestResultSet = {}
testCases.forEach((tc) => {
results[tc.test_id] = []
})
// Create a flat list of all individual runs we need to execute
const allRuns = testCases.flatMap((testCase) =>
Array(testConfig.number_of_runs)
.fill(null)
.map(() => testCase),
)
for (let i = 0; i < allRuns.length; i += maxConcurrency) {
const batch = allRuns.slice(i, i + maxConcurrency)
const batchPromises = batch.map((testCase) =>
this.runSingleTest(testCase, testConfig).then((result) => ({
...result,
test_id: testCase.test_id,
})),
)
const batchResults = await Promise.all(batchPromises)
// Calculate the total cost for this batch
const batchCost = batchResults.reduce((total, result) => {
return total + (result.streamResult?.usage?.totalCost || 0)
}, 0)
// Populate the results dictionary
for (const result of batchResults) {
if (result.test_id) {
results[result.test_id].push(result)
}
}
const batchNumber = i / maxConcurrency + 1
const totalBatches = Math.ceil(allRuns.length / maxConcurrency)
log(isVerbose, `-Completed batch ${batchNumber} of ${totalBatches}... (Batch Cost: $${batchCost.toFixed(6)})`)
}
return results
}
/**
* Print output of the tests
*/
printSummary(results: TestResultSet, isVerbose: boolean) {
let totalRuns = 0
let totalPasses = 0
let totalInputTokens = 0
let totalOutputTokens = 0
let totalCost = 0
let runsWithUsageData = 0
let totalDiffEditSuccesses = 0
let totalRunsWithToolCalls = 0
const testCaseIds = Object.keys(results)
log(isVerbose, "\n=== TEST SUMMARY ===")
for (const testId of testCaseIds) {
const testResults = results[testId]
const passedCount = testResults.filter((r) => r.success && r.diffEditSuccess).length
const runCount = testResults.length
totalRuns += runCount
totalPasses += passedCount
const runsWithToolCalls = testResults.filter((r) => r.success === true).length
const diffEditSuccesses = passedCount
totalRunsWithToolCalls += runsWithToolCalls
totalDiffEditSuccesses += diffEditSuccesses
// Accumulate token and cost data
for (const result of testResults) {
if (result.streamResult?.usage) {
totalInputTokens += result.streamResult.usage.inputTokens
totalOutputTokens += result.streamResult.usage.outputTokens
totalCost += result.streamResult.usage.totalCost
runsWithUsageData++
}
}
log(isVerbose, `\n--- Test Case: ${testId} ---`)
log(isVerbose, ` Runs: ${runCount}`)
log(isVerbose, ` Passed: ${passedCount}`)
log(isVerbose, ` Success Rate: ${runCount > 0 ? ((passedCount / runCount) * 100).toFixed(1) : "N/A"}%`)
}
log(isVerbose, "\n\n=== OVERALL SUMMARY ===")
log(isVerbose, `Total Test Cases: ${testCaseIds.length}`)
log(isVerbose, `Total Runs Executed: ${totalRuns}`)
log(isVerbose, `Overall Passed: ${totalPasses}`)
log(isVerbose, `Overall Failed: ${totalRuns - totalPasses}`)
log(isVerbose, `Overall Success Rate: ${totalRuns > 0 ? ((totalPasses / totalRuns) * 100).toFixed(1) : "N/A"}%`)
log(isVerbose, "\n\n=== OVERALL DIFF EDIT SUCCESS RATE ===")
if (totalRunsWithToolCalls > 0) {
const diffSuccessRate = (totalDiffEditSuccesses / totalRunsWithToolCalls) * 100
log(isVerbose, `Total Runs with Successful Tool Calls: ${totalRunsWithToolCalls}`)
log(isVerbose, `Total Runs with Successful Diff Edits: ${totalDiffEditSuccesses}`)
log(isVerbose, `Diff Edit Success Rate: ${diffSuccessRate.toFixed(1)}%`)
} else {
log(isVerbose, "No successful tool calls to analyze for diff edit success.")
}
log(isVerbose, "\n\n=== TOKEN & COST ANALYSIS ===")
if (runsWithUsageData > 0) {
log(isVerbose, `Total Input Tokens: ${totalInputTokens.toLocaleString()}`)
log(isVerbose, `Total Output Tokens: ${totalOutputTokens.toLocaleString()}`)
log(isVerbose, `Total Cost: $${totalCost.toFixed(6)}`)
log(isVerbose, "---")
log(
isVerbose,
`Avg Input Tokens / Run: ${(totalInputTokens / runsWithUsageData).toLocaleString(undefined, {
maximumFractionDigits: 0,
})}`,
)
log(
isVerbose,
`Avg Output Tokens / Run: ${(totalOutputTokens / runsWithUsageData).toLocaleString(undefined, {
maximumFractionDigits: 0,
})}`,
)
log(isVerbose, `Avg Cost / Run: $${(totalCost / runsWithUsageData).toFixed(6)}`)
} else {
log(isVerbose, "No usage data available to analyze.")
}
}
}
async function main() {
const program = new Command()
const defaultTestPath = path.join(__dirname, "test_cases")
const defaultOutputPath = path.join(__dirname, "test_outputs")
program
.name("TestRunner")
.description("Run evaluation tests for diff editing")
.version("1.0.0")
.option("--test-path <path>", "Path to the directory containing test case JSON files", defaultTestPath)
.option("--output-path <path>", "Path to the directory to save the test output JSON files", defaultOutputPath)
.option("--model-id <model_id>", "The model ID to use for the test")
.option("--system-prompt-name <name>", "The name of the system prompt to use", "basicSystemPrompt")
.option("-n, --number-of-runs <number>", "Number of times to run each test case", "1")
.option("--parsing-function <name>", "The parsing function to use", "parseAssistantMessageV2")
.option("--diff-edit-function <name>", "The diff editing function to use", "constructNewFileContentV2")
.option("--thinking-budget <tokens>", "Set the thinking tokens budget", "0")
.option("--parallel", "Run tests in parallel", false)
.option("--replay", "Run evaluation from a pre-recorded LLM output, skipping the API call", false)
.option("-v, --verbose", "Enable verbose logging", false)
program.parse(process.argv)
const options = program.opts()
const isVerbose = options.verbose
const testPath = options.testPath
const outputPath = options.outputPath
const testConfig: TestConfig = {
model_id: options.modelId,
system_prompt_name: options.systemPromptName,
number_of_runs: parseInt(options.numberOfRuns, 10),
parsing_function: options.parsingFunction,
diff_edit_function: options.diffEditFunction,
thinking_tokens_budget: parseInt(options.thinkingBudget, 10),
replay: options.replay,
}
try {
const startTime = Date.now()
const runner = new NodeTestRunner(testConfig.replay)
const testCases = runner.loadTestCases(testPath)
const processedTestCases: ProcessedTestCase[] = testCases.map((tc) => ({
...tc,
messages: runner.transformMessages(tc.messages),
}))
log(isVerbose, `-Loaded ${testCases.length} test cases.`)
log(isVerbose, `-Executing ${testConfig.number_of_runs} run(s) per test case.`)
if (testConfig.replay) {
log(isVerbose, `-Running in REPLAY mode. No API calls will be made.`)
}
log(isVerbose, "Starting tests...\n")
const results = options.parallel
? await runner.runAllTestsParallel(processedTestCases, testConfig, isVerbose)
: await runner.runAllTests(processedTestCases, testConfig, isVerbose)
runner.printSummary(results, isVerbose)
const endTime = Date.now()
const durationSeconds = ((endTime - startTime) / 1000).toFixed(2)
log(isVerbose, `\n-Total execution time: ${durationSeconds} seconds`)
runner.saveTestResults(results, outputPath)
} catch (error) {
console.error("\nError running tests:", error)
process.exit(1)
}
}
if (require.main === module) {
main()
}
+2500
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
{
"name": "cline-evals",
"version": "0.1.0",
"description": "Evaluation scripts and tools for Cline",
"main": "cli/dist/index.js",
"scripts": {
"build:cli": "cd cli && tsc",
"start:cli": "cd cli && node dist/index.js",
"dev:cli": "cd cli && ts-node src/index.ts",
"diff-eval": "./diff-edits/run_and_open_dashboard.sh",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"cline",
"evaluation",
"benchmark",
"diff-edits"
],
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^1.8.2",
"better-sqlite3": "^11.10.0",
"chalk": "^4.1.2",
"dotenv": "^16.5.0",
"commander": "^9.4.1",
"execa": "^5.1.1",
"node-fetch": "^2.7.0",
"ora": "^5.4.1",
"sqlite": "^4.1.2",
"tiktoken": "^1.0.21",
"uuid": "^9.0.0",
"yargs": "^17.6.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.3",
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.12",
"@types/uuid": "^9.0.0",
"@types/yargs": "^17.0.19",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": ".."
}
}
+8120 -21385
View File
File diff suppressed because it is too large Load Diff
+51 -20
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.17.13",
"version": "3.20.2",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -186,6 +186,12 @@
"category": "Cline",
"icon": "$(robot)"
},
{
"command": "cline.abortGitCommitMessage",
"title": "Generate Commit Message with Cline - Stop",
"category": "Cline",
"icon": "$(debug-stop)"
},
{
"command": "cline.explainCode",
"title": "Explain with Cline",
@@ -213,7 +219,7 @@
},
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git"
},
{
"command": "cline.focusChatInput",
@@ -306,13 +312,22 @@
{
"command": "cline.generateGitCommitMessage",
"group": "navigation",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git && !cline.isGeneratingCommit"
},
{
"command": "cline.abortGitCommitMessage",
"group": "navigation",
"when": "config.git.enabled && scmProvider == git && cline.isGeneratingCommit"
}
],
"commandPalette": [
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git && !cline.isGeneratingCommit"
},
{
"command": "cline.abortGitCommitMessage",
"when": "config.git.enabled && scmProvider == git && cline.isGeneratingCommit"
}
]
},
@@ -323,27 +338,31 @@
},
"scripts": {
"vscode:prepublish": "npm run package",
"compile": "npm run check-types && npm run lint && node esbuild.js",
"compile-standalone": "npm run check-types && npm run lint && node esbuild.js --standalone",
"compile": "npm run check-types && npm run lint && node esbuild.mjs",
"compile-standalone": "npm run check-types && npm run lint && node esbuild.mjs --standalone",
"postcompile-standalone": "node scripts/package-standalone.mjs",
"watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.js --watch",
"watch:esbuild": "node esbuild.mjs --watch",
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.js --production",
"protos": "node proto/build-proto.js && node scripts/generate-server-setup.mjs",
"postprotos": "prettier src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/standalone/server-setup.ts --write --log-level silent",
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.mjs --production",
"protos": "node scripts/build-proto.mjs",
"postprotos": "prettier src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --write --log-level warn",
"clean": "rimraf dist dist-standalone webview-ui/build src/generated out/",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint",
"check-types": "npm run protos && tsc --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && cd webview-ui && npm run lint",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc -b --noEmit",
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && buf lint && cd webview-ui && npm run lint",
"format": "prettier . --check",
"format:fix": "prettier . --write",
"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",
"e2e": "playwright test -c playwright.config.ts",
"test:e2e": "playwright install && vsce package --no-dependencies --out dist/e2e.vsix && node src/test/e2e/utils/build.js && playwright test",
"test:e2e:optimal": "vsce package --no-dependencies --out dist/e2e.vsix && node src/test/e2e/utils/build.js && playwright test",
"install:all": "npm install && cd webview-ui && npm install",
"dev:webview": "cd webview-ui && npm run dev",
"build:webview": "cd webview-ui && npm run build",
@@ -353,12 +372,18 @@
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version",
"docs": "cd docs && mintlify dev",
"docs:check-links": "cd docs && mintlify broken-links",
"docs:rename-file": "cd docs && mintlify rename",
"docs": "cd docs && npm run dev",
"docs:check-links": "cd docs && npm run check",
"docs:rename-file": "cd docs && npm run rename",
"report-issue": "node scripts/report-issue.js"
},
"lint-staged": {
"*": [
"prettier --write --ignore-unknown --log-level=log"
]
},
"devDependencies": {
"@bufbuild/buf": "^1.54.0",
"@changesets/cli": "^2.27.12",
"@types/chai": "^5.0.1",
"@types/clone-deep": "^4.0.4",
@@ -376,7 +401,8 @@
"@typescript-eslint/parser": "^7.18.0",
"@typescript-eslint/utils": "^8.33.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"@vscode/test-electron": "^2.5.2",
"@vscode/vsce": "^3.6.0",
"chai": "^4.3.10",
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
@@ -384,11 +410,13 @@
"eslint-plugin-eslint-rules": "file:eslint-rules",
"grpc-tools": "^1.13.0",
"husky": "^9.1.7",
"mintlify": "^4.0.515",
"lint-staged": "^16.1.0",
"minimatch": "^3.0.3",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"protoc-gen-ts": "^0.8.7",
"proxyquire": "^2.1.3",
"rimraf": "^6.0.1",
"should": "^13.2.3",
"sinon": "^19.0.2",
"ts-node": "^10.9.2",
@@ -397,10 +425,10 @@
"typescript": "^5.4.5"
},
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.12.4",
"@anthropic-ai/sdk": "^0.37.0",
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.821.0",
"@aws-sdk/client-bedrock-runtime": "^3.840.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
@@ -415,6 +443,7 @@
"@opentelemetry/sdk-node": "^0.39.1",
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@playwright/test": "^1.53.2",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@vscode/codicons": "^0.0.36",
@@ -439,8 +468,10 @@
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"jschardet": "^3.1.4",
"jwt-decode": "^4.0.0",
"mammoth": "^1.8.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"nice-grpc": "^2.1.12",
"ollama": "^0.5.13",
"open": "^10.1.2",
"open-graph-scraper": "^6.9.0",

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