Compare commits

...

860 Commits

Author SHA1 Message Date
celestial-vault b36fe247fd add dev command for cline-core changes for cli 2025-10-04 10:16:12 -07:00
pashpashpash 097f8e6239 cline cli super alpha (#6644)
* super sketchy big merge with main

* gitignore

* gitignore

* Delete cli/bin/air

* Delete cli/bin directory

* Delete cli/cline-host

* Fix missing package.json in cli

Copy the package JSON into the dist-standalone dir during compilation.
Remove workaround for missing package.json

* Update scripts/build-cli.sh

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

* Remove reference to watchservice, it has been removed

* Update scripts/build-go-proto.mjs

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

* Fix timestamp to string conversion

* diff.go ellipsis fix

* COMMON_TYPES

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-03 15:04:00 -07:00
Sarah Fortune a037ba8965 Make the results of the GH test workflow easier to understand & fix windows tests (#6628)
* Dont use continue-on-error in the GH workflow

Using continue-on-error makes the tests appear as passed even when they failed and this is confusing

* Increase timeout for getOpenTabs test

* Dont run any tests if the build step failed

* Update .github/workflows/test.yml

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

* Fix getOpenTabs on tabs

```
Extension host test runner error 1 test failed.
  1 failing
  1) Hostbridge - Window - getOpenTabs
       should return all tabs including deleted files:
     Error: EBUSY: resource busy or locked, rmdir 'C:\Users\RUNNER~1\AppData\Local\Temp\vscode-test-O06Qnd'
```

The test is failing because the clean can't delete the temp directory it created, just surround it with try/catch.

* Add debug logs to the openTabsTest

* Increase the timeout on the e2e tests

I see this test timing out, so try increasing the timeout
https://github.com/cline/cline/actions/runs/18209633465/job/51847553463?pr=6628

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-10-03 13:49:00 -07:00
Ara f9f96b0e8a Bug Fix: replace featureFlagsService with isMultiRootEnabled utility (#6631)
* refactor: replace featureFlagsService with isMultiRootEnabled utility

Replace direct usage of featureFlagsService.getMultiRootEnabled() with the
isMultiRootEnabled() utility function throughout the codebase. This change:

- Centralizes multi-root feature flag logic in a single utility function
- Removes dependency on featureFlagsService in task and tool modules
- Passes stateManager to isMultiRootEnabled() for consistent state access
- Improves code maintainability by reducing coupling to the feature flags service

The refactoring affects Task class initialization, system prompt generation,
workspace root formatting, and auto-approve functionality.

* cancel button
2025-10-03 11:48:05 -07:00
celestial-vault a5699e883d Make statemanager global singleton (#6619)
* do not initialize duplicate statemanager in migration; use vscode api directly

* make state manager a singleton

* move statemanager init to common.ts
2025-10-02 21:18:57 -07:00
Bee 1cee9f33a7 feat: feature flag for cline auth provider (#6629) 2025-10-03 04:01:12 +02:00
pashpashpash 1b1e66f9d1 cli <--> main sync (#6576)
* adding cli args to cline core for ports and cline directory

* added locking

* data dir is correct

* final touches

* added better sqlite3 dep

* fs

* making help text more accurate

* touch instance at the end

* shutdown impl

* moving SETTINGS_SUBFOLDER const to vscode-context

* not calling process exit in protobus or hostbridge, handling that in cline core with proper graceful shutdown

* hostbridge port default

* package lock

* sigh, biome auto updated and daniels mcp hub change caused issues. locking biome

* fixed package-lock
2025-10-02 16:45:19 -07:00
Nick Baumann 888968d387 Update local models docs: remove emojis, add Qwen3 Coder recommendations, improve guidance (#6624) 2025-10-02 16:28:18 -07:00
canvrno 3fa41068ba Added checkpoints warning for multiroot scenarios (#6615)
* Added checkpoints warning for multiroot scenarios

* changeset

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-10-02 15:01:11 -07:00
celestial-vault 4c820db231 do not initialize duplicate statemanager in migration; use vscode api directly (#6614) 2025-10-02 14:26:47 -07:00
Sarah Fortune afa3eed7eb Update scripts/runclinecore.sh to include platform specific node module path (#6618)
With the introduction of better sqlite, this script needs to set the correct path for platform specific node modules. The logic is copied from the JB plugin (the vscode extension does not set the node modules path).
2025-10-02 14:21:39 -07:00
Daniel Steigman 9b6a120da4 feat(focus-chain): Render checklist items as markdown (#6452)
* feat(focus-chain): Render checklist items as markdown

This change introduces markdown rendering for both the header and individual items in the focus chain checklist. It leverages the existing MarkdownBlock component and adds a 'compact' mode to ensure proper alignment and spacing.

* feat: Add LightMarkdown component for memory-efficient rendering

- Create ultra-lightweight LightMarkdown component as memory-efficient alternative to MarkdownBlock
- Support bold (**text**), italic (*text*), and headers (# text) with cached regex patterns
- Replace MarkdownBlock with LightMarkdown in ChecklistRenderer and FocusChain components
- Eliminate heavy remark/rehype pipeline, AST parsing, and syntax highlighting for simple text formatting
- Significantly reduce memory usage and GC pressure in focus chain and checklist rendering
- Fix linting errors and ensure proper React element handling

This optimizes memory usage for components that only need basic markdown formatting,
while preserving full MarkdownBlock functionality where advanced features are needed.

* LightMarkdown: super-lightweight emphasis parser (bold/italic only); single-pass O(n) scan with memoization; remove headers; disable underscore emphasis to avoid snake_case false positives
2025-10-02 13:38:02 -07:00
Sarah Fortune 80f84b551e Log env vars in cline-core (#6595) 2025-10-01 16:00:39 -07:00
github-actions[bot] 8456f45a80 v3.32.6 Release Notes (#6579)
* Add experimental support for VSCode multi root workspaces
* Add Claude Sonnet 4.5 to Claude Code provider
* Add Glm 4.6 to Z AI provider

Updated version to 3.32.6

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-10-01 15:18:16 -07:00
canvrno e288bb9e4f Adjusted position and wording of multiroot settings (#6590)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-10-01 11:24:49 -07:00
celestial-vault a369551a9e fix: resolve CSS @import ordering issue for Tailwind CSS v4 compatibility (#6463)
- Move external @import statements before Tailwind imports to prevent PostCSS errors
- Add comprehensive documentation explaining import order requirements
- Fix build failure caused by '@import must precede all other statements' error

The issue occurred because Tailwind CSS v4 expands its imports into thousands of
lines of generated CSS, causing external imports to appear after CSS rules in
the final compiled output, violating CSS specifications.
2025-10-01 11:24:07 -07:00
celestial-vault b0fa1be2df Accept task settings in init task (#6342)
* v3.28.5 Release Notes

* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for patch 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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Add task-specific settings caching to StateManager (#6171)

* Add task-specific settings caching to StateManager

Implement per-task settings storage with automatic loading/clearing:
- Add taskStateCache for isolated task settings
- Load task settings on task creation and reinitialize
- Clear task settings cache when tasks end
- Prioritize task cache over global state in getters

* update error wording for taskSettings read failure

* add missing return statement in promise.all

* fix: persist pending task settings before clearing cache

Changed clearTaskSettings to be async and ensure any pending task state
changes are persisted to storage before clearing the in-memory cache.
This prevents potential data loss when a task ends with unpersisted
settings still in the pending state queue.

- Made clearTaskSettings async and added optional taskId parameter
- Added logic to persist pending task state batch before clearing
- Updated controller to await clearTaskSettings and pass taskId

* add ability to set task setting overrides in newtask rpc

* spread proto object keys that don't need to be transformed and filter undefined values

* use most Settings fields in TaskSettings proto and convert fields that do not directly map to the application typescripts type of Settings

* accept taskSettings in newTask RPC and save them to task state

* remove test taskSettings in useMessageHandlers

---------

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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-10-01 11:00:21 -07:00
Ara 793db91291 Adding support for GLM-4.6 (#6589) 2025-10-01 10:42:40 -07:00
canvrno 9cb0e51ffc Feat: Exclude deleted files from environment_details visible/open tabs context (#6014)
* Change to hide deleted files from the visible files/tabs environment_details

* Moved filtering logic to extension

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-10-01 10:11:44 -07:00
canvrno d68bf862a8 Provide model with better environment details in multiroot scenarios (#6585)
* Provide model with better env details in multiroot scenarios

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-10-01 01:24:18 -07:00
Sarah Fortune c2f69737aa Improve the git commit message generator (#6583)
* Commit message generator shouldn't create it's own StateManager, just use the one from the webview.
* Use the correct Cline logo
* Move it into the vscode specific directory, it uses too many VSCode APIs to work cross-platform.
2025-09-30 23:56:04 -07:00
Ara 99b8b92b27 Adding Telemetry for multi root workspace (#6580)
* Adding Telemetry for multi root workspace

* Taking out command runner

* Refactoring
2025-09-30 18:42:15 -07:00
Ara 1239fe1b33 Fixing parsing issues for workspace hints (#6559)
* Fixing regex parsing for workspace hints

* Fixing regex parsing for workspace hints

* test

---------

Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-30 17:01:33 -07:00
Tomás Barreiro 062e597b74 feat: Add Claude Sonnet 4.5 to Claude Code (#6573)
* feat: Add Claude Sonnet 4.5 to Claude Code

* add changeset

* Add support for the latest opus and sonnet models

* fix tests
2025-09-30 14:48:44 -07:00
Ara d099be10fd Adding Telemetry for @ mention usage (#6499)
* cjage

* Refactoring
2025-09-30 14:23:51 -07:00
canvrno 3e8268605f Update Cline provider headers (#6575)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-30 13:50:04 -07:00
Saoud Rizwan 1615bf3f82 fix: set max thinking budgets to avoid overflow when switching models with different budget limits 2025-09-30 13:11:17 -07:00
kvyb 15f713d26a Pass host telemetry requests (#6444)
* feat: add ideId to headers

* Add IDE-id to telemetry and request headers

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

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

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

* feat: align headers with backend

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

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

* fix: improve readability of filteredDynamic

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

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

* remove more things

* rename all sidebarWebviews to webview

* remove null from getInstance and remove null checks

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

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

* Refresh CI cache - fix proto compilation

* add comment to try to invalidate CI cache

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

* remove clean script didn't work

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

* Don't delete unrelated tests in this PR

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-09-29 21:15:17 -07:00
Sarah Fortune 163bf77677 Add a way for cline-core to get the version of the client. (#6553)
Add fields to the getHostVersion RPC that return the version of the cline-core client (e.g. the extension or plugin version).
2025-09-29 21:08:30 -07:00
Saoud Rizwan edf5ea00f6 Change task timeline item hover style 2025-09-29 20:18:47 -07:00
github-actions[bot] c3c80ffc4d v3.32.5 Release Notes (#6552)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-29 18:17:17 -07:00
Saoud Rizwan f14ed8506d Use state to manage NewModelBanner presentation 2025-09-29 18:17:17 -07:00
Saoud Rizwan 41202df74e Add prompt to encourage Sonnet 4.5 to use multiple search/replace blocks in a diff edit call rather than as separate requests 2025-09-29 18:17:14 -07:00
Saoud Rizwan ab88599e05 Add ContextWindowSwitcher component to easily switch between 200k and 1m context models 2025-09-29 16:03:23 -07:00
celestial-vault c2dc0e531c make task constructor typed object (#6558) 2025-09-29 15:45:17 -07:00
Juan Pablo Flores 246b0fa999 Add documentation for changes introduced in 3.30 (#6512)
* docs: update what-is-cline to use generic IDE references

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

* docs: expand Cline installation guide with comprehensive setup instructions

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

* docs: remove font weight and reorder getting started pages

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

* fixes title font-weight to original values

* docs: improve JetBrains plugin installation link text

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

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

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

* docs: rename voice-mode to dictation for clarity

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

* feat(docs): add YOLO mode documentation

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

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

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

* docs: improve JetBrains logo visibility and simplify dictation instructions

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

* add changeset

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

* testing pipeline improvement

* testing new run

* adding missing protos

* adding previous cache + restoring dev dep version

* restoring webview package lock

* scripts update

* fixing old flaky test

* fixing old flaky test

* changeset update

* adding test-platform-integration again

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

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

* adding change set
2025-09-29 12:19:23 -07:00
Saoud Rizwan f3adf68775 v3.32.3 Release Notes 2025-09-29 11:50:11 -07:00
Saoud Rizwan 6bd3181133 Add Sonnet 4.5 to Bedrock; add model banner announcing Sonnet 4.5; modify bug report 2025-09-29 11:38:02 -07:00
github-actions[bot] dd3a234a69 v3.32.2 Release Notes (#6511)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-29 10:53:49 -07:00
Saoud Rizwan c496f8a90d Fix OpenRouter model id 2025-09-29 10:47:00 -07:00
Saoud Rizwan 25b1cf91fc Add fixed Sonnet 4.5 support 2025-09-29 10:40:15 -07:00
Saoud Rizwan b54e2043fe Revert "Add Claude Sonnet 4.5 (#6544)"
This reverts commit 98e5ccc547.
2025-09-29 10:26:31 -07:00
Saoud Rizwan 98e5ccc547 Add Claude Sonnet 4.5 (#6544) 2025-09-29 10:10:04 -07:00
Sarah Fortune 813a9589d0 Replace VSCode API with the host bridge. (#6529)
Add a method to the host bridge to open and focus the terminal panel.
2025-09-28 19:12:09 -07:00
Sarah Fortune 64eb66d49a Move getGlobalStorageDir out of the HostProvider into disk.ts (#6530) 2025-09-28 19:11:59 -07:00
Sarah Fortune 8c17d864c8 Replace VSCode API with Host Provider (#6527)
VSCode API doesn't work cross-platform, this should use the host provider instead.
2025-09-28 18:18:55 -07:00
Sarah Fortune 4f931c2d9d Handle quotes and other special chars in the curl request (#6525)
This workflow didn't work if the PR title contained quotes, e.g.
https://github.com/cline/cline/pull/6523 - Don't show VS Code LM provider on non-VSCode platforms
2025-09-28 17:50:46 -07:00
Sarah Fortune 5836db3093 [disk.ts] Replace uses of context.globalStorageUri with HostProvider.get().globalStorageFsPath (#6507)
* Fix ellipsis warning

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

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

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

Remove unused vscode context param.

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

* Add deep link handler for /task
2025-09-28 02:23:09 -07:00
github-actions[bot] fb7f0e36fe v3.32.1 Release Notes (#6488)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

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

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

Remove unused vscode context param.

* Fix test ModelContextTracker.test.ts

* Fix test FileContextTracker.test.ts
2025-09-27 17:47:27 -07:00
celestial-vault 3173483c0f remove task class enable checkpoints variable and directly use statemanager (#6491) 2025-09-27 16:38:23 -07:00
Sarah Fortune 8caf37600b Fix problem compiling integration tests (#6498)
Fixes the error below. The integraion tests are compiled to CommonJS and cannot import an .mjs directly.

```
> claude-dev@3.32.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> (/Users/sjf/cline/scripts/build-tests.js:56:1)
    at Module._compile (node:internal/modules/cjs/loader:1734:14)
    at Object..js (node:internal/modules/cjs/loader:1899:10)
    at Module.load (node:internal/modules/cjs/loader:1469:32)
    at Function._load (node:internal/modules/cjs/loader:1286:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14) {
  status: 2,
  signal: null,
  output: [
    null,
    "src/core/task/index.ts(3,65): error TS7016: Could not find a declaration file for module '@anthropic-ai/sdk/resources/index.mjs'. '/Users/sjf/cline/node_modules/@anthropic-ai/sdk/resources/index.mjs' implicitly has an 'any' type.\n" +
      "  There are types at '/Users/sjf/cline/node_modules/@anthropic-ai/sdk/resources/index.d.ts', but this result could not be resolved under your current 'moduleResolution' setting. Consider updating to 'node16', 'nodenext', or 'bundler'.\n",
    ''
  ],
  pid: 22680,
  stdout: "src/core/task/index.ts(3,65): error TS7016: Could not find a declaration file for module '@anthropic-ai/sdk/resources/index.mjs'. '/Users/sjf/cline/node_modules/@anthropic-ai/sdk/resources/index.mjs' implicitly has an 'any' type.\n" +
    "  There are types at '/Users/sjf/cline/node_modules/@anthropic-ai/sdk/resources/index.d.ts', but this result could not be resolved under your current 'moduleResolution' setting. Consider updating to 'node16', 'nodenext', or 'bundler'.\n",
  stderr: ''
}

Node.js v23.11.0
```
2025-09-27 13:07:29 -07:00
Igor Tceglevskii 58b14c69b1 CLINE_ACTIVE usage (#6471) 2025-09-27 10:02:05 -07:00
Saoud Rizwan b831100f20 feat: preserve reasoning traces for cline/openrouter/anthropic providers to maintain conversation integrity (#6495)
* feat: preserve reasoning traces for cline/openrouter/anthropic providers to maintain conversation integrity

* Add reasoning trace preservation for providers

This change introduces a feature to preserve reasoning traces for specific providers, enhancing conversation integrity.

* Update src/core/api/transform/openai-format.ts

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-27 06:17:10 -07:00
Saoud Rizwan 23fa305eac Enable thinking by default for models that support it to reduce text verbosity in chat (#6493)
* Enable thinking by default for models that support it to reduce text verbosity in chat

* Refactor
2025-09-27 05:42:57 -07:00
Saoud Rizwan 0762e6406d fix: sending message during interactive command would show double checkpoints 2025-09-27 00:55:15 -07:00
Sarah Fortune 94da9f6669 Only show the info banner messages about the right sidebar in VSCode (#6492)
Add a `type` field to the PlatConfig with type of the IDE: VSCode, standalone, etc.
Make the info banner conditional on the type.
Quiet the gRPC logs on startup.
2025-09-26 19:37:58 -07:00
Saoud Rizwan fdeef9cece fix: uses homedir instead of hardcoded tilde for MCP path 2025-09-26 17:51:54 -07:00
lcs-bdr dd055b3327 fix: add retry logic to SAP AI Core provider (#6453)
* Use retry behavior for SAP AI Core provider

* add changeset
2025-09-26 12:47:08 -07:00
Igor Tceglevskii e852c6953b force no proxy for hostbridge connection (#6474) 2025-09-26 12:06:02 -07:00
github-actions[bot] aef27eb1c4 v3.32.0 Release Notes (#6487)
* Added the new code-supernova-1-million stealth model, available for free and delivering a 1 million token context window
* Changes to inform Cline about commands that are available on your system

Updated version to 3.32.0 

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-09-26 10:32:37 -07:00
Ara 863572031f Empty PR to bump changeset (#6485) 2025-09-26 09:45:12 -07:00
pashpashpash 65eee1ac6a add code-supernova-1m (#6458)
* add code-supernova-1m

* Update src/core/api/providers/cline.ts

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

* fixing cache price

* wording

* Update webview-ui/src/components/chat/Announcement.tsx

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

* Fix announcement content

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-09-26 08:19:39 -07:00
Bee 8213b0b910 Update E2E Test for Chat input (#6470)
* Update E2E Test for Chat input

* update

* typo
2025-09-26 10:00:32 +08:00
Bee f5fc3fed6f test: skip API request failure check to prevent Windows timeout (#6468)
Remove API request failure assertions that cause test timeouts on Windows due to longer API request failure times, while preserving other test functionality
2025-09-25 17:51:33 -07:00
celestial-vault 42df03177f feat: add HeroTooltip to conversation history button (#6466)
- Rename OpenDiskTaskHistoryButton to OpenDiskConversationHistoryButton
- Add HeroTooltip for consistent UI experience
- Update protobuf service and backend handler
2025-09-25 17:22:43 -07:00
Bee 648ae1b1fd feat(chat): add scroll to top functionality (#6423)
* feat(chat): add scroll to top functionality

- Add scroll to top button when action buttons are not visible
- Pass virtuosoRef to ActionButtons component for scroll control
- Enhance scroll button logic to handle both up and down directions

* Update aria-label
2025-09-25 17:10:25 -07:00
Saoud Rizwan d3cff6ac47 fix: search tool long regex string causing overflow in chatview 2025-09-24 23:38:25 -07:00
github-actions[bot] 13af435103 v3.31.1 Release Notes (#6451)
* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for version 3.31.1

Added details about installed CLI tools and renamed MCP tab.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-24 23:08:59 -07:00
Saoud Rizwan 3b1477bc24 Rename MCP tab 'Installed' to 'Configure' (#5966)
* Rename MCP tab 'Installed' to 'Configure'

* Fix component name

* Fix errors; update docs

* Create green-wasps-brush.md
2025-09-24 23:05:23 -07:00
Saoud Rizwan 688f93db6d Show ToS update for cline account users 2025-09-24 23:00:41 -07:00
Saoud Rizwan a702270e85 Fix import linter error 2025-09-24 21:57:30 -07:00
Saoud Rizwan 03acada1b9 Fix padding in checkpoints error 2025-09-24 21:56:43 -07:00
adam jones 95cca05f5e Add CLI tools detection to environment details (#5471)
- Auto-detect available CLI tools in system PATH
- Add detected tools to environment context for AI models
- Include comprehensive list of common developer tools (gh, docker, aws, etc.)
- Cross-platform support using 'which' on Unix and 'where' on Windows

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-24 21:49:25 -07:00
Saoud Rizwan 33d77eb095 Copy changes 2025-09-24 21:16:25 -07:00
github-actions[bot] 3e0c39acbb v3.31.0 Release Notes (#6379)
* changeset version bump

* Updating CHANGELOG.md format

* Update package.json

* Update changelog for version 3.31.0

Updated version to 3.31.0 and added new features and improvements.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-24 18:33:47 -07:00
Saoud Rizwan 366d8a5411 Fix failing integration test due to duplicate test id 2025-09-24 18:25:13 -07:00
Saoud Rizwan d22596e5c2 Update announcement banner content (#6448) 2025-09-24 18:06:25 -07:00
Saoud Rizwan 7cc612dbce Fix right sidebar banner and docs (#6446) 2025-09-24 18:02:44 -07:00
Ara f0cab63a43 Fixing icons and positioning for UI for voice mode (#6445)
* Minor UX fixes for voice mode

* Minor UX fixes for voice mode

* Minor UX fixes for voice mode

* Fix alignment of stop icon

---------

Co-authored-by: frostbournesb <frostbournesb@protonmail.com>
2025-09-24 16:20:27 -07:00
Saoud Rizwan 3c1b670b73 fix: cline not knowing plan/act mode if compact mode is enabled (#6443) 2025-09-24 15:31:42 -07:00
Ara 5de05d68ef Restricting voice mode to mac os only (#6442) 2025-09-24 15:15:44 -07:00
Saoud Rizwan 9b6b1c376c Revert focus chain design changes (#6441)
This reverts commit e5e26f45fa.

Revert "Update colors and width of focus chain (#6437)"

This reverts commit b794583b7a.

Revert "Update task header and focus chain UI design (#6415)"

This reverts commit 011b19225e.

Fix

Fix
2025-09-24 14:50:30 -07:00
Saoud Rizwan e5e26f45fa Decrease focus chain height 2025-09-24 13:55:31 -07:00
Saoud Rizwan b794583b7a Update colors and width of focus chain (#6437) 2025-09-24 13:44:54 -07:00
celestial-vault ca96bd8f62 add infobanner (#6294)
* add infobanner

* fix type and update docs url

* restructure test to not include brittle elements; it is not clear why this banner was even added to auth tests

* move update info banner logic into rpc
2025-09-24 13:37:40 -07:00
Bee 0ecdf8d0cc update CompactTaskButton tooltip content and styling (#6424) 2025-09-24 13:10:44 -07:00
Jose Castelli 5be6ba68a3 Testing Platform - Support partial response validation via meta.expected (#6399)
Testing Platform - Support partial response validation via meta.expected
2025-09-24 20:03:32 +02:00
celestial-vault 1bdd1e943f Add docs for opening cline in right sidebar (#6292)
* Add docs for opening cline in right sidebar

* use frame tags

* change to gifs

* docs(customization): refactor sidebar instructions with Steps component

Updated opening-cline-in-sidebar.mdx to replace numbered lists with structured <Steps> components for improved readability. Also updated image sources and added a link for Cursor alignment guidance.

---------

Co-authored-by: Juan Pablo <juan@cline.bot>
2025-09-24 09:22:02 -07:00
Saoud Rizwan c85a4abeb4 Fix bg color of API configuration in settings (#6422) 2025-09-24 02:13:29 -07:00
Saoud Rizwan 011b19225e Update task header and focus chain UI design (#6415)
* Fix chatfield buttons positioning

* Fix task header icons being cut off at bottom

* Fix copy for focus chain

* Fix focus chain text overflowing and being hidden

* Remove transition animation

* Fix token stats

* Tweak task header styles

* Fix focus chain progress bar direction

* Hide checkpoint text unless hovered

* Make copy button smaller and muted

* Use new focus chain design

* Make timeline blocks circles

* Move focus chain down and fix pencil icon positioning
2025-09-24 02:06:06 -07:00
Sarah Fortune a3945dce7f Replace vscode context.globalStoragePath with HostProvider.globalStorageFsPath (#6419) 2025-09-24 01:19:06 -07:00
celestial-vault 8daca03996 add a script to reconstruct taskHistory (#6403)
* add a script to reconstruct taskHistory

* remove format setting unrelated
2025-09-23 23:23:44 -07:00
Bee 777b8576f2 fix: update fontsource import path to resolve 401 errors (#6414)
* fix: update fontsource import path to resolve 401 errors

Replace specific weight imports with node_modules path reference to fix accessibility issues with @fontsource/azeret-mono font files in webview

* update path
2025-09-23 18:47:56 -07:00
Ara 880755ec89 feat: add multi-root workspace support for auto-approve file reads (#6412)
* feat: add multi-root workspace support for auto-approve file reads

Add logic to handle auto-approval of file read operations in multi-root workspace scenarios. When multi-root is enabled and multiple workspaces are present, the system now checks if a file is located in any workspace rather than just the current working directory. This ensures proper auto-approval behavior across all workspace roots while maintaining backward compatibility for single-root workspaces.

* Fixing pulsing border
2025-09-23 17:57:12 -07:00
Bee 1c70089521 initialize compact mode to prevent UI glitching on mount (#6413)
- Set isCompactMode initial state to true instead of false
- Replace CSS variable with Tailwind class for settings title
- Prevents layout shifts and UI glitching during component initialization
2025-09-23 17:05:48 -07:00
Bee fe2a8a9477 dev: disable auto-condense threshold configuration in task header (#6407)
Remove autoCondenseThreshold prop and hardcode useAutoCondense to false in TaskHeader component to temporarily disable the configurable auto-condense threshold from UI

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-23 16:41:57 -07:00
nihar-oracle eb2550ec3d fix(oca): add auth guard, unify axios config, and rotate default IDCS client id (#6410)
- refreshOcaModels:

  - Add explicit auth guard: show a user-facing error if no OCA access token is present and return a typed error via OcaCompatibleModelInfo.
  - Switch axios invocation to use getAxiosSettings() (fetch adapter) instead of proxy agents.
  - Replace getProxyAgents import with getAxiosSettings.

- OcaAuthProvider:

  - Migrate all axios calls (discovery + token POSTs) to use getAxiosSettings().
  - Add explicit error when no id_token is returned from OCA during the auth code exchange to improve diagnostics.

- utils/constants:
  - Rotate DEFAULT_IDCS_CLIENT_ID to a new value.

- utils/utils:

  - Create getAxiosSettings() helper (uses axios fetch adapter) and remove proxy agent–specific helpers.

  - Revise createOcaHeaders to avoid direct vscode + package.json coupling:

    - Use HostProvider.env.getHostVersion for host/IDE details.
    - Use ExtensionRegistryInfo.version for the extension version.
    - Set headers: client=Cline, client-version, client-ide, client-ide-version, opc-request-id.

  - Note: import of HttpsProxyAgent remains but is now unused; consider removing to avoid lint/TS warnings.

Rationale

- Reliability/UX: Users now receive a clear error when attempting to refresh OCA models without being authenticated.
- Portability: Replacing direct vscode and package.json usage in headers with HostProvider + ExtensionRegistryInfo reduces coupling and makes code host-agnostic.
- Network config simplification: Standardize axios setup through a single getAxiosSettings() helper and the fetch adapter.
- Auth robustness: Explicitly surface the absence of id_token to speed up troubleshooting OIDC flows.

Potential behavior changes

- Proxy handling: getProxyAgents() was removed in favor of the axios fetch adapter via getAxiosSettings(). If explicit HTTP(S)_PROXY env-based proxying is required, follow-up work may be needed to reintroduce agent support or configure fetch-compatible proxying.

Files touched

- src/core/controller/models/refreshOcaModels.ts
- src/services/auth/oca/providers/OcaAuthProvider.ts
- src/services/auth/oca/utils/constants.ts
- src/services/auth/oca/utils/utils.ts
2025-09-23 15:36:31 -07:00
Bee 9c3ac14cab feat: add multi-root workspace setting with feature flag support (#6409)
* feat: add multi-root workspace setting with feature flag support

Add user-configurable multi-root workspace setting that works in conjunction with feature flags. Includes proto definition, state management, and UI toggle in settings panel.

- Add multi_root_enabled field to UpdateSettingsRequest proto
- Implement multiRootSetting with user preference and feature flag state
- Add ClineFeatureSetting interface for feature flag + user setting pattern
- Create settings UI toggle with feature flag override indication
- Update state helpers to properly handle boolean conversion

* remove docs

* remove env vars
2025-09-23 15:34:50 -07:00
canvrno 6a8f900d75 REmove VCS requirement from multiroot checkpoints (#6405)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-23 13:09:46 -07:00
Bee 407e472322 fix: poll feature flags for all users (#6404)
* fix: poll feature flags for all users instead of just authenticated users

Move feature flags polling outside the authenticated user check to ensure all users (logged in and anonymous) receive up-to-date feature flags. Reset flags only for authenticated users to maintain proper user-specific configuration.

* add changeset
2025-09-23 12:59:55 -07:00
Saoud Rizwan 580b2e35e2 Update CODEOWNERS to remove dcbartlett (#6408) 2025-09-23 12:54:50 -07:00
Sarah Fortune 30c121509f Add a workflow that will trigger the Jetbrains tests for PRs in the cline repo (#6402)
Changes in the cline repo have the potential to cause breakages in the JetBrains repo. The creator of the PR might not found out until some time later that they have made a change that causes problems for JetBrains.

This workflow will trigger the workflow .github/workflows/test-changes-from-cline-repo.yml in the JetBrains repo, that runs the JetBrains integration tests. When the tests complete, the workflow will leave a comment on the PR with the results of the tests.
2025-09-23 10:13:38 -07:00
Bee b3aee3857c feat: new Task Header UI with configurable auto condense threshold (#6049)
* Update TaskHeader UI

- Create new FocusChainContainer component for todo list management
- Add onSendMessage prop to TaskHeader and TaskSection components
- Refactor TaskHeader to use new FocusChainContainer
- Update tooltip styling and Tailwind configuration
- Improve task progress visualization and interaction handling

* use tailwind

* Remove edit thread btn

* Add interactive auto-compact marker to context window bar

- Add state management for auto-compact marker position (default 75%)
- Make context window bar clickable to reposition marker
- Wrap entire bar in tooltip instead of just marker
- Add click handler to calculate percentage from mouse position
- Fix cost display conditional and remove redundant CSS property

* Prevent event bubbling in task header button clicks

Add preventDefault and stopPropagation to all task header button click handlers to prevent unintended parent element interactions. Also standardize styling by replacing inline styles with Tailwind classes and update text color class for consistency.

* Clean up

* Add CheckpointError component and clean up task header UI

- Add new CheckpointError component for error handling
- Remove commented code from FocusChainContainer
- Add rounded corners to focus chain container
- Refactor formatLargeNumber function with default parameter handling
- Clean up token display formatting in TaskHeader

* Add configurable auto-condense threshold for context window management

- Add autoCondenseThreshold setting to control when context window compaction occurs
- Update ContextManager to accept threshold percentage parameter (0-100%)
- Add ContextWindowDetails component to display context usage in task header
- Extend protobuf schema and state management for new threshold setting
- Default threshold set to 75% when auto-condense is enabled

* v2 style

* Dynamic marker & remove HeroTooltip

* Update styles

* feat: enhance task header UX with expanded progress bar hitbox smart boundary detection timeline block hover dimming effects optimized spacing and standard confirmation dialog styling

* Extract TaskHeader styles to CSS module

Move inline styles from TaskHeader component to external CSS module file for better maintainability and separation of concerns.

* migrate to tailwind

* migrate inline styes to tailwind for FocusChain

* fix(ui): fix useEffect cleanup and add key prop to InfoRow

- Return cleanup function from useEffect instead of nested setTimeout
- Add key prop to InfoRow component to ensure proper re-rendering
- Improves component lifecycle management and prevents memory leaks

* price tag and warning positioning

* clean up & persist expand state

* debounce

* add keyboard navigation for auto condense threshold slider

Add arrow key controls to adjust auto condense threshold with 5% steps (10% with Shift). Include focus management, accessibility attributes, and click-outside handling for improved UX.

* feat: small vertical positioning adjustment

* add changeset

* Update Task Action Button Text

* clean up

* Update storybook

* Apply styling feedback

* clean up

* feat: accordian style metadata for context window bar tooltip

* fix: notch slide fix

* fix: add cleanup for animation frames and timeouts in AutoCondenseMarker

Add proper cleanup functions to useEffect hooks to prevent memory leaks by canceling animation frames and clearing timeouts when component unmounts or dependencies change.

* Fix animation on mount

* remove handleBlur

* fix: change the order of the instructional text

* fix: remove the color from the tooltip percentage value

* clean up

* simplify

* useAutoCondense

* remove highlights

* set maxAllowedSize

* Auto Compact

* remove fork button

* feat: add configurable auto-condense threshold setting

Add auto_condense_threshold parameter to control when context window compaction occurs. The threshold is configurable as a percentage (0-1 range) of the total context window size, allowing users to customize when automatic condensing triggers instead of using a fixed maximum size.

Changes:
- Add autoCondenseThreshold field to protobuf UpdateSettingsRequest
- Update ApiProviderInfo interface to include autoCondenseThreshold
- Modify shouldCompactContextWindow to accept threshold percentage parameter
- Add threshold validation and state management in updateSettings
- Include autoCondenseThreshold in controller state and UI data flow

* autoCondenseThreshold

* fix package

---------

Co-authored-by: Jose R. Perez <trupix@gmail.com>
2025-09-23 09:21:07 -07:00
Bee 10cbbb2c6b feat: Cline Auth Provider (#6131)
* Add ClineAuthProvider and integrate with AuthService

- Add new ClineAuthProvider class for Cline-specific authentication
- Update AuthService to support both Firebase and Cline auth providers
- Switch default provider from Firebase to Cline
- Add dynamic auth URL fetching for Cline provider
- Update type definitions to support multiple provider types

* Add API auth URL configuration and update Cline auth flow

- Add apiAuthUrl to environment configs for all environments
- Update ClineAuthProvider to use new token exchange API endpoint
- Add shared Cline API utilities and types
- Refactor auth service to handle access tokens with expiration
- Update mock auth service and test fixtures for new auth flow

* add changeset

* wip

* refactor authentication service and improve token handling

- Add null check for auth token in ClineAccountService
- Update authorization header format to use 'workos:' prefix
- Replace hardcoded API endpoints with CLINE_API_ENDPOINT constants
- Refactor ClineAuthInfo interface to use accessToken terminology
- Remove Firebase auth provider dependency
- Simplify auth callback handling and token storage
- Improve error handling for missing authentication tokens

* refactor(auth): standardize workos token prefix handling

Centralize workos: prefix application in AuthService.getAuthToken() method instead of duplicating across multiple API call sites. This ensures consistent authentication token formatting and simplifies maintenance by having a single source of truth for token prefixing.

* Remove unused code

* update mock responses

* Set Firebase Auth Provider as default

* Update src/shared/cline/api.ts

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>

* remove docs

* refactor(auth): replace type union with IAuthProvider interface

- Replace AvailableAuthProvider type union with IAuthProvider interface for better extensibility
- Add ServiceConfig type for provider configuration
- Remove hardcoded providerName field in favor of provider.name property
- Update method signatures to use IAuthProvider interface
- Improve error messages and code comments for clarity
- Add TODO for mock auth provider implementation

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2025-09-23 08:23:22 -07:00
Bee 08365b3e0b feat: add configurable auto-condense threshold setting (#6391)
* feat: add configurable auto-condense threshold setting

Add auto_condense_threshold parameter to control when context window compaction occurs. The threshold is configurable as a percentage (0-1 range) of the total context window size, allowing users to customize when automatic condensing triggers instead of using a fixed maximum size.

Changes:
- Add autoCondenseThreshold field to protobuf UpdateSettingsRequest
- Update ApiProviderInfo interface to include autoCondenseThreshold
- Modify shouldCompactContextWindow to accept threshold percentage parameter
- Add threshold validation and state management in updateSettings
- Include autoCondenseThreshold in controller state and UI data flow

* updateSettings
2025-09-23 06:48:12 -07:00
canvrno cb4c61b1ca Dependency changes (#6393)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-22 23:36:50 -07:00
canvrno 2d9ff863b7 Update dependencies (#6390)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-22 20:16:33 -07:00
Ara ae9b20a12b Adding Search tool for multi root workspace (#6288)
* Adding multi search

* Adding multi search

* Adding multi search

* Adding multi search

* feat: Cleanup

* feat: Cleanup

* feat: Cleanup

* feat: Cleanup

* Fixing search and workspace path stuff
2025-09-22 19:17:40 -07:00
Ara c16e271c14 Adding voice mode to Cline (#6208)
* Adding voice mode
2025-09-22 18:50:56 -07:00
Bee b940cef0e4 refactor: append stealth models on readOpenRouterModels & refreshOpenRouterModels (#6384)
* refactor: extract stealth models to reusable function

Move hardcoded stealth model addition from inline code to a dedicated `appendStealthModels` function. This improves code organization by centralizing stealth model management and ensures consistent application across both fresh API responses and cached model data.

* refactor(controller): integrate stealth models into OpenRouter handling

- Added import and integrated appendClineStealthModels in readOpenRouterModels
- Improved error handling with try-catch in readOpenRouterModels
- Refactored refreshOpenRouterModels to use controller method and renamed functions
- Renamed STEALTH_MODELS to CLINE_STEALTH_MODELS and made appendClineStealthModels exportable

* await cached models for immediate UI availability

Changed the initialization to synchronously await and post last cached OpenRouter models, improving UI responsiveness by making them available as soon as possible instead of relying on a promise chain.
2025-09-22 18:47:02 -07:00
tjandy98 bc228de20e Update SAP AI Core Provider Anthropic input token calculation (#6363)
* Update anthropic input token usage calculation

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

* changeset

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

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
2025-09-22 18:41:21 -07:00
Ara a9cac3206a feat: Fixing dictation settings (#6385) 2025-09-22 17:38:31 -07:00
Jose Castelli a9bc4c7d67 Testing platform coverage (#6332)
Testing platform coverage
2025-09-22 21:14:54 +02:00
celestial-vault 737dce09d1 Remove duplicate settings references in Task class (#6336)
* read settings from statemanager instead of keeping stale references in Task class and child classes

* removed unused vars
2025-09-22 12:02:17 -07:00
ZeroAurora a10d778bee fix: remove temperature settings in z.ai models (#6311)
To use the default temperature. (#6223 comment)
2025-09-22 12:00:13 -07:00
Jose Castelli 58b0ea9afa Run Testing platform within Test workflow [shadow] (#6273)
Run Testing platform within Test workflow [shadow]
2025-09-22 20:15:22 +02:00
canvrno 90fa3d7336 Dependency updates (#6096)
* Dependency updates

* package-lock

* Updated packages

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-22 10:39:11 -07:00
canvrno d0da22d5a9 Modify checkpoints to accept an array of workspaces (#6320)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-22 10:06:02 -07:00
nihar-oracle f2ce0b46a3 fix: Fixing oca provider utils (#6359) 2025-09-20 22:14:54 -07:00
github-actions[bot] 52ab767e44 v3.30.3 Release Notes (#6352)
* changeset version bump

* Updating CHANGELOG.md format

* Update version from 3.31.0 to 3.30.3

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-19 17:57:08 -07:00
Ara d858fb9360 Empty PR to bump changeset (#6351)
* Empty PR to bump changeset

* feat: Cleanup
2025-09-19 17:49:33 -07:00
nihar-oracle 428cdb670a feat(oca): add OCA provider with model picker and auth integration (#6339)
- Add webview UI components:

  - webview-ui/src/components/settings/providers/OcaProvider.tsx
  - webview-ui/src/components/settings/providers/OcaModelPicker.tsx

- Update settings to surface OCA:
  - webview-ui/src/components/settings/ApiOptions.tsx

- Wire backend for OCA auth and controller:

  - src/services/auth/oca/OcaAuthService.ts
  - src/services/auth/oca/providers/OcaAuthProvider.ts
  - src/core/controller/index.ts
2025-09-19 17:27:45 -07:00
Toshii aab002fe65 adding yolo mode telemetry which is triggered in grpc call updated (#6348) 2025-09-19 16:45:52 -07:00
Saoud Rizwan cc540d8158 Remove comment on cacheWritesPrice in clineCodeSupernovaModelInfo 2025-09-19 15:05:22 -07:00
Saoud Rizwan adc15c79d7 Fix copy 2025-09-19 14:57:54 -07:00
Saoud Rizwan af05d3497a v3.30.2 Release Notes 2025-09-19 14:51:19 -07:00
Saoud Rizwan 23fa1cb481 Fix Announcement banner UI tests 2025-09-19 14:50:33 -07:00
github-actions[bot] 800967d851 v3.30.1 Release Notes (#6343)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-19 14:25:10 -07:00
Saoud Rizwan 91deede3c3 fix: model list not being updated in time for user to use shortcut button to update model to stealth model (#6347)
* fix: model list not being updated in time for user to use shortcut button to update model to stealth model

* Create tame-rabbits-travel.md
2025-09-19 14:21:32 -07:00
pashpashpash b11e6171ff YOLO MODE (#6340)
* add yolo mode setting

* more explicit warning

* changeset
2025-09-19 13:43:50 -07:00
Bee 42666d9ca7 fix: use webview dependencies (#6344) 2025-09-19 13:40:32 -07:00
Bee 07f944b668 fix: update SectionHeader to prevent content overlap (#6337)
Remove sticky positioning and z-index styling from SectionHeader component to fix overlapping content issues during scroll. Also clean up unused imports and update description text styling to use semantic class.
2025-09-19 13:28:20 -07:00
canvrno c6e5b1509c Fix flicker issue when switching modes (#6341)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-19 13:04:29 -07:00
github-actions[bot] 6787dedf47 v3.30.0 Release Notes (#6338)
* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for Oracle Code Assist integration

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-19 12:04:04 -07:00
Saoud Rizwan d07648746a Add code-supernova stealth model (#6327)
* Update announcement banner

* Fix banner buttons

---------

Co-authored-by: pashpashpash <nik@cline.bot>
2025-09-19 11:53:07 -07:00
nihar-oracle 07b49baa2a feat: OCA provider (#5075)
* feat(oca): add Oracle Code Assist provider; auth, models, settings

- Implement OCA API handler (src/core/api/providers/oca.ts)

  - OpenAI-compatible chat.completions with custom fetch injecting OCA headers
  - Optional reasoning (thinking) budget and ephemeral prompt caching
  - LiteLLM session tracking and usage streaming; cost via /spend/calculate
  - Guarded client init; clear error when OCA access token is missing

- Wire provider into core API and controller

  - Register provider (src/core/api/index.ts)
  - Controller flows for OCA account login/logout and auth status subscription
  - refreshOcaModels command and model config plumbing

- Add protobuf surfaces

  - proto/cline/models.proto and proto/cline/ocaAccount.proto
  - Extend proto/cline/state.proto for settings/state

- Persist settings/state and helpers
  - Update StateManager, state-keys, state-helpers, updateSettings

- Misc

  - Add changeset entry
  - Minor .gitignore and commit-message generator tweak

feat: New redirect server

feat(oca): add Oracle Code Assist provider; auth, models, settings

- Implement OCA API handler (src/core/api/providers/oca.ts)

  - OpenAI-compatible chat.completions with custom fetch injecting OCA headers
  - Optional reasoning (thinking) budget and ephemeral prompt caching
  - LiteLLM session tracking and usage streaming; cost via /spend/calculate
  - Guarded client init; clear error when OCA access token is missing

- Wire provider into core API and controller

  - Register provider (src/core/api/index.ts)
  - Controller flows for OCA account login/logout and auth status subscription
  - refreshOcaModels command and model config plumbing

- Add protobuf surfaces

  - proto/cline/models.proto and proto/cline/ocaAccount.proto
  - Extend proto/cline/state.proto for settings/state

- Persist settings/state and helpers
  - Update StateManager, state-keys, state-helpers, updateSettings

- Misc

  - Add changeset entry
  - Minor .gitignore and commit-message generator tweak

feat: New redirect server

update UI and add NPS survey link

papercuts

fix model dropdown height

fix: Fix 1

fix: removing ui

feat(AuthManager): Adding an AuthManager

fix: fixing rebase

* fix: Removing AuthManager, simplifyng auth service initialization
2025-09-19 00:33:24 -07:00
Alex Ker 2668bcdbe0 added baseten link to docs.json (#6312)
* added baseten link to docs.json

* fixed docs formatting

---------

Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-09-18 16:25:55 -07:00
github-actions[bot] e5e293c32b v3.29.2 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for v3.29.2 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: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-18 15:56:16 -07:00
Bee fea8313695 Revert "fix: configure HeroUI setup (#6279)" (#6323)
* Revert "fix: configure HeroUI setup (#6279)"

This reverts commit 5c2d93617f.

* changeset
2025-09-18 15:44:01 -07:00
canvrno 4b450f4488 Pass max_tokens to moonshot provider (#6316)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-18 14:21:26 -07:00
Sarah Fortune 2687ae149f Set telemetry env vars for JetBrains builds [esbuild] (#6299) 2025-09-18 20:45:05 +00:00
celestial-vault 3b93871b50 use consolidated type parameters for getter functions in state-helpers (#6262)
* use consolidated type parameters for getter functions in state-helpers

* fix types

* fix types
2025-09-18 12:55:43 -07:00
Jose Castelli 767b81b22b Improve standalone startup times (#6272)
Improve standalone startup times
2025-09-18 21:38:46 +02:00
Jose Castelli 5db4970c7d Enhance Testing Framework - Improve non-deterministic scenarios + fix flag (#6244)
Enhance Testing Framework - Improve non-deterministic scenarios + fix flag
2025-09-18 21:27:41 +02:00
Sarah Fortune 4f66126a8c Consolidate duplicated code in BrowserSession and UrlContextFetcher (#6289)
Move duplicated code to utils.ts

Replace context.globalStorageUri with the HostProvider.globalStorageFsPath.
This is part of removing dependencies on the VSCode API fom the codebase except for in platform specific code in src/hosts/vscode and src/extension.ts.
2025-09-18 11:40:44 -07:00
Sarah Fortune 43006ca401 Update runclinecore.sh script (#6300) 2025-09-18 10:12:56 -07:00
github-actions[bot] 1064c631c5 v3.29.1 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for 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: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-17 20:15:56 -07:00
canvrno 981fe9cf09 Changeset bump and announcement update (#6290)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-17 20:01:36 -07:00
Sarah Fortune 90ab59d8f5 Replace context.globalStorageUri with the HostProvider in CheckpointTracker (#6277)
* Replace context.globalStorageUri with the HostProvider in CheckpointTracker

Replace context.globalStorageUri with the HostProvider.globalStorageFsPath.

Remove globalStoragePath param, it doesn't need to be passed around anymore.

Remove unused param taskId from shadowGit

* Remove globalStoragePath param from checkpoint manager.

Now tht the global storage path is available from the HostProvider anywhere, it doesn't need to be passed around.
2025-09-17 17:03:30 -07:00
kvyb f237dda413 fix: test e2e click “Show Code Actions” button then wait for listbox on macOS (#6287)
* fix: test e2e click “Show Code Actions” button then wait for listbox on macOS

* fix: trigger code actions during test with shortcut

* fix: add reasonable timeout to the menu and listbox call in test
2025-09-18 02:30:54 +03:00
Bee f08b0499d5 test: refactor chat e2e tests to support multi-roots workspace types (#6282)
* test: refactor chat e2e tests to support multiple workspace types

- Convert single test functions to parameterized test suite using describe blocks
- Add workspace type iteration for both chat messaging and slash command tests
- Consolidate test structure to run against different workspace configurations
- Maintain existing test logic while improving test coverage and organization
- consolidate chat input tests into single comprehensive test

Merged three separate chat input tests (slash commands, @ mentions, and partial completion) into one comprehensive test to reduce test setup time and improve test efficiency. Simplified test structure while maintaining all original functionality checks.

* update keybindings
2025-09-17 16:00:56 -07:00
Bee 5c2d93617f fix: configure HeroUI setup (#6279)
* fix: configure HeroUI setup

- Simplify Storybook stories pattern to only include TypeScript files
- Update HeroUI to v2.8.4 with dependencies
- Refactor HeroUI configuration with VSCode theme integration
- Streamline Tailwind CSS imports and plugin setup

* darkmode

* Theme

* remove workflow
2025-09-17 14:35:22 -07:00
celestial-vault 99201f9944 split up global state and settings types; split apart methods for fetching state and settings (#6263) 2025-09-17 14:11:56 -07:00
Sarah Fortune 0983a8a4b9 Replace context.globalStorageUri with HostProvider.globalStorageFsPath (#6276) 2025-09-17 21:05:10 +00:00
Jose Castelli 683096aed7 Interactive playwright script (#6222)
Interactive playwright script
2025-09-17 21:16:54 +02:00
github-actions[bot] 7189b224fc v3.29.0 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Updated changelog and announcement banner for release

* Swapped grok button for jetbrains button

---------

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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
2025-09-17 12:06:05 -07:00
Sarah Fortune fe3a75309d Don't use workspace resolver for tasks directory. (#6275) 2025-09-17 17:50:12 +00:00
Nick Baumann 7a00be2d55 Update JetBrains installation docs for GA release (#6264) 2025-09-17 10:39:50 -07:00
Ara 4e7af6eb5d Adding Multi Root Workspace Support for a few different tool calls (#6228)
* Adding multi root workspace support for different tools

* fixing spacing

* fixing spacing

* fixing spacing
2025-09-17 10:04:30 -07:00
Sarah Fortune e9c8f67822 Add global storage path to the Host Provider (#6248)
Add a the field `globalStorageFsPath` to replace the VSCode `context.globalStorageUri`
Remove duplicated code for getting the cache directory.
Add a util function to the HostProvider to get sub-directories of the global storage dir, and ensure that the sub-directory is created.
2025-09-17 00:13:12 -07:00
Sarah Fortune bef7d2c75a Clean up cline-core (#6255)
Move all the logic for waiting for the host bridge into `hostbridge-client.ts`
Add some comments
Use try/finally, remove unused param, log the error message when the health check fails.
2025-09-17 00:13:02 -07:00
Jose Castelli dfc660e73c Setup QLTY Initial Coverage Metrics (#6167)
Setup QLTY Initial Coverage Metrics
2025-09-17 08:39:08 +02:00
Bee af0bc4dc6c fix: CreditLimitError should use server returned url when available (#6261)
* fix: CreditLimitError should use server returned url when available

- Add useMemo hook for dashboard URL computation
- Display credit balance, spent, and promotions when available
- Replace inline styles with Tailwind CSS classes
- Simplify TaskServiceClient call by removing unnecessary properties
- Add proper conditional rendering for credit information
- Improve code organization and readability

* changeset added

* props

* Update storybook
2025-09-16 20:30:55 -07:00
Alex Ker f37962bbf2 Updated Baseten models to use dynamic fetching, added docs (#6148)
* Updated Baseten models to use dynamic fetching, added docs

* removed unused function, supportsImages

* added parsePrice into model-utils.ts

* updated toolcalling comment

* updated tools to fetch from API

* fixed conflicts and updated supportTools

* applied npm run format:fix

* added bedrock stuff back in that was breaking test

---------

Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-09-16 19:52:35 -07:00
celestial-vault e82597e069 move apihandler secrets to own type and fix some type errors related to the handlers (#6249) 2025-09-16 18:44:34 -07:00
Bee d1db8f747a docs: add comprehensive E2E testing documentation (#6259)
Add detailed documentation for end-to-end testing with Playwright including:
- Test execution commands and debug mode usage
- Test structure overview with file descriptions
- Writing test guidelines with fixtures and best practices
- Mock API server setup and workspace configuration
- Interactive debugging features and troubleshooting tips

Updates both CONTRIBUTING.md and E2E README to provide complete guidance for contributors working with the test suite.
2025-09-16 17:31:46 -07:00
Bee e8ba3c34fb feat: add Storybook configuration (#6256)
* feat: add Storybook configuration

- Bump package version from 3.28.3 to 3.28.4
- Add comprehensive Storybook setup with React-Vite framework and TypeScript support
- Configure Storybook with custom viewport settings and environment variables
- Add extensive story files for chat components, MCP displays, and browser automation
- Update gitignore files to exclude Storybook build artifacts and logs

* Add docs and changeset

* feat: refactor Storybook decorator to support state overrides and custom styling

- Extract ExtensionStateProviderWithOverrides component to safely use useExtensionState within provider context
- Add optional classNames parameter to createStorybookDecorator for custom styling
- Import cn utility from @heroui/react for className merging
- Fix margin class from m-x-auto to mx-auto

* Add message to mock history

---------

Co-authored-by: Jose R. Perez <trupix@gmail.com>
2025-09-16 17:27:55 -07:00
yuvalman fadcd7e3ad fix: sap provider - set sapAiCoreUseOrchestrationMode in state-helper instead of in sap provider components (#6221)
* fix: sap provider - handle undefined apiConfiguration.sapAiCoreUseOrchestrationMode

* fix: sap provider - handle undefined apiConfiguration.sapAiCoreUseOrchestrationMode

* fix: sap provider - handle undefined apiConfiguration.sapAiCoreUseOrchestrationMode
2025-09-16 14:57:30 -07:00
celestial-vault 81299d26d8 refactor: move favorited model IDs to dedicated state management (#6251)
Removed favorited_model_ids field from API configuration models in proto files and migrated storage handling to global state key management.

Cleans up configuration separation by removing non-API-related data from model definitions. Enables more consistent state handling across the application.
2025-09-16 14:56:14 -07:00
Sarah Fortune 832025c8cc Use the correct version number in cline-core (#6254)
* Use the correct version number in cline-core

cline-core should use the same version number as the extension because they share the same code for the core functionality.
Use the version number from the ExtensionRegistryInfo instead of from the standalone package.json

* Use node:fs instead of fs
2025-09-16 14:15:47 -07:00
celestial-vault f8a7a1cc58 [Cleanup] Remove API Configuration Conversion in updateSettings (#6196)
* Refactor API configuration to use proto enums and structured types

- Replace JSON string fields with proper proto message types
- Convert snake_case field names to camelCase for consistency
- Use ApiProvider enum instead of string for provider fields
- Add structured types for model info and selectors
- Remove deprecated settings conversion module
- Update proto conversions to handle new structured format

* fix types errors caused by changing to generic string
2025-09-16 10:15:32 -07:00
Sarah Fortune 3723288250 Add a field to the HostProvider for extension install dir (#6239)
* Add a field to the HostProvider `extensionFsPath`

Replace vscode.ExtensionContext `extensionUri` with `HostProvider.extensionFsPath`.

This part of removing uses of the VSCode API fom the codebase except for in platform specific code (these are src/hosts/vscode and src/extension.ts).

* Remove extra leading slash from webview URL on JetBrains

* Remove vscode.Uri from the WebviewProvider

Replace `vscode.Uri` with URL strings.
Replace Uri with Url in variable names.
2025-09-16 09:49:32 -07:00
Jose Castelli 0b5e8f5c37 Moving grpc recorder unit test (#6214)
Moving grpc recorder unit test
2025-09-16 12:54:39 +02:00
kvyb a04f6050ee fix standalone: isolate workspaceState per project via WORKSPACE_STORAGE_DIR (#6215)
* fix standalone: isolate workspaceState per project via WORKSPACE_STORAGE_DIR

* fix: keep logs global; default workspace storage dir; no try/catch on mkdir
2025-09-16 10:30:02 +03:00
Sarah Fortune ef7e8c5018 Use ExtensionRegistryInfo to get the extension version (#6237) 2025-09-16 04:06:43 +00:00
celestial-vault 60b17d092b Add task-specific settings caching to StateManager (#6171)
* Add task-specific settings caching to StateManager

Implement per-task settings storage with automatic loading/clearing:
- Add taskStateCache for isolated task settings
- Load task settings on task creation and reinitialize
- Clear task settings cache when tasks end
- Prioritize task cache over global state in getters

* update error wording for taskSettings read failure

* add missing return statement in promise.all

* fix: persist pending task settings before clearing cache

Changed clearTaskSettings to be async and ensure any pending task state
changes are persisted to storage before clearing the in-memory cache.
This prevents potential data loss when a task ends with unpersisted
settings still in the pending state queue.

- Made clearTaskSettings async and added optional taskId parameter
- Added logic to persist pending task state batch before clearing
- Updated controller to await clearTaskSettings and pass taskId
2025-09-15 15:49:10 -07:00
Bee 58808f3e2f fix process.env access for posthog (#6231)
* fix process.env access in build script

- Add CLINE_ENVIRONMENT=production to esbuild define config
- Remove fallback empty strings for API keys in build config
- Simplify optional chaining to direct property access for process.env
- Ensure consistent environment variable handling across config files

* verify CI secrets

* revert temp test
2025-09-15 13:55:34 -07:00
Sarah Fortune 281fd9505a Don't construct the IDE redirect URL in the webview. (#6229)
* Don't construct the redirect URL in the webview.

Add an RPC to the ProtoBus to get the URI to redirect back to the host IDE.
Support for JetBrains will be added in a second PR.

* Remove the uriScheme and extension name from the ExtensionStateContext.

These are being used to construct the IDE redirect URI, but this is not a cross-platform compatible way to do this.

* Update the host bridge to return the whole URL to redirect to the IDE

Return the whole redirect URI instead of just the URI scheme. VSCode needs the whole URI to redirect back to VSCode and open the cline extension.

* Update js doc

* Remove unused propertu uriScheme

All uses of vscode.env.uriScheme have been moved to platform specific code, so add it to linter rules for vscode API.
2025-09-15 12:58:25 -07:00
Ara fe1da0fa6c Normalize paths to fix windows test for workspace paths (#6227)
* Adding prompts

* Adding prompts
2025-09-15 12:17:49 -07:00
Toshii a505a79ec3 yolo mode (#6151)
* add global state var for yolo mode

* setting and updating yolo mode in autoApprover

* use approveAll variable in autoAPprove class

* add logic for automatically handling plan_mode_respond tool calls

* remove follow up question tool in yolo mode

* conditional parameter inclusion for execute_command in yolo mode

* logic for having terminal command continue in background once timer is up for yolo mode

* prompt adjustment for the timeout param

* changing function signature

* full template changes to support context

* merge conflict fix for system_info

* fixing default values

* update where we resolve template to TemplateEngine

* template engine test update

* test changes, adding types

* updating TemplateEngine test scoping

* add missing ide param in test

* clean up variable naming
2025-09-15 11:41:20 -07:00
Yukio Nozawa ac41b0dd33 Fix: Improve screen reader accessibility for MCP servers / Cline rules screens (#5861)
* Add descriptive aria-labels to mcp server screen

* Improve screen reader accessibility for cline rules page and its tabs

* Fix: Have screen readers read the new rule / new workflow file labels consistently (previously it always announced new rule file regardless of the actual file type)

* Add changeset
2025-09-15 11:40:41 -07:00
Yukio Nozawa fd3abdc68b fix: [accessibility] Improve screen reader accessibility for history view / preview (#5860)
* Fix: Add descriptive aria-labels to unlabelled buttons in the history preview screen

* Fix: Add descriptive aria-labels to unlabelled buttons in the history view screen

* Add changeset
2025-09-15 11:34:37 -07:00
Bee fe37ca9f29 Add environment variable injection to esbuild config (#6225)
* Add environment variable injection to esbuild config

Inject TELEMETRY_SERVICE_API_KEY, ERROR_SERVICE_API_KEY, and CLINE_ENVIRONMENT
at build time for production builds.

* add changeset

* update
2025-09-15 11:18:36 -07:00
Ara 7ecf395a9a Adding workspace adaptor and workspace hint for multi root workspace (#6143)
* Adding workspace adapter

* Adding workspace adapter
2025-09-15 10:10:33 -07:00
github-actions[bot] e6c251a5a9 v3.28.4 Release Notes (#6193)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG for version 3.28.4

Consolidate changelog entries for version 3.28.4 and improve clarity.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-14 21:02:09 -07:00
Saoud Rizwan 2fee3c47e7 fix: update secondary text for cancel button (#6212) 2025-09-14 20:44:40 -07:00
Saoud Rizwan b676c5df66 fix: convert action button isProcessing from ref to state to force re-render (#6211)
* fix: convert action button isProcessing from ref to state to force re-render

* Create eleven-swans-sort.md
2025-09-14 19:39:37 -07:00
Saoud Rizwan 9ae7c4f9e6 fix #6172: detectedShell returns non-string on some Windows machines leading to API request hanging (#6210)
* fix: detectedShell returns non-string on some Windows machines leading to indefinite API request hanging

* Fix bug causing API request to hang on Windows
2025-09-14 19:12:00 -07:00
Saoud Rizwan a8ba96ff4a fix: allows truncation for empty conversation, for when automatic truncation is tried after failed request (#6200) 2025-09-14 18:47:26 -07:00
yuvalman 0b551de152 fix: sap provider - support gpt-5 family in orchestration mode (#6195)
* feat: remove model_params in orchestration mode

* feat: remove model_params in orchestration mode
2025-09-14 00:39:07 -07:00
Bee 4985d1d185 fix: display prompt cache in history view (#6181)
* fix: display prompt cache in history view

* clean up

* no changeset
2025-09-13 04:38:55 -07:00
Bee 60ddf80e5c Remove --no-stash flag from lint-staged in pre-commit hook (#6188)
### Problem

The `--no-stash` flag was originally added to work around issues where teammates hadn't installed Biome after our migration from Prettier. When the formatter failed, lint-staged's default stashing behavior would remove staged changes, causing frustration.

However, this workaround now causes a different problem: lint-staged runs formatters on files containing both staged AND unstaged changes. When Biome formats these files, it inadvertently stages unstaged modifications, effectively merging work-in-progress changes into commits.

### Solution

Remove the `--no-stash` flag to restore lint-staged's default behavior:

- Stash unstaged changes before running formatters
- Run formatters only on staged content
- Restore the stash after formatting

This ensures that only intentionally staged changes are included in commits, preventing accidental inclusion of work-in-progress modifications.

### Context

It's been sufficient time since the Prettier → Biome migration that all team members should have the proper tooling installed. The original workaround is no longer needed and is now causing more problems than it solves.
2025-09-13 04:21:18 -07:00
github-actions[bot] eece559f51 v3.28.3 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Updated changelog for 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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 18:40:32 -07:00
celestial-vault cc7be60fd9 remove unnecessary git commit conversion function (#5913) 2025-09-12 17:35:23 -07:00
celestial-vault c4d576d830 remove rule files conversion and directly create grpc request (#5914) 2025-09-12 17:35:07 -07:00
Bee d462e0b67c fix: Start new task instead of resume completed task (#6179)
* fix: Start new task instead of resume completed task

* no changeset

* Start New Task with Context
2025-09-12 15:47:27 -07:00
Bee a4d8f7cb3d feat: generate commit for staged changes if any (#6177)
* feat: generate commit for staged changes if any

- Replace getWorkingState with getGitDiff function that return diff for staged changes only with unstaged change as fallback
- Add structured PROMPT constant with system and message templates
- Wrap generation logic in try-catch for better error handling
- Move input validation and progress handling into main generate function
- Improve error messages with more descriptive context

* changeset added

* clean up
2025-09-12 15:38:26 -07:00
github-actions[bot] 7868866bed v3.28.2 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Prepare for release v3.28.2

---------

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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 13:32:47 -07:00
canvrno ac291a6fa8 Changeset for focus chain settings fix (#6173)
* changeset

* Fix for focus chain settings

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 13:20:02 -07:00
canvrno b71f0ddbfb Fixed issue with focus chain settings (#6170)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 12:21:09 -07:00
Sarah Fortune 8a4c264415 Rename Uri to Url (#6155)
We have switched from using using the VSCode URI to regular URLs, so update the names of the functions to say Url instead of Uri.
2025-09-12 11:57:50 -07:00
github-actions[bot] af548e109a v3.28.1 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Prepare changelog for 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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 11:08:48 -07:00
Jose Castelli ddd03243f4 Adding initial integration spec files based on e2e playwright tests (#6136)
Adding initial integration spec files based on e2e playwright tests
2025-09-12 19:53:08 +02:00
canvrno 5f19701f33 Removed focus chain feature flag (#6168)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-12 10:41:54 -07:00
Sarah Fortune 0b992131e3 Use the correct IDE name in the API request (#6157)
* Use the correct IDE name in the API request

The IDE name is influences the model's response, so use the correct name instead of using VSCode on all platforms.

* Include the IDE type in the system info

* Move the ide name into the SystemPromptContext

Remove the legacy system prompt test, otherwise it would be need to be updated for these changes, but it is already deprecrated.
2025-09-11 23:41:46 -07:00
Bee 1530cfe034 Register commands and view to use centralized ExtensionRegistryInfo (#6153)
* Register commands and view to use centralized ExtensionRegistryInfo

Replace hardcoded package.json imports and string literals with a centralized
ExtensionRegistryInfo object that provides extension name and command
definitions. This improves maintainability and ensures consistency across
the codebase.

* update view id

* Fix environment variable serialization in vite config

Wrap all process.env values with JSON.stringify to ensure proper
string serialization and prevent undefined values from breaking
the build configuration.
2025-09-11 20:35:16 -07:00
John Costa 6b9dbccfd2 fix: using baseURL to fetch models and get API key (#5732)
* fix: using baseURL to fetch models and get API key

* change set

* fix: keeping /v1 in URL

This is because `URL` constructor, strips the path when giving two
arguments.
2025-09-11 19:52:42 -07:00
Sarah Fortune c3591290d2 When using the AuthHandler redirect to the host IDE after logging in (#6139)
* When using the AuthHandler redirect to the host IDE after logging in.

Add an RPC to the host bridge to the URI scheme for the host IDE.
Add a redirect to the login succeeded page.

* Typo
2025-09-11 17:37:27 -07:00
Bee 1b08f23f87 Add Active Workspaces info to system information and adding feature flag for multi root (#6128)
* Add Active Workspaces info to system information

Update system_info.ts to include active workspaces in the system prompt, providing AI assistants with context about all currently open workspace directories. This enhancement helps the AI understand the full scope of the user's development environment beyond just the current working directory.

* add changeset

* Add Active Workspaces info to system information

Update system_info.ts to include active workspaces in the system prompt, providing AI assistants with context about all currently open workspace directories. This enhancement helps the AI understand the full scope of the user's development environment beyond just the current working directory.

* add changeset

* Update test for single workspace

* IS_TEST

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager

* Refactor feature flags to use centralized service instead of state manager

- Replace direct state manager access with featureFlagsService calls
- Remove feature flag polling from webview initialization
- Move feature flag polling to main initialization flow
- Centralize focus chain feature flag logic in FeatureFlagsService

* Update system prompt snapshots

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-09-11 16:44:20 -07:00
github-actions[bot] 7734f04e2a v3.28.0 Release Notes
* changeset version bump

* Updating CHANGELOG.md format

* Changelog and Anncouncements update for 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: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-11 15:52:16 -07:00
celestial-vault 3ef7d0f5d2 introduce useEffect to update external state change (#6144) 2025-09-11 14:07:58 -07:00
Bee 9463b4ac72 Dev: Supports using secrets as PostHog API keys at build time (#5971)
* dev: PostHog config to use separate API keys for telemetry and error tracking

- Update PostHogErrorProvider to use dedicated errorTrackingApiKey
- Add comprehensive documentation and type definitions
- Support environment variables with fallback to public keys
- Improve code organization with clearer naming conventions

* changeset added

* Update GitHub Workflow

* debug

* revert debug and set process env for browser

* undefined environment variables fallback to public keys

* update workflow

* update provider factories with config validation and no-op logging

- Add PostHog config validation to determine provider type
- Replace "none" type with "no-op" for consistency
- Enhance NoOpProvider implementations with actual logging
- Update factory logic to use validated config checks
- Improve error handling and fallback behavior

* Update .github/workflows/publish.yml

Co-authored-by: Dennise Bartlett <bartlett.dc.1@gmail.com>

* Update workflow

* clean up

* update env vars in vite config

* Fix error handling recursion and update PostHog configuration

- Prevent infinite recursion in ClineError.transform() by checking for existing ClineError instances
- Use errorTrackingApiKey instead of apiKey for PostHog error provider initialization
- Replace Logger calls with console methods in NoOpErrorProvider to avoid circular dependencies
- Update dev environment detection logic to exclude CI check for more reliable configuration

* Remove console.error from unsupported error provider fallback

Remove unnecessary error logging when falling back to NoOpErrorProvider
for unsupported error provider types in ErrorProviderFactory.

* Update PostHog config to handle local and test environments

- Change dev environment detection to include local environment
- Add test environment detection for E2E and unit tests
- Disable PostHog validation in test environments to enable mocking

* add fallback back

* remove hardcoded keys

* Posthog secrets to Nightly workflow

---------

Co-authored-by: Dennise Bartlett <bartlett.dc.1@gmail.com>
2025-09-11 13:34:00 -07:00
Bee b858277da3 Add ESC key listener for task cancellation (#6121)
* - Add ESC key listener for task cancellation
- Refactor action buttons to use typed button actions to clean up unused code
- Replace string-based button handling with ButtonActionType enum
- Add ActionButtonConfig interface for better type safety
- Implement executeButtonAction method for centralized action handling
- Consolidate button click logic into reusable handlers

* clean up

* add changeset
2025-09-11 11:39:46 -07:00
Bee f152301ca9 dev: extension isolation in VS Code launch configs and E2E tests (#6141)
* dev: extension isolation in VS Code launch configs and E2E tests

- Replace specific extension disabling with --disable-extensions flag to avoid conflicts or bugs caused by other extensions
- Add channel configuration support for stable/insiders testing
- Enhance E2E test interface with channel selection capability
- Ensure better isolation during development and testing

* Update e2e test fixtures: configure workspace settings and allow .vscode tracking

- Add workbench.secondarySideBar.defaultVisibility setting to multiroots workspace
- Remove .vscode from gitignore to allow VS Code configuration tracking
2025-09-11 10:38:25 -07:00
Sarah Fortune 0d13ae1fa4 Make the Terminal entry in the @mentions configurable (#6126)
JetBrains doesn't support @terminal mentions, so don't show it in the mentions context menu.
2025-09-11 10:02:08 -07:00
Sarah Fortune 0cefe107b8 Add a configuration for the toggle plan/act mode keyboard shortcut. (#6125)
JetBrains already uses cmd-shift-p, so cmd-shift-a instead. Add a new field to
the platform specific config for the keyboard shortcut.

ref FDN-3
2025-09-11 09:50:31 -07:00
Jose Castelli 43a6e85d7a Add orchestrator script and improve standalone service for local testing (#6100)
Add orchestrator script and improve standalone service for local testing #6100
2025-09-11 11:48:14 +02:00
Sarah Fortune 7a27f09224 refactor: replace platform conditional __is_standalone__ with a platform configuration (#6122) 2025-09-10 22:01:41 -07:00
Sarah Fortune 0936634fe5 Remove uses of the VSCode API (#6124) 2025-09-10 21:46:11 -07:00
celestial-vault 7ec918261c Clean up HistoryView: remove debug logs and unused code (#6133)
- Remove console.info debug statement from deleteTaskWithId
- Rename filteredTasks to tasks for clarity
- Remove unused presentableTasks variable
- Remove commented out empty state UI code
2025-09-10 19:57:19 -07:00
celestial-vault 9ac17c2ec8 cleanup unnecessary functions in StateManager to reduce clutter (#6134) 2025-09-10 18:18:44 -07:00
Bee ee68fac5b8 Update nightly extension container name and vsce package scripts for test (#6132)
* Update nightly extension container name and e2e test setup

- Set activity bar title for nightly builds in package.json
- Remove unnecessary extension development flags from e2e tests as the test is set up to test from the vsix package it builds

* remove "--no-dependencies"

* activitybar title

* add back extensionDevelopmentPath
2025-09-10 17:18:58 -07:00
celestial-vault 3bcb1bacb7 Improve error handling and validation in taskHistory storage operations (#6115)
* Improve error handling and validation in taskHistory storage operations

- Add user-facing error message when StateManager initialization fails
- Replace empty string check with proper JSON parsing error handling in task history reading
- Add validation to ensure task history migration writes data correctly before clearing old state

* add missing return statement

* split up error check cases for write validation
2025-09-10 13:27:36 -07:00
kvyb 6392043f51 fix: leading slash missing in webview from files shown in chat window (#6127) 2025-09-10 23:07:09 +03:00
Derek Noggle 92177ac2ea Fix broken link in docs to Cline tools implementation (#6120) 2025-09-10 08:19:43 -07:00
Daniel Steigman 318f5a7829 added telemetry around unexpected API responses (#6066)
* added telemetry around uexpected API responses

* feat(cline): capture real HTTP request ID (X-Request-ID) in ClineHandler via custom fetch; expose getLastRequestId(); prefer true requestId over generationId in Task telemetry for empty-assistant-message

* Delete PR_BODY_nighttrek_api_error_tracking.md

* refactor(ts): improve type safety for request ID capture and empty-assistant diagnostics

cline.ts: strongly type custom fetch override using Parameters<typeof fetch>/ReturnType<typeof fetch>; safe URL extraction for string|URL|Request; removed any casts.

task/index.ts: encapsulate requestId retrieval via getApiRequestIdSafe(); avoid any; no behavior change. Scope limited to PR 6066-related changes.
2025-09-10 00:57:55 -07:00
CellenLee f98aa0fb50 feat: update kimi-k2-0905-preview and kimi-k2-turbo-preview (#5995)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-09 23:39:49 -07:00
Bee 0bc9326b62 Add multi-root workspace support to e2e tests (#6106)
* Add multi-root workspace support to e2e diff editor tests

- Extract shared diff editor test logic into reusable function
- Add WorkspaceType interface and workspace fixture configuration
- Create test.code-workspace file for multi-root workspace testing
- Add workspace_2 fixture directory with README
- Update test helpers to support both single and multi-root workspaces
- Add dedicated test case for diff editor in multi-root workspace

* Add verbose logging control and improve workspace parameter naming in e2e tests

- Add CLINE_E2E_TESTS_VERBOSE environment variable to control mock server logging
- Replace console.log with conditional log function in ClineApiServerMock
- Rename 'workspace' parameter to 'workspaceType' for clarity
- Rename 'workspace' function parameter to 'workspacePath' for better semantics

* Add doc string

* rename
2025-09-09 23:17:47 -07:00
Ara 92d7cdf593 Adding MultiRoot support scaffolding to tasks and adding support for multi root checkpoint manager (#5978) 2025-09-09 23:09:23 -07:00
Bee 6cc867ccb5 Replace hardcoded extension identifiers with dynamic package.json values (#6114)
* Replace hardcoded extension identifiers with dynamic package.json values

Replace hardcoded "saoudrizwan.claude-dev" and "claude-dev" strings with
dynamically imported package name and publisher from package.json across
extension activation, webview providers, commands, and test services.

* Refactor command registration to use centralized registry

- Add new registry.ts module to centralize command name management
- Replace hardcoded command strings with registry-based command names
- Import getClineCommands function to generate consistent command identifiers
- Improve maintainability by centralizing command name definitions
2025-09-09 22:56:13 -07:00
Saoud Rizwan e4325812d0 Update nightly workflow to use PublishNightly environment 2025-09-09 20:14:48 -07:00
Nick Baumann 8e0a70e38d Docs/zai coding plans (#6113) 2025-09-09 17:45:20 -07:00
Bee 272e162952 Add nightly release automation with GitHub Actions (#6041)
* Add nightly release automation with GitHub Actions

- Add GitHub workflow to publish nightly releases daily at 00:00 UTC
- Add publish:marketplace:nightly npm script
- Create publish-nightly.mjs script to handle version updates and publishing
- Script converts package to "cline-nightly" with timestamp-based versioning
- Publishes to both VS Code Marketplace and OpenVSX Registry

* Update file name

* Remove input tag

* Change nightly build schedule from midnight to 4 AM PST

- Change nightly build schedule from midnight to 4 AM PST
- Add check to skip build if no commits in last 24 hours
- Disable nightly extension in VS Code debug configs to avoid conflicts

* add if: github.repository == 'cline/cline'
2025-09-09 16:50:47 -07:00
Bee 78b47e3ebd dev: Configure auto-fix and import organization on save in VSCode (#6109)
* dev: Configure auto-fix and import organization on save in VSCode

Add editor.codeActionsOnSave settings to automatically fix linting issues,
remove unused imports, and organize imports using Biome when saving files.

* biome specific
2025-09-09 15:47:01 -07:00
Saoud Rizwan 8a97a88fb8 hotfix: remove grok-code-fast-1 promotion deadline (#6111) 2025-09-09 15:13:45 -07:00
Sarah Fortune 1caaf7d6ca Remove unused functions from vscode wrapper (#6108)
Remove unused function get/setState()
2025-09-09 14:38:08 -07:00
Sarah Fortune f1cd1518fb Remove Host Bridge watch service (#6090)
* Remove Host Bridge watch service

Replace the host bridge file watch service with native JS module chokidar.

Remove the watch service and references to it.

* Remove references to watch service from host provider
2025-09-09 12:29:41 -07:00
Jose Castelli 97dadea068 Adding hooks to record getlateststate for testing purposes (#6072)
Adding hooks to record getlateststate for testing purposes #6072
2025-09-09 21:24:22 +02:00
Sarah Fortune 28b5c1de24 Remove references to vscode.env.uriScheme (#6091)
On JetBrains getTelemetrySetting returns UNSUPPORTED. So, we do not need to check specifically for VSCode.
2025-09-09 12:06:07 -07:00
celestial-vault 6cd99c7738 Add comprehensive clean scripts to package.json (#6102)
- Add clean:build to remove build artifacts (dist, dist-standalone, webview-ui/build, src/generated, out/)
- Add clean:deps to remove node_modules directories (root and webview-ui)
- Add clean:all to run both clean:build and clean:deps
- Rename original clean command to clean:build for better organization
2025-09-09 10:56:51 -07:00
Jose Castelli 9b750783c9 Add gRPC recorder request filtering logic to make it more generic and configurable (#6070)
Add gRPC recorder request filtering logic to make it more generic and configurable #6070
2025-09-09 19:01:32 +02:00
Jose Castelli 592e1a6d49 Simple cli to trigger spec file calls against the standalone extension core (#6029)
Simple cli to trigger spec file calls against the standalone extension core #6029
2025-09-09 17:43:12 +02:00
Jose Castelli c30b2158e3 Add optional middleware for recording gRPC calls in grpc handlers (#6024)
Add optional middleware for recording gRPC calls in grpc handlers
2025-09-09 16:49:20 +02:00
Will Hardwick-Smith 26a47722aa Fix: LiteLLM extended thinking mode params for anthropic models (#5939)
* correctly set ext thinking tokens when max output set to default
-1, unset temperature on anthropic models in ext thinking mode

* fix wrong parenthesis location
2025-09-08 23:27:07 -07:00
Bee ce426c0344 Remove extension telemetry config check from PostHogTelemetryProvider (#6093)
Remove the extension telemetry config check from PostHogTelemetryProvider, which was looking at the wrong location which never get sets.
We should rely on setOptIn() for user preference management via UI which gets invoked when webview called the updateTelemetryState method in TelemetryService, which gets called in src/core/controller/ui/initializeWebview.ts
2025-09-08 18:54:30 -07:00
Sarah Fortune 461f02bd25 Remove unused file (#6092) 2025-09-08 18:37:24 -07:00
Sarah Fortune 9fe16941a3 Add telemetry APIs to the list of VSCode APIs that have been migrated. (#6089) 2025-09-08 18:13:35 -07:00
Sarah Fortune b93adc20af Move vscode.env.onDidChangeTelemetryEnabled to the Host Bridge (#6080)
* Add vscode.env.onDidChangeTelemetryEnabled to the Host Bridge

Add a streaming method to the host bridge that returns a message when
the host telemetry setting is changed.

Replace uses of vscode.env.onDidChangeTelemetryEnabled with `subscribeToTelemetrySettings`.

* Apply suggestion from @ellipsis-dev[bot]

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

* Remove debug logs

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-09-08 16:00:57 -07:00
Ara 7ccf7a8bb5 Fixing Extra code being hit by telemetry (#6086) 2025-09-08 15:25:28 -07:00
Sarah Fortune 8f9de630b3 Switch to getting the telemetry settings from the Host Bridge (#6079) 2025-09-08 15:01:53 -07:00
Sarah Fortune 87c4965110 Use ripgrep directly for @mentions (#6067)
Don't use the host bridge to search for files.
Remove searchFiles from the workspace.proto
2025-09-08 12:46:23 -07:00
Jose R. Perez 4f35a5975a feat: adding hubspot analytics to docs (#6081)
* feat: adding hubspot analytics to docs

* Update docs/hubspot.js

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

* Update docs/hubspot.js

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-08 12:06:38 -07:00
Sarah Fortune 17fd4ceb7f Prevent VSCode API calls from being re-introduced. (#6075)
* Prevent VSCode API calls from being re-introduced.

Add more grit patterns for the VSCode.

* Dont check for telemetry APIs yet
2025-09-08 11:58:36 -07:00
Sarah Fortune a231ee4d5c Use HostBridge to open diff (#6076)
* Use HostBridge to open diff

Use the host bridge to multi file diff. Using the VSCode API directly will not work on JetBrains.

* Use await
2025-09-08 11:20:36 -07:00
Sarah Fortune 531a272a63 Remove uses of VSCode API (#6073)
Remove uses of the VSCode API that was reintroduced in #5667.

The VSCode API is not portable, code using it will not work on JetBrains,
2025-09-08 07:13:10 -07:00
yuvalman 6b9ac49d0a feat: fetch deployment id in design-time instead of runtime (#6052) 2025-09-08 06:56:55 -07:00
Sarah Fortune 6d42a3fe0c Refactoring: Move the host bridge client out of the protobus-service file. (#6062) 2025-09-08 02:10:30 -07:00
Sarah Fortune 5c9c37a075 Remove uses of the VSCode API (#6071)
* Remove use of VSCode API

Remove unused field `disposables`.

* Remove unused field disposables
2025-09-08 01:28:49 -07:00
Sarah Fortune d08c394f68 Use the correct binary path for cline-core (#6065)
Binaries will be the cwd.

When tools fail with an error, log the exception to the console. This makes debugging cline-core easier.

# Conflicts:
#	src/services/ripgrep/index.ts
#	src/standalone/cline-core.ts
2025-09-07 22:14:29 -07:00
Sarah Fortune c0ca9889ff Add platform-agnostic support for ripgrep (#6063)
Add a method to the host provider that returns the location of the ripgrep binary.

Update the places where ripgrep is called.
2025-09-07 21:39:13 -07:00
Sarah Fortune fc19697fad Support node modules that include binaries in cline-core (#6046)
* Fix check for debug build in package-standalone script

* Support node modules that include binaries

Add support to the scripts/package-standalone.js for node modules that use platform-specific binary modules.

By default the script bundles the module for all platforms, this can be disabled with -s for single platform builds.

The module for each platform will be bundled into standalone.zip in platform specific directories:
```
binaries/linux-arm64/node_modules
binaries/darwin-x64/node_modules
binaries/win32-x64/node_modules
binaries/darwin-arm64/node_modules
binaries/linux-x64/node_modules
```

When running cline-core add the correct directory to the NODE_PATH, e.g.
```
$ export NODE_PATH=./node_modules/:./binaries/darwin-arm64/node_modules/
cline:/tmp/1$ node cline-core.js
Loading stubs...
Finished loading stubs
Loading stub impls...
Finished loading stub impls...
Cline environment: production
XS variant configuration warnings: [
  'Component overrides for unused components: TOOL_USE_SECTION, TOOLS_SECTION, MCP_SECTION, TODO_SECTION, FEEDBACK_SECTION',
  'Missing recommended components: TOOL_USE_SECTION'
]
[2025-09-05T19:53:00.853] #bot.cline.server.ts Running standalone cline  0.0.1
[2025-09-05T19:53:00.854] #bot.cline.server.ts Using settings dir: /Users/sjf/.cline/data
Finished loading vscode context...
[2025-09-05T19:53:00.858] #bot.cline.server.ts

Starting cline-core service...

sjfsjf created DBBBBBBBBB:  Database {
  name: '/tmp/db.sql',
  open: true,
  inTransaction: false,
  readonly: false,
  memory: false
}
```

* Apply suggestion from @ellipsis-dev[bot]

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

* Apply suggestion from @ellipsis-dev[bot]

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

* Support node modules that include binaries

Add support to the scripts/package-standalone.js for node modules that use platform-specific binary modules.

By default the script bundles the module for all platforms, this can be disabled with -s for single platform builds.

The module for each platform will be bundled into standalone.zip in platform specific directories:
```
binaries/linux-arm64/node_modules
binaries/darwin-x64/node_modules
binaries/win32-x64/node_modules
binaries/darwin-arm64/node_modules
binaries/linux-x64/node_modules
```

When running cline-core add the correct directory to the NODE_PATH, e.g.
```
$ export NODE_PATH=./node_modules/:./binaries/darwin-arm64/node_modules/
cline:/tmp/1$ node cline-core.js
Loading stubs...
Finished loading stubs
Loading stub impls...
Finished loading stub impls...
Cline environment: production
XS variant configuration warnings: [
  'Component overrides for unused components: TOOL_USE_SECTION, TOOLS_SECTION, MCP_SECTION, TODO_SECTION, FEEDBACK_SECTION',
  'Missing recommended components: TOOL_USE_SECTION'
]
[2025-09-05T19:53:00.853] #bot.cline.server.ts Running standalone cline  0.0.1
[2025-09-05T19:53:00.854] #bot.cline.server.ts Using settings dir: /Users/sjf/.cline/data
Finished loading vscode context...
[2025-09-05T19:53:00.858] #bot.cline.server.ts

Starting cline-core service...

sjfsjf created DBBBBBBBBB:  Database {
  name: '/tmp/db.sql',
  open: true,
  inTransaction: false,
  readonly: false,
  memory: false
}
```

* Apply suggestion from @ellipsis-dev[bot]

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

* Apply suggestion from @ellipsis-dev[bot]

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

* Apply suggestion from @ellipsis-dev[bot]

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

* Remove test code

* Use the correct target directory for the binaries

The directory structure that the JB host expects is does
not exactly match ${arch}-${os}

* Update package-standalone script

Warn if there is module that needs binaries, but it is not being used.
Reset the binaries dir before packaging.

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-09-07 16:31:06 -07:00
Sarah Fortune f64e8ddbf7 Remove warning about using int64 in proto files (#6061) 2025-09-07 14:42:22 -07:00
Sarah Fortune 70d1dce34f Increase the compression level for standalone.zip (#6056)
This reduces the size of the zip from 18MB to 15MB, it doesn't really change the amount of time it takes to make the zip.
2025-09-06 11:57:54 -07:00
watany 950142fdfb feat(gpt) reasoning effort minimal (#5900)
* feat(OpenAI): Reasoning Effort Minimal

* changeset
2025-09-05 21:32:47 -07:00
Bee 41765fc29a Fix styling for TelemetryBanner and SettingsView (#6031)
* Fix styling for TelemetryBanner and SettingsView

- Replace styled-components with Tailwind classes in TelemetryBanner
- Add performance optimizations to SettingsView with memoization and debouncing
- Update Tailwind config to support new banner color variables
- Improve component structure and reduce bundle size

* use lodash

* memo content map

* Update E2E test
2025-09-05 20:51:35 -07:00
Bee e5f8c048ce Re-render account view on auth change (#6043)
* Add key prop to ClineAccountView

Add key prop to ClineAccountView to force re-render on user change

Add key={clineUser.uid} to ClineAccountView component to ensure proper
component re-mounting when user changes, preventing stale state issues.

* changeset added
2025-09-05 20:38:50 -07:00
Saoud Rizwan 83de7bb2f1 Fix bug where user message for mistake_limit_reached was not being shown in chat view (#5965) 2025-09-05 20:12:02 -07:00
Bee 6c842c145f sets Biome as global default formatter (#6045)
Replace language-specific Biome formatter settings with a single global default formatter configuration for the repo.
2025-09-05 17:25:32 -07:00
Sarah Fortune 09adaca575 Fix check for debug build in package-standalone script (#6044) 2025-09-05 15:41:29 -07:00
Bee 0b1a237290 Unify tool name vars (#6012)
* Use ClineDefaultTool

* Use ClineDefaultTool
2025-09-05 11:18:55 -07:00
canvrno cb1bda9b5c Checkpoints refactor (#4452)
* add grok coder free model to cline provider (#5808)

* add free grok-coder-free model to cline provider

* add changeset

* fix typo

* checkpoints class created

* Added saveCheckpoint to Checkpoint class

* Rebased and updated for new ClineMessages

* Moved things around, started on saveCheckpoint

* implemented handler for checking and initializing the checkpointTracker if not already done

* Moved restoreCheckpoint and handleSucessfullRestore to checkpoints class

* Moved presentMultiDiff, not yet connected

* Migrated doesLatestTaskCompletionHaveNewChanges and compelted migration on presentMultifileDiff

* Better init handling

* moved fileContextTracker to new checkpoints class

* Checkpoints state management

* refactoring and cleanup in saveCheckpoint, init handler

* More saveCheckpoint refactoring

* Added sayTs return to say function for better async clineMessages updates

* Refactor checkpoint system with timestamp tracking and dependency separation

* More refactoring

* Friendship ended with checkpointTracker, checkpointManager is new best friend

* Better error handling

* checkpointTrackerErrorMessage > checkpointManagerErrorMessage

* Addressed possible race condition with message(Ts)

* Better error handling and 15s timeout changes

* Remove checkpoint delegation methods and call checkpoint manager directly

* updating checkpoints protos

* cleanup

* Restored autoApprove entry to task class

* cleanup

* cleanup

* Post-rebase fixes

* Migrated timeout and state changes from PR #5015

* Extract toolExecutor callback functions to private methods for readability

* Updated info/error messages to use HostProvider

* post rebase fixes

* Compare/diff button fix

* Fix lint errors

* Update webview-ui/src/components/chat/task-header/TaskHeader.tsx

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

* Update src/integrations/checkpoints/index.ts

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

* Fixed bad merge, updated focus change for compatability with new say()

* Fixed error message propagation issue

---------

Co-authored-by: pashpashpash <nik@cline.bot>
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-09-05 00:06:53 -07:00
canvrno 5dfd16359d e2e tests for slash/mentions in chat text area (#6022)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-04 22:46:23 -07:00
arman-sambanova 64a8096f96 sambanova provider: add DeepSeek-V3.1 (#6001) 2025-09-04 22:19:00 -07:00
Saoud Rizwan e5a1d11179 Fix empty taskHistory.json file being read and parsed on startup, leading to crash (#6016) 2025-09-04 22:16:10 -07:00
Wei Chen 5af6e8d5ed Improve the deep-planning prompt by excluding dependency folders on find commands (#5884) 2025-09-04 22:15:50 -07:00
Bee 6ecadfc7a1 fix parameterless tool docs in system prompt (#6018)
- Recognize GPT-5 IDs (including openai/gpt-5) in model family detection and variants
- Add GPT-5 (OpenAI) to integration matrix and unit tests
- Update snapshot test instructions to use npm run test:unit -- --update-snapshots
- Fix PromptBuilder: don’t early-return on missing params; init to [] to keep output consistent
- Tidy test diff formatting (braces, explicit returns)
- Polish load_mcp_documentation tool description
2025-09-04 21:03:59 -07:00
Saoud Rizwan eb3158c83d Fix updating focus chain when attempt_completion is called (#6019) 2025-09-04 20:54:13 -07:00
Saoud Rizwan 625b701a68 Update branch for hotfix adding new Kimi K2 model to Groq and Moonshot providers (#6017)
* Add 200k context window variant for Claude Sonnet 4 to OpenRouter and Cline providers

* v3.26.7 Release Notes

* Fix grok-code-fast-1 info

* v3.27.0 Release Notes

* Add new kimi model to groq and moonshot providers

* v3.27.1 Release Notes
2025-09-04 20:27:06 -07:00
pashpashpash dd59acf0fb Change supportsPromptCache to false (#6013) 2025-09-04 18:38:11 -07:00
pashpashpash 335d0ffa05 adding new kimi model to groq and moonshot providers (#6006)
* adding new kimi model to groq and moonshot providers

* added fireworks provider too

* fixing fireworks test

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-09-04 17:47:58 -07:00
canvrno 3f341d9cf7 Fix: Slash command / mention features remove following word (#5986)
* Fixed issue where slash command feature would remove first word after the command name

* Removed slashCommandsQueryRef

* Add fix for mentions as well

* Updated mentions test

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-09-04 12:01:13 -10:00
celestial-vault 0adb1046e4 fix taskHistory migration (#6004)
* fix taskHistory migration when run across main and the prod version which use the old and the new location

* Update src/core/storage/state-migrations.ts

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

* Update src/core/storage/state-migrations.ts

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

* Update src/core/storage/state-migrations.ts

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

* Update src/core/storage/state-migrations.ts

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

* Update src/core/storage/state-migrations.ts

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

* Adding Multi root algo

* Adding Multi root algo

* Simplify the migration function

Simplify the migration function by consolidating conditional logic,
removing redundant logging, and using concurrent operations for
better performance. The logic now handles both empty and populated
destination scenarios more clearly.

* update

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
Co-authored-by: abeatrix <beatrix@cline.bot>
2025-09-04 14:45:24 -07:00
Sarah Fortune 324564af72 Don't keep regenerating the telemetry UUID (#6005)
Some environments do not return a value for the vscode machine ID.
For these cases we are generating a UUID. But the UUID was not being stored, so a new one was being created everytime the extension started.

Start storing the generated ID in the global state.

I am changing the name of the key to be more descriptive, because we only want to store the generated ID. If there is an actual machine ID, we should just use that and not store it. The old key name was only ever been read, it was never written, so this will have no affect on existing users.
2025-09-04 12:39:27 -07:00
JicLotus 291287c8e4 chord: Optional gRPC session recording system to improve observability (#5999)
chord: Optional gRPC session recording system to improve observability
2025-09-04 21:26:58 +02:00
Bee d69fb10cfd fix: only focus chat input when in chat view (#5991)
* fix: only focus chat input when in chat view

- Only focus chat input when chat view is visible, not when hidden (in other view)
- Wrap onDone callback in arrow function for consistency
- Replace inline styles with Tailwind classes for button container

* update gap value
2025-09-04 10:39:09 -07:00
celestial-vault 0f6eab2bfe make proto objects not optional by default (#5985) 2025-09-03 19:47:14 -07:00
Saoud Rizwan 016ac1eade Fix diff viewer failing showing incorrect error message (#5988) 2025-09-03 19:17:34 -07:00
Bee 2606ed7abf Remove CI environment check from PostHog config selection (#5987)
Remove process.env.CI check and rely only on IS_DEV flag to determine whether to use development or production PostHog configuration.
This is because process.env.CI is always true during the publish GitHub workflow.
2025-09-03 19:07:32 -07:00
Ara 3ed4d55a36 Add telemetry tracking for terminal hang detection and user intervention (#5955)
* Add telemetry tracking for terminal hang detection and user interventions

- Add terminal hang detection with configurable timeouts for buffer stuck, stream timeout, and completion waiting stages
- Track user interventions when clicking "Process while Running" button
- Add telemetry for terminal output failures with specific failure reasons
- Implement comprehensive monitoring of terminal process lifecycle events
- Add metrics for shell integration usage and terminal operation performance

* Remove Shortcut of Cline from its title

* Remove Shortcut of Cline from its title

* Remove Shortcut of Cline from its title
2025-09-03 16:42:45 -07:00
celestial-vault a3b4ad53dc Add filewatcher to taskHistory (#5910)
* add filewatcher to taskHistory to update across Cline instances

* changeset
2025-09-03 12:08:51 -07:00
celestial-vault bd98955f57 Move updateDefaultTerminalProfile RPC into updateSettings RPC (#5976)
* move browserSettings rpc into updateSettings

* move updateDefaultTerminalProfile rpc into updateSettings rpc
2025-09-03 11:53:56 -07:00
celestial-vault 297cfbb895 move browserSettings rpc into updateSettings (#5959) 2025-09-03 11:40:29 -07:00
canvrno b4c95fbeab Respect user's settings when evaluating feature flag for focus chain (#5969)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-09-03 08:32:35 -07:00
JicLotus 5e8102e588 chord: Helper script for testing standalone Core API server (#5944)
* chord: Adding a new standalone core api server script for local and integration testing purposes
2025-09-03 08:54:58 +02:00
Saoud Rizwan 60f2c3a22b Update bug report template: correct model name to "Claude Sonnet 4" and change model section validation from required to optional. 2025-09-02 21:48:11 -07:00
Saoud Rizwan 7472b1cb4a Fix github issue default value 2025-09-02 21:45:57 -07:00
Saoud Rizwan 794d8bccd3 Fix github issue template formatting 2025-09-02 21:45:02 -07:00
Saoud Rizwan 0db3cfe34d Enhance bug report template with additional fields for plugin type and Cline version. Update placeholder text for provider/model input. Remove required validation for logs section. 2025-09-02 21:41:52 -07:00
Nick Baumann 5c878b5b84 Jetbrains docs (early access language tweaks) (#5957)
* docs: Update Claude Code documentation to include Pro plans alongside Max plans

* Add JetBrains installation documentation

- Create comprehensive installation guide for JetBrains IDEs
- Include both marketplace and manual installation methods
- Document supported IDEs and key differences from VSCode
- Add alpha status note and terminal integration limitations
- Update docs.json navigation to include new page

* Add images to JetBrains installation documentation

- Add demo GIF showing Cline in action in JetBrains IDE
- Add screenshot of JetBrains marketplace download page
- Add screenshot of Install Plugin from Disk dialog
- Add screenshot of file selection dialog with zip file
- Complete visual walkthrough of installation process

* Update JetBrains demo to high-quality GIF

- Replace jetbrains-demo.gif with jetbrains-demo-hifi.gif
- Improved visual quality for better user experience

* Add JetBrains settings dialog screenshot

- Add screenshot showing the main settings dialog
- Provides visual guidance for accessing IDE settings
- Complete visual walkthrough now includes 5 screenshots

* Add JetBrains logo and finalize documentation

- Add JetBrains logo at top of page with proper styling
- Update content with user revisions (BYOK note, streamlined structure)
- Complete visual installation walkthrough with 5 images
- Ready for PR review

* Update early access messaging

- Change from 'You're getting early access' to 'Cline is in early access'
- More professional and product-focused messaging
- Maintains excitement while being clearer about the product status

* Update installation link for Cline plugin

---------

Co-authored-by: pashpashpash <nik@cline.bot>
2025-09-02 17:13:38 -07:00
Ara e3bc5f0143 Setup Raw Structure for implementing multi-workspace support with WorkspaceRoot (#5849)
* Setup Raw Structure for implementing multi-workspace support with WorkspaceRoot

* Remove Shortcut of Cline from its title
2025-09-02 16:14:55 -07:00
Igor Tceglevskii f2dbab814e root folder path comparison on windows (#5938) 2025-09-02 14:26:05 -07:00
Bee b3abbd886e Update PostHog config to use dev environment in CI (#5954)
Add CI environment check to PostHog configuration logic to ensure
dev environment is used in both CI and local development contexts
2025-09-02 13:37:21 -07:00
Ara 8cdc4a936d Remove Shortcut of Cline from its title (#5952) 2025-09-02 13:14:54 -07:00
Nick Baumann ecc58178dc Jetbrains docs (#5948)
* docs: Update Claude Code documentation to include Pro plans alongside Max plans

* Add JetBrains installation documentation

- Create comprehensive installation guide for JetBrains IDEs
- Include both marketplace and manual installation methods
- Document supported IDEs and key differences from VSCode
- Add alpha status note and terminal integration limitations
- Update docs.json navigation to include new page

* Add images to JetBrains installation documentation

- Add demo GIF showing Cline in action in JetBrains IDE
- Add screenshot of JetBrains marketplace download page
- Add screenshot of Install Plugin from Disk dialog
- Add screenshot of file selection dialog with zip file
- Complete visual walkthrough of installation process

* Update JetBrains demo to high-quality GIF

- Replace jetbrains-demo.gif with jetbrains-demo-hifi.gif
- Improved visual quality for better user experience

* Add JetBrains settings dialog screenshot

- Add screenshot showing the main settings dialog
- Provides visual guidance for accessing IDE settings
- Complete visual walkthrough now includes 5 screenshots

* Add JetBrains logo and finalize documentation

- Add JetBrains logo at top of page with proper styling
- Update content with user revisions (BYOK note, streamlined structure)
- Complete visual installation walkthrough with 5 images
- Ready for PR review
2025-09-02 12:45:31 -07:00
celestial-vault ca3f0f1abd don't delete old location of taskHistory in migration for now (#5931) 2025-09-02 11:21:53 -07:00
celestial-vault 987812a886 add taskHistory size fetch after deleting all tasks to refresh size displayed (#5932) 2025-09-02 11:21:24 -07:00
Sarah Fortune 0e6afd9848 Add the OS name and version to the telemetry metadata (#5946)
Add the OS name and version to the telemetry metadata properties.
Update the test.
2025-09-02 10:52:40 -07:00
Bee 359e0e070d fix: use retry functionality for failed API requests and disable send btn (#5892)
- Add "retry" action type to ButtonActionType
- Update api_req_failed button config to use retry action with disabled sending
- Implement retry handler in useMessageHandlers to send simple approval and clear input state
2025-09-02 10:17:04 -07:00
Sarah Fortune b02ad8377d Add the host IDE metadata to the telemetry events (#5945)
Add properties to the telemetry events for the host environment name and version.

Add a .create() function to the TelemetryService because we can't use async in the constructor. (Getting the host platform version is async).
2025-09-02 09:21:18 -07:00
Sarah Fortune 8fdf5ab8c5 Fix bug in distinctId (#5943)
getMachineId was not returning the correct value and a new distint ID was getting generated every time the extension started.

Add tests and logging for distinctId.ts
2025-09-02 08:37:30 -07:00
Ara aceaeb069b Fixing failing webview test (#5933)
* Fixing failing webview test

* Fixing failing webview test
2025-09-01 16:22:35 -07:00
celestial-vault e39e58b5e2 add no unused imports error (#5911) 2025-09-01 15:44:38 -07:00
Saoud Rizwan 717be3f026 Fix grok-code-fast-1 model information and add promo in Announcement banner (#5926)
* Fix grok-code-fast-1 info

* Add call to action for trying free `grok-code-fast-1` in Announcement banner
2025-09-01 05:41:18 -07:00
Saoud Rizwan 5595d12dc3 fix (templated system prompt): add TASK_PROGRESS_PARAMETER to various tools and update descriptions (#5908)
* Add TASK_PROGRESS_PARAMETER to various tools and update descriptions

- Introduced TASK_PROGRESS_PARAMETER to enhance task tracking across multiple tools.
- Updated tool descriptions for clarity and consistency, including detailed instructions and usage examples.
- Adjusted existing parameters to improve user guidance and ensure proper tool functionality.

* update snapshots

* do not remove new lines within section around divider

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-08-30 22:41:24 -07:00
Saoud Rizwan c230de0a14 Disable buttons immediately after click (#5902) 2025-08-30 11:53:26 -07:00
celestial-vault 2ecb87ac5a Move task history to file storage (#5877)
* Move task history to file storage

* add console logs to migration

* update code comment
2025-08-30 10:45:31 -07:00
Saoud Rizwan 2315fc6769 Fix write_to_file tool diff streaming, discrepencies with original tool execution, attempt_completion command issue, and input not clearing when hitting approve (#5903)
* Fix write_to_file tool diff streaming

* Fix discrepencies with original tool execution logic

* Fix attempt completion command leading to 'ask promise was ignored' error

* Fix input not being cleared when hitting approve button
2025-08-30 06:15:09 -07:00
Ara 6449c36849 Revert "Adding frequency penalty for gemini models (#5893)" (#5898)
This reverts commit 10cfd8ba1e.
2025-08-30 00:35:36 -07:00
Saoud Rizwan 8f93e9cc40 Fix browser session not being persisted between browser tool calls (#5901) 2025-08-30 00:21:32 -07:00
Saoud Rizwan 3a52baac14 Fix ToolExecutor refactor issue where user feedback for tool use is ignored (#5899)
* Fix ToolExecutor refactor issue where user feedback for tool use is ignored

* Deduplicate code

* Fix merge conflicts
2025-08-30 00:18:54 -07:00
Tomás Barreiro 35f08731f6 fix: Improve Gemini Rate Limit handling (#5205)
* Pass all options to the handlers

* Do not pass all options

* Have onRetryAttempt as a common option

* Update the Gemini CLI

* Throw a RetriableError and extract retry delays from the error responses

* Add changeset

* Throw a RetriableError if extracting the delay fails

* Improve parseRetryDelay

* Add fallback
2025-08-29 20:58:04 -07:00
Bee 2c866c9265 Refactor posthog service providers and centralize distinct ID management (#5705)
* Refactor services architecture with provider pattern and factory classes

- Extract telemetry, error handling, and feature flags into separate service modules
- Implement provider pattern with factory classes for better abstraction
- Move PostHog-specific implementations to dedicated provider classes
- Add interfaces for telemetry, error, and feature flags providers
- Update imports across codebase to use new service structure
- Add unit tests for telemetry service

* Refactor service providers and centralize distinct ID management

- Move provider interfaces to dedicated providers/ subdirectories
- Extract distinct ID management to shared logging/distinctId module
- Simplify PostHogClientProvider by removing distinct ID parameter
- Update service factories to use centralized distinct ID
- Reorganize test files to __tests__/ directories
- Remove redundant distinct ID handling across services

* merge main

* clean up

* add grok coder free model to cline provider (#5808)

* add free grok-coder-free model to cline provider

* add changeset

* fix typo

* v3.26.6 Release Notes (#5788)

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.26.6 with user-friendly 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>

* Remove top padding from ActionButtons component (#5806)

Eliminate unnecessary top padding in the chat view.

* removing middle out from params to or / cline providers (#5811)

* Dify.ai integration (#5761)

* add focus chain settings to statemanager initialize function (#5798)

* add custom gpt-5 system prompt (#5757)

* gpt-5 system prompt

* add changeset

* Focus chain telemetry tweaks (#5810)

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Remove eslint-rules test patterns from Mocha spec configuration (#5812)

Update the "spec" array in .mocharc.json to exclude "eslint-rules/__tests__/**/*.test.ts",
as that directory has been removed.

* Increase horizontal margin in AutoApproveBar component (#5813)

Update the mx-[5px] to mx-[15px] in the div's className to adjust horizontal spacing for improved layout alignment.

* fix: remove hardcoded Ollama host from options (#5816)

* fix: remove hardcoded Ollama host from options

Updates the Ollama handler to remove the hardcoded "http://localhost:11434" as the `ollamaBaseUrl` fallback option for the host to allow the Ollama SDK to handle the default endpoint configured on users' machine.

Reason: Ollama allows cross-origin requests from 127.0.0.1 and 0.0.0.0 by default. However, when we use localhost, the browser would resolve it through DNS, which can result in different IP addresses.

Docs: https://github.com/ollama/ollama/blob/main/docs/faq.md#how-can-i-expose-ollama-on-my-network

* add changeset

* deep-planning prompt PowerShell (#5699)

* Windows/Powershell specific deep planning prompt changes

* Prompt adjustments

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Changes to condenseToolResponse & summarizeTask prompting (#5817)

* Condense & deep planning prompt adjustments

* Removed ps prompting ready for PR

* rebase

* Fixed typo on one word

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* rename CacheService to StateManager (#5681)

* rename CacheService to StateManager

* fix types

* infer state key types from existing interfaces (#5815)

* fix: AutoApproveModal positioning and scrolling behavior (#5819)

* fix: AutoApproveModal positioning and scrolling behavior

- Add dynamic positioning calculation to prevent modal overflow
- Implement proper flex layout with scrollable content container
- Ensure minimum usable height and top margin constraints
- Fix modal positioning when button is near viewport edges

* Add changeset

* clean up

* template-based system prompt (#5731)

* Refactor system prompt architecture with new template-based system

- Move existing system prompt files to legacy directory
- Implement new modular system with PromptBuilder, PromptRegistry, and TemplateEngine
- Add component-based prompt structure with reusable parts (capabilities, rules, tool_use, etc.)
- Create variant-specific templates for generic and next-gen models
- Add comprehensive test suite with snapshots for different model configurations
- Introduce template engine with placeholder support for dynamic prompt generation

* Refactor system prompt architecture with modular tool definitions

- Extract tool specifications into dedicated modules under tools/
- Add ClineToolSet class for managing tool variants by model family
- Restructure prompt components with centralized index exports
- Update prompt builder and registry to support new tool architecture
- Reorganize shared utilities and type definitions
- Update all test snapshots to reflect new prompt structure

* Update snapshots

* reorg

* Update template format

* clean up

* typos

* focus chain section

* fix task progress in attempt_completion

* Implement tool retrieval with fallback options in PromptBuilder

- Added `getToolByNameWithFallback` and `getToolsForVariantWithFallback` methods to `ClineToolSet` for improved tool resolution.
- Updated `getToolsPrompts` in `PromptBuilder` to utilize these new methods, allowing for better handling of tool requests with fallback to generic tools.
- Enhanced sorting and filtering of tools based on context requirements and requested order.

* update fild structure

* clean up

* fix static test string

* Update snapshot names

* Update unit test

* Remove unused placeholders and update docs

* Update README on how to add new tool

* Remove task_progress reference from attempt_completion tool description when focus chain is disabled

* Upgrade posthog-node to v5.8.0 and add exception filtering

- Update posthog-node from v4.8.1 to v5.8.0
- Add EventMessage import for type safety
- Implement posthogEventFilter to only capture exceptions from Cline extension
- Filter exceptions by checking for "cline" in error messages or "saoudrizwan" in stack frames

* Use env var keys

- Add PostHogClientConfig to ErrorProviderFactory with proper validation
- Update PostHogErrorProvider to use dedicated client instead of shared one
- Add API key validation in PostHogFeatureFlagsProvider before client creation
- Enhance error handling with fallback to NoOpErrorProvider instead of throwing
- Standardize configuration passing across telemetry, error, and feature flag services

* Upadte filter

* update filter

* update imports

* use secret

* disable enableExceptionAutocapture

* removes vscode.env.machineId

* initializeDistinctId

* use get trap as workaround

* on exit

---------

Co-authored-by: pashpashpash <nik@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: Toshii <94262432+0xToshii@users.noreply.github.com>
Co-authored-by: Yunus Emre AYHAN <ayhanyunusemre@gmail.com>
Co-authored-by: celestial-vault <58194240+celestial-vault@users.noreply.github.com>
Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-29 18:27:35 -07:00
Ara 10cfd8ba1e Adding frequency penalty for gemini models (#5893)
* Adding frequency penalty for gemini models

* Adding frequency penalty for gemini models

* Adding frequency penalty for gemini models

* Adding frequency penalty for gemini models

* Adding frequency penalty for gemini models
2025-08-29 17:24:38 -07:00
Saoud Rizwan da4d88fd84 hotfix: Add 200k context window variant for Claude Sonnet 4 to OpenRouter and Cline providers (#5894)
* Add 200k context window variant for Claude Sonnet 4 to OpenRouter and Cline providers

* v3.26.7 Release Notes
2025-08-29 16:56:50 -07:00
celestial-vault 889ed95840 fix z index mcp response dropdown (#5882) 2025-08-29 12:48:01 -07:00
Toshii 716e6cd6ab changing prompts for the context management (#5854)
* changing prompts for the context management

* distinction between the tool call options
2025-08-29 12:22:48 -07:00
Bee 45871a962e fix: improve caching and prevent duplicate fetches in AccountView (#5883)
* fix:  improve caching and prevent duplicate fetches in AccountView

- Wrap cacheCurrentData in useCallback with proper dependencies
- Add initialFetchCompleteRef to track mount fetch completion
- Improve organization change handling to prevent race conditions
- Remove biome-ignore comments for exhaustive dependencies
- Replace mb-[5px] with mb-1.5 for consistent Tailwind spacing

* changeset added
2025-08-29 11:18:55 -07:00
Sarah Fortune c6aa47095e Fix int32 overflow in the models proto (#5881)
Cline-core is setting some of these values in the models proto to the javascript Number.MAX_SAFE_VALUE, which won't fit in int32, so these protobuf messages fail to serialize to and can't be transported.

Just change all the int32s in this file to int64 beceause this is the second time this same issue has occured.

Fixes:
```
2025-08-28 16:30:03,824 [   3479]   WARN - bot.cline.services.ProtoBusProxyService - Stream cline.ModelsService.subscribeToOpenRouterModels encountered error
io.grpc.StatusException: INTERNAL: invalid int32: 9007199254740991
        at io.grpc.Status.asException(Status.java:548)
        at io.grpc.kotlin.ClientCalls$rpcImpl$1$1$1.onClose(ClientCalls.kt:300)
        at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:564)
        at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:72)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:729)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:710)
        at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Wor
```
2025-08-28 18:44:56 -07:00
Bee 8c1093cfdc add health checks and generic fallback to PromptRegistry (#5879)
* fix: Harden PromptRegistry with health checks and generic fallback

- Perform registry health check after loading (validate GENERIC, log counts/warnings)
- Always try GENERIC when family-specific variant is missing
- Enhance error diagnostics with available variants and registry state
- Ensure GENERIC variant exists; create minimal fallback if loading fails
- Minor test style cleanup and variants index update to support reliability

* simpilfy

* variants

* Fix import

* type safe

* remove lazy loading

* load and set variants

* fix import location
2025-08-28 16:39:56 -07:00
Saoud Rizwan 31161f894b Add search functionality to API provider dropdown (#5801)
* Add search functionality to API provider dropdown

* Create heavy-dolls-cry.md

* Remove unnecessary comments

* Remove unncessary comments

* Fix e2e tests checking API provide functionality

* Add Dify.ai provider

* Fix merge conflict
2025-08-28 13:32:45 -07:00
Sarah Fortune 20e5ae7b23 Don't throw an exception if deleting a directory fails. (#5868)
* Don't throw an exception if deleting a directory fails.

* Apply suggestion from @ellipsis-dev[bot]

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-08-28 13:08:33 -07:00
Toshii 22f306e79e default state for useCondense set to false (#5869) 2025-08-28 13:03:01 -07:00
Saoud Rizwan 553b56336c Update copy in README (#5871) 2025-08-28 12:23:38 -07:00
Saoud Rizwan a3fa8cf7b9 Revert "Modify workflow to publish to release to OVSX"
This reverts commit 3d5605f5d7.
2025-08-28 12:08:16 -07:00
Tomás Barreiro 4628eca3dc fix: Support Anthropic Prompt Caching when using LiteLLM (#5833)
* fix: Support Anthropic cache with LiteLLM

* Add changeset

* Fix and expand tests
2025-08-28 19:23:27 +02:00
yuvalman 518e624086 fix: sap provider - show models when resource group field is empty (and use the default value) (#5839)
* fix: sap provider - show models when resource group field is empty

* fix: sap provider - show models when resource group field is empty

* fix: sap provider - show models when resource group field is empty
2025-08-28 10:12:50 -07:00
kvyb fa4fa01ec3 feat: add openClineSidebarPanel RPC and route VS Code focus via hostbridge (#5859) 2025-08-28 19:38:19 +03:00
Toshii f526317796 swapping order of checkpoint and tool result (#5853) 2025-08-27 23:51:53 -07:00
Will Hardwick-Smith 550883df6a bugfix: fixes issue where thinking output wasn't passed through from (#5852)
litellm
2025-08-27 22:25:14 -07:00
Saoud Rizwan 3d5605f5d7 Modify workflow to publish to release to OVSX 2025-08-27 19:38:23 -07:00
Bee 1b48f06898 Update snapshots for system prompt tests (#5848)
* Update snapshots for system prompt tests

- Add detailed README.md explaining integration test workflow, snapshot testing, and troubleshooting
- Unit tests should fail when snapshots are mismatched
- Update all test snapshots across different model configurations (Anthropic Claude, OpenAI GPT)
- Refresh section title comparison data for prompt structure validation
- Improve test documentation with clear examples and failure handling guidance

* make old prompts static

* Fix old vs new comparasion mismatch
2025-08-27 15:46:51 -07:00
Bee b17631900d Remove action buttons from showing for followup and plan_mode_respond (#5846)
* Remove action buttons from showing for followup and plan_mode_respond

Set primaryText, secondaryText, and primaryAction to undefined for followup and plan_mode_respond button configurations to disable default approve/reject behavior.

* add changeset
2025-08-27 14:53:57 -07:00
canvrno 3d8d83568d Remove .sql from checkpoint exclusions (#5847)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-27 14:17:39 -07:00
Szymon Stasik 3d95adb0f3 Fix: Corrected token counting in Claude Code provider to prevent doub… (#5793)
* add grok coder free model to cline provider (#5808)

* add free grok-coder-free model to cline provider

* add changeset

* fix typo

* v3.26.6 Release Notes (#5788)

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.26.6 with user-friendly 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>

* Focus chain telemetry tweaks (#5810)

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Fix: Corrected token counting in Claude Code provider to prevent double-counting of cache tokens.

* Apply nullish coalescing operator suggestion in ClaudeCodeHandler

* Add unit tests for ClaudeCodeHandler token counting

* Apply PR review feedback: trim comments, fix imports, add documentation

* revert from upstream/main

---------

Co-authored-by: pashpashpash <nik@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: canvrno <46584286+canvrno@users.noreply.github.com>
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-27 23:01:14 +02:00
Ara 971ac0fdeb Refactor Tool Executor (#5667)
* Refactor Tool Executor

* Adding diff fix

* Fixing ordering of diff stuff
2025-08-27 13:05:35 -07:00
celestial-vault 2888af54f3 Refactor/consolidate state keys (#5831)
* add grok coder free model to cline provider (#5808)

* add free grok-coder-free model to cline provider

* add changeset

* fix typo

* v3.26.6 Release Notes (#5788)

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.26.6 with user-friendly 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>

* Remove top padding from ActionButtons component (#5806)

Eliminate unnecessary top padding in the chat view.

* removing middle out from params to or / cline providers (#5811)

* Dify.ai integration (#5761)

* add focus chain settings to statemanager initialize function (#5798)

* add custom gpt-5 system prompt (#5757)

* gpt-5 system prompt

* add changeset

* Focus chain telemetry tweaks (#5810)

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Remove eslint-rules test patterns from Mocha spec configuration (#5812)

Update the "spec" array in .mocharc.json to exclude "eslint-rules/__tests__/**/*.test.ts",
as that directory has been removed.

* Increase horizontal margin in AutoApproveBar component (#5813)

Update the mx-[5px] to mx-[15px] in the div's className to adjust horizontal spacing for improved layout alignment.

* fix: remove hardcoded Ollama host from options (#5816)

* fix: remove hardcoded Ollama host from options

Updates the Ollama handler to remove the hardcoded "http://localhost:11434" as the `ollamaBaseUrl` fallback option for the host to allow the Ollama SDK to handle the default endpoint configured on users' machine.

Reason: Ollama allows cross-origin requests from 127.0.0.1 and 0.0.0.0 by default. However, when we use localhost, the browser would resolve it through DNS, which can result in different IP addresses.

Docs: https://github.com/ollama/ollama/blob/main/docs/faq.md#how-can-i-expose-ollama-on-my-network

* add changeset

* deep-planning prompt PowerShell (#5699)

* Windows/Powershell specific deep planning prompt changes

* Prompt adjustments

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* Changes to condenseToolResponse & summarizeTask prompting (#5817)

* Condense & deep planning prompt adjustments

* Removed ps prompting ready for PR

* rebase

* Fixed typo on one word

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>

* rename CacheService to StateManager (#5681)

* rename CacheService to StateManager

* fix types

* infer state key types from existing interfaces (#5815)

* fix: AutoApproveModal positioning and scrolling behavior (#5819)

* fix: AutoApproveModal positioning and scrolling behavior

- Add dynamic positioning calculation to prevent modal overflow
- Implement proper flex layout with scrollable content container
- Ensure minimum usable height and top margin constraints
- Fix modal positioning when button is near viewport edges

* Add changeset

* clean up

* template-based system prompt (#5731)

* Refactor system prompt architecture with new template-based system

- Move existing system prompt files to legacy directory
- Implement new modular system with PromptBuilder, PromptRegistry, and TemplateEngine
- Add component-based prompt structure with reusable parts (capabilities, rules, tool_use, etc.)
- Create variant-specific templates for generic and next-gen models
- Add comprehensive test suite with snapshots for different model configurations
- Introduce template engine with placeholder support for dynamic prompt generation

* Refactor system prompt architecture with modular tool definitions

- Extract tool specifications into dedicated modules under tools/
- Add ClineToolSet class for managing tool variants by model family
- Restructure prompt components with centralized index exports
- Update prompt builder and registry to support new tool architecture
- Reorganize shared utilities and type definitions
- Update all test snapshots to reflect new prompt structure

* Update snapshots

* reorg

* Update template format

* clean up

* typos

* focus chain section

* fix task progress in attempt_completion

* Implement tool retrieval with fallback options in PromptBuilder

- Added `getToolByNameWithFallback` and `getToolsForVariantWithFallback` methods to `ClineToolSet` for improved tool resolution.
- Updated `getToolsPrompts` in `PromptBuilder` to utilize these new methods, allowing for better handling of tool requests with fallback to generic tools.
- Enhanced sorting and filtering of tools based on context requirements and requested order.

* update fild structure

* clean up

* fix static test string

* Update snapshot names

* Update unit test

* Remove unused placeholders and update docs

* Update README on how to add new tool

* Remove task_progress reference from attempt_completion tool description when focus chain is disabled

* consolidate field declarations for globalstate, workspacestate, and secret keys

* remove old cacheservice file

* read_file tool call change for all models (#5830)

* feat: refactor UseCustomPrompt into reusable component, add to Ollama (#5818)

* feat: refactor UseCustomPrompt into reusable component, add to Ollama

Refactor custom prompt checkbox functionality from LMStudioProvider and OllamaProvider into a shared UseCustomPrompt component to reduce code duplication and improve maintainability.

* Add changeset

* replace key with providerId

* clean up

* Rename UseCustomPrompt to UseCustomPromptCheckbox and update imports

Rename UseCustomPrompt.tsx to UseCustomPromptCheckbox.tsx for better clarity
and update import paths in LMStudioProvider and OllamaProvider components.

* use StateManager in auxilary access of cline state instead of using vscode api directly

* fix default formatter that was erroneously changed

* feat: sap provider - support orchestration mode (#5541)

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap ai core - add orchestration

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration modee

* feat: sap provider - support orchestration modee

* feat: sap provider - support orchestration modee

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: support doorway mapping semantic model [CCSTAHEL-2197]

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* Update docs/provider-config/sap-aicore.mdx

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

* feat: sap provider - support orchestration model

* feat: support doorway mapping semantic model [CCSTAHEL-2197]

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* fix converse api image data to base64 string.

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

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Lize Cai <lize.cai@sap.com>

* add in new sap field from main merge in the right place

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
Co-authored-by: pashpashpash <nik@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: Bee <68532117+abeatrix@users.noreply.github.com>
Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
Co-authored-by: Yunus Emre AYHAN <ayhanyunusemre@gmail.com>
Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: yuvalman <yuval.manor@sap.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Lize Cai <lize.cai@sap.com>
2025-08-26 18:58:18 -07:00
yuvalman 190d4a2c52 feat: sap provider - support orchestration mode (#5541)
* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap ai core - add orchestration

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration modee

* feat: sap provider - support orchestration modee

* feat: sap provider - support orchestration modee

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: support doorway mapping semantic model [CCSTAHEL-2197]

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* Update docs/provider-config/sap-aicore.mdx

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

* feat: sap provider - support orchestration model

* feat: support doorway mapping semantic model [CCSTAHEL-2197]

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* feat: sap provider - support orchestration model

* fix converse api image data to base64 string.

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

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Lize Cai <lize.cai@sap.com>
2025-08-26 15:24:18 -07:00
Bee 4d5ab59923 feat: refactor UseCustomPrompt into reusable component, add to Ollama (#5818)
* feat: refactor UseCustomPrompt into reusable component, add to Ollama

Refactor custom prompt checkbox functionality from LMStudioProvider and OllamaProvider into a shared UseCustomPrompt component to reduce code duplication and improve maintainability.

* Add changeset

* replace key with providerId

* clean up

* Rename UseCustomPrompt to UseCustomPromptCheckbox and update imports

Rename UseCustomPrompt.tsx to UseCustomPromptCheckbox.tsx for better clarity
and update import paths in LMStudioProvider and OllamaProvider components.
2025-08-26 15:24:18 -07:00
Toshii f0ad29accb read_file tool call change for all models (#5830) 2025-08-26 15:24:18 -07:00
Bee 0ba45084a0 template-based system prompt (#5731)
* Refactor system prompt architecture with new template-based system

- Move existing system prompt files to legacy directory
- Implement new modular system with PromptBuilder, PromptRegistry, and TemplateEngine
- Add component-based prompt structure with reusable parts (capabilities, rules, tool_use, etc.)
- Create variant-specific templates for generic and next-gen models
- Add comprehensive test suite with snapshots for different model configurations
- Introduce template engine with placeholder support for dynamic prompt generation

* Refactor system prompt architecture with modular tool definitions

- Extract tool specifications into dedicated modules under tools/
- Add ClineToolSet class for managing tool variants by model family
- Restructure prompt components with centralized index exports
- Update prompt builder and registry to support new tool architecture
- Reorganize shared utilities and type definitions
- Update all test snapshots to reflect new prompt structure

* Update snapshots

* reorg

* Update template format

* clean up

* typos

* focus chain section

* fix task progress in attempt_completion

* Implement tool retrieval with fallback options in PromptBuilder

- Added `getToolByNameWithFallback` and `getToolsForVariantWithFallback` methods to `ClineToolSet` for improved tool resolution.
- Updated `getToolsPrompts` in `PromptBuilder` to utilize these new methods, allowing for better handling of tool requests with fallback to generic tools.
- Enhanced sorting and filtering of tools based on context requirements and requested order.

* update fild structure

* clean up

* fix static test string

* Update snapshot names

* Update unit test

* Remove unused placeholders and update docs

* Update README on how to add new tool

* Remove task_progress reference from attempt_completion tool description when focus chain is disabled
2025-08-26 15:24:18 -07:00
Bee 213591a169 fix: AutoApproveModal positioning and scrolling behavior (#5819)
* fix: AutoApproveModal positioning and scrolling behavior

- Add dynamic positioning calculation to prevent modal overflow
- Implement proper flex layout with scrollable content container
- Ensure minimum usable height and top margin constraints
- Fix modal positioning when button is near viewport edges

* Add changeset

* clean up
2025-08-26 15:24:18 -07:00
celestial-vault 70fd35df6d infer state key types from existing interfaces (#5815) 2025-08-26 15:24:17 -07:00
celestial-vault bd526cb2d2 rename CacheService to StateManager (#5681)
* rename CacheService to StateManager

* fix types
2025-08-26 15:24:17 -07:00
canvrno 2fbebec7ae Changes to condenseToolResponse & summarizeTask prompting (#5817)
* Condense & deep planning prompt adjustments

* Removed ps prompting ready for PR

* rebase

* Fixed typo on one word

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-26 15:24:17 -07:00
canvrno ca1e008714 deep-planning prompt PowerShell (#5699)
* Windows/Powershell specific deep planning prompt changes

* Prompt adjustments

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-26 15:24:17 -07:00
Bee 1ab3de8911 fix: remove hardcoded Ollama host from options (#5816)
* fix: remove hardcoded Ollama host from options

Updates the Ollama handler to remove the hardcoded "http://localhost:11434" as the `ollamaBaseUrl` fallback option for the host to allow the Ollama SDK to handle the default endpoint configured on users' machine.

Reason: Ollama allows cross-origin requests from 127.0.0.1 and 0.0.0.0 by default. However, when we use localhost, the browser would resolve it through DNS, which can result in different IP addresses.

Docs: https://github.com/ollama/ollama/blob/main/docs/faq.md#how-can-i-expose-ollama-on-my-network

* add changeset
2025-08-26 15:24:17 -07:00
Bee 47f75225e8 Increase horizontal margin in AutoApproveBar component (#5813)
Update the mx-[5px] to mx-[15px] in the div's className to adjust horizontal spacing for improved layout alignment.
2025-08-26 15:24:17 -07:00
Bee 15f6577cb9 Remove eslint-rules test patterns from Mocha spec configuration (#5812)
Update the "spec" array in .mocharc.json to exclude "eslint-rules/__tests__/**/*.test.ts",
as that directory has been removed.
2025-08-26 15:24:17 -07:00
canvrno 7c5d56a5c1 Focus chain telemetry tweaks (#5810)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-26 15:24:17 -07:00
pashpashpash cdc24890ee add custom gpt-5 system prompt (#5757)
* gpt-5 system prompt

* add changeset
2025-08-26 15:24:17 -07:00
celestial-vault ef5465b667 add focus chain settings to statemanager initialize function (#5798) 2025-08-26 15:24:17 -07:00
Yunus Emre AYHAN d4ba4fd98a Dify.ai integration (#5761) 2025-08-26 15:24:17 -07:00
Toshii 074e5d7002 removing middle out from params to or / cline providers (#5811) 2025-08-26 15:24:17 -07:00
Bee 18e164fe81 Remove top padding from ActionButtons component (#5806)
Eliminate unnecessary top padding in the chat view.
2025-08-26 15:24:17 -07:00
github-actions[bot] 82be7c4ed5 v3.26.6 Release Notes (#5788)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.26.6 with user-friendly 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-08-26 15:24:17 -07:00
Saoud Rizwan 702dd75291 add grok coder free model to cline provider (#5808)
* add free grok-coder-free model to cline provider

* add changeset

* fix typo
2025-08-26 15:24:08 -07:00
celestial-vault ce89547f32 Use VS Code CSS variables for markdown/codeblock styling (#5783)
* use css variables for highlight styling and remove theme subscription along with vscode theme to highlight pipeline logic

* changeset

* Remove monaco-vscode-textmate-theme-converter

* Remove unnecessary markdown css

* Remove package-lock.json from version control

* re-add package-lock

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-25 10:15:29 -07:00
Saoud Rizwan 275be69932 fix: 'disable checkpoints' button font size does not match surrounding text (#5787)
* fix: 'disable checkpoints' button font size does not match surrounding text

* Remove non-existant font-inherit
2025-08-25 09:36:00 -07:00
Tomás Barreiro 8eba96582a fix: provider options (#5204)
* Pass all options to the handlers

* Add changeset

* Do not pass all options

* Have onRetryAttempt as a common option

* Do not duplicate the onRetryAttempt definition
2025-08-25 18:00:26 +02:00
evinelias e73364d497 Feature/Qwen Code CLI API Support with OAuth (#5766)
* feat: Integrate Qwen Code API with OAuth authentication

- Add Qwen Code API provider with OAuth2 authentication flow
- Implement QwenCodeProvider component for settings UI
- Add qwenCodeOauthPath to CacheService state management
- Update protobuf models with QWEN_CODE provider type
- Fix protobuf enum values (VSCODE_LM changed from 15 to 33)
- Add comprehensive API configuration conversion support
- Update build scripts to use system protoc for Windows compatibility
- Optimize VSIX packaging by excluding reference codebase
- Follow camelCase convention: qwen_code_oauth_path  qwenCodeOauthPath

* docs: Add Qwen Code API integration documentation

- Document OAuth2 authentication flow and features
- Highlight enterprise-grade security capabilities
- Include setup instructions for credential management
- Emphasize automatic token refresh and caching features

* cleanup: Clean up build configuration for production release

- Revert protoc path to use grpc-tools instead of exposing system path
- Restore vscode:prepublish script for proper VS Code marketplace publication
- Remove reference codebase exclusion from .vscodeignore for cleaner packaging

* refactor: Remove Windows platform check from build-proto script

- Remove unnecessary isWindows variable and platform-specific logic
- Simplify TS_PROTO_PLUGIN to use standard require.resolve approach
- Improve cross-platform compatibility and code clarity

* restore: Restore Windows platform check in build-proto script

- Add back isWindows platform detection variable
- Restore Windows-specific TS_PROTO_PLUGIN logic using .cmd file
- Maintain cross-platform compatibility for Windows builds

* Update ApiOptions.tsx

* Remove Qwen Code API integration section

* Revert README

* Fix protos order

* Revert change

* Remove validation for qwen code

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-24 20:25:20 -07:00
pashpashpash 56b8c4a847 add gpt-5 to recommended list (#5789) 2025-08-23 22:58:52 -07:00
Toshii cd066c4912 remove middle out for gpt5 (#5786)
* remove middle out for gpt5

* refactor: using standard family identifier functions

* fix: making sure to lowercase all model ids

* changeset

---------

Co-authored-by: pashpashpash <nik@nugbase.com>
2025-08-23 20:47:56 -07:00
github-actions[bot] 59a0d055de v3.26.5 Release Notes (#5785)
* changeset version bump

* Updating CHANGELOG.md format

* Revise changelog for version 3.26.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: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-23 17:06:49 -07:00
Saoud Rizwan b0ea2e48a7 Fix OVSX publish command (#5784)
* Fix OVSX publish command

* Fix OVSX publish command
2025-08-23 17:03:44 -07:00
github-actions[bot] 9e86ba580b v3.26.4 Release Notes (#5769)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

* Update version from 3.27.0 to 3.26.4

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-23 16:43:53 -07:00
Walter Korman 99eccaafd4 fix (provider/vercel-ai-gateway): load model list once on settings view display (#5776) 2025-08-23 15:54:13 -07:00
Saoud Rizwan cc0f695555 Allow packaging secrets in VSCE publish command (#5782)
* Allow packaging secrets in VSCE publish command

* Create shaggy-beans-yell.md

* Revert "fix publish yml action (#5770)"

This reverts commit 357f98c707.
2025-08-23 15:53:27 -07:00
Saoud Rizwan 96a461668c Revert "Scenario Test Workflow (#5711)" (#5781)
This reverts commit b45168f6a3.
2025-08-23 15:49:37 -07:00
pashpashpash 357f98c707 fix publish yml action (#5770) 2025-08-23 00:53:25 -07:00
Ara 6d4bea48d3 ReOrder Model List (#5767) 2025-08-22 23:38:30 -07:00
Dennise Bartlett 06cd873a46 Allow packaging secrets in VSCE command 2025-08-22 23:18:16 -07:00
pashpashpash 34e52757ff Revert "Build package per commit (#4570)" (#5768)
This reverts commit fe8ab85e1a.
2025-08-22 22:52:14 -07:00
Mark Percival 43d1bd858c chore: remove disabled 'codespell' workflow (#5662) 2025-08-22 20:55:58 -07:00
Mark Percival 90f07e824e chore: Remove 'old_docs' documentation (#5661) 2025-08-22 20:48:49 -07:00
yuvalman 8cc823ce05 feat: sap provider - support reasoning effort for open ai models (#5691)
* feat: sap provider - support reasoning effort for open ai models

* feat: sap provider - support reasoning effort for open ai models

* feat: sap provider - support reasoning effort for open ai models

* feat: sap provider - support reasoning effort for open ai models

* feat: sap provider - support reasoning effort for open ai models
2025-08-22 20:43:38 -07:00
dylan eeef3f89bd feat: add new models from Nebius AI Studio with correct pricing (#5729) 2025-08-22 20:26:52 -07:00
Lize Cai b1ab8967ec fix: Claude 4 image processing in SAP AI Core provider (#5735)
* fix converse api image data to base64 string.

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

* add test cases

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

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
2025-08-22 20:18:32 -07:00
Ann-Holmes 5a81f8f6d3 feat(deepseek): Update DeepSeek models context window from 64K to 128K (#5751)
- Updated contextWindow for deepseek-chat and deepseek-reasoner models from 64_000 to 128_000
- Modified context-window-utils.ts to handle DeepSeek models with 128K context window instead of 64K
- This change aligns with DeepSeek's official API documentation and improves model performance
2025-08-22 20:16:01 -07:00
github-actions[bot] 55b1b4c125 v3.26.3 Release Notes (#5759)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.26.3 release

- Add user-friendly descriptions for compact system prompt feature
- Add proper version formatting with brackets
- Improve clarity of LM Studio and token usage tracking features

* package lock

* changelog

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-22 17:22:16 -07:00
Tomás Barreiro fe8ab85e1a Build package per commit (#4570)
* Build the extension on every commit push

* Publish using the vsix path

* Fix tag resolution

* Remove `while ;`

* Remove test trigger

* use while true;

* Update package.json

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

* Use high capacity runner

* add if check to only run in the Cline repo

* Conditionally select a runner

---------

Co-authored-by: Dennise Bartlett <bartlett.dc.1@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-22 17:07:52 -07:00
Bee a50200aba1 feat: Support compact system prompt for LM studio models and token usage tracking (#5720)
* Add compact system prompt for local models

- Introduce compact system prompt for local models (lm studio, ollama)
- Add ApiProviderInfo { modelId, providerId } to API
- Persist promptType in global state and propagate to webview
  (updateSettings, state keys/helpers, ExtensionMessage, UI context)
- Wire provider info through task pipeline to buildSystemPrompt

* isLocalModelFamily

* Add custom prompt support and LM Studio API improvements

* Enable token usage tracking in LM Studio stream responses

This change adds the stream_options parameter with include_usage: true to LM Studio API requests, allowing the system to receive token usage information along with streaming responses. This enables better tracking of token consumption for LM Studio model interactions.

* update compact system prompt

* feat: Support compact system prompt for LM studio models and token usage tracking

* clean up

* Update UI helper text
2025-08-22 11:32:19 -07:00
github-actions[bot] 7640ae11ec v3.26.2 Release Notes (#5736)
* changeset version bump

* Updating CHANGELOG.md format

* changelog

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-21 16:26:04 -07:00
pashpashpash 08d94c450f removing max tokens from sonic model (#5742) 2025-08-21 16:01:24 -07:00
Nick Baumann d7a93cd618 docs: Vercel AI Gateway provider page (#5743) 2025-08-21 16:01:13 -07:00
Joyce Er 49475ad417 fix: small typo in focus chain settings page (#5744) 2025-08-21 15:58:22 -07:00
Saoud Rizwan e6c18ea793 Fix openrouter/cline gpt-5 contextWindow by setting to 272k since it's inaccurately reported as 400k (#5738) 2025-08-21 14:48:31 -07:00
Toshii 881593beea extract error code from the error message (#5741) 2025-08-21 12:28:24 -07:00
Bee 96198c82f9 fix: improve OpenRouter model info parsing (#5737)
* fix: improve OpenRouter model info parsing

Refactor OpenRouter model fetching to include `OpenRouterRawModelInfo` and `OpenRouterSupportedParams` types for better clarity and type safety. This allows for more accurate parsing of model capabilities, including support for "thinking" (reasoning) configurations.

The thinking config is now only set if the model explicitly supports the `include_reasoning` parameter. Additionally, the budget slider in the UI is now displayed for OpenRouter models that support thinking, not just specific Claude models. This provides a more dynamic and accurate representation of model features.

* add changelog

* Set thinking budget for stream
2025-08-21 11:55:55 -07:00
Brian b45168f6a3 Scenario Test Workflow (#5711)
* add scenario workflow and associated files

* add github PR validation

* add permissions restrictions

* add matrix_prep permissions

---------

Co-authored-by: Brian Pierce <brian@cline.bot>
2025-08-21 10:14:58 -07:00
Toshii 24f10eeee5 added telemetry for condense toggle in menu (#5718) 2025-08-20 21:35:07 -07:00
yuvalman d594368f05 fix: add support to *.go files in deep-planning prompt (#5640)
* fix: add support to *.go files in deep-planning feature

* fix: add support to *.go files in deep-planning feature

* adding go to the todos section

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-08-20 17:27:15 -07:00
pashpashpash 7177dd00ea add /cli to gitignore while in prerelease (#5717) 2025-08-20 17:17:53 -07:00
github-actions[bot] 8f0352ee01 v3.26.1 Release Notes (#5702)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for version 3.26.1 patch release

* announcement

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-20 16:44:55 -07:00
Nick Baumann 2ebd92ee94 docs: Add 5 new provider guides and update model selection guide (#5716)
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-20 16:24:15 -07:00
Daniel Steigman 8806beda20 Change default strict plan mode setting to enabled (#5714)
* Change default strict plan mode setting to enabled

- Updated default from false to true in state-helpers.ts (primary backend default)
- Updated fallback default in controller/index.ts (Task initialization)
- Updated frontend default in ExtensionStateContext.tsx for consistency
- Fixed linting issue with forEach callback return value
- New users will now have strict plan mode enabled by default
- Prevents file edits in Plan Mode, enforcing cleaner separation of planning vs execution

* added changeset

---------

Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-20 16:23:36 -07:00
Toshii 58ce23663d next gen context management method switch (#5715)
* truncate first user message

* base swapping

* linting

* menu

* apply biome fixes and add back in removed comments

* undo biome invalid changes

* updating feature section comment

* button to enable auto compact just for next gen models
2025-08-20 16:02:20 -07:00
Josh 6dc44b9c7e Add vercel ai gateway provider (#5355)
* Add vercel ai gateway provider

* Formatting

* grab correct context window field

* changelog

* Post-rebase fixes

* fix formatting

* Update model picker, add reasoning tokens to output

* Fix Vercel AI Gateway model info persistence

* use cache service rather than getallextensionstate

* Reorder vercel gateway option

* Show image support info

* Fix providerUtils.ts

* Fix broken model id and merge conflict issue

* fix pricing display for free users

* revert ts ignore

* revert to cost field, add note for free users 0 cost

* udpate gateway docs

* Delete docs/package-lock.json

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-20 15:13:05 -07:00
ershang-fireworks 7e7280d7c5 Fix fireworks provider (#5435)
* fix

* fix default model id

* fix tests

* Add changeset for fireworks provider fix

* add docs for fireworks provider

* add empty line to doc

* format

* fix model selector

* remove unnecessary

* fix test
2025-08-20 14:43:32 -07:00
Toshii 4b8927c055 adding task_progress param to the summarize task tool call (#5693)
* adding task_progress param to the summarize task tool call

* remove log statement

* prompt change
2025-08-20 13:02:43 -07:00
yuvalman aea979ff4e feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline (#5315)
* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline

* feat: sap provider - show deployed models from the ai core service instance alongside sap provider's supported models in cline
2025-08-20 22:01:15 +03:00
celestial-vault 714bcf92cf move clineignore filewatcher to chokidar (#5676) 2025-08-20 10:59:25 -07:00
Sarah Fortune a630b8c1a1 Fix issue where cline-core locks up when diff editor is closed. (#5615) 2025-08-20 10:54:16 -07:00
Bee a9836fb9fc Preserve clineMessages when currentTaskItem unchanged (#5700)
Keep previous clineMessages if the incoming state targets the same currentTaskItem and has no messages, preventing message loss on state sync/refresh while still accepting new messages when present.
2025-08-20 10:37:41 -07:00
benank 19f055e333 Add support for prompt caching on Groq (#5697) 2025-08-20 10:04:54 -07:00
kvyb 1997ee3e80 refactor to hostbridge: route @mentions search via WorkspaceService.searchWorkspaceItems (#5655) 2025-08-20 07:30:30 -07:00
Daniel Steigman 89ec9c4277 feat(telemetry): Add MCP tool usage tracking (#5698)
* feat(telemetry): Add MCP tool usage tracking

This commit introduces telemetry for MCP tool calls to monitor usage, success rates, and errors.

- Adds a new telemetry event 'task.mcp_tool_called'.
- Captures the server name, tool name, and status (started, success, error).
- Integrates telemetry calls into the McpHub to track tool execution lifecycle.

* chore: Add changeset for MCP telemetry

* refactor(telemetry): Clean up MCP tool usage tracking

This commit refactors the MCP tool usage tracking to be cleaner and more efficient.

- Removes null checks for 'ulid' in the 'callTool' method.
- Passes argument keys to the telemetry service for better monitoring without compromising user privacy.
2025-08-20 00:05:59 -07:00
Daniel Steigman e125540595 feat(telemetry): Add rules and workflow usage tracking (#5701)
* feat(telemetry): Add rules and workflow usage tracking

This commit implements telemetry tracking for Cline rules and workflow interactions to understand user engagement patterns:

- Add captureSlashCommandUsed() method to track slash command and workflow activations
- Add captureClineRuleToggled() method to track rule toggle events
- Update parseSlashCommands() to require ULID parameter and track command usage
- Add telemetry calls to toggleClineRule() with proper path sanitization
- Distinguish between builtin commands and workflow types
- Include task ULID context for tracking rule changes within tasks
- Sanitize file paths to include only filenames for privacy protection

* chore: Add changeset for rules and workflow telemetry

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

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

* Apply suggestion from @Copilot

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

* fixed import lol

* added more consistent event name to match the events type

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-19 23:49:20 -07:00
kvyb 9f3628ae19 refactor hostbridge: add openSettings RPC and vscode hostbridge; (#5651)
* refactor hostbridge: add openSettings RPC and vscode hostbridge; use in telemetry

* clarify query in OpenSettingsRequest
2025-08-20 08:42:16 +03:00
Sarah Fortune de133c27a0 Fix ProtoBus int32 too large error (#5696)
The context window is now being set to `Number.MAX_SAFE_INTEGER` to represent infinity. https://github.com/cline/cline/blob/01c4ead15548c906cc690ef030ee447720ccb5b0/src/shared/api.ts#L219-L220
However, this is larger than the max value of int32 and cannot be serialized over the ProtoBus. Update the max token and context window sizes to be int64.

```2025-08-14 18:28:36,492 [   4334]   WARN - bot.cline.services.ProtoBusProxyService - Stream cline.ModelsService.subscribeToOpenRouterModels encountered error
io.grpc.StatusException: INTERNAL: invalid int32: 9007199254740991
        at io.grpc.Status.asException(Status.java:548)
        at io.grpc.kotlin.ClientCalls$rpcImpl$1$1$1.onClose(ClientCalls.kt:300)
        at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:564)
        at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:72)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:729)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:710)
        at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
        at java.base/java.lang.Thread.run(Thread.java:1583)
```
2025-08-19 20:42:29 -07:00
Sarah Fortune 7a43024b61 When packaging cline-core, include map files for debug builds (#5682)
When the env var IS_DEBUG_BUILD is set, include .map files in the package.
2025-08-19 20:23:33 -07:00
Sarah Fortune 982f323162 Add an RPC to the host bridge to reveal a directory in the IDE file explorer (#5692)
When the user clicks on a directory file mention, it should open that directory in the explorer panel in the IDE. Add an RPC for this to the host bridge.

I had to change the logic to check if the mention is a directory or not because the current check was not working properly anymore. So, just file.stat to check if its a directory instead of checking if the path ends in /.
2025-08-19 20:23:09 -07:00
github-actions[bot] 67ef89a4cb v3.26.0 Release Notes (#5665)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and announcement for version 3.26.0

- Add user-friendly descriptions for Z AI provider, Cline Sonic Alpha model, LM Studio improvements, and Ollama fixes
- Include attribution for external contributor @jues
- Update announcement component with new 3.26 features
- Move previous 3.25 features to Previous Updates section

* announcement

* announcement

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-19 20:11:07 -07:00
pashpashpash c24ba53400 Add cline/sonic stealth model (#5669)
* microwave alpha stealth model

* microwave alpha stealth model

* swapped name to sonic

* pricing set to zero

* added case for sonic model to set temperature settings

* bumping max tokens to 16k for sonic

* sonic model does not have image support

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-08-19 19:33:26 -07:00
Sarah Fortune 01c4ead155 Add an RPC to the host bridge to return information about the active editor (#5690)
Add an RPC that returns details about the currently active editor. Right now it just returns the file path.

Update the place where this is used.

Remove commented out code that references `vscode.window.activeTextEditor`.
2025-08-19 14:52:20 -07:00
Sarah Fortune 6f4a4e1ccd Remove unused source files (#5642)
* Remove unused files

I used knip to find unused code- these files are not referenced anywhere in the codebase.

Dead code is a maintence burden, I am removing this unused code.

* Add knip config file

Add knip file with entry points for the extension, cline-core and the ProtoBus and HostBridge services.

Exclude test files, etc.
Exclude the `src/shared` directory because knip can't analyze the webview-ui react app properly.

* Apply suggestion from @ellipsis-dev[bot]

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

* Formatting

* Get the extension version from the ExtensionContext

The extension packageJson is available from the ExtensionContext, don't need to do `vscode.extensions.getExtension`.

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-08-19 14:39:48 -07:00
Sarah Fortune dc03b3bf1f Add an RPC to the host bridge to show the problems in the IDE (#5689)
Add an RPC that makes the problems panel visible and focuses it.
2025-08-19 13:57:09 -07:00
Sarah Fortune cf52db8f49 Get the extension URI from the ExtensionContext instead of vscode.extensions.getExtension("saoudrizwan.claude-dev") (#5688) 2025-08-19 13:52:41 -07:00
Sarah Fortune 26ce4a31b6 Get the extension version from ExtensionContext (#5686)
The extension packageJSON etc is already available in the ExtensionContext, don't need to do `vscode.extensions.getExtension`
2025-08-19 13:23:15 -07:00
Bee 06e0973c04 Apply biome rules: noUnusedVariables, noUnusedFunctionParameters, noUnusedImports (#5545)
* Enable biome rules: noUnusedVariables, noUnusedFunctionParameters, noUnusedImports

* Apply new rules with format

* remove unused currentReplaceContent

* update nextTerminalId

* fix all format issues

* update biome config

* add back applyContextOptimizations and killAllChromeBrowsers
2025-08-19 11:57:50 -07:00
Toshii 54faddb3ff truncate first user message (#5668) 2025-08-19 09:51:16 -07:00
celestial-vault d6935623f9 fix: enable auto-formatting in postprotos script to prevent build failures (#5675)
- Added --write flag to biome format command in postprotos script
- This automatically fixes formatting issues instead of just reporting them
- Prevents build failures due to quote style and other formatting inconsistencies
2025-08-19 13:31:04 +03:00
celestial-vault 803574e7f3 move api folder to core (#5539)
* move api folder to core

* fix incorrect import path mock in test setup

* fix import in zai.ts

* fix additional import errors
2025-08-19 12:54:11 +03:00
Ara f676f2be78 Fix: Prevent lint-staged from reverting staged changes on error (#5673)
* fix and refactor diff and write to file stuff

* fix: precommit

* fix: precommit
2025-08-19 02:12:44 -07:00
celestial-vault c88a852344 refactor: migrate MCP settings watcher to chokidar (#5499)
* refactor: migrate MCP settings watcher to chokidar

* remove console log
2025-08-19 11:27:22 +03:00
Bee 5709f34479 Support LM Studio local models from v0 api endpoint (#5591)
* Support LM Studio local models with max tokens set

Add configurable max tokens parameter for LM Studio provider across proto definitions, API handlers, storage, and UI components. Improved error handling for model fetching to use v0 api.

* changeset added

* clean up

* update

* Use loaded context length for LM Studio model configuration

- Add loaded_context_length field to LMStudioApiModel interface
- Prioritize loaded_context_length over max_context_length in UI
- Update context window display to show actual loaded context
- Refactor model selection logic and endpoint memoization
- Auto-update max tokens when loaded context differs from config

* Add DropdownContainer
2025-08-18 17:22:37 -07:00
Bee a7eb7defc9 fix: request_id extraction in ClineError handling (#5617)
* fix: request_id extraction in ClineError handling

Add back the removed fallback chain to extract request_id from multiple possible locations
in error objects, checking error.request_id and error.response.request_id
before falling back to the existing header extraction method.

* fix: override initial error struct with real request_id instead of overriding request_id with undefined

---------

Co-authored-by: Auroter <seangherardi@gmail.com>
2025-08-18 14:51:58 -07:00
jues a45278bb61 Add support for Z AI GLM-4.5 and GLM-4.5 air (#5316)
* Add support for Z AI GLM-4.5 and GLM-4.5 air

* Add changeset for Z AI provider

* add entrypoints for Z AI provider, add cacheReadsPrice and cacheWritesPrice

* fix old naming convention

* fix value in proto

* fix proto conversion and secret persistence

* Fix GitHub Actions errors: Add zaiApiKey and zaiApiLine to state-helpers.ts and remove unused state.ts

- Added missing zaiApiKey to readStateFromDisk, resetGlobalState functions and apiConfiguration object
- Added missing zaiApiLine to readStateFromDisk and apiConfiguration object
- Removed unused state.ts file that was causing ESLint errors with direct VS Code API calls
- All type definitions for zaiApiKey and zaiApiLine were already present in state-keys.ts
- This resolves the TypeScript errors in GitHub Actions for CacheService.ts

---------

Co-authored-by: wangshan <shan.wang@aminer.cn>
Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-08-18 14:51:06 -07:00
Bee 5d75a311f4 dev: migrate to Biome for linting/formatting (#5423)
* Migrate to Biome for linting/formatting and simplify hooks

- Add biome.jsonc and @biomejs CLI; configure VS Code to use Biome for format/fix and imports
- Replace verbose Husky pre-commit with lint-staged runner
- Remove ESLint setup and custom rule package (no-direct-vscode-api) and its tests
- Update package.json/package-lock and webview-ui package to reflect tooling change
- Add VS Code host typings and grit definitions under src/hosts

Rationale: unify lint/format tooling, speed up pre-commit checks, and reduce maintenance overhead from custom ESLint rules.

* remove eslint dependencies

* preserve eslint rules

* clean up

* update files list

* add docs

* fix build

* clean up

* update VSCode API usage detection in Grit rule

This commit updates the Grit rule for detecting VSCode API usage:
- Narrow down the list of monitored VSCode API methods
- Add more specific diagnostic messages for direct API usage
- Introduce a new check for `workspaceFolders` property
- Exclude `src/extension.ts` from the Grit rule in Biome configuration

The changes aim to improve code abstraction and provide clearer guidance for replacing direct VSCode API calls.

* adds new cacheService rule

* add back pre-commit

* Remove ESLint custom rule and update linting references

Remove custom ESLint rule for VSCode state API enforcement along with its tests, remove ESLint extension recommendation, and update documentation to use generic "linter" terminology instead of ESLint-specific references.

* update vscode.d.ts for IntelliSense

* remove format on save

* clean up default values

* update to 2.1.4

* buf lint

* format
2025-08-18 13:34:09 -07:00
canvrno 0054b21d67 Changed focus chain feature flag behavior (#5656)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-18 12:05:13 -07:00
pashpashpash ea4433d705 no more nectarines (#5650)
* no more nectarines

* no more nectarines
2025-08-17 20:48:10 -07:00
Sarah Fortune 4aaca09389 Move logic for manipulating tabs into the host bridge (#5631)
* Switch the DiffViewProvider to use the util `openFile`

This part of the work to migrate the vscode API calls `vscode.window.tabGroups.close`,
`vscode.window.tabGroups.all` and `vscode.window.activeTextEditor` to the host bridge.

`openFile` contains logic that uses these APIs to avoid re-avoiding tabs in the IDE. The end goal
is to move all this logic into `vscode/hostbridge/showTextDocument.ts`.

I am going to switch all the places that use `showTextDocument` over to use `openFile`.

Once everywhere that was using `showTextDocument` has been switched, and is verified to
work the same as before I will move the tab logic in `vscode/hostbridge/showTextDocument.ts`.

* Update src/integrations/editor/DiffViewProvider.ts

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

* Switch export-markdown to use the util `openFile`.

* Apply suggestion from @ellipsis-dev[bot]

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

* Move tab logic into vscode/showTextDocument

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-08-17 11:52:26 +01:00
Sarah Fortune feb92c45ce Add comments to window.proto (#5628)
Add descriptions for the RPCs in the window service.

Remove unused metadata field from requests messages.
2025-08-17 11:43:10 +01:00
Sarah Fortune e7c4757271 Update the script get-vscode-usages. (#5630) 2025-08-17 09:50:52 +01:00
Sarah Fortune a462a7aded Remove unused code from the commit-message-generator (#5634) 2025-08-17 09:49:55 +01:00
Sarah Fortune 2e729441ed Move use of vscode.version to the host bridge (#5635) 2025-08-17 09:49:26 +01:00
github-actions[bot] c1d7faee1a v3.25.3 Release Notes (#5604)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-16 16:39:16 -07:00
Saoud Rizwan 38d6af3a8d Use standard context truncation change (#5633) 2025-08-16 16:33:07 -07:00
Saoud Rizwan 612b8352ff fix: 'Enable Checkpoints' and 'Disable MCP Marketplace' settings getting reset to default on reload (#5632) 2025-08-16 16:24:50 -07:00
Toshii d4f26fe1de user message overwrite (#5614) 2025-08-16 14:05:11 -07:00
Sarah Fortune e242825dff Remove misleading log message (#5626) 2025-08-16 18:14:11 +01:00
Toshii 8fbccff853 prompt generation (#5612)
Co-authored-by: celestial-vault <58194240+celestial-vault@users.noreply.github.com>
2025-08-15 17:43:04 -07:00
canvrno 2615ea88b6 Adjust position of focus chain edit button (#5609)
* Adjust position of focus chain edit button

* Update webview-ui/src/components/chat/task-header/TaskHeader.tsx

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

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-08-15 15:42:17 -07:00
pashpashpash 61c2943715 minor adjustment to task timeline style (#5607)
* minor adjustment to task timeline style

* minor adjustment to task timeline style
2025-08-15 14:47:57 -07:00
Toshii b176772cd5 auto-condense telemetry (#5584)
* telemetry

* task state preference
2025-08-15 10:41:15 -07:00
canvrno e6b00527ed Improved git branch analysis workflow (#5602)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-08-15 10:33:03 -07:00
canvrno 2635f5f575 Focus Chain regex moved to /shared (#5592)
Co-authored-by: Kevin Bond <kevin@Mac.hsd1.ca.comcast.net>
2025-08-15 10:14:34 -07:00
Sarah Fortune 44f370f295 Add test host bridge server and refactor proto utilities (#5600)
- Extract getPackageDefinition() from loadProtoDescriptorSet() in proto-utils
- Add int64 encoding option to handle numbers properly
- Create test-hostbridge-server.ts with mock gRPC service implementations
- Add -h flag to runclinecore.sh to start test server
- Include testing.md documentation for cline rules
2025-08-15 18:07:45 +01:00
Matthias Oßwald 8c49ce56f6 fix: Prevent non-error logs from being misclassified as errors (#5531)
This re-applies the change from #2900 which got reverted by accident during
a refactoring in #3970.
2025-08-15 10:04:13 -07:00
Sarah Fortune 08543e051e Remove unused params from the AuthService (#5596) 2025-08-15 14:31:32 +01:00
github-actions[bot] f4828d3344 3.25.2 Release Notes (#5589)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-14 23:45:17 -07:00
Saoud Rizwan 385e952935 fix: OpenRouter showing cline credits error after 402 response (#5590)
* fix: OpenRouter showing cline credits error after 402 response

* Create silly-scissors-repair.md
2025-08-14 23:05:16 -07:00
Saoud Rizwan 9a2aaf0881 fix: attempt_completion showing twice in chat due to partial logic not being handled correctly (#5588)
* fix: attempt_completion showing twice in chat due to partial logic not being handled correctly

* Create orange-beds-itch.md
2025-08-14 22:35:19 -07:00
github-actions[bot] 5d65260611 v3.25.1 Release Notes (#5587)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-14 22:16:58 -07:00
Saoud Rizwan 7098c1a32a fix: attempt_completion command showing twice in chat view when updating progress checklist (#5583)
* fix: attempt_completion command showing twice in chat view when updating progress checklist

* Create heavy-walls-own.md
2025-08-14 22:13:04 -07:00
Saoud Rizwan d46e672990 feat(AnthropicProvider): Add Claude Sonnet 4 variant switching functionality (#5585) 2025-08-14 22:11:31 -07:00
Saoud Rizwan 7b2dddd4a5 fix: CacheService not populating with all the expected state (#5586)
* fix: CacheService not populating with all the expected state

* Create modern-impalas-hug.md
2025-08-14 22:10:21 -07:00
watany a6e657e0d1 feat(bedrock): Adding GPT-OSS (#5412)
* feat(bedrock): adding GPT-OSS

* changeset

* update usage return + add reasoning & text for token output estimate

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-08-14 20:18:49 -07:00
github-actions[bot] 612a67ee89 v3.25.0 Release Notes (#5547)
* changeset version bump

* Updating CHANGELOG.md format

* rebased

* changelog

* package-lock.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: pashpashpash <nik@cline.bot>
2025-08-14 19:17:11 -07:00
Saoud Rizwan 383826f7f7 fix: bug where ask question tool would show 'Start new task' button (#5581) 2025-08-14 18:33:35 -07:00
Sarah Fortune b44d3c8793 Add fix, explain, and improve commands to the ProtoBus (#5574)
* Add fix, explain, and improve commands to Cline

- Rename AddToClineRequest to CommandContext for reusability
- Implement fixWithCline, explainWithCline, and improveWithCline commands
- Extract common command utilities to commandUtils.ts
- Move file mention logic to mentions module
- Update command registration and handlers in extension.ts

* Update src/core/controller/commands/addToCline.ts

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

* Update src/extension.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-08-15 02:21:40 +01:00
Saoud Rizwan fbc517c9e5 Add support for 200k context for claude sonnet 4 using openrouter/cline (#5569)
* Add support for 200k context for claude sonnet 4 using openrouter/cline

* Update announcement

* Create beige-singers-jog.md
2025-08-14 18:19:06 -07:00
Saoud Rizwan 3175e19bd7 Fix partial plan_mode_respond cline ask being interrupted by task_progress say (#5578) 2025-08-14 18:18:17 -07:00
Igor Tceglevskii 8e80c18c52 Fix the New Task button in Navbar (#5577) 2025-08-14 18:07:28 -07:00
Toshii b5be6f57d5 requesty (#5579)
* adding option to have custom requesty base url

fix

changeset

* finish state changes

* cleanup

---------

Co-authored-by: John Costa <john@requesty.ai>
2025-08-14 17:44:58 -07:00
canvrno 28737ac62a Enable focus chain by default (#5575)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-14 17:35:34 -07:00
kvyb 61112aaa03 Hostbridge telemetry and startup (#5561)
* feat: Use hostbridge machine ID for posthog distinctId across hosts; VS Code only settings link in warning,, generic warning on other hosts.

* fix: block cline-core until hostbridge health is SERVING; exit on failure; initialize telemetry PostHog with hostbridge machineId;

* fix: posthog prefer host-provided UUID when running via HostBridge; fall back to VS Code's machineId, then a random UUID

* fix: add logging to waitForHostBridgeReady

* fix: log error in initialize
2025-08-15 02:36:19 +03:00
Igor Tceglevskii 922cfed632 Fix the case if the app state and the user state are inconsistent (#5549) 2025-08-14 14:26:29 -07:00
Sarah Fortune 6d7cca7d38 Allow external hosts to trigger the 'Add to Cline' action (#5548)
* Allow hosts to trigger the 'Add to Cline' action

Other platforms need a way to trigger the context menu actions and commands that are available currently in Vscode.

Add a service to the ProtoBus for this called `CommandService`, currently it just has the 'Add to Cline' action.

IDEs that are running cline with cline-core can trigger these actions and commands over gRPC.

Move the code for handling the 'Add to Cline' out of extension.ts into
`src/controller/commands/addToCline.ts`. This same handler will be used for the RPC.

Switch the handler over to use the proto Diagnostics types as it is host-agnostic.

* Fix getDiagnostics.test.ts on windows.

Use `toPosix()` on the fspath.

* Update src/extension.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-08-14 22:16:52 +01:00
Sarah Fortune d81fb542a9 Update logging (#5563)
Update logs for cline-core.
Save the logs from the script `runclinecore.sh` to the ~/.cline directory
2025-08-14 14:39:37 +01:00
pashpashpash a16fc09a68 bedrock docs cleanup (#5551)
* bedrock docs cleanup

* auto compact  docs

* drag and drops docs outdated
2025-08-13 20:22:21 -07:00
Ara 2ec21eda34 Adding a retry button for cases when the streaming response breaks with no text or error (#5505) 2025-08-13 16:53:27 -07:00
canvrno 88000d4f39 Feat: Focus Chain & Deep Planning (#5409)
* Focus Chain feature & Deep Planning workflow

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>

* Casing & variable  naming cleanup

* Alligned default focus chain internval values, corrected typos

* Rebase, moving focus chain settings state to cache

* Fix issue with duplicated ask responses, also renamed function

* renamed slash command

* updated docs and added focus-chain to docs sidebar

* Minor docs changes

* adding deep-planning slash command

* nit: linking

* Updated telemetry service to use ulid

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-13 16:17:45 -07:00
Sarah Fortune 6318eb5948 Add utils for working with Diagnostics (#5543)
These utils will be to build the 'Add to Cline' context menu action for external hosts. The context menu action only deals with diagnostics for a single file, so the current utils need to be adapted.

Export util functions for converting vscode diagnostics to Host Bridge diagnostics.

Export a util for converting diagnostics for a single file from `diagnostics/index.ts`.
2025-08-14 00:16:16 +01:00
Bee 0fd1c0a3aa Configure Playwright to retain videos on failure and simplify teardown (#5542)
* Close page to stop e2e test on teardown

* Configure Playwright to retain videos on failure and simplify teardown

- Enable video recording that only saves on test failures
- Remove complex cleanup logic from global teardown
- Streamline server shutdown to not block teardown process

* change build.js to build.mjs which fixes ES module load error

* speed up

---------

Co-authored-by: Brian Pierce <brian@cline.bot>
2025-08-13 14:31:49 -07:00
Toshii e0478493a2 auto compact - context management (#5520)
* base

* working state reduction & summarization flow wo duplicate calls

* stop injecting into user message

* focus on latest message

* edge case for cancelled stream post summarization tool call

* fix merge
2025-08-13 13:59:00 -07:00
github-actions[bot] 9355d3eea4 v3.24.0 Release Notes (#5472)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-13 13:09:15 -07:00
Saoud Rizwan f485d0cc8f Display context window in model info (#5546) 2025-08-13 13:04:58 -07:00
Saoud Rizwan 79bda976cb Add 1m context window model variant for claude sonnet 4 (#5526)
* Add 1m context window model variant for claude sonnet 4

* Fix cost calculation for 1m tier

* Add new 1m context window announcement

* Create beige-bobcats-watch.md

* Add bedrock support for 1m context
2025-08-13 12:53:23 -07:00
celestial-vault 94acfec39f refactor: migrate FileContextTracker to chokidar (#5501)
Co-authored-by: Igor Tceglevskii <igor@cline.bot>
2025-08-13 12:40:19 -07:00
Richard Meyer 0f67508fa3 Enable browser arguments (#4871)
* feat: add arguments option to browser settings

* feat: add custom browser arguments setting for Chrome launch flags

* remove hardcoded headless argument

* re-run npm run format:fix

* minmal targeted code change vs refactor

* fix: allow browser arguments to persist

* refac: match syntax browser persistence sytanx for customArgs to match chromeExecutablePath

* fix: update browser session to append custom arguments and remove undefined check

* small update to UI description
2025-08-13 12:16:49 -07:00
CellenLee e31bc6147f feat: add kimi-k2-turbo-preview model (#5510) 2025-08-13 11:28:13 -07:00
Peter Dave Hello 8d69e63d72 Add OpenAI GPT-5 Chat(gpt-5-chat-latest) (#5494)
GPT-5 Chat points to the GPT-5 snapshot currently used in ChatGPT. Just
like the dynamic model chatgpt-4o-latest for GPT-4o series.

Reference:
- https://platform.openai.com/docs/models/gpt-5-chat-latest
2025-08-13 11:24:33 -07:00
Igor Tceglevskii 49a678b835 Use HostProvider for creating the OpenRouter auth URL (#5522) 2025-08-13 09:27:06 -07:00
Sarah Fortune 67610b1f87 Refactoring: Move the FileDiagnostics from the host package into common. (#5537)
I am going to reuse the FileDiagnostics in the ProtoBus, so move them into a
common location.

Update the imports.
2025-08-13 09:19:36 -07:00
Sarah Fortune 45f837e1e9 Fix the PATH not being set in the standalone terminal (#5536)
`cline-core` cannot depend on its environment being set up properly
by its parent process. Run the terminal commands in a login shell so
that the PATH etc. will be setup correctly.
2025-08-13 08:34:51 -07:00
Sarah Fortune d0793e51c4 Refactoring: Move vscode specific code out of the WebviewProvider (#5534) 2025-08-13 11:48:53 +01:00
Sarah Fortune 00740de01d In the log timestamp use current timezone instead of UTC (#5535)
The ISO date format logs in UTC with the timezone information, this is unneccessary,
just log the time in the current timezone.
2025-08-13 11:08:15 +01:00
celestial-vault 1ffa4085a6 Remove experimental Sonnet 4 code (#5527)
* remove sonnet 4 experimental tool definitions and prompting

* remove instances of parseV3 in evals
2025-08-12 22:32:30 -07:00
Bee 4db5581cfc disable buttons for plan_mode_respond (#5528) 2025-08-12 22:18:14 -07:00
pashpashpash 675cd1779b using ulid instead of taskid (#5524)
* using ulid instead of taskid

* protos

* Update src/services/browser/BrowserSession.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-08-12 21:19:28 -07:00
pashpashpash af0f0b3d7c make cline better at git (#5525)
* make cline better at git

* typo
2025-08-12 19:09:48 -07:00
Saoud Rizwan 45767b87fd Fix usage endpoint call using oauth token instead of saved refresh token (#5483)
* Fix usage endpoint call using oauth token instead of saved refresh token

* Create odd-ladybugs-punch.md

* Update src/api/providers/cline.ts

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-12 19:08:23 -07:00
Sarah Fortune 8f4c6038dd Change the host bridge RPC closeDiff to close*All*Diffs (#5521)
* Change the host bridge RPC closeDiff to closeAllDiffs

In the vscode diff view provider when the diff is closed, it
closes _all_ open diff views.

I thought in the HostBridge, we would just only be closing the
current diff, but we do need to close all the open diff view
because there can be checkpoint diffs open as well.

* Update proto/host/diff.proto

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

* 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-08-13 01:16:42 +01:00
Peter Dave Hello 9dc021a881 Remove deprecated GPT-4.5 Preview (#5493) 2025-08-12 15:59:46 -07:00
Max Höhl 3e2bdf8b12 Set CLINE_ACTIVE environment variable for new terminals (#5367)
Resolves #5366
2025-08-12 15:44:51 -07:00
Sarah Fortune d4a99a4060 Task Refactor: Move logic for showing multi-file diffs out of Task (#5517)
* Move the logic for showing the multi-file diffs out of the Task class which >2000 lines long.

Split the logic up into functions, add tests.

Use try/finally to ensure that `sendRelinquishControlEvent` is always sent when the function returns.

* Fix warning about use of !!

* Fix tests

Remove asserts on console logs because they are not able to be stubbed properly.
Move test file to correct directory.

* Formatting
2025-08-12 23:27:53 +01:00
Auroter f4bbb45b07 fix: request_id was being incorrectly extracted from the API response… (#5504)
* fix: request_id was being incorrectly extracted from the API response -- it can always be found in the response header under X-Request-ID

* fix: leave error alone, no need to re-create it

* Update src/services/error/ClineError.ts

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

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-08-12 12:12:35 -07:00
Bee 088deebd63 Add VSCode theme colors to Tailwind config (#5516)
* Add VSCode theme colors to Tailwind config

- Add comprehensive VSCode theme color palette to Tailwind config
- Replace hardcoded VSCode CSS variables with Tailwind utility classes for HomeHeader
- Update button and text styling to use new theme-aware classes

* format
2025-08-12 10:42:45 -07:00
celestial-vault dcc744dd87 move browser settings menu to tailwind (#5507) 2025-08-12 10:20:31 -07:00
Bee 9ad8525bd0 Guard ActionButtons when no task (#5508)
Guard ActionButtons when no task; fix scroll deps/empty state

- Return null from ActionButtons if no task to avoid rendering controls without context
- Add missing setExpandedRows dependency and remove unnecessary deps to prevent stale closures and re-renders
- Hide “scroll to bottom” button when there are no messages
- Clean up unused index-tracking logic in scrollToMessage
2025-08-12 09:50:15 -07:00
Sarah Fortune 8bf6268952 Add multi-file diff to the host bridge. (#5515)
Add an RPC to the Host Bridge to open a diff for multiple files, this is
used when comparing check points or to display the changes cline has made
when it is finished editing.

Switch the file mentions unit test to an integration test because
now it is pulling vscode dependencies and they cannot be mocked
in the unit tests.
2025-08-12 09:24:16 -07:00
requesty-JohnCosta27 2081bb8dc6 fix requesty's api key url (#5498) 2025-08-11 21:56:14 -07:00
Bee ac22b63796 refactor: centralize action buttons state (#5462)
* Refactor action buttons: centralize state, remove useButtonState

- Replace useButtonState hook with centralized ButtonConfig logic in ActionButtons, mapping task/ask/tool states to button enablement and labels
- Update ActionButtons API to accept task, messages, mode; compute streaming/enablement internally; remove isStreaming prop
- Always render ActionButtons from ChatView; adjust props accordingly
- Update useIsStreaming call to pass task instead of enableButtons/primaryText
- Clean up useMessageHandlers to reset UI state consistently (input, quotes, files, images, autoscroll)
- Remove deprecated hook and align types

Why: unify and simplify button behavior across task lifecycle, reduce duplicated state/props, and make streaming/approval flows more predictable.

* clean up

* Refactor input clearing and streaming detection logic

This commit:
- Separates input clearing logic into a separate useEffect in ActionButtons
- Removes StreamingIndicator component and its useIsStreaming hook

* Revert newly added button states

Remove switch_to_act_mode button config and associated plan mode conditionals in getButtonConfig function, will do any UI change in follow-up

* simplify further

* Add test suite for button configuration logic

This commit introduces a new test file for the `buttonConfig` module, covering various scenarios such as:
- Default button configurations
- Streaming and partial message handling
- Error recovery states
- Tool approval states
- Command execution states
- Specific ask state configurations
- API request state testing

The tests ensure robust button configuration selection based on different message types and states.

* update button styles
2025-08-11 19:14:53 -07:00
Ara 44eb2cc65e Fixing context exceeded error (#5479)
* Detect OpenAI context window errors and auto-retry

- Add checkIsOpenAIContextWindowError to identify OpenAI context length issues (context_length_exceeded, 400 + context-length patterns)
- Integrate into Task: detect OpenAiHandler/OpenAiNativeHandler and handle first-chunk failures as context window overflows
- On detection, aggressively truncate history ("quarter"), persist changes, show truncation notice, wait 1s, then retry once
- Align behavior with Anthropic/OpenRouter handling to reduce failures from oversized prompts

* Fixing OpenAI context exceeded errors

* Fixing OpenAI context exceeded errors

* Fixing OpenAI context exceeded errors

* use OpenAI sdk error types

* Making errors for this generic and adding cerebras

* Making errors for this generic and adding cerebras

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-08-11 17:56:48 -07:00
Saoud Rizwan 2cf1d8628b Set gpt5 max tokens to 8_192 to fix context window exceeded error (#5478)
* Set gpt5 max tokens to 8_192 to fix context window exceeded error

* Create healthy-crabs-sip.md
2025-08-11 15:50:32 -07:00
celestial-vault 669e018b85 Move rest of state to cache (#5404)
* move rest of state to cacheService

* finish moving state to cache

* remove console logs

* fix types

* don't type cast

* add eslint rule banning use of direct storage apis

* fix types

* move vscode state eslint rule to separate rule since it's error and the others aren't

* fix eslint rules parsing
2025-08-11 14:46:39 -07:00
Sarah Fortune 2aa5156905 Update ExternalDiffViewProvider to return diagnostics before/after diff (#5500)
The diff view is supposed to return any new errors or warnings after the
file is edited. The ExternalDiffViewProvider was just returning *all*
the errors.

When the DiffViewProvider is being reset, reset *all* the properties.

Add unit tests for diagnostics functionality

Refactoring:
- Move diagnostics into the parent DiffViewProvider, remove duplicate implementations in VscodeDiffViewProvider and ExternalDiffViewProvider
- Move duplicated code for converting FileDiagnostics to string to `diagnosticsToProblemsString`.
- Use a single implementation of `getDiagnostics` and `diagnosticsToProblemsString` using the HostBridge protos.
2025-08-11 19:54:41 +01:00
celestial-vault 51b619e0d5 remove workspace tracker (#5346)
* remove workspace tracker

* remove console log

* fix search when clicking folder option

* create enum for searchType

* use hostbridge for active files

* use util function for relative path

* Fix into interests error where false security warning is being triggered
2025-08-11 09:51:47 -07:00
Sarah Fortune 85fb76a996 Call teardown() when cline-core is stopped. (#5496) 2025-08-11 17:29:27 +01:00
Dennise Bartlett d73a7cfd06 Fix package-lock version and update CODEOWNERS (#5490) 2025-08-11 01:43:08 -07:00
Ara 489dfbc932 Fixing Read of Workspace root by index.ts (#5482)
* Fixing Read of Workspace root by index.ts

* Fixing Read of Workspace root by index.ts
2025-08-09 20:50:50 -07:00
Bee 314c416788 remove PostHog exception autocapture (#5481)
Remove enableExceptionAutocapture option from PostHog client configuration.
2025-08-09 16:49:07 -07:00
Igor Tceglevskii 3b19c2ec95 Click from a file name in chat to editor (#5422) 2025-08-09 15:48:12 -07:00
Sarah Fortune e04cbea504 Add an endpoint to the HostBridge for integration testing (#5476)
Add an RPC to the HostBridge that returns the contents of the
webview, for use in integration tests.
2025-08-09 23:14:29 +01:00
Toshii affac119f5 stop double counting tokens (#5426)
* updated

* cleanup
2025-08-09 13:05:36 -07:00
Sarah Fortune 3847a2545c Test is still flaking, increase the timeout (#5473) 2025-08-09 16:25:02 +01:00
Sarah Fortune 15593bac2a Use the active webview in ProtoBus getWebviewHtml. (#5444) 2025-08-09 16:24:46 +01:00
Sarah Fortune 84267efb9e Don't use activate() in cline-core (#5448)
* Don't use activate() in cline-core

Have separate code paths to set up the extension and cline-core.

This means the cline-core is not running all the vscode setup and is
only using one `Controller` (the one from the WebviewProvider).

Move the shared logic into common.ts.

* Comments and logging
2025-08-09 14:49:23 +01:00
github-actions[bot] 985ce56809 v3.23.0 Release Notes (#5466)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-09 02:16:07 -07:00
xiongxiong cad28c4c0c fix: calibrate input token when using anthropic models of sap ai core provider (#5469) 2025-08-09 02:13:01 -07:00
Saoud Rizwan 4a22f7dbd2 Fix plan/act hover color and act mode color (#5470)
* Fix plan/act hover color and act mode color

* Revert plan color change
2025-08-09 02:10:49 -07:00
Saoud Rizwan a430226caa Revert unnecessary terminal command issue workarounds (#5463)
* Revert terminal process logic to pre-capture where we didn't use grace periods or fast command workarounds

* Create empty-pears-fail.md
2025-08-09 02:09:40 -07:00
Bee 5885a3cc1d improve mode switch background color (#5467)
* fix: mode switch styling

Replace the use of `--vscode-toolbar-hoverBackground` which is a `-hoverBackground` that tends to be transperant or opacity change on some themes. Replace it with `-background` which uses solid color instead. See https://code.visualstudio.com/api/references/theme-color

- Update Plan/Act mode switch colors var for better visibility across themes
- Remove hover effects from switch options
- Add background classes to active switch options

* changeset added
2025-08-09 00:30:07 -07:00
Oliver Schirmer 759ef873ae Feat: Prompt Caching in SAP AI Core (#5399)
* add: caching support for bedrock (claude)

* refactor: gemini message handling to adhere closer to original implementation (and make implicit caching clear)

* remove: unused bedrock conversion functions

* fix: payload for converse stream (older claude models)
remove: caching support flag for older claude models

* add: changeset

* Update package-lock.json
2025-08-09 00:12:26 -07:00
Saoud Rizwan 782e4ff6e0 Fix credit error tests (#5465)
* Fix credit error tests

* Create odd-tables-pump.md
2025-08-08 21:17:33 -07:00
github-actions[bot] 4bb00241bf v3.22.0 Release Notes (#5424)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-08 20:47:54 -07:00
Saoud Rizwan c325faf8db Fix bug where running out of credits on cline accounts would show '402 empty body' response instead of 'buy credits' component (#5464)
* fix: show credits purchase component when user runs out of credits and we receive 402 status from server

* revert unnecessary change

* Create many-adults-end.md
2025-08-08 20:43:43 -07:00
Igor Tceglevskii 20f8f9c9cf Request for requesting a current PR number for pr_review workflow (#5406) 2025-08-08 13:14:50 -07:00
Yechao LI 5be163f49d Fix safari does not support isComposing of input event (#4118)
* fix: safari does not support isComposing of input event

* formatting

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-08-08 12:28:46 -07:00
Kevin Taylor 7843ab937a Add cerebras rate limit handling (#5408)
* Update cerebras.ts

* Create friendly-geckos-accept.md
2025-08-08 12:28:34 -07:00
tjandy98 5ed4319d21 Add support for GPT-5 models to SAP AI Core Provider (#5428)
* add gpt-5 models

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

* add changeset

* remove max_tokens & temperature

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

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
2025-08-08 10:16:45 -07:00
Igor Tceglevskii a8971b807a Possibility to install binaries to a separate folder (#5446) 2025-08-08 15:24:05 +01:00
Sarah Fortune 51c4e0aceb Don't instantiate the AuthService at the top level of the module. (#5443)
I am working separating the initialization for the extension and cline-core
and this is causing a circular dependency.
2025-08-08 06:51:43 -07:00
Sarah Fortune 1cf62941cd Fix webview on IntelliJ (#5439)
The ExternalWebviewProvider has to return /something/ for `getWebview()` or
the rest of the code thinks that is not set up and it won't generate the HTML
for IntelliJ.

The Vscode webview panel, `resolveWebview()` and other Vscode specific parts are
planned to be moved out of the WebviewProvider and into VscodeWebviewProvider,
but that depends other changes to how the webview is initialized in extension.ts
to need to happen first.

Move the WebviewProvider out of index.ts and into a file name `WebviewProvider`,
this follows best practises.
2025-08-08 13:50:28 +01:00
Sarah Fortune cc2472f500 Sssh McpHub (#5434) 2025-08-08 11:58:14 +01:00
Ara 677e544c51 Fix Gpt 5 context window (#5414)
* Fix Gpt 5 context window

* Fix Gpt 5 context window
2025-08-08 01:04:12 -07:00
akfoster d3c8fbbf1d chore: remove unused parseAssistantmessageV1 (#5425)
* chore: remove unused parseAssistantmessageV1

* chore: add PR number to comments

* fix: include full path to PR
2025-08-07 22:21:17 -07:00
Sam 1b06633253 fix: LiteLLM provider cost calculations (#4990)
* fix: LiteLLM provider cost calculations

* fix: LiteLLM provider cost calculations

* Update src/api/providers/litellm.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-08-07 22:06:04 -07:00
Bee 4ab8559fce feat: support sending context to active editor panels (#5239)
* feat: add client-specific targeting for addToInput events

- Add client-specific targeting for addToInput events
- Update subscribeToAddToInput to accept client ID parameter
- Replace global event broadcasting with targeted client messaging
- Remove automatic sidebar focus when adding code to chat
- Use last active webview instance for context menu actions
- Maintain backward compatibility with subscription management

* add changeset

* remove debug profiler

* e2e test

* add type

* Add e2e test

* update teardown
2025-08-07 19:32:40 -07:00
github-actions[bot] 259368e0a3 v3.21.0 Release Notes (#5392)
* changeset version bump

* Updating CHANGELOG.md format

* release notes

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-07 10:03:39 -07:00
pashpashpash 9b7839efcd Pashpashpash/gpt 5 release (#5413)
* preparing for gpt5 release

* Update generic system prompt with needs_more_exploration param for plan mode

* changeset

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-07 09:47:04 -07:00
Ara 47a2ae83de Switch to ULID from UUID for tasks telemetry (#5407)
* Switch to ULID from UUID for tasks

* Switch to ULID from UUID for tasks

* Switch to ULID from UUID for tasks
2025-08-06 19:51:19 -07:00
Sarah Fortune 1b5590e26c Refactoring: move postMessageToWebview into vscode specific code (#5396) 2025-08-07 02:49:12 +01:00
Toshii 9e493341d2 Add ollama key for cloud endpoint (#5400)
* base

Co-authored-by: EndoTheDev <endothedev@gmail.com>

* toggle showing key box

* typing

---------

Co-authored-by: EndoTheDev <endothedev@gmail.com>
2025-08-06 14:41:48 -07:00
kvyb 1d4cd3187b Hostbridge diff diagnostics (#5368)
* feat: migrate diff edit diagnostics to hostbridge; Migrate diagnostics functionality from direct VS Code API calls to the hostbridge layer to enable multi-host support (VS Code + IntelliJ).

* remove test logging

* refactor: migrate diagnostics to workspace service and host separation
2025-08-06 18:16:17 +03:00
Ara 32f0f9618c Adding UUID to task creation for tracking the metrics of a Task in telemetry (#5379) 2025-08-06 00:14:32 -07:00
Ara 3001f883c2 Add walkthrough button and enable quick wins for new users (#5047)
* Add walkthrough button and enable quick wins for new users

- Add openWalkthrough RPC method to ui.proto
- Enable quick wins display for users with <3 tasks in history
- Add "Take a Tour" button in HomeHeader when quick wins are shown
- Update WelcomeSection to pass shouldShowQuickWins prop to HomeHeader

* Adding Gpt-oss through groq

* Adding Gpt-oss through groq

* Support prompt caching and thinking for Opus 4.1

* Support prompt caching and thinking for Opus 4.1

* Support prompt caching and thinking for Opus 4.1
2025-08-06 00:13:31 -07:00
github-actions[bot] a64e60b8f6 v3.20.13 Release Notes (#5391)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-06 00:12:50 -07:00
Saoud Rizwan 3a0e6a471b Add prompt caching for Opus 4.1 (#5389)
* Add prompt caching for Opus 4.1

* Create forty-poets-doubt.md
2025-08-06 00:10:50 -07:00
github-actions[bot] c10f4e0a66 v3.20.12 Release Notes (#5387)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.20.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-08-05 22:25:33 -07:00
Ara 3e11271cf8 Fix support for prompt caching and thinking for Opus 4.1 (#5386)
* Support prompt caching and thinking for Opus 4.1

* Support prompt caching and thinking for Opus 4.1
2025-08-05 22:12:14 -07:00
Jim Tang 29ae2c286d Update index.ts while tree possible as a null. (#5285) 2025-08-05 20:03:22 -07:00
github-actions[bot] 82aee44a9a v3.20.11 Release Notes (#5377) 2025-08-05 16:07:23 -07:00
omercelik 031604ddf6 feat: Added Claude Opus 4.1 to Bedrock (#5381)
* feat: Added Claude Opus 4.1 to Bedrock

* Create ninety-owls-develop.md
2025-08-05 15:03:15 -07:00
Bee f2101e375f fix: update Playwright config and teardown error handling (#5383)
- Remove teardown dependency on e2e tests to fix execution order
- Move server cleanup before file operations in teardown
- Add proper error handling and logging for cleanup operations
2025-08-05 14:22:19 -07:00
Tomás Barreiro 8a65f0c68b feat: Add Opus 4.1 to claude-code (#5382)
* Add opus-4-1 to claude-code

* Add changeset
2025-08-05 13:42:40 -07:00
Bee 32b8fa44cb refactor: Integrate Posthog into Feature Flags & Telemetry & Error Services (#5275)
* refactor: posthog services: feature flags + error + telemtry

- Convert PostHogClientProvider to singleton with lifecycle management
- Update ErrorServices to use PostHogClientProvider
- Update Telementry Service
- Update and enable Feature Flags service

* replace logger

* fix imports - part 1

* update distinct ID

* update

* update

* clean up

* revert autoformat

* fix merge conflicts

* clean up autoformat

* revert autoformatter

* clean up logs
2025-08-05 13:00:44 -07:00
Sarah Fortune 0d067f7470 Add getCallbackUri to the HostProvider (#5361) 2025-08-05 12:06:08 -07:00
Kevin Taylor de6166392c Update Cerebras gpt-oss-120b (#5376)
* Add Cerebras gpt-oss-120b

* Change completion tokens
2025-08-05 12:00:02 -07:00
Kevin Taylor 5f21a9162a Add Cerebras gpt-oss-120b (#5375)
* Add Cerebras gpt-oss-120b

* Update src/shared/api.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-08-05 11:27:11 -07:00
github-actions[bot] 4de991f1b0 v3.20.10 Release Notes (#5374) 2025-08-05 11:22:52 -07:00
pashpashpash 6e5d4a3f9e openai model in hugging face correct maxtokens (#5371)
* openai model in hugging face correct maxtokens

* maxtokens

* maxtokens 131k i guess?

* maxtokens swap

* changeset

* Adding Gpt-oss through groq

---------

Co-authored-by: arafatkatze <arafat.da.khan@gmail.com>
2025-08-05 11:08:53 -07:00
github-actions[bot] 95af95badf v3.20.9 Release Notes (#5354)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for version 3.20.9 patch 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-08-05 10:12:09 -07:00
Ara 61dcbd390c Adding Anthropic opus 4.1 (#5369)
* Adding Anthropic opus 4.1

* Adding Anthropic opus 4.1
2025-08-05 09:59:15 -07:00
pashpashpash 6255ac0a51 added provider flag to diff edit cli (#5334)
* added provider flag to diff edit cli

* dashboard ux

* more dashboard improvmeents

* native handler instead of just openai
2025-08-05 09:21:12 -07:00
Sarah Fortune 616800fcb9 Refactoring: move vscode specific property out of the WebviewProvider into the VscodeViewProvider (#5364) 2025-08-05 06:48:12 +01:00
Sarah Fortune df3826a59f In the webview grpc client, JSON encode/decode the messages when not running in Vscode (#5362) 2025-08-04 22:39:32 -07:00
Sarah Fortune 873917810d Remove left code from ProtoBus migration (#5363)
There is one place in the McpHub that sends messages mcp notification messages directly to the webview (not using the ProtoBus).

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

* fixed description rendering

* nit

* changeset

* revert openai version in package.json

* revert package-lock.json

* added space back in

* maintained previous protofield map order

* fixed import error due to location change from main

* updated Mode import for BasetenModelPicker

* revert readme since baseten is openai compatible

* refactored extensionStateContext

* added didOutputUsage flag

* fixed frontend loading

* no support for images on llama

* shifted VSCode Option order

* deleted typo

---------

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

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

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

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

* add changeset

* merge main and reset fail flag

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

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

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

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

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

  - Implemented callback URI provider

  - Updated to use HostProvider for callback URI

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

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

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

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

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

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

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

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

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

* base messaging implementation & ui

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

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 17:17:54 -07:00
Saoud Rizwan 3dd2ed9161 Add comment about testing fix (#5329)
* Add comment about testing fix

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

Switch over the remaining uses.

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

Exclude test files from the linter check.

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

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 16:57:50 -07:00
Sarah Fortune 88947592f0 Fix errors in tests (#5294)
* Fix errors in tests:

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

* Create brown-papayas-protect.md

---------

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

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

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-08-03 16:24:15 -07:00
celestial-vault 07ab6b19b8 check auth after initialize cacheservice (#5325)
* initialize cachService in controller constructor; remove authService as a class level variable on Controller

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

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

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

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

---------

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

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

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

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

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

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

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

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

* Formatting

---------

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

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.20.5

---------

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

* Add changeset

* Modify completion token limits

* Split qwen3 coder into free/paid

* Change -paid to base model name

* Update Cerebras models

* Update Cerebras models

* Update Cerebras models

* Update api.ts

* Update Cerebras models

---------

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

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

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

* use cache for apiCongfiguration state

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

* fix types after merge conflicts

* fix global state reset

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

* Updating CHANGELOG.md format

* releaseee

---------

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

* fix the conflicts for VscodeDiffViewProvider.ts has been moved

---------

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

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

* Rename Playwright test project names to match

* IS_DEV

* update helpers
2025-07-30 00:16:08 -07:00
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
1163 changed files with 114962 additions and 84010 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Added checkpoints warning when users start a multiroot task
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Added markdown support to focus chain text, allowing the model to display more interesting focus chains
+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)
}
@@ -0,0 +1,61 @@
# 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>
**Run the following command to get the latest changes (bash):**
```bash
B=$(for c in main master origin/main origin/master; do git rev-parse --verify -q "$c" >/dev/null && echo "$c" && break; done); B=${B:-HEAD}; r(){ git branch --show-current; printf "=== STATUS ===\n"; git status --porcelain | cat; printf "=== COMMIT MESSAGES ===\n"; git log "$B"..HEAD --oneline | cat; printf "=== CHANGED FILES ===\n"; git diff "$B" --name-only | cat; printf "=== FULL DIFF ===\n"; git diff "$B" | cat; }; L=$(r | wc -l); if [ "$L" -gt 500 ]; then r > cline-git-analysis.temp && echo "::OUTPUT_FILE=cline-git-analysis.temp"; else r; fi
```
```powershell
$B=$null;foreach($c in 'main','master','origin/main','origin/master'){git rev-parse --verify -q $c *> $null;if($LASTEXITCODE -eq 0){$B=$c;break}};if(-not $B){$B='HEAD'};function r([string]$b){git rev-parse --abbrev-ref HEAD; '=== STATUS ==='; git status --porcelain | cat; '=== COMMIT MESSAGES ==='; git log "$b"..HEAD --oneline | cat; '=== CHANGED FILES ==='; git diff "$b" --name-only | cat; '=== FULL DIFF ==='; git diff "$b" | cat};$out=r $B|Out-String;$lines=($out -split "`r?`n").Count;if($lines -gt 500){$out|Set-Content -NoNewline cline-git-analysis.temp; '::OUTPUT_FILE=cline-git-analysis.temp'}else{$out}
```
## 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
+3
View File
@@ -219,6 +219,9 @@ EOF
## Basic PR Commands
```bash
# Get current PR number
gh pr view --json number -q .number
# List open PRs
gh pr list
@@ -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.
-6
View File
@@ -1,6 +0,0 @@
[codespell]
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
skip = .git*,*.svg,package-lock.json,*.css,.codespellrc,locales
check-hidden = true
ignore-regex = (\b(optIn|isTaller)\b|https://\S+)
# ignore-words-list =
-35
View File
@@ -1,35 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "eslint-rules"],
"rules": {
"@typescript-eslint/naming-convention": [
"warn",
{
"selector": "import",
"format": ["camelCase", "PascalCase"]
}
],
"@typescript-eslint/semi": "off",
"curly": "warn",
"eqeqeq": "warn",
"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"]
}
+3 -1
View File
@@ -1 +1,3 @@
* @saoudrizwan @ocasta181 @NightTrek @pashpashpash @dcbartlett @saito-sv @Garoth
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
+66 -67
View File
@@ -1,70 +1,69 @@
name: 🐛 Bug Report
description: File a bug report
labels: ["bug"]
labels: ['bug']
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.
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Also tell us, what did you expect to happen?
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: How do you trigger this bug? Please walk us through it step by step.
value: |
1.
2.
3.
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant API REQUEST output
description: Please copy and paste any relevant output. This will be automatically formatted into code, so no need for backticks.
render: shell
- type: input
id: provider-model
attributes:
label: Provider/Model
description: What provider and model were you using when the issue occurred?
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"
validations:
required: true
- type: input
id: cline-version
attributes:
label: Cline Version
description: What version of Cline are you using? (You can find this at the bottom of the Settings view)
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.
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude Sonnet 4.5. Cline uses complex prompts so less capable models may not work as expected.
- type: dropdown
id: plugin-type
attributes:
label: Plugin Type
description: Which plugin are you reporting a bug for?
options:
- VSCode Extension
- JetBrains Plugin
default: 0
validations:
required: true
- type: input
id: cline-version
attributes:
label: Cline Version
description: What version of Cline are you using? (You can find this at the bottom of the Settings view)
placeholder: 'e.g., 1.2.3'
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Also tell us, what did you expect to happen?
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: How do you trigger this bug? Please walk us through it step by step.
value: |
1.
2.
3.
validations:
required: false
- type: input
id: provider-model
attributes:
label: Provider/Model
description: What provider and model were you using when the issue occurred?
placeholder: 'e.g., cline:anthropic/claude-sonnet-4.5, gemini:gemini-2.5-pro-exp-03-25'
validations:
required: false
- type: textarea
id: system-info
attributes:
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: false
@@ -1,116 +0,0 @@
name: 💡 Feature Proposal & Contribution
description: Propose a new feature or improvement, and optionally offer to implement feature as a contributor
labels: ["proposal"]
body:
- type: markdown
attributes:
value: |
**Feature Proposal & Contribution for Cline**
Thank you for proposing a feature or improvement for Cline! This template helps us understand the problem, evaluate the solution, and coordinate implementation.
**For detailed proposals:** Please provide comprehensive information to enable fast prioritization and discussion.
**For contribution offers:** You can indicate your willingness to implement the feature yourself.
Before submitting:
- Search existing [Issues](https://github.com/cline/cline/issues) and [Discussions](https://github.com/cline/cline/discussions) to avoid duplicates
- Read the [Contributing Guide](https://github.com/cline/cline/blob/main/CONTRIBUTING.md) if you plan to contribute
- Don't start implementation until the proposal is reviewed and approved
- type: textarea
id: problem-description
attributes:
label: What problem does this solve?
description: |
Describe the problem clearly from a user's point of view. Focus on why this matters, who it affects, and when it occurs.
✅ Good examples:
- "LLM provider returns 400 error when nearing the context window instead of truncating"
- "Submit button is invisible in dark mode"
- "Users can't easily share their Cline configurations with team members"
❌ Avoid vague descriptions:
- "Performance is bad"
- "UI needs work"
Your description should include:
- Who is affected?
- When does it happen?
- What's the current vs expected behavior?
- What is the impact?
placeholder: Be specific about the problem, who it affects, and the impact.
validations:
required: true
- type: textarea
id: proposed-solution
attributes:
label: What's the proposed solution?
description: |
Describe how the problem should be solved. Be specific about UX, system behavior, and any flows that would change.
✅ Good examples:
- "Add error handling immediately after attempting to create the llm stream and retry after manually truncating"
- "Update button styling to ensure contrast in all themes"
- "Add export/import functionality in settings with JSON format"
❌ Avoid vague solutions:
- "Improve performance"
- "Fix the bug"
Your solution should include:
- What exactly will change?
- How will users interact with it?
- What's the expected outcome?
placeholder: Describe the proposed changes and how they solve the problem.
validations:
required: false
- type: dropdown
id: contribution-intent
attributes:
label: Are you interested in implementing this?
description: Let us know if you'd like to contribute to this feature
options:
- "No, just proposing the idea"
- "Yes, I'd like to implement this myself"
- "Yes, I'd like to collaborate with others"
- "Maybe, depending on complexity and guidance"
validations:
required: false
- type: textarea
id: implementation-approach
attributes:
label: Implementation approach (if contributing)
description: |
**Only fill this out if you selected "Yes" above.**
How do you plan to implement this? Include:
- High-level technical approach
- Files/components that would be affected
- Any new dependencies required
- Potential challenges or considerations you've identified
This helps us provide better guidance and ensures alignment before you start coding.
placeholder: "My implementation approach would be..."
- type: checkboxes
id: checklist
attributes:
label: Proposal checklist
options:
- label: I've checked for existing issues or related proposals
required: true
- label: I understand this needs review before implementation can start
required: true
- type: checkboxes
id: contribution-checklist
attributes:
label: Contribution checklist (if contributing)
description: Only check these if you plan to contribute
options:
- label: I've read the [Contributing Guide](https://github.com/cline/cline/blob/main/CONTRIBUTING.md)
- label: I'm willing to make changes based on feedback
- label: I understand the code review process and requirements
+4 -5
View File
@@ -2,15 +2,14 @@
Thank you for contributing to Cline!
⚠️ Important: Before submitting this PR, please ensure you have:
- Opened an issue and discussed your proposed changes with the community / contributors
- Received approval from a core Cline contributor prior to proceeding with the implementation
- Link the associated issue in the "Related Issue" section
- 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
Limited exceptions:
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly.
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly without prior discussion.
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.
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
-28
View File
@@ -1,28 +0,0 @@
# Codespell configuration is within .codespellrc
---
name: Codespell
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
jobs:
codespell:
if: false
name: Check for spelling errors
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Annotate locations with typos
uses: codespell-project/codespell-problem-matcher@v1
- name: Codespell
uses: codespell-project/actions-codespell@v2
with:
only_warn: 1
+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/
+75
View File
@@ -0,0 +1,75 @@
name: "Publish Nightly Release"
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: write
packages: write
checks: write
pull-requests: write
jobs:
test:
uses: ./.github/workflows/test.yml
publish:
needs: test
name: Publish Cline (Nightly) Extension
if: github.repository == 'cline/cline'
runs-on: ubuntu-latest
environment: PublishNightly
steps:
- uses: actions/checkout@v4
- name: Check for recent commits
run: |
if [ $(git rev-list --count HEAD --since="24 hours ago") -eq 0 ]; then
echo "No commits in last 24 hours, exiting"
exit 0
fi
echo "Found recent commits, proceeding with build"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "lts/*"
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
- name: Publish Extension as Pre-release
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
run: npm run publish:marketplace:nightly
+4 -1
View File
@@ -94,9 +94,12 @@ jobs:
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
CLINE_ENVIRONMENT: production
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
run: |
# Required to generate the .vsix
vsce package --out "cline-${{ steps.get_version.outputs.version }}.vsix"
vsce package --allow-package-secrets sendgrid --out "cline-${{ steps.get_version.outputs.version }}.vsix"
if [ "${{ github.event.inputs.release-type }}" = "pre-release" ]; then
npm run publish:marketplace:prerelease
+141 -111
View File
@@ -1,6 +1,9 @@
name: Tests
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
branches:
@@ -14,7 +17,45 @@ permissions:
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
quality-checks:
runs-on: ubuntu-latest
name: Quality Checks
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Run Quality Checks (Parallel)
run: npm run ci:check-all
test:
needs: quality-checks
strategy:
fail-fast: false
matrix:
@@ -33,18 +74,6 @@ jobs:
with:
node-version: 22
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -52,7 +81,6 @@ jobs:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
@@ -68,57 +96,45 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install local modules on windows
if: runner.os == 'Windows' && steps.root-cache.outputs.cache-hit == 'true'
run: |
npm install eslint-plugin-eslint-rules
cd webview-ui/ && npm install eslint-plugin-eslint-rules
- name: Set up NPM on Windows
if: runner.os == 'Windows'
run: |
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
- name: Type Check
run: npm run check-types
- name: ESLint Check
run: npm run lint
- name: Prettier / Format Check
run: npm run format
# Build the extension before running tests
# Build the extension and tests (without redundant checks)
- name: Build Tests and Extension
run: npm run pretest
id: build_step
run: npm run ci:build
# Unit Tests disabled due to module system conflicts between backend and webview-ui
# - name: Unit Tests
# run: npm run test:unit
# Run extension tests with coverage
- name: Extension Tests with Coverage
id: extension_coverage
continue-on-error: true
- name: Unit Tests with coverage - Linux
id: unit_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: |
node ./scripts/test-ci.js > extension_coverage.txt 2>&1
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage extension_coverage.txt --type=extension --github-output --verbose
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
- name: Unit Tests - Non-Linux
id: unit_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: |
npm run test:unit
- name: Extension Integration Tests - Linux
id: integration_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: xvfb-run -a npm run test:coverage
- name: Extension Integration Tests - Non-Linux
id: integration_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: npm run test:integration
# Run webview tests with coverage
- name: Webview Tests with Coverage
id: webview_coverage
continue-on-error: true
id: webview_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: |
cd webview-ui
# Ensure coverage dependency is installed
npm install --no-save @vitest/coverage-v8
npm run test:coverage > webview_coverage.txt 2>&1
cd ..
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage webview-ui/webview_coverage.txt --type=webview --github-output --verbose
npm run test:coverage
# Save coverage reports as artifacts (workflow-scoped)
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
@@ -126,54 +142,21 @@ jobs:
with:
name: pr-coverage-reports
path: |
extension_coverage.txt
webview-ui/webview_coverage.txt
retention-period: workflow # Artifacts are automatically deleted when the workflow completes
coverage-unit/lcov.info
webview-ui/coverage/lcov.info
# Set the check as failed if any of the tests failed
- name: Print test results and check for failures
run: |
echo "Extension Tests Result: ${{ steps.extension_coverage.outcome }}"
cat extension_coverage.txt
echo "Webview Tests Result: ${{ steps.webview_coverage.outcome }}"
cat webview-ui/webview_coverage.txt
# Check if any of the test steps failed
# https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/accessing-contextual-information-about-workflow-runs#steps-context
if [ "${{ steps.extension_coverage.outcome }}" != "success" ] || [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
echo "Tests failed."
exit 1
fi
coverage:
needs: test
test-platform-integration:
needs: quality-checks
runs-on: ubuntu-latest
# Only run on PRs to main branch
if: github.event_name == 'pull_request' && github.base_ref == 'main'
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for accurate comparison
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -181,7 +164,6 @@ jobs:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
@@ -189,6 +171,14 @@ jobs:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
# Cache testing-platform dependencies
- name: Cache testing-platform dependencies
uses: actions/cache@v4
id: testing-platform-cache
with:
path: testing-platform/node_modules
key: ${{ runner.os }}-npm-testing-platform-${{ hashFiles('testing-platform/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
@@ -197,30 +187,70 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
# Build the extension before running tests
- name: Build Extension
run: npm run compile
- name: Compile standalone
run: npm run compile-standalone
# Download coverage artifacts from test job
- name: Download Coverage Reports
- name: Install testing platform dependencies
if: steps.testing-platform-cache.outputs.cache-hit != 'true'
run: cd testing-platform && npm ci
- name: Running testing platform integration spec tests
continue-on-error: true
timeout-minutes: 7
# Temporarily wrapping the test command to always return a neutral exit code.
# This prevents the job from showing as failed and avoids distracting developers
# until the integration tests are ready to be enforced.
run: |
npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage || true
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
with:
name: test-platform-integration-core-coverage
path: coverage/**/lcov.info
qlty:
needs: [test, test-platform-integration]
runs-on: ubuntu-latest
# Run on PRs to main, pushes to main, and manual dispatches
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download unit tests coverage reports
uses: actions/download-artifact@v4
with:
name: pr-coverage-reports
path: . # Download to root directory to match expected paths
path: .
# Process coverage workflow
- name: Process coverage workflow
id: coverage
run: |
# Extract PR number from GITHUB_REF
PR_NUMBER=$(echo "$GITHUB_REF" | sed -e 's/refs\/pull\///' -e 's/\/merge//')
- name: Upload core unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
coverage-unit/lcov.info
tag: unit:core
# Run the coverage workflow from root directory
PYTHONPATH=.github/scripts python -m coverage_check process-workflow \
--base-branch ${{ github.base_ref }} \
--pr-number $PR_NUMBER \
--repo $GITHUB_REPOSITORY \
--token ${{ secrets.GITHUB_TOKEN }} \
--verbose
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload webview-ui unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
webview-ui/coverage/lcov.info
tag: unit:webview-ui
add-prefix: webview-ui/
- name: Download test platform integration core coverage artifact
uses: actions/download-artifact@v4
with:
name: test-platform-integration-core-coverage
path: integration-core-coverage-reports
- name: Upload core integration tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
files: integration-core-coverage-reports/**/lcov.info
tag: integration:core
@@ -0,0 +1,53 @@
name: Trigger Jetbrains Plugin <-> Cline Tests
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: jetbrains-trigger-${{ github.event.number }}
cancel-in-progress: true
jobs:
trigger-integration-test:
name: Run Tests
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App Token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: 1998650
private-key: ${{ secrets.CLINE_JETBRAINS_WORKFLOW_KEY }}
owner: cline
repositories: intellij-plugin
- name: Trigger IntelliJ Plugin Integration Test
run: |
curl -X POST \
-H "Authorization: Bearer ${{ steps.app-token.outputs.token }}" \
-H "Accept: application/vnd.github.v3+json" \
-H "User-Agent: cline-pr-trigger" \
-H "Content-Type: application/json" \
https://api.github.com/repos/cline/intellij-plugin/dispatches \
-d @- <<EOF
{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"action": "${{ github.event.action }}",
"sha": "${{ github.event.pull_request.head.sha }}",
"pr_title": ${{ toJSON(github.event.pull_request.title) }},
"pr_url": "${{ github.event.pull_request.html_url }}"
}
}
EOF
- name: Log trigger details
run: |
echo "Triggered IntelliJ Plugin integration test for:"
echo " PR #${{ github.event.number }}: ${{ github.event.pull_request.title }}"
echo " Branch: ${{ github.head_ref }}"
echo " Action: ${{ github.event.action }}"
echo " SHA: ${{ github.event.pull_request.head.sha }}"
+10 -15
View File
@@ -15,27 +15,22 @@ pnpm-lock.yaml
.venv
.actrc
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
# Ignore coverage directories and files
coverage
coverage-unit
.nyc_output
# But don't ignore the coverage scripts in .github/scripts/
!.github/scripts/coverage/
*evals.env
# Generated files
## Generated files ##
src/generated/
# Core
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
src/shared/proto/
webview-ui/src/services/grpc-client.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
src/standalone/server-setup.ts
# E2E Tests
test-results
Executable → Regular
+1 -17
View File
@@ -1,17 +1 @@
echo "Running pre-commit checks..."
# Run ESLint
echo "Running ESLint..."
npm run lint || {
echo "❌ ESLint check failed. Please fix the errors and try committing again."
exit 1
}
# Run Prettier
echo "Running Prettier..."
npx lint-staged --verbose || {
echo "❌ Prettier failed. Please fix the errors and try committing again."
exit 1
}
echo "✅ All checks passed!"
lint-staged
+13 -4
View File
@@ -1,6 +1,15 @@
{
"extension": ["ts"],
"spec": ["src/**/__tests__/*.ts", "eslint-rules/__tests__/**/*.test.ts"],
"require": ["ts-node/register", "source-map-support/register", "./src/test/requires.ts"],
"recursive": true
"extension": [
"ts"
],
"spec": [
"src/**/__tests__/*.ts"
],
"require": [
"ts-node/register",
"source-map-support/register",
"./src/test/requires.ts"
],
"recursive": true,
"exit": true
}
+48
View File
@@ -0,0 +1,48 @@
{
"all": true,
"check-coverage": false,
"reporter": [
"text",
"lcov"
],
"include": [
"src/**/*.ts"
],
"exclude": [
"**/*.d.ts",
"**/*.{test,spec}.{js,jsx,ts,tsx,mjs,cjs}",
"**/__tests__/**",
"**/test/**",
"**/tests/**",
"**/.nyc_output/**",
"**/.vscode-test/**",
"**/tests-results/**",
"src/test/**",
"src/generated/**",
"**/node_modules/**",
"**/dist/**",
"**/out/**",
"**/build/**",
"**/coverage/**",
"**/coverage-unit/**",
"**/proto/**",
"**/*.{config,setup}.{js,ts,mjs,cjs}",
"**/vite-env.d.ts",
"**/*.{css,scss,sass,less,styl}",
"**/*.{svg,png,jpg,jpeg,gif,ico}",
"**/*.{json,yaml,yml}"
],
"extension": [
".ts",
".js"
],
"cache": true,
"sourceMap": true,
"instrument": true,
"report-dir": "./coverage-unit"
}
-8
View File
@@ -1,8 +0,0 @@
dist/
node_modules
webview-ui/build/
*.md
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
evals/
-8
View File
@@ -1,8 +0,0 @@
{
"tabWidth": 4,
"useTabs": true,
"printWidth": 130,
"semi": false,
"bracketSameLine": true,
"endOfLine": "lf"
}
+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
+2 -2
View File
@@ -2,9 +2,9 @@
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner",
"bradlc.vscode-tailwindcss"
"bradlc.vscode-tailwindcss",
"biomejs.biome"
]
}
+119 -19
View File
@@ -6,15 +6,63 @@
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"name": "Run Extension (production)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
],
"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",
"--disable-extensions", // Avoid conflicts with installed extensions
"${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",
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "local"
}
},
{
@@ -26,39 +74,91 @@
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extensions",
"--disable-extensions", // Avoid conflicts with installed extensions
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "clean-tmp-user",
"internalConsoleOptions": "openOnSessionStart",
"postDebugTask": "stop",
"env": {
"IS_DEV": "true",
"TEMP_PROFILE": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
{
"type": "node",
"request": "launch",
"name": "Run Standalone Service",
"skipFiles": ["<node_internals>/**"],
"name": "Debug Test Standalone Core Api Server (test:sca-server)",
"skipFiles": [
"<node_internals>/**"
],
"sourceMaps": true,
"resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
"cwd": "${workspaceFolder}/dist-standalone",
"outFiles": ["${workspaceFolder}/dist-standalone/**/*.js"],
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}",
"outFiles": [
"${workspaceFolder}/dist/**/*.js",
"${workspaceFolder}/dist-standalone/**/*.js"
],
"preLaunchTask": "compile-standalone",
"runtimeExecutable": "npx",
"runtimeArgs": [
"tsx"
],
"program": "scripts/test-standalone-core-api-server.ts",
"env": {
// Turns on grpc debug log.
//"GRPC_TRACE": "all",
//"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules",
"HOST_BRIDGE_ADDRESS": "localhost:50052"
"PROTOBUS_PORT": "26040",
"HOSTBRIDGE_PORT": "26041",
"WORKSPACE_DIR": "${workspaceFolder}",
"E2E_TEST": "true",
"CLINE_ENVIRONMENT": "local"
},
"program": "standalone.js"
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "launch",
"name": "Debug Current Test File",
"skipFiles": [
"<node_internals>/**"
],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npx",
"runtimeArgs": [
"mocha"
],
"args": [
"--require",
"ts-node/register",
"--require",
"source-map-support/register",
"--require",
"./src/test/requires.ts",
"--exit",
"${file}"
],
"env": {
"TS_NODE_PROJECT": "./tsconfig.unit-test.json",
"NODE_ENV": "test",
"IS_DEV": "true",
"CLINE_ENVIRONMENT": "local"
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnSessionStart"
}
]
}
+20 -2
View File
@@ -6,8 +6,26 @@
},
"search.exclude": {
"out": true, // set this to false to include "out" folder in search results
"dist": true // set this to false to include "dist" folder in search results
"dist": true, // set this to false to include "dist" folder in search results,
"node_modules": true,
"dist-standalone": true
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
"typescript.tsc.autoDetect": "off",
"typescript.preferences.quoteStyle": "double",
// Protobuf settings
"protoc": {
"options": [
"--proto_path=proto"
]
},
// Enable Lint and format using Biome
"biome.enabled": true,
"editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": {
"source.fixAll.biome": "explicit",
"source.removeUnused.biome": "always",
"source.removeUnusedImports": "always",
"source.organizeImports.biome": "always"
}
}
+36 -10
View File
@@ -30,7 +30,13 @@
},
{
"label": "watch",
"dependsOn": ["npm: protos", "npm: build:webview", "npm: dev:webview", "npm: watch:tsc", "npm: watch:esbuild"],
"dependsOn": [
"npm: protos",
"npm: build:webview",
"npm: dev:webview",
"npm: watch:tsc",
"npm: watch:esbuild"
],
"presentation": {
"reveal": "always"
},
@@ -60,7 +66,9 @@
"problemMatcher": [],
"isBackground": true,
"label": "npm: build:webview",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -78,7 +86,9 @@
"problemMatcher": [],
"isBackground": true,
"label": "npm: build:webview:test",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -113,7 +123,9 @@
],
"isBackground": true,
"label": "npm: dev:webview",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -149,7 +161,9 @@
},
"isBackground": true,
"label": "npm: watch:esbuild",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -185,7 +199,9 @@
},
"isBackground": true,
"label": "npm: watch:esbuild:test",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -204,7 +220,9 @@
"problemMatcher": "$tsc-watch",
"isBackground": true,
"label": "npm: watch:tsc",
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"group": "watch",
"reveal": "always"
@@ -215,7 +233,9 @@
"script": "watch-tests",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"dependsOn": ["npm: protos"],
"dependsOn": [
"npm: protos"
],
"presentation": {
"reveal": "always",
"group": "watchers"
@@ -224,7 +244,11 @@
},
{
"label": "tasks: watch-tests",
"dependsOn": ["npm: protos", "npm: watch", "npm: watch-tests"],
"dependsOn": [
"npm: protos",
"npm: watch",
"npm: watch-tests"
],
"problemMatcher": []
},
{
@@ -235,7 +259,9 @@
{
"label": "clean-tmp-user",
"type": "shell",
"dependsOn": ["watch"],
"dependsOn": [
"watch"
],
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
}
],
+29 -5
View File
@@ -1,27 +1,40 @@
# Default
.vscode/**
.vscode-test/**
out/**
dist-standalone/**
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/**
@@ -46,3 +59,14 @@ old_docs/**
# Include icons
!assets/icons/**
# Ignore E2E build files
e2e-build.mjs
e2e.vsix
test-results/
# Ignore Storybook files
**/*.stories.tsx
*storybook.log
storybook-static
**/StorybookDecorator.tsx
+928 -525
View File
File diff suppressed because it is too large Load Diff
+36 -10
View File
@@ -14,14 +14,11 @@ Bug reports help make Cline better for everyone! Before creating a new issue, pl
## 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.
- **Check existing issues**: Search [GitHub Issues](https://github.com/cline/cline/issues).
- **Create an issue**: Use appropriate templates:
- **Contributions:** Use the "Contribution Request" template to propose what you'd like to work on.
- **Bugs:** "Bug Report" template for reporting issues.
- **Features:** "Detailed Feature Proposal" template for suggesting new features.
- **Wait for approval**: A core Cline contributor must approve your contribution request before you start implementation.
- **Claim issues**: Once approved, the issue will be assigned to you.
**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.**
@@ -77,7 +74,6 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
4. Testing
- Run `npm run test` to run tests locally.
- Before submitting PR, run `npm run format:fix` to format your code
- Run `npm run test:ci` to run tests locally
### Extension
@@ -150,7 +146,7 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
- Run `npm run lint` to check code style
- Run `npm run format` to automatically format code
- All PRs must pass CI checks which include both linting and formatting
- Address any ESLint warnings or errors before submitting
- Address any warnings or errors from linter before submitting
- Follow TypeScript best practices and maintain type safety
3. **Testing**
@@ -160,6 +156,36 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
- Update existing tests if your changes affect them
- Include both unit tests and integration tests where appropriate
**End-to-End (E2E) Testing**
Cline includes comprehensive E2E tests using Playwright that simulate real user interactions with the extension in VS Code:
- **Running E2E tests:**
```bash
npm run test:e2e # Build and run all E2E tests
npm run e2e # Run tests without rebuilding
npm run test:e2e -- --debug # Run with interactive debugger
```
- **Writing E2E tests:**
- Tests are located in `src/test/e2e/`
- Use the `e2e` fixture for single-root workspace tests
- Use `e2eMultiRoot` fixture for multi-root workspace tests
- Follow existing patterns in `auth.test.ts`, `chat.test.ts`, `diff.test.ts`, and `editor.test.ts`
- See `src/test/e2e/README.md` for detailed documentation
- **Debug mode features:**
- Interactive Playwright Inspector for step-by-step debugging
- Record new interactions and generate test code automatically
- Visual VS Code instance for manual testing
- Element inspection and selector validation
- **Test environment:**
- Automated VS Code setup with Cline extension loaded
- Mock API server for backend testing
- Temporary workspaces with test fixtures
- Video recording for failed tests
4. **Version Management with Changesets**
- Create a changeset for any user-facing changes using `npm run changeset`
+4 -4
View File
@@ -30,9 +30,9 @@ English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md
</table>
</div>
Meet Cline (pronounced /klaɪn/, like "Klein"), an AI assistant that can use your **CLI** a**N**d **E**ditor.
Meet Cline, 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.
Thanks to [Claude 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.
1. Enter your task and add images to convert mockups into functional apps or fix bugs with screenshots.
2. Cline starts by analyzing your file structure & source code ASTs, running regex searches, and reading relevant files to get up to speed in existing projects. By carefully managing what information is added to context, Cline can provide valuable assistance even for large, complex projects without overwhelming the context window.
@@ -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.
@@ -87,7 +87,7 @@ All changes made by Cline are recorded in your file's Timeline, providing an eas
### Use the Browser
With Claude 3.5 Sonnet's new [Computer Use](https://www.anthropic.com/news/3-5-models-and-computer-use) capability, Cline can launch a browser, click elements, type text, and scroll, capturing screenshots and console logs at each step. This allows for interactive debugging, end-to-end testing, and even general web use! This gives him autonomy to fixing visual bugs and runtime issues without you needing to handhold and copy-pasting error logs yourself.
With Claude Sonnet's new [Computer Use](https://www.anthropic.com/news/3-5-models-and-computer-use) capability, Cline can launch a browser, click elements, type text, and scroll, capturing screenshots and console logs at each step. This allows for interactive debugging, end-to-end testing, and even general web use! This gives him autonomy to fixing visual bugs and runtime issues without you needing to handhold and copy-pasting error logs yourself.
Try asking Cline to "test the app", and watch as he runs a command like `npm run dev`, launches your locally running dev server in a browser, and performs a series of tests to confirm that everything works. [See a demo here.](https://x.com/sdrzn/status/1850880547825823989)
+166
View File
@@ -0,0 +1,166 @@
{
"$schema": "https://biomejs.dev/schemas/2.1.4/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"defaultBranch": "main"
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on",
"useSortedAttributes": "on"
}
}
},
"linter": {
"enabled": true,
"domains": {
"react": "recommended"
},
// Ideally we would want to turn on all the rules that are currently off,
// keeping them off currently to make sure only changes on the migrations
// are included in the initial PR before we apply the format and lint changes.
// TODO: turn on all rules that are currently off if applicable.
// TODO: Remove --diagnostic-level=error from CI commands.
"rules": {
"recommended": true,
"correctness": {
"useExhaustiveDependencies": "off",
"noUndeclaredVariables": "off",
"noEmptyPattern": "off",
"useJsxKeyInIterable": "off",
"noInnerDeclarations": "off",
"useHookAtTopLevel": "off",
"useYield": "off",
"noConstructorReturn": "off",
"noInvalidPositionAtImportRule": "off",
"noSwitchDeclarations": "off",
"noUnusedImports": "error"
},
"a11y": "off",
"style": {
"useNodejsImportProtocol": "off",
"useImportType": "off",
"useBlockStatements": "warn",
"useNamingConvention": "off",
"useThrowOnlyError": "info",
"useConsistentArrayType": "off",
"noParameterAssign": "off",
"useAsConstAssertion": "off",
"useDefaultParameterLast": "off",
"noNonNullAssertion": "off",
"useEnumInitializers": "off",
"useSelfClosingElements": "off",
"useSingleVarDeclarator": "off",
"useNumberNamespace": "off",
"noInferrableTypes": "off",
"useTemplate": "off",
"noUselessElse": "off"
},
"suspicious": {
"noDoubleEquals": "warn",
"noImplicitAnyLet": "info",
"noThenProperty": "off",
"noAsyncPromiseExecutor": "off",
"noImportAssign": "off",
"noExplicitAny": "off",
"noControlCharactersInRegex": "off",
"noShadowRestrictedNames": "off",
"noArrayIndexKey": "info",
"noAssignInExpressions": "warn"
},
"complexity": {
"noUselessConstructor": "off",
"useOptionalChain": "off",
"noBannedTypes": "off",
"useLiteralKeys": "off",
"noUselessCatch": "off",
"noUselessSwitchCase": "off",
"noStaticOnlyClass": "off"
},
"security": {
"noDangerouslySetInnerHtml": "warn"
}
}
},
"formatter": {
"enabled": true,
"indentStyle": "tab",
"indentWidth": 4,
"lineWidth": 130,
"lineEnding": "lf",
"formatWithErrors": true
},
"javascript": {
"formatter": {
"semicolons": "asNeeded",
"arrowParentheses": "always",
"bracketSameLine": true,
"bracketSpacing": true,
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "all"
}
},
"json": {
"formatter": {
"trailingCommas": "none",
"expand": "always"
}
},
"files": {
"includes": [
"**",
"!**/dist/**",
"!**/dist-*/**",
"!**/out/**",
"!**/evals/**",
"!**/playwright/**",
"!**/test-results/**",
"!**/node_modules/**",
"!**/webview-ui/build/**",
"!**/generated/**",
"!**/proto/**",
"!**/tests/specs/**"
]
},
"plugins": [
"src/dev/grit/process-env.grit"
],
"overrides": [
{
"includes": [
"**",
"!**/hosts/vscode/**",
"!**/test/**",
"!**/*.test.ts",
"!src/dev/**",
"!src/extension.ts",
"!src/integrations/git/commit-message-generator.ts",
"!src/integrations/terminal/**",
"!src/core/controller/ui/openWalkthrough.ts"
],
"plugins": [
"src/dev/grit/vscode-api.grit"
]
},
{
"includes": [
"**",
"!src/core/storage/state-migrations.ts",
"!src/core/storage/FileContextTracker.ts",
"!src/core/context/context-tracking/FileContextTracker.ts",
"!src/common.ts",
"!src/services/logging/distinctId.ts",
"!src/core/storage/utils/state-helpers.ts",
"!src/extension.ts"
],
"plugins": [
"src/dev/grit/use-cache-service.grit"
]
}
]
}
-1
View File
@@ -9,7 +9,6 @@ lint:
except: # Add exceptions for current patterns that contradict STANDARD settings
- RPC_PASCAL_CASE # rpcs are camel case (start with lowercase)
- PACKAGE_DIRECTORY_MATCH # the protos in the cline package are not in a dir named cline.
- 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
+2
View File
@@ -0,0 +1,2 @@
cline-core-debug.log
bin/*
+6
View File
@@ -0,0 +1,6 @@
/_____/\ /_/\ /_______/\/__/\ /__/\ /_____/\
\:::__\/ \:\ \ \__.::._\/\::\_\\ \ \\::::_\/_
\:\ \ __\:\ \ \::\ \ \:. `-\ \ \\:\/___/\
\:\ \/_/\\:\ \____ _\::\ \__\:. _ \ \\::___\/_
\:\_\ \ \\:\/___/\/__\::\__/\\. \`-\ \ \\:\____/\
\_____\/ \_____\/\________\/ \__\/ \__\/ \_____\/
+71
View File
@@ -0,0 +1,71 @@
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/spf13/cobra"
"github.com/cline/cli/pkg/hostbridge"
)
var (
port int
verbose bool
)
func main() {
rootCmd := &cobra.Command{
Use: "cline-host",
Short: "Cline Host Bridge Service",
Long: `A simple host bridge service that provides host operations for Cline Core.`,
RunE: runServer,
}
rootCmd.Flags().IntVarP(&port, "port", "p", 51052, "port to listen on")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func runServer(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Create gRPC hostbridge service
service := hostbridge.NewGrpcServer(port, verbose)
// Handle graceful shutdown
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
if verbose {
log.Println("Shutting down hostbridge server...")
}
cancel()
}()
// Start server
if verbose {
log.Printf("Starting Cline Host Bridge on port %d", port)
}
// Run the service
if err := service.Start(ctx); err != nil {
return fmt.Errorf("failed to run service: %w", err)
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"context"
"fmt"
"os"
"github.com/cline/cli/pkg/cli"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/common"
"github.com/spf13/cobra"
)
var (
coreAddress string
cfgFile string
verbose bool
outputFormat string
)
func main() {
rootCmd := &cobra.Command{
Use: "cline",
Short: "Cline CLI - AI-powered coding assistant",
Long: `A command-line interface for interacting with Cline AI coding assistant.
This CLI provides access to Cline's task management, configuration, and
monitoring capabilities from the terminal.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if outputFormat != "rich" && outputFormat != "json" && outputFormat != "plain" {
return fmt.Errorf("invalid output format '%s': must be one of 'rich', 'json', or 'plain'", outputFormat)
}
return global.InitializeGlobalConfig(&global.GlobalConfig{
ConfigPath: cfgFile,
Verbose: verbose,
OutputFormat: outputFormat,
CoreAddress: coreAddress,
})
},
}
rootCmd.PersistentFlags().StringVar(&coreAddress, "address", fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT), "Cline Core gRPC address")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cline/config.yaml)")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "o", "rich", "output format (rich|json|plain)")
rootCmd.AddCommand(cli.NewTaskCommand())
rootCmd.AddCommand(cli.NewInstanceCommand())
rootCmd.AddCommand(cli.NewVersionCommand())
rootCmd.AddCommand(cli.NewAuthCommand())
if err := rootCmd.ExecuteContext(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
+154
View File
@@ -0,0 +1,154 @@
package e2e
import (
"context"
"encoding/json"
"os"
"path/filepath"
"syscall"
"testing"
"github.com/cline/cli/pkg/common"
)
// 2. Multi-instance start: default_instance remains the first started.
func TestMultiInstanceDefaultUnchanged(t *testing.T) {
_ = setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Start first instance and wait healthy
_ = mustRunCLI(ctx, t, "instance", "new")
out1 := listInstancesJSON(ctx, t)
if len(out1.CoreInstances) != 1 {
t.Fatalf("expected 1 instance, got %d", len(out1.CoreInstances))
}
firstAddr := out1.CoreInstances[0].Address
waitForAddressHealthy(t, firstAddr, defaultTimeout)
// Start second instance
_ = mustRunCLI(ctx, t, "instance", "new")
out2 := listInstancesJSON(ctx, t)
if len(out2.CoreInstances) < 2 {
t.Fatalf("expected at least 2 instances, got %d", len(out2.CoreInstances))
}
// Default should remain the first started address
if out2.DefaultInstance != firstAddr {
t.Fatalf("default changed; expected %s, got %s", firstAddr, out2.DefaultInstance)
}
}
// 6. Default.json update after removal of current default
func TestDefaultJsonUpdateAfterRemoval(t *testing.T) {
_ = setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Start two instances
_ = mustRunCLI(ctx, t, "instance", "new")
_ = mustRunCLI(ctx, t, "instance", "new")
out := listInstancesJSON(ctx, t)
if len(out.CoreInstances) < 2 {
t.Fatalf("expected at least 2 instances, got %d", len(out.CoreInstances))
}
// Choose second as new default
target := out.CoreInstances[1]
waitForAddressHealthy(t, target.Address, defaultTimeout)
// Set as default
_ = mustRunCLI(ctx, t, "instance", "use", target.Address)
// Verify default switched
out = listInstancesJSON(ctx, t)
if out.DefaultInstance != target.Address {
t.Fatalf("default_instance not updated to %s (got %s)", target.Address, out.DefaultInstance)
}
// Kill the default instance using runtime PID discovery
corePID := getCorePID(t, target.Address)
if corePID <= 0 {
t.Fatalf("could not find PID for core process at %s", target.Address)
}
t.Logf("Killing cline-core process PID %d for instance %s", corePID, target.Address)
if err := syscall.Kill(corePID, syscall.SIGKILL); err != nil {
t.Fatalf("kill pid %d: %v", corePID, err)
}
// Wait for removal
waitForAddressRemoved(t, target.Address, longTimeout)
// Clean up dangling host process (SIGKILL leaves these behind by design)
t.Logf("Cleaning up dangling host process on port %d", target.HostPort())
findAndKillHostProcess(t, target.HostPort())
// Ensure default_instance updated to another available instance (or removed if none remain)
out = listInstancesJSON(ctx, t)
// If there are instances left, default_instance must be one of them
if len(out.CoreInstances) > 0 {
found := false
for _, it := range out.CoreInstances {
if out.DefaultInstance == it.Address {
found = true
break
}
}
if !found {
t.Fatalf("default_instance %s not set to an existing instance after removal", out.DefaultInstance)
}
} else {
// No instances remain; cli-default-instance.json should be removed
clineDir := getClineDir(t)
defPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
if _, err := os.Stat(defPath); err == nil {
t.Fatalf("expected cli-default-instance.json removed when no instances remain")
}
}
// Also verify cli-default-instance.json on disk reflects the in-memory default (if any)
clineDir := getClineDir(t)
defPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
if len(out.CoreInstances) > 0 {
raw, err := os.ReadFile(defPath)
if err != nil {
t.Fatalf("read cli-default-instance.json: %v", err)
}
var tmp struct {
DefaultInstance string `json:"default_instance"`
}
if err := json.Unmarshal(raw, &tmp); err != nil {
t.Fatalf("unmarshal cli-default-instance.json: %v", err)
}
if tmp.DefaultInstance != out.DefaultInstance {
t.Fatalf("cli-default-instance.json mismatch: file=%s list=%s", tmp.DefaultInstance, out.DefaultInstance)
}
}
}
// 11. SQLite database missing (edge): list succeeds and returns empty set
func TestRegistryDirMissingEdge(t *testing.T) {
clineDir := setTempClineDir(t)
// Remove the settings directory entirely (which contains locks.db)
settingsDir := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER)
if err := os.RemoveAll(settingsDir); err != nil {
t.Fatalf("RemoveAll(%s): %v", common.SETTINGS_SUBFOLDER, err)
}
// Listing should succeed and return empty results
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
out := listInstancesJSON(ctx, t)
if len(out.CoreInstances) != 0 {
t.Fatalf("expected 0 instances after removing %s dir, got %d", common.SETTINGS_SUBFOLDER, len(out.CoreInstances))
}
// Ensure cli-default-instance.json not present
defPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
if _, err := os.Stat(defPath); err == nil {
t.Fatalf("expected no cli-default-instance.json after removing %s dir", common.SETTINGS_SUBFOLDER)
}
}
+378
View File
@@ -0,0 +1,378 @@
package e2e
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/common"
"github.com/cline/grpc-go/cline"
)
const (
defaultTimeout = 30 * time.Second
longTimeout = 60 * time.Second
pollInterval = 250 * time.Millisecond
instancesBinRel = "../bin/cline"
)
func repoAwareBinPath(t *testing.T) string {
// Tests live in repoRoot/cli/e2e. Binary is at repoRoot/cli/bin/cline
t.Helper()
wd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd error: %v", err)
}
// cli/e2e -> cli/bin/cline
p := filepath.Clean(filepath.Join(wd, instancesBinRel))
if _, err := os.Stat(p); err != nil {
t.Fatalf("CLI binary not found at %s; run `npm run compile-cli` first: %v", p, err)
}
return p
}
func setTempClineDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
clineDir := filepath.Join(dir, ".cline")
if err := os.MkdirAll(clineDir, 0o755); err != nil {
t.Fatalf("mkdir clineDir: %v", err)
}
t.Setenv("CLINE_DIR", clineDir)
return clineDir
}
func runCLI(ctx context.Context, t *testing.T, args ...string) (string, string, int) {
t.Helper()
bin := repoAwareBinPath(t)
// Ensure CLI uses the same CLINE_DIR as the tests by passing --config=<CLINE_DIR>
// (InitializeGlobalConfig uses ConfigPath as the base directory for registry.)
if clineDir := os.Getenv("CLINE_DIR"); clineDir != "" && !contains(args, "--config") {
// Prepend persistent flag so Cobra sees it regardless of subcommand position
args = append([]string{"--config", clineDir}, args...)
}
cmd := exec.CommandContext(ctx, bin, args...)
// Run CLI from repo root so relative paths inside CLI (./cli/bin/...) resolve
if wd, err := os.Getwd(); err == nil {
repoRoot := filepath.Clean(filepath.Join(wd, "..", ".."))
cmd.Dir = repoRoot
}
// propagate env including CLINE_DIR
cmd.Env = os.Environ()
outB, errB := &strings.Builder{}, &strings.Builder{}
cmd.Stdout = outB
cmd.Stderr = errB
err := cmd.Run()
exit := 0
if err != nil {
// Extract exit code if possible
if ee, ok := err.(*exec.ExitError); ok {
exit = ee.ExitCode()
} else {
exit = -1
}
}
return outB.String(), errB.String(), exit
}
func mustRunCLI(ctx context.Context, t *testing.T, args ...string) string {
t.Helper()
out, errOut, exit := runCLI(ctx, t, args...)
if exit != 0 {
t.Fatalf("cline %v failed (exit=%d)\nstdout:\n%s\nstderr:\n%s", args, exit, out, errOut)
}
return out
}
func listInstancesJSON(ctx context.Context, t *testing.T) common.InstancesOutput {
t.Helper()
// Trigger CLI to perform cleanup/health by invoking list (table output is ignored)
_ = mustRunCLI(ctx, t, "instance", "list")
// Read from SQLite locks database to build structured output
clineDir := getClineDir(t)
// Load default instance from settings file
defaultInstance := readDefaultInstanceFromSettings(t, clineDir)
// Load instances from SQLite
instances := readInstancesFromSQLite(t, clineDir)
return common.InstancesOutput{
DefaultInstance: defaultInstance,
CoreInstances: instances,
}
}
func hasAddress(in common.InstancesOutput, addr string) bool {
for _, it := range in.CoreInstances {
if it.Address == addr {
return true
}
}
return false
}
func getByAddress(in common.InstancesOutput, addr string) (common.CoreInstanceInfo, bool) {
for _, it := range in.CoreInstances {
if it.Address == addr {
return it, true
}
}
return common.CoreInstanceInfo{}, false
}
func waitFor(t *testing.T, timeout time.Duration, cond func() (bool, string)) {
t.Helper()
deadline := time.Now().Add(timeout)
for {
ok, msg := cond()
if ok {
return
}
if time.Now().After(deadline) {
t.Fatalf("waitFor timeout: %s", msg)
}
time.Sleep(pollInterval)
}
}
func waitForAddressHealthy(t *testing.T, addr string, timeout time.Duration) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
t.Logf("Waiting for gRPC health check on %s...", addr)
waitFor(t, timeout, func() (bool, string) {
if common.IsInstanceHealthy(ctx, addr) {
return true, ""
}
return false, fmt.Sprintf("gRPC health check failed for %s", addr)
})
t.Logf("gRPC health check passed for %s", addr)
}
func waitForAddressRemoved(t *testing.T, addr string, timeout time.Duration) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
waitFor(t, timeout, func() (bool, string) {
out := listInstancesJSON(ctx, t)
if hasAddress(out, addr) {
return false, fmt.Sprintf("address %s still present", addr)
}
return true, ""
})
}
func findFreePort(t *testing.T) int {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen 127.0.0.1:0: %v", err)
}
defer l.Close()
_, portStr, _ := net.SplitHostPort(l.Addr().String())
var port int
fmt.Sscanf(portStr, "%d", &port)
return port
}
func getClineDir(t *testing.T) string {
t.Helper()
clineDir := os.Getenv("CLINE_DIR")
if clineDir == "" {
t.Fatalf("CLINE_DIR not set")
}
return clineDir
}
// isPortInUse checks if a port is currently in use by any process
func isPortInUse(port int) bool {
conn, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return true // Port is in use
}
conn.Close()
return false // Port is free
}
// waitForPortClosed waits for a port to become free (no process listening)
func waitForPortClosed(t *testing.T, port int, timeout time.Duration) {
t.Helper()
waitFor(t, timeout, func() (bool, string) {
if isPortInUse(port) {
return false, fmt.Sprintf("port %d still in use", port)
}
return true, ""
})
}
// waitForPortsClosed waits for both core and host ports to become free
func waitForPortsClosed(t *testing.T, corePort, hostPort int, timeout time.Duration) {
t.Helper()
waitFor(t, timeout, func() (bool, string) {
if isPortInUse(corePort) {
return false, fmt.Sprintf("core port %d still in use", corePort)
}
if isPortInUse(hostPort) {
return false, fmt.Sprintf("host port %d still in use", hostPort)
}
return true, ""
})
}
// findAndKillHostProcess finds and kills any process listening on the host port
// This is used to clean up dangling host processes after SIGKILL tests
func findAndKillHostProcess(t *testing.T, hostPort int) {
t.Helper()
// Use lsof to find process listening on the host port
cmd := exec.Command("lsof", "-ti", fmt.Sprintf(":%d", hostPort))
output, err := cmd.Output()
if err != nil {
// No process found on port - that's fine
return
}
pidStr := strings.TrimSpace(string(output))
if pidStr == "" {
return
}
var pid int
if _, err := fmt.Sscanf(pidStr, "%d", &pid); err != nil {
t.Logf("Warning: could not parse PID from lsof output: %s", pidStr)
return
}
if pid > 0 {
t.Logf("Cleaning up dangling host process PID %d on port %d", pid, hostPort)
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
t.Logf("Warning: failed to kill dangling host process %d: %v", pid, err)
}
}
}
// getPIDByPort returns the PID of the process listening on the specified port (fallback method)
func getPIDByPort(t *testing.T, port int) int {
t.Helper()
cmd := exec.Command("lsof", "-ti", fmt.Sprintf(":%d", port))
output, err := cmd.Output()
if err != nil {
return 0 // Process not found
}
pidStr := strings.TrimSpace(string(output))
if pidStr == "" {
return 0
}
pid, err := strconv.Atoi(pidStr)
if err != nil {
t.Logf("Warning: could not parse PID from lsof output: %s", pidStr)
return 0
}
return pid
}
// getCorePIDViaRPC returns the PID of the cline-core process using RPC (preferred method)
func getCorePIDViaRPC(t *testing.T, address string) int {
t.Helper()
// Initialize global config to access registry
clineDir := os.Getenv("CLINE_DIR")
if clineDir == "" {
t.Logf("Warning: CLINE_DIR not set, falling back to lsof")
return getCorePIDViaLsof(t, address)
}
cfg := &global.GlobalConfig{
ConfigPath: clineDir,
}
if err := global.InitializeGlobalConfig(cfg); err != nil {
t.Logf("Warning: failed to initialize global config, falling back to lsof: %v", err)
return getCorePIDViaLsof(t, address)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Get client for the address
client, err := global.Clients.GetRegistry().GetClient(ctx, address)
if err != nil {
t.Logf("Warning: failed to get client for %s, falling back to lsof: %v", address, err)
return getCorePIDViaLsof(t, address)
}
// Call GetProcessInfo RPC
processInfo, err := client.State.GetProcessInfo(ctx, &cline.EmptyRequest{})
if err != nil {
t.Logf("Warning: GetProcessInfo RPC failed for %s, falling back to lsof: %v", address, err)
return getCorePIDViaLsof(t, address)
}
return int(processInfo.ProcessId)
}
// getCorePIDViaLsof returns the PID using lsof (fallback method)
func getCorePIDViaLsof(t *testing.T, address string) int {
t.Helper()
_, portStr, err := net.SplitHostPort(address)
if err != nil {
t.Logf("Warning: invalid address format %s", address)
return 0
}
port, err := strconv.Atoi(portStr)
if err != nil {
t.Logf("Warning: invalid port in address %s", address)
return 0
}
return getPIDByPort(t, port)
}
// getCorePID returns the PID of the cline-core process for the given address
// Uses RPC first, falls back to lsof if RPC fails
func getCorePID(t *testing.T, address string) int {
t.Helper()
// Try RPC first (preferred method)
if pid := getCorePIDViaRPC(t, address); pid > 0 {
return pid
}
// Fall back to lsof if RPC fails
return getCorePIDViaLsof(t, address)
}
// getHostPID returns the PID of the cline-host process for the given host port
func getHostPID(t *testing.T, hostPort int) int {
t.Helper()
return getPIDByPort(t, hostPort)
}
// contains reports whether slice has the target string.
func contains(slice []string, target string) bool {
for _, s := range slice {
if s == target {
return true
}
}
return false
}
+47
View File
@@ -0,0 +1,47 @@
package e2e
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// TestMain validates required artifacts exist before running E2E tests.
// It does NOT build artifacts. Build manually via:
//
// npm run compile-standalone
// npm run compile-cli
func TestMain(m *testing.M) {
// Determine repo root from cli/e2e
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "getwd: %v\n", err)
os.Exit(2)
}
repoRoot := filepath.Clean(filepath.Join(wd, "..", ".."))
cliBin := filepath.Join(repoRoot, "cli", "bin", "cline")
coreJS := filepath.Join(repoRoot, "dist-standalone", "cline-core.js")
missing := []string{}
if _, err := os.Stat(cliBin); err != nil {
missing = append(missing, cliBin)
}
if _, err := os.Stat(coreJS); err != nil {
missing = append(missing, coreJS)
}
if len(missing) > 0 {
if testing.Short() {
// Optional quality-of-life: allow skipping with -short when artifacts are absent
fmt.Fprintf(os.Stderr, "[e2e] skipping (-short) due to missing artifacts:\n %s\n", strings.Join(missing, "\n "))
os.Exit(0)
}
fmt.Fprintf(os.Stderr, "Missing required build artifacts for E2E tests:\n %s\n\nPlease build them first:\n npm run compile-standalone\n npm run compile-cli\n", strings.Join(missing, "\n "))
os.Exit(2)
}
os.Exit(m.Run())
}
+120
View File
@@ -0,0 +1,120 @@
package e2e
import (
"context"
"fmt"
"os"
"path/filepath"
"syscall"
"testing"
"github.com/cline/cli/pkg/common"
)
// 9. Mixed localhost vs 127.0.0.1 addresses coexist and are both healthy
func TestMixedLocalhostVs127Coexist(t *testing.T) {
clineDir := setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Start one instance
_ = mustRunCLI(ctx, t, "instance", "new")
// Get the running instance and its port/PID
out := listInstancesJSON(ctx, t)
if len(out.CoreInstances) == 0 {
t.Fatalf("expected at least 1 instance")
}
inst := out.CoreInstances[0]
waitForAddressHealthy(t, inst.Address, defaultTimeout)
// Manually add a SQLite entry for the same port but 127.0.0.1 host
addr127 := fmt.Sprintf("127.0.0.1:%d", inst.CorePort())
dbPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "locks.db")
if err := insertRemoteInstanceIntoSQLite(t, dbPath, addr127, inst.CorePort(), inst.HostPort()); err != nil {
t.Fatalf("insert 127 alias entry: %v", err)
}
// Verify both addresses appear and are healthy
waitForAddressHealthy(t, inst.Address, defaultTimeout)
waitForAddressHealthy(t, addr127, defaultTimeout)
out = listInstancesJSON(ctx, t)
if !hasAddress(out, inst.Address) || !hasAddress(out, addr127) {
t.Fatalf("expected both %s and %s present", inst.Address, addr127)
}
}
// 10. Start-stop stress: loop starting then killing instances; ensure no leftovers
func TestStartStopStress(t *testing.T) {
_ = setTempClineDir(t)
for i := 0; i < 3; i++ { // keep small for CI time
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Snapshot current addresses
before := listInstancesJSON(ctx, t)
beforeSet := map[string]struct{}{}
for _, it := range before.CoreInstances {
beforeSet[it.Address] = struct{}{}
}
// Start a new instance
_ = mustRunCLI(ctx, t, "instance", "new")
// Find the new instance address
var newAddr string
waitFor(t, defaultTimeout, func() (bool, string) {
after := listInstancesJSON(ctx, t)
for _, it := range after.CoreInstances {
if _, ok := beforeSet[it.Address]; !ok {
newAddr = it.Address
return true, ""
}
}
return false, "new instance address not detected yet"
})
// Wait healthy
waitForAddressHealthy(t, newAddr, defaultTimeout)
// Get PID using runtime discovery and kill it
after := listInstancesJSON(ctx, t)
info, ok := getByAddress(after, newAddr)
if !ok {
t.Fatalf("new instance %s missing", newAddr)
}
// Get PID using runtime discovery
corePID := getCorePID(t, info.Address)
if corePID <= 0 {
t.Fatalf("could not find PID for new instance at %s", info.Address)
}
t.Logf("Killing new instance %s (PID %d) for iteration %d", info.Address, corePID, i)
if err := syscall.Kill(corePID, syscall.SIGKILL); err != nil {
t.Fatalf("kill pid %d: %v", corePID, err)
}
// Wait removed from SQLite database
waitForAddressRemoved(t, newAddr, longTimeout)
// Verify instance is removed from SQLite database
clineDir := os.Getenv("CLINE_DIR")
if clineDir != "" {
dbPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "locks.db")
if verifyInstanceExistsInSQLite(t, dbPath, newAddr) {
t.Fatalf("expected instance removed from SQLite database: %s", newAddr)
}
}
// Clean up dangling host process (SIGKILL leaves these behind by design)
t.Logf("Cleaning up dangling host process on port %d for iteration %d", info.HostPort(), i)
findAndKillHostProcess(t, info.HostPort())
// Verify both ports are now free
waitForPortsClosed(t, info.CorePort(), info.HostPort(), defaultTimeout)
}
}
+161
View File
@@ -0,0 +1,161 @@
package e2e
import (
"database/sql"
"encoding/json"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/cline/cli/pkg/common"
_ "github.com/mattn/go-sqlite3"
"google.golang.org/grpc/health/grpc_health_v1"
)
// readInstancesFromSQLite reads instances directly from the SQLite database for testing
func readInstancesFromSQLite(t *testing.T, clineDir string) []common.CoreInstanceInfo {
t.Helper()
dbPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "locks.db")
// Check if database exists
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return []common.CoreInstanceInfo{}
}
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
t.Logf("Warning: Failed to open SQLite database: %v", err)
return []common.CoreInstanceInfo{}
}
defer db.Close()
// Query instance locks
query := common.SelectInstanceLockHoldersAscSQL
rows, err := db.Query(query)
if err != nil {
t.Logf("Warning: Failed to query instance locks: %v", err)
return []common.CoreInstanceInfo{}
}
defer rows.Close()
var instances []common.CoreInstanceInfo
for rows.Next() {
var heldBy, lockTarget string
var lockedAt int64
err := rows.Scan(&heldBy, &lockTarget, &lockedAt)
if err != nil {
t.Logf("Warning: Failed to scan lock row: %v", err)
continue
}
// Create InstanceInfo
info := common.CoreInstanceInfo{
Address: heldBy,
HostServiceAddress: lockTarget,
Status: grpc_health_v1.HealthCheckResponse_UNKNOWN, // Will be updated by health check
LastSeen: time.Unix(lockedAt/1000, 0), // Convert from milliseconds
}
instances = append(instances, info)
}
return instances
}
// readDefaultInstanceFromSettings reads the default instance from the settings file
func readDefaultInstanceFromSettings(t *testing.T, clineDir string) string {
t.Helper()
settingsPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
data, err := os.ReadFile(settingsPath)
if err != nil {
if os.IsNotExist(err) {
return ""
}
t.Logf("Warning: Failed to read default instance file: %v", err)
return ""
}
var tmp struct {
DefaultInstance string `json:"default_instance"`
}
if err := json.Unmarshal(data, &tmp); err != nil {
t.Logf("Warning: Failed to parse default instance file: %v", err)
return ""
}
return tmp.DefaultInstance
}
// insertRemoteInstanceIntoSQLite inserts a remote instance entry directly into SQLite for testing
func insertRemoteInstanceIntoSQLite(t *testing.T, dbPath, address string, corePort, hostPort int) error {
t.Helper()
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return err
}
defer db.Close()
// Initialize database schema for testing
createTableSQL := `
CREATE TABLE IF NOT EXISTS locks (
id INTEGER PRIMARY KEY,
held_by TEXT NOT NULL,
lock_type TEXT NOT NULL CHECK (lock_type IN ('file', 'instance', 'folder')),
lock_target TEXT NOT NULL,
locked_at INTEGER NOT NULL,
UNIQUE(lock_type, lock_target)
);
`
createIndexesSQL := `
CREATE INDEX IF NOT EXISTS idx_locks_held_by ON locks(held_by);
CREATE INDEX IF NOT EXISTS idx_locks_type ON locks(lock_type);
CREATE INDEX IF NOT EXISTS idx_locks_target ON locks(lock_target);
`
if _, err := db.Exec(createTableSQL); err != nil {
return err
}
if _, err := db.Exec(createIndexesSQL); err != nil {
return err
}
// Insert the remote instance
hostAddress := "remote.example.com:0"
if hostPort != 0 {
hostAddress = "remote.example.com:" + strconv.Itoa(hostPort)
}
insertSQL := `INSERT INTO locks (held_by, lock_type, lock_target, locked_at) VALUES (?, 'instance', ?, ?)`
_, err = db.Exec(insertSQL, address, hostAddress, time.Now().Unix()*1000)
return err
}
// verifyInstanceExistsInSQLite checks if an instance exists in the SQLite database
func verifyInstanceExistsInSQLite(t *testing.T, dbPath, address string) bool {
t.Helper()
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
t.Logf("Failed to open database: %v", err)
return false
}
defer db.Close()
query := `SELECT COUNT(*) FROM locks WHERE held_by = ? AND lock_type = 'instance'`
var count int
err = db.QueryRow(query, address).Scan(&count)
if err != nil {
t.Logf("Failed to query database: %v", err)
return false
}
return count > 0
}
+178
View File
@@ -0,0 +1,178 @@
package e2e
import (
"context"
"fmt"
"syscall"
"testing"
)
// TestStartAndList verifies self-registration and default.json semantics in a fresh CLINE_DIR.
func TestStartAndList(t *testing.T) {
clineDir := setTempClineDir(t)
t.Logf("Using temp CLINE_DIR: %s", clineDir)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
t.Logf("Starting new instance...")
// Start a new instance
startOutput := mustRunCLI(ctx, t, "instance", "new")
t.Logf("Instance start output: %s", startOutput)
t.Logf("Listing instances to check registration...")
// It should appear healthy in list JSON and be the default.
out := listInstancesJSON(ctx, t)
t.Logf("Found %d instances after start", len(out.CoreInstances))
if len(out.CoreInstances) != 1 {
t.Fatalf("expected 1 instance, got %d", len(out.CoreInstances))
}
addr := out.CoreInstances[0].Address
t.Logf("Instance address: %s, status: %s", addr, out.CoreInstances[0].Status)
t.Logf("Waiting for address %s to become healthy...", addr)
waitForAddressHealthy(t, addr, defaultTimeout)
t.Logf("Address %s is now healthy", addr)
t.Logf("Checking default instance configuration...")
// Default should be set to the new instance.
out = listInstancesJSON(ctx, t)
t.Logf("Default instance: %s", out.DefaultInstance)
if out.DefaultInstance == "" {
t.Fatalf("default_instance not set")
}
if out.DefaultInstance != out.CoreInstances[0].Address {
t.Fatalf("expected default_instance=%s, got %s", out.CoreInstances[0].Address, out.DefaultInstance)
}
t.Logf("TestStartAndList completed successfully")
}
// TestTaskNewDefault ensures tasks route to default instance.
func TestTaskNewDefault(t *testing.T) {
_ = setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Start one instance and wait for healthy
_ = mustRunCLI(ctx, t, "instance", "new")
out := listInstancesJSON(ctx, t)
if len(out.CoreInstances) != 1 {
t.Fatalf("expected 1 instance, got %d", len(out.CoreInstances))
}
addr := out.CoreInstances[0].Address
waitForAddressHealthy(t, addr, defaultTimeout)
// Create a new task at default (success is sufficient)
_ = mustRunCLI(ctx, t, "task", "new", "hello world")
}
// TestExplicitAddressAutoStart verifies that giving an explicit address auto-starts an instance and routes the task.
func TestExplicitAddressAutoStart(t *testing.T) {
_ = setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Find a free port and use explicit address. This should auto-start an instance.
port := findFreePort(t)
addr := "localhost:" + itoa(port)
// Run a task at explicit address (auto-start path)
_ = mustRunCLI(ctx, t, "task", "new", "--address", "localhost:"+itoa(port), "explicit address task")
// Verify the instance is present and healthy
waitForAddressHealthy(t, addr, defaultTimeout)
}
// TestCrashCleanup verifies that after SIGKILL of a local core, the cleanup removes the registry entry.
// Also tests graceful shutdown (SIGTERM) vs crash cleanup and ensures no dangling host processes.
func TestCrashCleanup(t *testing.T) {
_ = setTempClineDir(t)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout)
defer cancel()
// Start two instances for testing both graceful and crash scenarios
_ = mustRunCLI(ctx, t, "instance", "new")
_ = mustRunCLI(ctx, t, "instance", "new")
out := listInstancesJSON(ctx, t)
if len(out.CoreInstances) < 2 {
t.Fatalf("expected at least 2 instances, got %d", len(out.CoreInstances))
}
// Test 1: Graceful shutdown (SIGTERM) - should clean up both processes
gracefulTarget := out.CoreInstances[0]
waitForAddressHealthy(t, gracefulTarget.Address, defaultTimeout)
// Get PID using runtime discovery
gracefulPID := getCorePID(t, gracefulTarget.Address)
if gracefulPID <= 0 {
t.Fatalf("could not find PID for graceful target at %s", gracefulTarget.Address)
}
t.Logf("Testing graceful shutdown (SIGTERM) for instance %s (PID %d)", gracefulTarget.Address, gracefulPID)
if err := syscall.Kill(gracefulPID, syscall.SIGTERM); err != nil {
t.Fatalf("kill SIGTERM pid %d: %v", gracefulPID, err)
}
// Wait for registry cleanup
waitForAddressRemoved(t, gracefulTarget.Address, longTimeout)
// Verify both core and host ports are freed (no dangling processes)
waitForPortsClosed(t, gracefulTarget.CorePort(), gracefulTarget.HostPort(), defaultTimeout)
// Verify the instance is removed from SQLite (no file to check anymore)
// The waitForAddressRemoved already confirms the instance is gone from the registry
// Test 2: Crash cleanup (SIGKILL) - creates dangling host process that we must clean up
crashTarget := out.CoreInstances[1]
waitForAddressHealthy(t, crashTarget.Address, defaultTimeout)
// Get PID using runtime discovery
crashPID := getCorePID(t, crashTarget.Address)
if crashPID <= 0 {
t.Fatalf("could not find PID for crash target at %s", crashTarget.Address)
}
t.Logf("Testing crash cleanup (SIGKILL) for instance %s (PID %d)", crashTarget.Address, crashPID)
if err := syscall.Kill(crashPID, syscall.SIGKILL); err != nil {
t.Fatalf("kill SIGKILL pid %d: %v", crashPID, err)
}
// Wait for registry cleanup
waitForAddressRemoved(t, crashTarget.Address, longTimeout)
// Verify the instance is removed from SQLite (no file to check anymore)
// The waitForAddressRemoved already confirms the instance is gone from the registry
// Clean up dangling host process (SIGKILL leaves these behind by design)
t.Logf("Cleaning up dangling host process %s", crashTarget.HostServiceAddress)
findAndKillHostProcess(t, crashTarget.HostPort())
// Verify both ports are now free
waitForPortsClosed(t, crashTarget.CorePort(), crashTarget.HostPort(), defaultTimeout)
}
// itoa is a small helper for readability
func itoa(i int) string {
return strconvItoa(i)
}
// minimal inline int->string to avoid extra imports in helpers
func strconvItoa(i int) string {
// simple fast path
return fmtInt(i)
}
func fmtInt(i int) string {
// allocate small buffer; ints here are short
return (func(n int) string {
return fmt.Sprintf("%d", n)
})(i)
}
+22
View File
@@ -0,0 +1,22 @@
module github.com/cline/cli
go 1.23.0
require (
github.com/cline/grpc-go v0.0.0
github.com/mattn/go-sqlite3 v1.14.24
github.com/spf13/cobra v1.8.0
google.golang.org/grpc v1.75.0
)
replace github.com/cline/grpc-go => ../src/generated/grpc-go
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect
google.golang.org/protobuf v1.36.6 // indirect
)
+48
View File
@@ -0,0 +1,48 @@
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc=
go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+125
View File
@@ -0,0 +1,125 @@
package cli
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/grpc-go/cline"
"github.com/spf13/cobra"
)
var isSessionAuthenticated bool
func NewAuthCommand() *cobra.Command {
return &cobra.Command{
Use: "auth",
Short: "Sign in to Cline",
Long: `Complete the authentication flow in browser to sign in to Cline.`,
RunE: func(cmd *cobra.Command, args []string) error {
return handleAuthCommand(cmd.Context())
},
}
}
func handleAuthCommand(ctx context.Context) error {
fmt.Print("Authenticating with Cline...\n")
if IsAuthenticated(ctx) {
return signOutDialog(ctx)
}
if err := signIn(ctx); err != nil {
return err
}
fmt.Println("You are signed in!")
return nil
}
func signOut(ctx context.Context) error {
client, err := global.GetDefaultClient(ctx)
if err != nil {
return err
}
if _, err = client.Account.AccountLogoutClicked(ctx, &cline.EmptyRequest{}); err != nil {
return err
}
isSessionAuthenticated = false
fmt.Println("You have been signed out of Cline.")
return nil
}
func signOutDialog(ctx context.Context) error {
fmt.Print("You are already signed in to Cline.\nWould you like to sign out? (y/N): ")
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
return nil
}
response := strings.ToLower(strings.TrimSpace(scanner.Text()))
if response == "y" || response == "yes" {
if err := signOut(ctx); err != nil {
fmt.Printf("Failed to sign out: %v\n", err)
return err
}
}
return nil
}
func signIn(ctx context.Context) error {
if IsAuthenticated(ctx) {
return nil
}
verboseLog("Ensuring default instance exists...")
if err := ensureDefaultInstance(ctx); err != nil {
verboseLog("Failed to ensure default instance: %v", err)
return err
}
verboseLog("Default instance ensured successfully.")
time.Sleep(2 * time.Second) // Allow services to start
client, err := global.GetDefaultClient(ctx)
if err != nil {
verboseLog("Failed to obtain client: %v", err)
return err
}
_, err = client.Account.AccountLoginClicked(ctx, &cline.EmptyRequest{})
if err != nil {
verboseLog("Failed to login: %v", err)
return err
}
isSessionAuthenticated = true
verboseLog("Login successful")
return nil
}
func IsAuthenticated(ctx context.Context) bool {
if isSessionAuthenticated {
return true
}
client, err := global.GetDefaultClient(ctx)
if err != nil {
return false
}
_, err = client.Account.GetUserCredits(ctx, &cline.EmptyRequest{})
return err == nil
}
func verboseLog(format string, args ...interface{}) {
if global.Config != nil && global.Config.Verbose {
fmt.Printf("[VERBOSE] "+format+"\n", args...)
}
}
+95
View File
@@ -0,0 +1,95 @@
package display
import (
"crypto/md5"
"fmt"
"sync"
"time"
"github.com/cline/cli/pkg/cli/types"
)
// MessageDeduplicator handles message deduplication to prevent duplicate displays
type MessageDeduplicator struct {
mu sync.RWMutex
seenMessages map[string]time.Time
maxAge time.Duration
cleanupTicker *time.Ticker
}
// NewMessageDeduplicator creates a new message deduplicator
func NewMessageDeduplicator() *MessageDeduplicator {
d := &MessageDeduplicator{
seenMessages: make(map[string]time.Time),
maxAge: 5 * time.Minute, // Keep messages for 5 minutes
cleanupTicker: time.NewTicker(1 * time.Minute), // Cleanup every minute
}
// Start cleanup goroutine
go d.cleanup()
return d
}
// IsDuplicate checks if a message is a duplicate
func (d *MessageDeduplicator) IsDuplicate(msg *types.ClineMessage) bool {
d.mu.Lock()
defer d.mu.Unlock()
// Create a hash of the message content
hash := d.hashMessage(msg)
// Check if we've seen this message recently
if lastSeen, exists := d.seenMessages[hash]; exists {
// If we've seen it within the last few seconds, it's a duplicate
if time.Since(lastSeen) < 2*time.Second {
return true
}
}
// Mark this message as seen
d.seenMessages[hash] = time.Now()
return false
}
// hashMessage creates a hash of the message for deduplication
func (d *MessageDeduplicator) hashMessage(msg *types.ClineMessage) string {
// Create a hash based on message content, type, and timestamp
content := fmt.Sprintf("%s|%s|%s|%d",
string(msg.Type),
msg.Say,
msg.Ask,
msg.Timestamp)
// For partial messages, include the text content in the hash
if msg.Partial {
content += "|" + msg.Text
}
hash := md5.Sum([]byte(content))
return fmt.Sprintf("%x", hash)
}
// cleanup removes old entries from the seen messages map
func (d *MessageDeduplicator) cleanup() {
for range d.cleanupTicker.C {
d.mu.Lock()
now := time.Now()
// Remove entries older than maxAge
for hash, timestamp := range d.seenMessages {
if now.Sub(timestamp) > d.maxAge {
delete(d.seenMessages, hash)
}
}
d.mu.Unlock()
}
}
// Stop stops the cleanup goroutine
func (d *MessageDeduplicator) Stop() {
if d.cleanupTicker != nil {
d.cleanupTicker.Stop()
}
}
+176
View File
@@ -0,0 +1,176 @@
package display
import (
"fmt"
"strings"
"time"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/grpc-go/cline"
)
type Renderer struct {
typewriter *TypewriterPrinter
}
func NewRenderer() *Renderer {
return &Renderer{
typewriter: NewTypewriterPrinter(DefaultTypewriterConfig()),
}
}
// RenderMessage renders a message with timestamp and prefix
func (r *Renderer) RenderMessage(timestamp, prefix, text string) error {
if text == "" {
return nil
}
cleanText := r.sanitizeText(text)
if cleanText == "" {
return nil
}
r.typewriter.PrintMessageLine(timestamp, prefix, cleanText)
return nil
}
// RenderCommand renders a command execution
func (r *Renderer) RenderCommand(timestamp, command string, isExecuting bool) error {
if isExecuting {
r.typewriter.PrintMessageLine(timestamp, "EXEC", command)
} else {
r.typewriter.PrintMessageLine(timestamp, "CMD", command)
}
return nil
}
// formatNumber formats numbers with k/m abbreviations
func formatNumber(n int) string {
if n >= 1000000 {
return fmt.Sprintf("%.1fm", float64(n)/1000000.0)
} else if n >= 1000 {
return fmt.Sprintf("%.1fk", float64(n)/1000.0)
}
return fmt.Sprintf("%d", n)
}
// formatUsageInfo formats token usage information (extracted from RenderAPI)
func (r *Renderer) formatUsageInfo(tokensIn, tokensOut, cacheReads, cacheWrites int, cost float64) string {
tokenDetails := fmt.Sprintf("[tokens in: %s, out: %s; cache read: %s, write: %s]",
formatNumber(tokensIn),
formatNumber(tokensOut),
formatNumber(cacheReads),
formatNumber(cacheWrites))
return fmt.Sprintf("%s ($%.4f)", tokenDetails, cost)
}
// RenderAPI renders API request information
func (r *Renderer) RenderAPI(timestamp, status string, apiInfo *types.APIRequestInfo) error {
if apiInfo.Cost >= 0 {
message := fmt.Sprintf("%s %s", status, r.formatUsageInfo(apiInfo.TokensIn, apiInfo.TokensOut, apiInfo.CacheReads, apiInfo.CacheWrites, apiInfo.Cost))
r.typewriter.PrintMessageLine(timestamp, "API INFO", message)
} else {
r.typewriter.PrintMessageLine(timestamp, "API INFO", status)
}
return nil
}
// RenderRetry renders retry information
func (r *Renderer) RenderRetry(timestamp string, attempt, maxAttempts, delaySec int) error {
message := fmt.Sprintf("Retrying failed attempt %d/%d", attempt, maxAttempts)
if delaySec > 0 {
message += fmt.Sprintf(" in %d seconds", delaySec)
}
message += "..."
r.typewriter.PrintMessageLine(timestamp, "API INFO", message)
return nil
}
// RenderTaskList displays task history with improved formatting
func (r *Renderer) RenderTaskList(tasks []*cline.TaskItem) error {
const maxTasks = 20
startIndex := 0
if len(tasks) > maxTasks {
startIndex = len(tasks) - maxTasks
}
recentTasks := tasks[startIndex:]
r.typewriter.PrintfLn("=== Task History (showing last %d of %d total tasks) ===\n", len(recentTasks), len(tasks))
for i, task := range recentTasks {
r.typewriter.PrintfLn("Task ID: %s", task.Id)
description := task.Task
if len(description) > 1000 {
description = description[:1000] + "..."
}
r.typewriter.PrintfLn("Message: %s", description)
usageInfo := r.formatUsageInfo(int(task.TokensIn), int(task.TokensOut), int(task.CacheReads), int(task.CacheWrites), task.TotalCost)
r.typewriter.PrintfLn("Usage : %s", usageInfo)
// Single space between tasks (except last)
if i < len(recentTasks)-1 {
r.typewriter.PrintfLn("")
}
}
return nil
}
func (r *Renderer) RenderDebug(format string, args ...interface{}) error {
if global.Config.Verbose {
timestamp := time.Now().Format("15:04:05")
message := fmt.Sprintf(format, args...)
r.typewriter.PrintMessageLine(timestamp, "[DEBUG]", message)
}
return nil
}
func (r *Renderer) ClearLine() {
fmt.Print("\r\033[K")
}
func (r *Renderer) MoveCursorUp(n int) {
fmt.Printf("\033[%dA", n)
}
func (r *Renderer) sanitizeText(text string) string {
text = strings.TrimSpace(text)
if text == "" {
return ""
}
// Remove control characters and escape sequences
var result strings.Builder
for _, r := range text {
// Keep printable characters, spaces, tabs, and newlines
if r >= 32 || r == '\t' || r == '\n' || r == '\r' {
result.WriteRune(r)
}
// Skip control characters (0-31 except tab, newline, carriage return)
}
return result.String()
}
func (r *Renderer) SetTypewriterEnabled(enabled bool) {
r.typewriter.SetEnabled(enabled)
}
func (r *Renderer) IsTypewriterEnabled() bool {
return r.typewriter.IsEnabled()
}
func (r *Renderer) SetTypewriterSpeed(multiplier float64) {
r.typewriter.SetSpeed(multiplier)
}
func (r *Renderer) GetTypewriter() *TypewriterPrinter {
return r.typewriter
}
+449
View File
@@ -0,0 +1,449 @@
package display
import (
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/cline/cli/pkg/cli/types"
)
// StreamingDisplay manages streaming message display with deduplication
type StreamingDisplay struct {
mu sync.RWMutex
state *types.ConversationState
renderer *Renderer
dedupe *MessageDeduplicator
}
// NewStreamingDisplay creates a new streaming display manager
func NewStreamingDisplay(state *types.ConversationState, renderer *Renderer) *StreamingDisplay {
return &StreamingDisplay{
state: state,
renderer: renderer,
dedupe: NewMessageDeduplicator(),
}
}
// HandlePartialMessage processes partial messages with streaming support
func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
s.mu.Lock()
defer s.mu.Unlock()
messageKey := fmt.Sprintf("%d", msg.Timestamp)
timestamp := msg.GetTimestamp()
// Check for deduplication
if s.dedupe.IsDuplicate(msg) {
return nil
}
// Get current streaming state
streamingMsg := s.state.GetStreamingMessage()
switch msg.Type {
case types.MessageTypeAsk:
return s.handleStreamingAsk(msg, messageKey, timestamp, streamingMsg)
case types.MessageTypeSay:
return s.handleStreamingSay(msg, messageKey, timestamp, streamingMsg)
default:
return s.renderer.RenderMessage(timestamp, "🤖", msg.Text)
}
}
// handleStreamingAsk handles streaming ASK messages
func (s *StreamingDisplay) handleStreamingAsk(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
if msg.Text == "" {
return nil
}
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
// Check if this is an update to the same ASK message
if streamingMsg.CurrentKey == messageKey {
// This is an update to the same ASK message - stream the changes
if cleanText != streamingMsg.LastText {
s.streamAskMessageUpdate(cleanText, streamingMsg.LastText, timestamp)
s.state.SetStreamingMessage(messageKey, cleanText)
}
} else {
// This is a new ASK message
s.finishCurrentStream()
s.streamAskMessage(cleanText, timestamp, true)
s.state.SetStreamingMessage(messageKey, cleanText)
}
return nil
}
// handleStreamingSay handles streaming SAY messages
func (s *StreamingDisplay) handleStreamingSay(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
switch msg.Say {
case string(types.SayTypeText), string(types.SayTypeCompletionResult):
return s.handleStreamingText(msg, messageKey, timestamp, streamingMsg)
case string(types.SayTypeCommand):
return s.handleStreamingCommand(msg, messageKey, timestamp, streamingMsg)
case string(types.SayTypeCommandOutput):
return s.handleStreamingCommandOutput(msg, messageKey, timestamp, streamingMsg)
case string(types.SayTypeTool):
return s.handleStreamingTool(msg, messageKey, timestamp, streamingMsg)
case string(types.SayTypeShellIntegrationWarning):
return s.handleShellIntegrationWarning(msg, messageKey, timestamp, streamingMsg)
default:
// For non-streaming message types, use regular display
return s.renderer.RenderMessage(timestamp, s.getMessagePrefix(msg.Say), msg.Text)
}
}
// handleStreamingText handles streaming text messages
func (s *StreamingDisplay) handleStreamingText(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
// Check if we've already displayed this exact message
if streamingMsg.CurrentKey == messageKey && streamingMsg.LastText == cleanText {
return nil // Duplicate - ignore it
}
// Check if this is an update to the same message
if streamingMsg.CurrentKey == messageKey {
// Show incremental changes
if len(cleanText) > len(streamingMsg.LastText) && strings.HasPrefix(cleanText, streamingMsg.LastText) {
// Show only the new characters with typewriter effect
newChars := cleanText[len(streamingMsg.LastText):]
s.typewriterPrint(newChars)
s.state.SetStreamingMessage(messageKey, cleanText)
} else {
// Text changed in a non-incremental way - replace the line
s.renderer.ClearLine()
prefix := s.getMessagePrefix(msg.Say)
s.renderer.typewriter.PrintfInstant("[%s] %s: ", timestamp, prefix)
s.typewriterPrint(cleanText)
s.state.SetStreamingMessage(messageKey, cleanText)
}
} else {
// This is a new message
s.finishCurrentStream()
prefix := s.getMessagePrefix(msg.Say)
s.renderer.typewriter.PrintfInstant("[%s] %s: ", timestamp, prefix)
// Add typewriter animation for new messages
s.typewriterPrint(cleanText)
s.state.SetStreamingMessage(messageKey, cleanText)
}
// If message is complete, add newline
if !msg.Partial {
fmt.Println()
s.state.SetStreamingMessage("", "")
}
return nil
}
// handleStreamingCommand handles command execution messages
func (s *StreamingDisplay) handleStreamingCommand(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
// Show command being executed with typewriter effect
s.finishCurrentStream()
s.renderer.typewriter.PrintfInstant("[%s] 🖥️ CMD: ", timestamp)
s.typewriterPrint(cleanText)
fmt.Println()
return nil
}
// handleStreamingCommandOutput handles streaming command output
func (s *StreamingDisplay) handleStreamingCommandOutput(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
// Check if we've already displayed this exact message
if streamingMsg.CurrentKey == messageKey && streamingMsg.LastText == cleanText {
return nil
}
// Check if this is an update to the same message
if streamingMsg.CurrentKey == messageKey {
// Show incremental changes with typewriter effect
if len(cleanText) > len(streamingMsg.LastText) && strings.HasPrefix(cleanText, streamingMsg.LastText) {
newChars := cleanText[len(streamingMsg.LastText):]
s.typewriterPrint(newChars)
s.state.SetStreamingMessage(messageKey, cleanText)
} else {
// Non-incremental change - replace the line
s.renderer.ClearLine()
s.renderer.typewriter.PrintfInstant("[%s] 🖥️ OUT: ", timestamp)
s.typewriterPrint(cleanText)
s.state.SetStreamingMessage(messageKey, cleanText)
}
} else {
// New command output message
s.finishCurrentStream()
s.renderer.typewriter.PrintfInstant("[%s] 🖥️ OUT: ", timestamp)
s.typewriterPrint(cleanText)
s.state.SetStreamingMessage(messageKey, cleanText)
}
// If message is complete, add newline
if !msg.Partial {
fmt.Println()
s.state.SetStreamingMessage("", "")
}
return nil
}
// handleShellIntegrationWarning handles shell integration warning messages
func (s *StreamingDisplay) handleShellIntegrationWarning(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
// Show a more concise shell integration warning
s.finishCurrentStream()
s.renderer.typewriter.PrintfInstant("[%s] ️ NOTE: ", timestamp)
s.typewriterPrint("Command executed (output not streamed due to shell integration)")
fmt.Println()
return nil
}
// handleStreamingTool handles streaming tool messages with deduplication
func (s *StreamingDisplay) handleStreamingTool(msg *types.ClineMessage, messageKey, timestamp string, streamingMsg *types.StreamingMessage) error {
cleanText := s.renderer.sanitizeText(msg.Text)
if cleanText == "" {
return nil
}
formattedTool := s.formatToolMessage(cleanText)
// Check if this is the exact same tool message we just displayed
if streamingMsg.LastToolMessage == formattedTool {
return nil // Exact duplicate - ignore it
}
// Check if this is a very similar tool message
if streamingMsg.LastToolMessage != "" && s.isSimilarToolMessage(streamingMsg.LastToolMessage, formattedTool) {
return nil // Similar duplicate - ignore it
}
// This is a genuinely new/different tool message
s.finishCurrentStream()
fmt.Printf("[%s] 🔧 TOOL: %s\n", timestamp, formattedTool)
// Store the formatted tool message for deduplication
s.state.StreamingMessage.LastToolMessage = formattedTool
return nil
}
// streamAskMessage streams an ASK message in a natural format
func (s *StreamingDisplay) streamAskMessage(text, timestamp string, isNew bool) {
// Try to parse as JSON
var askData types.AskData
if err := s.parseJSON(text, &askData); err != nil {
// Display as text but sanitized
fmt.Printf("[%s] 🤖 ASK: %s", timestamp, text)
return
}
fmt.Printf("[%s] 🤖 ASK: %s", timestamp, askData.Response)
// Display options if available
if len(askData.Options) > 0 {
fmt.Print("\n\nOptions:")
for i, option := range askData.Options {
fmt.Printf("\n%d. %s", i+1, option)
}
}
}
// streamAskMessageUpdate handles updates to an existing ASK message
func (s *StreamingDisplay) streamAskMessageUpdate(newText, oldText, timestamp string) {
var oldAskData, newAskData types.AskData
oldErr := s.parseJSON(oldText, &oldAskData)
newErr := s.parseJSON(newText, &newAskData)
if oldErr != nil || newErr != nil {
// Handle plain text incremental updates
if len(newText) > len(oldText) && strings.HasPrefix(newText, oldText) {
newChars := newText[len(oldText):]
fmt.Print(newChars)
} else {
// Non-incremental change - clear line and reprint everything
s.renderer.ClearLine()
fmt.Printf("[%s] 🤖 ASK: %s", timestamp, newText)
}
return
}
// Handle structured updates
if len(newAskData.Response) > len(oldAskData.Response) && strings.HasPrefix(newAskData.Response, oldAskData.Response) {
newChars := newAskData.Response[len(oldAskData.Response):]
fmt.Print(newChars)
} else if oldAskData.Response != newAskData.Response {
s.renderer.ClearLine()
fmt.Printf("[%s] 🤖 ASK: %s", timestamp, newAskData.Response)
}
// Handle options changes
if len(newAskData.Options) > len(oldAskData.Options) {
if len(oldAskData.Options) == 0 {
fmt.Print("\n\nOptions:")
}
for i := len(oldAskData.Options); i < len(newAskData.Options); i++ {
fmt.Printf("\n%d. %s", i+1, newAskData.Options[i])
}
}
}
// typewriterPrint displays text with a typewriter animation effect
func (s *StreamingDisplay) typewriterPrint(text string) {
// Use the renderer's typewriter for consistent animation
s.renderer.typewriter.Print(text)
}
// finishCurrentStream completes any ongoing streaming message
func (s *StreamingDisplay) finishCurrentStream() {
streamingMsg := s.state.GetStreamingMessage()
if streamingMsg.CurrentKey != "" {
//fmt.Println() // Add newline to finish the current streaming message
s.state.SetStreamingMessage("", "")
}
}
// getMessagePrefix returns the appropriate prefix for a message type
func (s *StreamingDisplay) getMessagePrefix(say string) string {
switch say {
case string(types.SayTypeCompletionResult):
return "✅ RESULT"
case string(types.SayTypeText):
return "🤖"
default:
return "🤖"
}
}
// formatToolMessage formats tool call messages for better readability
func (s *StreamingDisplay) formatToolMessage(text string) string {
var toolCall map[string]interface{}
if err := s.parseJSON(text, &toolCall); err == nil {
if tool, ok := toolCall["tool"].(string); ok {
parts := []string{tool}
if path, ok := toolCall["path"].(string); ok && path != "" {
parts = append(parts, fmt.Sprintf("path=%s", path))
}
if content, ok := toolCall["content"].(string); ok && content != "" {
if len(content) > 50 {
parts = append(parts, fmt.Sprintf("content=%s...", content[:50]))
} else {
parts = append(parts, fmt.Sprintf("content=%s", content))
}
}
return strings.Join(parts, " ")
}
}
// If not JSON or doesn't have expected structure, return truncated
if len(text) > 100 {
return text[:100] + "..."
}
return text
}
// isSimilarToolMessage checks if two tool messages are similar enough to be considered duplicates
func (s *StreamingDisplay) isSimilarToolMessage(msg1, msg2 string) bool {
parts1 := strings.Fields(msg1)
parts2 := strings.Fields(msg2)
if len(parts1) == 0 || len(parts2) == 0 {
return false
}
// If the first word (tool name) is the same, check for similarity
if parts1[0] == parts2[0] {
// For file operations, check if the path is the same
if strings.Contains(msg1, "path=") && strings.Contains(msg2, "path=") {
path1 := s.extractPathFromToolMessage(msg1)
path2 := s.extractPathFromToolMessage(msg2)
if path1 != "" && path1 == path2 {
return true
}
}
// For very similar content (>80% similarity), consider them duplicates
similarity := s.calculateStringSimilarity(msg1, msg2)
return similarity > 0.8
}
return false
}
// extractPathFromToolMessage extracts the path parameter from a tool message
func (s *StreamingDisplay) extractPathFromToolMessage(msg string) string {
parts := strings.Fields(msg)
for _, part := range parts {
if strings.HasPrefix(part, "path=") {
return strings.TrimPrefix(part, "path=")
}
}
return ""
}
// calculateStringSimilarity calculates a simple similarity ratio between two strings
func (s *StreamingDisplay) calculateStringSimilarity(s1, s2 string) float64 {
if s1 == s2 {
return 1.0
}
if len(s1) == 0 || len(s2) == 0 {
return 0.0
}
shorter, longer := s1, s2
if len(s1) > len(s2) {
shorter, longer = s2, s1
}
matches := 0
for i, r := range shorter {
if i < len(longer) && rune(longer[i]) == r {
matches++
}
}
return float64(matches) / float64(len(longer))
}
// parseJSON is a helper function to parse JSON with error handling
func (s *StreamingDisplay) parseJSON(text string, v interface{}) error {
return json.Unmarshal([]byte(text), v)
}
// Cleanup cleans up streaming display resources
func (s *StreamingDisplay) Cleanup() {
if s.dedupe != nil {
s.dedupe.Stop()
}
}
+214
View File
@@ -0,0 +1,214 @@
package display
import (
"fmt"
"os"
"time"
)
// TypewriterConfig holds configuration for the typewriter effect
type TypewriterConfig struct {
BaseDelay time.Duration // Base delay between characters
FastDelay time.Duration // Faster delay for common characters
SlowDelay time.Duration // Slower delay for punctuation
PauseDelay time.Duration // Pause after sentences
Enabled bool // Whether typewriter effect is enabled
RandomFactor float64 // Randomness factor (0.0 to 1.0)
}
// DefaultTypewriterConfig returns the default typewriter configuration
func DefaultTypewriterConfig() *TypewriterConfig {
return &TypewriterConfig{
BaseDelay: 15 * time.Millisecond,
FastDelay: 8 * time.Millisecond,
SlowDelay: 25 * time.Millisecond,
PauseDelay: 150 * time.Millisecond,
Enabled: false,
RandomFactor: 0.3,
}
}
// TypewriterPrinter handles typewriter-style output
type TypewriterPrinter struct {
config *TypewriterConfig
}
// NewTypewriterPrinter creates a new typewriter printer
func NewTypewriterPrinter(config *TypewriterConfig) *TypewriterPrinter {
if config == nil {
config = DefaultTypewriterConfig()
}
return &TypewriterPrinter{
config: config,
}
}
// Print prints text with typewriter effect
func (tp *TypewriterPrinter) Print(text string) {
if !tp.config.Enabled {
fmt.Print(text)
return
}
tp.typewriterPrint(text)
}
// Printf prints formatted text with typewriter effect
func (tp *TypewriterPrinter) Printf(format string, args ...interface{}) {
text := fmt.Sprintf(format, args...)
tp.Print(text)
}
// Println prints text with typewriter effect and adds a newline
func (tp *TypewriterPrinter) Println(text string) {
tp.Print(text + "\n")
}
// PrintfLn prints formatted text with typewriter effect and adds a newline
func (tp *TypewriterPrinter) PrintfLn(format string, args ...interface{}) {
text := fmt.Sprintf(format, args...)
tp.Println(text)
}
// PrintInstant prints text immediately without typewriter effect
func (tp *TypewriterPrinter) PrintInstant(text string) {
fmt.Print(text)
}
// PrintfInstant prints formatted text immediately without typewriter effect
func (tp *TypewriterPrinter) PrintfInstant(format string, args ...interface{}) {
fmt.Printf(format, args...)
}
// typewriterPrint displays text with a typewriter animation effect
func (tp *TypewriterPrinter) typewriterPrint(text string) {
// Convert string to runes to handle Unicode properly
runes := []rune(text)
for i, r := range runes {
// Print the character
fmt.Print(string(r))
os.Stdout.Sync() // Force immediate output
// Don't add delay after the last character
if i == len(runes)-1 {
break
}
// Determine delay based on character type
delay := tp.getDelayForCharacter(r, i)
// Sleep for the calculated delay
time.Sleep(delay)
}
}
// getDelayForCharacter returns the appropriate delay for a character
func (tp *TypewriterPrinter) getDelayForCharacter(r rune, position int) time.Duration {
var baseDelay time.Duration
switch {
case r == '.' || r == '!' || r == '?':
// Longer pause after sentence endings
baseDelay = tp.config.PauseDelay
case r == ',' || r == ';' || r == ':':
// Medium pause after punctuation
baseDelay = tp.config.SlowDelay
case r == ' ':
// Slightly faster for spaces
baseDelay = tp.config.FastDelay
case r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z':
// Fast for common letters
baseDelay = tp.config.FastDelay
case r == '\n':
// No delay for newlines
return 0
default:
// Base delay for other characters
baseDelay = tp.config.BaseDelay
}
// Add randomness to make it feel more natural
if tp.config.RandomFactor > 0 {
// Simple pseudo-random based on position to ensure consistency
randomFactor := 0.7 + (tp.config.RandomFactor * float64(position%7) / 6.0)
baseDelay = time.Duration(float64(baseDelay) * randomFactor)
}
return baseDelay
}
// SetEnabled enables or disables the typewriter effect
func (tp *TypewriterPrinter) SetEnabled(enabled bool) {
tp.config.Enabled = enabled
}
// IsEnabled returns whether the typewriter effect is enabled
func (tp *TypewriterPrinter) IsEnabled() bool {
return tp.config.Enabled
}
// SetSpeed adjusts the typewriter speed (multiplier: 0.1 = very slow, 1.0 = normal, 2.0 = fast)
func (tp *TypewriterPrinter) SetSpeed(multiplier float64) {
if multiplier <= 0 {
multiplier = 1.0
}
tp.config.BaseDelay = time.Duration(float64(15*time.Millisecond) / multiplier)
tp.config.FastDelay = time.Duration(float64(8*time.Millisecond) / multiplier)
tp.config.SlowDelay = time.Duration(float64(25*time.Millisecond) / multiplier)
tp.config.PauseDelay = time.Duration(float64(150*time.Millisecond) / multiplier)
}
// PrintMessageLine prints a complete message line with typewriter effect
func (tp *TypewriterPrinter) PrintMessageLine(timestamp, prefix, text string) {
// Print the timestamp and prefix with 10-char padding
tp.PrintfInstant("[%s] %-10s: ", timestamp, prefix)
// Print the message text with typewriter effect
tp.Println(text)
}
// Global typewriter printer instance
var globalTypewriter = NewTypewriterPrinter(DefaultTypewriterConfig())
// Global convenience functions that use the global typewriter instance
// TypewriterPrint prints text with typewriter effect using the global instance
func TypewriterPrint(text string) {
globalTypewriter.Print(text)
}
// TypewriterPrintf prints formatted text with typewriter effect using the global instance
func TypewriterPrintf(format string, args ...interface{}) {
globalTypewriter.Printf(format, args...)
}
// TypewriterPrintln prints text with typewriter effect and newline using the global instance
func TypewriterPrintln(text string) {
globalTypewriter.Println(text)
}
// TypewriterPrintfLn prints formatted text with typewriter effect and newline using the global instance
func TypewriterPrintfLn(format string, args ...interface{}) {
globalTypewriter.PrintfLn(format, args...)
}
// TypewriterPrintMessageLine prints a message line with typewriter effect using the global instance
func TypewriterPrintMessageLine(timestamp, prefix, text string) {
globalTypewriter.PrintMessageLine(timestamp, prefix, text)
}
// SetGlobalTypewriterEnabled enables or disables the global typewriter effect
func SetGlobalTypewriterEnabled(enabled bool) {
globalTypewriter.SetEnabled(enabled)
}
// SetGlobalTypewriterSpeed sets the speed of the global typewriter effect
func SetGlobalTypewriterSpeed(multiplier float64) {
globalTypewriter.SetSpeed(multiplier)
}
// GetGlobalTypewriter returns the global typewriter instance
func GetGlobalTypewriter() *TypewriterPrinter {
return globalTypewriter
}
+274
View File
@@ -0,0 +1,274 @@
package global
import (
"context"
"fmt"
"os"
"os/exec"
"time"
"github.com/cline/cli/pkg/common"
)
// ClineClients manages Cline instances using the new registry system
type ClineClients struct {
registry *ClientRegistry
}
// NewClineClients creates a new ClineClients instance
func NewClineClients(configPath string) *ClineClients {
registry := NewClientRegistry(configPath)
return &ClineClients{
registry: registry,
}
}
// Initialize performs cleanup of stale instances
func (c *ClineClients) Initialize(ctx context.Context) error {
// Clean up stale entries (direct SQLite operations)
_ = c.registry.CleanupStaleInstances(ctx)
return nil
}
// StartNewInstance starts a new Cline instance and waits for cline-core to self-register
func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstanceInfo, error) {
// Find available ports
corePort, hostPort, err := common.FindAvailablePortPair()
if err != nil {
return nil, fmt.Errorf("failed to find available ports: %w", err)
}
fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort)
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
// Start cline-core (it will register itself in SQLite locks database)
coreCmd, err := startClineCore(corePort, hostPort)
if err != nil {
// Clean up host process if core fails to start
if hostCmd != nil && hostCmd.Process != nil {
hostCmd.Process.Kill()
}
return nil, fmt.Errorf("failed to start cline-core: %w", err)
}
fullAddress := fmt.Sprintf("localhost:%d", corePort)
fmt.Println("Waiting for services to start and self-register in SQLite...")
// Use RetryOperation to wait for instance to be ready
var instance *common.CoreInstanceInfo
err = common.RetryOperation(12, 5*time.Second, func() error {
// Check if instance registered itself in SQLite
foundInstance, err := c.registry.GetInstance(fullAddress)
if err != nil || foundInstance == nil {
return fmt.Errorf("instance not found in registry: %v", err)
}
// Verify instance is healthy
if !common.IsInstanceHealthy(ctx, fullAddress) {
return fmt.Errorf("instance is registered but not healthy")
}
// Success - store the instance for return
instance = foundInstance
return nil
})
if err != nil {
// Clean up both processes on failure
if coreCmd != nil && coreCmd.Process != nil {
fmt.Printf("Cleaning up core process (PID: %d)\n", coreCmd.Process.Pid)
coreCmd.Process.Kill()
}
if hostCmd != nil && hostCmd.Process != nil {
fmt.Printf("Cleaning up host process (PID: %d)\n", hostCmd.Process.Pid)
hostCmd.Process.Kill()
}
return nil, fmt.Errorf("failed to start instance: %w", err)
}
fmt.Println("✅ Services started and registered successfully!")
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid)
return instance, nil
}
// StartNewInstanceAtPort starts a new Cline instance at the specified port and waits for self-registration
func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) (*common.CoreInstanceInfo, error) {
// Find available host port (core port + 1000)
hostPort := corePort + 1000
coreAddress := fmt.Sprintf("localhost:%d", corePort)
// Check if the specified core port is available
if common.IsInstanceHealthy(ctx, coreAddress) {
return nil, fmt.Errorf("port %d is already in use by another Cline instance", corePort)
}
fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort)
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
// Start cline-core (it will register itself in SQLite locks database)
coreCmd, err := startClineCore(corePort, hostPort)
if err != nil {
// Clean up host process if core fails to start
if hostCmd != nil && hostCmd.Process != nil {
hostCmd.Process.Kill()
}
return nil, fmt.Errorf("failed to start cline-core: %w", err)
}
fullAddress := fmt.Sprintf("localhost:%d", corePort)
fmt.Println("Waiting for services to start and self-register in SQLite...")
// Use RetryOperation to wait for instance to be ready
var instance *common.CoreInstanceInfo
err = common.RetryOperation(12, 5*time.Second, func() error {
// Check if instance registered itself in SQLite
foundInstance, err := c.registry.GetInstance(fullAddress)
if err != nil || foundInstance == nil {
return fmt.Errorf("instance not found in registry: %v", err)
}
// Verify instance is healthy
if !common.IsInstanceHealthy(ctx, fullAddress) {
return fmt.Errorf("instance is registered but not healthy")
}
// Success - store the instance for return
instance = foundInstance
return nil
})
if err != nil {
// Clean up both processes on failure
if coreCmd != nil && coreCmd.Process != nil {
fmt.Printf("Cleaning up core process (PID: %d)\n", coreCmd.Process.Pid)
coreCmd.Process.Kill()
}
if hostCmd != nil && hostCmd.Process != nil {
fmt.Printf("Cleaning up host process (PID: %d)\n", hostCmd.Process.Pid)
hostCmd.Process.Kill()
}
return nil, fmt.Errorf("failed to start instance at port %d: %w", corePort, err)
}
fmt.Println("✅ Services started and registered successfully!")
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid)
return instance, nil
}
// GetRegistry returns the client registry
func (c *ClineClients) GetRegistry() *ClientRegistry {
return c.registry
}
// EnsureInstanceAtAddress ensures an instance exists at the given address, starting one if needed
func (c *ClineClients) EnsureInstanceAtAddress(ctx context.Context, address string) error {
// Expect host:port everywhere
normalized := address
if normalized == "" {
normalized = fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT)
}
// Check if instance already exists at this address
if c.registry.HasInstanceAtAddress(normalized) {
return nil
}
// Parse host:port
host, port, err := common.ParseHostPort(normalized)
if err != nil {
return fmt.Errorf("invalid address format %s", address)
}
// Use IPv6-compatible localhost detection
if common.IsLocalAddress(host) {
_, err := c.StartNewInstanceAtPort(ctx, port)
if err != nil {
return fmt.Errorf("failed to start new instance at %s: %w", normalized, err)
}
return nil
}
return fmt.Errorf("cannot start remote instance at %s", normalized)
}
func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
fmt.Printf("Starting cline-host on port %d\n", hostPort)
// Start the cline-host process
cmd := exec.Command("./cli/bin/cline-host",
"--verbose",
"--port", fmt.Sprintf("%d", hostPort))
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
fmt.Printf("Started cline-host (PID: %d)\n", cmd.Process.Pid)
return cmd, nil
}
func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
fmt.Printf("Starting cline-core on port %d (with hostbridge on %d)\n", corePort, hostPort)
// Create port-tagged log file in OS temp directory with full address
logFileName := fmt.Sprintf("cline-core-debug-localhost-%d.log", corePort)
logFilePath := fmt.Sprintf("%s/%s", os.TempDir(), logFileName)
logFile, err := os.Create(logFilePath)
if err != nil {
return nil, fmt.Errorf("failed to create log file: %w", err)
}
// Start the cline-core process with --config flag instead of CLINE_DIR env var
args := []string{"cline-core.js",
"--port", fmt.Sprintf("%d", corePort),
"--host-bridge-port", fmt.Sprintf("%d", hostPort),
"--config", Config.ConfigPath}
fmt.Printf("DEBUG: Starting cline-core with command: node %v\n", args)
fmt.Printf("DEBUG: Working directory: ./dist-standalone\n")
fmt.Printf("DEBUG: Config path: %s\n", Config.ConfigPath)
cmd := exec.Command("node", args...)
// Set working directory to dist-standalone (relative to project root)
cmd.Dir = "./dist-standalone"
// Redirect stdout and stderr to log file
cmd.Stdout = logFile
cmd.Stderr = logFile
// Set environment variables (removed CLINE_DIR)
env := os.Environ()
env = append(env,
"GRPC_TRACE=all",
"GRPC_VERBOSITY=DEBUG",
"NODE_ENV=development",
)
cmd.Env = env
if err := cmd.Start(); err != nil {
logFile.Close()
return nil, fmt.Errorf("failed to start cline-core: %w", err)
}
fmt.Printf("Started cline-core (PID: %d)\n", cmd.Process.Pid)
fmt.Printf("Logging cline-core output to: %s\n", logFilePath)
return cmd, nil
}
+67
View File
@@ -0,0 +1,67 @@
package global
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/cline/cli/pkg/common"
"github.com/cline/grpc-go/client"
)
type Port uint16
type GlobalConfig struct {
ConfigPath string
Verbose bool
OutputFormat string
CoreAddress string
}
var (
Config *GlobalConfig
Clients *ClineClients
)
func InitializeGlobalConfig(cfg *GlobalConfig) error {
if cfg.ConfigPath == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
// Ensure .cline directory exists
if err := os.MkdirAll(cfg.ConfigPath, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
Config = cfg
Clients = NewClineClients(cfg.ConfigPath)
// Initialize the clients registry
ctx := context.Background()
if err := Clients.Initialize(ctx); err != nil {
return fmt.Errorf("failed to initialize clients: %w", err)
}
return nil
}
// GetDefaultClient returns a client for the default instance or the address override
func GetDefaultClient(ctx context.Context) (*client.ClineClient, error) {
if Config.CoreAddress != "" && Config.CoreAddress != fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT) {
// User specified a specific address, use that
return Clients.GetRegistry().GetClient(ctx, Config.CoreAddress)
}
// Use the default instance from registry
return Clients.GetRegistry().GetDefaultClient(ctx)
}
// GetClientForAddress returns a client for a specific address
func GetClientForAddress(ctx context.Context, address string) (*client.ClineClient, error) {
return Clients.GetRegistry().GetClient(ctx, address)
}
+267
View File
@@ -0,0 +1,267 @@
package global
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/cline/cli/pkg/cli/sqlite"
"github.com/cline/cli/pkg/common"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
"github.com/cline/grpc-go/host"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
// ClientRegistry manages Cline client connections using direct SQLite operations
type ClientRegistry struct {
lockManager *sqlite.LockManager
configPath string
}
// NewClientRegistry creates a new client registry
func NewClientRegistry(configPath string) *ClientRegistry {
lockManager, err := sqlite.NewLockManager(configPath)
if err != nil {
// Log error but continue - we can still function without SQLite
log.Fatalf("Warning: Failed to initialize SQLite lock manager: %v\n", err)
}
return &ClientRegistry{
lockManager: lockManager,
configPath: configPath,
}
}
// GetDefaultInstance returns the default instance address from settings file
func (r *ClientRegistry) GetDefaultInstance() string {
defaultAddr, err := sqlite.GetDefaultInstance(r.configPath)
if err != nil {
return ""
}
return defaultAddr
}
// SetDefaultInstance sets the default instance (writes default.json)
func (r *ClientRegistry) SetDefaultInstance(address string) error {
// Verify the instance exists in SQLite
if r.lockManager != nil {
exists, err := r.lockManager.HasInstanceAtAddress(address)
if err != nil {
return fmt.Errorf("failed to check instance existence: %w", err)
}
if !exists {
return fmt.Errorf("instance %s not found in registry", address)
}
}
return sqlite.SetDefaultInstance(r.configPath, address)
}
// GetInstance returns instance information directly from SQLite
func (r *ClientRegistry) GetInstance(address string) (*common.CoreInstanceInfo, error) {
if r.lockManager == nil {
return nil, fmt.Errorf("lock manager not available")
}
return r.lockManager.GetInstanceInfo(address)
}
// GetClient returns a connected client for the given address (created on-demand)
func (r *ClientRegistry) GetClient(ctx context.Context, address string) (*client.ClineClient, error) {
// Verify instance exists in SQLite
if r.lockManager != nil {
exists, err := r.lockManager.HasInstanceAtAddress(address)
if err != nil {
return nil, fmt.Errorf("failed to check instance existence: %w", err)
}
if !exists {
return nil, fmt.Errorf("instance %s not found", address)
}
}
// Create client on-demand (no caching)
target, err := common.NormalizeAddressForGRPC(address)
if err != nil {
return nil, fmt.Errorf("invalid address %s: %w", address, err)
}
cl, err := client.NewClineClient(target)
if err != nil {
return nil, fmt.Errorf("failed to create client for %s: %w", target, err)
}
if err := cl.Connect(ctx); err != nil {
return nil, fmt.Errorf("failed to connect to %s: %w", target, err)
}
return cl, nil
}
// GetDefaultClient returns a client for the default instance
func (r *ClientRegistry) GetDefaultClient(ctx context.Context) (*client.ClineClient, error) {
defaultAddr := r.GetDefaultInstance()
if defaultAddr == "" {
return nil, fmt.Errorf("no default instance configured")
}
return r.GetClient(ctx, defaultAddr)
}
// ListInstances returns all registered instances directly from SQLite
func (r *ClientRegistry) ListInstances() []*common.CoreInstanceInfo {
if r.lockManager == nil {
return []*common.CoreInstanceInfo{}
}
// Use context with timeout for health checks
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
instances, err := r.lockManager.ListInstancesWithHealthCheck(ctx)
if err != nil {
fmt.Printf("Warning: Failed to list instances: %v\n", err)
return []*common.CoreInstanceInfo{}
}
return instances
}
// HasInstanceAtAddress checks if an instance exists at the given address (delegates to SQLite)
func (r *ClientRegistry) HasInstanceAtAddress(address string) bool {
if r.lockManager == nil {
return false
}
exists, err := r.lockManager.HasInstanceAtAddress(address)
if err != nil {
fmt.Printf("Warning: Failed to check instance existence: %v\n", err)
return false
}
return exists
}
// CleanupStaleInstances removes stale instances using direct SQLite operations
func (r *ClientRegistry) CleanupStaleInstances(ctx context.Context) error {
if r.lockManager == nil {
return nil
}
// Get all instances with health checks
instances, err := r.lockManager.ListInstancesWithHealthCheck(ctx)
if err != nil {
return fmt.Errorf("failed to list instances for cleanup: %w", err)
}
// Clean up all stale instances
for _, instance := range instances {
if instance.Status != grpc_health_v1.HealthCheckResponse_SERVING {
// Try to gracefully shutdown the paired host process before cleanup
fmt.Printf("Attempting to shutdown dangling host service %s for stale cline core instance %s\n",
instance.HostServiceAddress, instance.Address)
r.tryShutdownHostProcess(instance.HostServiceAddress)
// Remove from SQLite database
if err := r.lockManager.RemoveInstanceLock(instance.Address); err != nil {
return fmt.Errorf("failed to remove stale instance %s: %w", instance.Address, err)
}
fmt.Printf("Removed stale instance: %s\n", instance.Address)
}
}
return nil
}
// tryShutdownHostProcess attempts to gracefully shutdown a host process via RPC
// Best effort, don't throw errors i guess
func (r *ClientRegistry) tryShutdownHostProcess(hostServiceAddress string) {
err := common.RetryOperation(3, 2*time.Second, func() error {
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Create gRPC connection to host bridge
conn, err := grpc.DialContext(ctx, hostServiceAddress,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock())
if err != nil {
return fmt.Errorf("connection failed: %w", err)
}
defer conn.Close()
// Create env service client and call shutdown
envClient := host.NewEnvServiceClient(conn)
_, err = envClient.Shutdown(ctx, &cline.EmptyRequest{})
if err != nil {
return fmt.Errorf("RPC failed: %w", err)
}
return nil
})
if err != nil {
fmt.Printf("Warning: Failed to request host bridge shutdown on port %s: %v\n", hostServiceAddress, err)
} else {
fmt.Printf("Host bridge shutdown requested successfully on port %s\n", hostServiceAddress)
}
}
// ListInstancesCleaned performs cleanup and returns instances with health checks
func (r *ClientRegistry) ListInstancesCleaned(ctx context.Context) ([]*common.CoreInstanceInfo, error) {
// 1. Clean up stale entries (best-effort)
_ = r.CleanupStaleInstances(ctx)
// 2. Get all instances with real-time health checks
instances := r.ListInstances()
// 3. Ensure default is set if instances exist
if err := r.ensureDefaultInstance(instances); err != nil {
fmt.Printf("Warning: Failed to ensure default instance: %v\n", err)
}
return instances, nil
}
// ensureDefaultInstance ensures a default instance is set if instances exist but no default is configured
func (r *ClientRegistry) ensureDefaultInstance(instances []*common.CoreInstanceInfo) error {
currentDefault := r.GetDefaultInstance()
// If we have no instances, clear any stale default and remove settings file
if len(instances) == 0 {
if currentDefault != "" {
// Remove the settings file since no instances exist
settingsPath := filepath.Join(r.configPath, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
_ = os.Remove(settingsPath)
}
return nil
}
// If we have instances but no default, pick the first one
if currentDefault == "" {
return sqlite.SetDefaultInstance(r.configPath, instances[0].Address)
}
// Validate current default still exists in the instances
defaultExists := false
for _, instance := range instances {
if instance.Address == currentDefault {
defaultExists = true
break
}
}
if !defaultExists {
// Current default doesn't exist, pick a new one from available instances
return sqlite.SetDefaultInstance(r.configPath, instances[0].Address)
}
return nil
}
+354
View File
@@ -0,0 +1,354 @@
package handlers
import (
"encoding/json"
"fmt"
"strings"
"github.com/cline/cli/pkg/cli/types"
)
// AskHandler handles ASK type messages
type AskHandler struct {
*BaseHandler
}
// NewAskHandler creates a new ASK handler
func NewAskHandler() *AskHandler {
return &AskHandler{
BaseHandler: NewBaseHandler("ask", PriorityHigh),
}
}
// CanHandle returns true if this is an ASK message
func (h *AskHandler) CanHandle(msg *types.ClineMessage) bool {
return msg.IsAsk()
}
// Handle processes ASK messages
func (h *AskHandler) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
timestamp := msg.GetTimestamp()
switch msg.Ask {
case string(types.AskTypeFollowup):
return h.handleFollowup(msg, dc, timestamp)
case string(types.AskTypePlanModeRespond):
return h.handlePlanModeRespond(msg, dc, timestamp)
case string(types.AskTypeCommand):
return h.handleCommand(msg, dc, timestamp)
case string(types.AskTypeCommandOutput):
return h.handleCommandOutput(msg, dc, timestamp)
case string(types.AskTypeCompletionResult):
return h.handleCompletionResult(msg, dc, timestamp)
case string(types.AskTypeTool):
return h.handleTool(msg, dc, timestamp)
case string(types.AskTypeAPIReqFailed):
return h.handleAPIReqFailed(msg, dc, timestamp)
case string(types.AskTypeResumeTask):
return h.handleResumeTask(msg, dc, timestamp)
case string(types.AskTypeResumeCompletedTask):
return h.handleResumeCompletedTask(msg, dc, timestamp)
case string(types.AskTypeMistakeLimitReached):
return h.handleMistakeLimitReached(msg, dc, timestamp)
case string(types.AskTypeAutoApprovalMaxReached):
return h.handleAutoApprovalMaxReached(msg, dc, timestamp)
case string(types.AskTypeBrowserActionLaunch):
return h.handleBrowserActionLaunch(msg, dc, timestamp)
case string(types.AskTypeUseMcpServer):
return h.handleUseMcpServer(msg, dc, timestamp)
case string(types.AskTypeNewTask):
return h.handleNewTask(msg, dc, timestamp)
case string(types.AskTypeCondense):
return h.handleCondense(msg, dc, timestamp)
case string(types.AskTypeReportBug):
return h.handleReportBug(msg, dc, timestamp)
default:
return h.handleDefault(msg, dc, timestamp)
}
}
// handleFollowup handles followup questions
func (h *AskHandler) handleFollowup(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
var question string
var options []string
var askData types.AskData
if err := json.Unmarshal([]byte(msg.Text), &askData); err == nil {
question = askData.Question
options = askData.Options
} else {
question = msg.Text
}
if question == "" {
return nil
}
err := dc.Renderer.RenderMessage(timestamp, "QUESTION", question)
if err != nil {
return err
}
// Display options if available
if len(options) > 0 {
fmt.Println("\nOptions:")
for i, option := range options {
fmt.Printf("%d. %s\n", i+1, option)
}
}
return nil
}
// handlePlanModeRespond handles plan mode responses
func (h *AskHandler) handlePlanModeRespond(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
var response string
var options []string
// Try to parse as JSON
type PlanModeResponse struct {
Response string `json:"response"`
Options []string `json:"options,omitempty"`
}
var planData PlanModeResponse
if err := json.Unmarshal([]byte(msg.Text), &planData); err == nil {
response = planData.Response
options = planData.Options
} else {
response = msg.Text
}
if response == "" {
return nil
}
err := dc.Renderer.RenderMessage(timestamp, "ASST PLAN", response)
if err != nil {
return err
}
// Display options if available
if len(options) > 0 {
fmt.Println("\nOptions:")
for i, option := range options {
fmt.Printf("%d. %s\n", i+1, option)
}
}
return nil
}
// handleCommand handles command execution requests
func (h *AskHandler) handleCommand(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
command := msg.Text
// Check if this command was flagged despite auto-approval settings turned on for safe commands
hasAutoApprovalConflict := strings.HasSuffix(command, "REQ_APP")
if hasAutoApprovalConflict {
command = strings.TrimSuffix(command, "REQ_APP")
}
err := dc.Renderer.RenderMessage(timestamp, "TERMINAL", "Cline wants to execute this command:")
if err != nil {
return fmt.Errorf("failed to render handleCommand: %w", err)
}
fmt.Printf("\n```shell\n%s\n```\n", strings.TrimSpace(command))
if hasAutoApprovalConflict {
fmt.Printf("\nThe model has determined this command requires explicit approval.\n")
} else {
fmt.Printf("\nApproval required for this command.\n")
}
return nil
}
// handleCommandOutput handles command output requests
func (h *AskHandler) handleCommandOutput(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
commandOutput := msg.Text
err := dc.Renderer.RenderMessage(timestamp, "TERMINAL", fmt.Sprintf("Current terminal output: %s", commandOutput))
if err != nil {
return fmt.Errorf("failed to render handleCommandOutput: %w", err)
}
fmt.Printf("\nApprove to proceed while this command runs in the background.\n")
return nil
}
// handleCompletionResult handles completion result requests
func (h *AskHandler) handleCompletionResult(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return nil
}
// handleTool handles tool execution requests
func (h *AskHandler) handleTool(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
// Parse tool message
var tool types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &tool); err != nil {
// Fallback to simple display
return dc.Renderer.RenderMessage(timestamp, "TOOL", msg.Text)
}
return h.renderToolMessage(&tool, dc, timestamp)
}
// renderToolMessage renders a tool message with appropriate formatting
func (h *AskHandler) renderToolMessage(tool *types.ToolMessage, dc *DisplayContext, timestamp string) error {
switch tool.Tool {
case string(types.ToolTypeEditedExistingFile):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to edit file: %s", tool.Path))
case string(types.ToolTypeNewFileCreated):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to create file: %s", tool.Path))
case string(types.ToolTypeReadFile):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to read file: %s", tool.Path))
case string(types.ToolTypeListFilesTopLevel):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to list files in: %s", tool.Path))
case string(types.ToolTypeListFilesRecursive):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to recursively list files in: %s", tool.Path))
case string(types.ToolTypeSearchFiles):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to search for '%s' in: %s", tool.Regex, tool.Path))
case string(types.ToolTypeWebFetch):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to fetch URL: %s", tool.Path))
case string(types.ToolTypeListCodeDefinitionNames):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to list code definitions for: %s", tool.Path))
default:
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline wants to use tool: %s", tool.Tool))
}
// Skip content preview for readFile and webFetch tools
if tool.Tool == string(types.ToolTypeReadFile) || tool.Tool == string(types.ToolTypeWebFetch) {
return nil
}
// Show content preview, truncating if necessary
preview := tool.Content
if preview != "" {
preview = strings.TrimSpace(tool.Content)
if len(preview) > 1000 {
preview = preview[:1000] + "..."
}
fmt.Printf("Preview: %s\n", preview)
}
fmt.Printf("\nApproval required.\n")
return nil
}
// handleAPIReqFailed handles API request failures
func (h *AskHandler) handleAPIReqFailed(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "ERROR", fmt.Sprintf("API Request Failed: %s. Approve to retry request.", msg.Text))
}
// handleResumeTask handles resume task requests
func (h *AskHandler) handleResumeTask(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "GEN INFO", "Resuming interrupted task.")
}
// handleResumeCompletedTask handles resume completed task requests
func (h *AskHandler) handleResumeCompletedTask(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "GEN INFO", "Resuming completed task.")
}
// handleMistakeLimitReached handles mistake limit reached
func (h *AskHandler) handleMistakeLimitReached(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "ERROR", fmt.Sprintf("Mistake Limit Reached: %s. Approval required.", msg.Text))
}
// handleAutoApprovalMaxReached handles auto-approval max reached
func (h *AskHandler) handleAutoApprovalMaxReached(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "WARNING", fmt.Sprintf("Auto-approval limit reached: %s. Approval required.", msg.Text))
}
// handleBrowserActionLaunch handles browser action launch requests
func (h *AskHandler) handleBrowserActionLaunch(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
url := strings.TrimSpace(msg.Text)
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Cline wants to launch browser and navigate to: %s. Approval required.", url))
}
// handleUseMcpServer handles MCP server usage requests
func (h *AskHandler) handleUseMcpServer(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
// Parse MCP server usage request
type McpServerRequest struct {
ServerName string `json:"serverName"`
Type string `json:"type"`
ToolName string `json:"toolName,omitempty"`
Arguments string `json:"arguments,omitempty"`
URI string `json:"uri,omitempty"`
}
var mcpReq McpServerRequest
if err := json.Unmarshal([]byte(msg.Text), &mcpReq); err != nil {
return dc.Renderer.RenderMessage(timestamp, "MCP", msg.Text)
}
var operation string
if mcpReq.Type == "access_mcp_resource" {
operation = "access a resource"
} else {
operation = fmt.Sprintf("use a tool (%s)", mcpReq.ToolName)
if mcpReq.Arguments != "" {
operation = fmt.Sprintf("%s with args (%s)", operation, mcpReq.Arguments)
}
}
return dc.Renderer.RenderMessage(timestamp, "MCP",
fmt.Sprintf("Cline wants to %s on the %s MCP server", operation, mcpReq.ServerName))
}
// handleNewTask handles new task creation requests
func (h *AskHandler) handleNewTask(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "NEW TASK", fmt.Sprintf("Cline wants to start a new task: %s. Approval required.", msg.Text))
}
// handleCondense handles conversation condensing requests
func (h *AskHandler) handleCondense(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "CONDENSE", fmt.Sprintf("Cline wants to condense the conversation: %s. Approval required.", msg.Text))
}
// handleReportBug handles bug report requests
func (h *AskHandler) handleReportBug(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
var bugData struct {
Title string `json:"title"`
WhatHappened string `json:"what_happened"`
StepsToReproduce string `json:"steps_to_reproduce"`
APIRequestOutput string `json:"api_request_output"`
AdditionalContext string `json:"additional_context"`
}
if err := json.Unmarshal([]byte(msg.Text), &bugData); err != nil {
return dc.Renderer.RenderMessage(timestamp, "BUG REPORT", fmt.Sprintf("Cline wants to create a GitHub issue: %s. Approval required.", msg.Text))
}
err := dc.Renderer.RenderMessage(timestamp, "BUG REPORT", "Cline wants to create a GitHub issue:")
if err != nil {
return fmt.Errorf("failed to render handleReportBug: %w", err)
}
fmt.Printf("\n**Title**: %s\n", bugData.Title)
fmt.Printf("**What Happened**: %s\n", bugData.WhatHappened)
fmt.Printf("**Steps to Reproduce**: %s\n", bugData.StepsToReproduce)
fmt.Printf("**API Request Output**: %s\n", bugData.APIRequestOutput)
fmt.Printf("**Additional Context**: %s\n", bugData.AdditionalContext)
fmt.Printf("\nApprove to create a GitHub issue.\n")
return nil
}
// handleDefault handles unknown ASK message types
func (h *AskHandler) handleDefault(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "ASK", msg.Text)
}
+128
View File
@@ -0,0 +1,128 @@
package handlers
import (
"github.com/cline/cli/pkg/cli/display"
"github.com/cline/cli/pkg/cli/types"
)
// MessageHandler defines the interface for handling different message types
type MessageHandler interface {
// CanHandle returns true if this handler can process the given message
CanHandle(msg *types.ClineMessage) bool
// Handle processes the message and renders it using the display context
Handle(msg *types.ClineMessage, dc *DisplayContext) error
// GetPriority returns the priority of this handler (higher = more priority)
GetPriority() int
// GetName returns a human-readable name for this handler
GetName() string
}
// DisplayContext provides context and utilities for message handlers
type DisplayContext struct {
State *types.ConversationState
Renderer *display.Renderer
IsLast bool
IsPartial bool
Verbose bool
MessageIndex int
}
// BaseHandler provides common functionality for message handlers
type BaseHandler struct {
name string
priority int
}
// NewBaseHandler creates a new base handler
func NewBaseHandler(name string, priority int) *BaseHandler {
return &BaseHandler{
name: name,
priority: priority,
}
}
// GetName returns the handler name
func (h *BaseHandler) GetName() string {
return h.name
}
// GetPriority returns the handler priority
func (h *BaseHandler) GetPriority() int {
return h.priority
}
// HandlerRegistry manages a collection of message handlers
type HandlerRegistry struct {
handlers []MessageHandler
}
// NewHandlerRegistry creates a new handler registry
func NewHandlerRegistry() *HandlerRegistry {
return &HandlerRegistry{
handlers: make([]MessageHandler, 0),
}
}
// Register adds a handler to the registry
func (r *HandlerRegistry) Register(handler MessageHandler) {
r.handlers = append(r.handlers, handler)
// Sort handlers by priority (highest first)
for i := len(r.handlers) - 1; i > 0; i-- {
if r.handlers[i].GetPriority() > r.handlers[i-1].GetPriority() {
r.handlers[i], r.handlers[i-1] = r.handlers[i-1], r.handlers[i]
} else {
break
}
}
}
// Handle finds the appropriate handler and processes the message
func (r *HandlerRegistry) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
for _, handler := range r.handlers {
if handler.CanHandle(msg) {
return handler.Handle(msg, dc)
}
}
// If no specific handler found, use default text handler
return r.handleDefault(msg, dc)
}
// handleDefault provides default handling for unrecognized messages
func (r *HandlerRegistry) handleDefault(msg *types.ClineMessage, dc *DisplayContext) error {
timestamp := msg.GetTimestamp()
if msg.Text == "" {
return nil
}
prefix := "RESPONSE:"
return dc.Renderer.RenderMessage(timestamp, prefix, msg.Text)
}
// GetHandlers returns all registered handlers
func (r *HandlerRegistry) GetHandlers() []MessageHandler {
return r.handlers
}
// GetHandlerByName finds a handler by name
func (r *HandlerRegistry) GetHandlerByName(name string) MessageHandler {
for _, handler := range r.handlers {
if handler.GetName() == name {
return handler
}
}
return nil
}
// HandlerPriorities defines standard priority levels for handlers
const (
PriorityHigh = 100
PriorityNormal = 50
PriorityLow = 10
)
+418
View File
@@ -0,0 +1,418 @@
package handlers
import (
"encoding/json"
"fmt"
"strings"
"github.com/cline/cli/pkg/cli/types"
)
// SayHandler handles SAY type messages
type SayHandler struct {
*BaseHandler
}
// NewSayHandler creates a new SAY handler
func NewSayHandler() *SayHandler {
return &SayHandler{
BaseHandler: NewBaseHandler("say", PriorityNormal),
}
}
// CanHandle returns true if this is a SAY message
func (h *SayHandler) CanHandle(msg *types.ClineMessage) bool {
return msg.IsSay()
}
// Handle processes SAY messages
func (h *SayHandler) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
timestamp := msg.GetTimestamp()
switch msg.Say {
case string(types.SayTypeTask):
return h.handleTask(msg, dc, timestamp)
case string(types.SayTypeError):
return h.handleError(msg, dc, timestamp)
case string(types.SayTypeAPIReqStarted):
return h.handleAPIReqStarted(msg, dc, timestamp)
case string(types.SayTypeAPIReqFinished):
return h.handleAPIReqFinished(msg, dc, timestamp)
case string(types.SayTypeText):
return h.handleText(msg, dc, timestamp)
case string(types.SayTypeReasoning):
return h.handleReasoning(msg, dc, timestamp)
case string(types.SayTypeCompletionResult):
return h.handleCompletionResult(msg, dc, timestamp)
case string(types.SayTypeUserFeedback):
return h.handleUserFeedback(msg, dc, timestamp)
case string(types.SayTypeUserFeedbackDiff):
return h.handleUserFeedbackDiff(msg, dc, timestamp)
case string(types.SayTypeAPIReqRetried):
return h.handleAPIReqRetried(msg, dc, timestamp)
case string(types.SayTypeCommand):
return h.handleCommand(msg, dc, timestamp)
case string(types.SayTypeCommandOutput):
return h.handleCommandOutput(msg, dc, timestamp)
case string(types.SayTypeTool):
return h.handleTool(msg, dc, timestamp)
case string(types.SayTypeShellIntegrationWarning):
return h.handleShellIntegrationWarning(msg, dc, timestamp)
case string(types.SayTypeBrowserActionLaunch):
return h.handleBrowserActionLaunch(msg, dc, timestamp)
case string(types.SayTypeBrowserAction):
return h.handleBrowserAction(msg, dc, timestamp)
case string(types.SayTypeBrowserActionResult):
return h.handleBrowserActionResult(msg, dc, timestamp)
case string(types.SayTypeMcpServerRequestStarted):
return h.handleMcpServerRequestStarted(msg, dc, timestamp)
case string(types.SayTypeMcpServerResponse):
return h.handleMcpServerResponse(msg, dc, timestamp)
case string(types.SayTypeMcpNotification):
return h.handleMcpNotification(msg, dc, timestamp)
case string(types.SayTypeUseMcpServer):
return h.handleUseMcpServer(msg, dc, timestamp)
case string(types.SayTypeDiffError):
return h.handleDiffError(msg, dc, timestamp)
case string(types.SayTypeDeletedAPIReqs):
return h.handleDeletedAPIReqs(msg, dc, timestamp)
case string(types.SayTypeClineignoreError):
return h.handleClineignoreError(msg, dc, timestamp)
case string(types.SayTypeCheckpointCreated):
return h.handleCheckpointCreated(msg, dc, timestamp)
case string(types.SayTypeLoadMcpDocumentation):
return h.handleLoadMcpDocumentation(msg, dc, timestamp)
case string(types.SayTypeInfo):
return h.handleInfo(msg, dc, timestamp)
case string(types.SayTypeTaskProgress):
return h.handleTaskProgress(msg, dc, timestamp)
default:
return h.handleDefault(msg, dc, timestamp)
}
}
// handleTask handles task messages
func (h *SayHandler) handleTask(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return nil
}
// handleError handles error messages
func (h *SayHandler) handleError(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "ERROR", msg.Text)
}
// handleAPIReqStarted handles API request started messages
func (h *SayHandler) handleAPIReqStarted(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
// Parse API request info
apiInfo := types.APIRequestInfo{Cost: -1}
if err := json.Unmarshal([]byte(msg.Text), &apiInfo); err != nil {
return dc.Renderer.RenderMessage(timestamp, "API INFO", msg.Text)
}
// Handle different API request states
if apiInfo.CancelReason != "" {
if apiInfo.CancelReason == "user_cancelled" {
return dc.Renderer.RenderMessage(timestamp, "API INFO", "Request Cancelled")
} else if apiInfo.CancelReason == "retries_exhausted" {
return dc.Renderer.RenderMessage(timestamp, "API INFO", "Request Failed (Retries Exhausted)")
}
return dc.Renderer.RenderMessage(timestamp, "API INFO", "Streaming Failed")
}
if apiInfo.Cost >= 0 {
return dc.Renderer.RenderAPI(timestamp, "Request completed", &apiInfo)
}
// Check for retry status
if apiInfo.RetryStatus != nil {
return dc.Renderer.RenderRetry(timestamp,
apiInfo.RetryStatus.Attempt,
apiInfo.RetryStatus.MaxAttempts,
apiInfo.RetryStatus.DelaySec)
}
return dc.Renderer.RenderAPI(timestamp, "Processing request", &apiInfo)
}
// handleAPIReqFinished handles API request finished messages
func (h *SayHandler) handleAPIReqFinished(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
// This message type is typically not displayed as it's handled by the started message
return nil
}
// handleText handles regular text messages
func (h *SayHandler) handleText(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
// Special case for the user's task input
prefix := "ASST TEXT"
if dc.MessageIndex == 0 {
prefix = "USER"
}
return dc.Renderer.RenderMessage(timestamp, prefix, msg.Text)
}
// handleReasoning handles reasoning messages
func (h *SayHandler) handleReasoning(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
return dc.Renderer.RenderMessage(timestamp, "THINKING", msg.Text)
}
func (h *SayHandler) handleCompletionResult(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
text := msg.Text
if strings.HasSuffix(text, "HAS_CHANGES") {
text = strings.TrimSuffix(text, "HAS_CHANGES")
}
return dc.Renderer.RenderMessage(timestamp, "RESULT", text)
}
// handleUserFeedback handles user feedback messages
func (h *SayHandler) handleUserFeedback(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text != "" {
return dc.Renderer.RenderMessage(timestamp, "USER", msg.Text)
} else {
return dc.Renderer.RenderMessage(timestamp, "USER", "[Provided feedback without text]")
}
}
// handleUserFeedbackDiff handles user feedback diff messages
func (h *SayHandler) handleUserFeedbackDiff(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
var toolMsg types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &toolMsg); err != nil {
return dc.Renderer.RenderMessage(timestamp, "USER DIFF", msg.Text)
}
message := fmt.Sprintf("User manually edited: %s\n\nDiff:\n%s",
toolMsg.Path,
toolMsg.Diff)
return dc.Renderer.RenderMessage(timestamp, "USER DIFF", message)
}
// handleAPIReqRetried handles API request retry messages
func (h *SayHandler) handleAPIReqRetried(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "API INFO", "Retrying request")
}
// handleCommand handles command execution announcements
func (h *SayHandler) handleCommand(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
command := strings.TrimSpace(msg.Text)
err := dc.Renderer.RenderMessage(timestamp, "TERMINAL", "Running command:")
if err != nil {
return fmt.Errorf("failed to render handleCommand: %w", err)
}
fmt.Printf("\n```shell\n%s\n```\n", command)
return nil
}
// handleCommandOutput handles command output messages
func (h *SayHandler) handleCommandOutput(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
commandOutput := msg.Text
return dc.Renderer.RenderMessage(timestamp, "TERMINAL", fmt.Sprintf("Current terminal output: %s", commandOutput))
}
func (h *SayHandler) handleTool(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
var tool types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &tool); err != nil {
return dc.Renderer.RenderMessage(timestamp, "TOOL", msg.Text)
}
return h.renderToolMessage(&tool, dc, timestamp)
}
func (h *SayHandler) renderToolMessage(tool *types.ToolMessage, dc *DisplayContext, timestamp string) error {
switch tool.Tool {
case string(types.ToolTypeEditedExistingFile):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline edited file: %s", tool.Path))
case string(types.ToolTypeNewFileCreated):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline created file: %s", tool.Path))
case string(types.ToolTypeReadFile):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline read file: %s", tool.Path))
case string(types.ToolTypeListFilesTopLevel):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline listed files in: %s", tool.Path))
case string(types.ToolTypeListFilesRecursive):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline recursively listed files in: %s", tool.Path))
case string(types.ToolTypeSearchFiles):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline searched for '%s' in: %s", tool.Regex, tool.Path))
case string(types.ToolTypeWebFetch):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline fetched URL: %s", tool.Path))
case string(types.ToolTypeListCodeDefinitionNames):
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline listed code definitions for: %s", tool.Path))
case string(types.ToolTypeSummarizeTask):
dc.Renderer.RenderMessage(timestamp, "TOOL", "Cline condensed the conversation")
default:
dc.Renderer.RenderMessage(timestamp, "TOOL", fmt.Sprintf("Cline executed tool: %s", tool.Tool))
}
// Skip content preview for readFile and webFetch tools
if tool.Tool == string(types.ToolTypeReadFile) || tool.Tool == string(types.ToolTypeWebFetch) {
return nil
}
// Show content preview, truncating if necessary
preview := tool.Content
if preview != "" {
preview = strings.TrimSpace(tool.Content)
if len(preview) > 1000 {
preview = preview[:1000] + "..."
}
fmt.Printf("Content: %s\n", preview)
}
return nil
}
// handleShellIntegrationWarning handles shell integration warning messages
func (h *SayHandler) handleShellIntegrationWarning(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "WARNING", "Shell Integration Unavailable - Cline won't be able to view the command's output.")
}
// handleBrowserActionLaunch handles browser action launch messages
func (h *SayHandler) handleBrowserActionLaunch(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
url := msg.Text
if url == "" {
return nil
}
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Launching browser at: %s", url))
}
// handleBrowserAction handles browser action messages
func (h *SayHandler) handleBrowserAction(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
type BrowserActionData struct {
Action string `json:"action"`
Coordinate string `json:"coordinate,omitempty"`
Text string `json:"text,omitempty"`
}
var actionData BrowserActionData
if err := json.Unmarshal([]byte(msg.Text), &actionData); err != nil {
return dc.Renderer.RenderMessage(timestamp, "BROWSER", msg.Text)
}
// Special handling for type action
if actionData.Action == "type" && actionData.Text != "" {
actionText := fmt.Sprintf("type '%s'", actionData.Text)
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Next action: %s", actionText))
}
// Special handling for click action
if actionData.Action == "click" && actionData.Coordinate != "" {
actionText := fmt.Sprintf("click (%s)", actionData.Coordinate)
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Next action: %s", actionText))
}
// Generic handling for all other actions
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Next action: %s", actionData.Action))
}
// handleBrowserActionResult handles browser action result messages
func (h *SayHandler) handleBrowserActionResult(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
type BrowserActionResult struct {
Screenshot string `json:"screenshot,omitempty"`
Logs string `json:"logs,omitempty"`
CurrentUrl string `json:"currentUrl,omitempty"`
CurrentMousePosition string `json:"currentMousePosition,omitempty"`
}
var result BrowserActionResult
if err := json.Unmarshal([]byte(msg.Text), &result); err != nil {
return dc.Renderer.RenderMessage(timestamp, "BROWSER", "Action completed")
}
// If we have logs, include them in the message
if result.Logs != "" {
return dc.Renderer.RenderMessage(timestamp, "BROWSER", fmt.Sprintf("Action completed with logs: '%s'", result.Logs))
}
// Default case
return dc.Renderer.RenderMessage(timestamp, "BROWSER", "Action completed")
}
// handleMcpServerRequestStarted handles MCP server request started messages
func (h *SayHandler) handleMcpServerRequestStarted(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "MCP", "Sending request to server")
}
// handleMcpServerResponse handles MCP server response messages
func (h *SayHandler) handleMcpServerResponse(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "MCP", fmt.Sprintf("Server response: %s", msg.Text))
}
// handleMcpNotification handles MCP notification messages
func (h *SayHandler) handleMcpNotification(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "MCP", fmt.Sprintf("Server notification: %s", msg.Text))
}
// handleUseMcpServer handles MCP server usage messages
func (h *SayHandler) handleUseMcpServer(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "MCP", "Server operation approved")
}
// handleDiffError handles diff error messages
func (h *SayHandler) handleDiffError(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "WARNING", "Diff Edit Failure - The model used an invalid diff edit format or used search patterns that don't match anything in the file.")
}
// handleDeletedAPIReqs handles deleted API requests messages
func (h *SayHandler) handleDeletedAPIReqs(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
// This message includes api metrics of deleted messages, which we do not log
return dc.Renderer.RenderMessage(timestamp, "GEN INFO", "Checkpoint restored")
}
// handleClineignoreError handles .clineignore error messages
func (h *SayHandler) handleClineignoreError(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "WARNING", fmt.Sprintf("Access Denied - Cline tried to access %s which is blocked by the .clineignore file", msg.Text))
}
// handleCheckpointCreated handles checkpoint created messages
func (h *SayHandler) handleCheckpointCreated(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "GEN INFO", "Checkpoint created")
}
// handleLoadMcpDocumentation handles load MCP documentation messages
func (h *SayHandler) handleLoadMcpDocumentation(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "GEN INFO", "Loading MCP documentation")
}
// handleInfo handles info messages
func (h *SayHandler) handleInfo(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return nil
}
// handleTaskProgress handles task progress messages
func (h *SayHandler) handleTaskProgress(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
if msg.Text == "" {
return nil
}
return dc.Renderer.RenderMessage(timestamp, "PROGRESS", fmt.Sprintf("Task Checklist: %s", msg.Text))
}
// handleDefault handles unknown SAY message types
func (h *SayHandler) handleDefault(msg *types.ClineMessage, dc *DisplayContext, timestamp string) error {
return dc.Renderer.RenderMessage(timestamp, "SAY", msg.Text)
}
+388
View File
@@ -0,0 +1,388 @@
package cli
import (
"context"
"fmt"
"os"
"syscall"
"text/tabwriter"
"time"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/grpc-go/cline"
"github.com/spf13/cobra"
"google.golang.org/grpc/health/grpc_health_v1"
)
func NewInstanceCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "instance",
Aliases: []string{"i"},
Short: "Manage Cline instances",
Long: `List and manage multiple Cline instances similar to kubectl contexts.`,
}
cmd.AddCommand(newInstanceListCommand())
cmd.AddCommand(newInstanceUseCommand())
cmd.AddCommand(newInstanceNewCommand())
cmd.AddCommand(newInstanceKillCommand())
return cmd
}
func newInstanceKillCommand() *cobra.Command {
var killAll bool
cmd := &cobra.Command{
Use: "kill <address>",
Aliases: []string{"k"},
Short: "Kill a Cline instance by address",
Long: `Kill a running Cline instance and clean up its registry entry.`,
Args: func(cmd *cobra.Command, args []string) error {
if killAll && len(args) > 0 {
return fmt.Errorf("cannot specify both --all flag and address argument")
}
if !killAll && len(args) != 1 {
return fmt.Errorf("requires exactly one address argument when --all is not specified")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
ctx := cmd.Context()
registry := global.Clients.GetRegistry()
if killAll {
return killAllInstances(ctx, registry)
} else {
return killSingleInstance(ctx, registry, args[0])
}
},
}
cmd.Flags().BoolVar(&killAll, "all", false, "kill all running instances")
return cmd
}
func killSingleInstance(ctx context.Context, registry *global.ClientRegistry, address string) error {
// Check if the instance exists in the registry
_, err := registry.GetInstance(address)
if err != nil {
return fmt.Errorf("instance %s not found in registry", address)
}
fmt.Printf("Killing instance: %s\n", address)
// Get gRPC client and process info
client, err := registry.GetClient(ctx, address)
if err != nil {
return fmt.Errorf("failed to connect to instance %s: %w", address, err)
}
processInfo, err := client.State.GetProcessInfo(ctx, &cline.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get process info for instance %s: %w", address, err)
}
pid := int(processInfo.ProcessId)
fmt.Printf("Terminating process PID %d...\n", pid)
// Kill the process
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
return fmt.Errorf("failed to kill process %d: %w", pid, err)
}
// Wait for the instance to remove itself from registry
fmt.Printf("Waiting for instance to clean up registry entry...\n")
for i := 0; i < 5; i++ {
time.Sleep(1 * time.Second)
if !registry.HasInstanceAtAddress(address) {
fmt.Printf("Instance %s successfully killed and removed from registry.\n", address)
// Update default instance if needed
instances, err := registry.ListInstancesCleaned(ctx)
if err == nil && len(instances) > 0 {
// ensureDefaultInstance logic will handle setting a new default
defaultInstance := registry.GetDefaultInstance()
if defaultInstance == address || defaultInstance == "" {
if len(instances) > 0 {
if err := registry.SetDefaultInstance(instances[0].Address); err == nil {
fmt.Printf("Updated default instance to: %s\n", instances[0].Address)
}
}
}
}
return nil
}
}
return fmt.Errorf("instance killed but failed to remove itself from registry within 5 seconds")
}
func killAllInstances(ctx context.Context, registry *global.ClientRegistry) error {
// Get all instances from registry
instances, err := registry.ListInstancesCleaned(ctx)
if err != nil {
return fmt.Errorf("failed to list instances: %w", err)
}
if len(instances) == 0 {
fmt.Println("No Cline instances found to kill.")
return nil
}
fmt.Printf("Killing %d instances...\n", len(instances))
var killResults []killResult
// Kill all instances
for _, instance := range instances {
result := killInstanceProcess(ctx, registry, instance.Address)
killResults = append(killResults, result)
if result.err != nil {
fmt.Printf("✗ Failed to kill %s: %v\n", instance.Address, result.err)
} else if result.alreadyDead {
fmt.Printf("⚠ Instance %s appears to be already dead\n", instance.Address)
} else {
fmt.Printf("✓ Killed %s (PID %d)\n", instance.Address, result.pid)
}
}
// Wait for all instances to clean up their registry entries
fmt.Printf("Waiting for instances to clean up registry entries...\n")
maxWaitTime := 10 // seconds
for i := 0; i < maxWaitTime; i++ {
time.Sleep(1 * time.Second)
remainingInstances, err := registry.ListInstancesCleaned(ctx)
if err != nil {
fmt.Printf("Warning: failed to check registry status: %v\n", err)
continue
}
if len(remainingInstances) == 0 {
fmt.Printf("✓ All instances successfully removed from registry.\n")
break
}
if i == maxWaitTime-1 {
fmt.Printf("⚠ %d instances still in registry after %d seconds\n", len(remainingInstances), maxWaitTime)
for _, remaining := range remainingInstances {
fmt.Printf(" - %s\n", remaining.Address)
}
}
}
// Print summary
successful := 0
failed := 0
alreadyDead := 0
for _, result := range killResults {
if result.err != nil {
failed++
} else if result.alreadyDead {
alreadyDead++
} else {
successful++
}
}
fmt.Printf("\nSummary: ")
if successful > 0 {
fmt.Printf("Successfully killed %d instances. ", successful)
}
if alreadyDead > 0 {
fmt.Printf("%d were already dead. ", alreadyDead)
}
if failed > 0 {
fmt.Printf("%d failures.", failed)
return fmt.Errorf("failed to kill %d out of %d instances", failed, len(instances))
}
fmt.Println()
return nil
}
type killResult struct {
address string
pid int
alreadyDead bool
err error
}
func killInstanceProcess(ctx context.Context, registry *global.ClientRegistry, address string) killResult {
// Get gRPC client and process info
client, err := registry.GetClient(ctx, address)
if err != nil {
return killResult{address: address, alreadyDead: true, err: nil}
}
processInfo, err := client.State.GetProcessInfo(ctx, &cline.EmptyRequest{})
if err != nil {
return killResult{address: address, alreadyDead: true, err: nil}
}
pid := int(processInfo.ProcessId)
// Kill the process
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
return killResult{address: address, pid: pid, err: err}
}
return killResult{address: address, pid: pid, err: nil}
}
func newInstanceListCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"l"},
Short: "List all registered Cline instances",
Long: `List all registered Cline instances with their status and connection details.`,
RunE: func(cmd *cobra.Command, args []string) error {
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
ctx := cmd.Context()
registry := global.Clients.GetRegistry()
// Load, cleanup stale local entries, and update health
instances, err := registry.ListInstancesCleaned(ctx)
if err != nil {
return fmt.Errorf("failed to list instances: %w", err)
}
defaultInstance := registry.GetDefaultInstance()
if len(instances) == 0 {
fmt.Println("No Cline instances found.")
fmt.Println("Run 'cline instance new' to start a new instance, or 'cline task new \"...\"' to auto-start one.")
return nil
}
// Always output a table
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "ADDRESS\tSTATUS\tVERSION\tLAST SEEN\tPID\tDEFAULT")
for _, instance := range instances {
isDefault := ""
if instance.Address == defaultInstance {
isDefault = "*"
}
lastSeen := instance.LastSeen.Format("15:04:05")
if time.Since(instance.LastSeen) > 24*time.Hour {
lastSeen = instance.LastSeen.Format("2006-01-02")
}
// Get PID via RPC if instance is healthy
pid := "N/A"
if instance.Status == grpc_health_v1.HealthCheckResponse_SERVING {
if client, err := registry.GetClient(ctx, instance.Address); err == nil {
if processInfo, err := client.State.GetProcessInfo(ctx, &cline.EmptyRequest{}); err == nil {
pid = fmt.Sprintf("%d", processInfo.ProcessId)
// Update version from RPC if available
if processInfo.Version != nil && *processInfo.Version != "" && *processInfo.Version != "unknown" {
instance.Version = *processInfo.Version
}
}
}
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
instance.Address,
instance.Status,
instance.Version,
lastSeen,
pid,
isDefault,
)
}
w.Flush()
return nil
},
}
return cmd
}
func newInstanceUseCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "use <address>",
Aliases: []string{"u"},
Short: "Set the default Cline instance",
Long: `Set the default Cline instance to use for subsequent commands.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
address := args[0]
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
registry := global.Clients.GetRegistry()
// Verify the instance exists
_, err := registry.GetInstance(address)
if err != nil {
return fmt.Errorf("instance %s not found. Run 'cline instance list' to see available instances", address)
}
// Set as default
if err := registry.SetDefaultInstance(address); err != nil {
return fmt.Errorf("failed to set default instance: %w", err)
}
fmt.Printf("Switched to instance: %s\n", address)
return nil
},
}
return cmd
}
func newInstanceNewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "new",
Aliases: []string{"n"},
Short: "Create a new Cline instance",
Long: `Create a new Cline instance with automatically assigned ports.`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if global.Clients == nil {
return fmt.Errorf("clients not initialized")
}
fmt.Println("Starting new Cline instance...")
instance, err := global.Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start instance: %w", err)
}
fmt.Printf("Successfully started new instance:\n")
fmt.Printf(" Address: %s\n", instance.Address)
fmt.Printf(" Core Port: %d\n", instance.CorePort())
fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort())
// Check if this is now the default instance
registry := global.Clients.GetRegistry()
if registry.GetDefaultInstance() == instance.Address {
fmt.Printf(" Status: Default instance\n")
}
return nil
},
}
return cmd
}
+366
View File
@@ -0,0 +1,366 @@
package sqlite
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"time"
"github.com/cline/cli/pkg/common"
_ "github.com/mattn/go-sqlite3"
"google.golang.org/grpc/health/grpc_health_v1"
)
// normalizeAddressVariants returns address variants to try when querying SQLite.
// Handles localhost/127.0.0.1 equivalence by returning both forms.
func normalizeAddressVariants(address string) []string {
variants := []string{address}
// Extract host and port
host, port, err := net.SplitHostPort(address)
if err != nil {
return variants
}
// Add the alternate form for localhost/127.0.0.1
if host == "localhost" {
variants = append(variants, net.JoinHostPort("127.0.0.1", port))
} else if host == "127.0.0.1" {
variants = append(variants, net.JoinHostPort("localhost", port))
}
return variants
}
// LockManager provides access to the SQLite locks database
type LockManager struct {
dbPath string
db *sql.DB
}
// NewLockManager creates a new lock manager
func NewLockManager(clineDir string) (*LockManager, error) {
dbPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "locks.db")
// Ensure the directory exists (for future DB creation by cline-core)
dbDir := filepath.Dir(dbPath)
if err := os.MkdirAll(dbDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create database directory: %w", err)
}
// Check if database exists
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
// Database doesn't exist - return manager with nil db
// All methods already handle this gracefully!
return &LockManager{dbPath: dbPath, db: nil}, nil
}
// Database exists - open it normally (no schema creation)
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
// If we can't open existing database, return nil db manager
return &LockManager{dbPath: dbPath, db: nil}, nil
}
// Test the connection
if err := db.Ping(); err != nil {
db.Close()
// If connection fails, return nil db manager
return &LockManager{dbPath: dbPath, db: nil}, nil
}
return &LockManager{
dbPath: dbPath,
db: db,
}, nil
}
// ensureConnection attempts to establish a database connection if one doesn't exist
func (lm *LockManager) ensureConnection() error {
// If we already have a connection, we're done
if lm.db != nil {
return nil
}
// Check if database exists now (created by cline-core)
if _, err := os.Stat(lm.dbPath); os.IsNotExist(err) {
return fmt.Errorf("database not available")
}
// Database exists, try to connect
db, err := sql.Open("sqlite3", lm.dbPath)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
if err := db.Ping(); err != nil {
db.Close()
return fmt.Errorf("database connection failed: %w", err)
}
// Success! Update our connection permanently
lm.db = db
return nil
}
// Close closes the database connection
func (lm *LockManager) Close() error {
if lm.db != nil {
return lm.db.Close()
}
return nil
}
// GetInstanceLocks returns all instance locks
func (lm *LockManager) GetInstanceLocks() ([]common.LockRow, error) {
if err := lm.ensureConnection(); err != nil {
return []common.LockRow{}, nil
}
query := common.SelectInstanceLocksSQL
rows, err := lm.db.Query(query)
if err != nil {
return nil, fmt.Errorf("failed to query instance locks: %w", err)
}
defer rows.Close()
var locks []common.LockRow
for rows.Next() {
var lock common.LockRow
err := rows.Scan(&lock.ID, &lock.HeldBy, &lock.LockType, &lock.LockTarget, &lock.LockedAt)
if err != nil {
return nil, fmt.Errorf("failed to scan lock row: %w", err)
}
locks = append(locks, lock)
}
return locks, nil
}
// RemoveInstanceLock removes an instance lock by address
func (lm *LockManager) RemoveInstanceLock(address string) error {
if err := lm.ensureConnection(); err != nil {
return nil // Gracefully handle missing database for cleanup operations
}
query := common.DeleteInstanceLockSQL
_, err := lm.db.Exec(query, address)
if err != nil {
return fmt.Errorf("failed to remove instance lock: %w", err)
}
return nil
}
// HasInstanceAtAddress checks if an instance exists at the given address
func (lm *LockManager) HasInstanceAtAddress(address string) (bool, error) {
if err := lm.ensureConnection(); err != nil {
return false, nil
}
query := common.CountInstanceLockSQL
var count int
err := lm.db.QueryRow(query, address).Scan(&count)
if err != nil {
return false, fmt.Errorf("failed to check instance existence: %w", err)
}
return count > 0, nil
}
// GetInstanceInfo returns instance information directly from SQLite.
// Handles localhost/127.0.0.1 equivalence by trying both variants.
func (lm *LockManager) GetInstanceInfo(address string) (*common.CoreInstanceInfo, error) {
if err := lm.ensureConnection(); err != nil {
return nil, err
}
query := common.SelectInstanceLockByHolderSQL
variants := normalizeAddressVariants(address)
var heldBy, lockTarget string
var lockedAt int64
var lastErr error
// Try each address variant (e.g., localhost:50607 and 127.0.0.1:50607)
for _, variant := range variants {
err := lm.db.QueryRow(query, variant).Scan(&heldBy, &lockTarget, &lockedAt)
if err == nil {
// Found it!
return &common.CoreInstanceInfo{
Address: heldBy,
HostServiceAddress: lockTarget,
Status: grpc_health_v1.HealthCheckResponse_UNKNOWN,
LastSeen: time.Unix(lockedAt/1000, 0),
}, nil
}
if err != sql.ErrNoRows {
// Real error (not just "not found"), save it
lastErr = err
}
}
// None of the variants were found
if lastErr != nil {
return nil, fmt.Errorf("failed to query instance: %w", lastErr)
}
return nil, fmt.Errorf("instance %s not found", address)
}
// ListInstancesWithHealthCheck returns all instances with real-time health checks
func (lm *LockManager) ListInstancesWithHealthCheck(ctx context.Context) ([]*common.CoreInstanceInfo, error) {
if err := lm.ensureConnection(); err != nil {
return []*common.CoreInstanceInfo{}, nil
}
// Get all instance locks
locks, err := lm.GetInstanceLocks()
if err != nil {
return nil, fmt.Errorf("failed to get instance locks: %w", err)
}
var instances []*common.CoreInstanceInfo
for _, lock := range locks {
// Create instance info using actual SQLite data
status, err := common.PerformHealthCheck(ctx, lock.HeldBy)
if status != grpc_health_v1.HealthCheckResponse_SERVING || err != nil {
time.Sleep(1 * time.Second)
status, err = common.PerformHealthCheck(ctx, lock.HeldBy)
}
info := &common.CoreInstanceInfo{
Address: lock.HeldBy,
HostServiceAddress: lock.LockTarget,
Status: status,
LastSeen: time.Unix(lock.LockedAt/1000, 0),
}
instances = append(instances, info)
}
return instances, nil
}
// GetDefaultInstance reads the default instance from the settings file
func GetDefaultInstance(clineDir string) (string, error) {
settingsPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
data, err := os.ReadFile(settingsPath)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", fmt.Errorf("failed to read default instance file: %w", err)
}
var defaultInstance common.DefaultCoreInstance
if err := json.Unmarshal(data, &defaultInstance); err != nil {
return "", fmt.Errorf("failed to parse default instance JSON: %w", err)
}
if defaultInstance.Address == "" {
return "", fmt.Errorf("default instance not set in settings file")
}
return defaultInstance.Address, nil
}
// SetDefaultInstance writes the default instance to the settings file with proper locking
func SetDefaultInstance(clineDir, address string) error {
// Create lock manager for this operation
lockManager, err := NewLockManager(clineDir)
if err != nil {
return fmt.Errorf("Warning: SQLite unavailable, writing without lock: %v\n", err)
}
defer lockManager.Close()
settingsPath := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings", "cli-default-instance.json")
// Generate a unique identifier for this CLI process
heldBy := fmt.Sprintf("cli-process-%d", os.Getpid())
// Use file lock for the write operation
return lockManager.WithFileLock(settingsPath, heldBy, func() error {
return writeDefaultInstanceJSONToDisk(clineDir, address)
})
}
func writeDefaultInstanceJSONToDisk(clineDir, address string) error {
settingsDir := filepath.Join(clineDir, common.SETTINGS_SUBFOLDER, "settings")
if err := os.MkdirAll(settingsDir, 0755); err != nil {
return fmt.Errorf("failed to create settings directory: %w", err)
}
settingsPath := filepath.Join(settingsDir, "cli-default-instance.json")
payload := common.DefaultCoreInstance{
Address: address,
LastUpdated: time.Now().Format(time.RFC3339),
}
data, err := json.MarshalIndent(payload, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal default instance JSON: %w", err)
}
if err := os.WriteFile(settingsPath, data, 0644); err != nil {
return fmt.Errorf("failed to write default instance file: %w", err)
}
return nil
}
// AcquireFileLock attempts to acquire a file lock
func (lm *LockManager) AcquireFileLock(filePath, heldBy string) error {
if err := lm.ensureConnection(); err != nil {
return err
}
now := time.Now().Unix() * 1000 // Convert to milliseconds
query := common.InsertFileLockSQL
_, err := lm.db.Exec(query, heldBy, filePath, now)
if err != nil {
return fmt.Errorf("failed to acquire file lock for %s: %w", filePath, err)
}
return nil
}
// ReleaseFileLock releases a file lock
func (lm *LockManager) ReleaseFileLock(filePath, heldBy string) error {
if lm.db == nil {
return nil
}
query := common.DeleteFileLockSQL
_, err := lm.db.Exec(query, heldBy, filePath)
if err != nil {
return fmt.Errorf("failed to release file lock for %s: %w", filePath, err)
}
return nil
}
// WithFileLock executes a function while holding a file lock
func (lm *LockManager) WithFileLock(filePath, heldBy string, fn func() error) error {
if err := lm.AcquireFileLock(filePath, heldBy); err != nil {
return err
}
defer func() {
if releaseErr := lm.ReleaseFileLock(filePath, heldBy); releaseErr != nil {
fmt.Printf("Warning: Failed to release file lock for %s: %v\n", filePath, releaseErr)
}
}()
return fn()
}
+444
View File
@@ -0,0 +1,444 @@
package cli
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/task"
"github.com/spf13/cobra"
)
func NewTaskCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "task",
Aliases: []string{"t"},
Short: "Manage Cline tasks",
Long: `Create, monitor, and manage Cline AI tasks.`,
}
cmd.AddCommand(newTaskNewCommand())
cmd.AddCommand(newTaskCancelCommand())
cmd.AddCommand(newTaskFollowCommand())
cmd.AddCommand(newTaskSendCommand())
cmd.AddCommand(newTaskViewCommand())
cmd.AddCommand(newTaskListCommand())
cmd.AddCommand(newTaskResumeCommand())
return cmd
}
var taskManager *task.Manager
func ensureTaskManager(ctx context.Context, address string) error {
if taskManager == nil || (address != "" && taskManager.GetCurrentInstance() != address) {
var err error
var instanceAddress string
if address != "" {
// Ensure instance exists at the specified address
if err := ensureInstanceAtAddress(ctx, address); err != nil {
return fmt.Errorf("failed to ensure instance at address %s: %w", address, err)
}
taskManager, err = task.NewManagerForAddress(ctx, address)
instanceAddress = address
} else {
// Ensure default instance exists
if err := ensureDefaultInstance(ctx); err != nil {
return fmt.Errorf("failed to ensure default instance: %w", err)
}
taskManager, err = task.NewManagerForDefault(ctx)
if err == nil {
instanceAddress = taskManager.GetCurrentInstance()
}
}
if err != nil {
return fmt.Errorf("failed to create task manager: %w", err)
}
// Always set the instance we're using as the default
registry := global.Clients.GetRegistry()
if err := registry.SetDefaultInstance(instanceAddress); err != nil {
// Log warning but don't fail - this is not critical
fmt.Printf("Warning: failed to set default instance: %v\n", err)
}
}
return nil
}
// ensureInstanceAtAddress ensures an instance exists at the given address
func ensureInstanceAtAddress(ctx context.Context, address string) error {
if global.Clients == nil {
return fmt.Errorf("global clients not initialized")
}
return global.Clients.EnsureInstanceAtAddress(ctx, address)
}
// ensureDefaultInstance ensures a default instance exists
func ensureDefaultInstance(ctx context.Context) error {
if global.Clients == nil {
return fmt.Errorf("global clients not initialized")
}
// Check if we have any instances in the registry
registry := global.Clients.GetRegistry()
if registry.GetDefaultInstance() == "" {
// No default instance, start a new one
instance, err := global.Clients.StartNewInstance(ctx)
if err != nil {
return fmt.Errorf("failed to start new default instance: %w", err)
}
// Set the new instance as default
if err := registry.SetDefaultInstance(instance.Address); err != nil {
return fmt.Errorf("failed to set default instance: %w", err)
}
}
return nil
}
func newTaskNewCommand() *cobra.Command {
var (
images []string
files []string
wait bool
workspaces []string
address string
mode string
)
cmd := &cobra.Command{
Use: "new <prompt>",
Aliases: []string{"n"},
Short: "Create a new task",
Long: `Create a new Cline task with the specified prompt. If no Cline instance exists at the specified address, a new one will be started automatically.`,
Args: cobra.MinimumNArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Get content from both args and stdin
prompt, err := getContentFromStdinAndArgs(args)
if err != nil {
return fmt.Errorf("failed to read prompt: %w", err)
}
// Validate that prompt is passed in call
if prompt == "" {
return fmt.Errorf("prompt required: provide as argument or pipe via stdin")
}
// Ensure task manager is initialized
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
// Set mode if provided
if mode != "" {
if err := taskManager.SetMode(ctx, mode, nil, nil, nil); err != nil {
return fmt.Errorf("failed to set mode: %w", err)
}
fmt.Printf("Mode set to: %s\n", mode)
}
// Create the task
taskID, err := taskManager.CreateTask(ctx, prompt, images, files, workspaces)
if err != nil {
return fmt.Errorf("failed to create task: %w", err)
}
fmt.Printf("Task created successfully with ID: %s\n", taskID)
fmt.Printf("Using instance: %s\n", taskManager.GetCurrentInstance())
// Wait for completion if requested
if wait {
fmt.Println("Following task conversation...")
return taskManager.FollowConversation(ctx)
}
return nil
},
}
cmd.Flags().StringSliceVarP(&images, "image", "i", nil, "attach image files")
cmd.Flags().StringSliceVarP(&files, "file", "f", nil, "attach files")
cmd.Flags().BoolVar(&wait, "wait", false, "wait for task completion")
cmd.Flags().StringSliceVarP(&workspaces, "workdir", "w", nil, "workdir directory paths")
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
cmd.Flags().StringVarP(&mode, "mode", "m", "", "mode (act|plan)")
return cmd
}
func newTaskCancelCommand() *cobra.Command {
var address string
cmd := &cobra.Command{
Use: "cancel",
Aliases: []string{"c"},
Short: "Cancel the current task",
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
if err := taskManager.CancelTask(ctx); err != nil {
return err
}
fmt.Println("Task cancelled successfully")
fmt.Printf("Instance: %s\n", taskManager.GetCurrentInstance())
return nil
},
}
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
return cmd
}
func newTaskSendCommand() *cobra.Command {
var (
images []string
files []string
address string
mode string
approve string
)
cmd := &cobra.Command{
Use: "send [message]",
Aliases: []string{"s"},
Short: "Send a followup message to the current task and/or update mode/approve",
Long: `Send a followup message to continue the conversation with the current task and/or update mode/approve.`,
Args: cobra.MinimumNArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Get content from both args and stdin
message, err := getContentFromStdinAndArgs(args)
if err != nil {
return fmt.Errorf("failed to read message: %w", err)
}
if message == "" && len(images) == 0 && len(files) == 0 && mode == "" && approve == "" {
return fmt.Errorf("content (message, files, images) required unless using --mode or --approve flags")
}
if approve != "" && approve != "true" && approve != "false" {
return fmt.Errorf("--approve must be 'true' or 'false'")
}
if approve != "" && mode != "" {
return fmt.Errorf("cannot use --approve and --mode together")
}
// Ensure task manager is initialized
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
sendDisabled, err := taskManager.CheckSendDisabled(ctx)
if err != nil {
return fmt.Errorf("failed to check if message can be sent: %w", err)
}
if sendDisabled {
fmt.Println("Cannot send message: task is currently busy")
return nil
}
if mode != "" {
if err := taskManager.SetModeAndSendMessage(ctx, mode, message, images, files); err != nil {
return fmt.Errorf("failed to set mode and send message: %w", err)
}
fmt.Printf("Mode set to %s and message sent successfully.\n", mode)
} else {
if err := taskManager.SendMessage(ctx, message, images, files, approve); err != nil {
return err
}
fmt.Printf("Message sent successfully.\n")
}
fmt.Printf("Instance: %s\n", taskManager.GetCurrentInstance())
return nil
},
}
cmd.Flags().StringSliceVarP(&images, "image", "i", nil, "attach image files")
cmd.Flags().StringSliceVarP(&files, "file", "f", nil, "attach files")
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
cmd.Flags().StringVarP(&mode, "mode", "m", "", "mode (act|plan)")
cmd.Flags().StringVarP(&approve, "approve", "a", "", "approve (true) or deny (false) pending request")
return cmd
}
func newTaskFollowCommand() *cobra.Command {
var address string
cmd := &cobra.Command{
Use: "follow",
Aliases: []string{"f"},
Short: "Follow current task conversation in real-time",
Long: `Follow the current task conversation, displaying new messages as they arrive in real-time.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
fmt.Printf("Using instance: %s\n", taskManager.GetCurrentInstance())
return taskManager.FollowConversation(ctx)
},
}
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
return cmd
}
func newTaskViewCommand() *cobra.Command {
var (
current bool
summary bool
address string
)
cmd := &cobra.Command{
Use: "view",
Aliases: []string{"v"},
Short: "View task conversation",
Long: `Output conversation until next completion, with options for current state or summary only.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
fmt.Printf("Using instance: %s\n", taskManager.GetCurrentInstance())
if current {
return taskManager.ShowConversation(ctx)
} else if summary {
return taskManager.GatherFinalSummary(ctx)
} else {
return taskManager.FollowConversationUntilCompletion(ctx)
}
},
}
cmd.Flags().BoolVarP(&current, "current", "c", false, "output current conversation without following")
cmd.Flags().BoolVarP(&summary, "summary", "s", false, "outputs only the completion summary")
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
return cmd
}
func newTaskListCommand() *cobra.Command {
var address string
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"l"},
Short: "List recent task history",
Long: `Display recent tasks from task history.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Ensure task manager is initialized
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
fmt.Printf("Using instance: %s\n", taskManager.GetCurrentInstance())
return taskManager.ListTasks(ctx)
},
}
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
return cmd
}
func newTaskResumeCommand() *cobra.Command {
var address string
cmd := &cobra.Command{
Use: "resume <task-id>",
Aliases: []string{"r"},
Short: "Resume a task by ID",
Long: `Resume an existing task by ID.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
taskID := args[0]
// Ensure task manager is initialized
if err := ensureTaskManager(ctx, address); err != nil {
return err
}
fmt.Printf("Using instance: %s\n", taskManager.GetCurrentInstance())
return taskManager.ResumeTask(ctx, taskID)
},
}
cmd.Flags().StringVar(&address, "address", "", "specific Cline instance address to use")
return cmd
}
// getContentFromStdinAndArgs reads content from both command line args and stdin, and combines them
func getContentFromStdinAndArgs(args []string) (string, error) {
var content strings.Builder
// Add command line args first (if any)
if len(args) > 0 {
content.WriteString(strings.Join(args, " "))
}
// Check if stdin has data
stat, err := os.Stdin.Stat()
if err != nil {
return "", fmt.Errorf("failed to stat stdin: %w", err)
}
// Check if data is being piped to stdin
if (stat.Mode() & os.ModeCharDevice) == 0 {
stdinBytes, err := io.ReadAll(os.Stdin)
if err != nil {
return "", fmt.Errorf("failed to read from stdin: %w", err)
}
stdinContent := strings.TrimSpace(string(stdinBytes))
if stdinContent != "" {
if content.Len() > 0 {
content.WriteString(" ")
}
content.WriteString(stdinContent)
}
}
return content.String(), nil
}
// CleanupTaskManager cleans up the task manager resources
func CleanupTaskManager() {
if taskManager != nil {
taskManager.Cleanup()
}
}
+946
View File
@@ -0,0 +1,946 @@
package task
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/cline/cli/pkg/cli/display"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/handlers"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
)
// Manager handles task execution and message display
type Manager struct {
mu sync.RWMutex
client *client.ClineClient
clientAddress string
state *types.ConversationState
renderer *display.Renderer
streamingDisplay *display.StreamingDisplay
handlerRegistry *handlers.HandlerRegistry
}
// NewManager creates a new task manager
func NewManager(client *client.ClineClient) *Manager {
state := types.NewConversationState()
renderer := display.NewRenderer()
streamingDisplay := display.NewStreamingDisplay(state, renderer)
// Create handler registry and register handlers
registry := handlers.NewHandlerRegistry()
registry.Register(handlers.NewAskHandler())
registry.Register(handlers.NewSayHandler())
return &Manager{
client: client,
clientAddress: "", // Will be set when client is provided
state: state,
renderer: renderer,
streamingDisplay: streamingDisplay,
handlerRegistry: registry,
}
}
// NewManagerForAddress creates a new task manager for a specific instance address
func NewManagerForAddress(ctx context.Context, address string) (*Manager, error) {
client, err := global.GetClientForAddress(ctx, address)
if err != nil {
return nil, fmt.Errorf("failed to get client for address %s: %w", address, err)
}
manager := NewManager(client)
manager.clientAddress = address
return manager, nil
}
// NewManagerForDefault creates a new task manager using the default instance
func NewManagerForDefault(ctx context.Context) (*Manager, error) {
client, err := global.GetDefaultClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get default client: %w", err)
}
manager := NewManager(client)
// Get the default instance address
if global.Clients != nil {
manager.clientAddress = global.Clients.GetRegistry().GetDefaultInstance()
}
return manager, nil
}
// SwitchToInstance switches the manager to use a different Cline instance
func (m *Manager) SwitchToInstance(ctx context.Context, address string) error {
m.mu.Lock()
defer m.mu.Unlock()
// Get client for the new address
newClient, err := global.GetClientForAddress(ctx, address)
if err != nil {
return fmt.Errorf("failed to get client for address %s: %w", address, err)
}
// Update the client and address
m.client = newClient
m.clientAddress = address
if global.Config.Verbose {
m.renderer.RenderDebug("Switched to instance: %s", address)
}
return nil
}
// GetCurrentInstance returns the address of the current instance
func (m *Manager) GetCurrentInstance() string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.clientAddress
}
// CreateTask creates a new task
func (m *Manager) CreateTask(ctx context.Context, prompt string, images, files []string, workspacePaths []string) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
if global.Config.Verbose {
m.renderer.RenderDebug("Creating task: %s", prompt)
if len(files) > 0 {
m.renderer.RenderDebug("Files: %v", files)
}
if len(images) > 0 {
m.renderer.RenderDebug("Images: %v", images)
}
if len(workspacePaths) > 0 {
m.renderer.RenderDebug("Workspaces: %v", workspacePaths)
}
}
// Check if there's an active task and cancel it first
if err := m.cancelExistingTaskIfNeeded(ctx); err != nil {
return "", fmt.Errorf("failed to cancel existing task: %w", err)
}
// Create task request
req := &cline.NewTaskRequest{
Text: prompt,
Images: images,
Files: files,
}
resp, err := m.client.Task.NewTask(ctx, req)
if err != nil {
return "", fmt.Errorf("failed to create task: %w", err)
}
taskID := resp.Value
return taskID, nil
}
// cancelExistingTaskIfNeeded checks if there's an active task and cancels it
func (m *Manager) cancelExistingTaskIfNeeded(ctx context.Context) error {
// Try to get the current state to check if there's an active task
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
// If we can't get state, assume no active task and continue
if global.Config.Verbose {
m.renderer.RenderDebug("Could not get state to check for active task: %v", err)
}
return nil
}
// Properly parse the state to check if there's actually an active task
if state.StateJson != "" {
var stateData types.ExtensionState
if err := json.Unmarshal([]byte(state.StateJson), &stateData); err != nil {
// If we can't parse state, assume no active task
if global.Config.Verbose {
m.renderer.RenderDebug("Could not parse state JSON: %v", err)
}
return nil
}
// Check if there's actually an active task
if stateData.CurrentTaskItem != nil && stateData.CurrentTaskItem.Id != "" {
if global.Config.Verbose {
m.renderer.RenderDebug("Found active task %s, cancelling...", stateData.CurrentTaskItem.Id)
}
// Cancel the existing task
_, err := m.client.Task.CancelTask(ctx, &cline.EmptyRequest{})
if err != nil {
if global.Config.Verbose {
m.renderer.RenderDebug("Cancel task returned error: %v", err)
}
} else {
fmt.Println("Cancelled existing task to start new one")
}
}
}
return nil
}
// CheckSendDisabled determines if we can send a message to the current task
// We duplicate the logic from buttonConfig::getButtonConfig
func (m *Manager) CheckSendDisabled(ctx context.Context) (bool, error) {
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return false, fmt.Errorf("failed to get latest state: %w", err)
}
messages, err := m.extractMessagesFromState(state.StateJson)
if err != nil {
return false, fmt.Errorf("failed to extract messages: %w", err)
}
if len(messages) == 0 {
return false, nil
}
// Use final message to perform validation
lastMessage := messages[len(messages)-1]
// Error types which we allow sending on
errorTypes := []string{
string(types.AskTypeAPIReqFailed), // "api_req_failed"
string(types.AskTypeMistakeLimitReached), // "mistake_limit_reached"
string(types.AskTypeAutoApprovalMaxReached), // "auto_approval_max_req_reached"
}
isError := false
// Check if message is an error type
if lastMessage.Type == types.MessageTypeAsk {
for _, errType := range errorTypes {
if lastMessage.Ask == errType {
isError = true
break
}
}
}
// Streaming and error check
if lastMessage.Partial && !isError {
if global.Config.Verbose {
m.renderer.RenderDebug("Send disabled: task is streaming and non-error")
}
return true, nil
}
// All ask messages allow sending
if lastMessage.Type == types.MessageTypeAsk {
if global.Config.Verbose {
m.renderer.RenderDebug("Send enabled: ask message")
}
return false, nil
}
// Technically unnecessary but implements getButtonConfig 1-1
if lastMessage.Type == types.MessageTypeSay && lastMessage.Say == string(types.SayTypeAPIReqStarted) {
if global.Config.Verbose {
m.renderer.RenderDebug("Send disabled: API request is active")
}
return true, nil
}
if global.Config.Verbose {
m.renderer.RenderDebug("Send disabled: default fallback")
}
return true, nil
}
// SendMessage sends a followup message to the current task
func (m *Manager) SendMessage(ctx context.Context, message string, images, files []string, approve string) error {
responseType := "messageResponse"
if approve == "true" {
responseType = "yesButtonClicked"
}
if approve == "false" {
responseType = "noButtonClicked"
}
if global.Config.Verbose {
m.renderer.RenderDebug("Sending message: %s", message)
if len(files) > 0 {
m.renderer.RenderDebug("Files: %v", files)
}
if len(images) > 0 {
m.renderer.RenderDebug("Images: %v", images)
}
}
// Send the followup message using AskResponse
req := &cline.AskResponseRequest{
ResponseType: responseType,
Text: message,
Images: images,
Files: files,
}
_, err := m.client.Task.AskResponse(ctx, req)
if err != nil {
return fmt.Errorf("failed to send message: %w", err)
}
return nil
}
// SetMode sets the Plan/Act mode for the current Cline instance and optionally sends message
func (m *Manager) SetMode(ctx context.Context, mode string, message *string, images, files []string) error {
if mode != "act" && mode != "plan" {
return fmt.Errorf("invalid mode '%s': must be 'act' or 'plan'", mode)
}
var protoMode cline.PlanActMode
if mode == "plan" {
protoMode = cline.PlanActMode_PLAN
} else {
protoMode = cline.PlanActMode_ACT
}
req := &cline.TogglePlanActModeRequest{
Metadata: &cline.Metadata{},
Mode: protoMode,
}
if message != nil {
req.ChatContent = &cline.ChatContent{
Message: message,
Images: images,
Files: files,
}
}
_, err := m.client.State.TogglePlanActModeProto(ctx, req)
if err != nil {
return fmt.Errorf("failed to set mode to '%s': %w", mode, err)
}
return nil
}
// SetModeAndSendMessage sets the mode and sends a message in one operation
// Handles task restoration internally if the mode switch cancels the current task
func (m *Manager) SetModeAndSendMessage(ctx context.Context, mode, message string, images, files []string) error {
if mode != "act" && mode != "plan" {
return fmt.Errorf("invalid mode '%s': must be 'act' or 'plan'", mode)
}
taskId, err := m.getCurrentTaskId(ctx)
if err != nil {
return fmt.Errorf("failed to get current task ID: %w", err)
}
fmt.Printf("Current task ID: %s\n", taskId)
var protoMode cline.PlanActMode
if mode == "plan" {
protoMode = cline.PlanActMode_PLAN
} else {
protoMode = cline.PlanActMode_ACT
}
req := &cline.TogglePlanActModeRequest{
Metadata: &cline.Metadata{},
Mode: protoMode,
ChatContent: &cline.ChatContent{
Message: &message,
Images: images,
Files: files,
},
}
result, err := m.client.State.TogglePlanActModeProto(ctx, req)
if err != nil {
return fmt.Errorf("failed to set mode to '%s': %w", mode, err)
}
taskPreserved := result.Value
if taskPreserved {
fmt.Printf("Message sent as part of mode change\n")
return nil
} else {
if message != "" || len(images) > 0 || len(files) > 0 {
fmt.Printf("Task was cancelled, restoring task ID: %s\n", taskId)
err = m.ReinitExistingTaskFromId(ctx, taskId)
if err != nil {
return fmt.Errorf("Failed to restore task: %w", err)
}
fmt.Printf("Task restored successfully\n")
// Hardcoded sleep should be replaced with a way to fetch whether task is ready algorithmically
time.Sleep(1 * time.Second)
err = m.SendMessage(ctx, message, images, files, "")
if err != nil {
return fmt.Errorf("Failed to send message: %w", err)
}
fmt.Printf("Message sent to restored task\n")
}
}
return nil
}
// getCurrentTaskId extracts the current task ID from the server state
func (m *Manager) getCurrentTaskId(ctx context.Context) (string, error) {
// Get the latest state
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return "", fmt.Errorf("failed to get state: %w", err)
}
// Parse the server state JSON
var stateData types.ExtensionState
if err := json.Unmarshal([]byte(state.StateJson), &stateData); err != nil {
return "", fmt.Errorf("failed to parse state JSON: %w", err)
}
// Extract current task ID
if stateData.CurrentTaskItem != nil && stateData.CurrentTaskItem.Id != "" {
return stateData.CurrentTaskItem.Id, nil
}
return "", fmt.Errorf("no current task found in state")
}
// ReinitExistingTaskFromId reinitializes an existing task from the given task ID
func (m *Manager) ReinitExistingTaskFromId(ctx context.Context, taskId string) error {
req := &cline.StringRequest{Value: taskId}
resp, err := m.client.Task.ShowTaskWithId(ctx, req)
if err != nil {
return fmt.Errorf("Failed to reinitialize task %s: %w", taskId, err)
}
fmt.Printf("Successfully reinitialized task: %s (ID: %s)\n", taskId, resp.Id)
return nil
}
// ResumeTask resumes an existing task by ID
func (m *Manager) ResumeTask(ctx context.Context, taskID string) error {
m.mu.Lock()
defer m.mu.Unlock()
if global.Config.Verbose {
m.renderer.RenderDebug("Resuming task: %s", taskID)
}
// This call handles cancellation of any active task
if err := m.ReinitExistingTaskFromId(ctx, taskID); err != nil {
return fmt.Errorf("failed to resume task %s: %w", taskID, err)
}
fmt.Printf("Task %s resumed successfully\n", taskID)
return nil
}
// CancelTask cancels the current task
func (m *Manager) CancelTask(ctx context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
_, err := m.client.Task.CancelTask(ctx, &cline.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to cancel task: %w", err)
}
return nil
}
// ListTasks retrieves and displays task history
func (m *Manager) ListTasks(ctx context.Context) error {
m.mu.RLock()
defer m.mu.RUnlock()
req := &cline.GetTaskHistoryRequest{
FavoritesOnly: false,
SearchQuery: "",
SortBy: "oldest",
CurrentWorkspaceOnly: false,
}
resp, err := m.client.Task.GetTaskHistory(ctx, req)
if err != nil {
return fmt.Errorf("failed to get task history: %w", err)
}
if len(resp.Tasks) == 0 {
fmt.Println("No task history found.")
return nil
}
return m.renderer.RenderTaskList(resp.Tasks)
}
// GatherFinalSummary attempts to gather the latest completion_result output and display it
func (m *Manager) GatherFinalSummary(ctx context.Context) error {
m.mu.RLock()
defer m.mu.RUnlock()
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get state: %w", err)
}
messages, err := m.extractMessagesFromState(state.StateJson)
if err != nil {
return fmt.Errorf("failed to extract messages: %w", err)
}
for i := len(messages) - 1; i >= 0; i-- {
msg := messages[i]
// Check if this is a completion result SAY message
if msg.IsSay() && msg.Say == string(types.SayTypeCompletionResult) {
return m.displayMessage(msg, false, false, i)
}
}
return nil
}
// ShowConversation displays the current conversation
func (m *Manager) ShowConversation(ctx context.Context) error {
m.mu.RLock()
defer m.mu.RUnlock()
// Get the latest state which contains messages
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get state: %w", err)
}
// Parse the state JSON to extract messages
messages, err := m.extractMessagesFromState(state.StateJson)
if err != nil {
return fmt.Errorf("failed to extract messages: %w", err)
}
if len(messages) == 0 {
fmt.Println("No conversation history found.")
return nil
}
// Display messages
for i, msg := range messages {
m.displayMessage(msg, false, false, i)
}
return nil
}
func (m *Manager) FollowConversation(ctx context.Context) error {
fmt.Println("Following task conversation... (Press Ctrl+C to exit)")
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Create stream coordinator
coordinator := NewStreamCoordinator()
// Load history first
totalMessageCount, err := m.loadAndDisplayRecentHistory(ctx)
if err != nil {
m.renderer.RenderDebug("Warning: Failed to load conversation history: %v", err)
totalMessageCount = 0
}
coordinator.SetConversationTurnStartIndex(totalMessageCount)
fmt.Println("\n--- Live updates ---")
// Start both streams concurrently
errChan := make(chan error, 2)
if global.Config.OutputFormat == "json" {
go m.handleStateStream(ctx, coordinator, errChan, nil)
} else {
go m.handleStateStream(ctx, coordinator, errChan, nil)
go m.handlePartialMessageStream(ctx, coordinator, errChan)
}
// Wait for either stream to error or context cancellation
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
cancel()
return err
}
}
// FollowConversationUntilCompletion streams conversation updates until task completion
func (m *Manager) FollowConversationUntilCompletion(ctx context.Context) error {
fmt.Println("Streaming conversation until completion... (Press Ctrl+C to exit)")
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Create stream coordinator
coordinator := NewStreamCoordinator()
// Get current message count without displaying history
totalMessageCount, err := m.getCurrentMessageCount(ctx)
if err != nil {
m.renderer.RenderDebug("Warning: Failed to get current message count: %v", err)
totalMessageCount = 0
}
coordinator.SetConversationTurnStartIndex(totalMessageCount)
// Start both streams concurrently
errChan := make(chan error, 2)
completionChan := make(chan bool, 1)
if global.Config.OutputFormat == "json" {
go m.handleStateStream(ctx, coordinator, errChan, completionChan)
} else {
go m.handleStateStream(ctx, coordinator, errChan, completionChan)
go m.handlePartialMessageStream(ctx, coordinator, errChan)
}
// Wait for completion, error, or context cancellation
select {
case <-ctx.Done():
return ctx.Err()
case <-completionChan:
cancel()
return nil
case err := <-errChan:
cancel()
return err
}
}
// handleStateStream handles the SubscribeToState stream
func (m *Manager) handleStateStream(ctx context.Context, coordinator *StreamCoordinator, errChan chan error, completionChan chan bool) {
stateStream, err := m.client.State.SubscribeToState(ctx, &cline.EmptyRequest{})
if err != nil {
errChan <- fmt.Errorf("failed to subscribe to state: %w", err)
return
}
for {
select {
case <-ctx.Done():
return
default:
stateUpdate, err := stateStream.Recv()
if err != nil {
m.renderer.RenderDebug("State stream receive error: %v", err)
errChan <- fmt.Errorf("failed to receive state update: %w", err)
return
}
var pErr error
if global.Config.OutputFormat == "json" {
pErr = m.processStateUpdateJsonMode(stateUpdate, coordinator, completionChan)
} else {
pErr = m.processStateUpdate(stateUpdate, coordinator, completionChan)
}
if pErr != nil {
m.renderer.RenderDebug("State processing error: %v", pErr)
}
}
}
}
func (m *Manager) processStateUpdateJsonMode(stateUpdate *cline.State, coordinator *StreamCoordinator, completionChan chan bool) error {
messages, err := m.extractMessagesFromState(stateUpdate.StateJson)
if err != nil {
return err
}
// Process messages from current conversation turn onwards
startIndex := coordinator.GetConversationTurnStartIndex()
var foundCompletion bool
var displayedUsage bool
for i := startIndex; i < len(messages); i++ {
msg := messages[i]
if global.Config.Verbose {
m.renderer.RenderDebug("State message %d: type=%s, say=%s", i, msg.Type, msg.Say)
}
// Exit after we've seen a task completion & printed out the usage info
if msg.Say == string(types.SayTypeCompletionResult) {
foundCompletion = true
}
// Determine if message is ready to be displayed now
shouldDisplay := true
switch {
case msg.Say == string(types.SayTypeAPIReqStarted):
shouldDisplay = false
apiInfo := types.APIRequestInfo{Cost: -1}
if err := json.Unmarshal([]byte(msg.Text), &apiInfo); err == nil && apiInfo.Cost >= 0 {
shouldDisplay = true
displayedUsage = true
}
}
// Skip if message is partial, except for a specific edge case
if msg.Partial {
// Exception: display if type=say, text="", say="text"
if msg.IsSay() && msg.Text == "" && msg.Say == string(types.SayTypeText) {
shouldDisplay = true
} else {
shouldDisplay = false
}
}
// Display valid messages, exit as soon as we hit a non-valid message
if shouldDisplay {
coordinator.CompleteTurn(i + 1) // Mark the message as complete as soon as we print it
m.displayMessage(msg, false, false, i)
} else {
break
}
}
// We only want to exit after we've displayed the usage, for the case of seeing completion result
if completionChan != nil && foundCompletion && displayedUsage {
completionChan <- true
}
return nil
}
// processStateUpdate processes state updates and supports logic for handling task competion markers
func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *StreamCoordinator, completionChan chan bool) error {
messages, err := m.extractMessagesFromState(stateUpdate.StateJson)
if err != nil {
return err
}
// Process messages from current conversation turn onwards
startIndex := coordinator.GetConversationTurnStartIndex()
var foundCompletion bool
var displayedUsage bool
for i := startIndex; i < len(messages); i++ {
msg := messages[i]
if global.Config.Verbose {
m.renderer.RenderDebug("State message %d: type=%s, say=%s", i, msg.Type, msg.Say)
}
// Exit after we've seen a task completion & printed out the usage info
if msg.Say == string(types.SayTypeCompletionResult) {
foundCompletion = true
}
// Currently handling a subset of message types for displaying
switch {
case msg.Say == string(types.SayTypeUserFeedback):
if !coordinator.IsProcessedInCurrentTurn("user_msg") {
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn("user_msg")
}
case msg.Say == string(types.SayTypeCheckpointCreated):
if !coordinator.IsProcessedInCurrentTurn("checkpoint") {
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn("checkpoint")
}
case msg.Say == string(types.SayTypeAPIReqStarted):
apiInfo := types.APIRequestInfo{Cost: -1}
if err := json.Unmarshal([]byte(msg.Text), &apiInfo); err == nil && apiInfo.Cost >= 0 {
fmt.Println() // adds a separator between cline message and usage message
m.displayMessage(msg, false, false, i)
coordinator.CompleteTurn(len(messages))
displayedUsage = true
}
}
}
// We only want to exit after we've displayed the usage, for the case of seeing completion result
if completionChan != nil && foundCompletion && displayedUsage {
completionChan <- true
}
return nil
}
// handlePartialMessageStream handles the SubscribeToPartialMessage stream for streaming assistant text
func (m *Manager) handlePartialMessageStream(ctx context.Context, coordinator *StreamCoordinator, errChan chan error) {
partialStream, err := m.client.Ui.SubscribeToPartialMessage(ctx, &cline.EmptyRequest{})
if err != nil {
errChan <- fmt.Errorf("failed to subscribe to partial messages: %w", err)
return
}
for {
select {
case <-ctx.Done():
return
default:
protoMsg, err := partialStream.Recv()
if err != nil {
m.renderer.RenderDebug("Partial stream receive error: %v", err)
errChan <- fmt.Errorf("failed to receive partial message: %w", err)
return
}
// Convert proto message to our Message struct
msg := types.ConvertProtoToMessage(protoMsg)
// Debug: Log received message (always show for debugging)
m.renderer.RenderDebug("Received streaming message: type=%s, partial=%v, text_len=%d",
msg.Type, msg.Partial, len(msg.Text))
// Handle the message with streaming support for de-dupping
if err := m.handleStreamingMessage(msg); err != nil {
m.renderer.RenderDebug("Error handling streaming message: %v", err)
}
}
}
}
// handleStreamingMessage handles a streaming message
func (m *Manager) handleStreamingMessage(msg *types.ClineMessage) error {
// Debug: Always log what we're processing
m.renderer.RenderDebug("Processing message: timestamp=%d, partial=%v, type=%s, text_preview=%s",
msg.Timestamp, msg.Partial, msg.Type, m.truncateText(msg.Text, 50))
// Use streaming display which handles deduplication internally
if err := m.streamingDisplay.HandlePartialMessage(msg); err != nil {
m.renderer.RenderDebug("Streaming display failed, using fallback: %v", err)
// Fallback to regular display
return m.displayMessage(msg, true, false, -1)
}
return nil
}
// truncateText truncates text for debug display
func (m *Manager) truncateText(text string, maxLen int) string {
if len(text) <= maxLen {
return text
}
return text[:maxLen] + "..."
}
// displayMessage displays a single message using the handler system
func (m *Manager) displayMessage(msg *types.ClineMessage, isLast, isPartial bool, messageIndex int) error {
if global.Config.OutputFormat == "json" {
return m.outputMessageAsJSON(msg)
} else {
dc := &handlers.DisplayContext{
State: m.state,
Renderer: m.renderer,
IsLast: isLast,
IsPartial: isPartial,
MessageIndex: messageIndex,
}
return m.handlerRegistry.Handle(msg, dc)
}
}
// outputMessageAsJSON prints a single cline message as json
func (m *Manager) outputMessageAsJSON(msg *types.ClineMessage) error {
jsonBytes, err := json.MarshalIndent(msg, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal message as JSON: %w", err)
}
fmt.Println(string(jsonBytes))
return nil
}
// getCurrentMessageCount gets the current message count without displaying messages
func (m *Manager) getCurrentMessageCount(ctx context.Context) (int, error) {
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return 0, fmt.Errorf("failed to get state: %w", err)
}
messages, err := m.extractMessagesFromState(state.StateJson)
if err != nil {
return 0, fmt.Errorf("failed to extract messages: %w", err)
}
return len(messages), nil
}
// loadAndDisplayRecentHistory loads and displays recent conversation history and returns the total number of existing messages
func (m *Manager) loadAndDisplayRecentHistory(ctx context.Context) (int, error) {
// Get the latest state which contains messages
state, err := m.client.State.GetLatestState(ctx, &cline.EmptyRequest{})
if err != nil {
return 0, fmt.Errorf("failed to get state: %w", err)
}
// Parse the state JSON to extract messages
messages, err := m.extractMessagesFromState(state.StateJson)
if err != nil {
return 0, fmt.Errorf("failed to extract messages: %w", err)
}
if len(messages) == 0 {
fmt.Println("No conversation history found.")
return 0, nil
}
// Show only the last 100 messages by default
const maxHistoryMessages = 100
totalMessages := len(messages)
startIndex := 0
if totalMessages > maxHistoryMessages {
startIndex = totalMessages - maxHistoryMessages
fmt.Printf("--- Conversation history (%d of %d messages) ---\n", maxHistoryMessages, totalMessages)
} else {
fmt.Printf("--- Conversation history (%d messages) ---\n", totalMessages)
}
// Display recent messages
for i := startIndex; i < len(messages); i++ {
msg := messages[i]
// Display the message
m.displayMessage(msg, false, false, i)
}
// Return the total number of messages in the conversation
return totalMessages, nil
}
// extractMessagesFromState parses the state JSON and extracts messages
func (m *Manager) extractMessagesFromState(stateJson string) ([]*types.ClineMessage, error) {
return types.ExtractMessagesFromStateJSON(stateJson)
}
// GetState returns the current conversation state
func (m *Manager) GetState() *types.ConversationState {
return m.state
}
// Cleanup cleans up resources
func (m *Manager) Cleanup() {
// Clean up streaming display resources if needed
if m.streamingDisplay != nil {
m.streamingDisplay.Cleanup()
}
}
+41
View File
@@ -0,0 +1,41 @@
package task
// StreamCoordinator manages coordination between SubscribeToState and SubscribeToPartialMessage streams
type StreamCoordinator struct {
conversationTurnStartIndex int // First message index of current turn
processedInCurrentTurn map[string]bool // What we've handled in THIS turn
}
// NewStreamCoordinator creates a new stream coordinator
func NewStreamCoordinator() *StreamCoordinator {
return &StreamCoordinator{
conversationTurnStartIndex: 0,
processedInCurrentTurn: make(map[string]bool),
}
}
// SetConversationTurnStartIndex sets the starting index for the current conversation turn
func (sc *StreamCoordinator) SetConversationTurnStartIndex(index int) {
sc.conversationTurnStartIndex = index
}
// GetConversationTurnStartIndex returns the starting index for the current conversation turn
func (sc *StreamCoordinator) GetConversationTurnStartIndex() int {
return sc.conversationTurnStartIndex
}
// MarkProcessedInCurrentTurn marks an item as processed in the current turn
func (sc *StreamCoordinator) MarkProcessedInCurrentTurn(key string) {
sc.processedInCurrentTurn[key] = true
}
// IsProcessedInCurrentTurn checks if an item has been processed in the current turn
func (sc *StreamCoordinator) IsProcessedInCurrentTurn(key string) bool {
return sc.processedInCurrentTurn[key]
}
// CompleteTurn resets the coordinator for the next conversation turn
func (sc *StreamCoordinator) CompleteTurn(totalMessages int) {
sc.conversationTurnStartIndex = totalMessages
sc.processedInCurrentTurn = make(map[string]bool)
}
+321
View File
@@ -0,0 +1,321 @@
package types
import (
"encoding/json"
"fmt"
"time"
"strconv"
"github.com/cline/grpc-go/cline"
)
// ClineMessage represents a conversation message in the CLI
type ClineMessage struct {
Type MessageType `json:"type"`
Text string `json:"text"`
Timestamp int64 `json:"ts"`
Reasoning string `json:"reasoning,omitempty"`
Say string `json:"say,omitempty"`
Ask string `json:"ask,omitempty"`
Partial bool `json:"partial,omitempty"`
Images []string `json:"images,omitempty"`
Files []string `json:"files,omitempty"`
}
// MessageType represents the type of message
type MessageType string
const (
MessageTypeAsk MessageType = "ask"
MessageTypeSay MessageType = "say"
)
// AskType represents different types of ASK messages
type AskType string
const (
AskTypeFollowup AskType = "followup"
AskTypePlanModeRespond AskType = "plan_mode_respond"
AskTypeCommand AskType = "command"
AskTypeCommandOutput AskType = "command_output"
AskTypeCompletionResult AskType = "completion_result"
AskTypeTool AskType = "tool"
AskTypeAPIReqFailed AskType = "api_req_failed"
AskTypeResumeTask AskType = "resume_task"
AskTypeResumeCompletedTask AskType = "resume_completed_task"
AskTypeMistakeLimitReached AskType = "mistake_limit_reached"
AskTypeAutoApprovalMaxReached AskType = "auto_approval_max_req_reached"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
)
// SayType represents different types of SAY messages
type SayType string
const (
SayTypeTask SayType = "task"
SayTypeError SayType = "error"
SayTypeAPIReqStarted SayType = "api_req_started"
SayTypeAPIReqFinished SayType = "api_req_finished"
SayTypeText SayType = "text"
SayTypeReasoning SayType = "reasoning"
SayTypeCompletionResult SayType = "completion_result"
SayTypeUserFeedback SayType = "user_feedback"
SayTypeUserFeedbackDiff SayType = "user_feedback_diff"
SayTypeAPIReqRetried SayType = "api_req_retried"
SayTypeCommand SayType = "command"
SayTypeCommandOutput SayType = "command_output"
SayTypeTool SayType = "tool"
SayTypeShellIntegrationWarning SayType = "shell_integration_warning"
SayTypeBrowserActionLaunch SayType = "browser_action_launch"
SayTypeBrowserAction SayType = "browser_action"
SayTypeBrowserActionResult SayType = "browser_action_result"
SayTypeMcpServerRequestStarted SayType = "mcp_server_request_started"
SayTypeMcpServerResponse SayType = "mcp_server_response"
SayTypeMcpNotification SayType = "mcp_notification"
SayTypeUseMcpServer SayType = "use_mcp_server"
SayTypeDiffError SayType = "diff_error"
SayTypeDeletedAPIReqs SayType = "deleted_api_reqs"
SayTypeClineignoreError SayType = "clineignore_error"
SayTypeCheckpointCreated SayType = "checkpoint_created"
SayTypeLoadMcpDocumentation SayType = "load_mcp_documentation"
SayTypeInfo SayType = "info"
SayTypeTaskProgress SayType = "task_progress"
)
// ToolMessage represents a tool-related message
type ToolMessage struct {
Tool string `json:"tool"`
Path string `json:"path,omitempty"`
Content string `json:"content,omitempty"`
Diff string `json:"diff,omitempty"`
Regex string `json:"regex,omitempty"`
FilePattern string `json:"filePattern,omitempty"`
OperationIsLocatedInWorkspace *bool `json:"operationIsLocatedInWorkspace,omitempty"`
}
// ToolType represents different types of tools
type ToolType string
const (
ToolTypeEditedExistingFile ToolType = "editedExistingFile"
ToolTypeNewFileCreated ToolType = "newFileCreated"
ToolTypeReadFile ToolType = "readFile"
ToolTypeListFilesTopLevel ToolType = "listFilesTopLevel"
ToolTypeListFilesRecursive ToolType = "listFilesRecursive"
ToolTypeListCodeDefinitionNames ToolType = "listCodeDefinitionNames"
ToolTypeSearchFiles ToolType = "searchFiles"
ToolTypeWebFetch ToolType = "webFetch"
ToolTypeSummarizeTask ToolType = "summarizeTask"
)
// AskData represents the parsed structure of an ASK message
type AskData struct {
Question string `json:"question"`
Response string `json:"response"`
Options []string `json:"options,omitempty"`
}
// APIRequestInfo represents API request information
type APIRequestInfo struct {
Request string `json:"request,omitempty"`
TokensIn int `json:"tokensIn,omitempty"`
TokensOut int `json:"tokensOut,omitempty"`
CacheWrites int `json:"cacheWrites,omitempty"`
CacheReads int `json:"cacheReads,omitempty"`
Cost float64 `json:"cost,omitempty"`
CancelReason string `json:"cancelReason,omitempty"`
StreamingFailedMessage string `json:"streamingFailedMessage,omitempty"`
RetryStatus *APIRequestRetryStatus `json:"retryStatus,omitempty"`
}
// APIRequestRetryStatus represents retry status information
type APIRequestRetryStatus struct {
Attempt int `json:"attempt"`
MaxAttempts int `json:"maxAttempts"`
DelaySec int `json:"delaySec"`
ErrorSnippet string `json:"errorSnippet,omitempty"`
}
// GetTimestamp returns a formatted timestamp string
func (m *ClineMessage) GetTimestamp() string {
return time.Unix(m.Timestamp/1000, 0).Format("15:04:05")
}
// IsAsk returns true if this is an ASK message
func (m *ClineMessage) IsAsk() bool {
return m.Type == MessageTypeAsk
}
// IsSay returns true if this is a SAY message
func (m *ClineMessage) IsSay() bool {
return m.Type == MessageTypeSay
}
// GetMessageKey returns a unique key for this message based on timestamp
func (m *ClineMessage) GetMessageKey() string {
return strconv.FormatInt(m.Timestamp, 10)
}
// ExtractMessagesFromStateJSON parses the state JSON and extracts messages
func ExtractMessagesFromStateJSON(stateJson string) ([]*ClineMessage, error) {
// Parse the state JSON to extract clineMessages
var rawState map[string]interface{}
if err := json.Unmarshal([]byte(stateJson), &rawState); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
// Try to extract clineMessages
clineMessagesRaw, exists := rawState["clineMessages"]
if !exists {
return []*ClineMessage{}, nil
}
// Convert to JSON and back to get proper Message structs
clineMessagesJson, err := json.Marshal(clineMessagesRaw)
if err != nil {
return nil, fmt.Errorf("failed to marshal clineMessages: %w", err)
}
var messages []*ClineMessage
if err := json.Unmarshal(clineMessagesJson, &messages); err != nil {
return nil, fmt.Errorf("failed to unmarshal clineMessages: %w", err)
}
return messages, nil
}
// ConvertProtoToMessage converts a protobuf ClineMessage to our local Message struct
func ConvertProtoToMessage(protoMsg *cline.ClineMessage) *ClineMessage {
var msgType MessageType
var say, ask string
// Convert message type
switch protoMsg.Type {
case cline.ClineMessageType_ASK:
msgType = MessageTypeAsk
ask = convertProtoAskType(protoMsg.Ask)
case cline.ClineMessageType_SAY:
msgType = MessageTypeSay
say = convertProtoSayType(protoMsg.Say)
default:
msgType = MessageTypeSay
say = "unknown"
}
return &ClineMessage{
Type: msgType,
Text: protoMsg.Text,
Timestamp: protoMsg.Ts,
Reasoning: protoMsg.Reasoning,
Say: say,
Ask: ask,
Partial: protoMsg.Partial,
}
}
// convertProtoAskType converts protobuf ask type to string
func convertProtoAskType(askType cline.ClineAsk) string {
switch askType {
case cline.ClineAsk_FOLLOWUP:
return string(AskTypeFollowup)
case cline.ClineAsk_PLAN_MODE_RESPOND:
return string(AskTypePlanModeRespond)
case cline.ClineAsk_COMMAND:
return string(AskTypeCommand)
case cline.ClineAsk_COMMAND_OUTPUT:
return string(AskTypeCommandOutput)
case cline.ClineAsk_COMPLETION_RESULT:
return string(AskTypeCompletionResult)
case cline.ClineAsk_TOOL:
return string(AskTypeTool)
case cline.ClineAsk_API_REQ_FAILED:
return string(AskTypeAPIReqFailed)
case cline.ClineAsk_RESUME_TASK:
return string(AskTypeResumeTask)
case cline.ClineAsk_RESUME_COMPLETED_TASK:
return string(AskTypeResumeCompletedTask)
case cline.ClineAsk_MISTAKE_LIMIT_REACHED:
return string(AskTypeMistakeLimitReached)
case cline.ClineAsk_AUTO_APPROVAL_MAX_REQ_REACHED:
return string(AskTypeAutoApprovalMaxReached)
case cline.ClineAsk_BROWSER_ACTION_LAUNCH:
return string(AskTypeBrowserActionLaunch)
case cline.ClineAsk_USE_MCP_SERVER:
return string(AskTypeUseMcpServer)
case cline.ClineAsk_NEW_TASK:
return string(AskTypeNewTask)
case cline.ClineAsk_CONDENSE:
return string(AskTypeCondense)
case cline.ClineAsk_REPORT_BUG:
return string(AskTypeReportBug)
default:
return "unknown"
}
}
// convertProtoSayType converts protobuf say type to string
func convertProtoSayType(sayType cline.ClineSay) string {
switch sayType {
case cline.ClineSay_TASK:
return string(SayTypeTask)
case cline.ClineSay_ERROR:
return string(SayTypeError)
case cline.ClineSay_API_REQ_STARTED:
return string(SayTypeAPIReqStarted)
case cline.ClineSay_API_REQ_FINISHED:
return string(SayTypeAPIReqFinished)
case cline.ClineSay_TEXT:
return string(SayTypeText)
case cline.ClineSay_REASONING:
return string(SayTypeReasoning)
case cline.ClineSay_COMPLETION_RESULT_SAY:
return string(SayTypeCompletionResult)
case cline.ClineSay_USER_FEEDBACK:
return string(SayTypeUserFeedback)
case cline.ClineSay_USER_FEEDBACK_DIFF:
return string(SayTypeUserFeedbackDiff)
case cline.ClineSay_API_REQ_RETRIED:
return string(SayTypeAPIReqRetried)
case cline.ClineSay_COMMAND_SAY:
return string(SayTypeCommand)
case cline.ClineSay_COMMAND_OUTPUT_SAY:
return string(SayTypeCommandOutput)
case cline.ClineSay_TOOL_SAY:
return string(SayTypeTool)
case cline.ClineSay_SHELL_INTEGRATION_WARNING:
return string(SayTypeShellIntegrationWarning)
case cline.ClineSay_BROWSER_ACTION_LAUNCH_SAY:
return string(SayTypeBrowserActionLaunch)
case cline.ClineSay_BROWSER_ACTION:
return string(SayTypeBrowserAction)
case cline.ClineSay_BROWSER_ACTION_RESULT:
return string(SayTypeBrowserActionResult)
case cline.ClineSay_MCP_SERVER_REQUEST_STARTED:
return string(SayTypeMcpServerRequestStarted)
case cline.ClineSay_MCP_SERVER_RESPONSE:
return string(SayTypeMcpServerResponse)
case cline.ClineSay_MCP_NOTIFICATION:
return string(SayTypeMcpNotification)
case cline.ClineSay_USE_MCP_SERVER_SAY:
return string(SayTypeUseMcpServer)
case cline.ClineSay_DIFF_ERROR:
return string(SayTypeDiffError)
case cline.ClineSay_DELETED_API_REQS:
return string(SayTypeDeletedAPIReqs)
case cline.ClineSay_CLINEIGNORE_ERROR:
return string(SayTypeClineignoreError)
case cline.ClineSay_CHECKPOINT_CREATED:
return string(SayTypeCheckpointCreated)
case cline.ClineSay_LOAD_MCP_DOCUMENTATION:
return string(SayTypeLoadMcpDocumentation)
case cline.ClineSay_INFO:
return string(SayTypeInfo)
case cline.ClineSay_TASK_PROGRESS:
return string(SayTypeTaskProgress)
default:
return "unknown"
}
}
+61
View File
@@ -0,0 +1,61 @@
package types
import (
"sync"
)
// ConversationState manages the state of the conversation
type ConversationState struct {
mu sync.RWMutex
StreamingMessage *StreamingMessage `json:"streamingMessage,omitempty"`
}
// StreamingMessage manages state for streaming message display
type StreamingMessage struct {
CurrentKey string `json:"currentKey"`
LastText string `json:"lastText"`
LastToolMessage string `json:"lastToolMessage,omitempty"`
}
// NewConversationState creates a new conversation state
func NewConversationState() *ConversationState {
return &ConversationState{
StreamingMessage: &StreamingMessage{},
}
}
// SetStreamingMessage updates the streaming message state
func (cs *ConversationState) SetStreamingMessage(key, text string) {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.StreamingMessage.CurrentKey = key
cs.StreamingMessage.LastText = text
}
// GetStreamingMessage returns the current streaming message state
func (cs *ConversationState) GetStreamingMessage() *StreamingMessage {
cs.mu.RLock()
defer cs.mu.RUnlock()
return &StreamingMessage{
CurrentKey: cs.StreamingMessage.CurrentKey,
LastText: cs.StreamingMessage.LastText,
LastToolMessage: cs.StreamingMessage.LastToolMessage,
}
}
// Clear resets state
func (cs *ConversationState) Clear() {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.StreamingMessage = &StreamingMessage{}
}
// ExtensionState represents the server-side extension state structure
type ExtensionState struct {
CurrentTaskItem *CurrentTaskItem `json:"currentTaskItem,omitempty"`
}
// CurrentTaskItem - minimal struct with just what we need
type CurrentTaskItem struct {
Id string `json:"id"`
}
+47
View File
@@ -0,0 +1,47 @@
package cli
import (
"fmt"
"runtime"
"github.com/spf13/cobra"
)
var (
// These will be set at build time via ldflags
Version = "dev"
Commit = "unknown"
Date = "unknown"
BuiltBy = "unknown"
)
// NewVersionCommand creates the version command
func NewVersionCommand() *cobra.Command {
var short bool
cmd := &cobra.Command{
Use: "version",
Short: "Show version information",
Long: `Display version information for the Cline Go host.`,
RunE: func(cmd *cobra.Command, args []string) error {
if short {
fmt.Println(Version)
return nil
}
fmt.Printf("Cline Go Host\n")
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Commit: %s\n", Commit)
fmt.Printf("Built: %s\n", Date)
fmt.Printf("Built by: %s\n", BuiltBy)
fmt.Printf("Go version: %s\n", runtime.Version())
fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
return nil
},
}
cmd.Flags().BoolVar(&short, "short", false, "show only version number")
return cmd
}
+6
View File
@@ -0,0 +1,6 @@
package common
// WE WILL HAVE TO MIGRATE THIS FROM DATA TO v1 LATER
const SETTINGS_SUBFOLDER = "data"
const DEFAULT_CLINE_CORE_PORT = 50052
+54
View File
@@ -0,0 +1,54 @@
package common
// Database query constants for the SQLite locks database
const (
// SelectInstanceLocksSQL selects all instance locks ordered by creation time
SelectInstanceLocksSQL = `
SELECT id, held_by, lock_type, lock_target, locked_at
FROM locks
WHERE lock_type = 'instance'
ORDER BY locked_at ASC
`
SelectInstanceLockByHolderSQL = `
SELECT held_by, lock_target, locked_at
FROM locks
WHERE held_by = ? AND lock_type = 'instance'
`
SelectInstanceLockHoldersAscSQL = `
SELECT held_by, lock_target, locked_at
FROM locks
WHERE lock_type = 'instance'
ORDER BY locked_at ASC
`
// DeleteInstanceLockSQL deletes an instance lock by address
DeleteInstanceLockSQL = `
DELETE FROM locks
WHERE held_by = ? AND lock_type = 'instance'
`
InsertFileLockSQL = `
INSERT INTO locks (held_by, lock_type, lock_target, locked_at)
VALUES (?, 'file', ?, ?)
`
// DeleteFileLockSQL deletes a file lock by holder and target
DeleteFileLockSQL = `
DELETE FROM locks
WHERE held_by = ? AND lock_type = 'file' AND lock_target = ?
`
// CountInstanceLockSQL counts instance locks for a given address
CountInstanceLockSQL = `
SELECT COUNT(*) FROM locks
WHERE held_by = ? AND lock_type = 'instance'
`
// InsertInstanceLockSQL inserts or replaces an instance lock
InsertInstanceLockSQL = `
INSERT OR REPLACE INTO locks (held_by, lock_type, lock_target, locked_at)
VALUES (?, 'instance', ?, ?)
`
)
+54
View File
@@ -0,0 +1,54 @@
package common
import (
"time"
"google.golang.org/grpc/health/grpc_health_v1"
)
// CoreInstanceInfo represents a discovered Cline instance
// This is the canonical definition used across all CLI packages
type CoreInstanceInfo struct {
// Full core address including port
Address string `json:"address"`
// Host bridge service address that core holds (host is ALWAYS running on localhost FYI)
HostServiceAddress string `json:"host_port"`
Status grpc_health_v1.HealthCheckResponse_ServingStatus `json:"status"`
LastSeen time.Time `json:"last_seen"`
ProcessPID int `json:"process_pid,omitempty"`
Version string `json:"version,omitempty"`
}
func (c *CoreInstanceInfo) CorePort() int {
_, port, _ := ParseHostPort(c.Address)
return port
}
func (c *CoreInstanceInfo) HostPort() int {
_, port, _ := ParseHostPort(c.HostServiceAddress)
return port
}
func (c *CoreInstanceInfo) StatusString() string {
return c.Status.String()
}
// LockRow represents a row in the locks table
type LockRow struct {
ID int64 `json:"id"`
HeldBy string `json:"held_by"`
LockType string `json:"lock_type"`
LockTarget string `json:"lock_target"`
LockedAt int64 `json:"locked_at"`
}
// InstancesOutput represents the JSON output format for instance listing
type InstancesOutput struct {
DefaultInstance string `json:"default_instance"`
CoreInstances []CoreInstanceInfo `json:"instances"`
}
type DefaultCoreInstance struct {
Address string `json:"default_instance"`
LastUpdated string `json:"last_updated"`
}
+159
View File
@@ -0,0 +1,159 @@
package common
import (
"context"
"fmt"
"net"
"strconv"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
// ParseHostPort parses a host:port address and returns the host and port separately
func ParseHostPort(address string) (string, int, error) {
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return "", 0, err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return "", 0, err
}
return host, port, nil
}
// IsLocalAddress checks if the given host is a local/loopback address
// Supports both IPv4 (localhost, 127.0.0.1) and IPv6 (::1) addresses
func IsLocalAddress(host string) bool {
// Handle common localhost names
if host == "localhost" {
return true
}
// Parse as IP and check if it's a loopback
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback()
}
return false
}
// PerformHealthCheck performs a gRPC health check on the given address
// Will return UNKNOWN if the service is unreachable (error)
func PerformHealthCheck(ctx context.Context, address string) (grpc_health_v1.HealthCheckResponse_ServingStatus, error) {
conn, err := grpc.DialContext(ctx, address, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return grpc_health_v1.HealthCheckResponse_UNKNOWN, err
}
defer conn.Close()
healthClient := grpc_health_v1.NewHealthClient(conn)
resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
if err != nil {
return grpc_health_v1.HealthCheckResponse_UNKNOWN, err
}
return resp.Status, nil
}
// It's healthy if we can reach it and it responds with SERVING
func IsInstanceHealthy(ctx context.Context, address string) bool {
status, err := PerformHealthCheck(ctx, address)
return err == nil && status == grpc_health_v1.HealthCheckResponse_SERVING
}
// It's (likely) our instance if we can reach it and it responds to health checks
func IsInstanceOurs(ctx context.Context, address string) bool {
_, err := PerformHealthCheck(ctx, address)
return err != nil
}
// (unreachable or not serving)
func IsInstanceStale(ctx context.Context, address string) (grpc_health_v1.HealthCheckResponse_ServingStatus, bool, error) {
status, err := PerformHealthCheck(ctx, address)
isStale := err != nil || status != grpc_health_v1.HealthCheckResponse_SERVING
return status, isStale, err
}
// IsPortAvailable checks if a port is available for binding
func IsPortAvailable(port int) bool {
address := fmt.Sprintf("localhost:%d", port)
listener, err := net.Listen("tcp", address)
if err != nil {
return false
}
listener.Close()
return true
}
// FindAvailablePortPair finds two available ports by letting the OS allocate them
func FindAvailablePortPair() (corePort, hostPort int, err error) {
coreListener, err := net.Listen("tcp", ":0")
if err != nil {
return 0, 0, err
}
defer coreListener.Close()
hostListener, err := net.Listen("tcp", ":0")
if err != nil {
return 0, 0, err
}
defer hostListener.Close()
corePort = coreListener.Addr().(*net.TCPAddr).Port
hostPort = hostListener.Addr().(*net.TCPAddr).Port
return corePort, hostPort, nil
}
// NormalizeAddressForGRPC converts address to host:port for grpc client with proper normalization
func NormalizeAddressForGRPC(address string) (string, error) {
host, port, err := ParseHostPort(address)
if err != nil {
return "", err
}
// Normalize local addresses to localhost for gRPC compatibility
if IsLocalAddress(host) {
return fmt.Sprintf("localhost:%d", port), nil
}
return address, nil
}
// RetryOperation performs an operation with retry logic
func RetryOperation(maxRetries int, timeoutPerAttempt time.Duration, operation func() error) error {
var lastErr error
for attempt := 1; attempt <= maxRetries; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), timeoutPerAttempt)
// Create a channel to capture the operation result
done := make(chan error, 1)
go func() {
done <- operation()
}()
select {
case err := <-done:
cancel()
if err == nil {
return nil // Success
}
lastErr = err
case <-ctx.Done():
cancel()
lastErr = ctx.Err()
}
// Add delay between attempts (except for the last one)
if attempt < maxRetries {
time.Sleep(1 * time.Second)
}
}
return fmt.Errorf("operation failed after %d attempts: %w", maxRetries, lastErr)
}
+351
View File
@@ -0,0 +1,351 @@
package hostbridge
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
proto "github.com/cline/grpc-go/host"
)
// diffSession represents an in-memory diff editing session
type diffSession struct {
originalPath string // File path from OpenDiff request
originalContent []byte // Original file content (for comparison)
currentContent []byte // Current modified content
lines []string // Current content split into lines
encoding string // File encoding (default: utf8)
}
// DiffService implements the proto.DiffServiceServer interface
type DiffService struct {
proto.UnimplementedDiffServiceServer
verbose bool
sessions *sync.Map // thread-safe: diffId -> *diffSession
counter *int64 // atomic counter for unique IDs
}
// NewDiffService creates a new DiffService
func NewDiffService(verbose bool) *DiffService {
counter := int64(0)
return &DiffService{
verbose: verbose,
sessions: &sync.Map{},
counter: &counter,
}
}
// generateDiffID creates a unique diff ID
func (s *DiffService) generateDiffID() string {
id := atomic.AddInt64(s.counter, 1)
return fmt.Sprintf("diff_%d_%d", os.Getpid(), id)
}
// splitLines splits content into lines, preserving line ending information
func splitLines(content string) []string {
if content == "" {
return []string{}
}
lines := []string{}
current := ""
for _, char := range content {
if char == '\n' {
lines = append(lines, current)
current = ""
} else if char != '\r' { // Skip \r characters, handle \r\n as \n
current += string(char)
}
}
// Add the last line if it doesn't end with newline
if current != "" {
lines = append(lines, current)
}
return lines
}
// joinLines joins lines back into content with newlines
func joinLines(lines []string) string {
if len(lines) == 0 {
return ""
}
return strings.Join(lines, "\n")
}
// OpenDiff opens a diff view for the specified file
func (s *DiffService) OpenDiff(ctx context.Context, req *proto.OpenDiffRequest) (*proto.OpenDiffResponse, error) {
if s.verbose {
log.Printf("OpenDiff called for path: %s", req.GetPath())
}
diffID := s.generateDiffID()
var originalContent []byte
// Check if file exists and read original content
if req.GetPath() != "" {
if _, err := os.Stat(req.GetPath()); err == nil {
// File exists, read its content
var readErr error
originalContent, readErr = ioutil.ReadFile(req.GetPath())
if readErr != nil {
return nil, fmt.Errorf("failed to read original file: %w", readErr)
}
} else {
// File doesn't exist, use empty content
originalContent = []byte{}
}
}
// Use provided content as the initial current content
currentContent := []byte(req.GetContent())
// Create the diff session
session := &diffSession{
originalPath: req.GetPath(),
originalContent: originalContent,
currentContent: currentContent,
lines: splitLines(req.GetContent()),
encoding: "utf8", // Default encoding
}
// Store the session
s.sessions.Store(diffID, session)
if s.verbose {
log.Printf("Created diff session: %s (original: %d bytes, current: %d bytes)",
diffID, len(originalContent), len(currentContent))
}
return &proto.OpenDiffResponse{
DiffId: &diffID,
}, nil
}
// GetDocumentText returns the current content of the diff document
func (s *DiffService) GetDocumentText(ctx context.Context, req *proto.GetDocumentTextRequest) (*proto.GetDocumentTextResponse, error) {
if s.verbose {
log.Printf("GetDocumentText called for diff ID: %s", req.GetDiffId())
}
sessionInterface, exists := s.sessions.Load(req.GetDiffId())
if !exists {
return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
}
session := sessionInterface.(*diffSession)
content := string(session.currentContent)
return &proto.GetDocumentTextResponse{
Content: &content,
}, nil
}
// ReplaceText replaces text in the diff document using line-based operations
func (s *DiffService) ReplaceText(ctx context.Context, req *proto.ReplaceTextRequest) (*proto.ReplaceTextResponse, error) {
if s.verbose {
log.Printf("ReplaceText called for diff ID: %s, lines %d-%d",
req.GetDiffId(), req.GetStartLine(), req.GetEndLine())
}
sessionInterface, exists := s.sessions.Load(req.GetDiffId())
if !exists {
return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
}
session := sessionInterface.(*diffSession)
startLine := int(req.GetStartLine())
endLine := int(req.GetEndLine())
newContent := req.GetContent()
// Validate line ranges
if startLine < 0 {
startLine = 0
}
if endLine < startLine {
endLine = startLine
}
// Split new content into lines
newLines := splitLines(newContent)
// Ensure we have enough lines in the current content
for len(session.lines) < endLine {
session.lines = append(session.lines, "")
}
// Replace the specified line range
if endLine > len(session.lines) {
// Extending beyond current content - append new lines
session.lines = append(session.lines[:startLine], newLines...)
} else {
// Replace within existing content
result := make([]string, 0, len(session.lines)-endLine+startLine+len(newLines))
result = append(result, session.lines[:startLine]...)
result = append(result, newLines...)
result = append(result, session.lines[endLine:]...)
session.lines = result
}
// Update current content
session.currentContent = []byte(joinLines(session.lines))
// Store the updated session
s.sessions.Store(req.GetDiffId(), session)
if s.verbose {
log.Printf("Updated diff session %s: %d lines, %d bytes",
req.GetDiffId(), len(session.lines), len(session.currentContent))
}
return &proto.ReplaceTextResponse{}, nil
}
// ScrollDiff scrolls the diff view to a specific line (no-op for CLI)
func (s *DiffService) ScrollDiff(ctx context.Context, req *proto.ScrollDiffRequest) (*proto.ScrollDiffResponse, error) {
if s.verbose {
log.Printf("ScrollDiff called for diff ID: %s, line: %d", req.GetDiffId(), req.GetLine())
}
// Verify session exists
if _, exists := s.sessions.Load(req.GetDiffId()); !exists {
return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
}
// In a CLI implementation, scrolling is a no-op
// In a GUI implementation, this would scroll the view to the specified line
return &proto.ScrollDiffResponse{}, nil
}
// TruncateDocument truncates the diff document at the specified line
func (s *DiffService) TruncateDocument(ctx context.Context, req *proto.TruncateDocumentRequest) (*proto.TruncateDocumentResponse, error) {
if s.verbose {
log.Printf("TruncateDocument called for diff ID: %s, end line: %d", req.GetDiffId(), req.GetEndLine())
}
sessionInterface, exists := s.sessions.Load(req.GetDiffId())
if !exists {
return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
}
session := sessionInterface.(*diffSession)
endLine := int(req.GetEndLine())
// Truncate lines at the specified position
if endLine >= 0 && endLine < len(session.lines) {
session.lines = session.lines[:endLine]
session.currentContent = []byte(joinLines(session.lines))
// Store the updated session
s.sessions.Store(req.GetDiffId(), session)
if s.verbose {
log.Printf("Truncated diff session %s to %d lines", req.GetDiffId(), len(session.lines))
}
}
return &proto.TruncateDocumentResponse{}, nil
}
// SaveDocument saves the diff document to the original file
func (s *DiffService) SaveDocument(ctx context.Context, req *proto.SaveDocumentRequest) (*proto.SaveDocumentResponse, error) {
if s.verbose {
log.Printf("SaveDocument called for diff ID: %s", req.GetDiffId())
}
sessionInterface, exists := s.sessions.Load(req.GetDiffId())
if !exists {
return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
}
session := sessionInterface.(*diffSession)
if session.originalPath == "" {
return nil, fmt.Errorf("no file path specified for diff session: %s", req.GetDiffId())
}
// Create parent directories if they don't exist
dir := filepath.Dir(session.originalPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create directories: %w", err)
}
// Write the current content to the original file
if err := ioutil.WriteFile(session.originalPath, session.currentContent, 0644); err != nil {
return nil, fmt.Errorf("failed to save file: %w", err)
}
if s.verbose {
log.Printf("Saved diff session %s to file: %s (%d bytes)",
req.GetDiffId(), session.originalPath, len(session.currentContent))
}
return &proto.SaveDocumentResponse{}, nil
}
// CloseAllDiffs closes all diff views and cleans up all sessions
func (s *DiffService) CloseAllDiffs(ctx context.Context, req *proto.CloseAllDiffsRequest) (*proto.CloseAllDiffsResponse, error) {
if s.verbose {
log.Printf("CloseAllDiffs called")
}
var count int64
s.sessions.Range(func(key, value any) bool {
// Optional: attempt to close if the value supports it
if c, ok := value.(interface{ Close() error }); ok {
_ = c.Close() // best-effort; ignore error
}
s.sessions.Delete(key)
atomic.AddInt64(&count, 1)
return true
})
if s.verbose {
log.Printf("Closed %d diff sessions", count)
}
return &proto.CloseAllDiffsResponse{}, nil
}
// OpenMultiFileDiff displays a diff view comparing before/after states for multiple files
func (s *DiffService) OpenMultiFileDiff(ctx context.Context, req *proto.OpenMultiFileDiffRequest) (*proto.OpenMultiFileDiffResponse, error) {
if s.verbose {
log.Printf("OpenMultiFileDiff called with title: %s, %d files", req.GetTitle(), len(req.GetDiffs()))
}
// In a CLI implementation, we could display the diffs to console
// For now, we'll just log the information
title := req.GetTitle()
if title == "" {
title = "Multi-file diff"
}
if s.verbose {
log.Printf("=== %s ===", title)
for i, diff := range req.GetDiffs() {
log.Printf("File %d: %s", i+1, diff.GetFilePath())
log.Printf(" Left content: %d bytes", len(diff.GetLeftContent()))
log.Printf(" Right content: %d bytes", len(diff.GetRightContent()))
}
}
// In a more sophisticated CLI implementation, we could:
// 1. Use a diff library to generate unified diffs
// 2. Display them with colors
// 3. Allow navigation between files
// For now, this is a no-op that just acknowledges the request
return &proto.OpenMultiFileDiffResponse{}, nil
}
+39
View File
@@ -0,0 +1,39 @@
package hostbridge
import (
"log"
"github.com/cline/grpc-go/host"
)
// WatchService implements the host.WatchServiceServer interface
type WatchService struct {
host.UnimplementedWatchServiceServer
coreAddress string
verbose bool
}
// NewWatchService creates a new WatchService
func NewWatchService(coreAddress string, verbose bool) *WatchService {
return &WatchService{
coreAddress: coreAddress,
verbose: verbose,
}
}
// SubscribeToFile subscribes to file change notifications
func (s *WatchService) SubscribeToFile(req *host.SubscribeToFileRequest, stream host.WatchService_SubscribeToFileServer) error {
if s.verbose {
log.Printf("SubscribeToFile called for path: %s", req.GetPath())
}
// For console implementation, we'll just log that we would watch the file
// In a real implementation, we'd use fsnotify or similar to watch file changes
log.Printf("[Cline] Would watch file: %s", req.GetPath())
// Keep the stream open but don't send any events for now
// In a real implementation, we'd send FileChangeEvent messages when files change
<-stream.Context().Done()
return nil
}
+63
View File
@@ -0,0 +1,63 @@
package hostbridge
import (
"context"
"fmt"
"log"
proto "github.com/cline/grpc-go/host"
)
// WindowService implements the proto.WindowServiceServer interface
type WindowService struct {
proto.UnimplementedWindowServiceServer
coreAddress string
verbose bool
}
// NewWindowService creates a new WindowService
func NewWindowService(coreAddress string, verbose bool) *WindowService {
return &WindowService{
coreAddress: coreAddress,
verbose: verbose,
}
}
// ShowTextDocument opens a text document for viewing/editing
func (s *WindowService) ShowTextDocument(ctx context.Context, req *proto.ShowTextDocumentRequest) (*proto.TextEditorInfo, error) {
if s.verbose {
log.Printf("ShowTextDocument called for path: %s", req.GetPath())
}
// For console implementation, we'll just log that we would open the document
fmt.Printf("[Cline] Would open document: %s\n", req.GetPath())
return &proto.TextEditorInfo{
DocumentPath: req.GetPath(),
IsActive: true,
}, nil
}
// ShowOpenDialogue shows a file open dialog
func (s *WindowService) ShowOpenDialogue(ctx context.Context, req *proto.ShowOpenDialogueRequest) (*proto.SelectedResources, error) {
if s.verbose {
log.Printf("ShowOpenDialogue called")
}
// For console implementation, return empty list (user cancelled)
return &proto.SelectedResources{
Paths: []string{},
}, nil
}
// ShowMessage displays a message to the user
func (s *WindowService) ShowMessage(ctx context.Context, req *proto.ShowMessageRequest) (*proto.SelectedResponse, error) {
if s.verbose {
log.Printf("ShowMessage called: %s", req.GetMessage())
}
// Display message to console
fmt.Printf("[Cline] %s\n", req.GetMessage())
return &proto.SelectedResponse{}, nil
}
+66
View File
@@ -0,0 +1,66 @@
package hostbridge
import (
"context"
"log"
"os"
"github.com/cline/grpc-go/host"
)
// WorkspaceService implements the host.WorkspaceServiceServer interface
type WorkspaceService struct {
host.UnimplementedWorkspaceServiceServer
coreAddress string
verbose bool
}
// NewWorkspaceService creates a new WorkspaceService
func NewWorkspaceService(coreAddress string, verbose bool) *WorkspaceService {
return &WorkspaceService{
coreAddress: coreAddress,
verbose: verbose,
}
}
// GetWorkspacePaths returns the workspace directory paths
func (s *WorkspaceService) GetWorkspacePaths(ctx context.Context, req *host.GetWorkspacePathsRequest) (*host.GetWorkspacePathsResponse, error) {
if s.verbose {
log.Printf("GetWorkspacePaths called")
}
// Get current working directory as the workspace
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
return &host.GetWorkspacePathsResponse{
Paths: []string{cwd},
}, nil
}
// SaveOpenDocumentIfDirty saves an open document if it has unsaved changes
func (s *WorkspaceService) SaveOpenDocumentIfDirty(ctx context.Context, req *host.SaveOpenDocumentIfDirtyRequest) (*host.SaveOpenDocumentIfDirtyResponse, error) {
if s.verbose {
log.Printf("SaveOpenDocumentIfDirty called for path: %s", req.GetPath())
}
// For console implementation, we'll assume the document is already saved
// In a real implementation, we'd check if the file has unsaved changes
return &host.SaveOpenDocumentIfDirtyResponse{
WasSaved: false, // Assume no changes to save
}, nil
}
// GetDiagnostics returns diagnostic information for a file
func (s *WorkspaceService) GetDiagnostics(ctx context.Context, req *host.GetDiagnosticsRequest) (*host.GetDiagnosticsResponse, error) {
if s.verbose {
log.Printf("GetDiagnostics called for path: %s", req.GetPath())
}
// For console implementation, return empty diagnostics
return &host.GetDiagnosticsResponse{
Diagnostics: []*host.Diagnostic{},
}, nil
}
+98
View File
@@ -0,0 +1,98 @@
package hostbridge
import (
"context"
"log"
"github.com/cline/grpc-go/cline"
"github.com/cline/grpc-go/host"
)
// Global shutdown channel - simple approach
var globalShutdownCh chan struct{}
func init() {
globalShutdownCh = make(chan struct{})
}
// EnvService implements the host.EnvServiceServer interface
type EnvService struct {
host.UnimplementedEnvServiceServer
verbose bool
}
// NewEnvService creates a new EnvService
func NewEnvService(verbose bool) *EnvService {
return &EnvService{
verbose: verbose,
}
}
// ClipboardWriteText writes text to the system clipboard
func (s *EnvService) ClipboardWriteText(ctx context.Context, req *cline.StringRequest) (*cline.Empty, error) {
if s.verbose {
log.Printf("ClipboardWriteText called with: %s", req.GetValue())
}
// TODO: Implement actual clipboard functionality
// For now, just return success
return &cline.Empty{}, nil
}
// ClipboardReadText reads text from the system clipboard
func (s *EnvService) ClipboardReadText(ctx context.Context, req *cline.EmptyRequest) (*cline.String, error) {
if s.verbose {
log.Printf("ClipboardReadText called")
}
// TODO: Implement actual clipboard functionality
// For now, return empty string
return &cline.String{
Value: "",
}, nil
}
// GetMachineId returns a stable machine identifier for telemetry distinctId purposes
func (s *EnvService) GetMachineId(ctx context.Context, req *cline.EmptyRequest) (*cline.String, error) {
if s.verbose {
log.Printf("GetMachineId called")
}
// TODO: Implement actual machine ID functionality
// For now, return empty string
return &cline.String{
Value: "",
}, nil
}
// GetHostVersion returns the host platform name and version
func (s *EnvService) GetHostVersion(ctx context.Context, req *cline.EmptyRequest) (*host.GetHostVersionResponse, error) {
if s.verbose {
log.Printf("GetHostVersion called")
}
// TODO: Implement actual host version functionality
// For now, return empty response
return &host.GetHostVersionResponse{}, nil
}
// Shutdown initiates a graceful shutdown of the host bridge service
func (s *EnvService) Shutdown(ctx context.Context, req *cline.EmptyRequest) (*cline.Empty, error) {
if s.verbose {
log.Printf("Shutdown requested via RPC")
}
// Trigger global shutdown signal
select {
case globalShutdownCh <- struct{}{}:
if s.verbose {
log.Printf("Shutdown signal sent successfully")
}
default:
if s.verbose {
log.Printf("Shutdown signal already pending")
}
}
return &cline.Empty{}, nil
}
+113
View File
@@ -0,0 +1,113 @@
package hostbridge
import (
"context"
"fmt"
"log"
"net"
"github.com/cline/grpc-go/host"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
)
// GrpcServer provides gRPC hostbridge functionality
type GrpcServer struct {
port int
verbose bool
server *grpc.Server
shutdownCh chan struct{}
}
// NewGrpcServer creates a new GrpcServer
func NewGrpcServer(port int, verbose bool) *GrpcServer {
return &GrpcServer{
port: port,
verbose: verbose,
shutdownCh: make(chan struct{}),
}
}
// Start starts the gRPC hostbridge server
func (s *GrpcServer) Start(ctx context.Context) error {
if s.verbose {
log.Printf("Starting gRPC hostbridge server on port %d", s.port)
}
// Create listener
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port))
if err != nil {
return fmt.Errorf("failed to listen on port %d: %w", s.port, err)
}
// Create gRPC server
s.server = grpc.NewServer()
// Register health service
healthServer := health.NewServer()
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(s.server, healthServer)
// Register services
workspaceService := NewSimpleWorkspaceService(s.verbose)
host.RegisterWorkspaceServiceServer(s.server, workspaceService)
windowService := NewWindowService(s.verbose)
host.RegisterWindowServiceServer(s.server, windowService)
diffService := NewDiffService(s.verbose)
host.RegisterDiffServiceServer(s.server, diffService)
envService := NewEnvService(s.verbose)
host.RegisterEnvServiceServer(s.server, envService)
if s.verbose {
log.Printf("Registered HealthService")
log.Printf("Registered WorkspaceService")
log.Printf("Registered WindowService")
log.Printf("Registered DiffService")
log.Printf("Registered EnvService")
}
// Start server in goroutine
go func() {
if s.verbose {
log.Printf("gRPC server listening on :%d", s.port)
}
if err := s.server.Serve(lis); err != nil {
log.Printf("gRPC server error: %v", err)
}
}()
// Wait for context cancellation or global shutdown signal
select {
case <-ctx.Done():
if s.verbose {
log.Println("Context cancelled, shutting down gRPC hostbridge server...")
}
case <-globalShutdownCh:
if s.verbose {
log.Println("Shutdown requested via RPC, shutting down gRPC hostbridge server...")
}
}
// Graceful shutdown
s.server.GracefulStop()
if s.verbose {
log.Println("gRPC hostbridge server stopped")
}
return nil
}
// TriggerShutdown triggers a graceful shutdown of the server
func (s *GrpcServer) TriggerShutdown() {
select {
case s.shutdownCh <- struct{}{}:
// Shutdown signal sent
default:
// Channel already has a signal or is closed
}
}
+43
View File
@@ -0,0 +1,43 @@
package hostbridge
import (
"context"
"fmt"
"log"
)
// Simple implementations that don't rely on proto files for now
// This allows us to test the basic hostbridge structure
// SimpleService provides basic hostbridge functionality
type SimpleService struct {
coreAddress string
verbose bool
}
// NewSimpleService creates a new SimpleService
func NewSimpleService(coreAddress string, verbose bool) *SimpleService {
return &SimpleService{
coreAddress: coreAddress,
verbose: verbose,
}
}
// Start starts the simple hostbridge service
func (s *SimpleService) Start(ctx context.Context) error {
if s.verbose {
log.Printf("Starting simple hostbridge service (connecting to core at %s)", s.coreAddress)
}
// For now, just log that we're running
fmt.Printf("[Cline Host Bridge] Service started on core address: %s\n", s.coreAddress)
// Keep running until context is cancelled
<-ctx.Done()
if s.verbose {
log.Println("Simple hostbridge service stopped")
}
return nil
}
+65
View File
@@ -0,0 +1,65 @@
package hostbridge
import (
"context"
"log"
"os"
"github.com/cline/grpc-go/cline"
"github.com/cline/grpc-go/host"
)
// SimpleWorkspaceService implements a basic workspace service without complex dependencies
type SimpleWorkspaceService struct {
host.UnimplementedWorkspaceServiceServer
verbose bool
}
// NewSimpleWorkspaceService creates a new SimpleWorkspaceService
func NewSimpleWorkspaceService(verbose bool) *SimpleWorkspaceService {
return &SimpleWorkspaceService{
verbose: verbose,
}
}
// GetWorkspacePaths returns the workspace directory paths
func (s *SimpleWorkspaceService) GetWorkspacePaths(ctx context.Context, req *host.GetWorkspacePathsRequest) (*host.GetWorkspacePathsResponse, error) {
if s.verbose {
log.Printf("GetWorkspacePaths called")
}
// Get current working directory as the workspace
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
return &host.GetWorkspacePathsResponse{
Paths: []string{cwd},
}, nil
}
// SaveOpenDocumentIfDirty saves an open document if it has unsaved changes
func (s *SimpleWorkspaceService) SaveOpenDocumentIfDirty(ctx context.Context, req *host.SaveOpenDocumentIfDirtyRequest) (*host.SaveOpenDocumentIfDirtyResponse, error) {
if s.verbose {
log.Printf("SaveOpenDocumentIfDirty called for path: %s", req.GetFilePath())
}
// For console implementation, we'll assume the document is already saved
wasSaved := false
return &host.SaveOpenDocumentIfDirtyResponse{
WasSaved: &wasSaved,
}, nil
}
// GetDiagnostics returns diagnostic information for a file - simplified version
func (s *SimpleWorkspaceService) GetDiagnostics(ctx context.Context, req *host.GetDiagnosticsRequest) (*host.GetDiagnosticsResponse, error) {
if s.verbose {
log.Printf("GetDiagnostics called")
}
// For console implementation, return empty diagnostics
return &host.GetDiagnosticsResponse{
FileDiagnostics: []*cline.FileDiagnostics{},
}, nil
}
+129
View File
@@ -0,0 +1,129 @@
package hostbridge
import (
"context"
"fmt"
"log"
proto "github.com/cline/grpc-go/host"
)
// WindowService implements the proto.WindowServiceServer interface
type WindowService struct {
proto.UnimplementedWindowServiceServer
verbose bool
}
// NewWindowService creates a new WindowService
func NewWindowService(verbose bool) *WindowService {
return &WindowService{
verbose: verbose,
}
}
// ShowTextDocument opens a text document for viewing/editing
func (s *WindowService) ShowTextDocument(ctx context.Context, req *proto.ShowTextDocumentRequest) (*proto.TextEditorInfo, error) {
if s.verbose {
log.Printf("ShowTextDocument called for path: %s", req.GetPath())
}
// For console implementation, we'll just log that we would open the document
fmt.Printf("[Cline] Would open document: %s\n", req.GetPath())
return &proto.TextEditorInfo{
DocumentPath: req.GetPath(),
IsActive: true,
}, nil
}
// ShowOpenDialogue shows a file open dialog
func (s *WindowService) ShowOpenDialogue(ctx context.Context, req *proto.ShowOpenDialogueRequest) (*proto.SelectedResources, error) {
if s.verbose {
log.Printf("ShowOpenDialogue called")
}
// For console implementation, return empty list (user cancelled)
return &proto.SelectedResources{
Paths: []string{},
}, nil
}
// ShowMessage displays a message to the user
func (s *WindowService) ShowMessage(ctx context.Context, req *proto.ShowMessageRequest) (*proto.SelectedResponse, error) {
if s.verbose {
log.Printf("ShowMessage called: %s", req.GetMessage())
}
// Display message to console
fmt.Printf("[Cline] %s\n", req.GetMessage())
return &proto.SelectedResponse{}, nil
}
// ShowInputBox shows an input dialog to the user
func (s *WindowService) ShowInputBox(ctx context.Context, req *proto.ShowInputBoxRequest) (*proto.ShowInputBoxResponse, error) {
if s.verbose {
log.Printf("ShowInputBox called: %s", req.GetTitle())
}
// For console implementation, return empty response (user cancelled)
return &proto.ShowInputBoxResponse{}, nil
}
// ShowSaveDialog shows a save file dialog
func (s *WindowService) ShowSaveDialog(ctx context.Context, req *proto.ShowSaveDialogRequest) (*proto.ShowSaveDialogResponse, error) {
if s.verbose {
log.Printf("ShowSaveDialog called")
}
// For console implementation, return empty response (user cancelled)
return &proto.ShowSaveDialogResponse{}, nil
}
// OpenFile opens a file in the editor
func (s *WindowService) OpenFile(ctx context.Context, req *proto.OpenFileRequest) (*proto.OpenFileResponse, error) {
if s.verbose {
log.Printf("OpenFile called for path: %s", req.GetFilePath())
}
// For console implementation, just log that we would open the file
fmt.Printf("[Cline] Would open file: %s\n", req.GetFilePath())
return &proto.OpenFileResponse{}, nil
}
// GetOpenTabs returns a list of currently open tabs
func (s *WindowService) GetOpenTabs(ctx context.Context, req *proto.GetOpenTabsRequest) (*proto.GetOpenTabsResponse, error) {
if s.verbose {
log.Printf("GetOpenTabs called")
}
// For console implementation, return empty list
return &proto.GetOpenTabsResponse{
Paths: []string{},
}, nil
}
// GetVisibleTabs returns a list of currently visible tabs
func (s *WindowService) GetVisibleTabs(ctx context.Context, req *proto.GetVisibleTabsRequest) (*proto.GetVisibleTabsResponse, error) {
if s.verbose {
log.Printf("GetVisibleTabs called")
}
// For console implementation, return empty list
return &proto.GetVisibleTabsResponse{
Paths: []string{},
}, nil
}
// GetActiveEditor returns information about the current active editor
func (s *WindowService) GetActiveEditor(ctx context.Context, req *proto.GetActiveEditorRequest) (*proto.GetActiveEditorResponse, error) {
if s.verbose {
log.Printf("GetActiveEditor called")
}
// Return empty response (no active file)
return &proto.GetActiveEditorResponse{
FilePath: nil,
}, nil
}
+84 -31
View File
@@ -25,15 +25,15 @@
},
"styling": {
"eyebrows": "breadcrumbs",
"codeblocks": "system"
"codeblocks": "system",
"css": "styles.css"
},
"appearance": {
"default": "system",
"strict": false
},
"fonts": {
"family": "Roboto",
"weight": 400
"family": "Roboto"
},
"navbar": {
"links": [
@@ -57,30 +57,30 @@
{
"group": "Getting Started",
"pages": [
"getting-started/for-new-coders",
"getting-started/what-is-cline",
"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"
{
"group": "For New Coders",
"pages": [
"getting-started/for-new-coders",
"getting-started/installing-dev-essentials"
]
}
]
},
{
"group": "Improving Your Prompting Skills",
"pages": ["prompting/prompt-engineering-guide", "prompting/cline-memory-bank"]
"pages": [
"prompting/prompt-engineering-guide",
"prompting/cline-memory-bank"
]
},
{
"group": "Features",
"pages": [
"features/auto-approve",
"features/checkpoints",
"features/cline-rules",
"features/drag-and-drop",
"features/plan-and-act",
"features/slash-commands/workflows",
"features/editing-messages",
{
"group": "@ Mentions",
"pages": [
@@ -92,15 +92,10 @@
"features/at-mentions/url-mentions"
]
},
{
"group": "Slash Commands",
"pages": [
"features/slash-commands/new-task",
"features/slash-commands/new-rule",
"features/slash-commands/smol",
"features/slash-commands/report-bug"
]
},
"features/auto-approve",
"features/auto-compact",
"features/checkpoints",
"features/cline-rules",
{
"group": "Commands & Shortcuts",
"pages": [
@@ -110,7 +105,31 @@
"features/commands-and-shortcuts/git-integration",
"features/commands-and-shortcuts/keyboard-shortcuts"
]
}
},
{
"group": "Customization",
"pages": [
"features/customization/opening-cline-in-sidebar",
"features/customization/disable-terminal-pagers"
]
},
"features/dictation",
"features/drag-and-drop",
"features/editing-messages",
"features/focus-chain",
"features/plan-and-act",
{
"group": "Slash Commands",
"pages": [
"features/slash-commands/new-task",
"features/slash-commands/new-rule",
"features/slash-commands/smol",
"features/slash-commands/report-bug",
"features/slash-commands/deep-planning"
]
},
"features/slash-commands/workflows",
"features/yolo-mode"
]
},
{
@@ -147,19 +166,33 @@
"pages": [
"provider-config/anthropic",
"provider-config/claude-code",
"provider-config/aws-bedrock-with-credentials-authentication",
"provider-config/aws-bedrock-with-profile-authentication",
{
"group": "AWS Bedrock",
"pages": [
"provider-config/aws-bedrock/api-key",
"provider-config/aws-bedrock/iam-credentials",
"provider-config/aws-bedrock/cli-profile"
]
},
"provider-config/gcp-vertex-ai",
"provider-config/litellm-and-cline-using-codestral",
"provider-config/vscode-language-model-api",
"provider-config/xai-grok",
"provider-config/mistral-ai",
"provider-config/deepseek",
"provider-config/groq",
"provider-config/cerebras",
"provider-config/doubao",
"provider-config/fireworks",
"provider-config/zai",
"provider-config/ollama",
"provider-config/openai",
"provider-config/openai-compatible",
"provider-config/openrouter",
"provider-config/requesty"
"provider-config/sap-aicore",
"provider-config/vercel-ai-gateway",
"provider-config/requesty",
"provider-config/baseten"
]
},
{
@@ -172,11 +205,16 @@
},
{
"group": "Troubleshooting",
"pages": ["troubleshooting/terminal-quick-fixes", "troubleshooting/terminal-integration-guide"]
"pages": [
"troubleshooting/terminal-quick-fixes",
"troubleshooting/terminal-integration-guide"
]
},
{
"group": "More Info",
"pages": ["more-info/telemetry"]
"pages": [
"more-info/telemetry"
]
}
]
},
@@ -187,10 +225,25 @@
"discord": "https://discord.gg/cline"
}
},
"anchors": [
{
"name": "What is Cline",
"icon": "house",
"url": "getting-started/what-is-cline"
}
],
"redirects": [
{
"source": "/getting-started/installing-cline-jetbrains",
"destination": "/getting-started/installing-cline"
}
],
"search": {
"prompt": "Search Cline documentation..."
},
"contextual": {
"options": ["copy"]
"options": [
"copy"
]
}
}
@@ -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)
@@ -56,7 +56,7 @@ Cline is your AI assistant that can:
## Available Tools
For the most up-to-date implementation details, you can view the full source code in the [Cline repository](https://github.com/cline/cline/blob/main/src/core/Cline.ts).
For the most up-to-date implementation details, you can view the full source code in the [Cline repository](https://github.com/cline/cline/blob/main/src/core/prompts/system-prompt/tools).
Cline has access to the following tools for various tasks:
@@ -105,11 +105,11 @@ Below is an example `.clinerules` file focused specifically on using `new_task`
````markdown
# You MUST use the `new_task` tool: Task Handoff Strategy Guide
**⚠️ CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THESE GUIDELINES ⚠️**
**CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THESE GUIDELINES**
This guide provides **MANDATORY** instructions for effectively breaking down complex tasks and implementing a smooth handoff process between tasks. You **MUST** follow these guidelines to ensure continuity, context preservation, and efficient task completion.
## ⚠️ CONTEXT WINDOW MONITORING - MANDATORY ACTION REQUIRED ⚠️
## CONTEXT WINDOW MONITORING - MANDATORY ACTION REQUIRED
You **MUST** monitor the context window usage displayed in the environment details. When usage exceeds 50% of the available context window, you **MUST** initiate a task handoff using the `new_task` tool.
@@ -370,7 +370,7 @@ You **MUST** initiate task handoffs in these scenarios:
5. **When switching focus areas** within a larger project
6. **When different expertise** might be beneficial for different parts of the task
**⚠️ FINAL REMINDER - CRITICAL INSTRUCTION ⚠️**
**FINAL REMINDER - CRITICAL INSTRUCTION**
You **MUST** monitor the context window usage in the environment details section. When it exceeds 50% (e.g., "105,000 / 200,000 tokens (53%)"), you **MUST** proactively initiate the task handoff process using the `ask_followup_question` tool followed by the `new_task` tool. You MUST use the `new_task` tool.
+75
View File
@@ -0,0 +1,75 @@
---
title: "Automatic Context Summarization"
sidebarTitle: "Auto Compact"
---
When your conversation approaches the model's context window limit, Cline automatically summarizes it to free up space and keep working.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/condensing.png"
alt="Auto-compact feature condensing conversation context"
/>
</Frame>
## How It Works
Cline monitors token usage during your conversation. When you're getting close to the limit, he:
1. Creates a comprehensive summary of everything that's happened
2. Preserves all the technical details, code changes, and decisions
3. Replaces the conversation history with the summary
4. Continues exactly where he left off
You'll see a summarization tool call when this happens, showing the total cost like any other api call in the chat view.
## Why This Matters
Previously, Cline would truncate older messages when hitting context limits. This meant losing important context from earlier in the conversation.
Now with summarization:
- All technical decisions and code patterns are preserved
- File changes and project context remain intact
- Cline remembers everything he's done
- You can work on much larger projects without interruption
<Tip>
Context Summarization synergizes beautifully with [Focus Chain](/features/focus-chain). When Focus Chain is enabled, todo lists persist across summarizations. This means Cline can work on long-horizon tasks that span multiple context windows while staying on track with the todo list guiding him through each reset.
</Tip>
## Technical Details
The summarization happens through your configured API provider using the same model you're already using. It leverages prompt caching to minimize costs.
1. Cline uses a [summarization prompt](https://github.com/cline/cline/blob/main/src/core/prompts/contextManagement.ts) to request a summary of the conversation.
2. Once the summary is generated, Cline replaces the conversation history with a [continuation prompt](https://github.com/cline/cline/blob/main/src/core/prompts/contextManagement.ts#L69) that asks Cline to keep working and provides the summary as context.
Different models have different context window thresholds for when auto-summarization kicks in. You can see how thresholds are determined in [context-window-utils.ts](https://github.com/cline/cline/blob/main/src/core/context/context-management/context-window-utils.ts).
## Cost Considerations
Summarization leverages your existing prompt cache from the conversation, so it costs about the same as any other tool call.
Since most input tokens are already cached, you're primarily paying for the summary generation (output tokens), making it very cost-effective.
## Restoring Context with Checkpoints
You can use [checkpoints](/features/checkpoints) to restore your task state from before a summarization occurred. This means you never truly lose context - you can always roll back to previous versions of your conversation.
<Note>
Editing a message before a summarization tool call will work similarly to a checkpoint, allowing you to restore the conversation to that point.
</Note>
## Next Generation Model Support
Auto Compact uses advanced LLM-based summarization which we've found works significantly better for next-generation models. We currently support this feature for the following models:
- **Claude 4 series**
- **Gemini 2.5 series**
- **GPT-5**
- **Grok 4**
<Note>
When using other models, Cline automatically falls back to the standard rule-based context truncation method, even if Auto Compact is enabled in settings.
</Note>
+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.
@@ -21,7 +21,6 @@ While Cline has only a few default keyboard shortcuts, you can assign your own s
| Command ID | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`cline.openInNewTab`](/features/commands-and-shortcuts/overview) | Opens Cline in a new editor tab |
| [`cline.addToChat`](/features/commands-and-shortcuts/code-commands) | Adds selected code to Cline chat |
| [`cline.addTerminalOutputToChat`](/features/commands-and-shortcuts/terminal-integration) | Adds terminal output to Cline |
| `cline.focusChatInput` | Focuses the Cline chat input field |
@@ -0,0 +1,79 @@
---
title: "Disable Terminal Pagers During Cline Sessions"
description: "Make CLI output non-interactive when Cline runs commands by detecting the CLINE_ACTIVE environment variable and disabling pagers like less."
---
Many CLI tools (like Git) use a pager such as `less` for interactive, scrollable output. When Cline runs commands in your terminal, that interactivity gets in the way — the pager can pause on the first page and block progress. You can configure your shell so that when a terminal is spawned by Cline, pagers are disabled and output streams through normally.
## How it works
Cline sets an environment variable for terminals it opens to run commands:
- `CLINE_ACTIVE` — non-empty when the shell is running under Cline
You can detect this variable in your shell startup file and adjust environment variables or aliases only for Cline-run sessions. This keeps your normal interactive terminals unchanged.
## Quick setup (Zsh/Bash)
Add the following to your `~/.zshrc`, `~/.bashrc`, or `~/.bash_profile`:
```bash
# Disable pagers when the terminal is launched by Cline
if [[ -n "$CLINE_ACTIVE" ]]; then
export PAGER=cat
export GIT_PAGER=cat
export SYSTEMD_PAGER=cat
export LESS="-FRX"
fi
```
<Note>
- `PAGER=cat` ensures generic pager-aware tools print directly to stdout
- `GIT_PAGER=cat` prevents Git from invoking `less`
- `SYSTEMD_PAGER=cat` disables paging in systemd tools (if present)
- `LESS="-FRX"` makes `less` behave more like streaming output if a tool still calls it
</Note>
This configuration only applies when `CLINE_ACTIVE` is set, so your normal terminals keep their usual interactive behavior.
## Verify
- Open a task in Cline that runs terminal commands and check:
- `echo "$CLINE_ACTIVE"` prints a non-empty value
- `git log` or other long outputs should stream without pausing
- If changes don't take effect:
- Make sure you updated the correct startup file for your shell
- Restart VS Code/Cursor so integrated terminals reload your shell config
- Confirm your terminal profile sources your `~/.zshrc` or `~/.bashrc`
## Optional tweaks
- Prefer command-line options when you don't want to rely on env vars:
```bash
# One-off usage (no aliases)
git --no-pager log -n 50 --decorate --oneline
systemctl --no-pager status nginx
journalctl --no-pager -u nginx -n 200
less -FRX README.md
```
- You can also override paging via shell aliases scoped to Cline sessions using options rather than env vars:
```bash
if [[ -n "$CLINE_ACTIVE" ]]; then
# Make 'less' non-interactive by default
alias less='less -FRX'
# Disable paging for common tools via CLI flags
alias git='command git --no-pager'
alias systemctl='command systemctl --no-pager'
alias journalctl='command journalctl --no-pager'
fi
```
- If you prefer environment variables, many CLIs also respect a generic or tool-specific pager variable:
- Git: `GIT_PAGER=cat`
- Systemd: `SYSTEMD_PAGER=cat`
- Man pages: `MANPAGER=cat` (not typically needed for Cline-driven commands)
- Aliases affect the current interactive shell, while environment variables propagate to child processes. Choose the approach that best fits your workflow.
@@ -0,0 +1,60 @@
---
title: "Opening Cline in the Right Sidebar"
description: "Learn how to open Cline in the right sidebar in VS Code and Cursor"
---
By default, when you first install Cline, it appears in VS Code's left sidebar alongside your file explorer and other extensions. However, for a better coding experience, we recommend moving Cline to the right sidebar. This allows you to keep your project files visible in the left sidebar while chatting with Cline on the right, giving you full visibility of your codebase as Cline works on your project.
## VS Code
To open Cline in the right sidebar:
<Steps>
<Step title="Align Extension View">
Make sure your extension view is aligned vertically to the left
</Step>
<Step title="Open Right Side View">
Click the button that opens the right side panel in VS Code (typically used to open GitHub Copilot chat). Optionally use the `Option + CMD/Ctrl + B` shortcut.
</Step>
<Step title="Drag Cline Icon">
Drag the Cline icon over to the nav panel at the top of that right view
</Step>
</Steps>
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/vscode_right_view.gif"
alt="VS Code Right Sidebar Setup"
/>
</Frame>
## Cursor
To open Cline in the right sidebar:
<Steps>
<Step title="Align Extensions">
Cursor uses a horizontal activity bar by default to optimize space for the AI chat interface ([see here for details](https://cursor.com/docs/configuration/migrations/vscode#activity-bar-orientation)). To switch to vertical:
1. Open the Command Palette (`CMD/Ctrl + Shift + P`)
2. Search for "Preferences: Open Settings (UI)"
3. Search for `workbench.activityBar.orientation`
4. Set the value to `vertical`
5. Restart Cursor for the changes to take effect
</Step>
<Step title="Open Agent Panel">
Click the Cursor cube icon button that opens Cursor's agent (right side view panel)
</Step>
<Step title="Drag to Three Dots">
Drag the Cline icon directly onto the three dots button - it doesn't work if you just drag it to the top, it has to be the three dots
</Step>
</Steps>
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/cursor-side-bar.gif"
alt="Cursor Right Sidebar Setup"
/>
</Frame>
Once set up, Cline will load on the right side and you can use it as normal.
+149
View File
@@ -0,0 +1,149 @@
---
title: "Dictation"
description: "Communicate with Cline using your voice for faster, more natural AI collaboration"
---
Dictation transforms how you work with AI. Instead of typing out complex thoughts, you speak naturally and share your complete intent. This isn't just about speed - though voice is faster - it's about unlocking the kind of fluid collaboration that typing can't match.
## Why Voice Changes Everything
When you type, you edit yourself. You simplify complex ideas, skip context, and lose nuance. When you speak, you share everything on your mind - the full problem, the constraints, the edge cases you're worried about.
Use Dictation constantly in [Plan mode](/features/plan-and-act) for rapid back-and-forth discussions. Instead of typing careful, structured prompts, think about a problem. Cline asks clarifying questions, respond immediately, and iterate until having a solid plan.
The friction of typing was holding back real collaboration. Voice removes that friction.
## Getting Started
**Enable Dictation:**
1. Go to Settings → Features → Dictation
2. Toggle "Enable Dictation" on
3. Sign into your Cline account when prompted
4. Install FFmpeg if you haven't already (Cline will guide you)
Once enabled, you'll see a microphone button in the chat input area.
**Using Dictation:**
- Click the microphone button to start recording
- Speak naturally
- Click again to stop recording
- Wait for transcription to appear in the chat
<Tip>
Dictation works with any AI model you've configured. The transcription happens through Cline's service, but your conversation continues with whatever model you're using.
</Tip>
## System Requirements
Dictation uses FFmpeg to capture your voice across all platforms:
- **macOS**: FFmpeg (via Homebrew: `brew install ffmpeg`)
- **Linux**: FFmpeg (via apt: `sudo apt-get install ffmpeg`)
- **Windows**: FFmpeg (via winget: `winget install Gyan.FFmpeg`)
If you don't have FFmpeg installed, Cline will automatically detect this and prompt you to install it with a single click.
## Where Dictation Shines
### Plan Mode Conversations
Dictation is perfect for [Plan mode](/features/plan-and-act) discussions. Instead of carefully crafting prompts, you can:
- Dictate your entire problem context in one go
- Respond to Cline's questions immediately
- Iterate on ideas without typing friction
- Think out loud while Cline listens
Start a planning session by speaking for 2-3 minutes straight, explaining the full context of what you're trying to build, the constraints you're working with, and the specific challenges you're facing.
### Complex Problem Explanation
Some problems are hard to type out. When you're dealing with:
- Multi-step workflows with edge cases
- Integration challenges across multiple systems
- Performance issues with specific reproduction steps
- UI/UX problems that need detailed context
Speaking lets you explain the full situation naturally, including all the "oh, and also..." details that matter.
### Code Review and Debugging
When reviewing code or explaining bugs, voice lets you walk through your thought process:
- "This function looks fine, but I'm worried about what happens when..."
- "The issue might be in this section, or possibly this other area..."
- "I tried X and Y, but neither worked because..."
You can share your complete debugging journey instead of just the final question.
## Technical Requirements
**System Requirements:**
- FFmpeg installed on your system
- Active internet connection
- Cline account with transcription credits
**Audio Quality:**
- Records in WebM format with Opus codec
- Mono audio at 16kHz sample rate
- Optimized for voice recognition
**Privacy:**
- Audio recorded locally on your machine
- Only audio files sent for transcription
- No audio stored after transcription
- Temporary files automatically cleaned up
## Cost and Credits
Voice transcription costs $0.006 per minute through your Cline account. For most users, this works out to pennies per session.
A typical 5-minute planning conversation costs about 3 cents. Even heavy voice users rarely spend more than a few dollars per month.
<Note>
Pricing is experimental and may change as we refine the service.
</Note>
## Best Practices
**Speak Naturally**
Don't try to speak like you type. Use your normal conversational tone and don't worry about perfect grammar.
**Give Context First**
Start with the big picture, then drill down into specifics. "I'm building a React app that needs to handle real-time data, and I'm running into performance issues with the WebSocket connection..."
**Use Voice for Exploration**
Dictation is perfect for exploratory conversations where you're not sure exactly what you need. Start talking through the problem and let the conversation evolve.
**Combine with Text**
You don't have to use voice for everything. Use voice for complex explanations and context, then switch to text for quick follow-ups or code snippets.
## Troubleshooting
**Microphone Not Working**
- Check your IDE permissions for microphone access
- Ensure FFmpeg is properly installed
- Try refreshing VSCode/your editor
**Poor Transcription Quality**
- Speak clearly and at normal volume
- Reduce background noise if possible
- Check your microphone settings
**Connection Issues**
- Verify internet connection
- Check if firewall is blocking Cline's servers
- Try signing out and back into your Cline account
**Authentication Issues**
- Sign out and back into your Cline account if you see authentication errors
- Check that your account has sufficient transcription credits
- Verify your internet connection is stable
**Audio Recording Issues**
- Ensure FFmpeg is properly installed and accessible
- Check that your browser/IDE has microphone permissions
- Try restarting your editor if audio capture fails
## The Future of AI Collaboration
When you can speak your thoughts as fast as you think them, you stop self-editing. You share the full context, the edge cases, the "what if" scenarios that matter. This leads to better solutions and fewer back-and-forth clarifications.
+19 -1
View File
@@ -5,10 +5,28 @@ sidebarTitle: "Drag & Drop"
Dragging and dropping files into Cline is a quick way to add images, code, and other files to your conversations.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/dran-n-drop.gif"
alt="Dragging and dropping files into Cline chat"
/>
</Frame>
<Note>Due to VS Code quirks, to drag and drop files into the Cline chat input, you need to hold `Shift` while dragging.</Note>
Dragging and dropping workspace files into Cline will automatically create a [file mention](/features/at-mentions/file-mentions). This allows you to reference the file in your conversation without needing to type out the path.
### Dragging from Finder/File Explorer
You can drag files directly from your system's file manager into Cline:
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/drag-n-drop-finder.gif"
alt="Dragging files from Finder into Cline"
/>
</Frame>
### Supported File Types
Cline supports dragging external images from your file system, as well as files from your workspace.
Cline supports dragging external images, pdfs, csv, excel, and other text files from your file system, as well as files from your workspace.
+303
View File
@@ -0,0 +1,303 @@
---
title: "Focus Chain"
sidebarTitle: "Focus Chain"
---
Focus Chain is a task management enhancement feature in Cline that provides automatic todo list management with real-time progress tracking throughout your tasks.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/2dos.gif"
alt="Focus Chain todo list management with real-time progress tracking"
/>
</Frame>
This enables Cline to work on long-horizon tasks, seamlessly managing the context sent to LLMs, and keeping Cline on track across many context window resets.
<Tip>
Focus Chain works particularly well with Cline's [Deep Planning slash command](/features/slash-commands/deep-planning), providing seamless progress tracking for implementation tasks created through the [planning process](/features/plan-and-act).
</Tip>
## Key Features
### Automatic Todo List Generation
Cline analyzes your task and automatically creates a comprehensive todo list with:
- Clear, actionable items in markdown checklist format
- Logical breakdown of complex tasks into manageable steps
- Real-time updates as work progresses
### User-Editable Todo Lists
Todo lists are stored as editable markdown files:
- Direct editing through your preferred markdown editor
- Automatic detection of changes you make
- Seamless integration back into Cline's workflow
- Quick access through the edit button in the task header
### Visual Progress Tracking
The task header displays clear progress indicators:
- **Step counters** showing current progress (e.g., "3/8")
- **Completed items** clearly marked with checkmarks
- **Current work** highlighted with indicators
- **Expandable view** to see the full todo list
### Smart Reminder System
Configurable reminders ensure todo lists stay current:
- Default reminder every 6 messages (customizable 1-100)
- Automatic prompts when switching from Plan Mode to Act Mode
- User-triggered updates when todo lists are manually edited
## Getting Started
<Steps>
<Step title="Open Cline Settings">
- Click the gear icon in the Cline sidebar
- Navigate to the "Features" section
</Step>
<Step title="Enable Focus Chain">
- Check "Enable Focus Chain"
- Optionally adjust "Remind Cline Interval" (default: 6 messages)
</Step>
<Step title="Start a New Task">
- Begin a new task
- Cline will automatically start creating and managing todo lists
</Step>
</Steps>
| Setting | Default | Range | Description |
|---------|---------|-------|-------------|
| Enable Focus Chain | Disabled | On/Off | Enables enhanced task progress tracking |
| Remind Cline Interval | 6 | 1-100 messages | How often Cline updates the todo list |
## Usage Examples
#### 1. Task Initiation
When you start a new task with Focus Chain enabled:
``` markdown User Request
User: "Create a user authentication system for my React app"
Cline: [Analyzes request and creates todo list]
```
#### 2. Todo List Created
Cline creates a comprehensive plan for the task, stored in a markdown file:
```markdown Todo List Created
- [ ] Set up project structure
- [ ] Install authentication dependencies
- [ ] Create user registration component
- [ ] Implement login functionality
- [ ] Add password validation
- [ ] Set up user database schema
- [ ] Write authentication tests
- [ ] Deploy to staging environment
```
#### 3. Progress Tracking
As Cline works, the task header shows real-time progress:
```markdown Todo List Header
[3/8] Implement login functionality ⌄
```
Click to expand and see the full list:
```markdown Full Todo List
✓ Set up project structure
✓ Install authentication dependencies
✓ Create user registration component
○ Implement login functionality ← Currently working
○ Add password validation
○ Set up user database schema
○ Write authentication tests
○ Deploy to staging environment
```
#### 4. User Editing
Need to tweak the todo list? No problem.
<Steps>
<Step title="Open the todo list">
Click the edit button in the expanded todo view
</Step>
<Step title="Edit the markdown file">
A markdown file opens in your editor:
```markdown Editing Todo List
# Focus Chain Todo List for Task abc123
<!-- Edit this markdown file to update your focus chain todo list -->
<!-- Use - [ ] for incomplete items and - [x] for completed items -->
- [x] Set up project structure
- [x] Install authentication dependencies (e.g., Firebase Auth)
- [x] Create user registration component
- [ ] Implement login functionality
- [ ] Add password reset feature
- [ ] Set up protected routes
- [ ] Implement logout functionality
- [ ] Add user profile page
- [ ] Write authentication tests
- [ ] Deploy to staging environment
<!-- Save this file to update the task's todo list -->
```
</Step>
<Step title="Make your changes">
Add, remove, or reorder items as needed
</Step>
<Step title="Save the file">
Cline automatically detects and uses your updates
</Step>
</Steps>
## File Structure
### Todo List Storage
Todo lists are stored as markdown files in your task directory:
``` markdown
<VSCode Global Storage>/
tasks/
<taskId>/
focus_chain_taskid_<taskId>.md
... other task files
```
### Markdown Format
Todo files use standard markdown checklist syntax:
```markdown Example Todo Syntax
# Focus Chain Todo List for Task abc123
<!-- Edit this markdown file to update your focus chain todo list -->
<!-- Use the format: - [ ] for incomplete items and - [x] for completed items -->
- [x] Set up project structure
- [x] Install authentication dependencies
- [ ] Create user registration component
- [ ] Implement login functionality
- [ ] Add password validation
- [ ] Set up user database schema
- [ ] Write authentication tests
- [ ] Deploy to staging environment
<!-- Save this file and the todo list will be updated in the task -->
```
## Integration with Plan/Act Mode
Focus Chain works seamlessly with Cline's [Plan/Act mode](/features/plan-and-act):
- **Plan Mode**: Optional todo lists for presenting concrete steps
- **Act Mode**: Automatic todo creation when switching from Plan Mode
<Tip>
For complex projects, start in Plan Mode to discuss and refine your approach before switching to Act Mode for implementation.
</Tip>
## Best Practices
<AccordionGroup>
<Accordion title="For Effective Todo Lists">
1. **Start with Clear Requests**
- Provide detailed initial task descriptions
- Include specific requirements and constraints
- Mention any preferred technologies or approaches
2. **Review Generated Lists**
- Check that Cline's breakdown aligns with your expectations
- Verify that all important steps are included
- Ensure the order makes sense for your project
3. **Edit When Needed**
- Add missing steps you identify
- Remove unnecessary items
- Reorder steps for better workflow
- Add more specific details to general items
</Accordion>
<Accordion title="For Complex Projects">
1. **Use Plan Mode First**
- Discuss the approach before implementation
- Refine requirements through conversation
- Switch to Act Mode when ready to begin work
2. **Break Down Large Tasks**
- Split complex projects into smaller, manageable tasks
- Create separate todo lists for different components
- Focus on one major area at a time
3. **Regular Reviews**
- Check progress periodically during long tasks
- Update todo lists as requirements evolve
- Communicate changes to Cline through edits
</Accordion>
<Accordion title="For Collaboration">
1. **Share Todo Files**
- Todo markdown files can be shared with team members
- Include in version control for project documentation
- Use as basis for project planning discussions
2. **Consistent Format**
- Follow the standard markdown checklist format
- Keep item descriptions clear and actionable
- Use consistent terminology across todo lists
</Accordion>
</AccordionGroup>
## Troubleshooting
Having issues? Try these quick fixes:
<AccordionGroup>
<Accordion title="Todo list not updating?">
- Check that Focus Chain is enabled in settings
- Focus Chain may not work as well with smaller, less capable models
- Ensure file permissions are correct in the task directory
</Accordion>
<Accordion title="Can't edit todo file?">
- Verify your editor supports markdown
- Check VSCode has write permissions for the directory
</Accordion>
<Accordion title="Progress not displaying?">
- Ensure todo items use correct syntax (`- [ ]` and `- [x]`)
- Verify the markdown file is properly formatted
</Accordion>
</AccordionGroup>
Still stuck? Use the [/reportbug](/features/slash-commands/report-bug) command in Cline to get help.
## Technical Details (for the curious)
<AccordionGroup>
<Accordion title="File Monitoring">
- Real-time file watching detects changes to todo markdown files
- Automatic synchronization between file edits and UI updates
- Graceful handling of file creation, modification, and deletion
</Accordion>
<Accordion title="Progress Calculation">
- Dynamic counting of completed vs. total todo items
- Support for both `- [x]` and `- [X]` completion syntax
- Unicode symbols (✓, ○) for enhanced visual display
</Accordion>
<Accordion title="Privacy Considerations">
- Todo lists stored locally in VSCode workspace
- No todo content transmitted to external services
- Usage telemetry (can be disabled in settings)
</Accordion>
</AccordionGroup>
Focus Chain turns Cline into your personal project manager, keeping you on track and your tasks organized. Give it a try on your next project!
+4
View File
@@ -24,6 +24,10 @@ Plan mode is where you and Cline figure out what you're trying to build and how
- Focuses on understanding requirements and creating a strategy
- Helps identify potential issues before you write a single line of code
<Tip>
Try [Dictation](/features/dictation) in Plan mode - instead of typing out complex requirements, you can speak naturally and share your complete thought process. It's perfect for rapid back-and-forth planning discussions.
</Tip>
#### Act Mode: Build It
Once you've got a plan, you switch to Act mode. Now Cline:
@@ -0,0 +1,160 @@
---
title: "Deep Planning Command"
sidebarTitle: "/deep-planning"
---
`/deep-planning` transforms Cline into a meticulous architect who investigates your codebase, asks clarifying questions, and creates a comprehensive implementation plan before writing a single line of code.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/deep-planning.png"
alt="Deep Planning command in action showing investigation and planning process"
/>
</Frame>
When you use `/deep-planning`, Cline follows a four-step process that mirrors how senior developers approach complex features: thorough investigation, discussion & clarification of requirements, detailed planning, and structured task creation with progress tracking.
## The Four-Step Process
### Step 1: Silent Investigation
Cline becomes a detective, silently exploring your codebase to understand its structure, patterns, and constraints. He examines source files, analyzes import patterns, discovers class hierarchies, and identifies technical debt markers. No commentary, no narration - just focused research.
During this phase, Cline runs commands like:
- Finding all class and function definitions across your codebase
- Analyzing import patterns to understand dependencies
- Discovering project structure and file organization
- Identifying TODOs and technical debt
### Step 2: Discussion and Questions
Once Cline understands your codebase, he asks targeted questions that will shape the implementation. These aren't generic questions - they're specific to your project and the feature you're building.
Questions might cover:
- Clarifying ambiguous requirements
- Choosing between equally valid implementation approaches
- Confirming assumptions about system behavior
- Understanding preferences for technical decisions
### Step 3: Implementation Plan Document
Cline creates a structured markdown document (`implementation_plan.md`) that serves as your implementation blueprint. This isn't a vague outline - it's a detailed specification with exact file paths, function signatures, and implementation order.
The plan includes eight comprehensive sections:
- **Overview**: The goal and high-level approach
- **Types**: Complete type definitions and data structures
- **Files**: Exact files to create, modify, or delete
- **Functions**: New and modified functions with signatures
- **Classes**: Class modifications and inheritance details
- **Dependencies**: Package requirements and versions
- **Testing**: Validation strategies and test requirements
- **Implementation Order**: Step-by-step execution sequence
### Step 4: Implementation Task Creation
Cline creates a new task that references the plan document and includes trackable implementation steps. The task comes with specific commands to read each section of the plan, ensuring the implementing agent (whether that's you or Cline in Act Mode) can navigate the blueprint efficiently.
<Tip>
Deep Planning works beautifully with [Focus Chain](/features/focus-chain). The implementation steps automatically become a todo list with real-time progress tracking, keeping complex projects organized and on track.
</Tip>
## Using Deep Planning
Start a deep planning session by typing `/deep-planning` followed by your feature description:
```
/deep-planning Add user authentication with JWT tokens and role-based access control
```
Cline will begin his investigation immediately. You'll see him reading files and running commands to understand your codebase. Once he's gathered enough context, he'll engage you in discussion before creating the plan.
## Example Workflow
Here's how I use `/deep-planning` for a real feature:
<Steps>
<Step title="Initiate Planning">
I type `/deep-planning implement a caching layer for API responses`
</Step>
<Step title="Silent Investigation">
Cline explores my codebase, examining:
- Current API structure and endpoints
- Existing data flow patterns
- Database queries and performance bottlenecks
- Configuration and environment setup
</Step>
<Step title="Targeted Discussion">
Cline asks me:
- "Should we use Redis or in-memory caching?"
- "What's the acceptable cache staleness for user data?"
- "Do you need cache invalidation webhooks?"
</Step>
<Step title="Plan Creation">
Cline generates `implementation_plan.md` with:
- Cache service class specifications
- Redis connection configuration
- Modified API endpoints with caching logic
- Cache key generation strategies
- TTL configurations for different data types
</Step>
<Step title="Task Generation">
Cline creates a new task with:
- Reference to the implementation plan
- Commands to read specific sections
- Trackable todo items for each implementation step
- Request to switch to Act Mode for execution
</Step>
</Steps>
## Integration with Plan/Act Mode
Deep Planning is designed to work seamlessly with [Plan/Act Mode](/features/plan-and-act):
- Use `/deep-planning` in Plan Mode for the investigation and planning phases
- The generated task requests switching to Act Mode for implementation
- Focus Chain automatically tracks progress through the implementation steps
This separation ensures planning stays focused on architecture while implementation stays focused on execution.
## Best Practices
### When to Use Deep Planning
Use `/deep-planning` for:
- Features touching multiple parts of your codebase
- Architectural changes requiring careful coordination
- Complex integrations with external services
- Refactoring efforts that need systematic execution
- Any feature where you'd normally spend time whiteboarding
### Making the Most of Investigation
Let Cline complete his investigation thoroughly. The quality of the plan directly correlates with how well he understands your codebase. If you have specific areas he should examine, mention them in your initial request.
### Reviewing the Plan
Always review `implementation_plan.md` before starting implementation. The plan is comprehensive but not immutable - you can edit it directly if needed. Think of it as a collaborative document between you and Cline.
### Tracking Progress
With Focus Chain enabled, your implementation progress displays in the task header. Each completed step gets checked off automatically as Cline works through the plan, giving you real-time visibility into complex implementations.
## Inspiration
I use `/deep-planning` whenever I'm about to build something that would normally require a design document. Recent examples from my workflow:
- **Migrating authentication systems**: Deep Planning mapped every endpoint, identified all authentication touchpoints, and created a migration plan that avoided breaking changes.
- **Adding real-time features**: The plan covered WebSocket integration, event handling, state synchronization, and fallback mechanisms for disconnections.
- **Database schema refactoring**: Cline identified all affected queries, created migration scripts, and planned the rollout to minimize downtime.
- **API versioning implementation**: The plan detailed route changes, backward compatibility layers, deprecation notices, and client migration paths.
The power of `/deep-planning` is that it forces thoughtful architecture before implementation. It's like having a senior developer review your approach before you write code, except that developer has perfect knowledge of your entire codebase.
<Note>
Deep Planning requires models with strong reasoning capabilities. It works best with the latest generation of models, like GPT-5, Claude 4, Gemini 2.5, or Grok 4. Smaller models may struggle with the comprehensive analysis required.
</Note>
For simpler tasks that don't require extensive planning, consider using [/newtask](/features/slash-commands/new-task) to create focused tasks with context, or jump straight into implementation if the path forward is clear.
+83
View File
@@ -0,0 +1,83 @@
---
title: "YOLO Mode"
sidebarTitle: "YOLO Mode"
---
YOLO mode is exactly what it sounds like - Cline auto-approves everything. Check the box in feature settings and he'll execute file changes, terminal commands, even transitions from Plan to Act mode without asking.
Think of it as [Auto Approve](/features/auto-approve) on steroids - instead of granular permissions, YOLO mode gives Cline complete autonomy.
<Note>
**Warning: This is dangerous.** YOLO mode disables all safety checks. Cline will execute whatever he decides without asking permission.
</Note>
## What Gets Auto-Approved
When YOLO mode is enabled, Cline automatically approves:
- **All file operations** - reading, writing, and modifying files anywhere on your system
- **All terminal commands** - including potentially destructive operations
- **Browser actions** - web scraping, form submissions, navigation
- **MCP server tools** - external integrations and API calls
- **Mode transitions** - automatic switching from Plan to Act mode
Essentially, every safety guardrail is removed. Cline operates with complete autonomy.
## How to Enable YOLO Mode
Navigate to Cline Settings → Features and check the "YOLO Mode" box. That's it - no confirmation dialogs, no additional warnings. Once enabled, Cline will start auto-approving all actions immediately.
To disable it, simply uncheck the box. Any pending actions will still require your approval once YOLO mode is turned off.
## When You Might Use This
YOLO mode was built primarily for our upcoming scriptable CLI where fully autonomous execution makes sense. In the GUI, you might consider it for:
**Rapid prototyping** where you want zero friction and don't care about potential mistakes. Perfect for throwaway experiments or exploring new ideas quickly.
**Trusted, repetitive tasks** where you've already validated Cline's approach and want to eliminate approval overhead. Think routine refactoring or well-established patterns.
**Demonstration purposes** where you want to show Cline's capabilities without constant interruptions.
## What Could Go Wrong
Since YOLO mode removes all safety checks, Cline could:
- Delete important files without warning
- Execute commands that modify system settings
- Make network requests to external services
- Overwrite configuration files
- Install or uninstall software packages
- Commit and push changes to version control
The risk level depends entirely on what you ask Cline to do. Simple tasks remain relatively safe, but complex requests can have unpredictable consequences.
## Best Practices
If you decide to use YOLO mode:
**Start with isolated environments.** Use it in throwaway projects or sandboxed environments first. Never enable it on production codebases until you understand the risks.
**Be specific with requests.** Vague instructions combined with unlimited permissions can lead to unexpected results. The clearer your requirements, the more predictable Cline's actions.
**Monitor the output.** Even though Cline doesn't ask for permission, he still shows you what he's doing. Watch the terminal output and file changes as they happen.
**Keep version control handy.** Make sure you can easily revert changes if something goes wrong. Git becomes your safety net when YOLO mode is your workflow.
## Inspiration: What Becomes Possible
With YOLO mode enabled, you can:
**Build entire applications** from a single prompt. Describe what you want and let Cline handle everything - file creation, dependency installation, configuration setup, even deployment scripts.
**Automate complex workflows** that normally require dozens of approval clicks. Data processing pipelines, build system setup, or multi-step refactoring operations become seamless.
**Rapid iteration cycles** where you can quickly test ideas without approval friction. Perfect for exploring different approaches or experimenting with new technologies.
**Live demonstrations** where you can show Cline's full capabilities without stopping to approve every action. Great for presentations or teaching scenarios.
The key is understanding that YOLO mode transforms Cline from an interactive assistant into an autonomous agent. Use that power wisely.
---
Questions or feedback? Reach us in our [Discord](https://discord.gg/cline) or [r/cline](https://reddit.com/r/cline).
+11 -11
View File
@@ -3,9 +3,9 @@ title: "For New Coders"
description: "Welcome to Cline, your AI-powered coding companion! This guide will help you quickly set up your development environment and begin your coding journey with ease."
---
> 💡 **Tip:** If you're completely new to coding, take your time with each step. There's no rush — Cline is here to guide you!
> **Tip:** If you're completely new to coding, take your time with each step. There's no rush — Cline is here to guide you!
### 🚀 Getting Started
### Getting Started
Before you jump into coding, make sure you have these essentials ready:
@@ -15,9 +15,9 @@ A popular, free, and powerful code editor.
- [<u>Download VS Code</u>](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](https://www.youtube.com/watch?v=MlIzFUI1QGA)
**Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](https://www.youtube.com/watch?v=MlIzFUI1QGA)
> **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
> **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
#### 2. **Organize Your Projects**
@@ -31,7 +31,7 @@ Inside your `Cline` folder, structure projects clearly:
- `Documents/Cline/workout-app` _(e.g., for a fitness tracking app)_
- `Documents/Cline/portfolio-website` _(e.g., to showcase your work)_
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
> **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 3. **Install the Cline VS Code Extension**
@@ -39,9 +39,9 @@ Enhance your coding workflow by installing the Cline extension directly within V
- Get Started with Cline Extension Tutorial
📺 **Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](https://www.youtube.com/watch?v=E7trgwZa-mk)
**Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](https://www.youtube.com/watch?v=E7trgwZa-mk)
> **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
> **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
#### 4. **Essential Development Tools**
@@ -51,9 +51,9 @@ Basic software required for coding efficiently:
- Node.js
- Git
👉 [<u>Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.</u>](https://docs.cline.bot/getting-started/installing-dev-essentials#installing-dev-essentials)
[<u>Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.</u>](https://docs.cline.bot/getting-started/installing-dev-essentials#installing-dev-essentials)
📺 **Recommended YouTube Tutorials for Manual Installation:**
**Recommended YouTube Tutorials for Manual Installation:**
- **For macOS:**
- [<u>Install Homebrew on Mac</u>](https://www.youtube.com/watch?v=hwGNgVbqasc)
@@ -63,6 +63,6 @@ Basic software required for coding efficiently:
- [<u>Install Git on Windows 10/11 (2024)</u>](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [<u>Install Node.js in Windows 10/11</u>](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
> **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
You're all set! Dive in and start coding smarter and faster with **Cline**.
+237 -48
View File
@@ -1,67 +1,256 @@
---
title: "Installing Cline"
description: "Cline is a VS Code extension that brings AI-powered coding assistance directly
to your editor. Install using one of these methods:"
description: "Get Cline set up in your editor and start building projects with AI assistance."
---
### Installation Options
## Prerequisites
- **VS Code Marketplace (Recommended):** Fastest method for standard VS Code and Cursor users.
- **Open VSX Registry:** For VS Code-compatible editors like VSCodium.
Before installing Cline, make sure you have the following:
### 🛠️ VS Code Marketplace: Step-by-Step Setup
### Create a Cline Account
Follow these steps to get Cline up and running:
Create a Cline account for the best experience. Creating a Cline account is completely free and you can [sign up here](https://app.cline.bot/signup). A Cline account provides:
- Access to multiple AI models including stealth models
- Seamless setup without needing to manage API keys
- At times, we partner with model providers to offer inferencing at no cost through your Cline account
1. **Open VS Code:** Launch the VS Code application.
### Compatible Editor
> ⚠️ **Note:** If VS Code shows "Running extensions might...", click "Allow".
Cline works with the following IDEs:
- **VS Code** - Microsoft's popular code editor
- **Cursor** - AI-powered code editor based on VS Code
- **JetBrains IDEs** - IntelliJ IDEA, PyCharm, WebStorm, DataSpell, PhpStorm, and other JetBrains products
- **VSCodium** - Open-source version of VS Code
- **Windsurf** - VS Code-compatible editor
2. **Open Your Cline Folder:** In VS Code, open the Cline folder you created in Documents.
3. **Navigate to Extensions:** Click on the Extensions icon in the Activity Bar on the side of VS Code (`Ctrl + Shift + X` or `Cmd + Shift + X`).
4. **Search for 'Cline':** In the Extensions search bar, type `Cline`.
Make sure you have one of these editors installed before proceeding with the Cline installation.
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
## Choose Your Editor
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
2. **Open Cline:**
- Click the Cline icon in the Activity Bar.
- Or, use the command palette (`Ctrl/Cmd + Shift + P`) and type "Cline: Open In New Tab" for a better view.
3. **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
Cline works across multiple IDEs. Select your preferred editor below for installation instructions:
> ✅ **Pro Tip:** You should see the Cline chat window appear in your VS Code editor!
<Tabs>
<Tab title="VS Code/Cursor" icon="code">
### Installation Steps
### 🌐 Open VSX Registry
1. **Open VS Code** and navigate to the Extensions view (`Ctrl/Cmd + Shift + X`)
2. **Search for "Cline"** in the Extensions marketplace
3. **Click Install** on the Cline extension
For VS Code-compatible editors without Marketplace access (like VSCodium and Windsurf):
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
1. Open your editor.
2. Access the Extensions view.
3. Search for "Cline".
4. Select "Cline" by saoudrizwan and click **Install**.
5. Reload if prompted.
4. **Access Cline** after installation:
- Click the Cline icon in the Activity Bar, or
- Use Command Palette (`Ctrl/Cmd + Shift + P`) → "Cline: Open In New Tab"
### 👤 Creating Your Cline Account
> **Note:** If VS Code shows "Running extensions might..." dialog, click "Allow". If you don't see the Cline icon, restart VS Code.
Now that you have Cline installed, let's get you set up with your account:
<Accordion title="Troubleshooting">
1. **Sign In to Cline:**
- Click the **Sign In** button in the Cline extension.
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account.
2. **Start with Free Credits:**
- No credit card needed!
3. **Available AI Models:**
- Anthropic Claude 3.5-Sonnet (recommended for coding)
- DeepSeek Chat (cost-effective alternative)
- Google Gemini 2.0 Flash
- And more — all through your Cline account.
**Plugin Installation Issues**
### 💻 Your First Interaction with Cline
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your VS Code version is compatible
If installation fails:
- Restart your VS Code and try again
- Check your internet connection
- Try installing from VSIX file as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart VS Code completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted VS Code after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
Performance or compatibility issues:
- Make sure you're using a supported VS Code version
- Check for VS Code updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
<Tab title="JetBrains IDEs" icon="brain">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-logo.svg"
alt="JetBrains logo"
style={{ width: "200px", height: "auto", margin: "0 auto 20px auto", display: "block" }}
/>
Cline for JetBrains works almost identically to Cline in VSCode. All the core features work properly: diff editing, using tools, logging in with different providers, MCP servers, Cline rules and workflows, and more.
### Installation Steps
**Method 1: From IDE (Recommended)**
1. Open your JetBrains IDE
2. Go to **Settings** (`Ctrl+Alt+S` on Windows/Linux, `Cmd+,` on macOS)
3. Navigate to **Plugins** → **Marketplace**
4. Search for "Cline" and click **Install**
5. Restart your IDE
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-marketplace-search.png"
alt="JetBrains marketplace showing Cline plugin search results"
/>
</Frame>
**Method 2: Browser Install**
Visit the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/28247-cline) and click **Install to IDE**.
<Accordion title="Method 3: Manual Installation">
1. Download the plugin from the [marketplace page](https://plugins.jetbrains.com/plugin/28247-cline)
2. Go to **Settings** → **Plugins**
3. Click the gear icon → **Install Plugin from Disk**
4. Select the downloaded `.zip` file
5. Restart your IDE
</Accordion>
### Using the Plugin
After installation, youll find Cline in your IDE. Look for the Cline tool window (usually on the right side) or go to View → Tool Windows → Cline.
### Key Features
Cline for JetBrains includes all core features:
- Diff editing and file modifications
- Multiple API providers (Anthropic, OpenAI, local models)
- MCP servers and custom tools
- Cline rules and workflows
- @ mentions for files, folders, and problems
- Drag & drop support
> **Note:** Terminal output appears in collapsible sections rather than streaming directly to chat.
### Key Differences from VSCode
The terminal integration works differently in JetBrains. Unlike VSCode where terminal output streams directly to the chat, JetBrains shows command output in a collapsible section. Commands still execute successfully - you just need to expand the Command Output section to see results.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your IDE version is compatible (2023.1 or later recommended)
If installation fails:
- Restart your IDE and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your IDE completely (File → Exit and reopen)
- Check **View** → **Tool Windows** → **Cline**
- Verify the plugin is enabled in **Settings** → **Plugins** → **Installed** tab
- Look for the Cline icon in your IDE's tool window bar (usually on the right side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your IDE after installation
- Check if there are any error messages in the IDE's event log
- Try disabling and re-enabling the plugin in Settings
Performance or compatibility issues:
- Make sure you're using a supported JetBrains IDE version
- Check for IDE updates that might improve compatibility
- Consider allocating more memory to your IDE if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
<Tab title="VSCodium/Windsurf" icon="terminal">
### Installation Steps
For VS Code-compatible editors using Open VSX Registry:
1. **Open your editor** (VSCodium, Windsurf, etc.)
2. **Navigate to Extensions view** (`Ctrl/Cmd + Shift + X`)
3. **Search for "Cline"** in the marketplace
4. **Select "Cline" by saoudrizwan** and click **Install**
5. **Reload** if prompted
> **Note:** These editors use the Open VSX Registry instead of the VS Code Marketplace.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your editor version is compatible
If installation fails:
- Restart your editor and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your editor completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your editor after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
Performance or compatibility issues:
- Make sure you're using a supported editor version
- Check for editor updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
</Tabs>
### Sign In to Your Cline Account
Now that you have Cline installed, sign in to access your account:
1. **Open Cline** in your editor (click the Cline icon in the Activity Bar or Tool Windows)
2. **Click "Sign In"** - you'll see this button in the Cline interface
3. **Complete authentication** - you'll be redirected to [app.cline.bot](https://app.cline.bot) to sign in
4. **Return to your editor** - once signed in, you'll be automatically redirected back
### Your First Interaction with Cline
You're ready to start building! Copy and paste this prompt into the Cline chat window:
@@ -69,15 +258,15 @@ You're ready to start building! Copy and paste this prompt into the Cline chat w
Hey Cline! Could you help me create a new project folder called "hello-world" in my Cline directory and make a simple webpage that says "Hello World" in big blue text?
```
> **Pro Tip:** Cline will help you create the project folder and set up your first webpage!
> **Pro Tip:** Cline will help you create the project folder and set up your first webpage!
### 🧩 Tips for Working with Cline
### Tips for Working with Cline
- **Ask Questions:** If you're unsure about something, ask Cline!
- **Use Screenshots:** Cline can understand images — show him what you're working on.
- **Copy and Paste Errors:** Share error messages in the chat for solutions.
- **Speak Plainly:** Use your own words — Cline will translate them into code.
### 🫂 Still Struggling?
### Still Struggling?
Join our Discord community and engage with our team and other Cline users directly.
Join our [Discord community](https://discord.gg/cline) and engage with our team and other Cline users directly.
@@ -6,7 +6,7 @@ description: >-
guided way.
---
### 🧰 The Essential Tools
### The Essential Tools
Here are the core tools you'll need for development:
@@ -17,9 +17,9 @@ Here are the core tools you'll need for development:
- Chocolatey for Windows
- apt/yum for Linux
> 💡 **Tip:** These tools are the foundation of your developer toolkit. Installing them properly will set you up for success!
> **Tip:** These tools are the foundation of your developer toolkit. Installing them properly will set you up for success!
### 🚀 Let Cline Install Everything
### Let Cline Install Everything
Copy one of these prompts based on your operating system and paste it into **Cline**:
@@ -41,9 +41,9 @@ Hello Cline! I need help setting up my Windows PC for software development. Coul
Hello Cline! I need help setting up my Linux system for software development. Could you please help me install the essential development tools like Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
> **Pro Tip:** Cline will show you each command before running it. You stay in control the entire time!
> **Pro Tip:** Cline will show you each command before running it. You stay in control the entire time!
### 🔍 What Will Happen
### What Will Happen
Cline will guide you through the following steps:
@@ -52,9 +52,9 @@ Cline will guide you through the following steps:
3. Showing you the exact command before it runs (you approve each step!)
4. Verifying each installation is successful
> ⚠️ **Note:** You might need to enter your computer's password for some installations. This is normal!
> **Note:** You might need to enter your computer's password for some installations. This is normal!
### 💡 Why These Tools Are Important
### Why These Tools Are Important
- **Node.js & npm:**
- Build websites with frameworks like React or Next.js
@@ -68,15 +68,15 @@ Cline will guide you through the following steps:
- Quickly install and update development tools
- Keep your environment organized and up to date
### 🧩 Notes
### Notes
> 💡 **Tip:** The installation process is interactive — Cline will guide you step by step!
> **Tip:** The installation process is interactive — Cline will guide you step by step!
- All commands are shown to you for approval before they run.
- If you run into any issues, Cline will help troubleshoot them.
- You may need to enter your computer's password for certain steps.
### 🧑‍💻 Additional Tips for New Coders
### Additional Tips for New Coders
#### Understanding the Terminal
+53 -100
View File
@@ -1,126 +1,79 @@
---
title: "Model Selection Guide"
description: "Last updated: Feb 5, 2025."
description: "Last updated: August 20, 2025."
---
## Understanding Context Windows
New models drop constantly, so this guide focuses on what's working well with Cline right now. We'll keep it updated as the landscape shifts.
Think of a context window as your AI assistant's working memory - similar to RAM in a computer. It determines how much information the model can "remember" and process at once during your conversation. This includes:
## Current Top Models
- Your code files and conversations
- The assistant's responses
- Any documentation or additional context provided
| Model | Context Window | Input Price* | Output Price* | Best For |
|-------|---------------|--------------|---------------|----------|
| **Claude Sonnet 4.5** | 1M tokens | $3-6 | $15-22.50 | Reliable tool usage, complex codebases |
| **Qwen3 Coder** | 256K tokens | $0.20 | $0.80 | Coding tasks, open source flexibility |
| **Gemini 2.5 Pro** | 1M+ tokens | TBD | TBD | Large codebases, document analysis |
| **GPT-5** | 400K tokens | $1.25 | $10 | Latest OpenAI tech, three modes |
Context windows are measured in tokens (roughly 3/4 of a word in English). Different models have different context window sizes:
*Per million tokens
- Claude 3.5 Sonnet: 200K tokens
- DeepSeek Models: 128K tokens
- Gemini Flash 2.0: 1M tokens
- Gemini 1.5 Pro: 2M tokens
## Budget Options
When you reach the limit of your context window, older information needs to be removed to make room for new information - just like clearing RAM to run new programs. This is why sometimes AI assistants might seem to "forget" earlier parts of your conversation.
| Model | Context Window | Input Price* | Output Price* | Notes |
|-------|---------------|--------------|---------------|-------|
| **DeepSeek V3** | 128K tokens | $0.14 | $0.28 | Great value for daily coding |
| **DeepSeek R1** | 128K tokens | $0.55 | $2.19 | Budget reasoning champion |
| **Qwen3 32B** | 128K tokens | Varies | Varies | Open source, multiple providers |
| **Z AI GLM 4.5** | 128K tokens | TBD | TBD | MIT licensed, hybrid reasoning |
Cline helps you manage this limitation with its Context Window Progress Bar, which shows:
*Per million tokens
- Input tokens (what you've sent to the model)
- Output tokens (what the model has generated)
- A visual representation of how much of your context window you've used
- The total capacity for your chosen model
<Frame caption="Visual representation of the context window usage in Cline">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(11).png"
alt="Context window progress bar example"
/>
</Frame>
## Context Window Guide
This visibility helps you work more effectively with Cline by letting you know when you might need to start fresh or break tasks into smaller chunks.
| Size | Word Count | Use Case |
|------|------------|----------|
| 32K tokens | ~24,000 words | Single files, small projects |
| 128K tokens | ~96,000 words | Most coding projects |
| 200K tokens | ~150,000 words | Large codebases |
| 400K+ tokens | ~300,000+ words | Entire applications |
### Model Comparison
**Performance note**: Most models start dropping in quality around 400-500K tokens, even if they claim higher limits.
## LLM Model Comparison for Cline (Feb 2025)
## Open Source vs Closed Source
| Model | Input Cost\* | Output Cost\* | Context Window | Best For |
| ----------------- | ------------ | ------------- | -------------- | ----------------------------------- |
| Claude 3.5 Sonnet | $3.00 | $15.00 | 200K | Best code implementation & tool use |
| DeepSeek R1 | $0.55 | $2.19 | 128K | Planning & reasoning champion |
| DeepSeek V3 | $0.14 | $0.28 | 128K | Value code implementation |
| o3-mini | $1.10 | $4.40 | 200K | Flexible use, strong planning |
| Gemini Flash 2.0 | $0.00 | $0.00 | 1M | Strong all-rounder |
| Gemini 1.5 Pro | $0.00 | $0.00 | 2M | Large context processing |
### Open Source Advantages
- **Multiple providers** compete to host them
- **Cheaper pricing** due to competition
- **Provider choice** - switch if one goes down
- **Faster innovation** cycles
\*Costs per million tokens
### Open Source Models Available
- **Qwen3 Coder** (Apache 2.0)
- **Z AI GLM 4.5** (MIT)
- **Kimi K2** (Open source)
- **DeepSeek series** (Various licenses)
### Top Picks for 2025
## Quick Decision Matrix
1. **Claude 3.5 Sonnet**
- Best overall code implementation
- Most reliable tool usage
- Expensive but worth it for critical code
2. **DeepSeek R1**
- Exceptional planning & reasoning
- Great value pricing
3. **o3-mini**
- Strong for planning with adjustable reasoning
- Three reasoning modes for different needs
- Requires OpenAI Tier 3 API access
- 200K context window
4. **DeepSeek V3**
- Reliable code implementation
- Great for daily coding
- Cost-effective for implementation
5. **Gemini Flash 2.0**
- Massive 1M context window
- Improved speed and performance
- Good all-around capabilities
| If you want... | Use this |
|----------------|----------|
| Something that just works | Claude Sonnet 4.5 |
| To save money | DeepSeek V3 or Qwen3 variants |
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4.5 |
| Open source | Qwen3 Coder, Z AI GLM 4.5, or Kimi K2 |
| Latest tech | GPT-5 |
| Speed | Qwen3 Coder on Cerebras (fastest available) |
### Best Models by Mode (Plan or Act)
## What Others Are Using
#### Planning
Check [OpenRouter's Cline usage stats](https://openrouter.ai/apps?url=https%3A%2F%2Fcline.bot%2F) to see real usage patterns from the community.
1. **DeepSeek R1**
- Best reasoning capabilities in class
- Excellent at breaking down complex tasks
- Strong math/algorithm planning
- MoE architecture helps with reasoning
2. **o3-mini (high reasoning)**
- Three reasoning levels:
- High: Complex planning
- Medium: Daily tasks
- Low: Quick ideas
- 200K context helps with large projects
3. **Gemini Flash 2.0**
- Massive context window for complex planning
- Strong reasoning capabilities
- Good with multi-step tasks
## Context Management
#### Acting (coding)
Cline automatically handles context limits with [auto-compact](/features/auto-compact). When you approach your model's limit, Cline summarizes the conversation to keep working. You don't need to micromanage this.
1. **Claude 3.5 Sonnet**
- Best code quality
- Most reliable with Cline tools
- Worth the premium for critical code
2. **DeepSeek V3**
- Nearly Sonnet-level code quality
- Better API stability than R1
- Great for daily coding
- Strong tool usage
3. **Gemini 1.5 Pro**
- 2M context window
- Good with complex codebases
- Reliable API
- Strong multi-file understanding
## The Bottom Line
### A Note on Local Models
Start with **Claude Sonnet 4.5** if you want reliability. Experiment with **open source options** once you're comfortable to find the best fit for your workflow and budget.
While running models locally might seem appealing for cost savings, we currently don't recommend any local models for use with Cline. [Local models are significantly less reliable](https://docs.cline.bot/running-models-locally/read-me-first) at using Cline's essential tools and typically retain only 1-26% of the original model's capabilities. The full cloud version of DeepSeek-R1, for example, is 671B parameters - local versions are drastically simplified copies that struggle with complex tasks and tool usage. Even with high-end hardware (RTX 3070+, 32GB+ RAM), you'll experience slower responses, less reliable tool execution, and reduced capabilities. For the best development experience, we recommend sticking with the cloud models listed above.
### Key Takeaways
1. **Plan vs Act Matters**: Choose models based on task type
2. **Real Performance > Benchmarks**: Focus on actual Cline performance
3. **Mix & Match**: Use different models for planning and implementation
4. **Cost vs Quality**: Premium models worth it for critical code
5. **Keep Backups**: Have alternatives ready for API issues
_\*Note: Based on real usage patterns and community feedback rather than just benchmarks. Your experience may vary. This is not an exhaustive list of all the models available for use within Cline._
The landscape moves fast - these recommendations reflect what's working now, but keep an eye on new releases.
@@ -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!
@@ -3,7 +3,7 @@ title: "Context Management"
description: "Context is key to getting the most out of Cline"
---
> 💡 **Quick Reference**
> **Quick Reference**
>
> - Context = The information Cline knows about your project
> - Context Window = How much information Cline can hold at once
@@ -38,7 +38,7 @@ Cline actively builds context in two ways:
- Guide focus areas
- Share design thoughts and requirements
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/features/plan-and-act) mode.
**Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan Mode](/features/plan-and-act).
### Context & Context Windows
@@ -53,12 +53,13 @@ Think of context like a whiteboard you and Cline share:
- **Context Window** is the size of the whiteboard itself:
- Measured in tokens (1 token ≈ 3/4 of an English word)
- Each model has a fixed size:
- Claude 3.5 Sonnet: 200,000 tokens
- DeepSeek: 64,000 tokens
- When the whiteboard is full, you need to erase (clear context) to write more
- [How Cline manages context under the hood](https://cline.bot/blog/understanding-the-new-context-window-progress-bar-in-cline)
- Claude Sonnet 4.5: 1,000,000 tokens
- Qwen3 Coder: 256,000 tokens
- Gemini 2.5 Pro: 1,000,000+ tokens
- GPT-5: 400,000 tokens
- When the whiteboard is full, Cline automatically summarizes the conversation to free up space
⚠️ **Important**: Having a large context window (like Claude's 200k tokens) doesn't mean you should fill it completely. Just like a cluttered whiteboard, too much information can make it harder to focus on what's important.
**Important**: Having a large context window doesn't mean you should fill it completely. Models start degrading around 400-500K tokens even if they claim higher limits. Just like a cluttered whiteboard, too much information can make it harder to focus on what's important.
## Understanding the Context Window Progress Bar
@@ -76,7 +77,7 @@ Cline provides a visual way to monitor your context window usage through a progr
- ↑ shows input tokens (what you've sent to the LLM)
- ↓ shows output tokens (what the LLM has generated)
- The progress bar visualizes how much of your context window you've used
- The total shows your model's maximum capacity (e.g., 200k for Claude 3.5-Sonnet)
- The total shows your model's maximum capacity (e.g., 1M for Claude Sonnet 4.5)
### When to Watch the Bar
@@ -85,7 +86,33 @@ Cline provides a visual way to monitor your context window usage through a progr
- Before starting complex tasks
- When Cline seems to lose context
💡 **Tip**: Consider starting a fresh session when usage reaches 70-80% to maintain optimal performance.
**Tip**: With [Auto Compact](/features/auto-compact), Cline can now handle long conversations automatically. When combined with [Focus Chain](/features/focus-chain), you can work on complex projects that span multiple context windows without losing progress.
## Automatic Context Management
Cline includes intelligent features to manage context automatically:
### Default Settings You Should Keep On
**Focus Chain** - Enabled by default in v3.25. Cline generates a todo list at task start and keeps it in context so the thread doesn't drift. You can edit the markdown to add or reorder steps and Cline will adapt. [Learn more about Focus Chain](/features/focus-chain).
**Auto Compact** - Always on. As the context window reaches its limit, Cline creates a comprehensive summary, replaces the bloated history, and continues where it left off. Decisions, code changes, and state are preserved. [Learn more about Auto Compact](/features/auto-compact).
## Advanced Context Tools
When you need more control over context management:
### Deep Planning (`/deep-planning`)
For substantial features, refactors, or integrations. Cline investigates your codebase, asks targeted questions, then writes `implementation_plan.md`. It creates a fresh task with distilled, high-value context. [Learn more about Deep Planning](/features/slash-commands/deep-planning).
### New Task (`/newtask`)
At natural transition points, packages only what matters into a fresh task. Clean slate for implementation after research, or crisp handoff between teammates. [Learn more about New Task](/features/slash-commands/new-task).
### Smol (`/smol`)
Compress the conversation in place to keep momentum. Ideal during debugging or exploratory work when you don't want to break flow. [Learn more about Smol](/features/slash-commands/smol).
### Memory Bank + .clinerules
For non-trivial projects. The Memory Bank captures project knowledge as Markdown in your repo. `.clinerules` are version-controlled instructions that align Cline's behavior with your team. [Learn more about Memory Bank](/prompting/cline-memory-bank) and [Cline Rules](/features/cline-rules).
## Working with Context Files
@@ -93,12 +120,12 @@ Context files help maintain understanding across sessions. They serve as documen
#### Approaches to Context Files
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/prompting/cline-memory-bank)**)**
1. **Evergreen Project Context (Memory Bank)**
- Living documentation that evolves with your project
- Updated as architecture and patterns emerge
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
- Useful for long-running projects and teams
2. **Task-Specific Context (i.e.** [**Structured Approach**](https://cline.bot/blog/building-advanced-software-with-cline-a-structured-approach)**)**
2. **Task-Specific Context**
- Created for specific implementation tasks
- Document requirements, constraints, and decisions
@@ -151,9 +178,19 @@ Context files help maintain understanding across sessions. They serve as documen
- Use Plan mode for complex discussions
- Start fresh sessions when needed
3. **Team Projects**
- Share common context files (consider using [.clinerules](https://docs.cline.bot/features/cline-rules) files in project roots)
- Share common context files (consider using [.clinerules](/features/cline-rules) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
Remember: The goal is to help Cline maintain consistent understanding of your project across sessions.
## Bonus Context Tips
- You can @ links and have the webpage's context added to Cline (docs, blogs, etc.)
- Utilize MCP servers to pull in context from your external knowledge bases
- Screenshots can be used as context for models that support image inputs
## The Bottom Line
Cline already does a lot of context work for you - [Focus Chain](/features/focus-chain), [Auto Compact](/features/auto-compact), and the planning flow are designed to keep the thread intact across long horizons. The goal is to help Cline maintain consistent understanding of your project across sessions.
Remember: The goal is to keep only what matters in view, at every step.

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