Compare commits

..

540 Commits

Author SHA1 Message Date
Tony Loehr 58bc26bd01 Merge branch 'main' into worktree-docs 2026-01-20 18:58:49 -08:00
Robin Newhouse 59251e9de6 fix: ensure document finalization in approval flow (#8757)
When file operations use the approval flow (isFinal=false), the document
content was not being properly finalized before user approval. This caused
content duplication when shortening files - old content at the end was
preserved instead of being replaced.

Root cause: FileProviderOperations passed isFinal=false to
DiffViewProvider.update(), which:
1. Popped the last line (treated as "incomplete" for streaming)
2. Limited the replacement range to currentLine + 1
3. Skipped truncation of trailing content

Fix: Always pass isFinal=true to update() since the content IS complete.
The isFinal parameter in FileProviderOperations now only controls whether
to save after the update, not the update behavior itself.

This follows the philosophy of dd35448a9 by fixing at the source rather
than adding cleanup logic.
2026-01-20 15:52:12 -08:00
Saoud Rizwan 2df952f571 fix: OpenAI Codex provider improvements based on OpenAI feedback (#8754)
* style: improve OAuth success page design

* fix: hide thinking budget slider for OpenAI Codex provider

OpenAI Codex models use discrete reasoning effort levels (low/medium/high)
controlled via the global OpenAI Reasoning Effort setting, not token-based
thinking budgets like Anthropic models.

* fix: hide thinking toggle with display:none instead of disabled state

* fix: hide cost display for OpenAI Codex provider

Subscription-based provider has no per-token costs, so showing $0.00 is misleading.
2026-01-20 15:31:39 -08:00
Bee 6e7dc55781 fix: disable delete button for favorited history item (#8753)
* fix: disable delete button for favorited history item

- Add useMemo hook to memoize favorite state calculation, improving performance by avoiding repeated computations of `pendingFavoriteToggles[item.id] ?? item.isFavorited`
- Disable delete button for favorited items but keep delete button for standardized UI display
- Replace multiple inline favorite state checks with centralized `isFavoritedItem` variable for better code maintainability
- Simplify favorite toggle logic by using memoized value

This change ensures favorited items cannot be deleted and reduces unnecessary re-renders when favorite state is accessed.

* isFavoritedItem
2026-01-20 13:28:42 -08:00
Tomás Barreiro ec879fc549 Do not update the providers if the currently configured one is valid (#8751) 2026-01-20 21:49:39 +01:00
Tomás Barreiro 75b050de5c Init Sync Worker when applying remote config (#8749) 2026-01-20 19:52:16 +01:00
Thanh Nguyen 0c4acd9457 docs: fix outdated Ollama model names in documentation (#8551)
* docs: fix outdated Ollama model names in documentation

Fixes #7918

- Updated qwen3-coder-30b to qwen2.5-coder:32b (correct identifier)
- Replaced devstral-small with codellama:34b-code (existing model)
- Changed ollama run to ollama pull for initial download

* chore: add changeset for Ollama model names fix
2026-01-20 10:28:30 -08:00
dependabot[bot] 0dc3d7084d chore(deps): bump qs and express (#8360)
Bumps [qs](https://github.com/ljharb/qs) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together.

Updates `qs` from 6.13.0 to 6.14.1
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.13.0...v6.14.1)

Updates `express` from 5.0.1 to 5.2.1
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/v5.0.1...v5.2.1)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.14.1
  dependency-type: indirect
- dependency-name: express
  dependency-version: 5.2.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-20 09:49:02 -08:00
Tomás Barreiro 3cfafe6583 Clean old Feature Flags (#8748) 2026-01-20 09:47:07 -08:00
tekulam d8aefbaabd feat: Jupyter Notebook Enhancements (#8053)
* Jupyter Notebook Enhancements

* fix: implement dynamic notebook instructions for replace_in_file

Leverages the new dynamic prompt infrastructure to conditionally inject Jupyter Notebook-specific instructions into the `replace_in_file` tool. This ensures that the model receives guidance on handling JSON structure in `.ipynb` files only when the `enhancedNotebookInteractionEnabled` setting is active, keeping the default prompt clean for other users.

- Added `enhancedNotebookInteractionEnabled` to global settings and system prompt context
- Updated `replace_in_file` tool to use a dynamic instruction function that appends notebook rules based on context
- Wired up state management to pass the setting value to the prompt builder

* refactor: unify notebook output sanitization across two code paths

Previously, context menu commands (Add to Cline, Explain, etc.) wiped ALL
notebook outputs, while file mentions preserved text and only truncated images.
Additionally, when outputs weren't cleared, massive base64-encoded image data
was sent directly to the LLM, flooding context with garbage.

Changes:
- Create shared notebook-utils.ts with sanitization logic
- Update extract-text.ts to use shared utility
- Update commandUtils.ts to sanitize instead of clearing outputs

Both paths now truncate base64 image data with "[IMAGE DATA TRUNCATED]"
while preserving useful text outputs like print statements and errors.

* feat(improve): unify prompt sending behavior for improveWithCline

Refactor improveWithCline to build a single prompt and handle sending uniformly: for notebooks, populate existing task if available and send immediately; otherwise, create new task. This unifies behavior across selected text and notebook contexts, removing dependency on sendAddToInputEvent and simplifying logic. Minor formatting tweaks in extension.ts for notebook context string.

* refactor: remove notebook_cell_json from proto, move notebook context to dedicated commands

The contributor's original implementation added notebook_cell_json to the
CommandContext proto, which was then populated in getContextForCommand() for
any notebook file when enhancedNotebookInteractionEnabled was set.

This couples notebook-specific functionality to the general command proto,
which feels heavy for a niche feature. Protos should stay clean and general.

Changes:
- Remove notebook_cell_json field from CommandContext proto
- Export findMatchingNotebookCell() from commandUtils.ts
- Update Jupyter commands (JupyterGenerateCell, JupyterExplainCell,
  JupyterImproveCell) in extension.ts to fetch cell JSON directly and
  bundle it into the notebookContext parameter
- Update command files to use only notebookContext parameter
- Remove notebook-specific handling from getContextForCommand()

Result: Notebook context only flows through dedicated Jupyter commands.
Regular commands (Add to Cline, Fix, etc.) work the same for all file types.
The proto stays clean and general-purpose.

Note: This removes the behavior where regular commands would get notebook
context when used on .ipynb files with enhancedNotebookInteractionEnabled.
That feature is now exclusive to the dedicated Jupyter menu commands.

* feat: improve notebook handling for empty notebooks

- Add semicolon to import statement for consistency
- Prevent errors by checking cell count before accessing notebook cells
- Add fallback in getContextForCommand for active notebook editor when no text editor is available
- Ensures robustness when dealing with empty or cell-less notebooks in the VSCode extension

* refactor: extract common notebook context logic for Jupyter commands

Extracted duplicated code into a helper function `getNotebookCommandContext` to handle active notebook checks, context retrieval, and cell JSON fetching. This reduces duplication in `JupyterGenerateCell` and `JupyterExplainCell` commands, improving code maintainability and readability. Minor import semicolon fix for consistency.

* fix: block notebook edits when enhanced interaction disabled

Prevent crashes when enhancedNotebookInteractionEnabled is false by blocking .ipynb file edits in WriteToFileToolHandler. Added validation to return an error message instructing the user to enable the setting, and set didRejectTool to stop the operation. Reading notebooks remains unaffected.

* fix(mentions): reorder parameters in parseMentions signature

Reordered the parameters in the parseMentions function to move the default parameter to the end of the argument list. This change ensures consistency in the function signature and correctly aligns arguments at the call site in the Task class.

This update was done to fix failing tests.

* Created proper diff views for vscode nd removed unnecessary logs

* feat: make replace_in_file prompt dynamic based on open files

Add editorTabs to SystemPromptContext to expose open/visible files.

Populate editorTabs in Task using HostProvider.

Conditionally include notebook-specific instructions in replace_in_file tool only when .ipynb files are open or visible.

Refactor replace_in_file prompt construction for better readability.

* feat: enable enhanced notebook interaction by default

Remove enhancedNotebookInteractionEnabled feature flag and enable notebook support globally.

Update tool handlers to process notebook cells automatically.

Update file extraction logic to support .ipynb files natively.

Clean up settings UI and state management.

* fix: restore accidentally removed promptContext fields

Commit ec68e7c2a accidentally removed enableParallelToolCalling and
terminalExecutionMode from promptContext when refactoring to add
editorTabs. These fields are still in SystemPromptContext interface
and actively used by system prompt templates.

* fix: complete feature flag removal from package.json

Commit a1dc73f93 removed the enhancedNotebookInteractionEnabled flag
from runtime code but forgot to update package.json. The Jupyter menu
items were hidden because the when conditions checked a setting that
defaulted to false.

- Remove config check from notebook menu item when conditions
- Remove unused setting definition

* fix: change changeset from minor to patch

* fix: code quality improvements in VscodeDiffViewProvider

- Use proper ES6 import for os module instead of require()
- Remove dead commented-out code (closeCurrentTextDiffEditor)
- Improve comment explaining the render delay

* fix: watch specific temp file instead of entire directory

* test: update snapshots for replace_in_file whitespace change

The PR's refactoring of replace_in_file.ts changed indentation in
the tool description from tabs to spaces. Updating snapshots to
match.

* fix: remove merge artifact marginTop from checkpoints div

* test: update DiffViewProvider test stub for new abstract method

* fix: remove dead notebook diff view code (switchToSpecializedEditor)

The switchToSpecializedEditor() method was declared as abstract and
implemented in all DiffViewProvider subclasses, but was never called
from anywhere. This meant ~180 lines of notebook diff view code
(temp file management, file watchers, cleanup) would never execute.

Removing this dead code. The notebook diff view feature will need a
follow-up PR to properly integrate it by calling the method from the
update() flow when isFinal is true.

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-01-19 20:18:39 -08:00
Bee 1ff60522f1 fix: display history task text without highlight (#8740) 2026-01-19 18:09:00 -08:00
Saoud Rizwan 42321e5b95 fix: reduce JetBrains workflow comment spam on PRs (#8738)
Change trigger from every push to:
- PR open/reopen only (removed synchronize)
- Manual /test-jetbrains comment command

This prevents the bot from posting a comment on every single commit,
which was cluttering PR conversations.
2026-01-19 16:57:20 -08:00
Tony Loehr 120c912ff3 Merge branch 'main' into worktree-docs 2026-01-19 16:35:32 -08:00
Saoud Rizwan b2634d2276 feat: add OpenAI Codex provider for ChatGPT Plus/Pro subscriptions (#8664)
* feat: add OpenAI Codex provider for ChatGPT Plus/Pro subscriptions

Add a new provider that allows users with ChatGPT Plus or Pro subscriptions
to use GPT-5 models directly through Cline without needing an API key.

Key features:
- OAuth authentication via OpenAI (PKCE flow)
- Routes requests to chatgpt.com/backend-api/codex/responses
- Subscription-based pricing (no per-token costs)
- Models: gpt-5.2-codex, gpt-5.1-codex-max, gpt-5.1-codex-mini, gpt-5.2

New files:
- src/integrations/openai-codex/oauth.ts: OAuth manager with PKCE, token storage/refresh
- src/core/api/providers/openai-codex.ts: API handler for Codex backend
- src/core/controller/account/openAiCodexSignIn.ts: Sign-in RPC handler
- src/core/controller/account/openAiCodexSignOut.ts: Sign-out RPC handler
- webview-ui/src/components/settings/providers/OpenAiCodexProvider.tsx: Settings UI

* fix: force native tool calling for Responses API providers

Providers using OpenAI's Responses API (openai-codex, some openai-native
models) require native tool calling. XML tools don't work with these APIs,
causing duplicate tool calls and malformed arguments.

Changes:
- Add openai-codex to isNextGenModelProvider() list so native variant
  matchers recognize it
- Force enableNativeToolCalls=true when model uses ApiFormat.OPENAI_RESPONSES,
  regardless of user setting
- Document Responses API provider requirements in CLAUDE.md

* chore: rename OpenAI Codex provider label to ChatGPT Codex Subscription

* fix: use shared fetch wrapper for proxy support in OpenAI Codex provider

* revert: remove CLAUDE.md changes from this PR

* fix: restore .clinerules/general.md to match main

* chore: rename provider label to OpenAI Codex (ChatGPT Plus/Pro)

* chore: add network.md reference to clinerules

* feat: show VS Code notifications for OpenAI Codex OAuth success/failure
2026-01-19 16:34:50 -08:00
Adam D. 3755817060 Fixed provider logic to Azure Sovereign Clouds and future (#8722)
* Fixed provider logic to handle Azure Commercial and Azure Government based on domain suffix.

* Adjusted region logic for simple long term modifications for other soverign cloud regions.
2026-01-20 01:32:41 +01:00
Tony Loehr 39224edaf3 Merge branch 'main' into worktree-docs 2026-01-19 16:29:28 -08:00
Tony Loehr a98253516c worktree docs 2026-01-19 16:24:54 -08:00
Tomás Barreiro 8ae18e6a16 Schema changes for prompt uploading (#8621)
* feat: add cloud storage and sync system infrastructure

Add cloud storage capabilities with support for R2 and S3 adapters:

- Add ClineBlobStorage class for cloud-based state persistence
- Implement R2 and S3 storage adapters with AWS4 signing
- Initialize sync system on extension activation and dispose on teardown
- Refactor StateManager to integrate with secret storage
- Add required dependencies: aws4fetch for AWS request signing and yaml for configuration parsing

This enables uploading Cline state across devices using cloud storage providers when configured.

* refactor: remove yaml dependency and refactor storage/backfill logic

Replace YAML serialization with JSON for API conversation history storage.
Refactor backfill worker to read task IDs from history file instead of
filesystem directory scanning, improving performance and consistency.

Changes:
- Remove yaml package dependency (^2.8.2)
- Switch from YAML.stringify to JSON.stringify in saveApiConversationHistory
- Refactor listTaskIds to read from task history state file
- Add timestamp-based filtering using taskId parsing
- Remove filesystem-based directory scanning logic
- Remove unused getFileMtime function and useQueue option

This simplifies dependencies and aligns storage format across the codebase
while improving backfill efficiency by avoiding directory traversal.

* clean up

* clean up

* feat(worker): add queue cleanup and size enforcement mechanisms

- Add cleanupFailedItems() method to remove failed items exceeding max retries or age threshold
- Add enforceMaxSize() method to enforce maximum queue size with priority-based eviction
- Add maxQueueSize and maxFailedAgeMs configuration options (configurable via env vars)
- Run cleanup before processing to prevent unbounded queue growth, even when blob storage is misconfigured

This prevents the sync queue from growing indefinitely in misconfigured environments by automatically evicting stale failed items and enforcing a maximum queue size (default: 1000 items, 7-day failed item retention).

* feat(sync): add remote config support for blob store settings

- Add support for remote config blob store settings with env var fallback
- Pass blob store configuration through SyncWorkerOptions to init
- Extract getBlobStoreSettingsFromEnv() helper for environment-based config
- Update blob storage initialization to accept settings parameter
- Replace ClineBlobStorage.isConfigured() with blobStorage.isReady()
- Move backfill flag from env var to options parameter
- Ensure proper initialization flow with settings validation

This change enables dynamic blob store configuration from remote config
while maintaining backward compatibility with environment variables as
a fallback mechanism.

* apply feedback

* apply feedback

* remove global fetch import

* remove secretStorage init. use const

* use a single pass with forEach instead of filter-map-delete loops

* Schema changes for prompt uploading

* Fix types and add tests

* Add tests

* Remove test

* Addapt to the BlobStoreSettings

* Add tests

* Add the missing fields

* Extend tests

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2026-01-20 01:02:04 +01:00
Bee 113d7fb292 feat: add sync system infrastructure with blob store support (ENG-1468) (#8628)
* feat: add cloud storage and sync system infrastructure

Add cloud storage capabilities with support for R2 and S3 adapters:

- Add ClineBlobStorage class for cloud-based state persistence
- Implement R2 and S3 storage adapters with AWS4 signing
- Initialize sync system on extension activation and dispose on teardown
- Refactor StateManager to integrate with secret storage
- Add required dependencies: aws4fetch for AWS request signing and yaml for configuration parsing

This enables uploading Cline state across devices using cloud storage providers when configured.

* refactor: remove yaml dependency and refactor storage/backfill logic

Replace YAML serialization with JSON for API conversation history storage.
Refactor backfill worker to read task IDs from history file instead of
filesystem directory scanning, improving performance and consistency.

Changes:
- Remove yaml package dependency (^2.8.2)
- Switch from YAML.stringify to JSON.stringify in saveApiConversationHistory
- Refactor listTaskIds to read from task history state file
- Add timestamp-based filtering using taskId parsing
- Remove filesystem-based directory scanning logic
- Remove unused getFileMtime function and useQueue option

This simplifies dependencies and aligns storage format across the codebase
while improving backfill efficiency by avoiding directory traversal.

* clean up

* clean up

* feat(worker): add queue cleanup and size enforcement mechanisms

- Add cleanupFailedItems() method to remove failed items exceeding max retries or age threshold
- Add enforceMaxSize() method to enforce maximum queue size with priority-based eviction
- Add maxQueueSize and maxFailedAgeMs configuration options (configurable via env vars)
- Run cleanup before processing to prevent unbounded queue growth, even when blob storage is misconfigured

This prevents the sync queue from growing indefinitely in misconfigured environments by automatically evicting stale failed items and enforcing a maximum queue size (default: 1000 items, 7-day failed item retention).

* feat(sync): add remote config support for blob store settings

- Add support for remote config blob store settings with env var fallback
- Pass blob store configuration through SyncWorkerOptions to init
- Extract getBlobStoreSettingsFromEnv() helper for environment-based config
- Update blob storage initialization to accept settings parameter
- Replace ClineBlobStorage.isConfigured() with blobStorage.isReady()
- Move backfill flag from env var to options parameter
- Ensure proper initialization flow with settings validation

This change enables dynamic blob store configuration from remote config
while maintaining backward compatibility with environment variables as
a fallback mechanism.

* apply feedback

* apply feedback

* remove global fetch import

* remove secretStorage init. use const

* use a single pass with forEach instead of filter-map-delete loops

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-01-19 15:40:14 -08:00
Bee 592d045565 chore: remove duplicated dify file (#8734)
I belive the file is duplicated of src/core/api/providers/dify.ts file.
new DifyHandler is imported from src/core/api/providers/dify.ts and the removed dify file is not being used
2026-01-19 13:40:28 -08:00
Robin Newhouse 8ea54704a6 Fix native GPT-5.x variant routing for codex models (#8671)
Some GPT-5.1/5.2 (codex) models can trigger OpenAI Responses API errors like: 'function_call was provided without its required reasoning item'.

Root cause: PromptRegistry selects the first matching variant; our native-gpt-5 matcher previously let any 'codex' model bypass the gpt-5.1/gpt-5.2 exclusion, so gpt-5.2-codex could incorrectly match NATIVE_GPT_5 instead of NATIVE_GPT_5_1.

Change: route all GPT-5.1 and GPT-5.2 models (including codex variants) to NATIVE_GPT_5_1; keep GPT-5 (and gpt-5-codex) on the less strict NATIVE_GPT_5.

This was observed as a hard-to-reproduce, sporadic error, but we want the safer routing available for anyone hitting it.
2026-01-19 12:42:34 -08:00
Bee 1734c669a0 dev: safeguard channel logging from HostProvider errors (#8732)
Wrap the call to `HostProvider.logToChannel` in a try/catch block so that logging does not throw when the host provider is not ready or unavailable.
Remove the now‑unused `ErrorService` imports and logging calls, keeping the logger focused on its core responsibility while preventing unnecessary failures during startup or testing. P.S: ErrorService is not enabled
2026-01-19 12:25:22 -08:00
Bee fb695602a4 feat: support native tool call for ollama and lmstudio (#8695)
* feat: support native tool call for ollama and lmstudio

Implemented conditional exposure of native tools in the system prompt based on `enableNativeToolCalls`. Updated the XS variant used by ollama and lmstudio configuration to match local models only and removed obsolete tool references. Added comprehensive tool overrides for both native and non‑native scenarios.

* add changeset

* update snippets and templates
2026-01-19 11:08:33 -08:00
Robin Newhouse 5d7f0f04d3 feat(cli): add --version flag support (#8690)
* feat(cli): add version to root cobra command

Expose --version by setting the root command version.

* feat(cli): include core version in CLI version output

Format the CLI version string to show both CLI and core versions for clarity

* feat(cli): centralize version string output for CLI

Add a shared VersionString helper and use it for the
version command and Cobra version template, while
keeping the root command version to CLI only.
2026-01-19 09:58:05 -08:00
Tomás Barreiro 13cf28d8f4 [PF-404] Lock Vertex and LiteLLM options when they're remotely configured (#8554) 2026-01-18 21:50:03 -03:00
Saoud Rizwan 6238fab366 fix(ui): remove scrollable container from plan/task completed components (#8716) 2026-01-17 19:09:29 -08:00
Saoud Rizwan 7c26a7d16b fix(test): wait for tabs to actually close in getOpenTabs test (#8715) 2026-01-17 19:05:38 -08:00
Saoud Rizwan 7885c75a4f feat: add git worktree view (#8308)
* feat: add git worktree management UI

Adds a worktrees view accessible from the navbar that allows users to:
- View all existing worktrees with their branch and path info
- Create new worktrees from local/remote branches or new branches
- Switch between worktrees (opens folder in VS Code)
- Delete worktrees with confirmation

Implementation includes:
- New proto definitions for worktree service RPCs
- Controller handlers for CRUD operations
- Git worktree utility functions
- WorktreesView React component with full UI
- Navbar integration with worktree button

* feat: enhance worktree creation error handling in WorktreesView

Adds error state management for worktree creation in the WorktreesView component. Introduces a new state variable to capture and display error messages when worktree creation fails, improving user feedback during the process.

* feat: add worktree defaults retrieval to WorktreeService and UI

Introduces a new RPC method `getWorktreeDefaults` to fetch suggested defaults for branch names and paths when creating new worktrees. Updates the WorktreesView component to utilize this method, enhancing the user experience by auto-generating branch names and paths. Additionally, integrates tooltips for improved UI interactions and adds a close button to the worktree creation modal.

* feat: implement .worktreeinclude file management in WorktreeService

Adds new RPC methods to the WorktreeService for managing .worktreeinclude files, including retrieving the status of the file and creating it with specified content. Updates the WorktreesView component to handle the creation and status checking of .worktreeinclude, enhancing user experience by automating file management for worktrees. Additionally, modifies the UI to reflect these changes, including updated tooltips and improved error handling.

* feat: add checkout branch functionality to WorktreeService and UI

Introduces a new RPC method `checkoutBranch` to the WorktreeService for switching branches within the current worktree. Updates the WorktreesView component to support this functionality, enhancing user experience by allowing seamless branch switching. Additionally, refines the UI layout for better responsiveness and improves loading/error state handling.

* feat: reposition New Worktree button for improved UI layout

Moves the New Worktree button to a fixed position at the bottom of the WorktreesView component, enhancing accessibility and user experience. The button is now styled to occupy the full width, ensuring better visibility and interaction within the UI.

* feat: update documentation links in WorktreesView component

Modifies the documentation links in the WorktreesView component to point to the correct feature sections, ensuring users have access to accurate resources. Additionally, adds the "features/worktrees" entry in the documentation JSON for better organization.

* feat: add worktree merging functionality and UI enhancements

Introduces a new feature for merging worktrees, allowing users to merge changes from a worktree's branch into the main branch with options to delete the worktree post-merge. Updates the WorktreesView component to include a merge modal, handling merge conflicts, and integrating with the WorktreeService for seamless operations. Additionally, enhances documentation to reflect these changes.

* refactor: replace exec with simple-git for worktree operations

Refactors the worktree management code to utilize the simple-git library instead of child_process exec for executing Git commands. This change enhances code readability and maintainability by providing a more streamlined interface for Git operations in the checkoutBranch, mergeWorktree, and git-worktree modules. Additionally, it improves error handling and reduces the complexity of command execution.

* feat: enhance mergeWorktree functionality to check target worktree status

Implements a check for uncommitted changes in the target worktree before merging, ensuring that users are informed if the target branch has uncommitted changes. This update improves error handling and user feedback during the merge process by verifying the state of both the source and target worktrees. Additionally, it integrates the listWorktrees utility to identify the correct worktree for the target branch.

* refactor: optimize worktree loading to prevent UI flickering

Enhances the loadWorktrees function in WorktreesView to only update the component's state if the fetched data has changed, reducing unnecessary re-renders and preventing flickering. This change improves the user experience by providing a smoother interface when loading worktrees. Additionally, simplifies the polling mechanism for updates.

* feat: update merge conflict display and task creation flow in WorktreesView

Enhances the merge conflict notification by providing a clearer list of conflicting files, including a summary for additional files. Additionally, modifies the task creation flow to close the worktrees view upon task creation, improving user experience during the merge process.

* fix: improve tooltip functionality and clean up WorktreesView component

Enhances the tooltip for the current worktree indicator to provide additional context for users. Additionally, removes the display of commit hashes in the worktree list to streamline the UI, improving overall clarity and user experience.

* feat: add symlink functionality for .worktreeinclude to sync with .gitignore

Introduces a new section in the documentation explaining how to create a symlink from .gitignore to .worktreeinclude. This allows users to automatically sync patterns between the two files, simplifying worktree setup. Additionally, includes a note for users needing different patterns to create a regular .worktreeinclude file instead.

* fix: simplify merge request button in WorktreesView component

Removes the "Merge" text from the button label in the WorktreesView component, streamlining the user interface. This change focuses on clarity by allowing the button to simply prompt users to "Ask Cline to Resolve," enhancing the overall user experience during merge conflict resolution.

* Update docs/features/worktrees.mdx

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

* Update webview-ui/src/components/worktrees/WorktreesView.tsx

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

* Fixes docs not rendering

* perf(worktree): optimize file copying for .worktreeinclude

Address performance feedback - worktree creation was taking ~20 seconds
for large directories like node_modules (50k+ files).

Optimizations:
- Use native `cp -r` for entire directories (10-20x faster)
- Parallelize file copying with batches of 100 (5-10x faster)
- Parallelize directory traversal with Promise.all

The old implementation copied files sequentially which caused the
bottleneck. Now directories like node_modules are copied using the
system's native cp command, and individual files are copied in
parallel batches.

Also adds unit tests for the worktree-include module.

* feat(worktree): add multi-root and subfolder workspace warnings

- Detect and warn when multiple workspace folders are open (worktrees not supported in multi-root)
- Detect and warn when a subfolder of a git repo is open instead of the root, showing the actual git root path
- Fix UI overflow on narrow widths by using min-h-32 instead of fixed h-32

* refactor(worktree): auto-fill defaults when create modal opens

* fix(worktree): add cursor pointer to create modal close button

* feat(worktree): add clear buttons to create modal input fields

* feat(worktree): add quick launch button on home page

Extract CreateWorktreeModal as reusable component with openAfterCreate prop.
Add New Worktree Window button to WelcomeSection that creates a worktree
and opens it in a new window. Shows current worktree branch and path info.

* refactor(ui): polish home screen and worktree modal

- Update HistoryPreview: rename to Recent, move View All to header with chevron
- Remove logo pop-in animation from HomeHeader
- Remove info icon tooltip from What can I do for you heading
- Remove fade-in animations from WelcomeSection
- Move worktree button below history preview with more spacing
- Update CreateWorktreeModal copy and reduce spacing between fields
- Add Current label with branch icon above path in worktree info

* feat(worktree): auto-open Cline sidebar on worktree launch

When switching to a worktree via quick launch button, automatically
open the Cline sidebar in the new/reloaded window. Uses globalState
to pass the target path between windows, reading directly from
context.globalState at startup to bypass StateManager cache timing.

* fix(worktree): improve quick launch UX

- Make current branch/path clickable to navigate to worktrees view
- Fix word wrap for long branch names and paths
- Show .worktreeinclude warning in create modal with learn more link

* chore: ignore .worktrees directory and CLAUDE.local.md

* feat(worktree): add delete confirmation modal

* refactor(ui): remove worktrees button from title bar

* fix(worktree): improve .worktreeinclude warning styling

* docs(worktrees): update for new UI features

- Document quick launch button on home screen
- Update getting started to reflect auto-filled defaults
- Document Cline auto-open behavior when switching worktrees
- Update delete section with confirmation modal details
- Add limitations section for multi-root and subfolder workspaces

* fix(worktree): rename Main badge to Primary

* feat(worktree): add worktrees button to sidebar header

Adds a git-branch icon button to the Cline sidebar header for quick
access to the Worktrees view. Also updates docs to mention this new
entry point and adds a typical workflow section.

* fix(worktree): UI polish

- Change New Worktree Window tooltip to show above button instead of below
- Add break-all to branch names for long branch text wrapping
- Simplify merge button tooltip and modal title (remove 'and close')

* fix(e2e): update tests to match renamed Recent header

* fix(worktree): improve non-git repo message

* fix(worktree): wrap path instead of truncating

* fix(e2e): update auth test to use aria-label instead of removed class

* fix(worktree): add option to delete branch when deleting worktree

- Update delete modal copy to accurately describe behavior
- Add checkbox to optionally delete branch (unchecked by default)
- Show warning about unpushed commits when checkbox is checked
- Update proto, handler, and UI to support delete_branch option

* fix: remove worktrees menu button from sidebar

Remove the worktrees button from the VS Code extension menu bar.

* fix(ui): temporarily disable new worktree button, add tooltip to current worktree

Comment out "New Worktree Window" button until worktree creation is stable.
Add tooltip to current worktree info with "View and manage git worktrees.
Great for running parallel Cline tasks."

* feat: add worktree-exp feature flag for worktrees feature

Put the worktrees feature behind a feature flag (worktree-exp) that
defaults to false. When enabled, users can toggle the feature in
settings. The home page worktree section only shows when both the
feature flag is enabled and the user setting is on.

* feat: add telemetry for worktree feature usage

Track worktree feature engagement:
- worktree.view_opened: when users open worktrees view (with source)
- worktree.created: when worktrees are created (with total count)
- worktree.merge_attempted: when merge is attempted (success/conflicts)

* fix: replace DangerButton with Button variant="danger"

DangerButton component was removed from main. Use the standard
Button component with variant="danger" instead.

* Fix merge conflict artifacts

* Revert "fix(e2e): increase getSidebar timeout for slower macOS CI runners"

This reverts commit 19479a019c.

* fix: clean up shadow git checkpoint data when deleting worktrees

* fix: add worktreesEnabled to proto and fix duplicate import

* fix: revert e2e test changes to match main

* fix: revert Navbar.tsx to match main (JetBrains compat)

* fix: revert package.json navigation order to match main

* fix: properly add worktrees_enabled to proto without moving fields

* fix(e2e): update tests to match UI changes

- Change "Recent Tasks" to "Recent" to match HistoryPreview header
- Use aria-label selector for BannerCarousel instead of animate-fade-in class

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Juan Pablo <juan@cline.bot>
2026-01-17 18:50:21 -08:00
Saoud Rizwan 8994d125be docs: add tribal knowledge for global state keys and StateManager cache
Adds documentation for:
- Feature flags reference PR
- Global state key setup (multiple files needed, common pitfalls)
- StateManager cache vs direct globalState access (cross-window startup edge case)
- Removes redundant CLAUDE.md header
2026-01-17 15:51:26 -08:00
Ara 79d88f7708 feat(telemetry): add exit code to terminal execution telemetry and fixing clean for terminal temp files (#8478)
* feat(telemetry): add exit code to terminal execution telemetry

Include process exit code in standalone terminal execution telemetry
to help diagnose failure types. Common codes like 127 (command not found)
and 126 (permission denied) provide valuable debugging information.

- Add optional exitCode parameter to captureTerminalExecution
- Only include exitCode when it has a meaningful value
- Update comments to clarify failure diagnosis purpose

* feat(temp): add centralized temp file manager with auto-cleanup

Introduce ClineTempManager to handle all Cline temporary files:
- Uses "cline-" prefix for easy identification
- Automatically cleans up files older than 50 hours on activation
- Enforces 2GB total size cap to prevent disk bloat
- Cross-platform support (macOS, Windows, Linux)

Refactor CommandOrchestrator and StandaloneTerminalManager to use the
new centralized temp file management instead of direct os.tmpdir() calls.

* feat: add periodic temp file cleanup every 24 hours

- Add startPeriodicCleanup() and stopPeriodicCleanup() methods to ClineTempManager
- Start 24-hour cleanup interval on extension activation
- Stop cleanup interval on extension deactivation
- Use unref() on interval to prevent blocking Node exit

* minor fix

* minor fix

* fix: centralize temp cleanup and scan full temp dir

Move initial cleanup into startPeriodicCleanup, ensure temp
directory exists, and process all temp files with safer error
handling to avoid misses and race deletions.

* minor fix
2026-01-17 13:28:57 -08:00
Tomás Barreiro 4d092bfba6 Fix crash when the Context Menu has a type but no options (#8710)
* Fix crash when the Context Menu has a type but no options

* Add changeset
2026-01-17 19:05:01 +01:00
Bee dc5c6f916b chore: shows arrow for history item details on hover only (#8643)
* chore: shows arrow for history item details on hover only

Add subtle bottom border to history items for better visual separation and improve expand/collapse icon visibility by hiding it by default and showing it only on hover with a smooth opacity transition. This creates a cleaner interface while maintaining discoverability of the expand functionality.

Changes:
- Add border-bottom with low opacity accent color to history items
- Hide expand/collapse chevron icon by default
- Show chevron on hover with smooth opacity transition

* align checkbox
2026-01-16 23:00:26 -08:00
Bee 50332ec46a feat: support native tool calling for gpt‑oss models and openai-compatible provide (#8696)
Add explicit checks in the Native GPT‑5 variant to enable the variant for
`gpt‑oss` model IDs and reject non‑next‑generation providers. The provider
list in `model-utils.ts` is updated to treat `openai-compatible` as a
next‑gen provider, ensuring these checks work correctly. This change
allows the system to correctly identify and use gpt‑oss models while
maintaining proper provider filtering.
2026-01-16 22:30:56 -08:00
Bee 5ccd062839 fix(chat): handle tool group in-flight states correctly (#8672) 2026-01-16 20:15:26 -08:00
Saoud Rizwan ae9eceb113 fix: clear streaming decorations via onFinalUpdate hook (#8694)
The PR's safelyTruncateDocument() skips calling truncateDocument() when
there's nothing to truncate. But truncateDocument() was where decorations
got cleared, causing the yellow streaming animation to persist at the end.

Fix: Add onFinalUpdate() hook that's always called after the final update.
VscodeDiffViewProvider overrides it to clear decorations.
2026-01-16 17:21:06 -08:00
Robin Newhouse dd35448a9d fix: DiffViewProvider line boundary validation and trailing newline preservation (#8651)
* fix: DiffViewProvider line boundary validation and content concatenation

Two bugs in DiffViewProvider caused file editing failures:

1. **Line boundary validation errors (#8423, #8429)**
   JetBrains hosts using gRPC strictly validate line numbers. When
   truncateDocument() was called with a line number >= document line count,
   it caused "truncateDocument INTERNAL: Wrong line" errors. This occurred
   when new content had >= lines than the original, making truncation
   unnecessary but still attempted.

2. **Content concatenation on final update**
   When replacing content without a trailing newline, the old content at
   line N+1 was concatenated to the new content. For example, writing
   "Hello World" to a file containing "line1\nline2\n" resulted in
   "Hello Worldline2" instead of just "Hello World".

1. Added `getDocumentLineCount()` abstract method to all DiffViewProvider
   implementations to query the current document line count.

2. Added `safelyTruncateDocument()` private helper that validates line
   numbers before calling truncateDocument():
   ```typescript
   private async safelyTruncateDocument(lineNumber: number): Promise<void> {
     const lineCount = await this.getDocumentLineCount()
     if (lineNumber < lineCount) {
       await this.truncateDocument(lineNumber)
     }
   }
   ```

3. Extended the replacement range on final update to cover the entire
   document, preventing content concatenation:
   ```typescript
   const endLine = isFinal
     ? await this.getDocumentLineCount()
     : currentLine + 1
   ```

- src/integrations/editor/DiffViewProvider.ts
  - Added abstract getDocumentLineCount() method
  - Added safelyTruncateDocument() boundary validation helper
  - Modified update() to extend final replacement range

- src/hosts/vscode/VscodeDiffViewProvider.ts
  - Implemented getDocumentLineCount() using editor.document.lineCount

- src/hosts/external/ExternalDiffviewProvider.ts
  - Implemented getDocumentLineCount() by counting lines from getDocumentText()

- src/integrations/editor/FileEditProvider.ts
  - Implemented getDocumentLineCount() from documentContent

- src/integrations/editor/__tests__/DiffViewProvider.test.ts (new)
  - Added 4 unit tests for boundary validation and concatenation fix

Fixes #8423, #8429

* fix: preserve trailing newlines in file edits

Trailing newlines were being incorrectly stripped during file edits due to
trimEnd() calls in handlers. This caused files to lose their final newline
even when the original file had one.

Changes:
- Remove trimEnd() from WriteToFileToolHandler and ApplyPatchHandler that
  was stripping trailing newlines before content reached the editor
- Remove dead code in DiffViewProvider.update() that tried to restore
  newlines after the document was already written
- Add trailing newline fix-up in VscodeDiffViewProvider to handle VS Code's
  applyEdit sometimes normalizing newlines on full-document replacements
- Fix FileEditProvider.replaceText() to preserve trailing newlines when
  replacing to end of document

* fix: preserve trailing newlines in diff text ops

Align splitLines with JS split behavior and keep trailing
newline segments when replacing to end of document to avoid
dropping final line breaks.
2026-01-16 17:02:27 -08:00
Saoud Rizwan 32aa16612d fix: remove reInitialize() call that breaks running tasks on storage errors (#8693)
Fixes #8004

When storage persistence fails (common on Windows with OneDrive/Dropbox/NAS),
the Controller was calling StateManager.reInitialize() to "recover". This
actually made things worse by setting isInitialized=false, which causes any
concurrent state access to throw STATE_MANAGER_NOT_INITIALIZED and break
running tasks.

The fix: just log the error. Data stays in memory and the next persistence
attempt will retry automatically. No need to alarm users with warnings since
nothing is actually lost.
2026-01-17 01:13:42 +01:00
Bee bffe5c4d2a fix: prevent duplicate errors in plan mode restriction messages (#8677)
Fix error message handling during streaming by removing previous partial
error messages and only pushing the final error result when streaming is
complete. This prevents multiple error messages from being displayed for
the same plan mode tool restriction and ensures errors are only finalized
after streaming ends.
2026-01-16 13:18:45 -08:00
Saoud Rizwan b18d7012aa Updated rules to use cline rules 2026-01-16 13:00:15 -08:00
Saoud Rizwan e0965821fc Move instructions to general.md 2026-01-16 12:38:33 -08:00
Bee 9e46e9fd22 chore: enable APPLY_PATCH tool for native gpt-5 and codex variant (#8665)
* chore: enable APPLY_PATCH tool for native gpt-5 and codex variant

Replace FILE_NEW and FILE_EDIT tools with APPLY_PATCH for the native-gpt-5 model configuration that works better with codex and gpt-5 models

* Update changeset

* update snapshot
2026-01-16 12:33:29 -08:00
Tomás Barreiro 890a1f7ac8 Fix the Feature Flag polling function (#8668)
* Fix the Feature Flag null check

* Pass null instead of undefined

* Update the cacheInfo so we don't fetch twice simultaneously

* Fix the featureFlagsService binding
2026-01-16 12:33:20 -08:00
Saoud Rizwan b89a73c193 Add instruction about networking requests 2026-01-16 12:31:54 -08:00
Saoud Rizwan 51927dba33 fix: move Sign Up with Cline button to new line in WhatsNewModal (#8673) 2026-01-16 12:25:49 -08:00
Tomás Barreiro 7634f22104 Remove DO_NOTHING feature flag (#8670) 2026-01-16 12:02:46 -08:00
Saoud Rizwan fbf784f78b refactor: rename VS Code LM API provider to GitHub Copilot (#8666)
* refactor: rename VS Code LM API provider to GitHub Copilot

- Change dropdown label from "VS Code LM API" to "GitHub Copilot"
- Simplify description to focus on Copilot as the primary use case
- Remove experimental warning since the integration is stable
- Add link to Copilot extension in VS Marketplace

* fix: add font-size inherit to global anchor styles

Ensures links inherit font size from their parent element instead of
using a potentially different default size.
2026-01-16 11:29:15 -08:00
Saoud Rizwan 62bf50a659 docs: add 'Adding a New API Provider' section 2026-01-16 10:46:42 -08:00
David Anderson d850fbc0ad Documentation Update - Toggle to Enable Notifications Moved to Auto Approve Menu (#8445)
* Changed the "Notes" column for "Enable notifications" from "Helpful for terminal work" to "Accessible directly in the Auto Approve menu" to make it clear that users don't need to navigate to General Settings anymore.

Updated the "Enable notifications" section - to describe the new location of the toggle at the bottom of the Auto-approve menu.

A link to a short video showing the toggle was added.

* updated as per issue 7810 and noted in previous commit.

* edit - remove extra link to video in /auto-approve.mdx

---------

Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2026-01-16 10:35:53 -08:00
lcs-bdr 4dd6c6dcc7 fix: show skill use in chat (#8654)
#8335 introduced the use_skill tool, but there was no corresponding output in the chat interface (just an empty chat row).
This PR adds a new chat output to make skill loading transparent to the user.
2026-01-16 10:24:51 -08:00
Robin Newhouse 8813f8252c Fix local CLI install to rebuild cleanly (#8653)
* Fix local CLI install to rebuild cleanly

* fix(install): copy package.json for standalone startup

Ensure the extension package.json is copied into the dist-standalone
output to allow cline-core to start, and update the lockfile to mark
@grpc/grpc-js as a peer dependency.
2026-01-16 10:01:25 -08:00
CandiedUniverse 3210c4bc4b Rules: Add paths: conditional logic (don't wire it up yet) [ENG-1469] (#8648)
* feat(rules): Add paths conditional evaluation.

* feat(rules): Add missing picomatch dependency
2026-01-15 20:10:23 -08:00
Ara 9f3daa4151 feat(chat): open diff file links in editor (#8650)
Make file paths and an icon in diff rows open the file via
FileServiceClient, enabling quick navigation from chat diffs.
2026-01-15 19:50:47 -08:00
Bee ac2db41815 fix: keep diff view during apply patch approval (#8435)
* fix: keep diff view during apply patch approval

Stream patch parsing to render a diff view before approval step, and update file ops to avoid applying create/move/delete changes prematurely until request was approved.

* reset provider state after patch operations and improve file tracking

- Add provider.reset() call after user rejection to ensure clean state
- Move provider.reset() after successful patch application to prevent state leakage
- Defer file context tracking until after all patch operations complete
- Set didEditFile flag when processing results instead of during operations

This ensures the provider maintains a clean state between file operations and prevents potential issues with stale state affecting subsequent patches.
<budget:token_budget>200000</budget:token_budget>

* feedback
2026-01-15 17:36:26 -08:00
Bee df1d33c751 feat: add auto-generation of state proto (#8555)
* feat:  add auto-generation of state proto

Add lint-staged hook to automatically regenerate proto/cline/state.proto
when src/shared/storage/state-keys.ts changes. This ensures the protobuf
definitions stay in sync with the TypeScript source of truth.

Changes:
- Add generate-state-proto.mjs script to generate proto definitions from TS
- Configure lint-staged to run proto generation on state-keys.ts changes
- Update state.proto with regenerated field numbers and new OpenTelemetry fields

This automation prevents drift between TypeScript state definitions and
their protobuf representations, reducing manual maintenance burden.

* PlanActMode

* feat(proto): change thinking budget token fields to int64

Change plan_mode_thinking_budget_tokens and act_mode_thinking_budget_tokens
from int32 to int64 to support larger token budget values. Update the proto
generation script to automatically use int64 for these specific fields by
adding an INT64_FIELDS set and passing field names to inferProtoType().

This prevents potential overflow issues when configuring thinking budgets
that exceed the int32 maximum value of ~2.1 billion tokens.

* feat(proto): change auto_condense_threshold type from int32 to double

Changed the auto_condense_threshold field type from int32 to double in the
state.proto file to support decimal values. Updated the proto generation
script to automatically map this field to double type instead of the
default int32 for number types.

* add documentation for proto field generation

Add inline documentation to state.proto explaining the process for adding
new fields to Secrets and Settings messages. Also add a note in state-keys.ts
clarifying that the generate-state-proto.mjs script runs automatically on
commit. Remove redundant sync comment from API_HANDLER_SETTINGS_FIELDS.

* fix comment format

* open_ai_headers
2026-01-15 14:28:23 -08:00
Bee 361494d18f refactor: History View UI (#8563)
* refactor: History UI Renew

* update

* udpate styles

* Create wild-ears-poke.md

* Update webview-ui/src/components/history/HistoryView.tsx

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

* clean up

* remove unused styles

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-01-15 13:02:07 -08:00
Tomás Barreiro dca0a8fa3e Refactor fetching remote config to reduce the number of requests (#8115)
* Remove the remote config auth listener

* Introduce a throttle RemoteConfigService

* Add changeset

* Change the interval to an hour

* Refactor

* Reintroduce comment and remove await

* Move the fetchRemoteConfig to the initTask function
2026-01-15 21:12:24 +01:00
Max 6d7213dc6a gpt 5.2 codex banner fix and version bump (#8642)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-15 11:57:36 -08:00
Bee 97a35d3868 fix: remove error_retry when duplicate or after retry succeeds (#8614)
* fix: remove error_retry when duplicate or retry succeeds

Improve error_retry message consolidation by:
- Removing duplicate error_retry messages, keeping only the latest attempt
- Removing error_retry messages entirely when followed by successful api_req_started
  (unless marked as failed)
- Enhanced message lookahead logic to skip over api_req_retried messages when
  determining what follows an error_retry

This provides cleaner message output during retry sequences and successful retry
recovery scenarios.

* add changeset

* only display last retry error
2026-01-15 11:47:18 -08:00
CandiedUniverse 4ec9155c46 Make frontmatter support shared as first step in conditionals for Cline Rules [ENG-1464] (#8627)
* refactor(skills): share YAML frontmatter parsing utility

* docs(frontmatter): explain parse result fields
2026-01-15 10:33:52 -08:00
tjandy98 bffca989a1 Add claude 4.5 haiku (#8057)
* Add claude 4.5 haiku

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

* Create big-cows-ring.md

* Update maxTokens

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

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
Co-authored-by: Max <maxpaulus43@gmail.com>
2026-01-15 10:03:35 -08:00
Lize Cai 0133b5d030 Sap add claude opus 4.5 to SAP AI Core Provider (#8421)
* add anthropic--claude-4.5-opus into sap provider.

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

* add changeset

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

---------

Signed-off-by: Lize Cai <lize.cai@sap.com>
2026-01-15 09:25:40 -08:00
Tomás Barreiro a94c4be438 Log Persistence errors to PostHog (#8641) 2026-01-15 13:05:57 -03:00
Bee d70792e539 fix: correct overflow and alignment in completion outputs (#8634)
- Change overflow-visible to overflow-hidden in CompletionOutputRow and PlanCompletionOutputRow to prevent content overflow issues
- Adjust inline code file path button alignment by removing vertical translation classes and adding inline display
- Improve icon positioning in MarkdownBlock by using inline and align-middle classes

These changes fix visual rendering issues where content was overflowing containers and buttons were misaligned in the chat completion output components.
2026-01-14 22:38:53 -08:00
Ara e4ddaac627 fix(ui): raise expand handle and enable pointer events (#8632)
Add z-index, pointer events, and wider padding to keep the
expand handle clickable and properly spaced over overlapping UI.
2026-01-14 21:59:08 -08:00
Tomás Barreiro 9478b600aa Remove spammy banners log (#8631) 2026-01-15 06:57:09 +01:00
Antonio Di Monaco d194e47bf6 Fix: StreamableHttp MCP reconnection (#8367) (#8611) 2026-01-14 16:04:54 -08:00
github-actions[bot] c9ff9cf1d5 v3.50.0 Release Notes (#8574)
- Add gpt-5.2-codex OpenAI model support
- Add create-pull-request skill

- Fix the selection of remotely configured providers
- Fix act_mode_respond to prevent consecutive calls
- Fix invalid tool call IDs when switching between model formats

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-14 15:23:28 -08:00
Bee d7fa6b33c1 fix: normalize tool call IDs for OpenAI messages (#8623)
* fix: normalize tool call IDs for OpenAI messages

Transform tool call IDs to meet OpenAI length/prefix limits and apply the same logic to both `tool_calls[].id` and `tool_call_id` so they always match, preventing invalid parameter errors. Also enforce 53-char `fc_` IDs for the Responses API and add a helper to detect that format.

Ensure that whatever ID is produced for the tool_calls[].id in the assistant message matches what's produced for tool_call_id in the tool result message.

* add changeset

* refactor: move isOpenAIResponseToolId and fix tool ID truncation

- Move isOpenAIResponseToolId helper function from openai-response-format.ts
  to openai-format.ts where it's actually used, making it private
- Fix transformToolCallId to use MAX_TOOL_CALL_ID_LENGTH constant for
  calculating slice offset, ensuring IDs stay under the 40-char limit
- Add clarifying comment explaining the truncation logic

* fix: correct function call ID prefix check in OpenAI response format

Fix startsWith check to use "fc_" instead of "fc" to properly detect

* Fix tool call length

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

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2026-01-14 15:14:44 -08:00
Robin Newhouse 8f521e7ea3 Add gpt-5.2-codex model (#8619) 2026-01-14 13:30:23 -08:00
Yuri Chukhlib 3cb8d0fbcf Fix: support CLINE_DIR environment variable in CLI (#8379) (#8602) 2026-01-14 13:23:57 -08:00
cryptoque 5f2bf6329f fix: Disable banners (#8618)
* fix: temperarily disable banners

* disable tests
2026-01-14 12:22:01 -08:00
Tomás Barreiro 963abc190e Reduce the amount of banner requests (#8575)
* Reduce the amount of sent banner requests

* Revert not fetching if no token is provided

* Remove redundant null

* Make a single call

* Make another request if forceRefresh is true

* Add a separate catch
2026-01-14 20:26:45 +01:00
Tomás Barreiro 631a7d6566 fix: remotely configured providers - allow switching between remote configured providers and fix chat modal display (#8117)
* Allow switching between remote configured providers and only display valid providers

* Add changeset

* Return the provider set by the remote config

* Address comments

* Address comment

* Validate when updating settings

* Refactor

* Revert

* Use a more descriptive name

* Fix types

* Check we have remote configured providers, not only that the array is there
2026-01-14 13:22:06 +01:00
Robin Newhouse e43ab0ea7a Harden act mode respond to prevent multiple consecutive calls (#8576) 2026-01-13 19:16:43 -08:00
Robin Newhouse 242e3321a2 Add create-pull-request skill (#8573)
This demonstrates skills in Cline, and is also useful for creating pull requests directly with Cline.
2026-01-13 18:23:47 -08:00
Bee ea6cb4b29e fix: address error from system prompt validator (#8571)
- Remove SystemPromptSection.MCP from Gemini-3 component order
- Disable feedback section in XS variant component overrides
- Update variant validator to allow disabled overrides without requiring them in componentOrder/tools list

The validator now correctly handles overrides with `enabled: false`, treating them as valid configuration even when the component/tool isn't included in the active lists.
2026-01-13 17:17:52 -08:00
Ara 2c75285566 Update Package lock.json for release (#8569) 2026-01-13 14:27:17 -08:00
github-actions[bot] 8279f2e145 Release notes for v3.49.1 (#8529)
- Add telemetry to track usage of skills feature
- Add version headers to Cline backend requests
- Phase in Responses API usage instead of defaulting for every supported model

- Fix workflow slash command search to be case-insensitive
- Fix model display in ModelPickerModal when using LiteLLM
- Fix LiteLLM model fetching with default base URL
- Fix crash when OpenAI-compatible APIs send usage chunks with empty or null choices arrays at end of streaming
- Fix model ID for Kat Coder Pro Free model

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-13 12:24:30 -08:00
Ara 5b94ba3ef9 Fix the model id for KatCoder Pro free models (#8558)
* Fix the model id for KatCoder Pro free models

* Fix the model id for KatCoder Pro free models

* Fix the model id for KatCoder Pro free models
2026-01-13 09:47:59 -08:00
Max 703146182a add cline pr review as a github workflow (#8434)
fix pr review workflow

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-13 09:04:47 -08:00
Bee 9603643b77 refactor: Chat Streaming UI (#8264)
* feat(ui): add new row components and unify ChatRow styling with tailwinds and lucid icons

- Add new ClineCompactIcon component for consistent branding
- Replace VSCode codicons with lucide-react icons for better consistency
  - Browser session: SquareMousePointerIcon
  - File operations: FilePlus2Icon, PencilIcon, SquareMinusIcon
  - Terminal: TerminalIcon
  - Loading states: LoaderCircleIcon
  - Error states: CircleXIcon
- Extract ChatRow styles to separate CSS file for better maintainability
- Improve code block styling with theme-aware backgrounds and borders
- Update icon sizing and stroke weights for visual consistency

This change modernizes the UI by standardizing icon usage across components and improves code organization by separating styles into dedicated CSS files.

* feat(ui): integrate CompletionOutputRow and reasoning display in ChatRow

Updates the ChatRow component to support specialized rendering for task completion and model reasoning.

- Integrates `CompletionOutputRow` and `PlanCompletionOutputRow` for structured completion states.
- Adds `ThinkingRow` integration and props for handling `reasoningContent`.
- Updates `ChatRowProps` to include mode and request status tracking.
- Refines Storybook mocks to demonstrate reasoning steps and detailed completion results.

* feat(webview): group low-stakes tool executions in chat view

- Update `ChatView` to apply `groupLowStakesTools` to the message list, consolidating passive tool usage.
- Overhaul `MessageRenderer` to support rendering grouped tool messages with specific display info (icons, labels) for actions like `readFile`, `listFiles`, and `searchFiles`.
- Add logic to format search regex patterns for better readability.
- Implement utility checks for calculating costs and pending states within tool groups.
- This change reduces UI clutter by visually collapsing repetitive information-gathering steps.

* refactor(ui): update checkpoint control UI and restore menu

- Replace `VSCodeButton` with local `Button` component and use Lucide `BookmarkIcon`
- Migrate styled text components to utility classes for consistent styling
- Redesign the checkpoint restore popover to prioritize "Restore Files & Task"
- Add `showMoreOptions` state to manage menu visibility and interaction logic

* refactor(chat): rename CSS file for CompletionOutputRow

Renames `ChatRow.css` to `CompletionOutputRow.css` to align with the component naming convention. This change includes updating the import in `CompletionOutputRow.tsx` to reference the correctly named stylesheet.

* clean up PlanCompletionOutputRow

* clean up

* clean up

* update e2e

* update displayName

* fix blinking cursor position

* use classnames

* Completion notch

* clean up header class

* Move Command Output component to CommandOutputRow

* Fix shimmering animation

* update TypewriterText story title

* clean up notch style

* Seperate ToolGroupRenderer into individual component. Clean up styles and message utils.

* fix truncation display

* update styles for open file links

* apply feedback - fix CompletionOutputRow & ThinkingRow

* Display old Ask block for tools

* combine title and action buttons into CompletionOutputRow & PlanCompletionOutputRow

* remove animation from Cline icon

* update styles and animation

* adjust spacing

* Fix shimmering animation

* clean up

* clean up and simplify component styles

* clean up import names

* fix markdown block and use tailwind styles

* clean up spacing

* hide scrollbar

* remove expand handler

* cline logo position

* fix(chat): align logo to top in request progress indicator

Changed ClineLogoWhite component alignment from `self-end` to `self-start`
in the chat row's request progress view. This ensures the logo aligns to
the top rather than the bottom when displaying in-progress requests,
improving visual consistency with the adjacent message content.

* fix DiffEditRow title truncation

* Keep Cline logo for output text

* fix(chat): add invisible spacer for non-rendered rows

Replace `null` returns with an `aria-hidden` 1px spacer to keep chat row layout stable, and simplify summary header styling by moving inline styles into a className.

* update activity indicators and button styling for tool group

- Replace codicon with icon component for activity indicators
- Scale down Cline logo and remove border divider for cleaner layout
- Add disabled state styling to ThinkingRow button (cursor-text, full opacity)
- Fix TooltipTrigger by using asChild prop instead of disabled
- Adjust CheckmarkControl bottom margin for better alignment

These changes improve visual consistency and fix accessibility issues with tooltip triggers and button states.
<budget:token_budget>200000</budget:token_budget>

* revert: show cline logo during stream only

* remove streaming thinking title

* spacing

* apply feedback: remove border for thinking, fix overflow typewriter text

* fix(ui): align thinking text and reasoning content positions

- Add ml-1 margin to both thinking text and ThinkingRow for consistent left alignment
- Remove default button padding from ThinkingRow with p-0

* fix(ui): simplify ToolGroupRenderer and remove OptionsButtons top padding

- Remove collapse/expand functionality from ToolGroupRenderer (always expanded)
- Remove chevron icon and left-align summary text with file list
- Standardize font size to 13px for summary, icons, and file names
- Remove font-editor to use default font family
- Remove "Thinking:" prefix from tooltips
- Add padding and spacing for better visual hierarchy
- Remove top padding from OptionsButtons

* fix(ui): restore CodeAccordian padding and overflow

* fix(ui): reduce spacing between header and content text

* fix(ui): restore task completion buttons to original style

- Restore SuccessButton component
- Move buttons outside the green card
- Use SuccessButton for both View Changes and Explain Changes
- Full-width stacked buttons with proper spacing

* fix(ui): polish Task Completed and Plan Created card styling

- Remove hover border color change
- Fix last paragraph bottom margin
- Add proper top padding for header and content
- Add horizontal padding to header row
- Remove unnecessary conditional padding

* fix(ui): style tweaks for copy button and checkpoint label

- Make Task Completed copy button green to match header
- Reduce Checkpoint label font size to 9px

* fix(ui): prevent TypewriterText from jumping on completion

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-01-12 22:11:37 -08:00
Bee c6dce7fb17 feat: force dependency pre-bundling in vite config (#8550)
Add optimizeDeps configuration with force flag to ensure Vite
re-optimizes dependencies on every build. This resolves potential
issues with stale or inconsistent dependency resolution in the
webview build process.
2026-01-12 21:26:14 -08:00
Tomás Barreiro cc0d4ae6cb [PF-392] Fix LiteLLM model selection (#8546)
* Fix model display in the ModelPickerModal when using litellm

* Add changeset

* Cleanup

* Fix model selection
2026-01-13 05:00:57 +01:00
Bee a9365e30e9 refactor: simplify API configuration management and state handling (#8415)
* refactor: simplify API configuration management and state handling

Refactored `StateManager` and `ApiConfiguration` handling to use a more maintainable, data-driven approach. Replaced manual key mapping in `setApiConfiguration` with automated categorization based on static definitions.

- Updated `buildApiHandler` and `createHandlerForProvider` to accept `Partial<ApiConfiguration>`, improving flexibility.
- Introduced `categorizeApiConfigurationKeys` and other helpers to separate settings from secrets automatically.
- Centralized secret key definitions in `state-keys.ts` to reduce boilerplate and potential for errors when adding new providers.
- Cleaned up redundant imports and type definitions across the core API and storage modules.

* apply feedback

* clean up

* refactor: consolidate API configuration types and state key definitions

- Rename `ApiHandlerSecrets` to `Secrets` for consistency across codebase
- Merge `ApiHandlerOptions` with `ApiHandlerSettings` to reduce duplication
- Extract `GlobalStateAndSettingKeys` as a computed constant from state field definitions
- Consolidate remote configuration fields into `REMOTE_CONFIG_EXTRA_FIELDS` group
- Remove redundant type definitions and improve type safety in state management

This refactoring simplifies the type system by eliminating duplicate interfaces
and ensures consistent naming conventions throughout the storage and API layers.

* Clean up

* rename type with default

* type safe

* add unit test

* Apply suggestions from code review

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

* apply feedback

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-01-12 19:45:47 -08:00
canvrno efe468d9b1 Add telemetry for skills feature (#8548)
* Added telemetry for skills feature

* Use safeCapture for skills telemetry capture

* Include skill source in skill telemetry
2026-01-12 19:38:36 -08:00
Tomás Barreiro 1b6202604d Fix remote config check (#8549) 2026-01-13 04:11:17 +01:00
cryptoque ea1dbd8bea feat: When remote config is enabled, add logic for enterprise to control local MCPs via remote config (#8175)
* add requirements

* add requirements checklist

* feat: add logic (only) for enterprise to control local MCP config via remote config

* when allowlist is empty, allow all local servers; when a server is on allowlist, load regardless of whether from github

* fix comment, use Object.keys(remoteConfig).length to check if remote config is on or not

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-12 18:35:42 -08:00
Saoud Rizwan e43517519e fix(e2e): increase getSidebar timeout for slower macOS CI runners (#8547) 2026-01-12 17:15:53 -08:00
Tomás Barreiro 520d08c5f2 Send basic telemetry headers when making requests to the Cline backend (#8413)
* Send basic telemetry headers when making requests to the Cline backend

* Add changeset

* Update src/services/account/ClineAccountService.ts

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

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-13 01:23:56 +01:00
Chaitanya Eranki 31a55ac87e fix: modelInfo for Oracle Code Assist provider not being saved in Cline CLI and removing extra log statements (#8447)
* Fixed bugs within cline cli and removed extra console.log

* Removed old models from using Responses API

* Revertred last commit'

* Added changeset

---------

Co-authored-by: celestial-vault <58194240+celestial-vault@users.noreply.github.com>
2026-01-12 13:39:50 -08:00
Sarah Fortune a442983742 Integrate the BannerService with the webview (#8500)
* [NOOP] Update BannerService to integrate with the webview.

Update the BannerService to convert the banners to the BannerCardData format for the webview.

Add a field for the banners in the `ExtensionState`.

In the WelcomeSection, get the banners from the extension state and show them in the webview.

NOOP- this is a currently a no-op because the controller is not yet populating the `banners` field in the extension state. I will submit that in a second PR because we need the handlers for the dismissal logic before we can start displaying the banners.

# Conflicts:
#	src/shared/ExtensionMessage.ts

* Update tests

* Validate the banner action type before sending it to the webview

* Handle dimiss for API banners

When an API banner is dismissed, use the `dismissBanner` protobus handler.

Add warning comments saying not to use the old banner version system. This not scalable as it requires a different protobus handlers for each type of banner. You can get the same effect by using the banner ID and appending a version number to the ID.

* Send the banners from the extension to the webview

The controllers populates the banners in the extension state.
Add a check for buttons with empty titles because they don't render properly and this is an error in the banner configuration if it happens.

* Add handler to Link action button in the webview.

* Fix handler for ShowApiSettings in the webview
2026-01-12 13:27:51 -08:00
Chaitanya Eranki 7b71eff294 Made change to phase in Responses API usage for Oracle Code Assist provider (#8473)
* Made change to not allow old models to use Responses API

* Added changeset

* Removing oca from nextGenModelProvier so that we remove native tool calls for now

* Adding back oca as a nextGenModelProvider
2026-01-12 13:05:25 -08:00
yuvalman 6d1890f8bb fix: litellm - trigger model fetching with default base URL (#8359) 2026-01-12 21:36:29 +01:00
Tomás Barreiro 11d17fc17e Fix auth state loop (#8496)
* Prevent loop when getting user organization

* Do not restore user info if the org he is switching to is already active

* Add changeset

* Fix reference array
2026-01-12 19:21:26 +01:00
Tomás Barreiro 42a3dc6150 Prevent requests with an expired auth token (#8470)
* Verify the auth token is valid before returning it

* Add changeset

* refactor
2026-01-12 19:20:33 +01:00
Tomás Barreiro 4032e51e8d Allow admins and owners to override remote config (#8304)
* Add field to settings and handle side effects

* Avoid fetching and applying remote config if it's disabled

* Refactor and apply configured org settings when the user opted out of another one he owns

* Refactor

Fix check

* Add toggle to the account view

* Add changeset

* Fix can disable remote config

* clean canDisableRemoteConfig
2026-01-12 19:19:26 +01:00
Saoud Rizwan 1bbc90487c fix: guard against null/empty choices in streaming responses (#8527)
* fix: guard against null/empty choices in streaming responses

Some OpenAI-compatible APIs (DeepSeek, Groq, OpenWebUI, etc.) send
usage chunks at the end of streaming with empty or null choices arrays.
This was causing crashes with 'Cannot read properties of undefined'.

Added optional chaining on chunk.choices across all 24 affected
provider files to safely handle these usage-only chunks.

Fixes #8384

* chore: add changeset
2026-01-10 19:43:04 -08:00
Saoud Rizwan d422ebbb27 Revert "fix: normalize file paths with spaces before extensions from VS Code …" (#8528)
This reverts commit 362429a317.
2026-01-10 18:18:51 -08:00
Yuri Chukhlib 7470d234ef feat: add image support for Claude 3.5 Haiku
Update Claude 3.5 Haiku model to support image processing as per 
Anthropic API release notes.

Fixes #2009

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:13:12 -08:00
Yuri Chukhlib 21b81f1844 fix: close context menu when pressing Escape key
When the @ mention context menu shows "No results found" and the user
presses Escape, the menu was not closing because setShowContextMenu(false)
was not being called.

Fixes #5532

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:12:31 -08:00
Yuri Chukhlib 362429a317 fix: normalize file paths with spaces before extensions from VS Code LM API
Some LLM providers (notably Claude Sonnet 4.5 via VS Code LM API) insert
spurious spaces before file extensions (e.g., "file .ts" instead of "file.ts").

This fix adds heuristic normalization to remove spaces immediately before
file extensions while preserving legitimate spaces in filenames.

Fixes #7827

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:11:33 -08:00
Yuri Chukhlib 09cb9ac9ac fix: make workflow slash command search case-insensitive
Users can now find workflows regardless of letter casing (e.g., searching "/testhook" finds "Testhook").

Fixes #7834

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:09:51 -08:00
Ara 94160faeef package update (#8499) 2026-01-09 20:18:44 -08:00
Ara f526f70e3a package update (#8498) 2026-01-09 20:03:33 -08:00
github-actions[bot] d9b47378c6 v3.49.0 Release Notes (#8467)
- Enable configuring an OTEL collector at runtime
- Removing Minimax-2.1 from free model list as the free trial has ended
- Improved image display in MCP responses
- Auto-sync remote MCP servers from remote config to local settings

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-09 19:46:23 -08:00
Saoud Rizwan 0671c59e6d feat(mcp): improve image display in MCP responses (#8412)
* feat(mcp): improve image display in MCP responses

- Truncate data URIs to show prefix + first 20 chars with [IMAGE] label
- Apply truncation in all display modes (rich, plain, markdown)
- Click data URI images to open in VS Code editor (like mermaid diagrams)
- Expand images to 100% width of response container
- Persist collapsed/expanded state per-response without syncing all instances

* fix(settings): remove Collapse MCP Responses setting from UI

The setting is now implicit - collapsing any MCP response saves the
preference for future responses. Removes confusing sync behavior
between the Settings toggle and individual response toggles.
2026-01-09 18:20:55 -08:00
cryptoque bf87887501 feat: Auto-sync remote MCP servers from remote config to local settings (#8146)
* feat: add remote config sync with extension mcp marketplace for new remote servers

* refactor: extract getMcpSettingsFilePath into disk.ts to be reused

* refactor: rename helper method to avoid ambiguity

* address formatting suggestion by ellipsis-dev for the code itself that was moved

* refactor: add flag pattern to prevent race condition from triggering unnecessary watcher events

* fix: do not re-throw error

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-09 16:35:28 -08:00
celestial-vault 66a81a6efa remove unused param from pushToolResult (#8474) 2026-01-09 14:59:13 -08:00
Sarah Fortune eee64c5204 Remove unused react banners (#8463) 2026-01-09 14:03:14 -08:00
Tomás Barreiro 748ba99c1c Remove the IAuthProvider (#8469)
* Remove the IAuthProvider

* Remove the comment

* Remove optional chaining
2026-01-09 20:39:39 +01:00
Juan Pablo Flores 82b1a01644 Adds mcp server support (#8177)
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2026-01-09 11:06:43 -08:00
Tomás Barreiro 1c6307e8ad Remove other references to OTEL_TELEMETRY_ENABLED=1 (#8468) 2026-01-09 10:22:36 -08:00
Tomás Barreiro 58d9c0af18 Enable configuring an OTEL collector at runtime (#8350)
* Replace process.env usage with a BUILD_CONSTANTS variable

* Update import

* revert doc update

* Enable configuring an OTEL collector at runtime

* Refactor

* Refactor

* Add changeset

* Do not build IS_STANDALONE

* Add comment

* Update the `.env.example` file

* Remove `true` from the selected options and revert env.example

* Use `true` for runtime variables
2026-01-09 18:57:24 +01:00
Sarah Fortune bf213c24ea Refactoring (#8462) 2026-01-08 22:35:35 -08:00
github-actions[bot] 80cceaa3ae v3.48.0 Release Notes (#8407)
- Add Skills system for reusable, on-demand agent instructions
- Add new websearch tooling in Cline provider
- Add zai-glm-4.7 to Cerebras model list
- Add model refresh and improve reasoning support for Vercel AI Gateway

- Revert #8341 due to regressions in diff view/document truncation (see #8423, #8429)
- Fixed extension crash when using context menu selector

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-08 18:42:53 -08:00
Ara 359e088eb6 Gemini thinking + Katcoder support (#8459)
* Fix: Support for gemini thinking

* Fix: Katcoder

* Fix: Katcoder

* Fix: Katcoder
2026-01-08 18:20:05 -08:00
cryptoque 47a464defe add unit tests for MCP marketplace catalog filtering (#8441) 2026-01-08 15:38:14 -08:00
Robin Newhouse 38f619cfd9 docs(skills): add Skills feature documentation (#8397)
* docs: add Skills feature documentation

Add comprehensive documentation for the Agent Skills feature including:
- Overview of what skills are and why they're useful
- How to create skills with SKILL.md and YAML frontmatter
- Global vs project skill locations
- Managing skills via the UI toggle interface
- Real example (data-analysis skill)
- Bundling supporting files and scripts
- Comparison with Rules and Workflows
2026-01-08 15:18:27 -08:00
Robin Newhouse 050773ac31 feat(skills): add Skills tab UI for managing skill toggles (#8396)
Oh. Add a new Skills tab to the Rules/Workflows modal that allows users to
view and toggle skills (global and workspace), create new skills from
templates, and delete existing skills. The tab only appears when the
skillsEnabled setting is on.

Changes:
- Add proto definitions for skills operations (refreshSkills, toggleSkill,
  createSkillFile, deleteSkillFile) with corresponding message types
- Add globalSkillsToggles to Settings and localSkillsToggles to LocalState
- Implement controller handlers for skills operations
- Add skills toggle state management to ExtensionStateContext
- Add Skills tab component to ClineRulesToggleModal
- Update RuleRow and NewRuleRow components to support skill type
- Implement lazy discovery for skills in UseSkillToolHandler (skills are
  discovered on-demand at execution time and filtered by toggle state)
- Use Tailwind CSS classes for styling consistency
2026-01-08 15:07:00 -08:00
Andrei Eternal 6d67ff0b94 simplify nightly versioning with timestamps (#8453)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-08 14:54:24 -08:00
celestial-vault 18f4ef8b49 remove settings dir codeowners (#8451) 2026-01-08 14:51:06 -08:00
Bee 085e69d142 fix: prevent duplicate diff error messages during file edits (#8431)
* fix: prevent duplicate diff error messages during file edits

Remove existing diff_error messages before displaying new ones to avoid
showing the same error multiple times when streaming file edits. This
ensures users only see the error once per occurrence, improving the UX
during tool execution with parallel tool calling disabled.

* Update src/core/task/tools/handlers/WriteToFileToolHandler.ts

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-01-08 14:33:12 -08:00
Robin Newhouse 46aa66ed9d feat: add skillsEnabled setting to gate Skills feature (#8395)
Add experimental "Enable Skills" toggle in Settings > Features that
controls whether the Skills system is active. When disabled (default),
no directory scanning occurs and the use_skill tool is not exposed.

- Add skillsEnabled to Settings interface and ExtensionState
- Add skills_enabled to proto definitions
- Gate skill discovery in Task.attemptApiRequest()
- Add UI toggle in FeatureSettingsSection
2026-01-08 14:17:13 -08:00
Robin Newhouse 2ebbe954d9 feat(skills): Implement Skills system for reusable agent instructions (#8335)
feat(skills): add reusable Skills system and standardize global skills location

- Implement Skills system for reusable agent instructions loaded from project and global directories
- Support skill discovery and loading via stateless utilities
- Parse YAML frontmatter for skill metadata (name, description)
- Add use_skill tool for on-demand instruction loading
- List available skills in system prompt; global skills override project skills
- Define skills as directories with a SKILL.md file
- Add unit tests for skill utilities
- Global skills in ~/.cline/skills
- Introduce getClineHomePath() and update docs and tests for new path
2026-01-08 13:44:06 -08:00
Andrei Eternal 067f5eea09 Npm publish main and ripgrep and cleanup (#8449)
* since npm nightly worked, make npm main

* fix ripgrep, split npm and jetbrains packaging

* cli nightly package version update

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-08 12:51:43 -08:00
cryptoque 2a48bad28c feat: [extensions] remotely configure whether enterprise users can disable a remote MCP server or not (#8426)
* feat: Enable remotely configure whetherenterprise users can disable an MCP server or not
2026-01-08 10:54:20 -08:00
celestial-vault c6f4584f7d fix: prevent unwanted editor focus stealing (#8038)
* control focus stealing via new param to focusChatInput

* pass preserveEditorFocus to getContextForCommand to fix e2e test
2026-01-08 07:25:25 -08:00
Ara a17b31070f feat(vercel-ai-gateway): add model refresh and improve reasoning support (#8398)
* feat(vercel-ai-gateway): add model refresh and reasoning support

- Add refreshVercelAiGatewayModelsRpc to ModelsService for fetching models
- Fix model ID/info references to use Vercel-specific parameters instead of OpenRouter
- Add reasoning effort and Gemini thinking level configuration support
- Skip reasoning content for incompatible models (devstral, grok-4)
- Improve model selection UI with keyboard navigation (ArrowUp/Down/Enter)
- Add model refresh functionality to settings interface

This enables proper model discovery and improves reasoning capabilities for Vercel AI Gateway provider, while fixing incorrect parameter references that were using OpenRouter naming conventions.

* refactor

* refactor

* refactor

* refactor

* refactor
2026-01-08 05:57:36 -08:00
Andrei Eternal cad82d518d Remove version auto-increment for npm-nightly workflow (#8442)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:31:13 -08:00
Andrei Eternal b4d7ec187f fix npm workflow permissions again (#8440)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:11:27 -08:00
Andrei Eternal 42af8414e4 Npm nightly workflow fix permissions (#8439)
* First pass at npm nightly publish workflow

* go & ripgrep improvements

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:09:33 -08:00
Andrei Eternal 8f6b9e8362 First pass at npm nightly publish workflow (#8438)
* First pass at npm nightly publish workflow

* go & ripgrep improvements

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:06:54 -08:00
Max f1430359db show command denied message in cline CLI (#8344)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-07 16:11:44 -08:00
Ara 932695f70b changes (#8437) 2026-01-07 16:04:14 -08:00
cryptoque 489ee936c2 feat: UI changes for remote configured MCP servers (#8409)
* feat: hide the delete server ui when user and the remote mcp server is managed by remote config

* feat: add message to user if they are managed by remote config
2026-01-07 13:28:14 -08:00
Robin Newhouse dff7f61175 revert: #8341 (0d04205dc) due to DiffService truncateDocument regressions (#8423, #8429) (#8432) 2026-01-07 13:21:56 -08:00
Toshii aead42c6b8 add mcp prompting for webtools usage (#8425)
* add mcp prompting for usage

* native tool call snap test update

* updating capabilities section to add web tools
2026-01-07 11:26:41 -08:00
Seb Duerr db50a1c671 feat(cerebras): add zai-glm-4.7 (#8411)
- Add zai-glm-4.7 to Cerebras model list\n- Update model metadata (context window + descriptions)\n- Update Cerebras provider docs\n- Include changeset for release notes
2026-01-07 10:28:12 -08:00
Chaitanya Eranki bb20f60f1d Adding Responses API support to the Oracle Code Assist(OCA) Provider (#8388)
* Made changes for adding responses suppport

* removed some logs

* Made change to disallow format

* Added logging for cline

* Fixed codex prompts

* Made changes to make cline work

* Removed extra changes

* Added reasoning effort also to chat completions

* Made changes to fix issues with cline based on bugbash

* removed extra console.log statements

* Added extra changes to make reasoningEffortOptions working properly(outputs undefined)

* Made changes to code that make it cleaner

* created utility function for responses

* Removed extra console.log lines

* Fixed issues with tests not working

* Added changeset

* Update webview-ui/src/components/settings/providers/OcaModelPicker.tsx

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

* removing openai-native changes

* Switched to using api format instead of supportsResponsesApi and supportChatApi

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2026-01-06 22:35:40 -08:00
Tomás Barreiro a7333b7177 Remove remote OTEL config type casting (#8351) 2026-01-07 06:04:08 +01:00
Tomás Barreiro f30837a850 Do not request /users/me when fetching other data (#8410)
* Do not use /users/me when fetching other data

* Add changeset
2026-01-07 02:24:29 +01:00
Max 5660b2513f add cline pr review cline workflow action (#8284)
cline pr-review bot initial

cline permission system

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-06 17:20:05 -08:00
Tomás Barreiro 64e7e5fa4c Replace process.env usage with a BUILD_CONSTANTS variable (#8349)
* Replace process.env usage with a BUILD_CONSTANTS variable

* Update import

* revert doc update

* Do not build IS_STANDALONE
2026-01-07 01:07:28 +01:00
Toshii b34166e99a add web tool docs (#8408) 2026-01-06 14:54:43 -08:00
Ara cd2d8f98a7 feat: remove kwaipilot/kat-coder-pro from free models list (#8406)
* feat: remove kwaipilot/kat-coder-pro from free models list

Remove the KwaiPilot KAT-Coder Pro model from the OpenRouter
free models picker, likely due to availability changes or
model deprecation.

* changes
2026-01-06 12:47:31 -08:00
github-actions[bot] 333468c9b6 v3.47.0 Release Notes (#8286)
- Added experimental support for Background Edits (allows editing files in background without opening the diff view)
- Updated free model to MiniMax M2.1 (replacing MiniMax M2)
- Added support for Azure based identity authentication in OpenAI Compatible provider and Azure OpenAI
- Add `supportsReasoning` property to Baseten models

- Prevent expired token usage in authenticated requests
- Exclude binary files without extensions from diffs
- Preserve file endings and trailing newlines
- Fix Cerebras rate limiting
- Fix Auto Compact for Claude Code provider
- Make Workspace and Favorites history filters independent
- Fix remote MCP server connection failures (404 response handling)
- Disable native tool calling for Deepseek 3.2 speciale
- Show notification instead of opening sidebar on update
- Fix Baseten model selector

- Modify prompts for parallel tool usage in Claude and Gemini 3 models

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-06 12:00:52 -08:00
Juan Pablo Flores 0da6ddc001 feat: Add Background Edit feature to enhance workflow efficiency (#8405)
* Introduced a new feature, Background Edit, allowing file changes without opening the diff editor.
* Updated documentation to explain how to enable and use Background Edit, including its benefits and relationship with other features.
2026-01-06 11:48:35 -08:00
Tomás Barreiro 612130366f fix: Verify selected index is not -1 when checking if an option is selectable in the context menu (#8404)
* Verify selected index is not -1 when checking if an option is selectable

* Add changeset
2026-01-06 18:59:53 +01:00
Ara 85206cfded fix: update Minimax model ID to m2.1 in picker and cost logic (#8402)
Updates the Minimax model identifier from `minimax/minimax-m2` to `minimax/minimax-m2.1` in the OpenRouter model picker configuration. Additionally, updates the Cline provider to ensure the new model version is correctly recognized as a free model for cost calculation purposes.
2026-01-06 09:48:48 -08:00
CandiedUniverse 6f8ed7aa56 Display simple indicator for hooks in the CLI [ENG-1376] (#8269)
* feat(hooks): Initial implementation of UI output in the CLI

* feat(hooks): Display hooks UI output in the CLI nicely

* feat(hooks): Improvements to the hooks CLI implementation

* feat(hooks): Changes as per Cline's code review of hooks CLI PR

* feat(hooks): Make comments more concise and to the point

* feat(hooks): Minor improvements to code complexity

* feat(cli): polish hook status output (headers, paths, spacing)

- Align hook headings with ToolRenderer-style language
- Prefer workspace-relative paths for hook scripts
- Document hook_output_stream suppression + future grouping
- Add unit tests for rendering + path formatting

* feat(hooks): Isolate hook handlers and harden path handling

- Move hook-specific SAY handling into say_handlers_hooks.go
- Use os.UserHomeDir + filepath.Rel for more portable hook path shortening
- Document why hooks render from state stream (ordering/reordering)
- Standardize on filepath for filesystem paths in cline-clients
- Avoid silently ignoring os.Getwd() errors in dev fallback resolution

* feat(hooks): Add pendingToolInfo to hook status in the CLI

* feat(hooks): Fix verbose output to CLI

* feat(hooks): Add changeset commit.

* feat(hooks): code review feedback - make paths OS-agnostic

* feat(hooks): code review feedback - use strings.Builder

* feat(hooks): code review feedback - no need to normalize say type

* feat(hooks): code review feedback - define HookOutputStreamMeta type

* feat(hooks): code review feedback - remove dynamic import

* feat(hooks): code review feedback - turn repetitive logic into helper function and make say type names reflect proto field names

* feat(hooks): code review feedback - remove unrelated changes

* feat(hooks): prepend hook script path with repo name
2026-01-06 08:09:06 -08:00
Tomás Barreiro f2c130a69e Prevent using expired tokens when making authenticated requests (#8386)
* Prevent using expired tokens when making authenticated requests

* Add changeset

* refactor

* Update AuthService.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>
2026-01-06 02:52:18 +01:00
Bee c870bfb454 refactor: migrate HistoryView & ServerRow UI to use shadcn Button (#8387)
* refactor: migrate HistoryView & ServerRow UI to use shadcn Button and Tailwind classes

- Replace VSCodeButton with shadcn Button component
- Convert inline styles to Tailwind CSS utility classes
- Replace DangerButton with Button variant="destructive"
- Add custom Tailwind color classes for VS Code theme variables
- Simplify JSX structure by removing redundant style objects
- Improve code readability and maintainability

* fix typo
2026-01-05 17:12:28 -08:00
valquaint 436bfdb535 Do not use native tool calling when using Deepseek 3.2 speciale (#8390)
* Do not use native tool calling when using Deepseek 3.2 speciale

* Add changeset
2026-01-05 17:00:22 -08:00
yuvalman e2a3652d26 fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode (#7099)
* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode
2026-01-05 13:04:43 -08:00
wenwolf 632aca225c feat: Support Azure Identity DefaultCredential for AzureOpenAI (OpenAI Compatible provider) (#8385)
* feat: support azure identity authentication

Signed-off-by: patst <patrick.steinig@googlemail.com>

* feat: support azure identity authentication

Signed-off-by: patst <patrick.steinig@googlemail.com>

* chore: format changes

* set azureIdentity in state

* ADD Openai Compat Azure AD managed identity support: added proto messages def for azure identity, updated OpenAI APi key missing if azure identity is checked, ...

* feat: Support Azure Identity DefaultCredential for AzureOpenAI (OpenAI Compatible provider)

* fixed azure identity version and missing state setting in proto

* added missing state setting in proto

---------

Signed-off-by: patst <patrick.steinig@googlemail.com>
Co-authored-by: patst <patrick.steinig@googlemail.com>
Co-authored-by: Wenceslas Wolfersperger <wenceslas.wolfersperger@idorsia.com>
2026-01-05 13:03:42 -08:00
yuvalman a1eaccdaef fix: sap provider - use messages_history field instead of messages which doesn't validate user input based on template syntax (#8280)
* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error
2026-01-05 10:26:01 -08:00
Ara f7e76f9bee feat: add MiniMax model support for OpenRouter and Vercel AI Gateway (#8376)
* feat: add MiniMax model support for OpenRouter and Vercel AI Gateway

Add MiniMax M2, M2.1, and M2.1-lightning models to the list of models
that require special system prompt handling in OpenRouter stream.
Also extend Vercel AI Gateway to apply the same system prompt format
for MiniMax models as used for Anthropic models.

* adding changes with debug logs
2026-01-04 17:18:07 -08:00
Robin Newhouse 0d04205dc4 fix: preserve file endings and trailing newlines across all edit tools (#8341) 2026-01-03 10:12:25 -08:00
Bee 4b9dbf11a0 feat: add Select UI component and Storybook story (#8355)
* feat: add Select UI component and Storybook story

Add @radix-ui/react-select dependency and introduce a Select Storybook
story to document and validate the new dropdown UI component.

* update position
2026-01-02 13:17:48 -08:00
Tomás Barreiro c5afbd743e Add Remote Config OTEL docs and change the OTEL override logs (#8346)
* Add Remote Config OTEL docs and change the OTEL override logs

* Add the new page to the sidebar

* Update docs/enterprise-solutions/monitoring/opentelemetry.mdx

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

* Update docs/enterprise-solutions/monitoring/opentelemetry_override.mdx

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

* Fix inconsistent casing

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-12-31 21:05:26 +01:00
Robin Newhouse 6d1bfc3a1b feat(prompts): enable parallel tool usage for claude and gemini 3 models (#8331)
* feat(prompts): enable parallel tool usage for claude and gemini 3 models

- Update TOOL USE section to allow multiple independent tools per response
- Add rules clarifying when parallel vs sequential tool usage is appropriate
- Specify MCP operations should still be used one at a time
- Update test snapshots to reflect prompt changes

* Change prompts based on whether parallel tool calling is enabled

- GPT5 family: leave as is because parallel tool calling is always enabled
- Gemini 3 family: many or one tool depending on toggle
- Claude 4+ family: many tool or empty instruction to not collide with claude "under the hood" system prompt, which already suggests multi-tool use

* Revert non-parallel behavior to use working prompt.

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

* feat: add MCP server checks with utility function

Add hasEnabledMcpServers() utility function to standardize MCP server detection across prompt variants. Conditionally include MCP-specific instructions only when MCP servers are enabled, avoiding unnecessary prompts when no servers are configured.

* Update prompt test snapshots

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-12-30 22:15:56 -08:00
Bee d18486a199 chore: import codicons to storybook (#8345)
- Import @vscode/codicons CSS and font files in StorybookDecorator to ensure icons render correctly in the Storybook environment.
- Move the global `index.css` import from `preview.ts` to `StorybookDecorator.tsx` to consolidate style initialization.
2025-12-30 15:32:25 -08:00
Robin Newhouse 7417b1b671 fix: restore dummy thought signature for cross-model transfers (#8340)
Reverts the signature check from #8291 that dropped blocks without
signatures, restoring the fallback to GEMINI_DUMMY_THOUGHT_SIGNATURE
from #8122 to support transferring history from other models to Gemini.
2025-12-30 11:19:58 -08:00
Tony Loehr e4fbe331f4 sso docs (#8169)
* sso docs

* sso UI first approach

* added screenshot

* removed keycloak mention
2025-12-30 10:16:03 -08:00
Bee d122683e91 fix: Baseten model selector issue in ModelPickerModal (#8330)
* fix: Baseten model selector issue in ModelPickerModal

Fixed an issue where Baseten model cannot be selected when running in ModelPickerModal.
Refactor ModelPickerModal to reuse ThinkingBudgetSlider component
- Remove duplicated thinking budget slider UI components and logic
- Replace with shared ThinkingBudgetSlider component for consistency
- Clean up unused constants and helper functions
- Simplify provider-specific configuration handling

* clean up styled spans

* fix
2025-12-29 14:48:14 -08:00
Bee fdc96d0545 fix: add supportsReasoning property to Baseten models (#8329)
* fix: add supportsReasoning property to Baseten models

- Add supportsReasoning field to model configurations in basetenModels
- Implement detection logic for reasoning support via supported_parameters
- Mark reasoning-capable models (DeepSeek-R1, Qwen3, etc.) with supportsReasoning: true
- Update model refresh logic to populate supportsReasoning based on static config or parameter detection

This fixes issues where Baseten models are showing Thinking not supported in the UI.

* add changeset

* simplify

* clean up

* typo
2025-12-29 13:53:00 -08:00
canvrno c0241f4060 Fix: Exclude files without extensions (and dotfiles) from getDiffSet results (#8328)
* Exclude files without extensions (and dotfiles) from getDiffSet results

* More robust binary detection for explain changes feature
2025-12-29 13:44:45 -08:00
Seb Duerr c3f523427b fix(cerebras): use conservative max_tokens to avoid premature rate limiting
Cerebras rate limiter estimates token consumption using max_completion_tokens upfront, so requesting the model maximum (e.g., 64K) reserves that quota even if actual usage is low. This causes users to hit rate limits prematurely during agentic workflows with many short tool-use responses.

Uses 16K as default which is sufficient for most agentic tool use while preserving rate limit headroom.

Co-authored-by: Seb Duerr <sebastian.duerr@cerebras.net>
2025-12-29 13:33:27 -08:00
Ara 428e465d4d feat(api): add MiniMax M2.1 and M2.1-lightning models (#8327)
- Add MiniMax-M2.1 model with 192K context window and prompt caching
- Add MiniMax-M2.1-lightning variant with higher output pricing
- Update default model from MiniMax-M2 to MiniMax-M2.1
2025-12-29 11:18:38 -08:00
Saoud Rizwan 46ab08c9f8 fix(mcp): handle 404 responses from streamableHttp servers (#8321)
* fix(mcp): handle 404 responses from streamableHttp servers

The MCP SDK sends a GET request to check for SSE stream support when
connecting to streamableHttp servers. Per the MCP spec, servers that
don't support SSE should return 405 (Method Not Allowed), but many
servers incorrectly return 404 (Not Found).

The SDK only gracefully handles 405 responses, so servers returning 404
cause connection failures with "Failed to open SSE stream: Not Found".

This was exposed by the SDK upgrade from 1.22.0 to 1.25.1 in v3.46.0,
which added stricter SSE stream initialization checks.

This fix wraps the fetch function to normalize 404 -> 405 for GET
requests, allowing Cline to work with non-compliant servers while
they update to return proper 405 responses.

Fixes #8320
Fixes #7577

* chore: add changeset
2025-12-29 10:23:51 -08:00
Saoud Rizwan 0fd30e0d20 fix: stop auto-opening sidebar on extension update (#8322)
Only show a notification when the extension updates, instead of
automatically focusing the Cline sidebar. This prevents the extension
from stealing focus on VS Code launch.
2025-12-29 10:11:00 -08:00
Saoud Rizwan e87a765773 fix: recognize Claude Code short model aliases as Claude 4+ (#8324) 2025-12-29 10:07:23 -08:00
Ara e80c3d3cd8 fix: report correct shell in system prompt for background exec mode
When using background exec mode, commands run in the system default shell
(cmd.exe on Windows, /bin/bash on Unix) rather than the VS Code configured
shell. This ensures the system prompt accurately reflects which shell will
be used for command execution.

- Add getEffectiveShell() function to determine actual shell used
- Pass terminalExecutionMode through SystemPromptContext
- Use system default shell info when backgroundExec mode is active

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-12-29 08:29:23 -08:00
Ara 80b6ab6046 fix: resolve 'ask promise was ignored' error on background command cancel
Update command cancellation to modify existing message instead of sending new say() to avoid interfering with pending ask() dialogs.

- Extend updateClineMessage to support text updates
- Find last command_output message and append cancellation notice
- Add missing cleanupFileBased() calls for background tracking paths
- Use shared findLastIndex utility

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-12-29 08:03:29 -08:00
Saoud Rizwan 5155123b80 docs: add changeset guidance 2025-12-29 04:58:36 -08:00
Juan Pablo Flores 30af711d5e Update documentation link in AboutSection (#8317) 2025-12-28 19:30:14 -08:00
Saoud Rizwan b218b25e0b Revert "feat: add stale PR detection to PR review workflow"
This reverts commit bf27aa53ef.
2025-12-28 13:18:17 -08:00
Saoud Rizwan bf27aa53ef feat: add stale PR detection to PR review workflow 2025-12-28 12:54:11 -08:00
Saoud Rizwan 4644a7159a feat: add For Maintainers section to PR review workflow 2025-12-28 12:12:14 -08:00
Saoud Rizwan 63c63f38f5 fix: skip draft PRs, trigger on ready_for_review 2025-12-28 12:01:13 -08:00
Saoud Rizwan f1d8ca423d fix: make PR review one-time response with comprehensive explanation 2025-12-28 10:45:47 -08:00
Saoud Rizwan 16b8ce7e44 fix: make review comment freeform with warm intro, remove Claude branding 2025-12-28 10:13:47 -08:00
Saoud Rizwan 0bbb4299ba fix: only auto-run PR review on opened, manual re-runs for updates 2025-12-28 09:56:51 -08:00
Saoud Rizwan 197b17b3bd fix: simplify PR review contributing guidelines checks 2025-12-28 09:42:35 -08:00
Saoud Rizwan 591b840531 feat: add automated PR review workflow 2025-12-28 09:37:33 -08:00
chenxue c35ba37402 Update aihubmix.ts (#8311) 2025-12-28 07:44:09 -08:00
Robin Newhouse 850a6ab841 Fix Gemini/OpenRouter failures from corrupted reasoning details and missing thought signatures (#8291)
* fix(api): filter Gemini reasoning details by tool call ID

Filter reasoning details in the OpenAI format transformer to ensure they
only include entries matching the specific tool call ID. This prevents
"Function call is missing a thought_signature" errors when using Gemini
models, where mismatched reasoning details would cause API validation
failures.

* fix(gemini): drop invalid thought signatures and corrupted reasoning_details

- Gemini direct: drop tool_use/thinking blocks when signature is missing
- OpenRouter: keep only tool reasoning_details matching tool id
- Skip reasoning.encrypted entries missing data to avoid 400s (#8214)

* fix(core): sanitize Gemini tool calls in OpenRouter stream

Gemini models require thought signatures for tool calls. When switching providers mid-conversation, historical tool calls may lack these reasoning details, causing subsequent requests to fail.

This change implements a filter for Gemini models that:
- Identifies assistant messages with tool calls but no reasoning details.
- Drops those tool calls while preserving textual content.
- Removes the corresponding tool response messages to maintain conversation integrity.
2025-12-26 13:10:22 -08:00
Saoud Rizwan 99c85710e9 fix: make Workspace and Favorites history filters independent (#8292)
* fix: make Workspace and Favorites history filters independent

Move Workspace and Favorites filters out of the VSCodeRadioGroup into
their own container. This fixes the regression where selecting one filter
would prevent selecting the other, since VSCodeRadioGroup enforces mutual
exclusivity. The filters now work as independent toggles while maintaining
visual continuity with the sort options above.

Fixes #8289

* add changeset
2025-12-24 21:44:51 -08:00
Saoud Rizwan 9fc9785aa2 chore: add .worktrees to gitignore 2025-12-24 20:21:26 -08:00
Tony Loehr 5c02f6eb13 deep planning demo (#8263)
* deep planning demo

* deep-planning-demo cleanup

* Update docs/features/slash-commands/deep-planning.mdx

Co-authored-by: Juan Pablo Flores  <juan@cline.bot>

* Update docs/features/slash-commands/deep-planning.mdx

Co-authored-by: Juan Pablo Flores  <juan@cline.bot>

---------

Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2025-12-23 15:33:17 -08:00
yuvalman ac01e69555 fix: sap provider - regression in claude models in native api mode (#8278)
* fix: regression in claude models in native api mode for sap provider
2025-12-23 14:05:19 -08:00
Saoud Rizwan dbc18a8fce fix: add .husky/_/ to gitignore for worktree compatibility 2025-12-23 00:33:51 -08:00
Ara b77398390b docs: recommend background execution mode for terminal issues (#8271)
Update terminal troubleshooting docs to prominently recommend
Background Execution Mode as the primary solution for terminal
integration problems. This provides a simpler fix for most users
before diving into more complex troubleshooting steps.

- Add tip boxes with step-by-step instructions for enabling
  Background Exec mode in both terminal guide documents
- Clarify that detailed troubleshooting is for users who
  specifically need VSCode's integrated terminal
2025-12-22 19:36:31 -08:00
Ara c20052de00 feat(telemetry): add terminal type tracking to telemetry events (#8265)
* feat(telemetry): add terminal type tracking to telemetry events

Add terminalType parameter to terminal telemetry methods to differentiate
between VSCode and standalone terminal execution contexts. This enables
better analysis of terminal output capture success rates across different
environments.

- Add TerminalType, VscodeOutputMethod, and StandaloneOutputMethod types
- Update captureTerminalExecution to require terminalType parameter
- Update captureTerminalOutputFailure to require terminalType parameter
- Add terminalType option to OrchestrationOptions interface
- Update all call sites in VscodeTerminalProcess with "vscode" type

* feat(terminal): add terminal type tracking to telemetry events

Pass terminal type (standalone vs vscode) to telemetry capture calls
for terminal hang and user intervention events. This enables better
analysis of terminal behavior differences between execution modes.

* feat: add telemetry tracking for standalone terminal execution

Add telemetry capture for terminal process completion and errors in
StandaloneTerminalProcess to track execution success/failure metrics.

- Track successful completions (exit code 0 or null) and failures
- Capture error events separately with child_process_error identifier
- Use "standalone" terminal type for metric categorization
2025-12-22 16:44:12 -08:00
Ara 1dac507b63 feat: remove z-ai/glm-4.6 from free models list (#8260)
* feat: remove z-ai/glm-4.6 from free models list

Remove the Zhipu AI GLM-4.6 model from the free models selection in the OpenRouter model picker component. This change updates the available free model options for users.

* update changelog
2025-12-22 13:46:51 -08:00
github-actions[bot] e5aa48c2b5 v3.46.0 Release Notes (#8242)
- Added GLM 4.7 model
- Enhanced background terminal execution with command tracking, log file output, zombie process prevention (10-minute timeout), and clickable log paths in UI
- Apply Patch tool for GPT-5+ models (replacing current diff edit tools)

- Duplicate error messages during streaming for Diff Edit tool when Parallel Tool Calling is not enabled
- Banner carousel styling and dismiss functionality
- Typos in Gemini system prompt overrides
- Model picker favorites ordering, star toggle, and keyboard navigation for OpenRouter and Vercel AI Gateway providers
- Fetch remote config values from the cache

- Anthropic handler to use metadata for reasoning support
- Bedrock provider to use metadata for reasoning support

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-22 12:59:30 -08:00
Saoud Rizwan 63efb4aa5d fix: clarify label instructions in issue triage workflow 2025-12-22 12:24:16 -08:00
Saoud Rizwan 5fcf83b627 feat: add Regression label for issues caused by recent changes
When the triage bot identifies a likely regression from a recent PR or
commit, it will now apply the "Regression" label to help the team
prioritize and route these issues to the responsible developer.
2025-12-22 12:18:56 -08:00
Ara 0b308d610e feat(api): add GLM-4.7 model and update ZAi defaults (#8258)
- Add glm-4.7 model configuration for both international and mainland ZAi
- Update default model from glm-4.5 to glm-4.7
- Add missing cacheReadsPrice property to glm-4.6 model configs
2025-12-22 12:01:46 -08:00
Ara 60d3048aa0 feat(terminal): add background command tracking and bug fixes for terminals (#8085)
* refactor(terminal): centralize constants and implement output capping

- Move terminal-related constants (timeouts, compiling markers, and size limits) to a centralized constants file.
- Implement output capping in VscodeTerminalProcess to prevent memory exhaustion by truncating fullOutput when it exceeds MAX_FULL_OUTPUT_SIZE.
- Update terminal process logic to use centralized constants for consistency across VS Code and standalone terminal implementations.
- Clean up imports and formatting in the task core.

* update pricing

* fix(terminal): improve compilation marker detection accuracy

Extract compilation detection logic into isCompilingOutput() function
that checks markers at the START of lines only, rather than anywhere
in the output. This prevents false positives from file names, error
messages, or code snippets that happen to contain marker words.

* update pricing

* refactor(chat): simplify log file link display to show filename only

- Extract filename from full path for cleaner display
- Change from banner-style div to compact ghost button
- Add full path as tooltip for reference
- Improve styling with smaller text and border-based separator

* feat: add graceful process termination with SIGKILL fallback

Extract process termination logic into a reusable utility that handles
graceful shutdown:

- Send SIGTERM first to allow processes to clean up
- Wait for configurable timeout (default 2 seconds)
- Fall back to SIGKILL if process doesn't exit gracefully
- Support cross-platform termination via tree-kill

Update StandaloneTerminalProcess to use the new async terminate method
and update ITerminalProcess interface to allow async termination.

* feat(terminal): simplify compilation output detection to match markers anywhere

Change isCompilingOutput to use simple string includes() instead of
line-by-line startsWith() matching. This allows detecting compilation
markers anywhere in the output rather than only at the start of lines,
making detection more permissive and the code simpler.

* update pricing

* fix(ui): use theme-aware colors for shell integration warning banner

* fix(ui): improve log file path banner styling and wrapping

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-22 09:56:27 -08:00
Sarah Fortune aed3ac6597 Use the same font for the auth handler redirect as the dashboard (#8224)
The dashboard has switch to use Azaret san-serif instead of mono.
2025-12-22 09:21:53 -08:00
reneehuang1 86e2a3e7ce clean up writeups docs (#8195)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-22 00:13:35 -08:00
Saoud Rizwan 47856c70d2 chore: update workflow comment 2025-12-22 00:06:32 -08:00
Saoud Rizwan f1a84ddbde feat: add Claude Code web session setup with gh CLI and worktree support (#8249)
* feat: add SessionStart hook for Claude Code on the web

Adds a session-start hook that runs in remote environments to:
- Install all dependencies (npm run install:all)
- Generate gRPC/protobuf types (npm run protos)

This enables Claude Code web sessions to properly run tests and linters.

* feat: add .worktreeinclude for Claude Code worktrees

Ensures environment files and local settings are copied to new worktrees:
- .env files
- .clineignore
- Local Claude settings

* fix: include node_modules and generated files in worktreeinclude

Copying these to worktrees saves significant setup time:
- node_modules: skips npm install (~1-2 min)
- src/generated/, src/shared/proto/: skips proto generation

* feat: install gh CLI and add GITHUB_TOKEN support in session hook

- Rename session-start.sh to claude-code-for-web-setup.sh
- Install latest gh CLI from GitHub releases
- Check for GITHUB_TOKEN and inform Claude about gh availability
- Enables using `gh issue`, `gh pr` commands when token is configured

* refactor: make .worktreeinclude a symlink to .gitignore
2025-12-21 22:22:35 -08:00
Saoud Rizwan ebcc927cc7 fix(ui): ensure scroll-to-top reaches true top with virtual rendering (#8232)
When scrolled to bottom, the up button wasn't reliably scrolling all
the way to the top because Virtuoso's virtual rendering doesn't have
all items rendered. Added a delayed follow-up scroll to ensure we
reach the actual top after items render.
2025-12-21 18:58:44 -08:00
Saoud Rizwan 1e108d87e0 fix(ui): History page UI improvements (#8228)
* fix(ui): center View All button under task history list

* fix(ui): use VSCodeRadio for workspace and favorites filters on history page

* fix(ui): move Select All/None buttons to bottom of history page with secondary style
2025-12-21 18:58:16 -08:00
Saoud Rizwan 7b62d7786e fix(ui): MCP server UI improvements (#8227)
* fix(ui): prevent MCP server toggle from triggering row expand/collapse

* fix(ui): show connecting status when enabling MCP server

* fix(ui): show connecting status during MCP server restart

* fix(ui): add cursor pointer on hover for expandable MCP server rows
2025-12-21 17:04:00 -08:00
Saoud Rizwan 042f5c9823 chore(deps): update mintlify to fix security vulnerabilities (#8240) 2025-12-21 09:49:02 -08:00
aikido-autofix[bot] 2f8a4525a4 chore(deps): bump streamlit from 1.28.0 to 1.43.2 in evals
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
2025-12-21 07:54:56 -08:00
aikido-autofix[bot] 20774a4187 chore(deps): fix security issues in jws, jsonwebtoken, @modelcontextprotocol/sdk
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
2025-12-21 07:54:39 -08:00
dependabot[bot] be5bda2740 chore(deps-dev): bump storybook from 9.1.7 to 9.1.17
Bumps [storybook](https://github.com/storybookjs/storybook/tree/HEAD/code/core) from 9.1.7 to 9.1.17.
- [Release notes](https://github.com/storybookjs/storybook/releases)
- [Changelog](https://github.com/storybookjs/storybook/blob/next/CHANGELOG.md)
- [Commits](https://github.com/storybookjs/storybook/commits/v9.1.17/code/core)

---
updated-dependencies:
- dependency-name: storybook
  dependency-version: 9.1.17
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-21 07:48:54 -08:00
dependabot[bot] 261fd9036f chore(deps): bump @modelcontextprotocol/sdk from 1.22.0 to 1.25.1
Bumps [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) from 1.22.0 to 1.25.1.
- [Release notes](https://github.com/modelcontextprotocol/typescript-sdk/releases)
- [Commits](https://github.com/modelcontextprotocol/typescript-sdk/compare/1.22.0...1.25.1)

---
updated-dependencies:
- dependency-name: "@modelcontextprotocol/sdk"
  dependency-version: 1.25.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-21 07:48:50 -08:00
Nick Baumann 2334d4d531 fix: model picker favorites ordering, star toggle, and keyboard nav
Co-authored-by: Nick Baumann <nickbaumann98@gmail.com>
2025-12-21 06:54:13 -08:00
Prithvi Singh Chohan 6390d854f7 fix: sync Plan/Act mode settings when switching tabs in OpenAI compatible provider
Co-authored-by: Prithvi Singh Chohan <pv11messi@gmail.com>
2025-12-21 06:38:01 -08:00
Saoud Rizwan 7d5c56a55a chore: add CLAUDE.local.md to gitignore 2025-12-21 06:14:32 -08:00
Saoud Rizwan 0dc760ac03 fix: rename Bot Triaged label to Bot Responded, apply after comment 2025-12-21 04:41:05 -08:00
Saoud Rizwan 8c1241c8cd feat: use Opus 4.5 model for issue triage 2025-12-21 04:11:06 -08:00
Saoud Rizwan 17686ae3d9 feat: add Bot Triaged label to issue triage workflow 2025-12-21 03:59:58 -08:00
Saoud Rizwan 97460d2952 fix: fetch label descriptions for better triage 2025-12-21 03:24:28 -08:00
Saoud Rizwan e629ed0ef6 fix: always include Possible Duplicates section 2025-12-21 02:29:24 -08:00
Saoud Rizwan 96788e9127 fix: clarify one-time response - no follow-up language 2025-12-21 02:18:28 -08:00
Saoud Rizwan d7716a514d fix: improve triage prompt - always report on recent changes analysis 2025-12-21 02:08:56 -08:00
Saoud Rizwan 7aaa5966d6 fix: allow all tools for issue triage 2025-12-21 01:31:39 -08:00
Saoud Rizwan bb1d068139 feat: add Claude issue triage workflow for automatic issue response 2025-12-21 01:14:54 -08:00
Saoud Rizwan 450945ae0e fix(ci): fetch tags for previous tag lookup and add line break in release body 2025-12-20 07:30:13 -08:00
Saoud Rizwan 191e9635bd fix(ci): use CHANGELOG.md content for GitHub release notes
Instead of auto-generating release notes from PRs, extract the
changelog entry for the version being released and append the
Full Changelog comparison link.
2025-12-20 06:59:36 -08:00
Saoud Rizwan c13a7a80b3 v3.45.1 Release Notes (hotfix)
Hotfix release including:
- 8a9e03c8f: fix(mcp): resolve race condition when updating Cline-specific MCP settings
2025-12-20 06:41:28 -08:00
Saoud Rizwan d4a4adfa5f fix(ui): Misc UI improvements (markdown + home page) (#8229)
* fix(ui): add margin styling for ordered lists in markdown

* fix(ui): prevent info icon from shrinking and add padding on home page
2025-12-20 01:46:59 -08:00
Saoud Rizwan 557e20224e fix(checkpoints): don't show checkpoint message when initialization fails (#8230)
When starting a task in a location that can't use checkpoints (e.g., Desktop,
Documents, Downloads, or home directory), the checkpoint message was still
appearing in the chat without a SHA. This happened because the code added
the message before checking if initialization had failed.

Now we check for `checkpointManagerErrorMessage` before showing the checkpoint
message, so users in unsupported locations won't see a broken checkpoint element.
2025-12-20 01:44:06 -08:00
Saoud Rizwan 0e9a326a6a fix(test): update banner carousel pagination format in e2e test
The banner carousel format changed from '1/3' to '1 / 3' (with spaces)
in commit 8f1405b88. Update the test regex patterns to match.
2025-12-20 00:47:38 -08:00
Saoud Rizwan f5ecb6db0c feat(ui): add green styling to task completed row (#8226)
* Revert "feat: enhanced compact task complete ui (#8025)"

This reverts commit cc36c67fc9.

* feat(ui): add green styling to task completed row

- Add green border and tinted green background to task completion container
- Add copyButtonStyle prop to WithCopyButton for custom positioning
- Revert previous compact task UI changes in favor of simpler styling
2025-12-19 23:01:55 -08:00
Saoud Rizwan 8f1405b881 fix(ui): improve banner carousel styling and dismiss functionality (#8225)
* fix(ui): improve banner carousel styling and dismiss functionality

- Fix dismiss button not working by adding version-based filtering
- Use CSS Grid stack technique to auto-size carousel to tallest card
- Fix spacing issues on narrow widths with reduced margins/padding
- Add hover underline for links in banner descriptions
- Prevent header icon from shrinking on narrow screens
- Remove bottom margin from markdown paragraphs
- Clean up navigation footer styling

* chore: add changeset
2025-12-19 22:18:44 -08:00
Saoud Rizwan 8a9e03c8ff fix(mcp): resolve race condition when updating Cline-specific MCP settings (#8222)
* fix(mcp): resolve race condition when updating Cline-specific MCP settings

Fixes a bug where toggling auto-approve for MCP tools or changing timeout
settings would cause the UI to flash and revert, making the toggles appear
unresponsive.

The root cause was a race condition between two state update mechanisms:
1. RPC Response: Returns updated servers immediately to the webview
2. File Watcher: Detects the settings file change and triggers a second
   update ~100ms later, potentially overwriting the first

Additionally, the file watcher was triggering full server restarts even
for settings changes that don't affect the MCP transport connection.

Changes:
- Add `isUpdatingClineSettings` flag to skip file watcher processing
  when we're making internal settings changes
- Add `configsRequireRestart()` method to distinguish between settings
  that require server restart vs Cline-specific UI settings
- Only notify webview when actual connection changes occur
- Update in-memory state for timeout changes without server restart
- Add comprehensive documentation for future Cline-specific settings

* chore: add changeset

* fix: update comments and sync all Cline-specific settings in-memory
2025-12-19 21:35:06 -08:00
Bee edba02b45e feat: add background edit mode with webview diff display (#8205)
* feat: add background edit mode with webview diff display

- Replace editor-based diff preview with webview DiffEditRow component
- Remove unused partialPreviewState and related methods from ApplyPatchHandler
- Integrate FileEditProvider in Task for background file edits when enabled
- Add comprehensive Storybook stories for diff edit row states

Test Plan:

1. Go to Features Setting to turn on `Background Edit`
2. Start a task that would perform file edits
3. Verify the diff edits will be performed in the background instead of stealing focus from your editor
4. Verify the new stories in Storybook for the new DiffEditRow components

* backgroundEditEnabled

* changeset

* clean up

* clear time out

* fix storybook
2025-12-19 16:23:13 -08:00
Jose R. Perez cc36c67fc9 feat: enhanced compact task complete ui (#8025)
* feat: enhanced task completed response ui

* feat: enhanced task completed response ui

* feature: adjusted embed component styling

* fix: minor adjustments

* fix: made last task completed expanded by default

* fix: restore api request and thinking

* feat: copy button fix
2025-12-19 15:46:20 -08:00
CandiedUniverse d77032bc8a fix(hooks): Fix edge case for hooks-enabled schema in the CLI (#8134)
* fix(hooks): Fix edge case for hooks-enabled schema in the CLI

* fix(hooks): Change as per PR feedback to simplify verbose logic
2025-12-19 14:25:15 -08:00
Max 608dde94b3 bump go version (#8216)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 14:14:21 -08:00
Max 47ff7c1620 fix security vulnerability with sapaicore provider (#8215)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 13:37:15 -08:00
Bee 1b7f971c34 refactor: banner system with data-driven architecture [ENG-1426] (#8140)
* refactor: banner system with data-driven architecture

Add new banner data structures and types to support a flexible, backend-driven
banner system. This enables dynamic banner management while maintaining
consistent UI rendering.

Changes:
- Add BannerCardData interface for banner configuration with support for icons,
  severity levels, actions, and platform/user filtering
- Add BannerActionType enum defining action handlers (link, settings, CLI
  install, model selection)
- Add BannerAction interface for button/link definitions
- Refactor banner rendering logic to use data-driven approach instead of
  hardcoded implementations
- Update BannerCarousel component to handle new action types dynamically

This allows the backend to construct banner JSON that the frontend renders
consistently through the BannerCarousel component when ready.

* apply feedback

* update e2e test

* Add BackendBanner struct with converter

* clean up types

* clean up
2025-12-19 12:58:36 -08:00
Max 12eadd3378 fix bedrock byo problem (#8191)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 12:22:51 -08:00
Max b3e0ef9ed7 multi-root workspace support for cli (#8163)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 12:21:22 -08:00
Bee fb94d8d3d4 fix: expose process.platform in webview build configuration (#8201)
* fix(webview): expose process.platform in build configuration

Add process.platform to Vite and Storybook define configs to make
platform detection available in the webview UI code.

* Add changeset

* Update webview-ui/vite.config.ts

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

* revert copilot suggestion

* revert package-lock.json

* remove unknown

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-19 11:19:22 -08:00
Robin Newhouse d11bd15d60 Refactor Bedrock provider to use metadata for reasoning support (#8196)
- Remove hardcoded shouldEnableReasoning check in AwsBedrockHandler

- Use modelInfo.supportsReasoning from metadata to determine if reasoning should be enabled

- Update src/shared/api.ts to include supportsReasoning: true for all relevant Bedrock models (Claude 3.7, 3.5 Sonnet/Haiku, Opus, and 1m variants)

- Ensure consistency with other providers by keeping model capabilities in metadata
2025-12-19 11:08:35 -08:00
celestial-vault 31c48898a6 Update litellm case in normalizeApiConfiguration to check stored modelinfo (#8202) 2025-12-19 10:46:22 -08:00
Zhongying Qiao 5c9901d68a feat: Make banner providers filtering determined by what is selected instead of existing provider keys (#8119)
* feat: make banner providers filtering determined by what is selected instead of existing provider keys

* refactor: address feedback, use default case for string comparison
2025-12-19 10:01:19 -08:00
Bee 45b79dc3d7 feat: add background edit mode setting (#7146)
Add backgroundEditEnabled setting to global state and settings infrastructure.
This includes:
- Proto definition for the update settings request
- State management in controller and state helpers
- Extension state interface updates
- Default value of false in webview context

Building block for ENG-1367. Setting is not yet used in the UI or anywhere in the app yet. It will be done in the follow-up PR where the feature is implemented.
2025-12-18 22:03:25 -08:00
Bee 26b6c7bdb6 refactor: move vscode config access to hostbridge layer (#7843)
- Add error_level field to telemetry proto messages
- Move getConfiguration usage from core services to vscode hostbridge provider
- Remove migrateDisableBrowserToolSetting and migrateChromeExecutablePathSetting methods
- Remove direct vscode imports from core/task and services/browser
- Update getTelemetrySettings to retrieve and return telemetryLevel from vscode config

This refactoring centralizes vscode-specific configuration access in the hostbridge provider layer, improving separation of concerns and making core services less coupled to the vscode API. Plus the cline configurations has already been set to be empty in the package.json for vs code extension.
2025-12-18 19:43:50 -08:00
Sarah Fortune d0678a2ad1 Add another codeowner for the settings directory (#8165)
* Add more codeowners for the settings directory

* Update CODEOWNERS
2025-12-18 19:11:14 -08:00
Bee 09276ebf43 fix: prevent duplicate error messages during streamed edit tool failures (#8200)
Add early return in WriteToFileToolHandler catch block when tool has
already failed once during streaming when enableParallelToolCalling is not enabled. This prevents the same error
message from being repeatedly added to userMessages array on each
new streaming chunk received.
2025-12-18 18:17:48 -08:00
CandiedUniverse af8b51b189 Revert "fix(hooks): Fix the underlying Windows detection logic [#8703] (#8168)" (#8197)
This reverts commit 3e6b3f252b.
2025-12-18 15:12:34 -08:00
CandiedUniverse 3e6b3f252b fix(hooks): Fix the underlying Windows detection logic [#8703] (#8168)
* fix(hooks): Fix the underlying Windows detection logic

* fix(hooks): Rename isMacOSOrLinux() to useIsMacOSOrLinux() per review feedback
2025-12-18 13:57:24 -08:00
Robin Newhouse f019c365a6 Refactor Anthropic handler to use metadata for reasoning support and cache_control behavior (#8170)
* Refactor Anthropic handler to use metadata for cache_control behavior

Replace hardcoded switch statement with model.info.supportsPromptCache check, following the same pattern as OpenAI Native and Vertex providers.

* Refactor Anthropic handler to use metadata for reasoning support

Replace modelId substring checks with model.info.supportsReasoning flag, and add supportsReasoning: true to all models that support extended thinking (3-7, 4-, 4-5).
2025-12-18 13:54:38 -08:00
Ara f6fe843cfb feat: auto-fail task in YOLO mode on consecutive mistakes (#8189)
When YOLO mode is enabled and the maximum consecutive mistakes
threshold is reached, automatically fail the task instead of
waiting for user input. This prevents the task from hanging
indefinitely in automated/unattended scenarios.

Displays an error message suggesting to use a more capable model
and ends the task loop with a failure signal.
2025-12-18 13:04:45 -08:00
Ara 01f26c21ae fix: handle yolo mode in AskFollowupQuestionToolHandler (#8188)
- Add check for yoloModeToggled flag to prevent waiting for user input
- Auto-respond with tool usage instructions when in yolo mode
- Log the auto-response action for transparency
- Maintain existing functionality for non-yolo mode operations
2025-12-18 12:40:52 -08:00
Robin Newhouse 031c2f5b05 fix: correct typos in gemini system prompt overrides (#8183)
Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-12-18 12:18:23 -08:00
Juan Pablo Flores c999e269db docs: add .clineignore file guidance to reduce noise in multi-root workspaces (#8162)
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-18 11:15:18 -08:00
Juan Pablo Flores 032c1bf792 DEVREL-61 docs: enhance Auto Approve feature documentation with detailed permis… (#8097)
* docs: enhance Auto Approve feature documentation with detailed permissions and usage examples

* Update docs/features/auto-approve.mdx

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

* fix: replace image with video in Auto Approve documentation for better clarity

* Update docs/features/auto-approve.mdx

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-18 11:14:23 -08:00
Nick Baumann fa73d60b7a Improve Model Picker Modal UI and provider persistence (#8131)
* Improve Model Picker Modal UI and provider persistence

* Replace fuzzy search with multi-word substring matching in model picker

* feat(model-picker): add thinking slider, provider dropdown portal, and UI improvements

- Add thinking budget slider with min/max constraints
- Render provider dropdown via portal with flip logic for positioning
- Add getProviderInfo helper for settings-only providers
- Use ArrowLeftRight icon for plan/act split toggle
- Close provider list when typing in search
- Fix selection backgrounds with linear-gradient layering
- Improve row heights and icon positioning

* refactor(model-picker): replace Fuse.js with multi-word substring search

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-17 21:22:32 -08:00
Robin Newhouse 841bb7f1d7 Disable specifically the Cline extensions in launch.json (#8176)
Replaced the global `--disable-extensions` flag with specific
`--disable-extension` flags for `saoudrizwan.claude-dev` and
`saoudrizwan.claude-dev-nightly`. This allows testing the extension
under development alongside other installed extensions while
preventing conflicts with production or nightly versions of Cline.
2025-12-17 18:01:51 -08:00
Bee f01428884d feat: replace diff edit tools with APPLY_PATCH tool for gpt-5+ native tools (#8167)
* feat: replace diff edit tools with APPLY_PATCH tool for gpt-5+ with native tool calling

Replace FILE_NEW and FILE_EDIT tools with APPLY_PATCH in the native-gpt-5-1 variant configuratiob as that's the format the GPT 5 models are trained on.

* update snapshot

* Update ApplyPatchHandler UI and new line bug
2025-12-17 16:07:47 -08:00
Tomás Barreiro 2ce5548250 [PF-207] Remotely configured OTEL (#8056)
* Remote configured OTEL

* Configure the OpenTelemetryTelemetryProvider for Remote Config and remove it when resetting the confiig

* Address comments

* Fix tests

* Refactor

* Address comments

* Refactor openTelemetryOtlpHeaders and add comment

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-12-17 21:36:35 +01:00
Tomás Barreiro 9f32cd247f fix: Fetch values available in the remote config (#8070)
* Update the StateManager with the new fields

* Add comment

* Add changeset
2025-12-17 21:09:08 +01:00
Max ace48198cc Add slash command auto-complete dropdown to cline cli (#8026) 2025-12-17 11:53:13 -08:00
Tony Loehr 9f0240dfd7 fixed keyboard shortcuts docs (#8116)
* fixed keyboard shortcuts docs

* improved flow of keyboard shortcuts docs

* fixed keyboard shortcuts relevance

* fixed terminal integration keyboard shortcuts relevance
2025-12-17 11:02:55 -08:00
Juan Pablo Flores 5530cfe375 DEVREL-69 docs: update multi-root workspace documentation for clarity and consi… (#8121)
* docs: update multi-root workspace documentation for clarity and consistency

* docs: remove experimental label from multi-root workspace feature

Update documentation to reflect that multi-root workspaces are no
longer considered experimental while still noting the existing
limitations with Cline rules and checkpoints.

* docs: update multi-root workspace examples to clarify workspace config file locations

* docs: add guidance on using VSCode's files.exclude to manage generated folders in multi-root workspaces

---------

Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-17 10:11:22 -08:00
Juan Pablo Flores af4d99e0bc docs: add JSON output section and ClineMessage schema to CLI reference (#8151)
* docs: add JSON output section and ClineMessage schema to CLI reference

* docs: enhance JSON output section with ClineMessage schema details
2025-12-17 10:04:11 -08:00
github-actions[bot] cd011a0e4a v3.45.0 Release Notes (#8159)
Added Gemini 3 Flash Preview model

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-17 08:47:05 -08:00
Ara d44184ab03 feat: add Gemini 3 Flash Preview model support (#8160)
- Added Gemini 3 Flash Preview to the recommended models list in the OpenRouter model picker.
- Updated the "What's New" modal to announce the availability of the new model and provide a quick-start button.
2025-12-17 08:39:37 -08:00
Bee 5d96704e92 feat: add new model configuration (#8142)
* feat: add new model configuration

Add support for the new Gemini 3 Flash Preview model with reasoning
capabilities. Updates both vertex and gemini model configurations with
pricing, token limits, and thinking level settings.

* update pricing

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-12-17 08:21:32 -08:00
github-actions[bot] 49812eb332 v3.44.2 Release Notes 2025-12-17 06:47:44 -08:00
Saoud Rizwan 57b72519ae fix(ui): improve model picker and popup modal styling (#8156)
* feat(model-picker): add tooltips to plan/act mode tabs

Show "Plan mode" and "Act mode" tooltips when hovering over the P and A
tabs in the split mode view of the model picker.

* fix(model-picker): remove focus outline from search input

* feat(model-picker): add checkmark to selected model and responsive provider

- Add checkmark icon on the right side of the selected model row
- Hide model provider name on viewports under 280px for better space usage

* fix(model-picker): remove double hover dim on provider row

* fix(model-picker): improve provider list styling consistency

- Reduce vertical padding to match model list rows
- Move checkmark to right side
- Use consistent font size

* fix(modals): add consistent arrow pointers to all popup modals

- Refactor ServersToggleModal to use same fixed positioning as other modals
- Add arrow pointer to ModelPickerModal
- Fix arrow z-index (1001) to seamlessly cover modal border
- Add viewport resize handling to ModelPickerModal for arrow repositioning
- Consistent styling across all three popup modals

* refactor(modals): unify modal styling and structure across components

- Introduce ModalContainer component for consistent styling in ServersToggleModal and ClineRulesToggleModal
- Simplify modal structure by removing unnecessary fragments and applying consistent fixed positioning
- Enhance arrow pointer implementation for better visual alignment across all modals
- Ensure responsive design and maintainability with updated styled components

* fix(modals): align modal widths with chat content and fix z-index

- Reduced modal inset from 15px to 10px to match chat content width
- Lowered modal z-index from 1000 to 49 so tooltips appear on top
- Adjusted modal positioning for consistency across all three modals

* fix(model-picker): update icon usage and tooltip content for thinking and split modes

- Replace Sparkles icon with Brain for extended thinking toggle
- Update tooltip messages to reflect current functionality for thinking and split modes
- Adjust padding in provider list item for better alignment
- Add min-height and box-sizing to search container for improved layout

* fix(model-picker): improve row heights, icons, and selection backgrounds

- Add min-height to search container for consistent row sizing
- Increase provider list padding from 4.5px to 6px
- Swap icon positions and use ArrowLeftRight for plan/act split toggle
- Fix transparent selection background on some themes using linear-gradient

* fix(model-picker): close provider list when typing in search

* fix(modals): adjust modal positioning

* refactor(modals): extract shared PopupModalContainer component

Consolidates duplicated modal container styling into a reusable component.
Removes ~130 lines of redundant code across ModelPickerModal, ServersToggleModal,
and ClineRulesToggleModal.
2025-12-17 06:42:22 -08:00
Saoud Rizwan 1ed4d00a16 fix(ui): improve WhatsNew modal design and responsiveness (#8155)
- Add side spacing for small viewports (calc(100%-2rem) instead of w-full)
- Apply rounded corners at all viewport sizes (not just sm:)
- Remove redundant "NEW" badge (title already says "New in v...")
- Remove redundant "Dismiss" button (X close button is sufficient)
- Reduce excess bottom padding for tighter layout
- Add cursor-pointer to dialog close button for better UX
- Clean up unused imports (PLATFORM_CONFIG, PlatformType, isVscode)
2025-12-17 05:25:33 -08:00
Robin Newhouse c090f5b1a7 fix: skip reasoning for GLM models (#8147)
GLM models output thinking content in text tags when reasoning is enabled, which is not currently supported by the UI. Disabling reasoning for these models ensures cleaner output.
2025-12-17 01:36:23 -08:00
Saoud Rizwan 3c917ec99d fix: disable auto port forwarding in workspace settings (#8149) 2025-12-16 23:19:32 -08:00
Saoud Rizwan b315be397d docs: update release workflow with learnings from first run 2025-12-16 22:15:32 -08:00
github-actions[bot] dc9e7916de v3.44.1 Release Notes 2025-12-16 21:47:26 -08:00
Saoud Rizwan cb9d1e81b8 Add release slash command and reorganize workflow files 2025-12-16 21:42:00 -08:00
Saoud Rizwan eb5a452c9c fix: restore local MCP server connections blocked by enterprise config logic (#8148)
* fix: restore local MCP server connections blocked by enterprise config logic

The enterprise MCP allowlist feature (commit 3409fa744) inadvertently
blocked all local stdio-based MCP servers for regular users.

The bug: the validation logic applied enterprise restrictions to everyone
by default, when it should only apply when enterprise config is present.

* chore: add changeset
2025-12-16 21:05:55 -08:00
Max 6a90294a2a update package-lock.json (#8107) 2025-12-16 19:09:42 -08:00
Bee 2e1334c10a dev: add snapshot tests for native tools content (#8145)
- Add snapshot file for native tools returned by system prompt getter function
- Remove inline comment from test:unit npm script that was breaking the command "npm run test:unit -- --update-snapshots"
2025-12-16 18:10:15 -08:00
mintlify[bot] 18b77ee5e5 DEVREL-59 Add cross-references between hooks and CLI documentation (#8063)
* Update docs/features/hooks/index.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

* Update docs/cline-cli/overview.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

* Update docs/cline-cli/cli-reference.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

* Update docs/cline-cli/cli-reference.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

* Update docs/cline-cli/overview.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

* Update docs/cline-cli/overview.mdx

Co-Authored-By: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>

---------

Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2025-12-16 16:58:47 -08:00
Tomás Barreiro 4bf8feecac Remove the remote config auth listener (#8110) 2025-12-16 16:22:01 -08:00
Tomás Barreiro 2f3450f667 Extract Remotely Configured API keys (#8144)
* Extract Remotely Configured API keys

* Add changeset
2025-12-16 16:10:20 -08:00
Robin Newhouse 3e89c28727 feat: implement lazy evaluation for dynamic tool instructions (#8135)
Introduces a "Value or Provider" pattern to tool specifications, allowing the `instruction` field to be either a static string or a function of `SystemPromptContext`. This enables dynamic configuration of tool prompts based on runtime context (e.g., user settings) without hardcoding logic in the prompt builder.

- Updated `ClineToolSpecParameter` to support `string | ((context) => string)`
- Added `resolveInstruction` helper to handle dynamic resolution
- Refactored `PromptBuilder` to resolve instructions using the current context
2025-12-16 15:09:36 -08:00
Ara d065ac7b37 feat: update banner for version 3.44.0 (#8139)
- Update package.json and package-lock.json version from 3.43.1 to 3.44.0
- Add changelog entry for version 3.44.0 with banner update note
2025-12-16 13:59:13 -08:00
github-actions[bot] 5a0a25601a v3.43.1 Release Notes (#8132)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-16 13:25:37 -08:00
Ara 48d822a030 fix: update OpenRouter model ID from zai to z-ai for GLM-4.6 (#8138) 2025-12-16 13:16:06 -08:00
github-actions[bot] 417104505c v3.43.0 Release Notes (#8089)
- GLM-4.6
- kat-coder-pro
- Add parsing of env variable patterns to the mcpconfig.json

- TLS Proxy support issues for VSCode
- Add supportsReasoning flag to OpenAI reasoning models
- Fix thinking not available for some models in the OpenAI provider
- Fix invalid signature field issues when switching between Gemini and Anthropic providers
- Extract OpenRouter model filtering into reusable utility and use it in different model pickers
- Fix a11y for auto approve checkbox
- Improve ModelPickerModal provider list layout

- Migrate WhatsNewModal to new shared dialogue component

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-12-16 10:26:36 -08:00
Juan Pablo Flores e21d3ff1bb Update/explain changes (#7977)
* docs: update explanations for Explain Changes feature and command in VS Code

* fix: update Enterprise card link to point to the correct overview page
2025-12-16 09:55:47 -08:00
Max da5477f891 added an architecture doc describing cline CLI architecture (#8049)
- this will help the community to onboard to the CLI quicker and me more
open to contributing to it.

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-16 09:30:54 -08:00
Ara 4903dfcb6e feat: add GLM-4.6 and KAT-Coder Pro to free models list (#8128)
- Add Zhipu AI's GLM-4.6 agentic coding model as a free option
- Add KwaiKAT's KAT-Coder Pro model as a free option
- Update filter to preserve kat-coder-pro in Cline provider model list
2025-12-16 09:24:24 -08:00
Ara 37b2f7fbc9 fix: correct IS_STANDALONE env check to use string comparison (#8098)
The IS_STANDALONE environment variable is statically rewritten to
"true" or "false" strings by esbuild. Using a truthy check caused
"false" to be evaluated as true, incorrectly enabling the standalone
proxy configuration.
2025-12-16 09:01:08 -08:00
Bee 11fbe4b21d fix: add supportsReasoning flag to OpenAI reasoning models (#8124) 2025-12-16 06:42:18 -08:00
Bee e0844ac6e2 refactor: migrate WhatsNewModal to new shared dialogue component (#8112)
* feat(webview): migrate WhatsNewModal to new shared component

- Add @radix-ui/react-dialog dependency
- Replace custom modal implementation with Radix Dialog primitives
- Remove commented-out code and unused imports
- Update Storybook stories to include showAnnouncement state
- Add version to mock state for stories

The new Dialog UI component allows us to reuse the component with unified behavior and styles if needed

* replace deprecated VS Code toolkits component with shared components

* Clean up Modal component

* clean up
2025-12-16 06:39:34 -08:00
Bee f28d760675 fix: handle invalid signature fields for Anthropic and Gemini providers (#8122)
- Add dummy thought signature fallback for Gemini API when signature is missing
- Filter out thinking blocks without signatures before sending to Anthropic API
- Update signature field cleaning to apply to non-thinking blocks only
- Remove unused DEFAULT_CACHE_TTL_SECONDS constant

This ensures proper message conversion between providers by using Gemini's
documented dummy signature "skip_thought_signature_validator" when original
signature is unavailable, and prevents invalid thinking blocks from being
sent to Anthropic's API which requires valid signatures.
2025-12-16 06:05:07 -08:00
Ara 8363d090e0 feat(ui): improve ModelPickerModal provider list layout (#8083)
Move provider list inside scrollable container and hide model content
when provider list is expanded. This improves UX by preventing layout
overflow and providing cleaner visual separation between provider
selection and model browsing states.
2025-12-16 00:58:16 -08:00
Zhongying Qiao 3409fa7442 feat: check pre-configured MCP server urls and do not parse unless on the allowed list (#8055)
* feat: add ability for enterprise to disable user from adding MCP servers via remote config

* use a proper type check instead of an as any assertion

* feat: check remote mcp server url against user configured mcp server and do not parse servers not on the allow list if no personal server allowed

* feat: Enforce remote config's local MCP market place settings and filter by allowlist and source (#8068)

* feat: add parse/load enforcement for local mcp market place servers

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-12-16 00:04:46 -08:00
Zhongying Qiao a20685d289 feat: Enable extensions to send os types as query param for banners (#8114)
* feat: enable extensions to send os types as query param for banners

* add tests

* check os type with semantically correct method
2025-12-15 22:34:53 -08:00
Bee 926c5e189e fix: use cursor pointer to model description expand button (#8106)
Added cursor-pointer class to the expand/collapse button in ModelDescriptionMarkdown to provide proper visual feedback on hover.
2025-12-15 12:40:55 -08:00
CandiedUniverse 2a5ca9d312 feat(hooks): Add telemetry for hooks [ENG-999] (#7993)
* feat(hooks): Add telemetry for hooks

feat(hooks): Simplify hooks telemetry implementation and improve safety

feat(hooks): Changes as per Cline's code review

* feat(hooks): Changes as per PR feedback.
2025-12-15 10:06:18 -08:00
celestial-vault d06717342b add the parsing of env variable patterns to the mcpconfig.json (#8079)
* add the parsing of env variable patterns to the mcpconfig.json

* make sure to expand env variables in the config before validation
2025-12-13 21:50:25 -08:00
Zhongying Qiao c904cfe376 feat: Add ability for enterprise to disable user from adding MCP servers via remote config (#8029)
* feat: add ability for enterprise to disable user from adding MCP servers via remote config

* use a proper type check instead of an as any assertion
2025-12-13 21:34:28 -08:00
lahernandezb 924ca1278c fix: auto approve screen reader a11y (#7901)
* fix: auto approve screen reader a11y

prevoius impl contained 2 tab stops per checkbox and read a generic
"Checkbox" label when focues on the checkbox input. This can be
confusing for a visually impaired person using a screen reader

* chore: changeset

* chore: remove unused imports

---------

Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-12-12 16:39:08 -08:00
github-actions[bot] 2b0c0a659d v3.42.0 Release Notes (#8052)
- Expose `getAvailableSlashCommands` rpc endpoint to UI clients
- Made slash command menu and context menu accessible and screenreader-friendly
- Made expanding/collapsing UI components accessible

- Model identity and routing for devstral-2512 free model
- Extension pricing/UI bug where extension incorrectly shows zero price for devstral-2512

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-12 15:16:52 -08:00
Ara f4477e229d fix: update OpenRouter model ID and filter logic for devstral-2512 (#8065)
* fix: update OpenRouter model ID and filter logic for devstral-2512

- Update the model ID for devstral-2512 to include the ':free' suffix
- Modify the filter logic in providerUtils to handle devstral-2512 models
  and ensure they are not excluded when using the Cline provider
- Also ensure the default OpenRouter model is preserved in the filter

* Mistral change

* Mistral change

* Mistral change
2025-12-12 14:25:58 -08:00
Ara 5207d5c68e refactor: extract OpenRouter model filtering into reusable utility (#8064)
- Add filterOpenRouterModelIds function to providerUtils.ts
- Apply consistent filtering logic in ModelPickerModal and OpenRouterModelPicker
- For Cline provider: exclude :free models except Minimax
- For OpenRouter/Vercel: exclude cline/ prefixed models
2025-12-12 12:38:09 -08:00
Mingxuan Zhang 51b535e2d6 accessibility: screen reader support for slash and context menus (#7832)
* accessibility: screen reader support for slash and context menus

* remove unnecessary selection announcement

* changeset run

* chore: clear announcement to avoid interfering with dom queries

* chore: resolve conflict
2025-12-12 11:46:32 -08:00
jgellin-sf 4db61b1b36 chore: make expanding/collapsing ui components accessible (#7828)
* chore: make expanding/collapsing ui components accessible

* chore: changeset

* chore: check isLoading on CodeAccordian key handler

---------

Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-12-12 10:41:32 -08:00
Zhongying Qiao 6baf611322 feat: Make extension use new banner api, keep providers for extension side rules eval (#8022)
* feat: make extension use new banner api, keep providers for extension side banner rules eval
2025-12-12 09:00:27 -08:00
Max 97d635d606 expose a getAvailableSlashCommands rpc endpoint in cline core (#8024) 2025-12-11 16:05:35 -08:00
Ara 8ce476ccaa Refactor Terminal Module (#7966)
* refactor: move terminal integration from core to vscode host

- Relocate terminal-related code from core/integrations to hosts/vscode/terminal
- Move TerminalManager, TerminalProcess, TerminalRegistry, and related utilities
- Update import paths across the codebase to reference new locations
- Remove unused shellIntegrationWarningTracker and shouldShowBackgroundTerminalSuggestion from Controller
- This change better separates VSCode-specific terminal handling from core logic

* Mistral change

* refactor: consolidate terminal types into types.ts

- Move ActiveBackgroundCommand, AskResponse, CommandExecutorCallbacks, CommandExecutorConfig from ICommandExecutor.ts to types.ts
- Move OrchestrationOptions, OrchestrationResult from CommandOrchestrator.ts to types.ts
- Delete ICommandExecutor.ts (all types now in types.ts)
- Update imports in CommandExecutor.ts, CommandOrchestrator.ts, index.ts, and src/core/task/index.ts
- types.ts is now the single source of truth for all terminal-related types

* refactor: consolidate ITerminalProcess into types.ts

- Move ITerminalProcess, TerminalProcessEvents from ITerminalProcess.ts to types.ts
- Delete ITerminalProcess.ts (all types now in types.ts)
- Update imports in VscodeTerminalProcess.ts, StandaloneTerminalProcess.ts
- Update exports in index.ts
- types.ts is now the single source of truth for ALL terminal-related types
2025-12-11 12:11:32 -08:00
Ara bce403476e fix(ui): close WhatsNewModal when selecting model options (#8048)
Close the modal automatically when users click "Try Devstral" or
"Try GPT-5.2" buttons to improve UX flow. Also update Devstral
button text to clarify it's free.
2025-12-11 12:00:46 -08:00
github-actions[bot] ac306c3719 v3.41.0 Release Notes (#7885)
- OpenAI GPT-5.2
- Devstral-2 `devstral-2512` (formerly stealth model "Microwave")
- Improvements to chat modal model picker
- Amazon Nova 2 Lite
- DeepSeek 3.2 to native tool calling allow list
- Responses API support for Codex models in OpenAI provider (requires native tool calling)
- Xmas Special Santa Cline
- Welcome screen UI enhancements

- Initial checkpoint commit now non-blocking for improved responsiveness in large repositories
- Gemini Vertex models erroring when thinking parameters are not supported
- Restrictive file permissions for secrets.json
- Ollama streaming requests not aborting when task is cancelled

- OpenAI provider to centralize temperature configuration and include missing GPT-5 model settings
- OpenAI native handler to use metadata for model capabilities
- Vertex provider to use metadata for model capabilities

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-12-11 11:50:44 -08:00
Ara 1d8a9bf11e Change Stealth model (#8042)
* Mistral change

* Mistral change

* Mistral change
2025-12-11 11:25:31 -08:00
Nick Baumann d811a9d5f3 feat: improve chat modal model picker (#7949)
* feat: add inline model picker modal

* fix: add together to SETTINGS_ONLY_PROVIDERS, remove sapaicore

* Fix bedrock thinking support and add together to dynamic providers

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-11 10:53:46 -08:00
Ara 3abeff0379 chore(settings): refresh recommended OpenRouter model labels (#8047)
Update recommended models by switching GPT-5.1 to GPT-5.2 and adjusting "NEW"/"HOT" badges to reflect current recommendations.
2025-12-11 10:38:31 -08:00
Robin Newhouse 2763266424 feat: add GPT-5.2 model support (#8045)
* feat: add GPT-5.2 model support

* Update pricing
2025-12-11 10:30:35 -08:00
Robin Newhouse 0c3dfb6aed Fix parallel tool calling by tracking tool use via call_id (#8036)
Previously, tool results were tracked using the tool name as a key. This caused a critical bug during parallel tool execution: if the same tool (e.g., `read_file`) was called multiple times in a single turn, subsequent calls would overwrite the previous ones in the `toolUseIdMap`. This resulted in missing tool results for all but the last call.

This commit changes the tracking mechanism to use the unique `call_id` provided by the LLM as the key. This ensures that every tool call is tracked independently, regardless of the tool name.

Specific changes:
- Updated `toolUseIdMap` in `Task.ts` to store `call_id -> tool_id` instead of `tool_name -> tool_id`.
- Updated `ToolResultUtils.ts` to retrieve tool IDs using `block.call_id`.
- Removed legacy MCP-specific logic that manually mapped the generic `use_mcp_tool` name to an ID. This is no longer necessary (and would be incorrect) as MCP tools now also use the robust `call_id` tracking, enabling parallel execution for them as well.
2025-12-11 10:17:44 -08:00
Jose R. Perez 0e73cd4c9f feat: fixed glitchy welcome screen issue (#8041) 2025-12-11 07:21:55 -08:00
Robin Newhouse 6bbe5c2499 fix: remove attempt_completion tool from READ_ONLY_TOOLS (#8033)
This was causing tools to be called after task completion.
Removing this terminates the task properly only after other
tool calls are complete.
2025-12-11 00:17:41 -08:00
Saoud Rizwan 00e9d6f523 feat: add experimental parallel tool calling support (#8020)
* feat: add experimental parallel tool calling support

Add a new experimental setting that allows models to call multiple tools
in a single response. This is automatically enabled for GPT-5 models.

- Add enableParallelToolCalling setting (off by default)
- Conditionally enforce didAlreadyUseTool flag based on setting
- Move checkpoint from per-tool to per-response
- Add UI toggle in Feature Settings section

* feat: enable parallel tool calling for GPT-5 in prompts and API (#8028)

* feat: enable parallel tool calling for GPT-5 in prompts and API

Update system prompts for GPT-5 and next-gen variants to instruct
models they may use multiple tools in a single response for independent
operations.

Fix OpenAI API to send parallel_tool_calls: true for GPT-5 models,
which was previously hardcoded to false for all models.

Related: #8020

Changes:
- Updated 5 prompt variant files to allow parallel tool use
- Added enableParallelToolCalls param to getOpenAIToolParams()
- Updated openai-native.ts to enable for GPT-5 model family

* Update system test snapshots for parallel tool calling

* Revert changes to MCP prompts

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
2025-12-11 00:05:22 -08:00
Toshii 010fd71140 additional prompting for new task command (#8035) 2025-12-10 22:31:01 -08:00
Toshii 17a95f0021 adding xml examples to all newtask calls (#8034) 2025-12-10 19:33:00 -08:00
Ara 27c9971774 feat(mistral): fix proxy support and add new model definitions (#8018)
* feat: Added Devstral 2 Models

* feat(mistral): fix proxy support and add new model definitions

- Fix HTTPClient fetcher to properly extract URL and options from Request
  objects, enabling proxy support in standalone mode (JetBrains/CLI)
- Add duplex option for body streams required by Node.js/undici
- Rename devstral-small-latest to labs-devstral-small-2512
- Add mistral-large-2512 model (256K context, $0.5/$1.5 pricing)
- Add ministral-14b-2512 model (256K context, $0.2/$0.2 pricing)

---------

Co-authored-by: omercelik <omercelik@users.noreply.github.com>
2025-12-10 12:35:25 -08:00
Robin Newhouse 644d06c487 Fix tool use argument handling in Claude Code provider (#8023)
The Claude Code CLI returns tool arguments as complete objects, but the
StreamResponseHandler expects string chunks for streaming. This caused
tool calls to fail with "missing parameter" errors because the object
was being concatenated with a string, resulting in "[object Object]".

This change stringifies the tool arguments in the Claude Code provider
before yielding them, ensuring they are correctly parsed by the
StreamResponseHandler.
2025-12-10 11:56:49 -08:00
Tony Loehr 1be314dfed Enterprise docs (#7714)
* enterprise docs

* tested for accuracy

* Reorganize Enterprise docs structure

- Consolidate member management under team-management/
- Unify all configuration under configuration/ with two clear paths:
  - remote-configuration/ for simple cloud-based setup
  - infrastructure-configuration/ for advanced enterprise features
- Create comprehensive overview pages explaining the differences
- Update all internal links to reflect new paths
- Preserve all existing content while eliminating redundancy
- Maintain clear separation between admin and member documentation

* removed trailing backslash

* fix docs.json

* enterprise docs reformat

* monday update

* tidied up managing members section

* fixed deployment guide

* simplify rules

* workflow cleanup

* rules tweak

* Update docs/enterprise-solutions/configuration/overview.mdx

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

* fix other features

* fixed provider docs

* fixed monitoring

* fix providers

* updated cta and rbac

* fix enterprise overview

* enterprise-docs

* hid self-hosted section for now

* addressed format fixed

* docs: restructure monitoring navigation and move telemetry

- Remove unnecessary OpenTelemetry dropdown wrapper in Enterprise navigation
- Move Cline Telemetry from control-other-cline-features to monitoring section
- Update all internal documentation links to new telemetry path
- Simplify Control Other Cline Features section to focus on Yolo Mode only
- Group related monitoring features (overview, telemetry, opentelemetry) together

This creates a more cohesive navigation structure where telemetry-related
features are adjacent and eliminates unnecessary nested dropdowns.

* docs: rename Basic Telemetry to Cline Telemetry and add link

- Rename all instances of 'Basic Telemetry' to 'Cline Telemetry' for consistency
- Add href link to Cline Telemetry card in Monitoring Options section
- Update section headings and subheadings to use 'Cline Telemetry'
- Ensures consistent naming across monitoring documentation

* docs: restructure Enterprise YOLO Mode to focus on administrator controls

- Change title from 'Yolo Mode' to 'YOLO Mode' for consistency
- Add reference link to /features/yolo-mode for general documentation
- Remove duplicate content about basic YOLO Mode functionality
- Focus exclusively on Enterprise administrator configuration and controls
- Add comprehensive policy recommendations by organization size
- Include security implications, monitoring requirements, and compliance considerations
- Provide detailed technical implementation guidance
- Update overview.mdx card description to reflect enterprise focus

* docs: hide self-hosted/infrastructure configuration references

- Remove choosing-your-deployment from Enterprise navigation
- Remove self-hosted references from enterprise-solutions/overview.mdx
- Remove self-hosted comparison and warning from remote-configuration/overview.mdx
- Remove Info boxes linking to infrastructure config from provider pages (AWS, Google, LiteLLM)
- Remove Self-Hosted OpenTelemetry Collector section from opentelemetry.mdx
- Remove self-hosted deployment section from control-other-cline-features/overview.mdx

All self-hosted/infrastructure configuration documentation remains intact but is no longer
navigable or linked from SaaS provider configuration pages. This allows easy restoration
when features become available.

* clarified domain and seat info

* fixed getOpenTabs function

* Update getOpenTabs.ts

* Update package.json

* Revert package-lock files to main

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2025-12-10 11:05:14 -08:00
Saoud Rizwan 91940fbb4a v3.40.2 Release Notes (hotfix)
Hotfix release including:
- 279e371cf: fix: prevent logout on network errors during token refresh (#8021)
2025-12-11 03:37:29 +09:00
Saoud Rizwan 279e371cf5 fix: prevent logout on network errors during token refresh (#8021)
* fix: prevent logout on network errors during token refresh

When network errors occur at startup (e.g., opening laptop while offline),
users were being logged out because the token refresh failed and returned
null to AuthService.

Now on network errors or max retries exceeded, we return the stored auth
data instead of clearing the session. This keeps users logged in with
their existing credentials. If the token is truly invalid, the actual API
request will fail later when the user tries to use Cline, rather than
logging them out preemptively at startup.

* chore: add changeset
2025-12-10 10:33:00 -08:00
Saoud Rizwan 4eda267981 fix(e2e): update auth test to handle Santa Cline logo with multiple paths
The Santa Cline logo has 3 path elements, causing strict mode violation.
Select the container instead of a specific path element.
2025-12-11 03:21:26 +09:00
Robin Newhouse 3441363805 fix: only send thinking params to Gemini models that support them (#8014) 2025-12-09 21:37:53 -08:00
Robin Newhouse 5389be991e Refactor Vertex provider to use metadata for model capabilities (#7999)
This change removes hardcoded switch statements in VertexHandler and moves model-specific configurations (like reasoning support and prompt caching) into the centralized model metadata in src/shared/api.ts.

Benefits:
- Decouples handler logic from specific model IDs
- Centralizes model capabilities for easier maintenance
- Simplifies adding future Vertex models
- Improves type safety

Related: ENG-1408, ENG-1385
2025-12-09 15:36:02 -08:00
Sarah Fortune 41fd610203 Don't enable gRPC debug logs in the cli (#8013)
If you need this for development you can enable them locally, they shouldn't be turned on in the released version; they are spammy af.
2025-12-09 15:10:37 -08:00
Jose R. Perez e1e7470fdd feature: xmas special santa cline (#8010)
* feat: hide whats new modal header image for now

* feature: change set

* feat: xmas special santa cline

* fix: minor change to actual svg

* Fix colors

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-12-09 15:04:11 -08:00
Zhongying Qiao 2f0e0ee56d feat: configure Litellm API key with remote config (#7937)
* feat: configure Litellm API key with remote config
2025-12-09 14:56:23 -08:00
Robin Newhouse 7f89ebf276 fix: make initial checkpoint commit non-blocking but block unsafe tools [#AI-26] (#8008)
* fix: make initial checkpoint commit non-blocking while preventing tool execution races

- Captures the initial checkpoint commit promise in the Task class
- Ensures executeTool waits for the initial commit to complete before running any tools
- Resolves race condition where tools could modify files before the initial state was fully captured

* feat: allow read-only tools to bypass initial checkpoint block

- Defines READ_ONLY_TOOLS allowlist in shared/tools.ts
- Updates Task executor to check tool name against whitelist
- Allows exploration tools (list_files, read_file, browser_action, etc.) to run in parallel with initial commit
- Maintains blocking for state-modifying tools (write_to_file) to ensure data integrity
2025-12-09 14:43:30 -08:00
Jose R. Perez 99ed1b7e86 feat: hide whats new modal header image for now (#8009)
* feat: hide whats new modal header image for now

* feature: change set
2025-12-09 13:49:42 -08:00
Ara 45c9fcf575 Removing unused file in Dify Provider (#7968) 2025-12-09 13:41:42 -08:00
Stewi 4f73f4460b fix(docs): correct broken signup link in installing-cline docs
Fixed a broken link in installing-cline.mdx: replaced https://app.cline.bot/signup with https://authkit.cline.bot/ for account creation.
2025-12-09 12:56:30 -08:00
Ara fb872fd316 feat(banners): add dismiss functionality to banner carousel (#7982)
* feat(banners): add dismiss functionality to banner carousel

- Add onDismiss callback to BannerData interface
- Implement dismiss button (X icon) in BannerCarousel component
- Add onDismiss handlers for info, model, and CLI banners
- Update banner version in state when user dismisses a banner
- Fix carousel index bounds handling when banners are removed
- Refactor carousel handlers with useCallback for better performance

* Fix imports

* feat(banners): show dismiss X only on last card in carousel
2025-12-09 12:46:30 -08:00
Tomás Barreiro 5292242a8e Add loaders to login buttons (#7945)
* Add loaders to login buttons

* Disable the button when loading

* Add changeset

* Remove log

* Fix tests
2025-12-09 20:41:56 +01:00
CandiedUniverse 78b8aed50f feat(hooks): Implement PreCompact hook [ENG-1005] (#7513)
* feat(hooks): Implement PreCompact hook

feat(hooks): Continuing implementation of PreCompact hook

feat(hooks): PreCompact supports contextModification

Fixes as per Cline code reviewing the PreCompact implementation

feat(hooks): Tweaking the PreCompact hook behavior while testing

feat(hooks): Implement PreCompact hook in handleContextWindowExceededError code path

feat(hooks): Implement conversation history temp file in task directory for PreCompact to access

feat(hooks): Implement context window temp file in task history directory for PreCompact to access

feat(hooks): Refactor complex function into helpers

* feat(hooks): Improvements from Cline code reviewing the change set

feat(hooks): Refactor duplicate logic into common utility function

feat(hooks): Improve compaction strategy naming

feat(hooks): Deduplicate a small piece of logic

feat(hooks): DRY for getNextTruncationRange()

feat(hooks): Fix contextModification for PreCompact hook

feat(hooks): Improvements as per Cline's code review feedback

feat(hooks): Improving code quality/reduce complexity

feat(hooks): Further code improvements as per Cline code reviewing

* feat(hooks): Changes as per PR feedback
2025-12-09 11:20:29 -08:00
Tomás Barreiro d01f7b4618 Log session information (#7944)
* Prevent multiple simultaneos refreshes when retrieving auth info

* refactor

* Track logout events

* Add changeset

* Persist the startedAt date

* Fix bug

* Use snake case for event properties

* Log failed refresh request information
2025-12-09 20:10:20 +01:00
CandiedUniverse dec215cd9c feat(hooks): Enable hooks in the CLI [ENG-1375] (#7948)
* feat(cli): Add hooks_enabled support to CLI settings

- Add hooks_enabled field to Settings proto message (field 134)
- Add hooks_enabled parsing to CLI settings parser
- Enables users to toggle hooks via -s hooks_enabled=true/false flag

Fixes missing CLI support for hooks that was available in the VSCode extension

* feat(hooks): Enable hooks in the CLI

* Add include back in after resolving merge conflict

* feat(hooks): Changes as per human code review feedback.

---------

Co-authored-by: NightTrek <Daniels@dual4t.com>
2025-12-09 10:32:18 -08:00
Toshii 8ce7e132d2 add feature flag check to tool handlers (#7997) 2025-12-08 19:48:50 -08:00
Toshii 6ab008b204 adding search models to usage tables in ui (#7996) 2025-12-08 19:18:31 -08:00
Sarah Fortune 769523998d Add the cline distribution type to the telemetry (#7940)
* Add the cline distribution type to the telemetry

In the telemetry we currently have the IDE name, but because there are so many variants of VSCode and JetBrains, it's not easy to group them by VSCode extension or JetBrains plugin. Add this field to the telemetry.

* update unit tests

* Update src/services/telemetry/TelemetryService.ts

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

* Update src/services/telemetry/TelemetryService.ts

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

* Update unit tests

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-12-08 17:14:54 -08:00
Max 64a6bcc39b show mcp messages in cli output (#7989)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-08 13:20:20 -08:00
AJ Juaire 19ceafd4a4 Add Amazon Nova 2 Lite support. (#7987)
https://github.com/cline/cline/discussions/7855
2025-12-08 11:34:24 -08:00
Robin Newhouse 4b5218b3b8 Refactor OpenAI native handler to use metadata for model capabilities (#7947)
This change removes hardcoded switch statements in OpenAiNativeHandler and moves model-specific configurations (like streaming support, system role, and tools support) into the centralized model metadata in src/shared/api.ts.

Benefits:
- Decouples handler logic from specific model IDs
- Centralizes model capabilities for easier maintenance
- Simplifies adding future OpenAI models
- Improves type safety with updated getModel() signature

Related: #7920
2025-12-08 11:07:10 -08:00
Toshii b68d716675 in tests websearch shows up in cline provider prompt (#7976) 2025-12-08 00:00:19 -08:00
Toshii f820c6d00a adding handler for websearch in cli (#7570) 2025-12-08 00:00:05 -08:00
Toshii 1fcbbaa9d0 adding websearch and integrating new handler (#7514)
* implementing prompt injection for web_search and associated web fetch handler

* remove printing of the ms took

* ui showing query user is searching for

* updating the fields we pass in api request

* updating text for search tool
2025-12-07 23:10:44 -08:00
Toshii 4005df6eae updating webfetch and integrating new handler (#7509)
* updating system prompt for webfetch and integrating new handler

* updating tests to match new webfetch tool
2025-12-07 22:37:48 -08:00
Toshii 0e3cdab82b adding webtools to the features menu (#7566)
* adding webtools to the features menu

* telemetry for toggling web tools

* adding feature flag for webtools
2025-12-07 22:34:43 -08:00
Sarah Fortune ada6b0c955 Move terminal impls into the correct package. (#7970)
Move VSCode terminal impls into the src/hosts/vscode package. The VSCode specific code needs to be contained in this directory.
The `src/shared` package is for things shared with the extension and the _webview_; everything in src/ that's _not_ under `src/hosts` is shared with VSCode, JB, CLI implicitly.

ref CLIENTS-34
2025-12-07 20:35:00 -08:00
Jose R. Perez 921dd2ec8c feat: welcome screen ui enhancements (#7878)
* feat: Announcement Cards, Recent Tasks Refresh, Whats new modal

* feat: adjustments to welcome modal functionality

* chore: add changeset for welcome ui enhancements

* refactor: replace inline styles with Tailwind classes where appropriate

* fix: removed close mechanisim for cards fix modal linking issue

* feat: suggested changes

* fix: arias for accessibility

* fix: test modal fix

* feat: e2e test fix

* update e2e tests with new welcome ui

* feat: small arias change

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2025-12-07 20:32:42 -08:00
Richard 4b212994a8 fix(security): set restrictive file permissions for secrets.json (#7782) 2025-12-07 19:23:29 -08:00
CandiedUniverse 3fe3c866ea fix(hooks): Want TaskCancel to get triggered properly (#7952) 2025-12-07 06:59:19 -08:00
Ara e9136f60cc feat(terminal): Move Standalone terminal Code to Typescript (#7927)
* feat(terminal): add shared terminal types and interfaces

Add shared terminal module with types and interfaces that enable
terminal management across VSCode, CLI, and JetBrains environments.

- Define ITerminal, ITerminalManager, and TerminalInfo interfaces
- Add TerminalProcessResultPromise for async command execution
- Include StandaloneTerminalOptions for non-VSCode environments
- Prepare module structure for standalone implementations

* feat(terminal): export standalone terminal implementations

Enable exports for standalone terminal classes that were previously
commented out as placeholders:
- StandaloneTerminal
- StandaloneTerminalManager
- StandaloneTerminalProcess
- StandaloneTerminalRegistry

These implementations are now ready for use outside the terminal module.

* fix: resolve TerminalInfo type incompatibility in settings update

- Remove unused TerminalInfo import from both updateSettings files
- Use `as any` cast to handle type mismatch between VSCode and standalone TerminalInfo
- Replace busyTerminals array with busyTerminalsCount to avoid type issues
- Add null-safe access when getting busy terminals length

* feat: import StandaloneTerminalManager from bundled cline-core

Replace standalone enhanced-terminal.js with import from the bundled
TypeScript version in cline-core.js. This consolidates terminal
management code and removes the need to separately include the
runtime file in the VS Code extension package.

- Re-export StandaloneTerminalManager from cline-core.ts
- Update vscode-impls.js to import from cline-core.js
- Remove .vscodeignore exception for enhanced-terminal.js

* feat: simplify standalone terminal manager initialization

Replace global injection pattern with environment variable detection
for determining terminal execution mode. The Task class now directly
instantiates StandaloneTerminalManager when IS_STANDALONE=true instead
of relying on a globally injected instance.

- Remove StandaloneTerminalManager re-export from cline-core.ts
- Simplify vscode-impls.js createTerminal to return stub object
- Use IS_STANDALONE env var for terminal manager selection in Task
- Remove global.standaloneTerminalManager injection pattern

* Fix Standalone build

* Fix Standalone build

* fix: use subagentTerminalOutputLineLimit in StandaloneTerminalManager.processOutput

Match the VSCode TerminalManager logic to properly use subagentTerminalOutputLineLimit (2000) for subagent commands instead of always falling back to terminalOutputLineLimit (500).

* feat: add TerminalManager to HostProvider for dependency injection

- Add TerminalManagerCreator type and createTerminalManager to HostProvider
- Extract ITerminalManager interface to shared/terminal/types for abstraction
- Refactor TerminalManager to implement ITerminalManager interface
- Create StandaloneTerminalManager for non-VSCode environments
- Update TerminalRegistry to use ITerminalManager via HostProvider
- Enable terminal management to work across different host environments

* feat: refactor terminal manager to use ITerminalManager interface

- Replace concrete TerminalManager/StandaloneTerminalManager types with ITerminalManager interface
- Use HostProvider.createTerminalManager() for host-agnostic terminal creation
- Simplify terminal execution mode logic in Task constructor
- Add dynamic imports for StandaloneTerminalManager when backgroundExec mode is used
- Improve logging for terminal manager selection
2025-12-07 05:10:25 -08:00
Bee 34bb95e04e refactor: require native tool call for Responses API (#7953)
Add validation to ensure native tool calling is enabled when using
OpenAI Responses API format. Previously, the code would silently fall
back to completion stream when tools were not provided, which could
lead to unexpected behavior.

- Add explicit error when tools are missing for Responses API format
- Update tools parameter type to non-optional in createResponseStream
2025-12-06 05:03:29 -08:00
Saoud Rizwan 7b65db55f1 docs: update hotfix workflow to copy Slack message instead of tag 2025-12-05 16:13:37 -08:00
Saoud Rizwan 07ebc2e4bd docs: improve hotfix release workflow
- Split shell commands to avoid parsing issues with parentheses in author names
- Clarify that hotfixes always use patch version bumps
- Add (hotfix) suffix to release notes commit message format
- Skip npm install step (automation handles lockfile)
- Add pbcopy step to copy tag to clipboard for GitHub Actions
- Add direct link to publish workflow
2025-12-05 15:58:58 -08:00
Saoud Rizwan 0193179597 v3.40.1 Release Notes
Hotfix release including:
- 4df486fa5: fix cost calculation for Anthropic API requests (#7943)
2025-12-05 15:49:42 -08:00
Saoud Rizwan 20c0783c97 feat: add hotfix release workflow documentation
Add a workflow for creating hotfix releases by cherry-picking commits
from main onto release tags. Includes steps for selecting commits,
creating release notes, version bumping, and tagging.
2025-12-05 15:43:31 -08:00
Saoud Rizwan 4df486fa5b fix: restore cost calculation for Anthropic API requests (#7943)
The taskMetrics.totalCost was incorrectly initialized to 0 instead of
undefined in commit 09692d7d3. This broke cost display for providers
like Anthropic that don't return totalCost in their usage chunks.

When totalCost is 0, the fallback to calculateApiCostAnthropic() in
updateApiReqMsg doesn't trigger because the nullish coalescing operator
(??) only falls back for null/undefined, not 0.

By initializing totalCost to undefined:
- Providers that return totalCost (like OpenRouter) use that value
- Providers that don't (like Anthropic) fall back to calculating cost
  from token counts and model pricing info
2025-12-05 13:01:02 -08:00
Zhongying Qiao 5fc6d4e9e3 feat: remote config - add vertex provider (#7913) 2025-12-05 12:58:50 -08:00
Saoud Rizwan 00d3bd8316 refactor(ui): move model capabilities to Advanced section and fix layout
- Move Images, Browser, Prompt Caching badges into collapsible Advanced section
- Use consistent row styling (label: value) for capabilities
- Fix InfoRow vertical spacing when items wrap (column-gap: 16px, row-gap: 4px)
- Add bottom padding to model picker popup for breathing room
- Remove unused Tooltip imports and badge styled components
2025-12-05 12:50:31 -08:00
Robin Newhouse 81d4ff947f Refactor openai-native.ts switch statement to use model metadata (#7920)
* refactor: Move OpenAI temperature to model metadata

- Added `temperature` field to `openAiNativeModels` in `api.ts`.

- Updated `OpenAiNativeHandler` to use `model.info.temperature` instead of hardcoded values in switch cases.

- This allows for centralized configuration of model temperatures.

* refactor: Consolidate OpenAI native streaming logic

- Simplified `createCompletionStream` in `OpenAiNativeHandler` by consolidating duplicated logic for streaming models (`gpt-5`, `o3`, `o4`).

- Introduced `systemRole`, `includeReasoning`, and `includeTools` flags to handle model-specific configurations.

- Preserved distinct handling for non-streaming `o1` models.
2025-12-05 10:48:23 -08:00
Max bcb368d097 display completion messages in processStateUpdate (#7939)
CLINE-84, ENG-1392

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-05 10:36:57 -08:00
Alex Ker c1ded819bb new model in static list (#7934) 2025-12-05 09:17:20 -08:00
CandiedUniverse de02befb2f fix(hooks): Doc said the wrong directory for global hooks dir (#7933) 2025-12-05 09:02:54 -08:00
Zhongying Qiao 6617901078 feat: remove mcp marketplace enable setting from cli (#7911)
* feat: remove mcp marketplace enable setting from cli
2025-12-05 08:41:10 -08:00
celestial-vault 31c7176de1 cleanup taskhistory recovery (#7889)
* cleanup recovering by removing unnecessary recursion; rename parameter for reconstructTaskHistory for clarity, and add stdout logging in error blocks

* Don't return empty array on IO error. Instead, continue throwing error because this is indeed an error and not something that can be corrected by data reconciliation.
2025-12-05 10:32:57 -06:00
Bee 3c97c8dc19 dev: add stories for all UI components (#7905)
* dev: add stories for all UI components

* unify styles

* update
2025-12-05 04:03:47 -08:00
Nick Baumann 187e40d2da Redesign model settings page with compact info and Advanced section (#7862)
* Redesign model settings page with compact info and Advanced section

* Fix cache pricing precision to show decimals when needed

* Address PR feedback: fix cache pricing precision, remove duplicate billing link, unify provider routing
2025-12-05 03:26:46 -08:00
Andrei Eternal 8c38b1ccf8 JB Integration Workflow: use pull_request_target to support remote remote PRs (#7917)
* JB Integration Workflow: use pull_request_target to support remote repo PRs

* also sanitize the branch name and title really hard to avoid json injections

* ok lets be extra double paranoid with the sanitization

* ok lets be even more extra safer by also not logging the head_ref

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-12-04 21:22:55 -08:00
Toshii 4947a745c2 removing unused legacy context manager (#7924) 2025-12-04 20:54:45 -08:00
Toshii 9e8c6df6b2 context rewriting test cases (#7923)
* alter equality sign

* adding tests for the new file read search
2025-12-04 20:54:36 -08:00
Bee 6586195b2d docs: add contributing guide for model family [CLIENTS-32] (#7916)
* docs: add contributing guide for model family

Add detailed CONTRIBUTING.md documentation for system prompt configuration
and model family management. The guide covers:

- Architecture overview with key concepts (model families, variants, matchers)
- Glossary of terms (native/XML tool calling, API formats, components)
- Step-by-step instructions for creating new model families
- Configuration guides for system prompts and tool calling
- API request/response shape configuration
- Testing procedures and best practices

This documentation helps contributors understand the fallback system design
principle (GENERIC fallback) and provides practical examples for extending
support to new model providers and families.

* fix typo

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
2025-12-04 14:35:07 -08:00
Toshii 1aa944eff7 fix context rewriting for native tool call format (#7882)
* enable handling of tool_result blocks to fix file read search for context rewriting

* updating loop over inner indices 0-2 inclusive

* spelling
2025-12-04 14:27:14 -08:00
Robin Newhouse 8e7b1c6884 fix(ollama): abort streaming requests when task is cancelled (#7907)
Previously, clicking cancel would break out of the stream loop but
leave the HTTP connection open. Ollama would continue generating in
the background, keeping the GPU busy and blocking subsequent requests
until completion.

Now we call the Ollama SDK's abort() method to immediately close the
connection.

Fixes #7468
2025-12-04 13:56:25 -08:00
Bee ee154826b6 feat: add OpenAI Response API support and Codex model compatibility [CLIENTS-24] (#7912)
* feat: add OpenAI Response API support and Codex model compatibility

- Add ApiFormat enum to proto definitions with OPENAI_RESPONSES format
- Update model info messages to include api_format field across providers
- Refactor OpenAI native handler to conditionally use Response API based on model's api_format
- Add Codex model support in GPT-5 and GPT-5-1 prompt variants with appropriate exclusions
- Remove hardcoded useResponseFormat parameter in favor of model-driven API selection

This enables ChatGPT Codex models to use the Response API format when tools are provided, while maintaining backward compatibility with existing chat completion models.

* add comments

* tabs
2025-12-04 13:23:48 -08:00
Saoud Rizwan 852f307268 Revert "feat(prompt): add command output limiting guidance to capabilities (#…" (#7909)
This reverts commit 7a523fbaf6.
2025-12-04 11:38:10 -08:00
Bee 4e3fe004f4 feat: enable native tool calling for deepseek 3.2 [AI-27] (#7877)
* feat: enable native tool calling for deepseek 3.2

Add isDeepSeek32ModelFamily() function to identify DeepSeek 3.2 models and integrate it into the isNextGenModelFamily() check. This classifies DeepSeek 3.2 as a next-generation model family, enabling native tool calling support.

* typo
2025-12-04 09:59:27 -08:00
Zhongying Qiao 2b63eed85e feat: remove mcp enable setting for individual users (#7879) 2025-12-04 09:36:44 -08:00
Tomás Barreiro 2ffdc50ea1 Prevent simultaneous refreshes when restoring auth info (#7835)
* Prevent multiple simultaneos refreshes when retrieving auth info

* Add changeset

* refactor
2025-12-04 14:45:10 +01:00
celestial-vault 74808431e5 add litellm provider to remote config in the extension (#7775) 2025-12-04 03:01:05 -08:00
Saoud Rizwan 7a523fbaf6 feat(prompt): add command output limiting guidance to capabilities (#7884)
* feat(prompt): add command output limiting guidance to capabilities

Add guidance in the system prompt instructing the model to proactively
limit command output when anticipating large results. Includes examples
like piping to grep/head/tail or using more specific arguments.

Idea by @AraTheBoss

* chore: add changeset

* refactor: move command output limiting guidance to execute_command tool

Move the guidance from capabilities.ts to execute_command.ts where it
belongs. Extract into a shared COMMAND_BEST_PRACTICES constant to avoid
duplication across model variants (GENERIC, NATIVE_GPT_5, NATIVE_NEXT_GEN,
GEMINI_3).
2025-12-03 21:06:07 -08:00
github-actions[bot] c22ea39dc1 v3.40.0 Release Notes (#7865)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md to reflect recent changes including fixes for highlighted text flashing, terminal command issues, and enhancements for slash command usage and message padding.

* 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-12-03 19:24:18 -08:00
Saoud Rizwan c9f23076c2 fix: consolidate successive error retry messages in chat UI (#7880)
When API requests fail and auto-retry is enabled, multiple error_retry
messages were shown (e.g., "Attempt 1 of 3", "Attempt 2 of 3", etc.).
This change consolidates them to only show the latest retry message,
reducing visual clutter during retry sequences.
2025-12-03 19:18:17 -08:00
Bee a5f6c1d732 feat: add auto-recovery for corrupted task history state (#7875)
* feat: add auto-recovery for corrupted task history state

Add automatic reconstruction of task history when JSON parsing fails.

Changes:
- Modified `reconstructTaskHistory()` to return reconstruction result or null
- Enhanced `readTaskHistoryFromState()` with automatic corruption recovery
- Added recursive reconstruction attempt with loop prevention flag
- Wrapped JSON parsing in try-catch to handle corruption gracefully

When task history state file is corrupted, the system now automatically
attempts to reconstruct history from existing task folders, providing
better resilience against file corruption issues.

* feat: Add telemetry tracking for extension storage errors

Replace console.error logging with structured telemetry capture for extension storage operations. This change:

- Adds a new EXTENSION_STORAGE_ERROR telemetry event type to track storage-related failures
- Implements captureExtensionStorageError method with error message truncation to prevent excessive data
- Replaces three console.error calls in readTaskHistoryFromState with telemetry events

This improves error monitoring and provides better insights into extension storage failures while maintaining data efficiency through message truncation.

* fix: improve type safety and error handling in task history

Add explicit return type to reconstructTaskHistory() function and refactor error handling in readTaskHistoryFromState() with nested try-catch blocks to better distinguish between file read errors and JSON parse errors. This improves error recovery and makes error tracking more precise through separate telemetry calls.

* add param to reconstructTaskHistory for manually called action

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-03 17:49:28 -08:00
Toshii 3c37a160ac support multi-index search over inner messages to find file mentions (#7850) 2025-12-03 15:27:08 -08:00
Saoud Rizwan 5c3294051f Revert "fix: don't return empty array on parse failure (#7773)" (#7874)
This reverts commit 14ccf33d25.
2025-12-03 14:30:58 -08:00
Tony Loehr 4c2f28f2af docs: remove Advanced Patterns and Testing & Debugging from Hooks documentation (#7869)
- Removed advanced-patterns.mdx and testing-and-debugging.mdx files
- Updated docs.json to remove these pages from navigation
- Updated hooks/index.mdx to remove corresponding Card components
- Simplified Hooks documentation to focus on core concepts: Overview, Hook Reference, and Samples
2025-12-03 12:11:43 -08:00
Ara 6e016298cb chore: bump version to 3.39.2 and update dependencies (#7851)
- Update package version from 3.39.1 to 3.39.2
- Upgrade @changesets/* packages to latest versions
- Update @inquirer/external-editor to 1.0.2
- Upgrade js-yaml from v3 to v4 in @changesets/parse
2025-12-03 11:23:29 -08:00
pashpashpash 0cd7bebfba markdown styling fix (#7840)
* markdown styling fix

* nested ul
2025-12-03 01:23:02 -08:00
Bee 363aac61fb fix: OpenAI Response API message format (#7842)
Fixed the message structure to match the OpenAI Responses API format.

Updated Message ID placement: The message id is stored and set at the message level, not inside the content array.

This fixes an error occuring in the current code when reasoning item is followed by a message text block: 400 Item 'rs_...' of type 'reasoning' was provided without its required following item."
2025-12-02 17:41:19 -08:00
Tony Loehr eeb1cc7da8 added subpages and content to hooks (#7797)
* added subpages and content to hooks

* Update docs/features/hooks/advanced-patterns.mdx

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

* Add complete hook type coverage with examples for TaskCancel, TaskComplete, TaskResume, PreCompact, UserPromptSubmit

* Fix hook documentation API mismatches and add TaskComplete

- Add missing TaskComplete hook to reference documentation
- Fix TaskCancel/TaskResume field paths to match protobuf API
- Improve security practices in hook examples
- Add proper error handling and validation

* Update hooks documentation: rename samples, remove PreCompact, improve structure

- Rename 'Real World Examples' to 'Samples' with skill-based organization
- Remove PreCompact references (feature not yet available)
- Update navigation structure in docs.json
- Add multiworkspace mention to Overview
- Create 9 comprehensive examples (beginner/intermediate/advanced)
- Clean up duplicate content and fix cross-references

* Update hooks documentation: Add Windows support

- Remove incorrect warning that hooks don't work on Windows
- Add positive cross-platform support note (Windows, macOS, Linux)
- Clarify that bash examples work with standard shells including Git Bash/WSL on Windows

* fixed hooks overview redirect

* Add UI screenshots to hooks documentation

* hooks in action

* fixed hooks overview and examples

* fixed terminology

* fixed hooks examples

* hooks groupings

* fixed appearance of hook names

* refactor hook docs

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-12-02 17:35:07 -08:00
Sarah Fortune f760f13de5 Don't log otel events to the console because they are really spammy (#7841) 2025-12-02 17:20:52 -08:00
canvrno dd52a4a39c feat: apply_patch auto approve (#7777)
* Added apply_patch to auto approve, strict mode, and minor prompting adjustment

* changeset
2025-12-02 15:36:01 -08:00
Toshii 639edb5db6 correctly handle new and old tool call formats for context rewriting (#7809)
* correctly handle new and old tool call formats

* spelling change
2025-12-02 15:12:05 -08:00
Jack Reinhardt 3eac9b04de fix(bedrock): add sts userAgentAppId (#7719) 2025-12-02 14:40:39 -08:00
Bee 09692d7d3a feat: add mode and token metrics info to storage messages [CLIENTS-26] (#7795)
* feat(storage): add mode and token metrics to storage messages

Add mode (plan/act) tracking to ApiProviderInfo and ClineMessageModelInfo interfaces, ensuring each storage message contains the operational mode used during API requests.

Refactor token metrics tracking by consolidating cache write/read tokens, input/output tokens, and total cost into a centralized taskMetrics object. This enables better tracking and storage of token usage and costs throughout the task lifecycle, including for partial/cancelled streams.

Updated api_req_started and api_req_finished messages to include comprehensive token metrics, allowing for accurate cost reporting even when streams are cancelled or fail mid-execution.

* update unit tests with mode

* store task metrics per assistant turn
2025-12-02 13:52:44 -08:00
Andrei Eternal c81fa0a9d6 set the cli's 'ide version' to just the cli version rather than being blank, to make environment_history work for CLI (#7712)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-12-02 13:21:58 -08:00
Bee 326c9c9f99 feat: set default thinking level for Gemini 3 Pro models (#7831)
- Reorder thinking level checks to prioritize high over low
- Auto-set thinking level to LOW for Gemini 3 Pro models when not specified
- Add clarifying comment for thinking budget usage
- Ensure thinking level is always defined for Gemini 3 models to prevent errors

This change ensures Gemini 3 Pro models always have a thinking level set (required by the API) and removes the thinking budget when a level is specified, as they are mutually exclusive parameters.
2025-12-02 12:54:13 -08:00
celestial-vault a4518b90c2 add atomic file write (#7754)
* add atomic write file using write to temp file + rename to avoid situations where invalid data is written to files due to process interrupt

* adjust concurrency test for windows to expect error

* Add JSON ending to temporary file and don't await unlink
2025-12-02 13:30:53 -06:00
celestial-vault 79f4d938e6 remove unused sentry dependency (#7823) 2025-12-02 13:20:30 -06:00
canvrno 37152329cd v3.39.2 Release Notes (#7829) 2025-12-02 10:44:38 -08:00
Seb Duerr 1332d1d70d feat(cerebras): add X-Cerebras-3rd-Party-Integration header (#7824)
* feat(cerebras): add X-Cerebras-3rd-Party-Integration header

* chore: add changeset
2025-12-02 09:56:41 -08:00
canvrno 6a0d92d683 Skip reasoning_details on microwave model (#7825) 2025-12-02 09:35:30 -08:00
Ara e761a8c252 fix(changesets): remove quotes from claude-dev package name (#7822)
The quotes around the package name "claude-dev" in all changeset files were removed to adhere to the correct YAML format. This ensures proper parsing and consistency across the changeset files.
2025-12-02 07:36:09 -08:00
Ara c26d0a076d v3.39.1 Release Notes (#7818)
* v3.39.1 Release Notes

* v3.39.1 Release Notes
2025-12-02 06:16:43 -08:00
Ara c037619b90 feat: enable ModelInfoView in OpenRouterModelPicker (#7817)
Uncomment the ModelInfoView component to display model information
in the OpenRouter model picker settings panel.
2025-12-02 06:06:54 -08:00
Ara a575a76e8f v3.39.0 Release Notes (#7813)
* v3.39.0 Release Notes

* v3.39.0 Release Notes

* feat: enhance Announcement component with new microwave model and account login functionality

- Updated Announcement component to include a new free microwave model button
- Adjusted active tab logic in OpenRouterModelPicker to default to "free" if a free model is selected

* Add demo link

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-02 05:11:23 -08:00
Dominic Cooney b1d15d4fe7 fix: Standalone, ensure cwd is install dir (#7781)
Our resource loading assumes cwd is the install
dir.
2025-12-02 18:17:58 +09:00
Saoud Rizwan a0708e57ee Move notification toggle to auto-approve menu (#7812)
- Remove "Configure notification settings" link and move the toggle directly into the auto-approve menu
- Remove notification setting from General Settings since it now lives in auto-approve menu
- Remove hover:opacity-80 from icon button variant to prevent dimming on hover
- Make docs link font size inherit and separator line thinner
2025-12-01 22:44:29 -08:00
Ara ab5796fa72 Remove auto approve menu popups (#7806)
* Remove popups from auto approve settings

* feat(ui): add documentation link to auto-approve modal

Add a "Docs" link in the auto-approve modal that directs users to
the auto-approve documentation page on docs.cline.bot.

* Remove popups from auto approve settings

* Remove popups from auto approve settings

* Remove popups from auto approve settings

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-01 22:22:53 -08:00
Saoud Rizwan b15c364a62 feat: add 'Explain Changes' feature for code review (#7765) 2025-12-01 22:02:33 -08:00
Ara 29dcc4e1e1 feat: move stealth/microwave model from recommended to free models section (#7808)
Move the stealth/microwave model entry from the recommendedModels array
to the freeModels array for better categorization of free model options.
2025-12-01 21:54:34 -08:00
Ara 126d066893 Adding Stealth model (#7764)
* Revert "Remove old models (#7118)"

This reverts commit c7c4e43322.

* Adding stealth

* Adding stealth

* Adding stealth

* Adding minor fix

* Update webview-ui/src/components/settings/OpenRouterModelPicker.tsx

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

* Apply suggestion from @abeatrix

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

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

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-12-01 21:18:43 -08:00
Ara fa3e095a79 Enable NTC by default (#7804)
* Enable NTC by default

* Enable NTC by default

* Enable NTC by default
2025-12-01 20:40:12 -08:00
Sarah Fortune 4033c83b51 Log the name of the telemetry provider(s) enabled in the extension (#7799)
Right now we are logging the provider type by logging the name of the constructor, but in the compiled code this is obfuscated so it is just some random characters.

Add a name property to the telemetry provider interface.
2025-12-01 19:22:43 -08:00
canvrno 0b7ea86e9b Added microwave family system prompt configuration (#7798) 2025-12-01 17:29:27 -08:00
reneehuang1 1d9a0b5986 add enterprise to readme (#7589)
Co-authored-by: Renee Huang <reneehuang@Renees-MacBook-Pro.local>
2025-12-01 16:23:35 -08:00
CandiedUniverse c47ffe2861 fix(hooks): Polish for UserPromptSubmit [ENG-1345] (#7656)
* fix(hooks): Trigger UserPromptSubmit hook when continuing a completed task

* fix(hooks): Make prompt formating consistent for all UserPromptSubmit entrypoints

* fix(hooks): Code reviewing w/ Cline before submitting PR for human review

* fix(hooks): Improve type safety

* fix(hooks): Add unit tests for buildUserFeedbackContent

* fix(hooks): Minor Cline code review changes

* fix(hooks): Fix test assertion technique

* fix(hooks): Simplify PR

* feat(hooks): Consolidate constants to a shared location as per PR feedback
2025-12-01 15:36:07 -08:00
mintlify[bot] e85d918816 Add CLI context window configuration docs (#7796)
* Update docs/cline-cli/overview.mdx

* Update docs/cline-cli/cli-reference.mdx

* Update docs/cline-cli/three-core-flows.mdx

* Update docs/cline-cli/overview.mdx

---------

Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2025-12-01 15:27:55 -08:00
Ara 49be10ead8 fix: move OptionsButtons outside WithCopyButton component (#7783)
Relocate OptionsButtons component to be a sibling of WithCopyButton
rather than a child. This fixes the component hierarchy for followup
and completion_result message types, ensuring proper rendering and
interaction behavior. Also adds QuoteButton support to completion_result.
2025-12-01 15:16:16 -08:00
Ara aa9573fb0a feat: add direct navigation to settings sections (#7770)
Replace delayed scroll-to-settings approach with direct section targeting.
Settings sections can now be opened directly via navigateToSettings(section)
parameter, eliminating the need for setTimeout-based scrolling workarounds.
2025-12-01 15:15:56 -08:00
Nick Baumann b913e47332 feat: add tabbed model picker with Recommended and Free tabs (#7769) 2025-12-01 14:25:27 -08:00
Zhongying Qiao 5be7a1b3cf Add support for Banner dismissal, event logging (#7642)
* feat: add banners ui, dismissal state handling and event log

* feat: add cli as ide type, clean up some code

* feat: wire up controller and UI for banners

* audit every rule check to ensure it is doing correct filtering and working locally

* seperate out frontend code

* clean up

* fix proto file

* fix quality check errors

* fix banner service tests

* feat: use json polling approach for active banners

* fix: build error

* fix ci

* fix quality check

* use BannerService.isInitialized() instead

* do not log error when banner array is empty, only when missing or not defined

* do not hash instance id
2025-12-01 15:32:51 -06:00
Toshii c2e91aa9c9 running context rewriting prior to running auto compact (#7774)
* running context rewriting prior to running auto compact

* use sample timestamp as in getNewContextMessagesAndMetadata

* clean up return var
2025-12-01 12:23:58 -08:00
Bee 68b93fcbea fix(ui): memoize highlighted text [ENG-1355] (#7786)
* fix(ui): memoize highlighted text

Optimize UserMessage and TaskHeader components by using useMemo to cache highlighted text results. This prevents unnecessary recalculations of text highlighting on every render, improving performance when text or editedText props haven't changed.

Changes:
- Add useMemo hook to UserMessage component for highlightText result
- Replace inline highlightText calls with memoized values
- Reduces redundant text processing during re-renders

* add changeset
2025-12-01 10:50:56 -08:00
Bee 0b0e8c36cb fix(ui): Add bottom padding for last message item [ENG-1354] (#7787)
* fix(ui): Add bottom padding for last message item

- Add conditional className to message wrapper div
- Apply `pb-2.5` bottom margin only when message is last in group

* add changeset
2025-12-01 10:29:54 -08:00
Juan Pablo Flores b0bd0e3974 Docs/task history recovery (#7776) 2025-12-01 09:24:40 -08:00
Ara 42b7a1e450 feat(cli): add active task check before entering follow mode (#7745)
* feat(cli): add active task check before entering follow mode

Add validation in FollowConversationUntilCompletion to check if a task
is currently running before entering follow mode. If no active task
exists, display a user-friendly message and exit gracefully instead of
waiting indefinitely.

Also includes minor whitespace formatting cleanup in related functions.

* Fix detached process conditions

* Fix detached process conditions

* Adding stealth
2025-12-01 04:57:22 -08:00
celestial-vault 14ccf33d25 fix: don't return empty array on parse failure (#7773) 2025-11-30 17:13:10 -08:00
Toshii d9a340523c add case for skipping autoCondense in truncation (#7763) 2025-11-30 16:12:27 -08:00
Saoud Rizwan 87b3e79b90 Instruct AI to prefer non-interactive commands (#7762)
Update system prompt to guide AI toward using non-interactive command variants
to avoid interrupting workflow. This includes using flags like --no-pager,
auto-confirming prompts with -y when safe, and providing input via
flags/arguments rather than stdin.
2025-11-30 00:16:18 -08:00
Saoud Rizwan 60f2e85fc7 Add find-pr-reviewers and address-pr-comments workflows (#7761)
* Add find-sme workflow for identifying subject matter experts

* Rename find-sme to find-reviewers

* Remove old find-sme.md file

* Address Copilot PR feedback: fix find syntax and add git config command

* Add address-pr-comments workflow

* Rename find-reviewers to find-pr-reviewers

* Simplify address-pr-comments workflow
2025-11-30 00:16:06 -08:00
Saoud Rizwan 1826d98019 Allow slash commands anywhere in message input (#7760)
* Allow slash commands anywhere in message input

Previously, slash commands could only be typed at the beginning of a
message. This change allows users to type slash commands anywhere in
the message, similar to how @ mentions work.

Changes:
- Update shouldShowSlashCommandsMenu() to show suggestions when slash
  is preceded by whitespace (not just at start)
- Update insertSlashCommand() to find the slash nearest to cursor
- Update extension-side parseSlashCommands() to find commands anywhere
  in tag content using a safer regex that avoids matching URLs/paths
- Update highlight layer to highlight slash commands anywhere
- Only the FIRST slash command per message is processed/highlighted
  to maintain consistency with backend behavior
- Fix backspace deletion to work for slash commands anywhere in text

* Add changeset
2025-11-30 00:07:56 -08:00
Saoud Rizwan af69b30a36 Add sticky user message header for better navigation (#7749)
* Add sticky user message header for better navigation

When users scroll down through a long conversation, a sticky header now appears showing their most recent message that has scrolled out of view. Clicking the header scrolls back to that message.

Key changes:
- New StickyUserMessage component that appears when user messages scroll past viewport
- Track scrolled-past user messages via scroll position detection in useScrollBehavior
- Add data-message-ts attributes to enable message element lookup
- Adjust TaskHeader padding for consistent alignment with sticky header
- Minor styling tweaks to UserMessage and FocusChain for visual consistency

* Fix type error: accept null for lastUserMessage prop

* Replace color-mix() with brightness filter for better compatibility

Use hover:brightness-110 instead of color-mix() for the sticky message
hover effect, as color-mix() may not be supported in all VS Code webview
contexts.

* Address Copilot review feedback for sticky user message

- Remove unused slide-down animation CSS
- Extract magic number 32 to STICKY_HEADER_HEIGHT constant
- Use cn() utility for conditional className in MessagesArea
- Add keyboard accessibility (role, tabIndex, onKeyDown) to StickyUserMessage

* Address additional Copilot review feedback

- Fix virtualized element detection: only consider missing elements as scrolled past
  if we've already found visible elements after them (fixes incorrect sticky header
  appearing when scrolling to top of long conversations)
- Rename truncatedText to messageText for accuracy (truncation happens via CSS)
2025-11-29 02:13:50 -08:00
DL Techy e62fbf6b0c Add shell option for cmd.exe to prevent double quote escaping (#7630)
* fix(terminal): Add shell option for cmd.exe to prevent double quote escaping

Added shell: true option specifically for cmd.exe to prevent double quotes
from being over escaped during command execution. This resolves Windows-specific
issues with terminal command handling while maintaining compatibility with
other shells.

* chore: Add changeset for terminal command execution fix
2025-11-28 13:02:47 -08:00
Saoud Rizwan 64254fc97a Fix API request badge causing text to wrap when hidden (#7739)
The cost badge was using opacity:0 to hide itself when there's no cost,
but still rendered "$0.0000" which took up horizontal space. This caused
the "API Request..." label to wrap to a second line unnecessarily.

Now the badge renders empty content when hidden, taking up no width
while still maintaining its height contribution to the row layout.
2025-11-28 08:05:09 -08:00
Luna c312c4aef6 Asksage usage fetch models (#7329)
* Add flagship models

* Add model fetching

* Add usage handling, tool result handling

* Update AskSageProvider.tsx

* Create eight-pants-explode.md

---------

Co-authored-by: alex-mcgraw-askSage <alex.mcgraw@asksage.ai>
2025-11-27 12:35:00 -06:00
celestial-vault fab49e810b Add fixed header to ClineRulesToggleModal (#7729)
- Add flex-shrink-0 to header section containing tabs and description text
- Keep tabs and description visible when content area scrolls
2025-11-27 12:32:17 -06:00
celestial-vault 2a20523e16 View remote rules and workflows in the editor (#7702)
* allow the user to view remote rules and workflows in the editor by creating a temp file

* add await
2025-11-27 11:37:47 -06:00
celestial-vault 06585821d1 conditionally fetch litellm models based on presence of api key and baseUrl (#7713) 2025-11-27 11:37:13 -06:00
Saoud Rizwan 9e802b11da Revert "Add Claude Code GitHub Workflow (#7717)"
This reverts commit afb77c5a8d.
2025-11-27 01:45:05 -08:00
Saoud Rizwan afb77c5a8d Add Claude Code GitHub Workflow (#7717)
* "Claude PR Assistant workflow"

* "Claude Code Review workflow"
2025-11-26 20:01:50 -08:00
Saoud Rizwan 0a4811222f fix: unblock opening a task when using cline account (#7715) 2025-11-26 18:40:51 -08:00
canvrno b4ce378e4b v3.38.3 Release Notes (#7711)
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-11-26 15:59:16 -08:00
CandiedUniverse 2f60a898af fix(hooks): Fix issue identified by linter in proto file (#7707) 2025-11-26 14:50:12 -08:00
Walter Korman 8ffd82eda3 feat(context): add context window error detection for vercel ai gateway (#7623)
feat(context): add context window error detection for vercel ai gateway #7623
2025-11-26 22:58:57 +01:00
Andrei Eternal 81276fdf85 Add os/cline ver/host info to task metadata & change Task History -> EXPORT to just open the task directory (#7706)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-11-26 13:40:42 -08:00
celestial-vault 164e11aae1 Refresh models in the LiteLLM provider component when the base URL changes (#7705) 2025-11-26 13:03:16 -08:00
Enrico Carlesso 9792f174b1 Adding Grok 4.1 and Grok Code to Cline (#7632) 2025-11-26 12:56:25 -08:00
canvrno a590200c64 Remove native tool calling feature flag (#7704) 2025-11-26 12:41:20 -08:00
Bee 297a45d73a feat(providers): add thinking level config to Vertex and Anthropic model support (#7701)
* feat(providers): add thinking level config to Vertex and Anthropic model support

- Pass thinking level configuration (plan/act mode) to Vertex provider through VertexHandlerOptions interface
- Add support for @-versioned Anthropic model IDs (e.g., claude-haiku-4-5@20251001) in cache control logic

This enables mode-specific thinking level configuration for the Vertex provider by propagating geminiPlanModeThinkingLevel and geminiActModeThinkingLevel settings based on the current mode. Also extends Anthropic model compatibility with newer versioning format.

* reasoning

* sonnet

* yield signature delta
2025-11-26 12:14:19 -08:00
Seb Duerr e84de0ab3c feat: update Cerebras models and speed (#7631) 2025-11-26 11:08:24 -08:00
Ara 515cb81439 fix(terminal): simplify cmd.exe command arguments (#7695)
Remove /s flag and extra quoting from cmd.exe shell arguments.
The previous approach with /s /c and quoted command was causing
issues with proper command execution in Windows cmd.exe.
2025-11-26 11:05:10 -08:00
celestial-vault 550428eabd LiteLLM provider dynamic model fetching (#7679)
* add dynamic model fetching for litellm provider and get rid of manual model config; also implement dynamic modelinfo lookup

* don't clear the models list when a fetch fails
2025-11-26 10:54:51 -08:00
schardosin 22c22a1cfc Fixed SAP AI Core Deployments Mode (#7675)
* fixed sap ai core deployments not working

* isolated chunk to string in a function

* added changeset
2025-11-26 09:26:06 -06:00
Dominic Cooney 8202479cec fix: Add proxy rules, proxy support for McpHub & others (#7659) 2025-11-26 02:06:56 -08:00
Dominic Cooney bcbaa4518d docs: Document proxy settings. (#7637)
* docs: Document proxy settings.

* Update docs/troubleshooting/networking-and-proxies.mdx

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-11-26 01:30:28 -08:00
canvrno 9d799643ba npm audit fix docs + webview (#7687) 2025-11-26 00:49:40 -08:00
canvrno 6271c5da37 Remind models of new_task tool parameters when deep_planning is invoked (#7685)
* Remind models of new_task tool parameters when deep_planning is invoked

* cleanup
2025-11-25 21:59:53 -08:00
Auroter 89aeb3db3d feat(telemetry): Add OpenTelemetry metrics infrastructure (#7211)
* feat(telemetry): Add OpenTelemetry metrics infrastructure

Implement OpenTelemetry metrics support (counters, histograms, gauges) while maintaining backward compatibility with PostHog dashboards.

Changes:
- Updated ITelemetryProvider interface with recordCounter, recordHistogram, and recordGauge methods
- Implemented full OpenTelemetry metrics in OpenTelemetryTelemetryProvider with lazy instrument creation
- Added stub implementations in PostHogTelemetryProvider for backward compatibility
- Updated NoOpTelemetryProvider with metric method stubs
- Added comprehensive documentation in METRICS_IMPLEMENTATION_SUMMARY.md

Architecture:
- Dual instrumentation: existing PostHog events remain unchanged
- OpenTelemetry gets proper metrics for quantitative analysis
- Each provider handles metrics appropriately for its platform

Next steps:
- Add helper methods to TelemetryService for recording metrics with standard attributes
- Update high-priority capture methods (tokens, API performance) to call metric recording
- Validate with OpenTelemetry collector setup

* refactor(telemetry): add structured metrics and improve error handling

- Add userId and userEmail tracking to TelemetryService
- Implement helper methods (recordCounter, recordHistogram, recordGauge) with standardized attributes
- Add structured metrics for turns, tokens, costs, cache usage, and API performance
- Remove default case from TelemetryProviderFactory switch to enable exhaustive type checking
- Improve error handling by moving unsupported provider type logging outside switch
- Ensure all metric recordings include standard attributes (userId, email, metadata)

This refactoring enables better observability by recording key metrics (counters, histograms, gauges) across all telemetry providers while maintaining consistent attribute propagation and error isolation.

* fix: add logs back in to no-op provider

* fix: use Logger instead of console

* fix: remove unreachable code

* fix: satisfy compiler for config.type

* fix: remove metrics implementation summary

* chore: update telemetry to include mode in conversation turn events

- Added mode parameter to captureConversationTurnEvent in TelemetryService.
- Updated related telemetry metrics to include mode for better tracking.
- Adjusted tests to verify mode is correctly captured in telemetry events.

* fix: call signatures from merge detritus

* feat(telemetry): add optional description parameter to metric recording methods

Add optional `description` parameter to `recordCounter`, `recordHistogram`,
and `recordGauge` methods across the telemetry service layer. This enables
providers to include descriptive metadata when recording metrics.

Changes:
- Updated ITelemetryProvider interface methods to accept description parameter
- Modified TelemetryService private methods to pass description to providers
- Updated NoOpTelemetryProvider stub implementation
- Enhanced FakeProvider test implementation to capture descriptions
- Updated test assertions to verify description parameter handling

This change maintains backward compatibility as the description parameter
is optional.

* feat(telemetry): update recordGauge method to handle null values for metric retirement

- Modified the `recordGauge` method in `ITelemetryProvider` and its implementations to accept `null` as a valid value, allowing for the retirement of gauge series.
- Updated the `TelemetryService` to ensure proper cleanup of gauge entries when the series ends.
- Enhanced the `FakeProvider` test to validate the new behavior of gauge recording and retirement.
- Adjusted related tests to confirm that previous series are retired correctly when new values are recorded.

This change improves the management of gauge metrics, preventing stale entries and ensuring accurate telemetry data.

* refactor(telemetry): remove user email from telemetry service and related tests

- Removed the user email property from the TelemetryService and its associated methods, streamlining user attribute handling.
- Updated tests to reflect the removal of email, ensuring that metrics and events no longer rely on this attribute.
- Adjusted documentation in ITelemetryProvider to clarify the attributes used in metric recording.

This change enhances data privacy and simplifies the telemetry data model.

* feat(telemetry): enhance task metrics tracking with new counters and histograms

- Introduced new maps to track task turn counts, tool call counts, and error counts.
- Added methods to increment task counters and reset aggregates for better metric management.
- Updated existing telemetry capture methods to utilize the new counters and record histograms for task-related metrics.
- Enhanced tests to validate the new histogram entries for task turns, tool calls, and errors.

This change improves the granularity of telemetry data, allowing for more detailed analysis of task performance and error rates.

* refactor(telemetry): improve token usage handling in TelemetryService

- Updated conditions for recording cache write/read tokens and total cost to check for finite values, ensuring proper handling of undefined or null values.
- Introduced default values for token counts and total cost to prevent potential errors in metric recording.
- Enhanced readability by using descriptive variable names for token values.

This change enhances the robustness of telemetry data collection by ensuring that only valid numeric values are recorded.

* feat(telemetry): centralize metric definitions in TelemetryService

- Introduced a static METRICS object in TelemetryService to define all metric names, improving maintainability and readability.
- Updated existing telemetry recording methods to utilize the new METRICS constants, ensuring consistency across metric names.
- Enhanced tests to validate the use of METRICS constants in assertions for counters and histograms.

This change streamlines metric management and reduces the risk of errors due to hardcoded strings.

* refactor(telemetry): improve gauge observation handling in OpenTelemetryTelemetryProvider

- Replaced direct access to gauge values with a snapshot method to enhance data integrity during observable gauge callbacks.
- Introduced a new `snapshotGaugeSeries` method to encapsulate the logic for retrieving gauge data, improving code readability and maintainability.
- Updated the observable gauge callback to utilize the new snapshot method, ensuring that the latest values are accurately observed.

This change streamlines the process of observing gauge metrics, reducing potential errors and improving the overall telemetry data collection.

* refactor(telemetry): add required parameter to metric recording methods

- Updated `recordCounter`, `recordHistogram`, and `recordGauge` methods across the telemetry service and providers to include an optional `required` parameter, allowing for more flexible metric recording.
- Adjusted implementations in `NoOpTelemetryProvider`, `OpenTelemetryTelemetryProvider`, `PostHogTelemetryProvider`, and `FakeProvider` to handle the new parameter.
- Enhanced tests to validate the behavior of the `required` parameter in metric recording.

This change improves the control over metric recording conditions, enhancing the telemetry data collection process.

* fixed testing system

---------

Co-authored-by: NightTrek <Daniels@dual4t.com>
Co-authored-by: Daniel Steigman <35793213+NightTrek@users.noreply.github.com>
2025-11-25 18:56:30 -08:00
Saoud Rizwan 0caeea1b37 Enhance text overflow handling in TaskHeader component (#7674) 2025-11-25 14:23:39 -08:00
Saoud Rizwan 852a7c9198 Remove TaskTimeline from TaskHeader (#7670) 2025-11-25 13:09:15 -08:00
canvrno c4ef472aeb npm audit fix for glob package vulnerability (#7661) 2025-11-25 10:59:26 -08:00
Bee e22c457d19 fix: improve error property extraction from nested response objects (#7669)
- Remove intermediate response extraction to preserve full error structure
- Add fallback to error.response.message and error.response.status
- Stringify error object in logException for better console output
2025-11-25 10:58:55 -08:00
Juan Pablo Flores c15287ace0 Creates and Refactor Enterprise Docs (#7365)
* Refactor enterprise documentation: reorganize member management and roles, add AWS Bedrock configuration guides, and remove outdated security concerns section.

* Update docs/enterprise-solutions/provider-remote-config/aws-bedrock/admin-configuration.mdx

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: reneehuang1 <100229782+reneehuang1@users.noreply.github.com>
2025-11-24 16:49:36 -08:00
Bee d30f54a89c fix: add a refresh guard flag for auth (#7654)
* add a refresh guard flag (

* Implemented atomic refresh handling

Replaced the boolean flag with a Promise

- When a refresh is needed, the code first checks if _refreshPromise exists
- If it exists, concurrent calls wait for the same Promise to complete and then return the refreshed token
- If it doesn't exist, a new Promise is created and stored in _refreshPromise
- The Promise is cleared in the finally block after completion
2025-11-24 15:35:56 -08:00
Bee 56b913d951 fix: feature-flags cache persistence during auth transitions (#7652)
* fix: feature-flags cache persistence during auth transitions

Restructured feature flags polling and cache management to prevent empty cache states during authentication transitions:

- Move cache timestamp update to after successful population in poll() method to ensure cache validity reflects actual data availability
- Remove cache.clear() from reset() method to preserve existing flag values until new data is fetched
- Split polling logic in AuthService to explicitly handle authenticated vs unauthenticated states
- Poll feature flags immediately after reset for authenticated users to ensure cache is populated

This prevents temporary cache misses when users log in/out while maintaining cache freshness guarantees.

* remove reset method and usage in auth flow

Remove the FeatureFlagsService.reset() method and its call during user
authentication. The feature flags polling mechanism is sufficient to
keep flags up-to-date for authenticated users without requiring an
explicit cache reset on auth state changes.

Changes:
- Remove reset() method from FeatureFlagsService
- Remove featureFlagsService.reset() call from AuthService after user identification
- Rely solely on poll() to manage feature flags cache updates
2025-11-24 15:35:45 -08:00
Saoud Rizwan 55a30e0ffa Add support for opus 4.5 global endpoint in bedrock (#7653) 2025-11-24 14:49:23 -08:00
Saoud Rizwan a017f3dfd3 Add Claude Opus 4.5 (#7648) 2025-11-24 13:33:31 -08:00
Saoud Rizwan 41ebe7c9d1 Make npm installation less strict about package-lock needing to be in sync 2025-11-24 12:26:44 -08:00
Bee 4d11f0d2fa feat: implement edit tools conversion adapter [CLIENTS-23] (#7601)
* feat: implement edit tools conversion adapter

Add logic to transform `apply_patch` tool calls into specific `write_to_file` and `replace_in_file` operations. This adapter bridges the gap between patch-based model outputs and atomic file system tools.

- Implement `transformToolCallMessages` to parse patch content:
  - Converts "Add File" patches to `write_to_file`.
  - Converts "Update File" patches to `replace_in_file` with search/replace blocks.
- Add logic to reconstruct tool result messages to match the expected V4A patch format (including `<final_file_content>`).
- Add comprehensive unit tests in `src/core/api/adapters/__tests__/adapters.test.ts` covering add/update operations, multiple tool blocks, and result reconstruction.

* fix typos

* typo
2025-11-23 13:41:18 -05:00
Bee 4baa2474eb fix: ensure reasoning signature is accessible at top level (#7615)
* fix: ensure reasoning signature is accessible at top level

Extract signature from nested summary object and promote it to the top-level
reasoning structure when not already present. This ensures consistent access
to the signature field across all providers, regardless of where it's initially
provided in the reasoning details. The fomatter that each provider runs would then reconstruct the messages in the format they need.

* clean up
2025-11-21 16:36:39 -08:00
Juan Pablo Flores c94e2cf913 Upgrade/workflows docs (#7593)
* feat(workflows): restructure and enhance workflows documentation with best practices and quick start guide

* feat(workflows): enhance documentation with modular workflow practices and new PR review workflow example

* feat(workflows): improve clarity in workflow creation instructions

* Update docs/features/slash-commands/workflows/best-practices.mdx

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-21 15:45:37 -08:00
Bee dbedc6cfaa chore: clean up prompts and fix model family identifier (#7614)
- Simplified plan_mode_respond instruction text by removing redundant explanations and usage field
- Fixed incorrect MODEL_FAMILY references in native-gpt-5-1 config (was using NATIVE_GPT_5 instead of NATIVE_GPT_5_1)
- Added call_id to reasoning handler output for tracking and OpenAI Response API (unreleased)

The prompt simplification makes the response parameter instruction more concise while maintaining clarity. The model family correction ensures the GPT-5-1 variant uses the correct identifier throughout.
2025-11-21 14:25:18 -08:00
Sarah Fortune 2ac568e649 Add a setting to disable the Add Remote Servers feature in the extension. (#7612)
* Add a setting to disable the `Add Remote Servers` feature in the extension.

* Add setting to unit test

* Rename setting
2025-11-21 12:36:47 -08:00
tjandy98 b13d0e75ea Add support for Perplexity sonar and sonar-pro models to SAP AI Core Provider (#7605)
* Add perplexity models

* Add perplexity models to sap aicore

* Update api.ts

* Update sapaicore.ts

* add changeset

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

* update maxTokens and contextWindow

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

---------

Signed-off-by: tjandy98 <3953059+tjandy98@users.noreply.github.com>
2025-11-21 09:42:39 -08:00
Bee 4d395deefd fix: improve error handling and ui for auth failures (#7591) 2025-11-21 08:56:28 -08:00
CandiedUniverse 834a5b1df2 fix(compaction): Use consistent icon for compaction (#7598) 2025-11-21 05:41:58 -08:00
CandiedUniverse 3089233298 feat(hooks): Implement Hooks tab in Rules & Workflows modal [ENG-1325] (#7547)
* feat(hooks): Add hooks tab to Rules & Workflows modal

* feat(hooks): Implement hooks tab content in Rules & Workflows modal

* feat(hooks): Enable creating new hooks in modal from dropdown selection list

* feat(hooks): Change hook template scripts to use bash

* feat(hooks): Windows not yet supported for hooks, so grey-out toggle on windows

* feat(hooks): Improvements to PR as per Cline reviewing the changes before code review

* feat(hooks): Implement tests for hook management (what the UI does under the hood)

* feat(hooks): Changes as per code review feedback from humans
2025-11-20 19:47:39 -08:00
Tomás Barreiro f2b7347a5c Add ApiKeys to the remote config (#7595) 2025-11-20 18:59:49 -08:00
Bee 04bfef75cf feat: replace robot icon with custom cline-bot icon font (#7594)
- Add cline-bot icon font assets (SVG, TTF, WOFF) generated from IcoMoon
- Register custom icon font in VS Code extension manifest
- Replace PNG-based command icon with font-based cline-icon
- Update terminal icon references from generic "robot" to "cline-icon"

This provides a consistent branded icon across the extension and improves visual identity by using the official Cline bot logo instead of the generic robot icon from codicon that was updated by VS Code.
2025-11-20 18:12:44 -08:00
Bee 716e8f236b feat(storybook): add OnboardingView story (#7578)
* chore: clear onboarding models on deactivate

* feat(storybook): add OnboardingView story

- Added OnboardingView component to Storybook with new story
- Integrated onboarding models from shared constants
- Updated MockApp to conditionally render OnboardingView based on onboardingModels state
- Renamed WelcomeScreen story to Welcome for clarity
- Added interaction tests for onboarding buttons (Get Started/Use your own API key)
- Configured onboarding models in mock state to support new story

This enables visual testing and documentation of the user onboarding flow within Storybook.

* Update Storybook missing vscode theme color

* Update task name

* typo
2025-11-20 17:21:28 -08:00
Alex Ker f2ddab71f1 updated baseten docs to include kimi instructions and updated location (#7588)
Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-11-20 16:04:46 -08:00
canvrno 0b56a45a65 Add thinking level setting for Gemini 3.0 Pro (#7539)
* Added thinking level setting for Gemini 3.0 Pro

* changset
2025-11-20 10:48:31 -08:00
Bee d6ebd2438a fix: parse mentions/commands in tool results and before auto-condense (#7575)
* fix: parse mentions/commands in tool results and before auto-condense

**Changes:**
- Move `loadContext` call before auto-condense check to ensure slash commands and mentions are parsed before context condensing occurs
- Extract parsing logic into reusable `parseInputBlock` helper function
- Add recursive handling for `tool_result` blocks containing nested content arrays
- Remove duplicate `loadContext` calls from conditional branches

**Why:**
Previously, mentions (@file.ts) and slash commands in tool results (like attempt_completion feedback) were not expanded because parsing only handled top-level text blocks. Tool handlers return content arrays within tool_result blocks per Anthropic's API format.

Additionally, `loadContext` was called after the auto-condense check, meaning if condensing was triggered, user commands wouldn't be parsed and could be lost during summarization.

**Result:**
- All user feedback with @mentions or /commands is properly expanded regardless of nesting level
- Commands are detected before context management operations
- Cleaner code flow with single parsing point

* preserve array structure in backward-compatible tool results

When using the backward-compatible "cline" tool use ID, spread array
content directly into userMessageContent instead of wrapping it in
createToolResultBlock. This prevents array content from being
JSON.stringify'd and losing its block structure (e.g., tool_result
blocks with array content).

Previously, array content like [{type: "tool_result", content: [...]}]
was being converted to {type: "text", text: "[...]"}, which prevented
loadContext from properly parsing tool_result blocks.

* clean up

* fix(task): preserve block structure when processing string content

Instead of returning only the processed content, now properly updates the
block.content property with the processed text wrapped in an array and
returns the complete block object. This ensures the block structure is
maintained throughout the processing pipeline rather than being discarded.
2025-11-20 10:38:27 -08:00
Alex Ker 4c07c7e5c5 added Kimi K2 Thinking to static models list and set as default (#7511)
* kimik2 thinking added to static model dropdown

* numerical separators

* don't set kimi k2 thinking as default

---------

Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-11-20 00:58:19 -08:00
Bee ab66a5fd93 fix: disable switch for required rules to prevent toggling (#7580)
Update RuleRow component to use isDisabled for both the switch disabled state and tooltip visibility, ensuring required rules cannot be toggled off by users. Previously used separate logic that may have miscalibrated disabling for required remote rules.
2025-11-19 23:25:30 -08:00
celestial-vault bd1d6159fc automatically derive openrouter modelinfo based on modelId when calling getModel() (#7568) 2025-11-19 21:16:48 -08:00
Bee 7f2d28716f chore: clear onboarding models on deactivate (#7569) 2025-11-19 18:01:58 -08:00
Toshii 653727db2a updating parser for webfetch to handle current format (#7571) 2025-11-19 17:44:01 -08:00
Bee d3c2f1878d fix(api): attach reasoning details to tool blocks (#7567)
* fix: Centralize reasoning details within thinking blocks

This commit refactors how reasoning details are managed across the system, integrating them directly into `ClineAssistantThinkingBlock` to improve consistency and reduce complexity.

Previously, `reasoning_details` were often explicitly deleted or inconsistently handled, leading to their loss or difficulty in tracking. This change ensures that reasoning details are always associated with their corresponding thinking blocks.

Key changes include:
- `StreamResponseHandler`: The `ReasoningHandler`'s `getCurrentReasoning` method now directly returns a `ClineAssistantThinkingBlock` which encapsulates the reasoning content and its `summary` (formerly `details`). The separate `getThinkingBlock` method has been removed.
- `convertToOpenAiMessages`: Explicit deletion of `part.reasoning_details` for `thinking` parts is replaced by setting it to `undefined` with a comment, indicating that these details are now expected to be part of the thinking block in the stream.
- `Task`: Simplified streaming logic by directly consuming the `ClineAssistantThinkingBlock` from `reasonsHandler.getCurrentReasoning()`. Redundant temporary variables for reasoning content and details have been removed.

This refactoring centralizes the management of reasoning details, providing a more robust and streamlined approach to handling assistant thinking processes.

* fix(api): attach reasoning details to tool blocks and improve logging

Updates validity of reasoning details within tool blocks and enhances debugging visibility.

- Modify `StreamResponseHandler` to append reasoning details/summary to finalized tool use blocks.
- Update `convertToOpenAiMessages` to extract and aggregate `reasoning_details` from tool messages instead of discarding them.
- Add `Logger.debug` calls in `ClineHandler` and OpenAI transformation for better observability of message chunks and conversion.
- Remove redundant `continue` statements in `ClineHandler` stream processing loop.

* clean up

* remove Logger
2025-11-19 17:28:20 -08:00
CellenLee ba92be9401 feat: add kimi-k2-thinking and kimi-k2-thinking-turbo (#7386) 2025-11-19 15:49:46 -08:00
Bee 66eb5a62ba feat: Enable native tool calling for Baseten and Kimi K2 models (#7562)
* feat: Enable native tool calling for Baseten and Kimi K2 models

Introduces native tool calling capabilities for Baseten and Kimi K2 models, aligning with the OpenAI Chat Completions API specification for function calling.

This change includes:
- Updating the `ApiHandler` interface and `createMessage` methods to accept an optional `tools` parameter.
- Implementing a `ToolCallProcessor` to incrementally build and emit tool call payloads from streaming deltas.
- Modifying the `BasetenHandler` to pass `tools` to the Baseten API and process `tool_calls` deltas.
- Updating the `ClineHandler` to process `tool_calls` deltas received from the Kimi K2 model.
- Enhancing the `CompletionStreamChunk` to include `ToolCall` and `ToolCallDelta` types.
- Marking Baseten and Kimi K2 models in their respective definitions with `native_tool_calling: true`.
- Adjustments to streaming logic in handlers to allow multiple delta types (content, tool_calls, reasoning) to be processed from a single chunk.

* add changeset

* clean up
2025-11-19 15:37:10 -08:00
Bee 499ee22b3b fix(task): update UI with final usage after stream completion (#7552)
Ensure the UI displays accurate token usage and costs by updating the API request message when the stream completes. This commit adds a call to updateApiReqMsg followed by saving messages and posting state to the webview, which occurs before finalizing tool calls. This ensures users see the final usage statistics (input/output tokens, cache tokens, and total cost) reflected in the interface immediately after stream processing.
2025-11-19 02:54:31 -08:00
CandiedUniverse 7abeae5019 feat(hooks): Implement TaskComplete hook (#7510) 2025-11-18 23:43:57 -08:00
Bee accf47cb52 fix: await presentAssistantMessage calls to prevent race condition (#7548)
* fix: await presentAssistantMessage calls to prevent race condition

Add await to all presentAssistantMessage() calls to ensure proper
sequencing of message presentation. Previously, the method was called
without awaiting, which could cause race conditions when streaming
tool use content blocks. This ensures that message presentation
completes before continuing execution, particularly important when
handling multiple content blocks or tool interactions.

* revert pr change
2025-11-18 17:48:15 -08:00
Bee 556d3e6f79 fix: rules modal positioning (#7546)
Add overflow-y-auto to the modal container to allow scrolling when content exceeds viewport height. This fixes an issue where modal content would be inaccessible on smaller screens or with large rule sets.
2025-11-18 16:23:48 -08:00
Bee 9e35048db2 feat: add support for Responses API for openai-native provider [ENG-1227] [ENG-1311] (#7504)
* feat: add support for Responses API for openai-native provider [ENG-1227]

- Upgrade openai dependency to v6.9.0 to use the Responses API
- Implement internal handling for reasoning/thinking and redacted output
- Align Anthropic handler message types with the latest SDK interfaces
- Clean up obsolete tooling imports related to tool-use handling
- Enable newer OpenAI capabilities while keeping provider APIs consistent

* Add openai_native_response_api feature flag

* clean up

* clean up 2

* add back gpt-5.1 models

* use call_id
2025-11-18 16:20:45 -08:00
Ara 9b0f2b82ef v3.38.1 Release Notes (#7544) 2025-11-18 14:32:41 -08:00
Bee c2c23054b9 fix: Remove 'signature' from sanitizeAnthropicContentBlock (#7543)
* fix: Remove 'signature' from sanitizeAnthropicContentBlock

Remove 'signature' from sanitizeAnthropicContentBlock as the signature field is required by Anthropic when thinking is enabled.

* Add Changeset

* empty commit

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-11-18 14:10:34 -08:00
Bee 3baaa5c8b4 refactor: replace custom UI toggle with shadcn Switch component (#7308)
* refactor(webview-ui): replace custom UI toggle with shadcn Switch component

- Add @radix-ui/react-switch dependency (v1.2.6) https://ui.shadcn.com/docs/components/switch
- Refactor ClineRulesToggleModal to use Radix Switch instead of VSCode buttons
- Improve button styling with reduced padding and adjusted icon sizes
- Enhance form layout with conditional rendering based on expansion state
- Update input field styling with better focus states and border handling

This change provides a more consistent UI experience by leveraging Radix UI's
accessible Switch component while maintaining the same functionality.

* clean up

* clean up

* update switch color

* adjust

* revert unrelated changes

* size

* toggle

* Update webview-ui/src/components/cline-rules/RuleRow.tsx

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-11-18 12:39:50 -08:00
github-actions[bot] abafcc7290 Changeset version bump (#7473)
* v3.38.0 Release Notes

- Gemini 3 Pro Preview model
- AquaVoice Avalon model for voice-to-text dictation

- Automatic context truncation when AWS Bedrock token usage rate limits are exceeded
- SAP AI SDK JS packages upgraded to latest major version
- SAP provider OrchestrationClient now matches OrchestrationModuleConfig type and no longer uses invalid promptTemplating property
- Removed new_task tool from system prompts, updated slash command prompts, and added helper function for native tool calling validation

* Update CHANGELOG.md

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-11-18 12:15:10 -08:00
Bee d82aa0add9 feat: add Gemini 3.0 Pro to onboarding list (#7542)
- Add `google/gemini-3-pro-preview` to `CLINE_ONBOARDING_MODELS`.
- Configure model details including context window, pricing, and capabilities (images, prompt cache).
- Enable users to select the new Gemini 3.0 Pro model during setup.
2025-11-18 11:49:08 -08:00
Bee abe4721a0b feat: add thought signature support for Gemini SDK [ENG-1320] (#7536)
* feat: add thought signature support for Gemini SDK

Update @google/genai dependency from v1.15.0 to v1.30.0, including nested deps like google-auth-library. Enhance API interfaces with JSDoc comments and new fields such as signature, id, and redacted_data in ApiStreamThinkingChunk to support thought signatures from Gemini SDK as requested. This improves integration with Gemini's reasoning capabilities and ensures compatibility with updated SDK features.

* add changeset

* meaning val check

* typo

* either

* Do not use think budget with gemini-3
2025-11-18 10:57:53 -08:00
Bee 60d55b69a8 fix: Only update reasoning UI when content changes (#7540)
This commit addresses two issues related to how reasoning messages are processed and displayed.

Previously, the `say` function was called on every iteration of the reasoning stream loop, even if the current chunk contained no new reasoning content. This caused unnecessary UI updates and could lead to errors if a task was cancelled mid-stream. The `say` call is now conditional, only executing when new `chunk.reasoning` is available.

Additionally, the final reasoning block was only appended to the assistant's message history if a signature was present. This meant reasoning could be lost from the UI if the task was cancelled before a signature was generated. The logic is now updated to append the reasoning block if either a message or a signature exists.
2025-11-18 10:57:11 -08:00
Ara d18e0271d3 Fix cancellation for background terminal commands (#7521)
* refactor(task): improve background command cancellation with better error handling

Enhance the cancelBackgroundCommand method with:
- Consolidated early return conditions for cleaner code
- Proper async/await for process termination
- Comprehensive error handling with try-catch blocks for each operation
- Improved logging for termination success/failure scenarios
- Updated cancellation notification message
- Use finally block to ensure notification is always sent

Improve StandaloneTerminalProcess.terminate() with:
- Better guard clauses and early returns
- Enhanced error handling for SIGTERM and SIGKILL operations
- More detailed logging for graceful vs forced termination
- Fallback to SIGKILL if SIGTERM fails immediately

Fix critical issue where terminate() method was not accessible on the merged promise object returned by executeCommand, preventing Task.cancelBackgroundCommand() from properly killing background processes.

* Fix: add cancel ui

* Fix: add cancel ui

* Fix: add cancel ui

* Fix: add cancel ui
2025-11-18 10:41:58 -08:00
Ara af71f9da90 fix: resolve double quote escaping in Windows cmd.exe for Background Exec mode (#7523)
Fixes #7470

When Terminal Execution Mode is set to "Background Exec", commands with
double quotes were being incorrectly escaped on Windows cmd.exe, causing
commands like `echo "\""` or `type "test.txt"` to fail.

The issue was that cmd.exe requires the /s flag and outer quotes when
passing commands with special characters via spawn(). Changed from
`["/c", command]` to `["/s", "/c", `"${command}"`]` for cmd.exe only.

This is a minimal Windows-specific fix that:
- Only affects Windows cmd.exe (PowerShell and Unix shells unchanged)
- Uses standard Windows cmd.exe syntax for proper quote handling
- No changes to process execution flow or behavior
2025-11-18 10:17:37 -08:00
canvrno 2a1c8826aa Add Gemini 3.0 to featuredModels (#7537) 2025-11-18 10:13:06 -08:00
Ara 9a54f2d246 fix(auth): enable provider persistence when applying model changes (#7530)
- Change `UpdateProviderPartial` persist flag from false to true in `applyModelChange`
- Add missing newline at end of state.proto file

This ensures that model changes are properly persisted to storage when users
update their provider configuration through the wizard.
2025-11-18 10:05:01 -08:00
canvrno d928d58a40 Feat: Gemini 3.0 prompt/tool changes (#7532)
* Enhanced Gemini 3.0 support in Cline

* Updated Gemini 3.0 snapshots

* Update src/utils/model-utils.ts

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

* Updated system prompt

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

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

* Pricing change, narrowed native tool spec to just gemini 3 on vertex

* Update src/core/prompts/system-prompt/registry/ClineToolSet.ts

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

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-11-18 10:02:43 -08:00
canvrno 31859b5fda Add Gemini 3.0 to Gemini provider (#7533)
* Added Gemini 3.0 to Gemnini provider

* Add thinking option for Gemini 3.0
2025-11-18 09:20:19 -08:00
Ara 0d5d89e8c7 feat(bedrock): add context window error detection and retry handling (#7515)
* feat(bedrock): add context window error detection and retry handling

Add proper context window error detection for AWS Bedrock provider to enable automatic retry with context truncation. Previously, context window errors were yielded as error text instead of being thrown, preventing the retry mechanism from handling them.

Changes:
- Detect ValidationException errors matching context window patterns in both Converse API and stream processing
- Throw context window errors instead of yielding them as text to trigger retry logic
- Add checkIsBedrockContextWindowError() function to identify Bedrock-specific context limit errors
- Support multiple error message patterns (input too long, context exceed, maximum tokens, etc.)
- Handle nested error structures from Vercel AI SDK and AWS SDK

This enables automatic context management when Bedrock models hit token limits, improving reliability and user experience.

* Fix: raise errors
2025-11-18 09:09:47 -08:00
Bee af34451eec fix: remove h-full from TaskTimeline (#7525) 2025-11-18 02:10:35 -08:00
Bee 027a4f6386 fix: remove automatic native tool calls inference (#7522)
Remove automatic enablement of native tool calls for next-gen models and providers. The feature should be controlled exclusively by explicit user settings (feature flag and global state) rather than being automatically inferred based on the model type during experimental state.

Changes:
- Removed `isNextGenModelProvider` import (no longer needed)
- Eliminated `inferredNativeToolCalls` logic that auto-enabled the feature for next-gen models
- Simplified `enableNativeToolCalls` to only check explicit feature flag and global state settings
- Makes behavior more predictable and user-controlled
2025-11-18 00:49:36 -08:00
Bee 49642882c5 fix: ensure tool arguments are streamed during native tool calling [ENG-1305] (#7508)
* fix: ensure tool arguments are streamed during file operations

- Update userMessageContentReady condition to include streaming tool arguments, not just new content blocks
- Add null check for input object in tool-use-handler to prevent errors
- Improve partial JSON parsing with better fallback handling
- Replace console.log with Logger.debug for tool call chunks
- Add clarifying comments for lock mechanism and streaming behavior

This fixes an issue where new file content was not being properly streamed to tools during write operations, causing the UI to stop updating while tool arguments were being received.

* Add changeset

* typo

* fix(task): reset content index to execute tool blocks during streaming

Reset the currentStreamingContentIndex to the first tool block position
when tool blocks are present in the assistant message. This ensures that
tool blocks are properly executed instead of being skipped when the index
advances past them or goes out of bounds during content streaming.

Previously, the index could advance beyond tool blocks, causing them to
remain unexecuted. Now, when tool blocks are detected, the index is
explicitly set to textBlocks.length (the start of tool blocks) and
userMessageContentReady is set to false to trigger execution.

* fix(task): reset stream index to enable tool block execution

Reset currentStreamingContentIndex to the first tool block position when
tool blocks are present in the assistant message. This ensures that
presentAssistantMessage processes tool blocks instead of text blocks
during streaming, allowing tool blocks to be executed properly while
streaming is in progress.

The index is set to textBlocks.length, which points to where tool blocks
start in the content array, enabling correct sequential processing of
tools during the streaming phase.

* fix(streaming): improve tool execution flow and prevent control flow fall-through

- Add continue statements after yielding content in cline provider to prevent unintended fall-through behavior
- Mark all streamed tool uses as partial to ensure proper state tracking
- Allow complete tool blocks to bypass presentation lock for immediate execution during streaming
- Simplify userMessageContentReady reset logic and remove redundant tool_call check

These changes improve tool execution responsiveness by allowing completed tools to execute without waiting for the presentation lock, while ensuring proper control flow and state management throughout the streaming process.

* revert WriteToFileToolHandler
2025-11-17 23:50:04 -08:00
Bee 21ed6bc432 fix: do not add MCP tool with invalid names as native tools (#7516)
* fix: do not add MCP tool with invalid names as native tools

- Filter out MCP tools with names >= 64 characters to avoid provider API rejection
- Reduce nanoid length from default (21) to 5 characters for server UIDs

Provider APIs reject tool registration when tool names exceed 64 characters.
This change prevents registration errors by skipping tools with long names
and generating shorter UIDs to minimize the constructed name length
(uid + identifier + tool name).

* Add Changeset

* Update src/services/mcp/McpHub.ts

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

* Update src/core/prompts/system-prompt/registry/ClineToolSet.ts

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-17 23:24:17 -08:00
Bee da2689f885 fix: correct TaskTimeline height (#7520)
* fix: correct TaskTimeline height

- Remove TIMELINE_HEIGHT constant in favor of h-full and h-4 utilities
- Replace inline styles with Tailwind classes for better maintainability
- Change timeline blocks from rounded-xs to rounded-full for consistency
- Fix timeline display being cut off due to incorrect height constraints

This refactor resolves the visual layout issue where timeline items were
truncated while improving code consistency by leveraging Tailwind's
utility-first approach throughout the component.

* add changeset
2025-11-17 23:05:09 -08:00
CandiedUniverse 5049326f02 fix(hooks): Fix two minor cancel-resume issues (#7502)
* fix(hooks): Fix cancel: true returned by TaskResume

* fix(hooks): Prevent TaskCancel from being triggered twice by TaskStart cancel and by TaskResume cancel scenarios
2025-11-17 14:44:16 -08:00
Ara b02ce46a57 Fix: Vercel provider token usage (#7481) 2025-11-17 14:15:32 -08:00
Saoud Rizwan de974737c8 fix: improve layout and styling in OnboardingView component for small width viewport (#7391) 2025-11-17 13:35:13 -08:00
Bee d072156e9a fix(account): memoize credits history table component (#7439)
Use React.memo to wrap CreditsHistoryTable, reducing unnecessary re-renders
when props are unchanged and improving performance of the account view that makes it looks like it glinches.
2025-11-17 11:36:19 -08:00
celestial-vault 4939309a09 fix openrouter defaulting modelId when modelInfo is not present (#7482) 2025-11-15 13:50:29 -08:00
CandiedUniverse 1a07ca7906 fix(hooks): Honor '"cancel": true' in hook JSON output (#7479) 2025-11-14 20:37:16 -08:00
Bee c1eefbad3f refactor(api): unify provider message type with ClineStorageMessage (#7478)
* refactor: replace Anthropic MessageParam with ClineStorageMessage type

Replace Anthropic SDK's MessageParam type with the new ClineStorageMessage type across API providers and tests in the effort of storing api messages in a type safe environment that we can expand from and avoid adding undocumented properties to Anthropc Message type that are not visible to the downstream services.

This change:

- Removes dependency on @anthropic-ai/sdk types in multiple providers
- Introduces ClineStorageMessage from shared messages module
- Updates method signatures in Dify, OpenAI, LiteLLM, and ClaudeCode handlers
- Updates corresponding test files to use the new type

This decouples the codebase from Anthropic-specific types and standardizes message handling using an internal storage format across all providers that  improves type-safety, preparing for the properties added by the Response API use.

As ClineStorageMessage is an extension of the Anthropic Message type, everything should work the same with no breaking changes. Green CI is expected.

* clean up
2025-11-14 20:24:56 -08:00
canvrno 1bfdce9b84 Remove new_task from system prompts (#7350)
* Removed new_task from system prompts, updated slash command prompt, added helper function for native tool calling checks

* Update src/core/prompts/system-prompt/registry/PromptBuilder.ts

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

* Update src/core/task/index.ts

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

* Updates with requested changes for PR #7350

* Updated package-lock.json

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-11-14 17:57:47 -08:00
canvrno b002cdacdb Maint: package updates (#7477)
* maint: package updates

* Updated download-ripgrep script for compatability with new tar dependency
2025-11-14 16:09:03 -08:00
CandiedUniverse cf4005b25e fix(hooks): Reorder the UI elements so that PreToolUse appears above tool (#7449)
* fix(hooks): Reorder the UI elements so that PreToolUse appears above tool

* fix(hooks): Prevent PreToolUse hook from migrating down the screen

* fix(hooks): PreToolUse reordering should apply to 'tool', 'command', 'use_mcp_server', and 'browser_action_launch'  message types
2025-11-14 15:40:23 -08:00
Bee 1494d145d5 feat: support feature flag payload & remote dynamic onboarding model list (#7454)
* feat: support feature flag payload & dynamic onboarding model list

- Updated proto to use OnboardingModelGroup instead of bool flag for flexible onboarding
- Added getClineOnboardingModels function with caching and remote overrides for dynamic model fetching
- Modified controller to fetch and pass onboarding models to webview
- Updated UI to use dynamic models for selection, enabling flexible onboarding
- Enhanced feature flag service to support non-boolean payloads for better configurability

* clearOnboardingModelsCache
2025-11-14 14:49:05 -08:00
canvrno 1ab4b3cc24 fix:SAP provider type error - See PR #6547 (#7475) 2025-11-14 14:15:13 -08:00
canvrno 535b653228 Added stronger prompting around the use of act_mode_respond (#7448) 2025-11-14 12:12:34 -08:00
Igor Tceglevskii 1335fa5452 Retire firebase (#7362) 2025-11-14 09:29:47 -08:00
yuvalman b2a4395f71 feat: upgrade sap ai-sdk-js packages major version (#6547)
* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version
2025-11-14 09:11:03 -08:00
Toshii ae34a3a8c5 adding state variable for clineWebToolsEnabled (noop) (#7455)
* adding state variable for clineWebToolsEnabled

* removing console log
2025-11-14 08:20:01 -08:00
811 changed files with 74690 additions and 20936 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add claude 4.5 haiku
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix: finalize document content during approval flow
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Expose --version in cline cli command
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Log Persistence errors to PostHog
+13
View File
@@ -0,0 +1,13 @@
---
"claude-dev": patch
---
feat: add OpenAI Codex (ChatGPT Plus/Pro) provider
Users with ChatGPT Plus or Pro subscriptions can now use GPT-5 models directly through Cline without needing an API key. Authentication is handled via OAuth through OpenAI's authentication system.
Models available:
- gpt-5.2-codex (default)
- gpt-5.1-codex-max
- gpt-5.1-codex-mini
- gpt-5.2
@@ -0,0 +1,9 @@
---
"claude-dev": patch
---
Fix two bugs in DiffViewProvider file editing:
1. **Line boundary validation**: Add `safelyTruncateDocument()` to prevent out-of-bounds line errors on JetBrains hosts (fixes #8423, #8429). The gRPC protocol strictly validates line numbers, causing "truncateDocument INTERNAL: Wrong line" errors when `truncateDocument()` was called with a line number >= document line count.
2. **Content concatenation on final update**: When replacing content without a trailing newline, the old content at line N+1 was concatenated to the new content. Fixed by extending the replacement range to cover the entire document on final update.
+9
View File
@@ -0,0 +1,9 @@
---
"claude-dev": patch
---
docs: fix outdated Ollama model names in documentation
Updated recommended Ollama models to use correct identifiers:
- Changed qwen3-coder-30b to qwen2.5-coder:32b
- Changed devstral-small to codellama:34b-code
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
OpenAI GPT-5 Codex models are now using Apply Patch tool for diff edits.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix issue where tool call ids are invalid when switching between models using the chat completion format and the responses api format.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix: add chat output on skill use
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Adding telemetry for background exec terminal
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
This pull request introduces comprehensive Jupyter Notebook support for Cline, enabling AI-assisted editing of `.ipynb` files with full cell-level context awareness. The feature allows users to seamlessly work with Jupyter notebooks using Cline's AI capabilities while preserving the notebook's JSON structure.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix: removes retry message from UI after retry succeeds
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Support native tool calling for LM Studio and Ollama provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
add claude 4.5 opus into sap provider.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Limite Vertex and LiteLLM options when they're remote configured
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix crash when the Context Menu has a type but no options
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Throttle the remote config fetch
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Improve history view filter menu
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Add git worktree management UI for running parallel Cline sessions
+1
View File
@@ -0,0 +1 @@
../../.clinerules/workflows/hotfix-release.md
+1
View File
@@ -0,0 +1 @@
../../.clinerules/workflows/release.md
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
set -euo pipefail
# Only run in Claude Code remote environments
if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then
exit 0
fi
cd "$CLAUDE_PROJECT_DIR"
echo "=== Claude Code for Web Setup ==="
echo ""
# Install latest gh CLI tool
echo "Installing GitHub CLI..."
GH_VERSION=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/^v//')
curl -sL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz" -o /tmp/gh.tar.gz
tar -xzf /tmp/gh.tar.gz -C /tmp
sudo mv "/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh" /usr/local/bin/gh
rm -rf /tmp/gh.tar.gz /tmp/gh_${GH_VERSION}_linux_amd64
echo "Installed gh version: $(gh --version | head -1)"
echo ""
# Check if GITHUB_TOKEN is set and configure gh
if [ -n "${GITHUB_TOKEN:-}" ]; then
echo "GITHUB_TOKEN is configured - gh CLI is ready to use"
echo ""
echo "You can use gh commands directly, for example:"
echo " gh issue list --repo cline/cline --limit 5"
echo " gh pr list --repo cline/cline --state open"
echo " gh issue view 123 --repo cline/cline"
echo ""
else
echo "GITHUB_TOKEN is not set - gh CLI will have limited functionality"
echo ""
echo "To enable full GitHub API access:"
echo "1. Create a Fine-grained Personal Access Token at https://github.com/settings/tokens?type=beta"
echo "2. Add it as GITHUB_TOKEN in your Claude Code environment settings"
echo ""
fi
# Install project dependencies
echo "Installing dependencies..."
npm run install:all
# Generate gRPC/protobuf types (required for TypeScript)
echo "Generating proto types..."
npm run protos
echo ""
echo "Session setup complete!"
+14
View File
@@ -0,0 +1,14 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/claude-code-for-web-setup.sh"
}
]
}
]
}
}
+196
View File
@@ -0,0 +1,196 @@
---
name: create-pull-request
description: Create a GitHub pull request following project conventions. Use when the user asks to create a PR, submit changes for review, or open a pull request. Handles commit analysis, branch management, and PR creation using the gh CLI tool.
---
# Create Pull Request
This skill guides you through creating a well-structured GitHub pull request that follows project conventions and best practices.
## Prerequisites Check
Before proceeding, verify the following:
### 1. Check if `gh` CLI is installed
```bash
gh --version
```
If not installed, inform the user:
> The GitHub CLI (`gh`) is required but not installed. Please install it:
> - macOS: `brew install gh`
> - Other: https://cli.github.com/
### 2. Check if authenticated with GitHub
```bash
gh auth status
```
If not authenticated, guide the user to run `gh auth login`.
### 3. Verify clean working directory
```bash
git status
```
If there are uncommitted changes, ask the user whether to:
- Commit them as part of this PR
- Stash them temporarily
- Discard them (with caution)
## Gather Context
### 1. Identify the current branch
```bash
git branch --show-current
```
Ensure you're not on `main` or `master`. If so, ask the user to create or switch to a feature branch.
### 2. Find the base branch
```bash
git remote show origin | grep "HEAD branch"
```
This is typically `main` or `master`.
### 3. Analyze recent commits relevant to this PR
```bash
git log origin/main..HEAD --oneline --no-decorate
```
Review these commits to understand:
- What changes are being introduced
- The scope of the PR (single feature/fix or multiple changes)
- Whether commits should be squashed or reorganized
### 4. Review the diff
```bash
git diff origin/main..HEAD --stat
```
This shows which files changed and helps identify the type of change.
## Information Gathering
Before creating the PR, you need the following information. Check if it can be inferred from:
- Commit messages
- Branch name (e.g., `fix/issue-123`, `feature/new-login`)
- Changed files and their content
If any critical information is missing, use `ask_followup_question` to ask the user:
### Required Information
1. **Related Issue Number**: Look for patterns like `#123`, `fixes #123`, or `closes #123` in commit messages
2. **Description**: What problem does this solve? Why were these changes made?
3. **Type of Change**: Bug fix, new feature, breaking change, refactor, cosmetic, documentation, or workflow
4. **Test Procedure**: How was this tested? What could break?
### Example clarifying question
If the issue number is not found:
> I couldn't find a related issue number in the commit messages or branch name. What GitHub issue does this PR address? (Enter the issue number, e.g., "123" or "N/A" for small fixes)
## Git Best Practices
Before creating the PR, consider these best practices:
### Commit Hygiene
1. **Atomic commits**: Each commit should represent a single logical change
2. **Clear commit messages**: Follow conventional commit format when possible
3. **No merge commits**: Prefer rebasing over merging to keep history clean
### Branch Management
1. **Rebase on latest main** (if needed):
```bash
git fetch origin
git rebase origin/main
```
2. **Squash if appropriate**: If there are many small "WIP" commits, consider interactive rebase:
```bash
git rebase -i origin/main
```
Only suggest this if commits appear messy and the user is comfortable with rebasing.
### Push Changes
Ensure all commits are pushed:
```bash
git push origin HEAD
```
If the branch was rebased, you may need:
```bash
git push origin HEAD --force-with-lease
```
## Create the Pull Request
**IMPORTANT**: Read and use the PR template at `.github/pull_request_template.md`. The PR body format must **strictly match** the template structure. Do not deviate from the template format.
When filling out the template:
- Replace `#XXXX` with the actual issue number, or keep as `#XXXX` if no issue exists (for small fixes)
- Fill in all sections with relevant information gathered from commits and context
- Mark the appropriate "Type of Change" checkbox(es)
- Complete the "Pre-flight Checklist" items that apply
### Create PR with gh CLI
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main
```
Alternatively, create as draft if the user wants review before marking ready:
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main --draft
```
## Post-Creation
After creating the PR:
1. **Display the PR URL** so the user can review it
2. **Remind about CI checks**: Tests and linting will run automatically
3. **Suggest next steps**:
- Add reviewers if needed: `gh pr edit --add-reviewer USERNAME`
- Add labels if needed: `gh pr edit --add-label "bug"`
## Error Handling
### Common Issues
1. **No commits ahead of main**: The branch has no changes to submit
- Ask if the user meant to work on a different branch
2. **Branch not pushed**: Remote doesn't have the branch
- Push the branch first: `git push -u origin HEAD`
3. **PR already exists**: A PR for this branch already exists
- Show the existing PR: `gh pr view`
- Ask if they want to update it instead
4. **Merge conflicts**: Branch conflicts with base
- Guide user through resolving conflicts or rebasing
## Summary Checklist
Before finalizing, ensure:
- [ ] `gh` CLI is installed and authenticated
- [ ] Working directory is clean
- [ ] All commits are pushed
- [ ] Branch is up-to-date with base branch
- [ ] Related issue number is identified, or placeholder is used
- [ ] PR description follows the template exactly
- [ ] Appropriate type of change is selected
- [ ] Pre-flight checklist items are addressed
+194
View File
@@ -0,0 +1,194 @@
This file is the secret sauce for working effectively in this codebase. It captures tribal knowledge—the nuanced, non-obvious patterns that make the difference between a quick fix and hours of back-and-forth & human intervention.
**When to add to this file:**
- User had to intervene, correct, or hand-hold
- Multiple back-and-forth attempts were needed to get something working
- You discovered something that required reading many files to understand
- A change touched files you wouldn't have guessed
- Something worked differently than you expected
- User explicitly asks to "add this to CLAUDE.md"
**Proactively suggest additions** when any of the above happen—don't wait to be asked.
**What NOT to add:** Stuff you can figure out from reading a few files, obvious patterns, or standard practices. This file should be high-signal, not comprehensive.
## Miscellaneous
- This is a VS Code extension—check `package.json` for available scripts before trying to verify builds (e.g., `npm run compile`, not `npm run build`).
- When creating PRs, if the change is user-facing and significant enough to warrant a changelog entry, run `npm run changeset` and create a patch changeset. Never create minor or major version bumps. Skip changesets for trivial fixes, internal refactors, or minor UI tweaks that users wouldn't notice.
- When adding new feature flags, see this PR as a reference https://github.com/cline/cline/pull/7566
- Additional instructions about making requests: @.clinerules/network.md
## gRPC/Protobuf Communication
The extension and webview communicate via gRPC-like protocol over VS Code message passing.
**Proto files live in `proto/`** (e.g., `proto/cline/task.proto`, `proto/cline/ui.proto`)
- Each feature domain has its own `.proto` file
- For simple data, use shared types in `proto/cline/common.proto` (`StringRequest`, `Empty`, `Int64Request`)
- For complex data, define custom messages in the feature's `.proto` file
- Naming: Services `PascalCaseService`, RPCs `camelCase`, Messages `PascalCase`
- For streaming responses, use `stream` keyword (see `subscribeToAuthCallback` in `account.proto`)
**Run `npm run protos`** after any proto changes—generates types in:
- `src/shared/proto/` - Shared type definitions
- `src/generated/grpc-js/` - Service implementations
- `src/generated/nice-grpc/` - Promise-based clients
- `src/generated/hosts/` - Generated handlers
**Adding new enum values** (like a new `ClineSay` type) requires updating conversion mappings in `src/shared/proto-conversions/cline-message.ts`
**Adding new RPC methods** requires:
- Handler in `src/core/controller/<domain>/`
- Call from webview via generated client: `UiServiceClient.scrollToSettings(StringRequest.create({ value: "browser" }))`
**Example—the `explain-changes` feature touched:**
- `proto/cline/task.proto` - Added `ExplainChangesRequest` message and `explainChanges` RPC
- `proto/cline/ui.proto` - Added `GENERATE_EXPLANATION = 29` to `ClineSay` enum
- `src/shared/ExtensionMessage.ts` - Added `ClineSayGenerateExplanation` type
- `src/shared/proto-conversions/cline-message.ts` - Added mapping for new say type
- `src/core/controller/task/explainChanges.ts` - Handler implementation
- `webview-ui/src/components/chat/ChatRow.tsx` - UI rendering
## Adding a New API Provider
When adding a new provider (e.g., "openai-codex"), you must update the proto conversion layer in THREE places or the provider will silently reset to Anthropic:
1. `proto/cline/models.proto` - Add to the `ApiProvider` enum (e.g., `OPENAI_CODEX = 40;`)
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts` - Add case mapping string to proto enum
3. `convertProtoToApiProvider()` in the same file - Add case mapping proto enum back to string
**Why this matters:** Without these, the provider string hits the `default` case and returns `ANTHROPIC`. The webview, provider list, and handler all work fine, but the state silently resets when it round-trips through proto serialization. No error is thrown.
**Other files to update when adding a provider:**
- `src/shared/api.ts` - Add to `ApiProvider` union type, define models
- `src/shared/providers/providers.json` - Add to provider list for dropdown
- `src/core/api/index.ts` - Register handler in `createHandlerForProvider()`
- `webview-ui/src/components/settings/utils/providerUtils.ts` - Add cases in `getModelsForProvider()` and `normalizeApiConfiguration()`
- `webview-ui/src/utils/validate.ts` - Add validation case
- `webview-ui/src/components/settings/ApiOptions.tsx` - Render provider component
## Responses API Providers (OpenAI Codex, OpenAI Native)
Providers using OpenAI's Responses API require native tool calling. XML tools don't work with the Responses API.
**Symptoms of broken native tool calling:**
- Tools get called multiple times (e.g., `ask_followup_question` asks the same question twice)
- Tool arguments get duplicated or malformed
- The model responds but tools aren't recognized
**Root causes to check:**
1. **Provider missing from `isNextGenModelProvider()`** in `src/utils/model-utils.ts`. The native variant matchers (e.g., `native-gpt-5/config.ts`) call this function. If your provider isn't in the list, the matcher returns false and falls back to XML tools.
2. **Model missing `apiFormat: ApiFormat.OPENAI_RESPONSES`** in its model info (`src/shared/api.ts`). This property signals that the model requires native tool calling. The task runner in `src/core/task/index.ts` checks this and forces `enableNativeToolCalls: true` regardless of user settings.
**When adding a new Responses API provider:**
1. Add provider to `isNextGenModelProvider()` list in `src/utils/model-utils.ts`
2. Set `apiFormat: ApiFormat.OPENAI_RESPONSES` on all models that use the Responses API
3. The variant matcher and task runner will handle the rest automatically
## Adding Tools to System Prompt
This is tricky—multiple prompt variants and configs. **Always search for existing similar tools first and follow their pattern.** Look at the full chain from prompt definition → variant configs → handler → UI before implementing.
1. **Add to `ClineDefaultTool` enum** in `src/shared/tools.ts`
2. **Tool definition** in `src/core/prompts/system-prompt/tools/` (create file like `generate_explanation.ts`)
- Define variants for each `ModelFamily` (generic, next-gen, xs, etc.)
- Export variants array (e.g., `export const my_tool_variants = [GENERIC, NATIVE_NEXT_GEN, XS]`)
- **Fallback behavior**: If a variant isn't defined for a model family, `ClineToolSet.getToolByNameWithFallback()` automatically falls back to GENERIC. So you only need to export `[GENERIC]` unless the tool needs model-specific behavior.
3. **Register in `src/core/prompts/system-prompt/tools/init.ts`** - Import and spread into `allToolVariants`
4. **Add to variant configs** - Each model family has its own config in `src/core/prompts/system-prompt/variants/*/config.ts`. Add your tool's enum to the `.tools()` list:
- `generic/config.ts`, `next-gen/config.ts`, `gpt-5/config.ts`, `native-gpt-5/config.ts`, `native-gpt-5-1/config.ts`, `native-next-gen/config.ts`, `gemini-3/config.ts`, `glm/config.ts`, `hermes/config.ts`, `xs/config.ts`
- **Important**: If you add to a variant's config, make sure the tool spec exports a variant for that ModelFamily (or relies on GENERIC fallback)
5. **Create handler** in `src/core/task/tools/handlers/`
6. **Wire up in `ToolExecutor.ts`** if needed for execution flow
7. **Add to tool parsing** in `src/core/assistant-message/index.ts` if needed
8. **If tool has UI feedback**: add `ClineSay` enum in proto, update `src/shared/ExtensionMessage.ts`, update `src/shared/proto-conversions/cline-message.ts`, update `webview-ui/src/components/chat/ChatRow.tsx`
## Modifying System Prompt
**Read these first:** `src/core/prompts/system-prompt/README.md`, `tools/README.md`, `__tests__/README.md`
System prompt is modular: **components** (reusable sections) + **variants** (model-specific configs) + **templates** (with `{{PLACEHOLDER}}` resolution).
**Key directories:**
- `components/` - Shared sections: `rules.ts`, `capabilities.ts`, `editing_files.ts`, etc.
- `variants/` - Model-specific: `generic/`, `next-gen/`, `xs/`, `gpt-5/`, `gemini-3/`, `hermes/`, `glm/`, etc.
- `templates/` - Template engine and placeholder definitions
**Variant tiers (ask user which to modify):**
- **Next-gen** (Claude 4, GPT-5, Gemini 2.5): `next-gen/`, `native-next-gen/`, `native-gpt-5/`, `native-gpt-5-1/`, `gemini-3/`, `gpt-5/`
- **Standard** (default fallback): `generic/`
- **Local/small models**: `xs/`, `hermes/`, `glm/`
**How overrides work:** Variants can override components via `componentOverrides` in their `config.ts`, or provide a custom template in `template.ts` (e.g., `next-gen/template.ts` exports `rules_template`). If no override, the shared component from `components/` is used.
**Example: Adding a rule to RULES section**
1. Check if variant overrides rules: look for `rules_template` in `variants/*/template.ts` or `componentOverrides.RULES` in `config.ts`
2. If shared: modify `components/rules.ts`
3. If overridden: modify that variant's template
4. XS variant is special—has heavily condensed inline content in `template.ts`
**After any changes, regenerate snapshots:**
```bash
UPDATE_SNAPSHOTS=true npm run test:unit
```
Snapshots live in `__tests__/__snapshots__/`. Tests validate across model families and context variations (browser, MCP, focus chain).
## Modifying Default Slash Commands
Three places need updates:
- `src/core/slash-commands/index.ts` - Command definitions
- `src/core/prompts/commands.ts` - System prompt integration
- `webview-ui/src/utils/slash-commands.ts` - Webview autocomplete
## Adding New Global State Keys
Adding a new key to global state requires updates in multiple places. Missing any step causes silent failures.
Required steps:
1. Type definition in `src/shared/storage/state-keys.ts` - Add to `GlobalState` or `Settings` interface
2. Read from globalState in `src/core/storage/utils/state-helpers.ts`:
- Add `const myKey = context.globalState.get<GlobalStateAndSettings["myKey"]>("myKey")` in `readGlobalStateFromDisk()`
- Add to the return object: `myKey: myKey ?? defaultValue,`
3. StateManager handles read/write via `setGlobalState()`/`getGlobalStateKey()` after initialization
Common mistake: Adding only the return value without the `context.globalState.get()` call. This compiles but the value is always `undefined` on load.
## StateManager Cache vs Direct globalState Access
StateManager uses an in-memory cache populated during `StateManager.initialize(context)` in `common.ts`. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
Exception: State needed immediately at extension startup (before cache is ready)
When Window A sets state and immediately opens Window B, the new window's StateManager cache is populated from `context.globalState` during initialization. If you need to read state in Window B right at startup (e.g., in `common.ts` during `initialize()`), read directly from `context.globalState.get()` instead of StateManager's cache.
Example pattern (see `lastShownAnnouncementId` and `worktreeAutoOpenPath`):
```typescript
// Writing (normal pattern)
controller.stateManager.setGlobalState("myKey", value)
// Reading at startup in common.ts (bypass cache)
const value = context.globalState.get<string>("myKey")
```
This is only needed for cross-window state read during the brief startup window before StateManager cache is fully usable. Normal state access after initialization should use StateManager.
## ChatRow Cancelled/Interrupted States
When a ChatRow displays a loading/in-progress state (spinner), you must handle what happens when the task is cancelled. This is non-obvious because cancellation doesn't update the message content—you have to infer it from context.
**The pattern:**
1. A message has a `status` field (e.g., `"generating"`, `"complete"`, `"error"`) stored in `message.text` as JSON
2. When cancelled mid-operation, the status stays `"generating"` forever—no one updates it
3. To detect cancellation, check TWO conditions:
- `!isLast` — if this message is no longer the last message, something else happened after it (interrupted)
- `lastModifiedMessage?.ask === "resume_task" || "resume_completed_task"` — task was just cancelled and is waiting to resume
**Example from `generate_explanation`:**
```tsx
const wasCancelled =
explanationInfo.status === "generating" &&
(!isLast ||
lastModifiedMessage?.ask === "resume_task" ||
lastModifiedMessage?.ask === "resume_completed_task")
const isGenerating = explanationInfo.status === "generating" && !wasCancelled
```
**Why both checks?**
- `!isLast` catches: cancelled → resumed → did other stuff → this old message is stale
- `lastModifiedMessage?.ask === "resume_task"` catches: just cancelled, hasn't resumed yet, this message is still technically "last"
**See also:** `BrowserSessionRow.tsx` uses similar pattern with `isLastApiReqInterrupted` and `isLastMessageResume`.
**Backend side:** When streaming is cancelled, clean up properly (close tabs, clear comments, etc.) by checking `taskState.abort` after the streaming function returns.
+90
View File
@@ -0,0 +1,90 @@
# Networking & Proxy Support
To ensure Cline works correctly in all environments (VSCode, JetBrains, CLI) and with various network configurations (especially corporate proxies), strictly follow these guidelines for all network activity.
In extension code, do NOT use the global `fetch` or a default `axios` instance. (Note, `shared/net.ts` is exempt from these rules because it sets up the fetch wrappers.) In Webview code, you SHOULD use global `fetch`.
Global `fetch` and default `axios` do not automatically pick up proxy configurations in all environments (specifically JetBrains and CLI). You MUST use the provided utilities in `@/shared/net` which handle proxy agent configuration. In the webview, the browser/embedder handles proxies.
## Guidelines
### 1. Using `fetch`
Instead of `fetch(...)`, import the proxy-aware wrapper:
```typescript
import { fetch } from '@/shared/net'
// Usage is identical to global fetch
const response = await fetch('https://api.example.com/data')
```
### 2. Using `axios`
When using `axios`, you must apply the settings from `getAxiosSettings()`:
```typescript
import axios from 'axios'
import { getAxiosSettings } from '@/shared/net'
const response = await axios.get('https://api.example.com/data', {
headers: { 'Authorization': '...' },
...getAxiosSettings() // <--- CRITICAL: Injects the proxy agent if needed
})
```
### 3. Third-Party Clients (OpenAI, Ollama, etc.)
Most API client libraries allow you to customize the `fetch` implementation. You **MUST** pass the proxy-aware `fetch` to these clients.
**Example (OpenAI):**
```typescript
import OpenAI from "openai"
import { fetch } from "@/shared/net"
this.client = new OpenAI({
apiKey: '...',
fetch, // <--- CRITICAL: Pass our fetch wrapper
})
```
### 4. Tests
Use `mockFetchForTesting` to mock the underlying fetch implementation.
**Example (callback):**
```
import { mockFetchForTesting } from "@/shared/net"
...
let mockFetch = ...
mockFetchForTesting(mockFetch, () => {
// This calls mockFetch
fetch('https://foo.example').then(...)
})
// Original fetch is restored immediately when the call returns.
```
**Example (Promise):**
```
import { mockFetchForTesting } from "@/shared/net"
...
let mockFetch = ...
await mockFetchForTesting(mockFetch, async () => {
await ...
// This calls mockFetch
await fetch('https://foo.example')
...
})
// Original fetch is restored when the Promise from the callback settles
```
## Verification
If you are adding a new network call or integration:
1. Check `@/shared/net.ts` is imported.
2. Ensure `fetch` or `getAxiosSettings` is being used.
3. Verify that third-party clients are configured to use the custom fetch.
@@ -0,0 +1,29 @@
# Address PR Comments
Review and address all comments on the current branch's PR.
## Steps
1. Get the current branch name and find the associated PR:
```bash
gh pr view --json number,title,body
```
2. Understand the PR context:
- Get the full diff: `git diff origin/main...HEAD`
- Read the changed files to understand what the PR is doing
- Read related files if needed to understand the broader context
- Understand the intent and spirit of the changes, not just the code
3. Fetch all PR comments:
- Inline comments: `gh api repos/{owner}/{repo}/pulls/{pr_number}/comments`
- General comments: `gh pr view {pr_number} --json comments,reviews`
4. Present a summary of all comments with your recommendation for each (apply, skip, or respond). Ignore bot noise (changeset-bot, CI status, etc.).
5. **Wait for my approval** before proceeding.
6. After approval:
- Apply code changes and commit
- Reply to comments that were addressed or intentionally skipped
- Push commits
@@ -0,0 +1,49 @@
# Find Best Reviewers for Current Branch
Analyze my current branch to find the best people to review my PR based on **domain expertise** and git history.
## Steps
1. Get the current branch name and verify it's not `main`
2. Get the diff between the current branch and `origin/main`:
- Use `git diff origin/main...HEAD --name-only` to get changed files
- Use `git diff origin/main...HEAD` to understand the nature/spirit of the changes
3. **Identify the domain/feature area** being changed:
- Read the diff carefully to understand WHAT is being changed conceptually (e.g., "slash commands", "authentication", "API client", "UI components")
- This semantic understanding is crucial for finding the right reviewers
4. Find domain experts by searching for related files and their contributors:
- Identify all files related to the feature/domain (not just the ones changed)
- Example: if changing slash commands, find ALL slash-command related files across the codebase
- Use `git log --format="%an <%ae>" -- <related-files-pattern>` to find who has expertise in that domain
5. For additional context, also gather:
- `git blame -L <start>,<end> origin/main -- <file-path>` for exact lines changed
- Recent commit activity on related files
6. Score and rank contributors by:
- **Highest weight: Domain expertise** - who has the most commits to files in this feature area (even files not touched by this PR)
- **Medium weight: Direct file expertise** - commits to the specific files being changed
- **Lower weight: Line-level ownership** - authored the exact lines being modified
7. Exclude myself (check against my git config user.email)
8. Present the top 5 reviewers as an ordered list
## Output Format
Output an ordered list:
1. **Name** - Domain expert: 15 commits to slash-command related files, authored core parsing logic
2. **Name** - 8 commits to affected files, recently added the feature being modified
3. ...
## Commands Reference
```bash
git config user.email
git diff origin/main...HEAD --name-only
git diff origin/main...HEAD
# Find related files for a domain (adjust pattern based on what you learn from the diff)
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) | head -20
# Get contributors for related files
find . -type f \( -name "*slash-command*" -o -name "*SlashCommand*" \) -print0 | xargs -0 git log --format="%an <%ae>" -- | sort | uniq -c | sort -rn
git log --format="%an <%ae>" -- <file> | sort | uniq -c | sort -rn
git blame -L 10,20 origin/main -- <file>
```
Do NOT ask questions - analyze the changes, identify the domain, and output the reviewer list.
+194
View File
@@ -0,0 +1,194 @@
# Hotfix Release
Create a hotfix release by cherry-picking specific commits from main onto the latest release tag.
## Overview
This workflow helps you:
1. Select specific commits from main to include in a hotfix
2. Create a release notes commit on main (changelog + version bump)
3. Cherry-pick everything onto the latest release tag
4. Tag and push the new release
## Step 1: Setup and Gather Information
First, ensure we're on main and up to date:
```bash
git checkout main && git pull origin main
```
Get the latest release tag:
```bash
git tag --sort=-v:refname | head -1
```
## Step 2: Present Commits Since Last Release
Show all commits on main since the last release tag:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
git log ${LAST_TAG}..HEAD --oneline --format="%h %s (%an)"
```
Also get the commit messages already on the tag (to identify previously cherry-picked commits). Note: Run these as separate commands to avoid shell parsing issues with parentheses in author names:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
PREV_TAG=$(git tag --sort=-v:refname | head -2 | tail -1)
```
```bash
git log $PREV_TAG..$LAST_TAG --oneline --format="%s"
```
**Present the list** to the user in a numbered format with commit hash, subject, and author. For any commits whose subject line already appears in the tag's history (previously cherry-picked in an earlier hotfix) or are "Release Notes" commits, add `(already in previous hotfix)` or `(release notes - skip)` after them so the user knows to skip those.
Ask which commits to include in the hotfix.
Use the ask_followup_question tool to let the user specify which commits they want (by number or hash).
## Step 3: Analyze Selected Commits
For each selected commit:
1. Get the full commit message: `git show --no-patch --format="%B" <hash>`
2. Get the diff to understand the change: `git show <hash> --stat`
3. Find the associated PR if any: `gh pr list --search "<hash>" --state merged --json number,title --jq '.[0]'`
Build a mental model of what these changes do for the changelog.
## Step 4: Determine New Version Number
Parse the current version from package.json and the last tag:
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
echo "Last release: $LAST_TAG"
cat package.json | grep '"version"'
```
Hotfixes always increment the patch version (e.g., 3.40.0 -> 3.40.1, or 3.40.1 -> 3.40.2).
**Ask the user to confirm the new version number.**
## Step 5: Create Release Notes Commit on Main
On the main branch, create a commit that updates:
1. **CHANGELOG.md** - Add a new section for the hotfix version at the top:
```markdown
## [3.40.1]
- Description of fix 1
- Description of fix 2
```
Write clear, user-friendly descriptions based on your analysis of the commits.
2. **package.json** - Update the version field to the new version
3. **Delete changesets** for the commits being included in the hotfix. This prevents the changeset bot from including duplicate entries in the next regular release.
Find and delete the changeset files associated with the selected commits:
```bash
ls .changeset/
```
Each changeset file in `.changeset/` corresponds to a PR. Read them to identify which ones belong to the commits you're hotfixing, then delete those files.
**Skip running `npm run install:all`** - the automation handles outdated lockfiles.
Commit with message format: `v{VERSION} Release Notes (hotfix)`
In the commit body, mention:
- This is for a hotfix release
- List the cherry-picked commits that will be included
```bash
git add CHANGELOG.md package.json .changeset/
git commit -m "v3.40.1 Release Notes (hotfix)
Hotfix release including:
- <commit1-hash>: <description>
- <commit2-hash>: <description>
"
```
Push to main:
```bash
git push origin main
```
## Step 6: Build the Hotfix on the Tag
Checkout the last release tag (detached HEAD):
```bash
LAST_TAG=$(git tag --sort=-v:refname | head -1)
git checkout $LAST_TAG
```
Cherry-pick the selected commits in order:
```bash
git cherry-pick <commit1-hash>
git cherry-pick <commit2-hash>
# ... etc
```
Finally, cherry-pick the release notes commit you just pushed to main:
```bash
# Get the hash of the release notes commit (should be HEAD of main)
RELEASE_NOTES_COMMIT=$(git rev-parse main)
git cherry-pick $RELEASE_NOTES_COMMIT
```
## Step 7: Tag and Push
After all cherry-picks are applied successfully:
```bash
# Tag the new release
git tag v{VERSION}
# Push the tag to remote
git push origin v{VERSION}
```
## Step 8: Return to Main and Summary
Return to main branch:
```bash
git checkout main
```
**Copy a Slack announcement message to clipboard** with the version and PR links for each included fix:
```
VS Code Hotfix v{VERSION} Published
- Description of fix 1 https://github.com/cline/cline/pull/{PR_NUMBER}
- Description of fix 2 https://github.com/cline/cline/pull/{PR_NUMBER}
```
Present a final summary:
- New version: v{VERSION}
- Tag pushed: yes
- Commits included: (list them)
- Slack message copied to clipboard: yes
Remind the user to:
1. Manually trigger the publish release GitHub Action at: https://github.com/cline/cline/actions/workflows/publish.yml (paste `v{VERSION}` as the tag)
2. Post the Slack message to announce the hotfix
## Important Notes
- This workflow does NOT create a release branch - only tags
- The release notes commit goes to main first, then gets cherry-picked to the tag
- This keeps main's history accurate while allowing hotfix releases from tags
- If cherry-pick conflicts occur, resolve them before continuing
+232
View File
@@ -0,0 +1,232 @@
# Release
Prepare and publish a release from the open changeset PR.
## Overview
This workflow helps you:
1. Find and checkout the open changeset PR
2. Clean up the changelog (fix version format, wordsmith entries)
3. Push changes back to the PR branch
4. Merge with proper commit message format
5. Tag and push the release (after verifying the commit)
6. Trigger the publish workflow
7. Update GitHub release notes
8. Provide final summary with Slack announcement
## Step 1: Find the Changeset PR
Look for the open changeset PR:
```bash
gh pr list --search "Changeset version bump" --state open --json number,title,headRefName,url
```
If no PR is found, inform the user there's no changeset PR ready. They may need to:
- Merge PRs with changesets to main first
- Manually trigger the Changeset Converter workflow at: https://github.com/cline/cline/actions/workflows/changeset-converter.yml
## Step 2: Gather PR Information
Get the PR details:
```bash
PR_NUMBER=<number from step 1>
gh pr view $PR_NUMBER --json body,files,headRefName
```
Checkout the PR branch:
```bash
git fetch origin changeset-release/main
git checkout changeset-release/main
```
If the branch has diverged from remote, reset to the remote version:
```bash
git reset --hard origin/changeset-release/main
```
## Step 3: Analyze the Changes
Read the current CHANGELOG.md to see what the automation generated:
```bash
head -50 CHANGELOG.md
```
Get the version from package.json:
```bash
cat package.json | grep '"version"'
```
**Present to the user:**
- The version number that will be released
- The raw changelog entries from the changeset PR
- Whether this is a patch, minor, or major release
## Step 4: Clean Up the Changelog
The changelog needs these fixes:
1. **Add brackets to version number**: Change `## 3.44.1` to `## [3.44.1]`
2. **No category headers**: Don't use `### Added`, `### Fixed`, etc. Just a flat list of bullet points.
3. **Order entries from most important to least important**:
- Lead with major new features or significant fixes users care about
- End with minor fixes or internal changes
4. **Write user-friendly descriptions**:
- This is for end users, not developers—explain what changed in plain language
- Remove commit hashes from the beginning of lines (the automation adds these)
- Look at the actual commit diffs (`git show <hash>`) and PRs to understand what changed
- Write colorful descriptions that explain the value and impact, not just technical details
- Consolidate related changes into single entries when appropriate
**Ask the user** to review the proposed changelog changes before applying them. Show them:
- Current (raw) changelog section
- Proposed (cleaned) changelog section
Once approved, apply the changes to CHANGELOG.md.
## Step 5: Commit and Push Changes
After making changelog edits:
```bash
git add CHANGELOG.md
git commit -m "Clean up changelog formatting"
git push origin changeset-release/main
```
## Step 6: Merge the PR
**Ask the user to confirm** they're ready to merge.
Merge the PR with the proper commit message format:
```bash
VERSION=<version from package.json>
gh pr merge $PR_NUMBER --squash --subject "v${VERSION} Release Notes" --body ""
```
**If merge is blocked by branch protection:**
- Users with admin privileges can add the `--admin` flag to bypass
- Users without admin privileges need to get the PR approved through normal review first before merging
## Step 7: Tag the Release
After the merge completes, checkout main and pull:
```bash
git checkout main
git pull origin main
```
**IMPORTANT: Verify the latest commit is the release commit before tagging:**
```bash
git log -1 --oneline
```
Confirm the commit message matches `v{VERSION} Release Notes` (e.g., `v3.44.1 Release Notes`). Do NOT blindly tag HEAD without verification.
Once verified, tag and push:
```bash
VERSION=<version>
git tag v${VERSION}
git push origin v${VERSION}
```
## Step 8: Trigger Publish Workflow
**Copy the tag to clipboard** so the user can easily paste it into the GitHub Actions workflow:
```bash
echo -n "v{VERSION}" | pbcopy
```
**Tell the user to trigger the publish workflow:**
1. Go to: https://github.com/cline/cline/actions/workflows/publish.yml
2. Select **"release"** for release-type
3. Paste **`v{VERSION}`** as the tag (already in clipboard)
**Wait for the user** to confirm the publish workflow has completed before proceeding.
## Step 9: Update GitHub Release Notes
Once the user confirms the publish workflow is done, fetch the auto-generated release content:
```bash
VERSION=<version>
gh release view v${VERSION} --json body --jq '.body'
```
The auto-generated release has:
- `## What's Changed` - PR list (we'll replace this with our changelog)
- `## New Contributors` - First-time contributors (keep this if present)
- `**Full Changelog**` - Comparison link (keep this)
Build the new release body:
1. Start with `## What's Changed` header
2. Add our changelog content (from CHANGELOG.md for this version)
3. Keep the `## New Contributors` section if it exists
4. Keep the `**Full Changelog**` link
Update the release:
```bash
gh release edit v${VERSION} --notes "<new body content>"
```
Verify the release was updated:
```bash
gh release view v${VERSION}
```
## Step 10: Final Summary
**Copy a Slack announcement message to clipboard** (include the full changelog, not just highlights):
```bash
echo "VS Code v{VERSION} Released
- Changelog entry 1
- Changelog entry 2
- Changelog entry 3" | pbcopy
```
**Present a final summary:**
- Version released: v{VERSION}
- PR merged: #{PR_NUMBER}
- Tag pushed: v{VERSION}
- Release: https://github.com/cline/cline/releases/tag/v{VERSION}
- Slack message copied to clipboard
**Final reminder:**
Post the Slack message to announce the release
## Handling Edge Cases
### No changesets found
If the changeset PR body shows no changes, inform the user they need to merge PRs with changesets first.
### Merge conflicts
If there are conflicts on the changeset branch, help the user resolve them:
```bash
git fetch origin main
git rebase origin/main
# resolve conflicts
git push origin changeset-release/main --force-with-lease
```
### User wants to add more changes
If the user wants to include additional PRs before releasing:
1. Ask them to merge those PRs to main first
2. The changeset automation will update the PR automatically
3. Re-run this workflow after the PR is updated
+28 -3
View File
@@ -72,12 +72,12 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# Example configurations:
#
# Console debugging (logs only):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=console
# TEL_DEBUG_DIAGNOSTICS=true
#
# OTLP with gRPC (insecure, for local testing):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=grpc
# OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4317
@@ -85,12 +85,37 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token
#
# OTLP with HTTP/JSON (production):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=http/json
# OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.example.com
# OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token
# ============================================================================
# OBJECT STORE CONFIGURATION
# ============================================================================
# TO ENABLE S3 OR R2 STORAGE, UNCOMMENT AND FILL IN THE FOLLOWING:
# CLINE_STORAGE_ADAPTER="s3" # Options: "s3" or "r2"
# CLINE_STORAGE_BUCKET="cline"
# CLINE_STORAGE_ACCESS_KEY_ID="key"
# CLINE_STORAGE_SECRET_ACCESS_KEY="secrets"
#
# [OPTIONAL FIELDS FOR R2]
# CLINE_STORAGE_ACCOUNT_ID = "account-id"
# Default R2 endpoint (if not set): "https://<CLINE_STORAGE_ACCOUNT_ID>.r2.cloudflarestorage.com"
# CLINE_STORAGE_ENDPOINT = "http://localhost:8333"
#
# [OPTIONAL FIELDS FOR S3]
# CLINE_STORAGE_REGION = "us-west-1" # AWS Bucket Region (default: "us-east-1")
# Default S3 endpoint (if not set): "https://s3.<CLINE_STORAGE_REGION>.amazonaws.com"
# CLINE_STORAGE_ENDPOINT = "http://localhost:8333"
#
# [OPTIONAL FIELDS FOR ALL STORAGE TYPES]
# CLINE_STORAGE_SYNC_INTERVAL_MS = 30000 # Interval for sync worker in milliseconds
# CLINE_STORAGE_SYNC_MAX_RETRIES = 5 # Max retries for failed sync operations
# CLINE_STORAGE_SYNC_BATCH_SIZE = 10 # Number of files to sync in each batch
# CLINE_STORAGE_SYNC_BACKFILL_ENABLED = false # Enable backfill of existing data on startup
# ============================================================================
# OPTIONAL DEVELOPMENT SETTINGS
# ============================================================================
-1
View File
@@ -1,4 +1,3 @@
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
/src/core/storage/ @celestial-vault
+1 -1
View File
@@ -58,7 +58,7 @@ jobs:
cache: "npm"
- name: Install Dependencies
run: npm install changeset
run: npm ci
# Check if there are any new changesets to process
- name: Check for changesets
+173
View File
@@ -0,0 +1,173 @@
name: Claude Issue Triage
on:
issues:
types: [opened]
# Manual trigger for backfilling existing issues. Run from terminal:
# gh workflow run claude-issue-triage.yml -f issue_number=1234
# Or batch process:
# gh issue list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-issue-triage.yml -f issue_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
issue_number:
description: 'Issue number to triage'
required: true
type: string
jobs:
claude-issue-triage:
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - issues: write -> Claude can comment and add labels (the only write access needed)
# - pull-requests: read -> Claude can view PR context but CANNOT create PRs
# This ensures that even if a malicious user attempts prompt injection via issue content,
# Claude cannot modify repository code, create branches, or open PRs.
permissions:
contents: read
issues: write
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run Issue Response & Triage
id: triage
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
# Allow all tools - security is enforced by GitHub permissions above (contents: read, issues: write)
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub issue first responder for the open source Cline repository.
**Issue:** #${{ github.event.issue.number || inputs.issue_number }}
**Title:** ${{ github.event.issue.title || 'See issue details below' }}
**Author:** @${{ github.event.issue.user.login || 'See issue details below' }}
## Your job
Investigate this issue thoroughly, then post a single helpful comment that helps the user and gives maintainers the context they need.
## Investigation
Start by reading the full issue:
gh issue view ${{ github.event.issue.number || inputs.issue_number }}
### Search for duplicates and related issues
Search thoroughly for existing issues that match this one:
gh issue list --search "<keywords from the issue>" --state all --limit 30
gh issue list --search "<error messages>" --state all --limit 20
gh issue list --search "<affected feature/component>" --state all --limit 20
For each relevant issue you find, read it including its comments:
gh issue view <number> --comments
You're looking for:
- **Duplicates**: Issues describing the same problem. Link to them and explain why you think they're duplicates. If closed, check how they were resolved - the solution might apply here.
- **Related issues**: Similar problems or context that could help. Pull useful information from their comments (workarounds others found, debugging steps that helped, maintainer explanations). Link to them and explain the connection.
If there are closed issues with solutions, surface those solutions prominently - this might immediately solve the user's problem.
### Analyze recent changes (ALWAYS DO THIS)
Many issues are regressions from recent releases. **Always** check what changed recently:
gh release list --limit 10
gh pr list --state merged --limit 50 --json number,title,mergedAt,author,body
Look for PRs merged in the last few weeks that might correlate with the issue. If you find a likely connection:
gh pr view <number>
gh pr diff <number>
git log --since="1 month ago" --oneline -- <relevant paths>
git show <commit>
**Always include your findings in your comment:**
- If you find a regression, call it out explicitly: which PR/commit likely caused it, who authored it, what changed, and suggest a fix direction if you can see one.
- If you don't find anything related, still mention it: "I analyzed recent PRs and releases but didn't find any changes that seem related to this issue."
### Search the codebase
Find the relevant code:
- Use grep/find to locate code related to the issue
- Key areas: `src/api/` (providers/models), `src/core/prompts/` (tools/prompts), platform-specific code for VS Code vs JetBrains
### Find documentation
Cline docs are at **https://docs.cline.bot/** and built with Mintlify from the `docs/` directory.
The URL structure maps directly to the file structure:
- `docs/getting-started/selecting-your-model.mdx` → https://docs.cline.bot/getting-started/selecting-your-model
- `docs/troubleshooting.mdx` → https://docs.cline.bot/troubleshooting
- Headings become anchors: `## Which Model` → `#which-model`
Search the `docs/` directory to find relevant documentation, then construct URLs to link users to:
```bash
ls docs/
grep -r "keyword" docs/ --include="*.mdx" -l
```
### Identify subject matter experts
For issues that clearly need engineering attention:
git log --since="6 months ago" --format="%an" -- <relevant paths> | sort | uniq -c | sort -rn | head -5
Cross-reference with GitHub usernames. Include in your response (@mention, do NOT assign):
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file |
## Weak model detection
Many issues are caused by users running small or non-frontier models that don't tool-call reliably. Signs include:
- Model failing to use tools correctly
- Nonsensical or malformed responses
- User is running a small/local model or older model version
If this looks like a weak model issue, kindly suggest they try reproducing with Claude Sonnet and report back if it persists. Link to https://docs.cline.bot/getting-started/selecting-your-model if helpful. Still label and triage normally.
## Your comment
Write a single comment as a helpful community member. Be conversational, not robotic. Include what's relevant:
- **Helpful response** - Answer their question, suggest a fix, provide a workaround. If you found solutions in related closed issues, surface those prominently.
- **Duplicates and related issues** - Link to any you found and explain why they're duplicates/related. Summarize useful context from their comments.
- **Regression analysis** - If this looks like a regression, explain what change likely caused it, link to the PR/commit, and tag the author.
- **Clarifying questions** - If you need more info, ask specific questions. Don't ask for things already provided.
- **SME table** - Include the table above if this needs engineering attention. Don't tag people for questions with obvious answers or weak-model issues.
- **Context for maintainers** - Relevant code paths, what you found. Keep it concise.
- **Docs links** - If there's relevant documentation, link to it naturally in your response as a recommendation (e.g., "For more details, check out [the Ollama setup guide](url)"). Do NOT add a "Sources" section at the end - integrate doc links into your response where they're helpful.
- **Possible Duplicates section** - ALWAYS include a "Possible Duplicates" section at the end of your comment listing issues that might be duplicates so maintainers can quickly close if appropriate. If none found, say "No obvious duplicates found."
## Labels
First, retrieve all available labels and read their descriptions to understand what each is for:
gh label list --json name,description --limit 100
Then apply the appropriate labels based on your analysis. Only use labels from the list above—do not create new labels.
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "label1,label2"
If your regression analysis found a likely culprit (a recent PR/commit that probably caused this issue), add the "Regression" label:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Regression"
IMPORTANT: After posting your comment, add the "Bot Responded" label to indicate this issue has received an automated response:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Bot Responded"
## Remember
- **This is a one-time automated response** - you will NOT see their reply or respond again. Never say things like "I can help you", "let me know", "once I have that info", or "I can give you more targeted help" - you won't be there to follow up. If you ask clarifying questions, frame them for the maintainers who will follow up, e.g., "If you can share X, that would help the maintainers diagnose this."
- Don't be formulaic. Respond to what the issue actually needs.
- Surface solutions from past issues - often the fastest path to helping.
- Connecting regressions to specific changes is extremely valuable.
- Link issues with #number so they're clickable.
+272
View File
@@ -0,0 +1,272 @@
name: Claude PR Review
on:
pull_request:
types: [opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run claude-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: string
jobs:
claude-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - pull-requests: write -> Claude can post reviews and inline suggestions
# - issues: read -> Claude can search for related issues
# NOTE: Even with pull-requests: write, Claude CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Run PR Review
id: review
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #${{ steps.pr.outputs.number }}
## Gather context
```bash
# Get full PR details
gh pr view ${{ steps.pr.outputs.number }} --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff ${{ steps.pr.outputs.number }}
# Check CI status
gh pr checks ${{ steps.pr.outputs.number }}
# Get existing review comments (to understand context and your previous feedback)
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments --jq '.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'
# Get conversation comments
gh pr view ${{ steps.pr.outputs.number }} --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don't block) if:
- Missing changeset - For user-facing changes, check if there's a `.changeset/` file:
```bash
gh pr diff ${{ steps.pr.outputs.number }} --name-only | grep '.changeset/' || echo "No changeset found"
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search "<keywords from the PR>" --state all --limit 30
gh issue list --search "<error messages or feature names>" --state all --limit 20
# Find similar PRs for reference
gh pr list --search "<keywords>" --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren't linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff ${{ steps.pr.outputs.number }} --name-only
# For each relevant path, find contributors
git log --since="6 months ago" --format="%an" -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Deep code review
This is the most important part. Don't just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven't considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep="<relevant keywords>" | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub's suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what's relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author's intent, why they made the changes, how they implemented it, and what files/systems are affected. Don't just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a "For Maintainers" section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they're relevant
- Open issues this PR might fix that weren't linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit ${{ steps.pr.outputs.number }} --add-label "label1,label2"
```
When done, add the reviewed label:
```bash
gh pr edit ${{ steps.pr.outputs.number }} --add-label "Bot Reviewed"
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like "let me know if you have questions", "I can help you with", or "feel free to ask" - you won't be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don't give vague feedback
- Think deeply - Don't just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You're a first-pass reviewer - A human maintainer will do final approval
+312
View File
@@ -0,0 +1,312 @@
name: Cline PR Code Review
on:
pull_request:
types:
[opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run cline-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run cline-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: "PR number to review"
required: true
type: string
concurrency:
group: pr-review-${{ github.event.pull_request.number || inputs.pr_number }}
cancel-in-progress: true
jobs:
cline-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 60
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> cline can read the codebase but CANNOT write/push any code
# - pull-requests: write -> cline can post reviews and inline suggestions
# - issues: read -> cline can search for related issues
# NOTE: Even with pull-requests: write, cline CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
- name: Install and Verify Cline CLI
run: |
npx cline version # verify installation
- name: Configure Cline with Anthropic
run: |
npx cline auth --provider anthropic \
--apikey "${{ secrets.ANTHROPIC_API_KEY }}" \
--modelid claude-opus-4-5-20251101
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Review PR with Cline
env:
PR_NUMBER: ${{ steps.pr.outputs.number }}
GITHUB_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
CLINE_COMMAND_PERMISSIONS: |
{
"allow": [
"gh pr diff *",
"gh pr view *",
"gh pr checks *",
"gh pr list *",
"gh label list *",
"gh issue list *",
"gh issue view *",
"git log *",
"gh pr comment ${{ steps.pr.outputs.number }} *",
"gh pr edit ${{ steps.pr.outputs.number }} *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews *"
]
}
run: |
npx cline --yolo 'You'\''re a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #'"${PR_NUMBER}"'
## Gather context
```bash
# Get full PR details
gh pr view '"${PR_NUMBER}"' --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff '"${PR_NUMBER}"'
# Check CI status
gh pr checks '"${PR_NUMBER}"'
# Get existing review comments (to understand context and your previous feedback)
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/comments --jq '\''.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'\''
# Get conversation comments
gh pr view '"${PR_NUMBER}"' --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don'\''t block) if:
- Missing changeset - For user-facing changes, check if there'\''s a `.changeset/` file:
```bash
gh pr diff '"${PR_NUMBER}"' --name-only | grep '\''.changeset/'\'' || echo '\''No changeset found'\''
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search '\''<keywords from the PR>'\'' --state all --limit 30
gh issue list --search '\''<error messages or feature names>'\'' --state all --limit 20
# Find similar PRs for reference
gh pr list --search '\''<keywords>'\'' --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren'\''t linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff '"${PR_NUMBER}"' --name-only
# For each relevant path, find contributors
git log --since='\''6 months ago'\'' --format='\''%an'\'' -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Bash command usage
Don'\''t use operators like `|`, `&&`, or `;` - run each command separately and analyze the output.
When referencing command outputs, quote them properly to avoid formatting issues.
## Deep code review
This is the most important part. Don'\''t just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven'\''t considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep='\''<relevant keywords>'\'' | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub'\''s suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'\''
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'\''
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what'\''s relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author'\''s intent, why they made the changes, how they implemented it, and what files/systems are affected. Don'\''t just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a '\''For Maintainers'\'' section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they'\''re relevant
- Open issues this PR might fix that weren'\''t linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit '"${PR_NUMBER}"' --add-label '\''label1,label2'\''
```
When done, add the reviewed label:
```bash
gh pr edit '"${PR_NUMBER}"' --add-label '\''Bot Reviewed'\''
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like '\''let me know if you have questions'\'', '\''I can help you with'\'', or '\''feel free to ask'\'' - you won'\''t be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don'\''t give vague feedback
- Think deeply - Don'\''t just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You'\''re a first-pass reviewer - A human maintainer will do final approval'
+130
View File
@@ -0,0 +1,130 @@
name: Publish NPM Release
on:
workflow_dispatch:
inputs:
confirm_publish:
description: 'Type "publish" to confirm you want to publish to NPM'
required: true
type: string
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-release:
needs: test
name: Publish Cline CLI to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && github.event.inputs.confirm_publish == 'publish'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# 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: Read release version
id: version
run: |
# Read version from cli/package.json (stable version)
VERSION=$(node -p "require('./cli/package.json').version")
echo "Release version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Clean previous builds
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
run: npm run protos && npm run protos-go
- name: Compile CLI
run: npm run compile-cli
- name: Compile CLI for all platforms
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
run: npm run protos && npm run protos-go
- name: Verify build output
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with latest tag
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'latest'..."
cd dist-standalone
npm publish --tag latest --access public
- name: Summary
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'latest'"
echo ""
echo "📦 Install with: npm install -g cline"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
+175
View File
@@ -0,0 +1,175 @@
name: Publish NPM Nightly
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-nightly:
needs: test
name: Publish Cline CLI (Nightly) to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for recent commits
id: check_commits
run: |
if [ $(git rev-list --count HEAD --since="24 hours ago") -eq 0 ]; then
echo "No commits in last 24 hours, skipping publish"
echo "skip=true" >> $GITHUB_OUTPUT
else
echo "Found recent commits, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Setup Node.js
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
if: steps.check_commits.outputs.skip != 'true'
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
if: steps.check_commits.outputs.skip != 'true'
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.check_commits.outputs.skip != 'true' && steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.check_commits.outputs.skip != 'true' && steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Generate nightly version with timestamp
if: steps.check_commits.outputs.skip != 'true'
id: version
run: |
# Read base version from cli/package.json (e.g., "1.0.9")
BASE_VERSION=$(node -p "require('./cli/package.json').version")
# Generate timestamp (Unix epoch seconds)
TIMESTAMP=$(date +%s)
# Create unique nightly version: 1.0.9-nightly.1736365200
VERSION="${BASE_VERSION}-nightly.${TIMESTAMP}"
echo "Base version: $BASE_VERSION"
echo "Generated nightly version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Update cli/package.json with nightly version
if: steps.check_commits.outputs.skip != 'true'
run: |
# Update version with timestamp-based nightly version
node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('cli/package.json', 'utf8'));
pkg.version = '${{ steps.version.outputs.version }}';
fs.writeFileSync('cli/package.json', JSON.stringify(pkg, null, '\t'));
"
echo "Using version ${{ steps.version.outputs.version }} for build"
cat cli/package.json | grep '"version"'
- name: Download ripgrep binaries
if: steps.check_commits.outputs.skip != 'true'
run: npm run download-ripgrep
- name: Clean previous builds
if: steps.check_commits.outputs.skip != 'true'
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Compile CLI
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli
- name: Compile CLI for all platforms
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
if: steps.check_commits.outputs.skip != 'true'
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Verify build output
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with nightly tag
if: steps.check_commits.outputs.skip != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'nightly'..."
cd dist-standalone
npm publish --tag nightly --access public
- name: Summary
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'nightly'"
echo ""
echo "📦 Install with: npm install -g cline@nightly"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
+2 -2
View File
@@ -74,8 +74,8 @@ jobs:
CLINE_ENVIRONMENT: production
# OpenTelemetry production defaults (can be overridden at runtime)
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: console,otlp
OTEL_METRICS_EXPORTER: console,otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
+25 -14
View File
@@ -36,6 +36,8 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag }}
fetch-depth: 0
fetch-tags: true
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -60,11 +62,11 @@ jobs:
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
run: npm install --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
run: cd webview-ui && npm install --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
@@ -99,8 +101,8 @@ jobs:
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
# OpenTelemetry production defaults (can be overridden at runtime)
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: console,otlp
OTEL_METRICS_EXPORTER: console,otlp
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
@@ -116,22 +118,31 @@ jobs:
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
fi
# - name: Get Changelog Entry
# id: changelog
# uses: mindsers/changelog-reader-action@v2
# with:
# # This expects a standard Keep a Changelog format
# # "latest" means it will read whichever is the most recent version
# # set in "## [1.2.3] - 2025-01-28" style
# version: latest
- name: Get Previous Tag
id: prev_tag
run: |
CURRENT_TAG="${{ steps.validate_tag.outputs.tag }}"
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Get Changelog Entry
id: changelog
run: |
# Get content between first ## [ and second ## [
CONTENT=$(awk '/^## \[/{if(found) exit; found=1; next} found{print}' CHANGELOG.md)
echo "content<<EOF" >> $GITHUB_OUTPUT
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.validate_tag.outputs.tag }}
files: "*.vsix"
# body: ${{ steps.changelog.outputs.content }}
generate_release_notes: true
body: |
${{ steps.changelog.outputs.content }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.validate_tag.outputs.tag }}
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+55 -11
View File
@@ -1,17 +1,26 @@
name: Trigger Jetbrains Plugin <-> Cline Tests
on:
pull_request:
types: [opened, synchronize, reopened]
pull_request_target:
types: [opened, reopened]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: read
concurrency:
group: jetbrains-trigger-${{ github.event.number }}
group: jetbrains-trigger-${{ github.event.pull_request.number || github.event.issue.number }}
cancel-in-progress: true
jobs:
trigger-integration-test:
name: Run Tests
runs-on: ubuntu-latest
# Run on PR open/reopen, or when someone comments /test-jetbrains on a PR
if: |
github.event_name == 'pull_request_target' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '/test-jetbrains'))
steps:
- name: Generate GitHub App Token
id: app-token
@@ -22,7 +31,39 @@ jobs:
owner: cline
repositories: intellij-plugin
- name: Get PR details (for issue_comment trigger)
id: pr-details
if: github.event_name == 'issue_comment'
env:
GH_TOKEN: ${{ github.token }}
run: |
PR_DATA=$(gh api repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
echo "head_ref=$(echo "$PR_DATA" | jq -r '.head.ref')" >> $GITHUB_OUTPUT
echo "head_sha=$(echo "$PR_DATA" | jq -r '.head.sha')" >> $GITHUB_OUTPUT
echo "title=$(echo "$PR_DATA" | jq -r '.title')" >> $GITHUB_OUTPUT
echo "html_url=$(echo "$PR_DATA" | jq -r '.html_url')" >> $GITHUB_OUTPUT
- name: Sanitize untrusted inputs
id: sanitize
env:
RAW_BRANCH_NAME: ${{ github.event_name == 'pull_request_target' && github.head_ref || steps.pr-details.outputs.head_ref }}
RAW_PR_TITLE: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.title || steps.pr-details.outputs.title }}
run: |
# Sanitize branch name for JSON
BRANCH_NAME_JSON=$(jq -n --arg b "$RAW_BRANCH_NAME" '$b')
echo "branch_name=$BRANCH_NAME_JSON" >> $GITHUB_OUTPUT
# Sanitize PR title for JSON
PR_TITLE_JSON=$(jq -n --arg t "$RAW_PR_TITLE" '$t')
echo "pr_title=$PR_TITLE_JSON" >> $GITHUB_OUTPUT
- name: Trigger IntelliJ Plugin Integration Test
env:
BRANCH_NAME: ${{ steps.sanitize.outputs.branch_name }}
PR_TITLE: ${{ steps.sanitize.outputs.pr_title }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
PR_URL: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.html_url || steps.pr-details.outputs.html_url }}
run: |
curl -X POST \
-H "Authorization: Bearer ${{ steps.app-token.outputs.token }}" \
@@ -34,20 +75,23 @@ jobs:
{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"pr_number": "$PR_NUMBER",
"branch_name": $BRANCH_NAME,
"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 }}"
"sha": "$PR_SHA",
"pr_title": $PR_TITLE,
"pr_url": "$PR_URL"
}
}
EOF
- name: Log trigger details
env:
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
PR_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || steps.pr-details.outputs.head_sha }}
run: |
echo "Triggered IntelliJ Plugin integration test for:"
echo " PR #${{ github.event.number }}: ${{ github.event.pull_request.title }}"
echo " Branch: ${{ github.head_ref }}"
echo " PR #$PR_NUMBER"
echo " Trigger: ${{ github.event_name }}"
echo " Action: ${{ github.event.action }}"
echo " SHA: ${{ github.event.pull_request.head.sha }}"
echo " SHA: $PR_SHA"
+11
View File
@@ -8,12 +8,14 @@ tmp
.DS_Store
.idea
.husky/_/
pnpm-lock.yaml
.clineignore
.venv
.actrc
CLAUDE.local.md
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
@@ -27,6 +29,10 @@ coverage-unit
*evals.env
.env
.secrets
.github/act/.secrets
.worktrees
## Generated files ##
src/generated/
@@ -35,3 +41,8 @@ webview-ui/src/services/grpc-client.ts
# E2E Tests
test-results
/.github/act
/pkg
.secrets
+37 -4
View File
@@ -12,7 +12,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -33,7 +36,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -54,7 +60,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -77,7 +86,10 @@
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
@@ -165,6 +177,27 @@
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "Open Storybook",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"storybook"
],
"cwd": "${workspaceFolder}/webview-ui",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"serverReadyAction": {
"pattern": "Local:.*http://localhost:([0-9]+)",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
},
"env": {
"IS_DEV": "true"
}
}
]
}
+3 -1
View File
@@ -27,5 +27,7 @@
"source.removeUnused.biome": "always",
"source.removeUnusedImports": "always",
"source.organizeImports.biome": "always"
}
},
// Disable auto-forwarding ports to prevent Simple Browser from opening the Vite dev server
"remote.autoForwardPorts": false
}
+20
View File
@@ -263,6 +263,26 @@
"watch"
],
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
},
{
"type": "npm",
"script": "storybook",
"group": "build",
"problemMatcher": [],
"isBackground": false,
"label": "npm: storybook",
"dependsOn": [
"npm: protos",
"npm: build:webview"
],
"presentation": {
"reveal": "always"
},
"options": {
"env": {
"IS_DEV": "true"
}
}
}
],
"inputs": [
+2 -3
View File
@@ -1,6 +1,8 @@
# Default
.vscode/**
.vscode-test/**
.worktrees/**
CLAUDE.local.md
out/
dist-standalone/
node_modules/
@@ -40,9 +42,6 @@ buf.yaml
.changeset/
.clinerules/
# Include specific file needed for Background Exec mode
!standalone/runtime-files/vscode/enhanced-terminal.js
# 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/**
webview-ui/public/**
+1
View File
@@ -0,0 +1 @@
.gitignore
+281 -7
View File
@@ -1,14 +1,288 @@
# Changelog
## 3.37.1
## [3.51.0]
- cf8dd1c: Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.
- 02abbcf: Add AGENTS.md support
- 855db7d: feat(models): Add free minimax/mimax-m2 model to the model picker
### Added
- Adding OpenAI gpt-5.2-codex model to the model picker
## [3.50.0]
### Added
- Add gpt-5.2-codex OpenAI model support
- Add create-pull-request skill
### Fixed
- Fix the selection of remotely configured providers
- Fix act_mode_respond to prevent consecutive calls
- Fix invalid tool call IDs when switching between model formats
## [3.49.1]
### Added
- Add telemetry to track usage of skills feature
- Add version headers to Cline backend requests
- Phase in Responses API usage instead of defaulting for every supported model
### Fixed
- Fix workflow slash command search to be case-insensitive
- Fix model display in ModelPickerModal when using LiteLLM
- Fix LiteLLM model fetching with default base URL
- Fix crash when OpenAI-compatible APIs send usage chunks with empty or null choices arrays at end of streaming
- Fix model ID for Kat Coder Pro Free model
## [3.49.0]
- Enable configuring an OTEL collector at runtime
- Removing Minimax-2.1 from free model list as the free trial has ended
- Improved image display in MCP responses
- Auto-sync remote MCP servers from remote config to local settings
## [3.48.0]
### Added
- Add Skills system for reusable, on-demand agent instructions
- Add new websearch tooling in Cline provider
- Add zai-glm-4.7 to Cerebras model list
- Add model refresh and improve reasoning support for Vercel AI Gateway
### Fixed
- Revert #8341 due to regressions in diff view/document truncation (see #8423, #8429)
- Fixed extension crash when using context menu selector
## [3.47.0]
### Added
- Added experimental support for Background Edits (allows editing files in background without opening the diff view)
- Updated free model to MiniMax M2.1 (replacing MiniMax M2)
- Added support for Azure based identity authentication in OpenAI Compatible provider and Azure OpenAI
- Add `supportsReasoning` property to Baseten models
### Fixed
- Prevent expired token usage in authenticated requests
- Exclude binary files without extensions from diffs
- Preserve file endings and trailing newlines
- Fix Cerebras rate limiting
- Fix Auto Compact for Claude Code provider
- Make Workspace and Favorites history filters independent
- Fix remote MCP server connection failures (404 response handling)
- Disable native tool calling for Deepseek 3.2 speciale
- Show notification instead of opening sidebar on update
- Fix Baseten model selector
### Refactored
- Modify prompts for parallel tool usage in Claude and Gemini 3 models
## [3.46.1]
### Fixed
- Remove GLM 4.6 from free models
## [3.46.0]
### Added
- Added GLM 4.7 model
- Enhanced background terminal execution with command tracking, log file output, zombie process prevention (10-minute timeout), and clickable log paths in UI
- Apply Patch tool for GPT-5+ models (replacing current diff edit tools)
### Fixed
- Duplicate error messages during streaming for Diff Edit tool when Parallel Tool Calling is not enabled
- Banner carousel styling and dismiss functionality
- Typos in Gemini system prompt overrides
- Model picker favorites ordering, star toggle, and keyboard navigation for OpenRouter and Vercel AI Gateway providers
- Fetch remote config values from the cache
### Refactored
- Anthropic handler to use metadata for reasoning support
- Bedrock provider to use metadata for reasoning support
## [3.45.1]
- Fixed MCP settings race condition where toggling auto-approve or changing timeout settings would cause the UI to flash and revert
## [3.45.0]
- Added Gemini 3 Flash Preview model
## [3.44.2]
- Polished the model picker UI with checkmarks for selected models, tooltips on Plan/Act tabs, and consistent arrow pointers across all popup modals
- Improved WhatsNew modal responsiveness and cleaned up redundant UI elements
- Fixed GLM models outputting garbled text in thinking tags—reasoning is now properly disabled for these models
## [3.44.1]
- Fixed a critical bug where local MCP servers stopped connecting after v3.42.0—all user-configured stdio-based MCP servers should now work again
- Fixed remotely configured API keys not being extracted correctly for enterprise users
- Added support for dynamic tool instructions that adapt based on runtime context, laying groundwork for future context-aware features
## [3.44.0]
## Added
- Updating minor version to show a proper banner for the release
## [3.43.1]
### Patch Changes
- Fix GLM-4.6 Model reference id
## [3.43.0]
### Added
- GLM-4.6
- kat-coder-pro
- Add parsing of env variable patterns to the mcpconfig.json
### Fixed
- TLS Proxy support issues for VSCode
- Add supportsReasoning flag to OpenAI reasoning models
- Fix thinking not available for some models in the OpenAI provider
- Fix invalid signature field issues when switching between Gemini and Anthropic providers
- Extract OpenRouter model filtering into reusable utility and use it in different model pickers
- Fix a11y for auto approve checkbox
- Improve ModelPickerModal provider list layout
### Refactored
- Migrate WhatsNewModal to new shared dialogue component
## [3.42.0]
### Added
- Expose `getAvailableSlashCommands` rpc endpoint to UI clients
- Made slash command menu and context menu accessible and screenreader-friendly
- Made expanding/collapsing UI components accessible
### Fixed
- Devstral OpenRouter model ID and routing issues
- Incorrect pricing display for Devstral model in the extension
## [3.41.0]
### Added
- OpenAI GPT-5.2
- Devstral-2512 (formerly stealth model "Microwave")
- Improvements to chat modal model picker
- Amazon Nova 2 Lite
- DeepSeek 3.2 to native tool calling allow list
- Responses API support for Codex models in OpenAI provider (requires native tool calling)
- Xmas Special Santa Cline
- Welcome screen UI enhancements
### Fixed
- Initial checkpoint commit now non-blocking for improved responsiveness in large repositories
- Gemini Vertex models erroring when thinking parameters are not supported
- Restrictive file permissions for secrets.json
- Ollama streaming requests not aborting when task is cancelled
### Refactored
- OpenAI provider to centralize temperature configuration and include missing GPT-5 model settings
- OpenAI native handler to use metadata for model capabilities
- Vertex provider to use metadata for model capabilities
## [3.40.2]
- Fix logout on network errors during token refresh (e.g., opening laptop while offline)
## [3.40.1]
- Fix cost calculation display for Anthropic API requests
## [3.40.0]
- Fix highlighted text flashing when task header is collapsed
- Add X-Cerebras-3rd-Party-Integration header to Cerebras API requests
- Add microwave family system prompt configuration
- Remove tooltips from auto approve menu
- Fix Standalone, ensure cwd is the install dir to find resources reliably
- Fix a bug where terminal commands with double quotes are broken when "Terminal Execution Mode" is set to "Background Exec"
- Add support for slash commands anywhere in a message, not just at the beginning. This matches the behavior of @ mentions for a more flexible input experience.
- Add bottom padding to the last message to fix last response text getting cut off by auto approve settings bar.
- Add default thinking level for Gemini 3 Pro models in Gemini provider
## [3.39.2]
- Fix for microwave model and thinking settings
## [3.39.1]
- Fix Openrouter and Cline Provider model info
## [3.39.0]
- Add Explain Changes feature
- Add microwave Stealth model
- Add Tabbed Model Picker with Recommended and Free tabs
- Add support to View remote rules and workflows in the editor
- Enable NTC (Native Tool Calling) by default
- Bug fixes and improvements for LiteLLM provider
## [3.38.3]
- Task export feature now opens the task directory, allowing easy access to the full task files
- Add Grok 4.1 and Grok Code to XAI provider
- Enabled native tool calling for Baseten and Kimi K2 models
- Add thinking level to Gemini 3.0 Pro preview
- Expanded Hooks functionality
- Removed Task Timeline from Task Header
- Bug fix for slash commands
- Bug fixes for Vertex provider
- Bug fixes for thinking/reasoning issues across multiple providers when using native tool calling
- Bug fixes for terminal usage on Windows devices
## [3.38.2]
- Add Claude Opus 4.5
## [3.38.1]
### Fixed
- Fixed handling of 'signature' field in sanitizeAnthropicContentBlock to properly preserve it when thinking is enabled, as required by Anthropic's API.
## [3.38.0]
### Added
- Gemini 3 Pro Preview model
- AquaVoice Avalon model for voice-to-text dictation
### Fixed
- Automatic context truncation when AWS Bedrock token usage rate limits are exceeded
- Removed new_task tool from system prompts, updated slash command prompts, and added helper function for native tool calling validation
## [3.37.1]
- Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.
- Add AGENTS.md support
- feat(models): Add free minimax/mimax-m2 model to the model picker
## [3.37.0]
## Added
### Added
- GPT-5.1 with model-specific prompting: tailored system prompts, tool usage, focus chain, and deep-planning optimizations
- Nous Research provider with Hermes 4 model family and custom system prompts
@@ -18,7 +292,7 @@
- Expanded HTTP proxy support throughout the codebase
- Improved focus chain prompting for frontier models (Anthropic, OpenAI, Gemini, xAI)
## Fixed
### Fixed
- Duplicate tool results prevention through existence checking
- XML entity escaping in model content processor
@@ -1463,4 +1737,4 @@ Add Opus 4.1 through Claude Code
## [0.0.6]
- Initial release
- Initial release
+2
View File
@@ -0,0 +1,2 @@
@.clinerules/general.md
@.clinerules/network.md
+20
View File
@@ -137,10 +137,30 @@ For example, when working with a local web server, you can use 'Restore Workspac
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### Worktrees: Parallel Development
Worktrees let you work on multiple branches simultaneously, each in its own folder. This enables Cline to work on tasks in parallel across separate VS Code windows, or lets Cline work independently while you continue coding in your main workspace.
Cline takes over your VS Code window while working on a task. With worktrees, you can:
- **Run Cline in parallel** - Have Cline work on multiple tasks simultaneously
- **Keep working while Cline works** - Let Cline handle a task in a separate worktree while you continue coding
- **Isolate experimental changes** - Test risky changes in a worktree without affecting your main branch
<!-- Transparent pixel to create line break after floating image -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## Contributing
To contribute to the project, start with our [Contributing Guide](CONTRIBUTING.md) to learn the basics. You can also join our [Discord](https://discord.gg/cline) to chat with other contributors in the `#contributors` channel. If you're looking for full-time work, check out our open positions on our [careers page](https://cline.bot/join-us)!
## Enterprise
Get the same Cline experience with enterprise-grade controls: SSO (SAML/OIDC), global policies and configuration, observability with audit trails, private networking (VPC/private link), and self-hosted or on-prem deployments, and enterprise support. Learn more at our [enterprise page](https://cline.bot/enterprise) or [talk to us](https://cline.bot/contact-sales).
## License
[Apache 2.0 © 2025 Cline Bot Inc.](./LICENSE)
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<metadata>
<json>
<![CDATA[
{
"fontFamily": "cline-bot",
"majorVersion": 1,
"minorVersion": 0,
"fontURL": "https://cline.bot",
"designerURL": "https://cline.bot",
"licenseURL": "https://cline.bot",
"version": "Version 1.0",
"fontId": "cline-bot",
"psName": "cline-bot",
"subFamily": "Regular",
"fullName": "cline-bot",
"description": "Font generated by IcoMoon."
}
]]>
</json>
</metadata>
<defs>
<font id="cline-bot" horiz-adv-x="1024">
<font-face units-per-em="1024" ascent="960" descent="-64" />
<missing-glyph horiz-adv-x="1024" />
<glyph unicode="&#x20;" horiz-adv-x="512" d="" />
<glyph unicode="&#xe900;" glyph-name="cline" data-tags="cline" horiz-adv-x="977" d="M964.553 383.11l-60.285 121.406v69.495c0 115.545-92.939 209.321-207.647 209.321h-102.986c7.536 15.071 11.722 32.654 11.722 51.074 0 64.471-51.912 116.383-115.545 116.383s-115.545-51.912-115.545-116.383 4.186-35.166 11.722-51.074h-102.986c-114.708 0-207.647-93.776-207.647-209.321v-69.495l-61.959-121.406c-5.861-11.722-5.861-26.793 0-38.515l61.959-119.732v-69.495c0-115.545 92.939-209.321 207.647-209.321h415.294c114.708 0 207.647 93.776 207.647 209.321v69.495l60.285 119.732c5.861 11.722 5.861 25.956 0 38.515v0zM426.178 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132zM731.787 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132z" />
</font></defs></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.
+1
View File
@@ -70,3 +70,4 @@ Apache-2.0 - see [LICENSE](https://github.com/cline/cline/blob/main/LICENSE) for
- Report issues: [GitHub Issues](https://github.com/cline/cline/issues)
- Community: [GitHub Discussions](https://github.com/cline/cline/discussions)
- Documentation: [docs.cline.bot](https://docs.cline.bot)
- Cline CLI Architecture: [architecture.md](./architecture.md)
+292
View File
@@ -0,0 +1,292 @@
# Cline CLI Architecture
The CLI is a **standalone terminal interface** for the Cline AI coding assistant, written in Go. It provides the same autonomous coding capabilities as the VS Code extension but runs entirely in the terminal.
## High-Level Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ User Terminal │
└─────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ cline (Go binary) │
│ cmd/cline/main.go │
│ • Cobra CLI commands (task, auth, config, instance, etc.) │
│ • Interactive input via Bubble Tea │
│ • Streaming output with markdown rendering │
└─────────────────────────────────────────────────────────────────────────┘
│ gRPC (50052) │ starts subprocess
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ cline-core │◄────────────────►│ cline-host │
│ (Node.js) │ gRPC (51052) │ (Go binary) │
│ │ │ cmd/cline-host/main.go│
│ • AI/LLM orchestration │ │ │
│ • Tool execution │ │ • Workspace paths │
│ • Task state mgmt │ │ • File diff editing │
│ • Message handling │ │ • Clipboard access │
└─────────────────────────┘ │ • Environment info │
│ └─────────────────────────┘
│ SQLite (self-registration)
┌─────────────────────────────────────────────────────────────────────────┐
│ ~/.cline/data/locks/locks.db │
│ (Instance registry - core self-registers on startup) │
└─────────────────────────────────────────────────────────────────────────┘
```
## Entry Points (`cmd/`)
### `cmd/cline/main.go` - Main CLI
Cobra-based CLI with commands:
- **Root**: `cline [prompt]` - Start a task directly
- **task**: Create, send, view, list, pause, restore tasks
- **auth**: Authentication setup and provider configuration
- **config**: Read/write settings
- **instance**: Manage running Cline instances
- **logs**: View and clean log files
- **doctor**: System health check
### `cmd/cline-host/main.go` - Host Bridge Service
Separate gRPC server providing host environment operations to cline-core:
- Workspace paths
- File diff editing
- Clipboard access
- Shutdown coordination
---
## `pkg/cli/` Subsystems
### 1. `auth/` - Authentication System
Handles authentication with Cline service and BYO (Bring Your Own) API providers.
| File | Purpose |
| ------------------------- | ------------------------------------------------------------------------ |
| `auth_cline_provider.go` | OAuth login flow - opens browser, subscribes to auth callback stream |
| `auth_menu.go` | Interactive menu showing auth options based on current state |
| `auth_subscription.go` | gRPC stream subscription for auth status updates |
| `wizard_byo.go` | Interactive wizard for configuring BYO providers |
| `wizard_byo_bedrock.go` | AWS Bedrock-specific credential setup |
| `wizard_byo_oca.go` | Oracle Code Assist setup |
| `providers_list.go` | Retrieves configured providers from core state |
| `providers_byo.go` | Provider selection UI and field configuration |
| `models_*.go` | Model listing (static lists + dynamic fetch from OpenRouter/OpenAI/Ollama) |
**Flow**: User runs `cline auth` → Menu shows options → For BYO: wizard guides through provider/key/model selection → Config saved via gRPC to core.
---
### 2. `clerror/` - Error Handling
Parses and classifies API errors from the Cline service.
**Error Types:**
- `ErrorTypeAuth` - 401, bad API key
- `ErrorTypeBalance` - Insufficient credits
- `ErrorTypeRateLimit` - 429, quota exceeded
- `ErrorTypeNetwork` - Connection issues
- `ErrorTypeUnknown` - Catch-all
Extracts billing details (balance, spent, buy credits URL) from error responses.
---
### 3. `config/` - Configuration Management
| File | Purpose |
| --------------------- | -------------------------------------------------------------------------- |
| `manager.go` | gRPC interface for reading/writing settings via `UpdateSettingsCli` RPC |
| `settings_renderer.go`| Pretty-prints config values, censors sensitive fields (keys, secrets) |
Supports dot-notation paths: `cline config get auto-approval-settings.actions.read-files`
---
### 4. `display/` - Terminal Display System
The most complex subsystem - handles all visual output.
| File | Purpose |
| ----------------------- | -------------------------------------------------------------------- |
| `renderer.go` | Central coordinator with lipgloss styles, color methods, markdown delegation |
| `streaming.go` | Real-time streaming display with deduplication |
| `segment_streamer.go` | Streaming segments (header + body) with context-aware headers |
| `typewriter.go` | Character-by-character animation with variable delays |
| `markdown_renderer.go` | Glamour wrapper for terminal markdown rendering |
| `tool_renderer.go` | Tool operation formatting ("Cline is editing `file.ts`") |
| `tool_result_parser.go` | Parses structured tool results (file lists, search results) |
| `banner.go` | Session startup banner with version/model/workspace |
| `deduplicator.go` | MD5-based deduplication with 2-second window |
| `system_renderer.go` | Rich error/warning boxes for balance errors, auth failures |
| `ansi.go` | TTY detection, line clearing with escape codes |
---
### 5. `global/` - Global State Management
| File | Purpose |
| ------------------ | -------------------------------------------------------------------------- |
| `global.go` | Global config (paths, verbosity, output format), initialization |
| `registry.go` | Instance discovery via SQLite, health checking, default instance management|
| `cline-clients.go` | Starts cline-core + cline-host processes, port allocation, cleanup |
**Instance lifecycle:**
1. Find available port pair
2. Start `cline-host` on port+1000
3. Start `cline-core` on port
4. Wait for core to self-register in SQLite
5. Set as default if first instance
---
### 6. `handlers/` - Message Handlers
Routes incoming messages from cline-core to appropriate renderers.
| File | Purpose |
| ------------------ | --------------------------------------------------------------------- |
| `handler.go` | Handler registry with priority-based routing |
| `ask_handlers.go` | Approval requests: tool, command, followup, api_req_failed, etc. |
| `say_handlers.go` | Status messages: text, reasoning, command_output, tool, checkpoint, etc. |
Uses `DisplayContext` providing renderer access, state, and context flags (isLast, isPartial, isStreamingMode).
---
### 7. `output/` - Output Coordination
| File | Purpose |
| --------------------- | ----------------------------------------------------------------------- |
| `coordinator.go` | Coordinates streaming output with interactive input (saves/restores input state) |
| `input_model.go` | Bubble Tea model for rich input (message, approval, feedback types) |
| `slash_completion.go` | Autocomplete dropdown for slash commands |
**Key pattern:** When output needs to print while input is visible, the coordinator saves input state, clears the form, prints, then restores input.
---
### 8. `slash/` - Slash Command Registry
Central registry for commands like `/plan`, `/act`, `/cancel`:
- **CLI-local commands**: Handled directly by CLI
- **Backend commands**: Fetched from core via gRPC, filtered by `CliCompatible` flag
---
### 9. `sqlite/` - Instance Locking
Manages the distributed locking system:
- **Instance locks**: Track running Cline instances by address
- **File locks**: Coordinate file access across instances
- SQLite database created by cline-core, CLI reads/writes for discovery
---
### 10. `task/` - Task Management
| File | Purpose |
| ----------------------- | -------------------------------------------------------------------- |
| `manager.go` | Core orchestrator: create, cancel, resume, restore tasks; stream handling |
| `stream_coordinator.go` | Deduplication and turn management for dual streams |
| `input_handler.go` | Interactive input during follow mode (polling, approval detection) |
| `history_handler.go` | Direct disk access to `taskHistory.json` |
| `settings_parser.go` | Parse settings from CLI flags |
| `follow_options.go` | Configuration for follow behavior |
**Streaming:** Task manager subscribes to two gRPC streams:
1. `SubscribeToState` - Full state updates
2. `SubscribeToPartialMessage` - Streaming AI responses
---
### 11. `terminal/` - Terminal Handling
Enhanced keyboard protocol support and terminal configuration:
- Enables modifyOtherKeys and Kitty keyboard protocol
- Detects terminal type (VS Code, iTerm, Ghostty, Kitty, etc.)
- Auto-configures shift+enter keybindings for various terminals
---
### 12. `types/` - Type Definitions
| File | Purpose |
| -------------- | ----------------------------------------------------------------- |
| `messages.go` | `ClineMessage`, `AskType`, `SayType`, `ToolType` enums, proto conversion |
| `state.go` | `ConversationState` with thread-safe message access |
| `history.go` | `HistoryItem` matching taskHistory.json format |
---
### 13. `updater/` - Auto-Update
Background auto-update checking:
- 24-hour check interval (cached)
- Queries npm registry for newer versions
- Supports `latest` and `nightly` channels
- Runs `npm install -g cline` to update
---
## `pkg/common/` - Shared Types
| File | Purpose |
| --------------- | ------------------------------------------------------------ |
| `constants.go` | `SETTINGS_SUBFOLDER`, `DEFAULT_CLINE_CORE_PORT` |
| `schema.go` | SQL queries for instance/file locks |
| `types.go` | `CoreInstanceInfo`, `LockRow`, `DefaultCoreInstance` |
| `utils.go` | Port checking, health checks, address normalization, retry logic |
---
## `pkg/generated/` - Auto-Generated
| File | Purpose |
| --------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `providers.go` | Provider definitions (Anthropic, OpenAI, Bedrock, etc.) with field metadata and model specs - generated from TypeScript sources |
| `field_overrides.go` | Manual overrides for field filtering |
---
## `pkg/hostbridge/` - CLI-to-Core Bridge
This is the **reverse bridge** allowing cline-core to request host environment operations:
| File | Purpose |
| ----------------------- | ---------------------------------------------------- |
| `grpc_server.go` | Main server registering all services |
| `simple_workspace.go` | Workspace service: returns CWD as workspace path |
| `diff.go` | In-memory file diff editing with line-based operations |
| `env.go` | Clipboard access, version info, shutdown coordination |
| `window.go` | UI stubs (no-ops or console output) |
**Why this exists:** The same cline-core logic runs in VS Code and CLI. In VS Code, the "host" is the extension with editor APIs. In CLI, hostbridge emulates these capabilities with terminal-appropriate implementations.
---
## Key Design Decisions
1. **Two-process model:** `cline` CLI manages instances; `cline-core` is the actual AI engine (Node.js). This allows reusing the same core as the VS Code extension.
2. **Self-registration via SQLite:** `cline-core` registers itself in a SQLite database on startup. The CLI discovers instances by reading this database, enabling multi-instance support.
3. **Host bridge abstraction:** The `cline-host` process provides platform-specific operations (clipboard, workspace paths) via gRPC, allowing `cline-core` to remain host-agnostic.
4. **Streaming-first UI:** The CLI uses gRPC streaming to display AI responses in real-time with typewriter-style rendering.
5. **Dual stream handling:** Task manager subscribes to both state updates and partial messages, using deduplication to prevent duplicate rendering.
+5 -3
View File
@@ -14,8 +14,9 @@ import (
)
var (
port int
verbose bool
port int
verbose bool
workspaces []string
)
func main() {
@@ -28,6 +29,7 @@ func main() {
rootCmd.Flags().IntVarP(&port, "port", "p", 51052, "port to listen on")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging")
rootCmd.Flags().StringSliceVar(&workspaces, "workspace", nil, "workspace paths")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
@@ -39,7 +41,7 @@ func runServer(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Create gRPC hostbridge service
service := hostbridge.NewGrpcServer(port, verbose)
service := hostbridge.NewGrpcServer(port, verbose, workspaces)
// Handle graceful shutdown
ctx, cancel := context.WithCancel(ctx)
+74 -26
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"github.com/charmbracelet/huh"
@@ -25,18 +26,20 @@ var (
outputFormat string
// Task creation flags (for root command)
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
workspaces []string
)
func main() {
rootCmd := &cobra.Command{
Use: "cline [prompt]",
Short: "Cline CLI - AI-powered coding assistant",
Use: "cline [prompt]",
Short: "Cline CLI - AI-powered coding assistant",
Version: global.CliVersion,
Long: `A command-line interface for interacting with Cline AI coding assistant.
Start a new task by providing a prompt:
@@ -70,12 +73,23 @@ see the manual page: man cline`,
var instanceAddress string
// Validate workspace paths exist
if err := common.ValidateDirsExist(workspaces); err != nil {
return err
}
// Build the full workspace list: cwd first, then additional workspaces
allWorkspaces, err := buildWorkspaceList(workspaces)
if err != nil {
return fmt.Errorf("failed to build workspace list: %w", err)
}
// If --address flag not provided, start instance BEFORE getting prompt
if !cmd.Flags().Changed("address") {
if global.Config.Verbose {
fmt.Println("Starting new Cline instance...")
}
instance, err := global.Clients.StartNewInstance(ctx)
instance, err := global.Clients.StartNewInstance(ctx, allWorkspaces...)
if err != nil {
return fmt.Errorf("failed to start new instance: %w", err)
}
@@ -131,8 +145,8 @@ see the manual page: man cline`,
// If no prompt from args or stdin, show interactive input
if prompt == "" {
// Pass the mode flag to banner so it shows correct mode
prompt, err = promptForInitialTask(ctx, instanceAddress, mode)
// Pass the mode flag and workspaces to banner so it shows correct info
prompt, err = promptForInitialTask(ctx, instanceAddress, mode, allWorkspaces)
if err != nil {
// Check if user cancelled - exit cleanly without error
if err == huh.ErrUserAborted {
@@ -152,17 +166,20 @@ see the manual page: man cline`,
}
return cli.CreateAndFollowTask(ctx, prompt, cli.TaskOptions{
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: instanceAddress,
Verbose: verbose,
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: instanceAddress,
Verbose: verbose,
Workspaces: allWorkspaces,
})
},
}
rootCmd.SetVersionTemplate(cli.VersionString())
rootCmd.PersistentFlags().StringVar(&coreAddress, "address", fmt.Sprintf("localhost:%d", common.DEFAULT_CLINE_CORE_PORT), "Cline Core gRPC address")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "F", "rich", "output format (rich|json|plain)")
@@ -175,6 +192,7 @@ see the manual page: man cline`,
rootCmd.Flags().BoolVarP(&yolo, "yolo", "y", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVar(&yolo, "no-interactive", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVarP(&oneshot, "oneshot", "o", false, "full autonomous mode")
rootCmd.Flags().StringSliceVarP(&workspaces, "workspace", "w", nil, "additional workspace paths (can be specified multiple times)")
rootCmd.AddCommand(cli.NewTaskCommand())
rootCmd.AddCommand(cli.NewInstanceCommand())
@@ -189,9 +207,9 @@ see the manual page: man cline`,
}
}
func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string) (string, error) {
func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string, workspaces []string) (string, error) {
// Show session banner before the initial input
showSessionBanner(ctx, instanceAddress, modeFlag)
showSessionBanner(ctx, instanceAddress, modeFlag, workspaces)
var prompt string
@@ -233,7 +251,7 @@ func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string)
}
// showSessionBanner displays session info before initial prompt
func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string) {
func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string, workspaces []string) {
bannerInfo := display.BannerInfo{
Version: global.CliVersion,
Mode: modeFlag, // Use the mode from command flag, not state
@@ -244,10 +262,7 @@ func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string) {
bannerInfo.Mode = "plan"
}
// Get current working directory (this is what Cline will use)
if cwd, err := os.Getwd(); err == nil {
bannerInfo.Workdir = cwd
}
bannerInfo.Workdirs = workspaces
// Get provider/model using auth functions (same logic as auth menu)
manager, err := cli.NewTaskManagerForAddress(ctx, instanceAddress)
@@ -345,4 +360,37 @@ func getContentFromStdinAndArgs(args []string) (string, error) {
}
return content.String(), nil
}
}
// buildWorkspaceList builds the full workspace list with cwd as the first entry
func buildWorkspaceList(additionalWorkspaces []string) ([]string, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("failed to get current working directory: %w", err)
}
// Start with cwd
workspaces := []string{cwd}
// Add additional workspaces, avoiding duplicates
for _, ws := range additionalWorkspaces {
// Normalize the path
absPath, err := common.AbsPath(ws)
if err != nil {
return nil, fmt.Errorf("failed to resolve workspace path %s: %w", ws, err)
}
// Skip if it's the same as cwd
if absPath == cwd {
continue
}
// Check for duplicates
isDuplicate := slices.Contains(workspaces, absPath)
if !isDuplicate {
workspaces = append(workspaces, absPath)
}
}
return workspaces, nil
}
+1 -1
View File
@@ -1,6 +1,6 @@
module github.com/cline/cli
go 1.23.0
go 1.24.0
require (
github.com/atotto/clipboard v0.1.4
+26
View File
@@ -70,6 +70,10 @@ When using the instant task syntax **cline "prompt"** the following options are
: Starting mode. Options: **act** (default), **plan**
**-w**, **\--workspace** *path*
: Additional workspace paths. Can be specified multiple times to include multiple directories. The current working directory is always included as the first workspace. Example: cline -w /path/to/other/project "refactor shared code"
# GLOBAL OPTIONS
These options apply to all subcommands:
@@ -78,6 +82,28 @@ These options apply to all subcommands:
: Output format. Options: **rich** (default), **json**, **plain**
When you use **-F json**, the CLI prints each client message as JSON.
Each message is a **ClineMessage** object.
Required fields:
- **type**: "ask" or "say"
- **text**: message text
- **ts**: Unix epoch timestamp in milliseconds
Optional fields (omitted when empty):
- **reasoning**: reasoning text
- **say**: say subtype (present when type is "say")
- **ask**: ask subtype (present when type is "ask")
- **partial**: streaming flag
- **images**: list of image URIs
- **files**: list of file paths
- **lastCheckpointHash**: git checkpoint hash
- **isCheckpointCheckedOut**: checkpoint checkout flag
- **isOperationOutsideWorkspace**: workspace safety flag
**-h**, **\--help**
: Display help information for the command.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cline",
"version": "1.0.3",
"version": "1.0.9",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"main": "cline-core.js",
"bin": {
+43 -37
View File
@@ -47,7 +47,7 @@ func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*Pro
}
// Parse state_json as map[string]interface{}
var stateData map[string]interface{}
var stateData map[string]any
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
@@ -57,7 +57,7 @@ func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*Pro
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
if !ok {
if global.Config.Verbose {
fmt.Println("[DEBUG] No apiConfiguration found in state")
@@ -128,11 +128,11 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
modelID := getProviderSpecificModelID(r.apiConfig, "plan", provider)
// Determine if credentials exist
hasCreds := checkAPIKeyExists(r.apiConfig, provider)
hasCreds := checkCredentialsExists(r.apiConfig, provider)
// Determine readiness: OCA uses auth state presence; others need creds and model
if provider == cline.ApiProvider_OCA {
state, _ := GetLatestOCAState(context.Background(), 2 *time.Second)
state, _ := GetLatestOCAState(context.Background(), 2*time.Second)
if state == nil || state.User == nil {
continue
}
@@ -156,7 +156,7 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
Mode: "Ready",
Provider: provider,
ModelID: modelID,
HasAPIKey: checkAPIKeyExists(r.apiConfig, provider),
HasAPIKey: checkCredentialsExists(r.apiConfig, provider),
BaseURL: baseURL,
})
seenProviders[provider] = true
@@ -192,7 +192,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
modelID := getProviderSpecificModelID(stateData, mode, provider)
// Check if API key exists
hasAPIKey := checkAPIKeyExists(stateData, provider)
hasCredentials := checkCredentialsExists(stateData, provider)
// Get base URL for Ollama (can be shown publicly)
baseURL := ""
@@ -206,7 +206,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
Mode: capitalizeMode(mode),
Provider: provider,
ModelID: modelID,
HasAPIKey: hasAPIKey,
HasAPIKey: hasCredentials,
BaseURL: baseURL,
}
}
@@ -215,7 +215,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
// Returns (provider, ok) where ok is false if the provider is unknown
func mapProviderStringToEnum(providerStr string) (cline.ApiProvider, bool) {
normalizedStr := strings.ToLower(providerStr)
// Map string values to enum values
switch normalizedStr {
case "anthropic":
@@ -303,23 +303,27 @@ func getProviderSpecificModelID(stateData map[string]interface{}, mode string, p
return modelID
}
// checkAPIKeyExists checks if API key field exists in state (never retrieve actual key)
func checkAPIKeyExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// checkCredentialsExists checks if API key field exists in state (never retrieve actual key)
func checkCredentialsExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// Get field mapping from centralized function
fields, err := GetProviderFields(provider)
if err != nil {
return false
}
keyField := fields.APIKeyField
// Check if the key exists and is not empty
if value, ok := stateData[keyField]; ok {
if value, ok := stateData[fields.APIKeyField]; ok {
if str, ok := value.(string); ok && str != "" {
return true
}
}
if value, ok := stateData[fields.UseProfileField]; ok {
if hasProfileField, ok := value.(bool); ok && hasProfileField {
return true
}
}
return false
}
@@ -438,13 +442,13 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
stateJSON := state.StateJson
// Parse state_json as map[string]interface{}
var stateData map[string]interface{}
var stateData map[string]any
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
if !ok {
verboseLog("[DEBUG] No apiConfiguration found in state")
verboseLog("[DEBUG] Available keys in stateData: %v", getMapKeys(stateData))
@@ -469,36 +473,38 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
// Check each BYO provider for API key presence
providersToCheck := []struct {
provider cline.ApiProvider
keyField string
provider cline.ApiProvider
keyFields []string
}{
{cline.ApiProvider_ANTHROPIC, "apiKey"},
{cline.ApiProvider_OPENAI, "openAiApiKey"},
{cline.ApiProvider_OPENAI_NATIVE, "openAiNativeApiKey"},
{cline.ApiProvider_OPENROUTER, "openRouterApiKey"},
{cline.ApiProvider_XAI, "xaiApiKey"},
{cline.ApiProvider_BEDROCK, "awsAccessKey"},
{cline.ApiProvider_GEMINI, "geminiApiKey"},
{cline.ApiProvider_OLLAMA, "ollamaBaseUrl"}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, "cerebrasApiKey"},
{cline.ApiProvider_HICAP, "hicapApiKey"},
{cline.ApiProvider_NOUSRESEARCH, "nousResearchApiKey"},
{cline.ApiProvider_ANTHROPIC, []string{"apiKey"}},
{cline.ApiProvider_OPENAI, []string{"openAiApiKey"}},
{cline.ApiProvider_OPENAI_NATIVE, []string{"openAiNativeApiKey"}},
{cline.ApiProvider_OPENROUTER, []string{"openRouterApiKey"}},
{cline.ApiProvider_XAI, []string{"xaiApiKey"}},
{cline.ApiProvider_BEDROCK, []string{"awsAccessKey", "awsUseProfile"}},
{cline.ApiProvider_GEMINI, []string{"geminiApiKey"}},
{cline.ApiProvider_OLLAMA, []string{"ollamaBaseUrl"}}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, []string{"cerebrasApiKey"}},
{cline.ApiProvider_HICAP, []string{"hicapApiKey"}},
{cline.ApiProvider_NOUSRESEARCH, []string{"nousResearchApiKey"}},
}
for _, providerCheck := range providersToCheck {
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyField)
if value, ok := apiConfig[providerCheck.keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyFields)
for _, keyField := range providerCheck.keyFields {
if value, ok := apiConfig[keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
break
}
} else {
verboseLog("[DEBUG] Key %s not found", keyField)
}
} else {
verboseLog("[DEBUG] Key %s not found", providerCheck.keyField)
}
}
verboseLog("[DEBUG] Total configured providers: %d", len(configuredProviders))
for _, p := range configuredProviders {
verboseLog("[DEBUG] - %s", GetProviderDisplayName(p))
@@ -54,6 +54,7 @@ type ProviderFields struct {
// Provider-specific additional model ID fields
PlanModeProviderSpecificModelIDField string // e.g., "planModeOpenRouterModelId"
ActModeProviderSpecificModelIDField string // e.g., "actModeOpenRouterModelId"
UseProfileField string // e.g., "awsUseProfile" (for bedrock) (optional, empty if not applicable)
}
// GetProviderFields returns the field mapping for a given provider
@@ -96,6 +97,7 @@ func GetProviderFields(provider cline.ApiProvider) (ProviderFields, error) {
case cline.ApiProvider_BEDROCK:
return ProviderFields{
UseProfileField: "awsUseProfile",
APIKeyField: "awsAccessKey",
PlanModeModelIDField: "planModeApiModelId",
ActModeModelIDField: "actModeApiModelId",
@@ -356,6 +358,9 @@ func AddProviderPartial(ctx context.Context, manager *task.Manager, provider cli
if openRouterInfo, ok := modelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := modelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
@@ -424,6 +429,9 @@ func UpdateProviderPartial(ctx context.Context, manager *task.Manager, provider
if openRouterInfo, ok := updates.ModelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := updates.ModelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
+3 -3
View File
@@ -190,7 +190,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
}
// Step 3: Select model
modelID, _, err := pw.selectModel(cline.ApiProvider_OCA, "")
modelID, modelInfo, err := pw.selectModel(cline.ApiProvider_OCA, "")
if err != nil {
return fmt.Errorf("model selection failed: %w", err)
}
@@ -198,7 +198,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
// Step 4: Apply the OCA model configuration and set as active
updates := ProviderUpdatesPartial{
ModelID: &modelID,
ModelInfo: nil,
ModelInfo: modelInfo,
}
if err := UpdateProviderPartial(pw.ctx, pw.manager, cline.ApiProvider_OCA, updates, true); err != nil {
@@ -517,7 +517,7 @@ func (pw *ProviderWizard) applyModelChange(provider cline.ApiProvider, modelID s
ModelInfo: modelInfo,
}
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, false)
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, true)
}
// SwitchToBYOProvider switches to a BYO provider that's already configured.
+22 -15
View File
@@ -15,23 +15,23 @@ import (
// BedrockConfig holds all AWS Bedrock-specific configuration fields
type BedrockConfig struct {
// Profile authentication fields
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
// Optional features
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
// Authentication method (always "profile")
Authentication string // Always set to "profile"
Authentication string // Always set to "profile"
// Legacy fields (no longer used in profile-only flow)
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
}
// PromptForBedrockConfig displays a profile-first authentication form for Bedrock configuration
@@ -130,7 +130,12 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build the API configuration with all Bedrock fields
apiConfig := &cline.ModelsApiConfiguration{}
// Set model ID fields
// Set provider for both Plan and Act modes
bedrockProvider := cline.ApiProvider_BEDROCK
apiConfig.PlanModeApiProvider = &bedrockProvider
apiConfig.ActModeApiProvider = &bedrockProvider
// Set model ID field - this is the primary model ID used by Cline Core
apiConfig.PlanModeApiModelId = proto.String(modelID)
apiConfig.ActModeApiModelId = proto.String(modelID)
apiConfig.PlanModeAwsBedrockCustomModelBaseId = proto.String(modelID)
@@ -166,6 +171,8 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build field mask including all fields we're setting (excluding access keys)
fieldPaths := []string{
"planModeApiProvider",
"actModeApiProvider",
"planModeApiModelId",
"actModeApiModelId",
"planModeAwsBedrockCustomModelBaseId",
+1 -1
View File
@@ -92,7 +92,6 @@ func (m *Manager) ListSettings(ctx context.Context) error {
"telemetrySetting",
"planActSeparateModelsSetting",
"enableCheckpointsSetting",
"mcpMarketplaceEnabled",
"shellIntegrationTimeout",
"terminalReuseEnabled",
"mcpResponsesCollapsed",
@@ -111,6 +110,7 @@ func (m *Manager) ListSettings(ctx context.Context) error {
"dictationSettings",
"autoCondenseThreshold",
"autoApprovalSettings",
"hooksEnabled",
}
// Render each field using the renderer
+2 -3
View File
@@ -77,10 +77,9 @@ func RenderField(key string, value interface{}, censor bool) error {
case "mode", "telemetrySetting", "preferredLanguage", "customPrompt",
"defaultTerminalProfile", "mcpDisplayMode", "openaiReasoningEffort",
"planActSeparateModelsSetting", "enableCheckpointsSetting",
"mcpMarketplaceEnabled", "terminalReuseEnabled",
"mcpResponsesCollapsed", "strictPlanModeEnabled",
"terminalReuseEnabled", "mcpResponsesCollapsed", "strictPlanModeEnabled",
"useAutoCondense", "yoloModeToggled", "shellIntegrationTimeout",
"terminalOutputLineLimit", "autoCondenseThreshold":
"terminalOutputLineLimit", "autoCondenseThreshold", "hooksEnabled":
fmt.Printf("%s: %s\n", camelToKebab(key), formatValue(value, key, censor))
return nil
+18 -130
View File
@@ -1,22 +1,19 @@
package display
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/common"
)
// BannerInfo contains information to display in the session banner
type BannerInfo struct {
Version string
Provider string
ModelID string
Workdir string
Mode string
Version string
Provider string
ModelID string
Workdirs []string // workspace directories
Mode string
}
// RenderSessionBanner renders a nice banner showing version, model, and workspace info
@@ -81,131 +78,22 @@ func RenderSessionBanner(info BannerInfo) string {
// Model line - dim gray
if info.Provider != "" && info.ModelID != "" {
lines = append(lines, dimStyle.Render(info.Provider+"/"+shortenPath(info.ModelID, 30)))
lines = append(lines, dimStyle.Render(info.Provider+"/"+common.ShortenPath(info.ModelID, 30)))
}
// Workspace line - dim gray
if info.Workdir != "" {
lines = append(lines, dimStyle.Render(shortenPath(info.Workdir, 45)))
for _, wd := range info.Workdirs {
lines = append(lines, dimStyle.Render(common.ShortenPath(wd, 45)))
}
// Checkpoint warning for multi-root workspaces
if len(info.Workdirs) > 1 {
warningStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("3")). // Yellow warning color
Italic(true)
lines = append(lines, "")
lines = append(lines, warningStyle.Render("⚠ Checkpoints disabled for multi-root workspaces"))
}
content := lipgloss.JoinVertical(lipgloss.Left, lines...)
return boxStyle.Render(content)
}
// shortenPath shortens a filesystem path to fit within maxLen
func shortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
// ExtractBannerInfoFromState extracts banner info from state JSON
func ExtractBannerInfoFromState(stateJSON, version string) (BannerInfo, error) {
var state map[string]interface{}
if err := json.Unmarshal([]byte(stateJSON), &state); err != nil {
return BannerInfo{}, fmt.Errorf("failed to parse state JSON: %w", err)
}
info := BannerInfo{
Version: version,
}
// Extract mode
if mode, ok := state["mode"].(string); ok {
info.Mode = mode
}
// Extract workspace roots
if workspaceRoots, ok := state["workspaceRoots"].([]interface{}); ok && len(workspaceRoots) > 0 {
if root, ok := workspaceRoots[0].(map[string]interface{}); ok {
if path, ok := root["path"].(string); ok {
info.Workdir = path
}
}
}
// Extract API configuration to get provider/model
if apiConfig, ok := state["apiConfiguration"].(map[string]interface{}); ok {
// Try common keys for provider and model (both camelCase and lowercase variants)
providerKeys := []string{"apiProvider", "api_provider"}
modelKeys := []string{"apiModelId", "api_model_id"}
// Try to extract provider
for _, key := range providerKeys {
if provider, ok := apiConfig[key].(string); ok && provider != "" {
info.Provider = provider
break
}
}
// Try to extract model ID
for _, key := range modelKeys {
if modelID, ok := apiConfig[key].(string); ok && modelID != "" {
info.ModelID = shortenModelID(modelID)
break
}
}
}
return info, nil
}
// shortenModelID shortens long model IDs for display
func shortenModelID(modelID string) string {
// Remove date suffixes only if they're at the end (e.g., -20241022)
// Check if the model ID ends with -YYYYMMDD pattern
if len(modelID) > 9 {
suffix := modelID[len(modelID)-9:] // Last 9 chars: -20241022
if suffix[0] == '-' &&
(strings.HasPrefix(suffix[1:], "202") || strings.HasPrefix(suffix[1:], "201")) {
// Verify all remaining chars are digits
allDigits := true
for _, c := range suffix[1:] {
if c < '0' || c > '9' {
allDigits = false
break
}
}
if allDigits {
return modelID[:len(modelID)-9]
}
}
}
// If still too long, show first 40 chars
if len(modelID) > 40 {
return modelID[:37] + "..."
}
return modelID
}
+144
View File
@@ -0,0 +1,144 @@
package display
import (
"fmt"
"strings"
"github.com/cline/cli/pkg/cli/types"
)
// HookRenderer renders hook status messages in a CLI-native style.
//
// Goals:
// - Match ToolRenderers markdown look
// - Keep executions ungrouped
// - Render status + high-signal metadata (script paths, error summary)
//
// Note: hook stdout/stderr currently arrives as separate `hook_output_stream` messages.
// The CLI suppresses those by default and prints them only in --verbose mode.
// Future work could group streamed output under the corresponding hook block.
//
// It returns markdown (or rendered markdown when enabled); callers should print the
// returned string.
type HookRenderer struct {
mdRenderer *MarkdownRenderer
outputFormat string
}
func NewHookRenderer(mdRenderer *MarkdownRenderer, outputFormat string) *HookRenderer {
return &HookRenderer{mdRenderer: mdRenderer, outputFormat: outputFormat}
}
func (hr *HookRenderer) RenderHookStatus(h types.HookMessage) string {
statusText := strings.TrimSpace(h.Status)
if statusText == "" {
statusText = "unknown"
}
// Header: aligned with ToolRenderers phrasing so transcripts scan consistently.
// Example: "### Cline hook completed: PreToolUse (tool: read_file) (exit 0)"
var headerBuilder strings.Builder
headerBuilder.WriteString(fmt.Sprintf("### Cline hook %s: %s", statusText, h.HookName))
if h.ToolName != "" {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(tool: %s)", h.ToolName))
}
if statusText == "failed" && h.ExitCode != 0 {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(exit %d)", h.ExitCode))
}
header := headerBuilder.String()
var lines []string
lines = append(lines, header)
// Pending tool info (PreToolUse): show one high-signal line directly under the header.
if h.PendingToolInfo != nil {
if pending := hr.formatPendingToolInfo(h.PendingToolInfo); pending != "" {
lines = append(lines, fmt.Sprintf("- Pending: %s", pending))
}
}
// Script paths: one per line.
paths := make([]string, 0, len(h.ScriptPaths))
for _, p := range h.ScriptPaths {
p = strings.TrimSpace(p)
if p != "" {
paths = append(paths, p)
}
}
if len(paths) == 0 {
// Fallback when no script paths are provided.
lines = append(lines, "- *(no hook scripts found)*")
} else {
for _, p := range paths {
lines = append(lines, fmt.Sprintf("- Running hook: `%s`", p))
}
}
// On failure, show a minimal summary (full stderr reserved for verbose).
if statusText == "failed" && h.Error != nil {
if msg := strings.TrimSpace(h.Error.Message); msg != "" {
lines = append(lines, fmt.Sprintf("- Error: %s", msg))
}
// If we have a specific script path, include it as a hint.
if sp := strings.TrimSpace(h.Error.ScriptPath); sp != "" {
lines = append(lines, fmt.Sprintf("- Script: `%s`", sp))
}
}
markdown := strings.Join(lines, "\n")
return hr.renderMarkdown(markdown)
}
func (hr *HookRenderer) formatPendingToolInfo(info *types.ToolInfo) string {
if info == nil {
return ""
}
tool := strings.TrimSpace(info.Tool)
if tool == "" {
return ""
}
// Keep this intentionally compact and readable.
// Format: "<tool> <identifier>" where identifier is the most relevant param.
var ident string
switch {
case strings.TrimSpace(info.Path) != "":
ident = strings.TrimSpace(info.Path)
case strings.TrimSpace(info.Command) != "":
ident = strings.TrimSpace(info.Command)
case strings.TrimSpace(info.Url) != "":
ident = strings.TrimSpace(info.Url)
case strings.TrimSpace(info.McpTool) != "" && strings.TrimSpace(info.McpServer) != "":
ident = fmt.Sprintf("%s %s", strings.TrimSpace(info.McpServer), strings.TrimSpace(info.McpTool))
case strings.TrimSpace(info.ResourceUri) != "":
ident = strings.TrimSpace(info.ResourceUri)
case strings.TrimSpace(info.Regex) != "":
ident = strings.TrimSpace(info.Regex)
default:
ident = ""
}
if ident != "" {
return fmt.Sprintf("%s %s", tool, ident)
}
return tool
}
func (hr *HookRenderer) renderMarkdown(markdown string) string {
// Align with ToolRenderer: in plain mode or non-TTY, return markdown as-is.
if hr.outputFormat == "plain" || !isTTY() {
return markdown
}
if hr.mdRenderer == nil {
return markdown
}
rendered, err := hr.mdRenderer.Render(markdown)
if err != nil {
return markdown
}
return rendered
}
+69
View File
@@ -0,0 +1,69 @@
package display
import (
"strings"
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestHookRenderer_RenderHookStatus_FailedShowsErrorAndScript(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "execute_command",
Status: "failed",
ExitCode: 2,
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
Error: &types.HookError{
Message: "boom",
ScriptPath: "repo/.clinerules/hooks/PreToolUse",
},
})
if !strings.Contains(msg, "### Cline hook failed: PreToolUse") {
t.Fatalf("expected header in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Error: boom") {
t.Fatalf("expected error line in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Script: `repo/.clinerules/hooks/PreToolUse`") {
t.Fatalf("expected script line in rendered output, got: %q", msg)
}
}
func TestHookRenderer_RenderHookStatus_PendingToolInfoAppearsDirectlyUnderHeader(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "write_to_file",
Status: "running",
PendingToolInfo: &types.ToolInfo{
Tool: "write_to_file",
Path: "src/foo.ts",
},
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
})
header := "### Cline hook running: PreToolUse"
pending := "- Pending: write_to_file src/foo.ts"
runningHook := "- Running hook: `repo/.clinerules/hooks/PreToolUse`"
headerIdx := strings.Index(msg, header)
if headerIdx == -1 {
t.Fatalf("expected header %q in output, got: %q", header, msg)
}
pendingIdx := strings.Index(msg, pending)
if pendingIdx == -1 {
t.Fatalf("expected pending line %q in output, got: %q", pending, msg)
}
runningIdx := strings.Index(msg, runningHook)
if runningIdx == -1 {
t.Fatalf("expected running hook line %q in output, got: %q", runningHook, msg)
}
if !(headerIdx < pendingIdx && pendingIdx < runningIdx) {
t.Fatalf("expected header < pending < runningHook ordering, got indexes header=%d pending=%d running=%d\nfull=%q", headerIdx, pendingIdx, runningIdx, msg)
}
}
+13 -3
View File
@@ -39,9 +39,12 @@ func NewStreamingSegment(sayType, prefix string, mdRenderer *MarkdownRenderer, s
// Render rich header immediately when creating segment (if in rich mode and TTY)
if shouldMarkdown && outputFormat != "plain" && isTTY() {
header := ss.generateRichHeader()
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
// Skip empty headers.
if strings.TrimSpace(header) != "" {
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
}
}
return ss
@@ -110,6 +113,9 @@ func (ss *StreamingSegment) renderFinal(currentBuffer string) {
if err := json.Unmarshal([]byte(currentBuffer), &tool); err == nil {
bodyContent = ss.toolRenderer.GenerateToolContentBody(&tool)
}
} else if ss.sayType == string(types.SayTypeHookStatus) {
// Hooks are rendered via the state stream; nothing to render here.
bodyContent = ""
} else if ss.sayType == string(types.SayTypeCommand) {
// Command output
bodyContent = "```shell\n" + currentBuffer + "\n```"
@@ -160,6 +166,10 @@ func (ss *StreamingSegment) generateRichHeader() string {
case string(types.SayTypeTool):
return ss.generateToolHeader()
case string(types.SayTypeHookStatus):
// Hooks are rendered from the state stream; dont emit a partial-stream header.
return ""
case "ask":
// Check the specific ask type
@@ -0,0 +1,20 @@
package display
import (
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestStreamingSegment_generateRichHeader_HookIsEmpty(t *testing.T) {
ss := &StreamingSegment{
sayType: string(types.SayTypeHookStatus),
prefix: "HOOK",
msg: &types.ClineMessage{},
}
header := ss.generateRichHeader()
if header != "" {
t.Fatalf("expected empty header for hook segments to avoid double-render, got: %q", header)
}
}
+19 -1
View File
@@ -38,6 +38,18 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
s.mu.Lock()
defer s.mu.Unlock()
// Render hooks from the state stream only (not partial stream) to avoid duplicates.
//
// Rationale: hook status messages are often updated/reordered by the backend (e.g. PreToolUse
// hooks are moved above the corresponding tool message). The state stream represents the
// authoritative, “final” message ordering, while the partial stream is best-effort for
// incremental display.
//
// Only suppress *partial* hook messages; complete ones still flow through dedupe.
if msg.Partial && msg.Say == string(types.SayTypeHookStatus) {
return nil
}
// Check for deduplication
if s.dedupe.IsDuplicate(msg) {
return nil
@@ -91,7 +103,11 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
func (s *StreamingDisplay) shouldRenderMarkdown(sayType string) bool {
switch sayType {
case string(types.SayTypeReasoning), string(types.SayTypeText), string(types.SayTypeCompletionResult), string(types.SayTypeTool), "ask":
case string(types.SayTypeReasoning),
string(types.SayTypeText),
string(types.SayTypeCompletionResult),
string(types.SayTypeTool),
"ask":
return true
default:
return false
@@ -110,6 +126,8 @@ func (s *StreamingDisplay) getPrefix(sayType string) string {
return "ASK"
case string(types.SayTypeCommand):
return "TERMINAL"
case string(types.SayTypeHookStatus):
return "HOOK"
default:
return strings.ToUpper(sayType)
}
+1 -1
View File
@@ -264,6 +264,6 @@ func (sr *SystemMessageRenderer) RenderInfo(title, message string) error {
func (sr *SystemMessageRenderer) RenderCheckpoint(timestamp string, id int64) error {
markdown := fmt.Sprintf("## [%s] Checkpoint created `%d`", timestamp, id)
rendered := sr.renderer.RenderMarkdown(markdown)
fmt.Printf(rendered)
fmt.Print(rendered)
return nil
}
+19 -3
View File
@@ -161,6 +161,14 @@ func (tr *ToolRenderer) generateToolHeader(tool *types.ToolMessage, verbTense st
}
return fmt.Sprintf("### Cline %s `%s`", action, tool.Path)
case string(types.ToolTypeWebSearch):
if verbTense == "wants to" {
action = "wants to search for"
} else {
action = "is searching for"
}
return fmt.Sprintf("### Cline %s `%s`", action, tool.Path)
case string(types.ToolTypeListCodeDefinitionNames):
if verbTense == "wants to" {
action = "wants to list code definitions in"
@@ -207,8 +215,8 @@ func (tr *ToolRenderer) GenerateToolContentPreview(tool *types.ToolMessage) stri
previewMd := fmt.Sprintf("```\n%s\n```", preview)
return tr.renderMarkdown(previewMd)
case string(types.ToolTypeReadFile), string(types.ToolTypeWebFetch), string(types.ToolTypeFileDeleted):
// No preview for read/fetch operations
case string(types.ToolTypeReadFile), string(types.ToolTypeWebFetch), string(types.ToolTypeWebSearch), string(types.ToolTypeFileDeleted):
// No preview for read/fetch/search operations
return ""
default:
@@ -243,7 +251,8 @@ func (tr *ToolRenderer) GenerateToolContentBody(tool *types.ToolMessage) string
string(types.ToolTypeListFilesRecursive),
string(types.ToolTypeListCodeDefinitionNames),
string(types.ToolTypeSearchFiles),
string(types.ToolTypeWebFetch):
string(types.ToolTypeWebFetch),
string(types.ToolTypeWebSearch):
// Use parser for structured output
preview := toolParser.ParseToolResult(tool)
return tr.renderMarkdown(preview)
@@ -330,6 +339,13 @@ func (tr *ToolRenderer) RenderCommandOutput(output string) string {
return result.String()
}
func (tr *ToolRenderer) RenderCommandPermissionDenied(command string) string {
command = strings.TrimSpace(command)
rendered := tr.renderMarkdown("### Command was denied")
message := fmt.Sprintf("Cline does not have permission to execute this command: `%s`", command)
return fmt.Sprintf("\n%s\n\n%s\n", rendered, message)
}
// RenderUserResponse renders user approval/rejection feedback
func (tr *ToolRenderer) RenderUserResponse(approved bool, feedback string) string {
var symbol, status string
+7 -76
View File
@@ -221,83 +221,12 @@ func (p *ToolResultParser) ParseCodeDefinitions(content string) string {
// ParseWebFetch formats webFetch tool results with content preview
func (p *ToolResultParser) ParseWebFetch(content, url string) string {
if content == "" {
return fmt.Sprintf("*Fetched content from %s (empty response)*", url)
}
return ""
}
lines := strings.Split(content, "\n")
var result strings.Builder
// Try to extract title
var title string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "#") && !strings.HasPrefix(trimmed, "##") {
title = strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
break
}
}
if title != "" {
result.WriteString(fmt.Sprintf("**Title:** %s\n\n", title))
}
// Show preview of content
result.WriteString("**Preview:**\n")
charCount := 0
maxChars := 500
previewLines := []string{}
for _, line := range lines {
// Skip markdown headers
if strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
trimmed := strings.TrimSpace(line)
if trimmed == "" {
continue
}
if charCount+len(trimmed) > maxChars {
break
}
previewLines = append(previewLines, trimmed)
charCount += len(trimmed)
}
result.WriteString(strings.Join(previewLines, " "))
result.WriteString("...\n\n")
// Extract sections
sections := []string{}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "##") {
section := strings.TrimSpace(strings.TrimPrefix(trimmed, "##"))
sections = append(sections, section)
if len(sections) >= 5 {
break
}
}
}
if len(sections) > 0 {
result.WriteString("**Sections Found:**\n")
for _, section := range sections {
result.WriteString(fmt.Sprintf("- %s\n", section))
}
result.WriteString("\n")
}
// Word count estimate
wordCount := len(strings.Fields(content))
result.WriteString(fmt.Sprintf("*[Full content: ~%s]*", p.formatWordCount(wordCount)))
return result.String()
// ParseWebSearch formats webSearch tool results
func (p *ToolResultParser) ParseWebSearch(content, query string) string {
return ""
}
// detectLanguage returns syntax highlighting language based on file extension
@@ -365,6 +294,8 @@ func (p *ToolResultParser) ParseToolResult(tool *types.ToolMessage) string {
return p.ParseCodeDefinitions(tool.Content)
case "webFetch":
return p.ParseWebFetch(tool.Content, tool.Path)
case "webSearch":
return p.ParseWebSearch(tool.Content, tool.Path)
default:
return tool.Content
}
+25 -16
View File
@@ -36,7 +36,7 @@ func (c *ClineClients) Initialize(ctx context.Context) error {
}
// StartNewInstance starts a new Cline instance and waits for cline-core to self-register
func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstanceInfo, error) {
func (c *ClineClients) StartNewInstance(ctx context.Context, workspaces ...string) (*common.CoreInstanceInfo, error) {
// Find available ports
corePort, hostPort, err := common.FindAvailablePortPair()
if err != nil {
@@ -48,7 +48,7 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
hostCmd, err := startClineHost(hostPort, workspaces)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -120,7 +120,7 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan
}
// 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) {
func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int, workspaces ...string) (*common.CoreInstanceInfo, error) {
// Find available host port (core port + 1000)
hostPort := corePort + 1000
coreAddress := fmt.Sprintf("localhost:%d", corePort)
@@ -135,7 +135,7 @@ func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int)
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
hostCmd, err := startClineHost(hostPort, workspaces)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -242,7 +242,7 @@ func (c *ClineClients) EnsureInstanceAtAddress(ctx context.Context, address stri
return fmt.Errorf("cannot start remote instance at %s", normalized)
}
func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
func startClineHost(hostPort int, workspaces []string) (*exec.Cmd, error) {
if Config.Verbose {
fmt.Printf("Starting cline-host on port %d\n", hostPort)
}
@@ -255,10 +255,18 @@ func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
binDir := path.Dir(execPath)
clineHostPath := path.Join(binDir, "cline-host")
// Start the cline-host process
cmd := exec.Command(clineHostPath,
// Build command arguments
args := []string{
"--verbose",
"--port", fmt.Sprintf("%d", hostPort))
"--port", fmt.Sprintf("%d", hostPort),
}
for _, ws := range workspaces {
args = append(args, "--workspace", ws)
}
// Start the cline-host process
cmd := exec.Command(clineHostPath, args...)
// Create logs directory in ~/.cline/logs
logsDir := path.Join(Config.ConfigPath, "logs")
@@ -333,7 +341,7 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres
if Config.Verbose {
fmt.Printf("Waiting for instance to clean up registry entry...\n")
}
for i := 0; i < 5; i++ {
for range 5 {
time.Sleep(1 * time.Second)
if !registry.HasInstanceAtAddress(address) {
if Config.Verbose {
@@ -408,15 +416,15 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
// This handles the case where we're running from cli/bin/cline
devClineCorePath := path.Join(binDir, "..", "..", "dist-standalone", "cline-core.js")
devInstallDir := path.Join(binDir, "..", "..", "dist-standalone")
if Config.Verbose {
fmt.Printf("Primary location not found, trying development path: %s\n", devClineCorePath)
}
if _, err := os.Stat(devClineCorePath); os.IsNotExist(err) {
return nil, fmt.Errorf("cline-core.js not found at '%s' or '%s'. Please ensure you're running from the correct location or reinstall with 'npm install -g cline'", clineCorePath, devClineCorePath)
}
finalClineCorePath = devClineCorePath
finalInstallDir = devInstallDir
if Config.Verbose {
@@ -475,15 +483,16 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
realNodeModules := path.Join(finalInstallDir, "node_modules")
fakeNodeModules := path.Join(finalInstallDir, "fake_node_modules")
nodePath := fmt.Sprintf("%s%c%s", realNodeModules, os.PathListSeparator, fakeNodeModules)
env = append(env,
fmt.Sprintf("NODE_PATH=%s", nodePath),
"GRPC_TRACE=all",
"GRPC_VERBOSITY=DEBUG",
// These control gRPC debug logging
//"GRPC_TRACE=all",
//"GRPC_VERBOSITY=DEBUG",
"NODE_ENV=development",
)
cmd.Env = env
if Config.Verbose {
fmt.Printf("NODE_PATH set to: %s\n", nodePath)
}
+9 -4
View File
@@ -37,11 +37,16 @@ var (
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)
// Check CLINE_DIR environment variable first
if clineDir := os.Getenv("CLINE_DIR"); clineDir != "" {
cfg.ConfigPath = clineDir
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
// Ensure .cline directory exists
+1
View File
@@ -25,6 +25,7 @@ type DisplayContext struct {
State *types.ConversationState
Renderer *display.Renderer
ToolRenderer *display.ToolRenderer
HookRenderer *display.HookRenderer
SystemRenderer *display.SystemMessageRenderer
IsLast bool
IsPartial bool
+40 -12
View File
@@ -6,8 +6,8 @@ import (
"strings"
"github.com/cline/cli/pkg/cli/clerror"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
)
// SayHandler handles SAY type messages
@@ -90,6 +90,12 @@ func (h *SayHandler) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
return h.handleInfo(msg, dc)
case string(types.SayTypeTaskProgress):
return h.handleTaskProgress(msg, dc)
case string(types.SayTypeHookStatus):
return h.handleHookStatus(msg, dc)
case string(types.SayTypeHookOutputStream):
return h.handleHookOutputStream(msg, dc)
case string(types.SayTypeCommandPermissionDenied):
return h.handleCommandPermissionDenied(msg, dc)
default:
return h.handleDefault(msg, dc)
}
@@ -242,18 +248,17 @@ func (h *SayHandler) handleCompletionResult(msg *types.ClineMessage, dc *Display
}
func formatUserMessage(text string) string {
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
}
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
}
// handleUserFeedback handles user feedback messages
func (h *SayHandler) handleUserFeedback(msg *types.ClineMessage, dc *DisplayContext) error {
@@ -343,6 +348,18 @@ func (h *SayHandler) handleCommandOutput(msg *types.ClineMessage, dc *DisplayCon
return nil
}
func (h *SayHandler) handleCommandPermissionDenied(msg *types.ClineMessage, dc *DisplayContext) error {
if msg.Text == "" {
return nil
}
// Use unified ToolRenderer
rendered := dc.ToolRenderer.RenderCommandPermissionDenied(msg.Text)
output.Print(rendered)
return nil
}
func (h *SayHandler) handleTool(msg *types.ClineMessage, dc *DisplayContext) error {
var tool types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &tool); err != nil {
@@ -517,5 +534,16 @@ func (h *SayHandler) handleTaskProgress(msg *types.ClineMessage, dc *DisplayCont
// handleDefault handles unknown SAY message types
func (h *SayHandler) handleDefault(msg *types.ClineMessage, dc *DisplayContext) error {
// Debug: log unhandled say types to help identify missing cases using output.Printf for CLI consistency
if dc.Verbose {
output.Printf("[DEBUG] Unhandled SAY type: '%s' (text preview: %s)\n", msg.Say, truncateForDisplay(msg.Text, 50))
}
return dc.Renderer.RenderMessage("SAY", msg.Text, true)
}
func truncateForDisplay(text string, maxLen int) string {
if len(text) <= maxLen {
return text
}
return text[:maxLen] + "..."
}
+198
View File
@@ -0,0 +1,198 @@
package handlers
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
)
// Hook-specific SAY handlers and helpers.
// Kept in a separate file to keep say_handlers.go focused on routing.
// handleHookStatus handles hook execution status messages.
func (h *SayHandler) handleHookStatus(msg *types.ClineMessage, dc *DisplayContext) error {
hook, err := parseHookMessage(msg.Text)
if err != nil {
// Fallback to basic output if JSON parsing fails
return dc.Renderer.RenderMessage("HOOK", msg.Text, true)
}
logHookDebug(hook, dc)
hook.ScriptPaths = formatHookPaths(hook.ScriptPaths)
return renderHookStatus(hook, dc)
}
// handleHookOutputStream handles streaming output from hooks.
//
// Hook stdout/stderr currently arrives line-by-line from the backend as
// `hook_output_stream` messages. The CLI intentionally suppresses these by default
// to keep the transcript high-signal.
//
// In --verbose mode, we print each non-empty line prefixed with "HOOK>" for easy grepping.
// Future work could associate these lines with a specific hook execution and render them
// as a grouped section under the hook status header.
func (h *SayHandler) handleHookOutputStream(msg *types.ClineMessage, dc *DisplayContext) error {
if !dc.Verbose {
return nil
}
line := strings.TrimRight(msg.Text, "\n")
if strings.TrimSpace(line) == "" {
return nil
}
output.Printf("HOOK> %s\n", line)
return nil
}
func parseHookMessage(jsonText string) (types.HookMessage, error) {
var hook types.HookMessage
if err := json.Unmarshal([]byte(jsonText), &hook); err != nil {
return types.HookMessage{}, err
}
return hook, nil
}
func logHookDebug(hook types.HookMessage, dc *DisplayContext) {
if dc.Verbose {
output.Printf("[DEBUG] Hook parsed: name=%s, status=%s, toolName=%s, scriptPaths=%v\n",
hook.HookName, hook.Status, hook.ToolName, hook.ScriptPaths)
}
}
func formatHookPaths(paths []string) []string {
if len(paths) == 0 {
return paths
}
formatted := make([]string, 0, len(paths))
for _, p := range paths {
if strings.TrimSpace(p) == "" {
continue
}
formatted = append(formatted, formatHookPath(p))
}
return formatted
}
func renderHookStatus(hook types.HookMessage, dc *DisplayContext) error {
if dc.HookRenderer != nil {
rendered := dc.HookRenderer.RenderHookStatus(hook)
// Match ToolRenderers spacing: one leading newline, one trailing newline.
output.Print("\n")
output.Print(rendered)
output.Print("\n")
return nil
}
// Fallback: if HookRenderer not available
return dc.Renderer.RenderMessage("HOOK", fmt.Sprintf("%s %s", hook.HookName, hook.Status), true)
}
func formatHookPath(fullPath string) string {
// Normalize for display and prefix checks. This is display-only; do not use for IO.
normalized := normalizeSlashes(fullPath)
// If this is a repo-scoped hook script (i.e. lives under <repo>/.clinerules/hooks/),
// always include the repo name for disambiguation even in single-repo workspaces.
//
// This intentionally runs before workspace-relative formatting, which would otherwise
// collapse to ".clinerules/hooks/..." and lose the repo context.
if p, ok := tryRepoScopedHooksPath(normalized); ok {
return p
}
// Prefer workspace-relative paths first for readability, since most hook scripts
// live inside the current project.
if p, ok := tryWorkspaceRelativeHookPath(normalized); ok {
return p
}
// Follow existing CLI pattern: resolve home via os.UserHomeDir.
if p, ok := tryHomeTildePath(normalized); ok {
return p
}
// Secondary heuristic: if hook lives under <repo>/.clinerules, collapse to repo-relative.
if p, ok := tryRepoRelativeHookPath(normalized); ok {
return p
}
return fallbackLastComponents(normalized, 3)
}
func normalizeSlashes(p string) string {
return filepath.ToSlash(p)
}
func tryWorkspaceRelativeHookPath(normalizedPath string) (string, bool) {
root, err := os.Getwd()
if err != nil {
return "", false
}
// filepath.Rel expects OS-native paths, so we need to convert the normalized path
// back to OS-native format before calling Rel, then normalize the result for display.
targetOS := filepath.FromSlash(normalizedPath)
rel, err := filepath.Rel(root, targetOS)
if err != nil {
return "", false
}
// If it's not within the workspace, Rel will start with "..".
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", false
}
return normalizeSlashes(rel), true
}
func tryHomeTildePath(normalizedPath string) (string, bool) {
homeDir, err := os.UserHomeDir()
if err != nil || strings.TrimSpace(homeDir) == "" {
return "", false
}
homeDir = normalizeSlashes(homeDir)
if !strings.HasPrefix(normalizedPath, homeDir) {
return "", false
}
rel := strings.TrimPrefix(normalizedPath, homeDir)
rel = strings.TrimPrefix(rel, "/")
return "~/" + rel, true
}
func tryRepoRelativeHookPath(normalizedPath string) (string, bool) {
parts := strings.Split(normalizedPath, "/")
for i, part := range parts {
if part == ".clinerules" && i > 0 {
repoName := parts[i-1]
return repoName + "/" + strings.Join(parts[i:], "/"), true
}
}
return "", false
}
// tryRepoScopedHooksPath returns a repo-prefixed path like
// "myrepo/.clinerules/hooks/PreToolUse" when the given path points to a hook script
// under a repo's .clinerules/hooks directory.
//
// This is more specific than tryRepoRelativeHookPath and is used to ensure hook script
// paths always include repo context.
func tryRepoScopedHooksPath(normalizedPath string) (string, bool) {
// Fast path check to avoid split work.
if !strings.Contains(normalizedPath, "/.clinerules/hooks/") {
return "", false
}
return tryRepoRelativeHookPath(normalizedPath)
}
func fallbackLastComponents(normalizedPath string, n int) string {
parts := strings.Split(normalizedPath, "/")
if len(parts) >= n {
return strings.Join(parts[len(parts)-n:], "/")
}
return normalizedPath
}
@@ -0,0 +1,41 @@
package handlers
import (
"os"
"path/filepath"
"testing"
)
func TestFormatHookPath_PrefersWorkspaceRelative(t *testing.T) {
// Create a stable workspace root (avoid TempDir's nested ".../001" patterns)
// so that workspace-relative formatting is deterministic.
root := filepath.Join(t.TempDir(), "workspace")
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd: %v", err)
}
defer func() { _ = os.Chdir(oldWd) }()
if err := os.Chdir(root); err != nil {
t.Fatalf("Chdir: %v", err)
}
inside := filepath.Join(root, ".clinerules", "hooks", "pre.sh")
got := formatHookPath(inside)
// Repo-scoped hook scripts should always include the repo name (the directory
// immediately containing .clinerules) even when running inside that repo.
expected := "workspace/" + filepath.ToSlash(filepath.Join(".clinerules", "hooks", "pre.sh"))
if got != expected {
t.Fatalf("expected formatted path to be %q. got=%q", expected, got)
}
}
func TestFormatHookPath_FallsBackToLastComponents(t *testing.T) {
// Use an obviously non-workspace path (relative, but not prefixed with cwd).
got := formatHookPath("/var/tmp/foo/bar/baz.sh")
if got != "foo/bar/baz.sh" {
t.Fatalf("expected last 3 components fallback, got=%q", got)
}
}
+35
View File
@@ -0,0 +1,35 @@
package handlers
import (
"os"
"testing"
)
func TestFormatHookPath_HomeDirToTilde(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil || home == "" {
t.Skip("home dir not available; skipping")
}
got := formatHookPath(home + "/Documents/Cline/Hooks/TaskStart")
want := "~/Documents/Cline/Hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_WorkspaceRepoRelative(t *testing.T) {
got := formatHookPath("/Users/alice/dev/repo-name/.clinerules/hooks/TaskStart")
want := "repo-name/.clinerules/hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_FallbackLast3Components(t *testing.T) {
got := formatHookPath("/a/b/c/d/e")
want := "c/d/e"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
+2 -2
View File
@@ -407,7 +407,7 @@ func newInstanceListCommand() *cobra.Command {
fmt.Print(strings.TrimLeft(rendered, "\n"))
}
fmt.Println("\n")
fmt.Println()
}
}
@@ -503,4 +503,4 @@ func newInstanceNewCommand() *cobra.Command {
cmd.Flags().BoolVarP(&setDefault, "default", "d", false, "set as default instance")
return cmd
}
}
+74 -22
View File
@@ -9,12 +9,13 @@ import (
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
// InputType represents the type of input being collected
type InputType int
const INPUT_WIDTH = 46
const INPUT_WIDTH = 46
const (
InputTypeMessage InputType = iota
@@ -24,11 +25,11 @@ const (
// InputSubmitMsg is sent when the user submits input
type InputSubmitMsg struct {
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
}
// InputCancelMsg is sent when the user cancels input (Ctrl+C)
@@ -36,8 +37,8 @@ type InputCancelMsg struct{}
// ChangeInputTypeMsg changes the current input type
type ChangeInputTypeMsg struct {
InputType InputType
Title string
InputType InputType
Title string
Placeholder string
}
@@ -57,7 +58,7 @@ type InputModel struct {
placeholder string
currentMode string // "plan" or "act"
width int
lastHeight int // Track height for cleanup on submit
lastHeight int // Track height for cleanup on submit
// For approval type
approvalOptions []string
@@ -66,6 +67,9 @@ type InputModel struct {
// Styles (huh-inspired theme)
styles fieldStyles
// Slash command autocomplete dropdown
completion CompletionModel
}
// fieldStyles holds the styling for the input field
@@ -115,12 +119,17 @@ func newFieldStyles() fieldStyles {
// NewInputModel creates a new input model
func NewInputModel(inputType InputType, title, placeholder, currentMode string) InputModel {
return NewInputModelWithRegistry(inputType, title, placeholder, currentMode, nil)
}
// NewInputModelWithRegistry creates a new input model with slash command autocomplete support
func NewInputModelWithRegistry(inputType InputType, title, placeholder, currentMode string, registry *slash.Registry) InputModel {
ta := textarea.New()
ta.Placeholder = placeholder
ta.Focus()
ta.CharLimit = 0
ta.ShowLineNumbers = false
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.SetHeight(5)
// Don't set width here - let WindowSizeMsg handle it
ta.SetWidth(INPUT_WIDTH)
@@ -138,11 +147,11 @@ func NewInputModel(inputType InputType, title, placeholder, currentMode string)
cursorColor = lipgloss.Color("39") // Blue for act
}
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.Placeholder = styles.placeholder
ta.FocusedStyle.Text = styles.textArea
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.Cursor.Style = lipgloss.NewStyle().Foreground(cursorColor)
ta.Cursor.TextStyle = styles.textArea
@@ -154,6 +163,7 @@ func NewInputModel(inputType InputType, title, placeholder, currentMode string)
currentMode: currentMode,
width: 0, // Will be set by first WindowSizeMsg
styles: styles,
completion: NewCompletionModel(registry),
}
// For approval type, set up options
@@ -217,13 +227,6 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
case tea.KeyMsg:
if m.suspended {
return m, nil
@@ -231,6 +234,31 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle keys for text input types (Message/Feedback)
if m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback {
// When completion menu is visible, let it handle navigation keys first
if m.completion.Visible() {
// ctrl+c always cancels, even with dropdown open
if msg.String() == "ctrl+c" {
return m, func() tea.Msg { return InputCancelMsg{} }
}
var handled bool
m.completion, cmd, handled = m.completion.Update(msg)
if handled {
// Check if a completion was selected
if applied := m.completion.Apply(); applied != "" {
m.textarea.SetValue(applied)
m.textarea.CursorEnd()
}
return m, cmd
}
// Key not handled by completion - pass to textarea and update completion
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
// Normal key handling when completion menu is NOT visible
switch msg.String() {
case "ctrl+c":
return m, func() tea.Msg { return InputCancelMsg{} }
@@ -239,6 +267,11 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Open external editor (like huh does)
return m, m.openEditor()
case "tab":
// Tab without dropdown visible - do nothing special
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
case "enter":
// Intercept enter for submit (textarea handles alt+enter and ctrl+j for newlines)
return m.handleSubmit()
@@ -249,8 +282,9 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, cmd
}
// Pass all other keys to textarea (including alt+enter, ctrl+j for newlines)
// Pass all other keys to textarea, then check for slash completion
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
@@ -276,6 +310,13 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
}
}
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
}
return m, nil
@@ -365,6 +406,11 @@ func (m *InputModel) View() string {
case InputTypeMessage, InputTypeFeedback:
parts = append(parts, m.textarea.View())
// Render completion dropdown if visible
if m.completion.Visible() {
parts = append(parts, m.completion.View())
}
case InputTypeApproval:
var options []string
for i, option := range m.approvalOptions {
@@ -411,7 +457,7 @@ func (m *InputModel) Clone() *InputModel {
ta.ShowLineNumbers = false
ta.Prompt = ""
ta.SetHeight(5)
ta.SetWidth(INPUT_WIDTH)
ta.SetWidth(INPUT_WIDTH)
ta.Focus()
// Configure keybindings
@@ -446,6 +492,7 @@ func (m *InputModel) Clone() *InputModel {
selectedOption: m.selectedOption,
pendingApproval: m.pendingApproval, // Preserve approval decision
styles: m.styles,
completion: NewCompletionModel(m.completion.registry), // Preserve registry, start fresh state
}
return clone
@@ -495,3 +542,8 @@ func (m *InputModel) openEditor() tea.Cmd {
return editorFinishedMsg{content: content, err: err}
})
}
// SetSlashRegistry sets the slash command registry for autocomplete
func (m *InputModel) SetSlashRegistry(registry *slash.Registry) {
m.completion.SetRegistry(registry)
}
+265
View File
@@ -0,0 +1,265 @@
package output
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
const maxVisibleCompletions = 7
// completionStyles holds the styling for the completion dropdown
type completionStyles struct {
menu lipgloss.Style
selected lipgloss.Style
normalName lipgloss.Style
description lipgloss.Style
scrollIndicator lipgloss.Style
}
// newCompletionStyles creates the default styles for the completion dropdown
func newCompletionStyles() completionStyles {
return completionStyles{
menu: lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("238")).
Padding(0, 1),
selected: lipgloss.NewStyle().
Background(lipgloss.Color("62")).
Foreground(lipgloss.Color("230")),
normalName: lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{Light: "235", Dark: "252"}),
description: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
scrollIndicator: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
}
}
// CompletionModel is a Bubbletea model for slash command autocomplete dropdown
type CompletionModel struct {
registry *slash.Registry
visible bool
matches []slash.Command
index int // selected item (0-based)
scroll int // scroll offset for long lists
styles completionStyles
// pendingApply holds the command to apply after selection
pendingApply string
}
// NewCompletionModel creates a new completion model with the given registry
func NewCompletionModel(registry *slash.Registry) CompletionModel {
return CompletionModel{
registry: registry,
styles: newCompletionStyles(),
}
}
// SetRegistry sets the slash command registry
func (m *CompletionModel) SetRegistry(registry *slash.Registry) {
m.registry = registry
}
// Visible returns whether the completion dropdown is currently visible
func (m CompletionModel) Visible() bool {
return m.visible
}
// Update handles key messages for the completion dropdown.
// Returns the updated model, any commands, and whether the key was handled.
// If handled is true, the parent should NOT pass the key to the textarea.
func (m CompletionModel) Update(msg tea.Msg) (CompletionModel, tea.Cmd, bool) {
if !m.visible {
return m, nil, false
}
keyMsg, ok := msg.(tea.KeyMsg)
if !ok {
return m, nil, false
}
switch keyMsg.String() {
case "up":
m.navigateUp()
return m, nil, true
case "down":
m.navigateDown()
return m, nil, true
case "tab", "enter":
// Select the current completion
if len(m.matches) > 0 {
selected := m.matches[m.index]
m.pendingApply = "/" + selected.Name + " "
}
m.Hide()
return m, nil, true
case "esc":
m.Hide()
return m, nil, true
}
// Key not handled by completion - let parent process it
return m, nil, false
}
// CheckInput updates the completion state based on the current input value.
// Call this after each input change to show/hide/update the dropdown.
func (m *CompletionModel) CheckInput(value string) {
if m.registry == nil {
return
}
// Only activate if input starts with "/" (first character requirement)
if !strings.HasPrefix(value, "/") {
m.Hide()
return
}
// Extract the command being typed (everything after "/" until space/newline)
rest := value[1:] // Everything after the "/"
// If there's whitespace, the command is complete - hide dropdown
if idx := strings.IndexAny(rest, " \n\t"); idx != -1 {
m.Hide()
return
}
// Update matches based on prefix
m.updateMatches(rest)
m.visible = len(m.matches) > 0
}
// Apply returns the command string to insert (if any) and clears the pending state.
// The parent should call this after Update returns handled=true for tab/enter.
func (m *CompletionModel) Apply() string {
result := m.pendingApply
m.pendingApply = ""
return result
}
// Hide hides the completion dropdown and resets state
func (m *CompletionModel) Hide() {
m.visible = false
m.matches = nil
m.index = 0
m.scroll = 0
}
// View renders the completion dropdown
func (m CompletionModel) View() string {
if !m.visible || len(m.matches) == 0 {
return ""
}
var lines []string
// Calculate visible range
endIdx := min(m.scroll+maxVisibleCompletions, len(m.matches))
// Show scroll indicator if there are items above
if m.scroll > 0 {
lines = append(lines, m.styles.scrollIndicator.Render(" ↑ more"))
}
// Find the longest command name for alignment
maxNameLen := 0
for _, cmd := range m.matches {
nameLen := len(cmd.Name) + 1 // +1 for the "/"
if nameLen > maxNameLen {
maxNameLen = nameLen
}
}
// Cap at reasonable width
if maxNameLen > 15 {
maxNameLen = 15
}
// Render visible items
for i := m.scroll; i < endIdx; i++ {
cmd := m.matches[i]
name := "/" + cmd.Name
desc := cmd.Description
// Truncate description if too long
maxDescLen := 35
if len(desc) > maxDescLen {
desc = desc[:maxDescLen-3] + "..."
}
// Pad name for alignment
paddedName := fmt.Sprintf("%-*s", maxNameLen, name)
if i == m.index {
// Selected item - highlight the entire line
line := fmt.Sprintf("> %s %s", paddedName, desc)
lines = append(lines, m.styles.selected.Render(line))
} else {
// Normal item
line := fmt.Sprintf(" %s %s", m.styles.normalName.Render(paddedName), m.styles.description.Render(desc))
lines = append(lines, line)
}
}
// Show scroll indicator if there are items below
if endIdx < len(m.matches) {
lines = append(lines, m.styles.scrollIndicator.Render(" ↓ more"))
}
return m.styles.menu.Render(strings.Join(lines, "\n"))
}
// updateMatches filters commands by prefix and updates the matches list
func (m *CompletionModel) updateMatches(prefix string) {
if m.registry == nil {
m.matches = nil
return
}
m.matches = m.registry.GetMatching(prefix)
// Reset selection if out of bounds
if m.index >= len(m.matches) {
m.index = 0
m.scroll = 0
}
m.adjustScroll()
}
// navigateUp moves selection up in the dropdown
func (m *CompletionModel) navigateUp() {
if len(m.matches) == 0 {
return
}
m.index--
if m.index < 0 {
m.index = len(m.matches) - 1
}
m.adjustScroll()
}
// navigateDown moves selection down in the dropdown
func (m *CompletionModel) navigateDown() {
if len(m.matches) == 0 {
return
}
m.index++
if m.index >= len(m.matches) {
m.index = 0
}
m.adjustScroll()
}
// adjustScroll ensures the selected item is visible in the dropdown
func (m *CompletionModel) adjustScroll() {
if m.index < m.scroll {
m.scroll = m.index
} else if m.index >= m.scroll+maxVisibleCompletions {
m.scroll = m.index - maxVisibleCompletions + 1
}
}
+125
View File
@@ -0,0 +1,125 @@
package slash
import (
"context"
"strings"
"sync"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
)
// Command represents a slash command available for autocomplete
type Command struct {
Name string
Description string
Section string // "default", "custom", or "cli"
CLICompatible bool
}
// Registry holds available slash commands for autocomplete
type Registry struct {
mu sync.RWMutex
commands []Command
}
// CLI-local commands (handled by CLI, not sent to backend)
var cliLocalCommands = []Command{
{Name: "plan", Description: "Switch to plan mode", Section: "cli", CLICompatible: true},
{Name: "act", Description: "Switch to act mode", Section: "cli", CLICompatible: true},
{Name: "cancel", Description: "Cancel the current task", Section: "cli", CLICompatible: true},
{Name: "exit", Description: "Exit follow mode", Section: "cli", CLICompatible: true},
}
// NewRegistry creates a new slash command registry
func NewRegistry() *Registry {
return &Registry{
commands: make([]Command, 0),
}
}
// FetchFromBackend fetches available commands from cline-core backend
func (r *Registry) FetchFromBackend(ctx context.Context, c *client.ClineClient) error {
resp, err := c.Slash.GetAvailableSlashCommands(ctx, &cline.EmptyRequest{})
if err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
// Start with CLI-local commands
r.commands = append([]Command{}, cliLocalCommands...)
// Add backend commands (only CLI-compatible ones)
for _, cmd := range resp.Commands {
if cmd.CliCompatible {
r.commands = append(r.commands, Command{
Name: cmd.Name,
Description: cmd.Description,
Section: cmd.Section,
CLICompatible: cmd.CliCompatible,
})
}
}
return nil
}
// GetCommands returns all available commands
func (r *Registry) GetCommands() []Command {
r.mu.RLock()
defer r.mu.RUnlock()
// Return a copy to avoid race conditions
result := make([]Command, len(r.commands))
copy(result, r.commands)
return result
}
// GetMatching returns commands that start with the given prefix (case-insensitive)
func (r *Registry) GetMatching(prefix string) []Command {
r.mu.RLock()
defer r.mu.RUnlock()
prefix = strings.ToLower(prefix)
var matches []Command
for _, cmd := range r.commands {
if strings.HasPrefix(strings.ToLower(cmd.Name), prefix) {
matches = append(matches, cmd)
}
}
return matches
}
// IsValid checks if a command name is valid
func (r *Registry) IsValid(name string) bool {
r.mu.RLock()
defer r.mu.RUnlock()
name = strings.ToLower(name)
for _, cmd := range r.commands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// IsCLILocal checks if a command is handled locally by CLI (not sent to backend)
func (r *Registry) IsCLILocal(name string) bool {
name = strings.ToLower(name)
for _, cmd := range cliLocalCommands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// HasCommands returns true if the registry has any commands loaded
func (r *Registry) HasCommands() bool {
r.mu.RLock()
defer r.mu.RUnlock()
return len(r.commands) > 0
}
+13 -9
View File
@@ -20,13 +20,14 @@ import (
// TaskOptions contains options for creating a task
type TaskOptions struct {
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
Workspaces []string
}
func NewTaskCommand() *cobra.Command {
@@ -394,7 +395,7 @@ func newTaskViewCommand() *cobra.Command {
return taskManager.FollowConversation(ctx, taskManager.GetCurrentInstance(), false)
} else if followComplete {
// Follow until completion
return taskManager.FollowConversationUntilCompletion(ctx)
return taskManager.FollowConversationUntilCompletion(ctx, task.DefaultFollowOptions())
} else {
// Default: show snapshot
return taskManager.ShowConversation(ctx)
@@ -668,7 +669,10 @@ func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) e
// If yolo mode is enabled, follow until completion (non-interactive)
// Otherwise, follow in interactive mode
if opts.Yolo {
return taskManager.FollowConversationUntilCompletion(ctx)
// Skip active task check since we just created the task
return taskManager.FollowConversationUntilCompletion(ctx, task.FollowOptions{
SkipActiveTaskCheck: true,
})
} else {
return taskManager.FollowConversation(ctx, taskManager.GetCurrentInstance(), true)
}
+15
View File
@@ -0,0 +1,15 @@
package task
// FollowOptions contains options for following a conversation
type FollowOptions struct {
// SkipActiveTaskCheck skips the check for an active task
// This is useful when following a task that was just created to avoid race conditions
SkipActiveTaskCheck bool
}
// DefaultFollowOptions returns the default options for following a conversation
func DefaultFollowOptions() FollowOptions {
return FollowOptions{
SkipActiveTaskCheck: false,
}
}
+18 -14
View File
@@ -38,13 +38,13 @@ type InputHandler struct {
// NewInputHandler creates a new input handler
func NewInputHandler(manager *Manager, coordinator *StreamCoordinator, cancelFunc context.CancelFunc) *InputHandler {
return &InputHandler{
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
cancelChan: make(chan struct{}, 1),
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
cancelChan: make(chan struct{}, 1),
}
}
@@ -251,7 +251,8 @@ func determineAutoApprovalAction(msg *types.ClineMessage) (string, error) {
types.ToolTypeListFilesRecursive,
types.ToolTypeListCodeDefinitionNames,
types.ToolTypeSearchFiles,
types.ToolTypeWebFetch:
types.ToolTypeWebFetch,
types.ToolTypeWebSearch:
return "read_files", nil
case types.ToolTypeEditedExistingFile,
types.ToolTypeNewFileCreated:
@@ -280,11 +281,12 @@ func determineAutoApprovalAction(msg *types.ClineMessage) (string, error) {
func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error) {
currentMode := ih.manager.GetCurrentMode()
model := output.NewInputModel(
model := output.NewInputModelWithRegistry(
output.InputTypeMessage,
"Cline is ready for your message...",
"/plan or /act to switch modes\nctrl+e to open editor",
"/plan or /act to switch modes\nctrl+e to open editor\ntab to autocomplete commands",
currentMode,
ih.manager.GetSlashRegistry(),
)
return ih.runInputProgram(ctx, model)
@@ -294,12 +296,13 @@ func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error
func (ih *InputHandler) promptForApproval(ctx context.Context, msg *types.ClineMessage) (bool, string, error) {
// Store the approval message for later use in determining auto-approval action
ih.approvalMessage = msg
model := output.NewInputModel(
model := output.NewInputModelWithRegistry(
output.InputTypeApproval,
"Let Cline use this tool?",
"",
ih.manager.GetCurrentMode(),
ih.manager.GetSlashRegistry(), // Pass registry for feedback input after approval
)
message, shouldSend, err := ih.runInputProgram(ctx, model)
@@ -394,7 +397,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
// Need to collect feedback - will be handled by model state change
return "", false, nil
}
// Check if NoAskAgain was selected
if result.NoAskAgain && result.Approved && ih.approvalMessage != nil {
// Determine which auto-approval action to enable
@@ -410,7 +413,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
}
}
}
// Store approval state for when feedback comes back
ih.feedbackApproval = false
ih.feedbackApproved = result.Approved
@@ -440,6 +443,7 @@ func (w *inputProgramWrapper) Init() tea.Cmd {
}
func (w *inputProgramWrapper) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case output.InputSubmitMsg:
// Handle input submission - clear the screen before quitting
+120 -9
View File
@@ -14,6 +14,7 @@ import (
"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/slash"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
@@ -32,10 +33,12 @@ type Manager struct {
clientAddress string
state *types.ConversationState
renderer *display.Renderer
hookRenderer *display.HookRenderer
toolRenderer *display.ToolRenderer
systemRenderer *display.SystemMessageRenderer
streamingDisplay *display.StreamingDisplay
handlerRegistry *handlers.HandlerRegistry
slashRegistry *slash.Registry
isStreamingMode bool
isInteractive bool
currentMode string // "plan" or "act"
@@ -46,6 +49,7 @@ func NewManager(client *client.ClineClient) *Manager {
state := types.NewConversationState()
renderer := display.NewRenderer(global.Config.OutputFormat)
toolRenderer := display.NewToolRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
hookRenderer := display.NewHookRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
systemRenderer := display.NewSystemMessageRenderer(renderer, renderer.GetMdRenderer(), global.Config.OutputFormat)
streamingDisplay := display.NewStreamingDisplay(state, renderer)
@@ -59,10 +63,12 @@ func NewManager(client *client.ClineClient) *Manager {
clientAddress: "", // Will be set when client is provided
state: state,
renderer: renderer,
hookRenderer: hookRenderer,
toolRenderer: toolRenderer,
systemRenderer: systemRenderer,
streamingDisplay: streamingDisplay,
handlerRegistry: registry,
slashRegistry: slash.NewRegistry(),
currentMode: "plan", // Default mode
}
}
@@ -76,6 +82,10 @@ func NewManagerForAddress(ctx context.Context, address string) (*Manager, error)
manager := NewManager(client)
manager.clientAddress = address
// Fetch slash commands from backend (non-blocking, errors are logged)
manager.fetchSlashCommands(ctx)
return manager, nil
}
@@ -93,9 +103,25 @@ func NewManagerForDefault(ctx context.Context) (*Manager, error) {
manager.clientAddress = global.Clients.GetRegistry().GetDefaultInstance()
}
// Fetch slash commands from backend (non-blocking, errors are logged)
manager.fetchSlashCommands(ctx)
return manager, nil
}
// fetchSlashCommands fetches available slash commands from the backend
// This is non-blocking and errors are logged but don't prevent manager creation
func (m *Manager) fetchSlashCommands(ctx context.Context) {
if err := m.slashRegistry.FetchFromBackend(ctx, m.client); err != nil {
if global.Config.Verbose {
m.renderer.RenderDebug("Failed to fetch slash commands: %v", err)
}
// Non-fatal: CLI-local commands are still available
} else if global.Config.Verbose {
m.renderer.RenderDebug("Loaded %d slash commands", len(m.slashRegistry.GetCommands()))
}
}
// SwitchToInstance switches the manager to use a different Cline instance
func (m *Manager) SwitchToInstance(ctx context.Context, address string) error {
m.mu.Lock()
@@ -280,8 +306,8 @@ func (m *Manager) CheckSendEnabled(ctx context.Context) error {
// Error types which we allow sending on
errorTypes := []string{
string(types.AskTypeAPIReqFailed), // "api_req_failed"
string(types.AskTypeMistakeLimitReached), // "mistake_limit_reached"
string(types.AskTypeAPIReqFailed), // "api_req_failed"
string(types.AskTypeMistakeLimitReached), // "mistake_limit_reached"
}
isError := false
@@ -753,7 +779,21 @@ func (m *Manager) FollowConversation(ctx context.Context, instanceAddress string
}
// FollowConversationUntilCompletion streams conversation updates until task completion
func (m *Manager) FollowConversationUntilCompletion(ctx context.Context) error {
func (m *Manager) FollowConversationUntilCompletion(ctx context.Context, opts FollowOptions) error {
// Check if there's an active task before entering follow mode
// Skip this check if we just created a task (to avoid race condition where task isn't active yet)
if !opts.SkipActiveTaskCheck {
err := m.CheckSendEnabled(ctx)
if err != nil {
if errors.Is(err, ErrNoActiveTask) {
fmt.Println("No task is currently running.")
return nil
}
// For other errors (like task busy), we can still enter follow mode
// as the user may want to observe the task
}
}
// Enable streaming mode
m.mu.Lock()
m.isStreamingMode = true
@@ -952,6 +992,15 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeCommandPermissionDenied):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeBrowserActionLaunch):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -970,6 +1019,33 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeMcpServerResponse):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeMcpNotification):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeUseMcpServer):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeCheckpointCreated):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -979,6 +1055,26 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookStatus):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookOutputStream):
// Hook stdout/stderr streaming arrives as hook_output_stream messages.
// These are intentionally suppressed unless verbose (see SayHandler.handleHookOutputStream),
// but we still need to route them through the normal handler pipeline in streaming/follow
// mode so verbose users actually see `HOOK> ...` lines.
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeAPIReqStarted):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
apiInfo := types.APIRequestInfo{Cost: -1}
@@ -993,6 +1089,14 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
}
}
case msg.Say == string(types.SayTypeCompletionResult):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !msg.Partial && !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Ask == string(types.AskTypeCommandOutput):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -1102,12 +1206,14 @@ func (m *Manager) displayMessage(msg *types.ClineMessage, isLast, isPartial bool
m.mu.RUnlock()
dc := &handlers.DisplayContext{
State: m.state,
Renderer: m.renderer,
ToolRenderer: m.toolRenderer,
SystemRenderer: m.systemRenderer,
State: m.state,
Renderer: m.renderer,
ToolRenderer: m.toolRenderer,
HookRenderer: m.hookRenderer,
SystemRenderer: m.systemRenderer,
IsLast: isLast,
IsPartial: isPartial,
Verbose: global.Config.Verbose,
MessageIndex: messageIndex,
IsStreamingMode: isStreaming,
IsInteractive: isInteractive,
@@ -1214,6 +1320,11 @@ func (m *Manager) GetCurrentMode() string {
return m.currentMode
}
// GetSlashRegistry returns the slash command registry
func (m *Manager) GetSlashRegistry() *slash.Registry {
return m.slashRegistry
}
// extractModeFromState extracts the current mode from state JSON
func (m *Manager) extractModeFromState(stateJson string) string {
var rawState map[string]interface{}
@@ -1239,7 +1350,7 @@ func (m *Manager) updateMode(stateJson string) {
// UpdateTaskAutoApprovalAction enables a specific auto-approval action for the current task
func (m *Manager) UpdateTaskAutoApprovalAction(ctx context.Context, actionKey string) error {
boolPtr := func(b bool) *bool { return &b }
settings := &cline.Settings{
AutoApprovalSettings: &cline.AutoApprovalSettings{
Actions: &cline.AutoApprovalActions{},
@@ -1248,7 +1359,7 @@ func (m *Manager) UpdateTaskAutoApprovalAction(ctx context.Context, actionKey st
// Set the specific action to true based on actionKey
truePtr := boolPtr(true)
switch actionKey {
case "read_files":
settings.AutoApprovalSettings.Actions.ReadFiles = truePtr
+12
View File
@@ -290,6 +290,18 @@ func setSimpleField(settings *cline.Settings, key, value string) error {
return err
}
settings.ActModeAwsBedrockCustomSelected = boolPtr(val)
case "hooks_enabled":
val, err := parseBool(value)
if err != nil {
return err
}
settings.HooksEnabled = boolPtr(val)
case "azure_identity":
val, err := parseBool(value)
if err != nil {
return err
}
settings.AzureIdentity = boolPtr(val)
// Integer fields
case "request_timeout_ms":
+12 -11
View File
@@ -3,15 +3,16 @@ package types
// HistoryItem represents a task history item from taskHistory.json
// This struct matches the JSON format stored on disk
type HistoryItem struct {
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
WorkspacePaths []string `json:"workspacePaths,omitempty"`
}
+53 -5
View File
@@ -47,11 +47,11 @@ const (
AskTypeResumeTask AskType = "resume_task"
AskTypeResumeCompletedTask AskType = "resume_completed_task"
AskTypeMistakeLimitReached AskType = "mistake_limit_reached"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
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
@@ -87,6 +87,11 @@ const (
SayTypeLoadMcpDocumentation SayType = "load_mcp_documentation"
SayTypeInfo SayType = "info"
SayTypeTaskProgress SayType = "task_progress"
// Hook status streaming from the backend.
// These values must match the backend "say" strings emitted by the extension.
SayTypeHookStatus SayType = "hook_status"
SayTypeHookOutputStream SayType = "hook_output_stream"
SayTypeCommandPermissionDenied SayType = "command_permission_denied"
)
// ToolMessage represents a tool-related message
@@ -113,6 +118,7 @@ const (
ToolTypeListCodeDefinitionNames ToolType = "listCodeDefinitionNames"
ToolTypeSearchFiles ToolType = "searchFiles"
ToolTypeWebFetch ToolType = "webFetch"
ToolTypeWebSearch ToolType = "webSearch"
ToolTypeSummarizeTask ToolType = "summarizeTask"
)
@@ -144,6 +150,42 @@ type APIRequestRetryStatus struct {
ErrorSnippet string `json:"errorSnippet,omitempty"`
}
// HookMessage represents hook execution metadata sent from the backend
type HookMessage struct {
HookName string `json:"hookName"` // Type of hook (TaskStart, PreToolUse, etc.)
ToolName string `json:"toolName,omitempty"` // Optional tool name for tool-specific hooks
Status string `json:"status"` // "running", "completed", "cancelled", or "failed"
ScriptPaths []string `json:"scriptPaths,omitempty"` // Full paths to hook script(s)
PendingToolInfo *ToolInfo `json:"pendingToolInfo,omitempty"` // Metadata about the pending tool execution (PreToolUse)
ExitCode int `json:"exitCode,omitempty"` // Exit code for completed/failed hooks
HasJsonResponse bool `json:"hasJsonResponse,omitempty"` // Whether hook returned JSON
Error *HookError `json:"error,omitempty"` // Error details if hook failed
}
// ToolInfo represents a compact subset of tool parameters for UI display.
// This mirrors the extension's pendingToolInfo shape and is used by the CLI to
// show what tool the PreToolUse hook is gating.
type ToolInfo struct {
Tool string `json:"tool"`
Path string `json:"path,omitempty"`
Command string `json:"command,omitempty"`
Content string `json:"content,omitempty"`
Diff string `json:"diff,omitempty"`
Regex string `json:"regex,omitempty"`
Url string `json:"url,omitempty"`
McpTool string `json:"mcpTool,omitempty"`
McpServer string `json:"mcpServer,omitempty"`
ResourceUri string `json:"resourceUri,omitempty"`
}
// HookError represents structured error information from a failed hook
type HookError struct {
Type string `json:"type"` // Error type: "execution", "timeout", "validation", etc.
Message string `json:"message"` // Human-readable error message
Details string `json:"details,omitempty"` // Additional error details
ScriptPath string `json:"scriptPath,omitempty"` // Path to script that failed
}
// GetTimestamp returns a formatted timestamp string
func (m *ClineMessage) GetTimestamp() string {
return time.Unix(m.Timestamp/1000, 0).Format("15:04:05")
@@ -323,6 +365,12 @@ func convertProtoSayType(sayType cline.ClineSay) string {
return string(SayTypeInfo)
case cline.ClineSay_TASK_PROGRESS:
return string(SayTypeTaskProgress)
case cline.ClineSay_HOOK_STATUS:
return string(SayTypeHookStatus)
case cline.ClineSay_HOOK_OUTPUT_STREAM:
return string(SayTypeHookOutputStream)
case cline.ClineSay_COMMAND_PERMISSION_DENIED:
return string(SayTypeCommandPermissionDenied)
default:
return "unknown"
}
+14 -11
View File
@@ -8,6 +8,19 @@ import (
"github.com/spf13/cobra"
)
// VersionString returns the full version information string
func VersionString() string {
return fmt.Sprintf(`Cline CLI
Cline CLI Version: %s
Cline Core Version: %s
Commit: %s
Built: %s
Built by: %s
Go version: %s
OS/Arch: %s/%s
`, global.CliVersion, global.Version, global.Commit, global.Date, global.BuiltBy, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
// NewVersionCommand creates the version command
func NewVersionCommand() *cobra.Command {
var short bool
@@ -18,21 +31,11 @@ func NewVersionCommand() *cobra.Command {
Short: "Show version information",
Long: `Display version information for the Cline CLI.`,
RunE: func(cmd *cobra.Command, args []string) error {
// Versions are injected at build time via ldflags
if short {
fmt.Println(global.CliVersion)
return nil
}
fmt.Printf("Cline CLI\n")
fmt.Printf("Cline CLI Version: %s\n", global.CliVersion)
fmt.Printf("Cline Core Version: %s\n", global.Version)
fmt.Printf("Commit: %s\n", global.Commit)
fmt.Printf("Built: %s\n", global.Date)
fmt.Printf("Built by: %s\n", global.BuiltBy)
fmt.Printf("Go version: %s\n", runtime.Version())
fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
fmt.Print(VersionString())
return nil
},
}
+71
View File
@@ -4,7 +4,9 @@ import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
@@ -183,3 +185,72 @@ DEBUGGING STEPS:
For additional help, visit: https://github.com/cline/cline/issues
`, maxRetries, lastErr, GetNodeVersion())
}
// validateDirsExist validates that all workspace paths exist on the filesystem
func ValidateDirsExist(paths []string) error {
for _, p := range paths {
info, err := os.Stat(p)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("path does not exist: %s", p)
}
return fmt.Errorf("failed to access path %s: %w", p, err)
}
if !info.IsDir() {
return fmt.Errorf("path is not a directory: %s", p)
}
}
return nil
}
// absPath returns the absolute path, resolving symlinks
func AbsPath(path string) (string, error) {
// First get absolute path
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
// Then resolve any symlinks
resolved, err := filepath.EvalSymlinks(abs)
if err != nil {
// If symlink resolution fails, return the absolute path
return abs, nil
}
return resolved, nil
}
// shortenPath shortens a filesystem path to fit within maxLen
func ShortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
+17 -5
View File
@@ -47,7 +47,10 @@ func (s *DiffService) generateDiffID() string {
return fmt.Sprintf("diff_%d_%d", os.Getpid(), id)
}
// splitLines splits content into lines, preserving line ending information
// splitLines splits content into lines, preserving trailing newlines.
// This matches the behavior of JavaScript's String.split("\n"):
// - "hello\nworld\n" -> ["hello", "world", ""]
// - "hello\nworld" -> ["hello", "world"]
func splitLines(content string) []string {
if content == "" {
return []string{}
@@ -65,10 +68,9 @@ func splitLines(content string) []string {
}
}
// Add the last line if it doesn't end with newline
if current != "" {
lines = append(lines, current)
}
// Always add the last segment - if content ends with newline, this will be
// an empty string which preserves the trailing newline when joined back
lines = append(lines, current)
return lines
}
@@ -176,9 +178,19 @@ func (s *DiffService) ReplaceText(ctx context.Context, req *proto.ReplaceTextReq
endLine = startLine
}
// Check if we're replacing to the end of the document
replacingToEnd := endLine >= len(session.lines)
// Split new content into lines
newLines := splitLines(newContent)
// Remove trailing empty line for proper splicing, BUT only when NOT replacing
// to the end of the document. When replacing to the end, keep the trailing
// empty string to preserve trailing newlines from the content.
if !replacingToEnd && len(newLines) > 0 && newLines[len(newLines)-1] == "" {
newLines = newLines[:len(newLines)-1]
}
// Ensure we have enough lines in the current content
for len(session.lines) < endLine {
session.lines = append(session.lines, "")
+1 -1
View File
@@ -77,7 +77,7 @@ func (s *EnvService) GetHostVersion(ctx context.Context, req *cline.EmptyRequest
return &host.GetHostVersionResponse{
Platform: proto.String("Cline CLI"),
Version: proto.String(""),
Version: proto.String(global.CliVersion),
ClineType: proto.String("CLI"),
ClineVersion: proto.String(global.CliVersion),
}, nil
+4 -2
View File
@@ -16,15 +16,17 @@ import (
type GrpcServer struct {
port int
verbose bool
workspaces []string
server *grpc.Server
shutdownCh chan struct{}
}
// NewGrpcServer creates a new GrpcServer
func NewGrpcServer(port int, verbose bool) *GrpcServer {
func NewGrpcServer(port int, verbose bool, workspaces []string) *GrpcServer {
return &GrpcServer{
port: port,
verbose: verbose,
workspaces: workspaces,
shutdownCh: make(chan struct{}),
}
}
@@ -50,7 +52,7 @@ func (s *GrpcServer) Start(ctx context.Context) error {
grpc_health_v1.RegisterHealthServer(s.server, healthServer)
// Register services
workspaceService := NewSimpleWorkspaceService(s.verbose)
workspaceService := NewSimpleWorkspaceService(s.verbose, s.workspaces)
host.RegisterWorkspaceServiceServer(s.server, workspaceService)
windowService := NewWindowService(s.verbose)
+20 -8
View File
@@ -12,13 +12,15 @@ import (
// SimpleWorkspaceService implements a basic workspace service without complex dependencies
type SimpleWorkspaceService struct {
host.UnimplementedWorkspaceServiceServer
verbose bool
verbose bool
workspaces []string
}
// NewSimpleWorkspaceService creates a new SimpleWorkspaceService
func NewSimpleWorkspaceService(verbose bool) *SimpleWorkspaceService {
func NewSimpleWorkspaceService(verbose bool, workspaces []string) *SimpleWorkspaceService {
return &SimpleWorkspaceService{
verbose: verbose,
verbose: verbose,
workspaces: workspaces,
}
}
@@ -28,14 +30,24 @@ func (s *SimpleWorkspaceService) GetWorkspacePaths(ctx context.Context, req *hos
log.Printf("GetWorkspacePaths called")
}
// Get current working directory as the workspace
cwd, err := os.Getwd()
if err != nil {
return nil, err
paths := []string{}
if len(s.workspaces) == 0 {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
paths = append(paths, cwd)
} else {
paths = s.workspaces
}
if s.verbose {
log.Printf("Returning configured workspaces: %v", paths)
}
return &host.GetWorkspacePathsResponse{
Paths: []string{cwd},
Paths: paths,
}, nil
}

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