Compare commits

...

370 Commits

Author SHA1 Message Date
Dominic Cooney eab96e6a8a Simplify symbol formatting: omit () from all symbol names
Appending () is language-specific and can mislead for TypeScript,
Obj-C, etc. The kind suffix (— function, — class, etc.) already
communicates the symbol type clearly.
2026-03-27 15:15:48 +09:00
Dominic Cooney 00526721d7 Gate telemetry behind isCategoryEnabled('code_intelligence')
Without this, the code_intelligence category in the telemetry defaults
map had no effect — captureToolUsage doesn't check per-category gating.
Now telemetry is only emitted when the category is enabled, matching the
pattern used by browser, checkpoints, skills, focus_chain, and subagents.
2026-03-27 15:03:36 +09:00
Dominic Cooney 9852d459ba Address review feedback: fix validation ordering and symbol formatting
- Move consecutiveMistakeCount reset after parseQueries validation so
  empty-but-present queries (only comments/whitespace) correctly
  increment the mistake counter instead of silently resetting it
- Move say() call after query parsing so no dangling tool-start UI
  message appears when queries are invalid
- Only append () to callable symbol kinds (function, method, constructor)
  instead of unconditionally on all symbols, preventing misleading
  output like MyClass() or MY_CONSTANT()
2026-03-27 14:53:33 +09:00
Dominic Cooney 9153f36989 Fix cross-platform path handling in CodeIntelligenceToolHandler
Use toPosix() to normalize Windows backslash paths before splitting
in shortenPath(), ensuring consistent display on all platforms (Windows
JetBrains included).
2026-03-27 14:04:51 +09:00
Dominic Cooney 08047d6efd Add code intelligence settings UI, tool gating, and tests
- Add codeIntelligenceEnabled setting to state-keys, proto, and updateSettings
- Gate code_intelligence tool behind codeIntelligenceAvailable context flag
- Add settings toggle in Experimental section, only visible when PSI available
- Wire codeIntelligenceEnabled/Available through Controller -> webview state
- Add telemetry capture for code-intelligence tool usage
- Add CodeIntelligenceToolHandler unit tests (9 tests)
- Add code-intelligence context variation to system prompt integration tests
- Generate 12 new snapshots for code-intelligence across all model families
2026-03-27 13:51:27 +09:00
Dominic Cooney b970af74ca Add a code intelligence service. 2026-03-27 13:51:27 +09:00
Dominic Cooney a915122c6d fix: Transcode kanban demo video from H.264/MP4 to VP9/WebM (#9997)
JetBrains IDEs use JCEF (Chromium Embedded Framework) for webviews,
which often does not include H.264 decoding due to licensing
restrictions. This causes the kanban demo video to fail to play.

Transcode the video from H.264/MP4 to VP9/WebM, which is a royalty-free
codec universally supported in Chromium derivatives. This also reduces
the file size from 3.6MB to ~900KB.

Updated all references:
- Source component import (ClineKanbanLaunchModal.tsx)
- Git LFS tracking (.gitattributes)
- CI workflow LFS checks (publish.yml, publish-nightly.yml)
2026-03-27 07:39:05 +09:00
Robin Newhouse 835ed94736 fix: exclude new_task tool from system prompt in yolo/headless mode (#9958) 2026-03-26 12:10:47 -07:00
Robin Newhouse 00ca3d13fa test(oca): add messages api routing and stream helper tests (#9494) 2026-03-26 12:02:13 -07:00
CandiedUniverse 3f3a87aed9 Hooks: Notification hook polish (#9909)
* Create implementation plan doc

* Implement notification hook helper

* Remove generated proto artifacts from branch

* Remove implementation plan doc

* Update src/core/hooks/__tests__/notification-hook.test.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update src/core/hooks/notification-hook.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2026-03-26 10:10:15 -07:00
John Simone 7a0f11837e Add Kanban docs (#9988)
* add kanban docs

* fix rendering error in overview, drop kanban flags from commands

* fix stray link

---------

Co-authored-by: Renee Huang <100229782+reneehuang1@users.noreply.github.com>
2026-03-26 08:12:09 -07:00
Max 03d2d01eed chore: bump version to 3.76.0 (#9986) 2026-03-26 07:52:28 -07:00
Dominic Cooney db1b1c45bd chore: update dependencies flagged by npm audit (#9980) 2026-03-26 21:03:35 +09:00
Saoud Rizwan a4131e57d8 fix(cli): replace --tui hint with kanban description in migration view
The migration announcement didn't explain what Kanban is. Swap the
"run cline --tui" line for a one-liner describing the product so users
know what they're opting into. The --tui escape hatch is still
discoverable via the Exit menu item.
2026-03-25 22:52:22 -07:00
Saoud Rizwan 683dd9a741 chore(cli): bump version to 2.11.0 2026-03-25 19:24:48 -07:00
Saoud Rizwan 0d437f71b0 fix(cli): remove noisy install message when launching kanban 2026-03-25 19:24:20 -07:00
Saoud Rizwan fc77c0faea chore(cli): bump version to 2.10.0 2026-03-25 18:38:24 -07:00
Saoud Rizwan 12c85c4233 Update tips about kanban 2026-03-25 18:26:06 -07:00
Saoud Rizwan d6b7a1ab41 fix(cli): launch kanban directly with package manager fallback 2026-03-25 18:26:06 -07:00
CandiedUniverse 3926e7b404 Stabilize auth e2e onboarding tests and clean up mock server URL parsing (#9974)
* Fix tests that fail when kanban modal is visible

* Fix deprecation warning

* Improve isVisible() as per Greptile suggestion
2026-03-25 16:35:09 -07:00
Tony Loehr 5ba4314b9a feat: add toggle to disable feature tips in chat (#9973) 2026-03-25 15:28:09 -07:00
John Choi 9ccad7f764 refactor: replace hand-rolled YAML parser in refreshSkills with shared helper (#9956)
* refactor: replace hand-rolled YAML parser in refreshSkills with shared helper

The refreshSkills controller had its own line-by-line YAML parser that
only handled simple key: value pairs. Replace it with the shared
parseYamlFrontmatter helper already used by the skills discovery path.

Same output for name and description fields. The shared parser handles
edge cases (arrays, nested values, quoted colons) more robustly.

* refactor: inline parseYamlFrontmatter, remove redundant wrapper

Remove the parseFrontmatter wrapper since only `data` is used by
the caller. Inline the call directly at the use site.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: John Choi <johnchoi@MacBook-Pro.local>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 09:06:15 -07:00
Saoud Rizwan 3562f54dbf fix(cli): enable shell mode for kanban spawn on Windows
npx.cmd requires shell: true on Windows to resolve correctly.
2026-03-25 07:35:53 -07:00
Octopus d427d5d76a feat: upgrade MiniMax default model to M2.7 (#9886)
* feat: upgrade MiniMax default model to M2.7

- Add MiniMax-M2.7 and MiniMax-M2.7-highspeed to model list
- Set MiniMax-M2.7 as default model
- Keep all previous models as alternatives
- Update provider documentation

* fix: correct M2.7 cache pricing and update prompt caching docs

- Updated cacheReadsPrice from 0.015 to 0.03 for both MiniMax-M2.7 and
  MiniMax-M2.7-highspeed to match M2.5 pricing (same cache read rate
  across M2.x models)
- Updated prompt caching tip to explicitly mention highspeed variants

* fix: correct MiniMax model pricing to match official rates

- M2.7-highspeed/M2.5-highspeed/M2.1-lightning: $0.60/$2.40 (not $0.30/$1.20)
- M2.7 cache: reads $0.06/M (not $0.03), writes $0.375/M (not $0.0375)
- All models: cache writes $0.375/M (not $0.0375)

Ref: https://platform.minimax.io/docs/llms.txt

---------

Co-authored-by: PR Bot <pr-bot@minimaxi.com>
2026-03-25 05:17:13 -07:00
Saoud Rizwan 072e2887b0 fix(cli): add --tui flag to TUI e2e tests to bypass Kanban redirect
The Kanban launch-by-default feature (beb54a4) redirects bare `cline`
invocations to Kanban, which blocks all TUI tests that launch without
`--tui`. Adding the flag ensures tests reach the legacy TUI as expected.
2026-03-25 04:36:12 -07:00
Saoud Rizwan 9c71a6f021 feat(webview): add Cline Kanban launch modal and queue announcements (#9963)
* feat(webview): add dedicated Cline Kanban launch modal

* fix(ci): fetch LFS media assets in publish workflows
2026-03-25 04:32:09 -07:00
Saoud Rizwan 7627a382aa feat(cli): launch kanban by default with migration view (#9914)
* feat(cli): refresh welcome banner and kanban launcher

* feat(cli): launch kanban by default with migration view

* feat(cli): add kanban process lifecycle management

Detach the kanban child process on Unix so it gets its own process
group, forward signals to the group for graceful shutdown, and fall
back to SIGKILL after a 10s timeout. Resolves exit codes from signals
correctly (130 for SIGINT, 143 for SIGTERM).
2026-03-25 02:01:56 -07:00
Tomás Barreiro 978c633c90 Add KanBan to remote config [PF-632] (#9959)
* Add KanBan to remote config

* Update tests
2026-03-25 02:33:52 +01:00
Tony Loehr e807b520e0 feat(cli): add rotating feature tips during thinking/acting phases (#9874)
* feat(cli): add rotating feature tips during thinking/acting phases

Port the FeatureTip component from the VSCode extension (PR #9799) to the
CLI. Shows rotating educational tips below the ThinkingIndicator while Cline
is processing, appearing after a 2-second delay and cycling every 8 seconds.

Includes 17 tips covering:
- Core features: .clinerules, Plan/Act mode, checkpoints, MCP servers
- CLI-specific: /settings, /skills, /history, /compact, /reportbug
- Workflows: kanban, auto-approve toggle, history navigation, @ mentions
- Images via --images flag, browser testing, double-check completion

* Update FeatureTip.tsx

* Apply suggestions from code review

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: resolve FeatureTip.tsx syntax errors (duplicate export, missing tipIndex state)

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-24 17:57:35 -07:00
John Choi f3a3f30db5 feat: add repeated tool call loop detection (#9933)
* feat: add repeated tool call loop detection

Detect when the LLM calls the same tool with identical arguments
repeatedly, which wastes tokens without making progress. This is
the #1 active complaint in the Cline issue tracker (13+ open issues
including #9923, #9916, #9846, #9816).

Two-stage escalation:
- Stage 1 (3 identical calls): inject a warning nudging the LLM
  to try a different approach
- Stage 2 (5 identical calls): trigger the existing
  consecutiveMistakeCount escalation (asks user or fails in YOLO)

Detection uses JSON.stringify with a sorted key replacer for
deterministic comparison. Metadata params like task_progress
(which change every call even when actual tool arguments are
identical) are stripped from the comparison.

Complementary to fileReadCache, which deduplicates file content but
still allows the tool call to succeed and consume a turn. Loop
detection catches the repeated call pattern itself.

Changes:
- loop-detection.ts: shared helper (toolCallSignature, checkRepeatedToolCall)
- TaskState.ts: add lastToolParams, consecutiveIdenticalToolCount
- ToolExecutor.ts: call checkRepeatedToolCall in handleCompleteBlock
- responses.ts: add formatResponse.repeatedToolCall
- loop-detection.test.ts: 5 tests

Manually verified: CLI test confirms soft warning at call 3,
YOLO mode failure at call 5.

Refs: #9923, #9916, #9846, #9816

* fix: address review feedback on loop detection

- Change hardEscalation threshold from >= to === so it fires exactly
  once at count 5, matching softWarning behavior
- Widen toolCallSignature param type to Partial<Record<string, string>>
  to match actual block.params type from ToolExecutor
- Add negative boundary assertions to verify no false positives at
  calls 0, 1, 3, 4

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: reset loop detection state when user continues after mistake_limit_reached

When hard escalation fired at count === 5 and the user clicked
"continue", consecutiveIdenticalToolCount was never reset. The count
would exceed 5 but === 5 never matched again, silently disabling
loop detection for the rest of the task.

Reset consecutiveIdenticalToolCount, lastToolName, and lastToolParams
alongside the existing consecutiveMistakeCount reset so the detector
fully re-arms after the user continues.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: John Choi <johnchoi@MacBook-Pro.local>
2026-03-24 13:40:31 -07:00
Igor Tceglevskii f1c7934064 fix: prevent OOM crash from globby's eager .gitignore scanning in lis… (#9917)
* fix: prevent OOM crash from globby's eager .gitignore scanning in listFiles

Replace globby's gitignore:true (which reads ALL .gitignore files in the
entire tree upfront, including inside gitignored directories) with
incremental .gitignore reading during BFS traversal.

In projects with large gitignored vendored dependencies containing many
nested repos, globby collects thousands of patterns, builds a massive
regex, and V8 runs out of memory during regex compilation (~488MB).

The fix reads .gitignore files only from directories the BFS actually
enters. Gitignored directories are never entered, so their .gitignore
files are never parsed and the pattern count stays small.

- Set gitignore:false, handle .gitignore ourselves
- Read root .gitignore in buildIgnorePatterns() to seed initial patterns
- Read subdirectory .gitignore lazily during globbyLevelByLevel BFS
- Accumulate patterns in currentIgnore so deeper levels respect them
- Add 4 tests: root patterns, file patterns, subdirectory .gitignore,
  and OOM-prevention (no reading inside gitignored dirs)

* Code review followup

* Potential fix for code scanning alert no. 147: Incomplete string escaping or encoding

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-03-22 15:20:57 -07:00
Robin Newhouse 1d42da5248 Add tool-specific error messages for replace_in_file and execute_command (#9710)
Replace generic "missing parameter" errors with targeted guidance for
the two tools observed failing most in SWE-bench (6% of failures).
The new messages include the expected format (SEARCH/REPLACE blocks,
XML example) without the 30-line boilerplate reminder.

Made-with: Cursor
2026-03-21 11:57:00 -07:00
Ara 7f3974a827 fix: read cache_write_tokens from OpenRouter API instead of hardcoding 0 (#9871)
* fix: read cache_write_tokens from OpenRouter API instead of hardcoding 0

- Read prompt_tokens_details.cache_write_tokens from OpenRouter stream usage
  chunks instead of hardcoding cacheWriteTokens to 0
- Read native_tokens_cache_write from generation endpoint fallback
- Replace fragile hardcoded model ID switch statement for cache_control blocks
  with prefix-based matching (anthropic/, minimax/) so new models automatically
  get prompt caching enabled
- Add unit test verifying cache_write_tokens are correctly extracted

Co-authored-by: Ara <arafat.da.khan@gmail.com>

* fix: read cache_write_tokens from OpenRouter API instead of hardcoding 0

- Read prompt_tokens_details.cache_write_tokens from OpenRouter stream usage
  chunks instead of hardcoding cacheWriteTokens to 0
- Read native_tokens_cache_write from generation endpoint fallback
- Replace fragile hardcoded model ID switch statement for cache_control blocks
  with prefix-based matching (anthropic/, minimax/) so new models automatically
  get prompt caching enabled
- Add unit test verifying cache_write_tokens are correctly extracted

Co-authored-by: Ara <arafat.da.khan@gmail.com>

* Release v3.74.0 Notes

* Release v3.74.0 Notes

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: alex-lum <alex@cline.bot>
2026-03-20 15:46:29 -07:00
CandiedUniverse d40ab56aff Changelog and version bump for release (#9910) 2026-03-20 15:29:45 -07:00
CandiedUniverse bbdf445db7 fix: prevent resume asks from unblocking on abort (#9908)
* fix: prevent resume asks from unblocking on abort

* Add test case for resume_completed_task

* Prevent flaky tests
2026-03-20 10:51:16 -07:00
CandiedUniverse d992a3bf21 Stabilize hooks fixture tests with per-scenario isolation (fix flaking tests) (#9868)
* Refactor flaking hooks tests

Fix flaking hooks tests

Strengthen hooks fixture test isolation

* Address Greptile hooks test review

* Harden Windows hook timing tests

* Loosen hook cancellation timing margins

* Fixing more flaking tests
2026-03-20 09:50:14 -07:00
Max ace95988f8 fix: resolve deadlock when clicking New Task/Exit after task completion (#9905)
The presentation scheduler introduced in ff05ec3bb awaits in-flight
flushes during dispose(), but ask() blocks indefinitely on pWaitFor
waiting for user input. When abortTask() sets abort=true and then
awaits scheduler.dispose(), the in-flight flush (blocked on
ask("completion_result")) never resolves, deadlocking the UI.

Add abort flag check to ask()'s pWaitFor condition so blocked asks
unblock immediately when the task is aborted.

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 08:53:21 -07:00
Tony Loehr 54726f1677 docs: fix SDK documentation accuracy and completeness (#9856)
* docs: fix SDK documentation accuracy and completeness

- Fix setPermissionHandler API Reference to use correct async/return signature
  (was showing old callback pattern with (request, resolve) => void)
- Remove non-existent PermissionResolver type from Exported Types table
- Fix PermissionHandler type description to match actual signature
- Add missing hooksDir option to ClineAgentOptions documentation
- Fix newSession() example to use real model IDs
- Replace developer personal path in Full Example with generic path
- Use placeholder for version in initialize() example to avoid staleness
- Expand Stop Reasons table and add note about current implementation
- Add missing key exported types: AcpSessionStatus, AcpSessionState,
  RequestPermissionRequest/Response, PermissionOption, SessionUpdatePayload,
  SessionModelState, ModelInfo, TextContent/ImageContent/AudioContent,
  SetSessionMode/Model request/response types, TranslatedMessage

* docs: improve SDK visibility and disambiguate from API code examples

- Move SDK page higher in Cline CLI nav (after Installation, before Interactive Mode)
- Add sidebarTitle 'SDK (Programmatic Use)' for clearer nav label
- Rename api/sdk-examples to 'Code Examples' to avoid naming confusion with the Cline SDK
- Update API overview card title to match

* Apply suggestions from code review

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* docs: add ClientCapabilities, Error Handling, and BYO API key docs to SDK

- Document clientCapabilities object and its effect on agent behavior
- Add Error Handling section with all throwable errors per method
- Expand BYO API key setup with concrete CLI auth examples

* docs: fix duplicated Stop Reasons table rows from code review

* docs: fix 3 accuracy issues found in source code audit

- Fix protocolVersion: was '0.9.0' (fabricated), actually 1 (number) from @agentclientprotocol/sdk
- Fix clientCapabilities: was claiming they change SDK behavior, but ClineAgent always uses standalone providers (capabilities only matter via AcpAgent stdio wrapper)
- Fix permission options: remove reject_always (never sent by agent, only allow_once/allow_always/reject_once are used)

* docs: clarify custom clineDir usage with CLI --config flag

Address PR review feedback: the BYO auth section mentioned custom
clineDir without showing how to target it from the CLI. Remove the
vague reference and add explicit --config flag documentation with
side-by-side SDK and CLI examples.

* docs: remove misleading 'by default' qualifier from SDK BYO auth section

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-19 21:01:24 -07:00
Saoud Rizwan 6308fef0a9 fix(cli): use kanban@latest to always fetch newest version (#9898)
* fix(cli): use kanban@latest to always fetch newest version

npx -y kanban may use a cached version. Using @latest ensures
users always get the most recent kanban release.

* chore(cli): bump version to 2.8.2 and update changelog
2026-03-19 19:37:53 -07:00
CandiedUniverse b3fc79b8ce Remove example hooks (#9896) 2026-03-19 18:42:55 -07:00
CandiedUniverse ff05ec3bbe Latency improvements for remote workspaces (#9858)
* Implement minimal change set for latency improvements

Cline's code review improvements

Further code review improvements

* fix: address code review issues for presentation scheduler

- Add reset() method to TaskPresentationScheduler to prevent stale
  timer leaks between API request retries within the same task
- Call presentationScheduler.reset() in streaming state reset section
- Fix hadVisibleAssistantContent to track reasoning content, not just
  text, preventing every reasoning chunk from getting immediate priority
- Remove unused 'low' priority from PresentationPriority type and
  associated cadence configuration (YAGNI)
- Trim TaskLatencyTrigger to only values actually used: text/reasoning/tool
- Add JSDoc to isRemoteWorkspaceEnvironment documenting the heuristic
  fallback and its false-positive risk
- Add Logger.warn for invalid cadence env-var overrides
- Add comment at scheduler construction explaining detection promise
  dependency on remoteWorkspaceDetectionPromise
- Add comments to CLI host bridge about intentional remoteName omission
- Expand test coverage: reset(), coalescing, priority upgrade tests

* fix: address code review issues in latency/presentation scheduler

- Fix #1/#3: Set didPresentAnyContent=true for text and tool_calls chunks
  so coalescing actually activates for text-only and tool streams (was
  only set for reasoning chunks, defeating the 40/90ms cadence goal)

- Fix #2: Re-check flushInProgress after awaiting in-flight flush in
  runFlushCycle to prevent two concurrent callers from both proceeding
  past the guard and starting concurrent flushes

- Fix #4: Document flushNow() disposed no-op contract so callers
  understand the finalization guarantee

- Fix #5: Add disposed guard to reset() to prevent post-dispose state
  mutation

- Fix #6: Remove platform/version heuristic from isRemoteWorkspaceEnvironment
  — only use remoteName. The substring match on 'remote' produced false
  positives for version strings like '1.0.0-remote-fix'. Non-VSCode hosts
  should populate remoteName explicitly to opt in to the higher cadence.

- Fix #7: Add remoteWorkspaceDetectionSettled flag and warn if getDelayMs
  is called before detection resolves, making the timing dependency
  explicit and detectable in production logs

- Fix #8: Upgrade disabled-scheduler bypass error from Logger.debug to
  Logger.warn so silent flush failures are visible

- Update latency.test.ts: replace heuristic test with false-positive
  regression tests and add null/empty-field coverage

* fix: address code review issues in latency/presentation scheduler

- Fix flushNow race condition: wait for all in-flight flushes to drain
  before setting pendingPriority so the post-flush continuation cannot
  steal it, guaranteeing at least one flush runs after flushNow() returns
- Add regression test for the flushNow race condition
- Fix disabled-path (CLINE_DISABLE_PRESENTATION_SCHEDULER): use
  presentationScheduler.flushNow() instead of a fire-and-forget void
  call so the presentAssistantMessage lock/pending-updates mechanism
  is respected when the scheduler is bypassed
- Rename didPresentAnyContent -> didScheduleAnyContent to accurately
  reflect that content has been scheduled, not necessarily flushed
- Update stale comment in streaming loop to match new variable semantics
- Upgrade remote workspace detection failure log level from debug to warn
- Document reset() interaction with in-flight flush on already-reset state
- Document empty-string remoteName edge case in getHostVersion.ts

* refactor: polish presentation scheduler for production readiness

- Extract PresentationPriority type to shared presentation-types.ts,
  breaking the latency.ts → TaskPresentationScheduler.ts type coupling
- Remove redundant pendingWhileFlushing flag from TaskPresentationScheduler;
  pendingPriority alone is sufficient for the post-flush continuation check
- Cache env var reads in latency.ts at module load (hot path optimization)
- Inline flushAssistantPresentation() one-liner into the scheduler constructor
- Make processNativeToolCalls protected to enable type-safe test access
- Remove as any cast in Task.processNativeToolCalls.test.ts

* Fixes as per Greptile review feedback

* Further fixes as per Greptile feedback

* Further fixes as per Greptile feedback
2026-03-19 17:05:49 -07:00
Ara bde7049c01 Release v3.74.0 Notes (#9879) 2026-03-18 19:08:50 -07:00
Ara 7cd06744ad feat: implement dynamic free model detection for Cline API (#9878)
Replace hardcoded free models list with runtime resolution from
recommended models. The handler now dynamically fetches free model
IDs using refreshClineRecommendedModels with fallback to static
defaults, and normalizes model IDs for consistent comparison.
2026-03-18 18:55:06 -07:00
shey-cline c88d3238cf Replace Error Message When Not Logged In to Cline (#9632) 2026-03-18 16:01:06 -07:00
jessy-cline 852ca2348f fix(ui): align ClineRulesToggleModal padding with ServersToggleModal (#9870)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-03-18 14:13:39 -07:00
CandiedUniverse 7091ccf2c7 Fix flaky CLI Enter-key handling across Windows/test environments (#9867)
* fix(cli): normalize enter key handling in ink inputs

* fix(cli): pass input through auth select enter handling
2026-03-18 12:20:25 -07:00
Mathis ad6c33ac5b feat: add file read deduplication cache to prevent repeated reads (#9836)
* feat: add file read deduplication cache to prevent repeated reads

- Add fileReadCache to TaskState for tracking read files per task
- ReadFileToolHandler checks cache before reading, returns cached content on repeat reads
- Warns model after 3+ reads of same file to stop re-reading
- WriteToFileToolHandler and ApplyPatchHandler invalidate cache on file changes
- Reduces wasted API tokens from models reading same files repeatedly

* fix: address file read cache gaps - image blocks, execute_command, redundant invalidation

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* PR changes

- __`TaskState.ts`__ — Simplified cache type from `{ content: string; readCount: number; imageBlock? }` to `{ readCount: number; mtime: number; imageBlock? }`. Dropped `content` to save memory; added `mtime` for external change detection.

- __`ReadFileToolHandler.ts`__ — Four improvements:

  - __Removed redundant `.set()` call__ — reviewer was correct that objects are modified by reference in Map
  - __Added mtime-based cache validation__ — on cache hit, `stat()` the file and compare mtime. If the file was modified externally (user edited in their editor), the cache entry is evicted and a fresh read occurs
  - __Dropped content from cache__ — cache now only stores metadata (readCount, mtime, imageBlock). On cache hits, the file is re-read from disk, addressing memory concerns
  - __Softened readCount >= 3 warning__ — removed the aggressive "Do NOT read this file again" language; now says "Please use the information you already have and proceed with your task"

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-18 10:38:23 -07:00
Tony Loehr 71e312e92a feat: add feature tips tooltip during thinking state (#9799)
* feat: add feature tips tooltip during thinking state

Show rotating feature tips below the Thinking indicator to keep users engaged and educate them on features like Double-Check Completion, .clinerules, Plan Mode, MCP Servers, checkpoints, and more.

- New FeatureTip component with 12 curated tips
- 2s delayed appearance, 8s cycling with fade transitions
- Visible throughout entire thinking/reasoning phase
- Proper timer cleanup on unmount

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: remove unused useMemo import from FeatureTip

* fix: increase test delays in QuitCommand.test.tsx for Windows CI reliability

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: add smooth fade-in for first tooltip appearance

The first tooltip was appearing abruptly because the element went from
not-in-DOM (return null) to opacity-100 instantly. Added hasFadedIn state
with requestAnimationFrame to ensure the CSS transition applies on initial
render, giving the first tip a smooth 300ms fade-in.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-17 13:51:37 -07:00
Charlotte Stinson 5903840f79 Added Fields to Responses API for the Oracle Code Assist (OCA) Provider (#9852)
* added fields to responses api

* fix temp problem

* cleaning up

* clean modelId

* Apply suggestion from @greptile-apps[bot]

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Charlotte Stinson <charlottestinson@Charlottes-MacBook-Pro.local>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-17 13:41:39 -07:00
ClineXDiego 0c677b63db fix(browser): skip WebP for GLM and Devstral models running through llama.cpp (#9837)
llama.cpp's STB image library doesn't support WebP format. Users running
GLM 4.6V, GLM 4.5, and Devstral models via llama.cpp server (openai-compatible
endpoint) were hitting a 400 error when using the browser tool because Cline
sends screenshots as WebP by default.

modelDoesntSupportWebp() only checked for Grok models. Extend it to also
cover GLM and Devstral model families using the existing family detection
functions. Also update isGLMModelFamily() to handle space-separated model IDs
like 'GLM 4.6V' (the format llama.cpp server reports for this model).

Fixes #8203
2026-03-17 14:57:40 -03:00
ClineXDiego b741135f85 fix(litellm): respect user-configured context window in getModel() (#9834) 2026-03-17 05:36:44 -07:00
Ara 2eab216815 fix(wandb): honor explicit model IDs outside static catalog (#9839) 2026-03-16 16:40:28 -07:00
Ara e57174eec8 fix(fireworks): add missing serverless models and pricing (#9810)
* feat: refresh Fireworks serverless model defaults

* fix(fireworks): handle cached token usage and write pricing

* fixing maxtokens for gemini family

* feat(fireworks): add missing serverless models and pricing
2026-03-16 14:28:23 -07:00
Max ad4631c682 bump cline version (#9833) 2026-03-16 13:36:41 -07:00
Mathis aae23e8685 fix: Claude Code provider failing with 4.6 models and newer CLI versions (#9783)
* fix: Claude Code provider failing with 4.6 models and newer CLI versions

- Update --disallowedTools list to match current Claude Code CLI tools
  (12 new tools were unblocked, causing models to use native tool_use
  instead of Cline's XML tools)
- Fix rate_limit_event handling for new CLI format (top-level type
  instead of system subtype)
- Handle unknown content block types and new message types gracefully
- Fix assistantHasContent check to account for tool calls accumulated
  via toolUseHandler even when useNativeToolCalls is false

* resolved .include mismatch to .containEql

* Update src/integrations/claude-code/types.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Removed `LegacyRateLimitEvent` type and its union reference from `types.ts`

* Fixed loop with async tool calls in new claude code.

* PR review feedback fixes

__Fix #2 (claude-code.ts):__ Cleaned up the error field check — replaced verbose `"error" in message` guard + ternary chain with a simpler `message.error` check using optional chaining and nullish coalescing (`message.content?.[0]` + `?? fallback`).

__Fix #3 (claude-code.ts):__ Replaced `message.content.length > 0 ? message.content[0] : undefined` with `message.content?.[0]` using optional chaining for the `stop_reason` block.

__Fix #4 (claude-code.ts):__ Replaced repeated `(content as any)` casts in the `default` switch case with a single typed cast: `const unknownBlock = content as { type: string; text?: string }`, making the code cleaner and safer.

__Fix #5 (ApplyPatchHandler.ts):__ Replaced both `await import("node:path")` and `require("node:path")` dynamic imports with a static `import { resolve as resolvePath } from "node:path"` at the top of the file.

* Remove file read deduplication feature (moved to separate PR)

* Remove ReadFileToolHandler file-not-found test (moved to separate PR)

* Add LegacyRateLimitEvent type for older CLI format

* Restore ReadFileToolHandler.ts and test from upstream/main (fix stale local main revert)

* Revert ReadFileToolHandler.ts to match fork main (no try/catch, no test file)

* manually reverting back

* Update src/core/api/providers/claude-code.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Restore ReadFileToolHandler.ts and test to match cline/cline upstream main

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-16 13:01:55 -07:00
dependabot[bot] 0ff27591d5 chore(deps-dev): bump lodash (#8803)
Bumps the npm_and_yarn group with 1 update in the /testing-platform directory: [lodash](https://github.com/lodash/lodash).


Updates `lodash` from 4.17.21 to 4.17.23
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.21...4.17.23)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.17.23
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-16 12:25:46 -07:00
dependabot[bot] 23127f22de chore(deps): bump qs from 6.14.1 to 6.15.0 (#9343)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.1 to 6.15.0.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.1...v6.15.0)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.15.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-16 12:00:02 -07:00
CandiedUniverse 57ed14d1b1 Fix issue with Windows notification (#9743)
* Fix issue with Windows notification

Fix Windows proto tooling

Fix Windows unit test path normalization

Revert "Fix Windows unit test path normalization"

This reverts commit 73400a3ca6f0300d009f7c8238a016d769186f3a.

Remove package-lock.json changes

* Remove unnecessary changes

* Use command approval string for notifications

* Address PR feedback on Windows notifications

* Fix Windows protoc path for CI

* Polish notification safety and test coverage

* Fix unfound tests in CI

* Harden Windows notifications and protoc execution

* Fix Windows path normalization in glob test

* Fix as per Greptile feedback
2026-03-16 09:44:20 -07:00
aikido-autofix[bot] a769585406 fix(security): update dependencies (#9812)
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
Co-authored-by: Max <maxpaulus43@gmail.com>
2026-03-16 09:15:40 -07:00
CandiedUniverse c44b29b002 Fix Windows CLI tests related to /q and /exit (#9747)
* Fix flaky Windows CLI quit slash tests

* Refine CLI slash command handling and test stability

* Address Greptile cleanup feedback
2026-03-16 07:59:26 -07:00
dependabot[bot] bb4e397a51 chore(deps): bump undici from 7.20.0 to 7.24.3 (#9825)
Bumps [undici](https://github.com/nodejs/undici) from 7.20.0 to 7.24.3.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v7.20.0...v7.24.3)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 7.24.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-16 07:52:50 -07:00
Saoud Rizwan 9824d8d476 Bump CLI version from 2.7.0 to 2.7.1 2026-03-15 20:36:02 -07:00
Saoud Rizwan a46c5288ca Fix Notification hook getting called by command output asks 2026-03-15 20:08:06 -07:00
Mohammad Bakir 91b947de69 feat: Add W&B Inference by Coreweave as provider (#9800)
* feat(wandb): add W&B Inference by CoreWeave provider

Adds support for W&B Inference as an API provider using a W&B API key.
Implements a provider handler with OpenAI-compatible streaming and a static
model catalog, and wires the provider through the API layer, configuration
schema, storage, CLI model picker, and settings UI.

* Updated input/output price of NVIDIA-Nemotron

* Updated helpText

* handle reasoning tokens in streaming respons

* Added clarifying comment on how W&B token usage is reported and why cached tokens

* fix: restore proto field numbers changed by generation script

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

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-13 16:06:35 -07:00
Saoud Rizwan 7b25a21b26 fix(cli): add -y flag to npx kanban to auto-confirm install 2026-03-13 15:47:18 -07:00
Ara 1d1071dcf5 fix: consolidate Parallel tool-calling fixes (#9738)
* fix: consolidate parallel tool-calling fixes

* test(snapshot): fix vertex gemini3 snapshot newline

* fix gemini toolcall id collision (#9768)

* test(snapshot): fix vertex gemini3 snapshot newline

* fix(gemini): prevent native tool-call ID collisions

* fixing maxtokens for gemini family

* test(gemini): assert fallback tool call ids
2026-03-13 09:20:23 -07:00
Dominic Cooney 8d07b7d6cb fix: catch errors in path-based tool handlers instead of crashing (#9732)
* fix: catch errors in path-based tool handlers instead of crashing

ListCodeDefinitionNamesToolHandler, ListFilesToolHandler, and
SearchFilesToolHandler let exceptions from their core operations
propagate through ToolExecutor's re-throw path, crashing the CLI
process. This is the same class of bug fixed for ReadFileToolHandler
in #9730.

Changes per handler:
- Wrap the core operation in try/catch, returning formatResponse.toolError()
  on failure so the model can see the error and recover gracefully.
- Move consecutiveMistakeCount reset to after a successful operation so
  repeated failures accumulate toward the yolo-mode mistake limit.
- Increment consecutiveMistakeCount on caught errors.

Add end-to-end tests exercising each handler with a mock TaskConfig,
covering: non-existent paths, missing parameters, failure accumulation,
and success-based counter reset.

* address review: expand try/catch scope, add stub-based tests

- Include resolveWorkspacePath inside try/catch in
  ListCodeDefinitionNamesToolHandler and ListFilesToolHandler (matching
  SearchFilesToolHandler's pattern) so path resolution failures are
  also caught gracefully.
- Fix trivially-true assertion in file-not-a-directory test.
- Add 6 new stub-based tests that force core operations to throw:
  parseSourceCodeForDefinitionsTopLevel, listFiles, and
  determineSearchPaths — verifying the catch paths return
  formatResponse.toolError() and increment consecutiveMistakeCount.
- Total: 19 passing tests (up from 13).

* address review: move clineignore check before IO in ListFilesToolHandler

Move the .clineignore access validation before resolveWorkspacePath and
listFiles so blocked paths are rejected without incurring IO cost.
Also ensures consecutiveMistakeCount is only reset after all
validations and the core operation succeed.

* address review: increment counter on clineignore denial

Clineignore denial in ListFilesToolHandler now increments
consecutiveMistakeCount so repeated attempts at blocked paths
accumulate toward the yolo-mode mistake limit. Added 2 tests
verifying single and repeated clineignore denials.
Total: 21 passing tests.

* fix: increment consecutiveMistakeCount when SearchFilesToolHandler searches fail

Previously, SearchFilesToolHandler's executeSearch() caught regexSearchFiles
errors and returned {success: false}, but the handler unconditionally reset
consecutiveMistakeCount to 0 even when ALL searches failed. This contradicted
the PR's goal of accumulating failures toward the yolo-mode mistake limit.

Now we check if any search succeeded before resetting the counter:
- If at least one search succeeded: reset to 0 (existing behavior for successes)
- If all searches failed: increment the counter (new fix)

Also added comprehensive test coverage for this scenario, including tests for:
- regexSearchFiles throwing errors
- Repeated search failures accumulating
- Successful search resetting the counter after failures

* fix: detect error strings in ListCodeDefinitionNamesToolHandler

parseSourceCodeForDefinitionsTopLevel returns error strings instead of
throwing exceptions for file paths and non-existent directories. The
handler now detects these error conditions and increments
consecutiveMistakeCount so repeated failures accumulate correctly.

This addresses Greptile's feedback that the counter was unconditionally
resetting to 0 for all real-world failure modes of this handler.
2026-03-12 20:58:06 -07:00
Dominic Cooney aacc69a558 fix: catch file-not-found in ReadFileToolHandler instead of crashing CLI (#9730)
* fix: catch extractFileContent errors in ReadFileToolHandler

When extractFileContent throws (e.g. file not found), the exception
propagated through ToolExecutor which re-threw it, crashing the CLI
process with exit code 1.

Now file read errors are caught and returned as formatResponse.toolError()
so the model can see the error and recover gracefully (e.g. try a
different file path) instead of terminating the entire task.

Also increments consecutiveMistakeCount so the yolo-mode mistake limit
still functions correctly.
2026-03-13 10:52:32 +09:00
Max a27bedffb6 max/cli tui e2e tests (#9753)
* add tui UI tests

using microsoft/tui-test library, can run many headless versions of
cline and execute ui tests (requires Node <= 20)

improve brittle sleep calls

* add cli-tui-tests github action

---------

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-03-12 16:06:25 -07:00
Diego Ferreyra bbeecefe84 docs: fix broken Oracle Code Assist website link (#9782)
The Oracle Code Assist URL moved from /artificial-intelligence/code-assist/
to /application-development/code-assist/. The old URL returns a 404.

Fixes #9776

Co-authored-by: gatof81 <gatof81@users.noreply.github.com>
2026-03-12 11:56:34 -03:00
alex-lum 50b57f472f feat(telemetry): add provider to task.tokens event (#9762) 2026-03-11 17:30:03 -07:00
CandiedUniverse 0e7e0099cd Changelog and version bump for release (#9775) 2026-03-11 17:21:04 -07:00
AJ Juaire 44cbfe9d9c Update Jupyter Notebook gifs (#9772)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-03-11 16:25:46 -07:00
Saoud Rizwan 4ecccf5105 feat(cli): add mcp add shortcuts for stdio and http servers (#9773) 2026-03-11 16:17:43 -07:00
Ara 6d29bc6551 fix(prompt): resolve native tool placeholder interpolation (#9764)
* fix(prompt): resolve CWD and MULTI_ROOT_HINT in native tool schemas

* refactor(prompt): share multi-root hint constant
2026-03-11 08:10:58 -07:00
Saoud Rizwan 820057308a feat(cli): add kanban alias command (#9763) 2026-03-10 21:57:16 -07:00
Ara 7355f7e3b9 fix(gemini): cap flash output tokens to 8192 across providers (#9749) 2026-03-10 14:10:14 -07:00
Max 156f18f7b2 call telemetry service after initializeCli (#9752)
- calling telemetry service before initializeCli call causes a
"hostprovider not initialized error", which invokes errorservice, which
causes another "hostprovider not initialized error", which was breaking
this cline use case: echo "say hello" | cline

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-03-10 11:50:34 -07:00
Tomás Barreiro 6129caa423 Get user consent before loading images in Markdown (#9745)
* Add an UsafeImage handler that asks for consent before loading specific images

* Fix div as child of p

* Render self-contained images without consent

* Render alt conditionally and store approved src

* use a block span
2026-03-09 21:06:57 -07:00
alex-lum ffa4785f43 fix(telemetry): restore cache token and cost metrics in captureTokenUsage (#9741)
* feat(telemetry): restore cache token and cost metrics in captureTokenUsage

Add optional `options` parameter to `captureTokenUsage()` to record
cache write/read token counters and cost histograms that were
previously missing from telemetry.

- Extend `captureTokenUsage` with `cacheWriteTokens`, `cacheReadTokens`,
  and `totalCost` fields via an options object
- Record `cline.tokens.cache_write`, `cline.tokens.cache_read` counters/
  histograms and `cline.tokens.cost` histogram when provided
- Forward cache/cost data from both streaming `onUsageChunk` and
  `getApiStreamUsage` fallback call sites in the task loop
- Add 3 test cases covering options forwarding, undefined skipping,
  and event property inclusion

* refactor(telemetry): extract shared TokenUsage type and add value assertions

Address PR review feedback:
- Extract shared TokenUsage interface used by both captureTokenUsage and
  captureConversationTurnEvent, preventing future drift
- Add numeric value assertions for cache/cost counters and histograms
  so regressions recording wrong values are caught
2026-03-09 15:55:23 -07:00
CandiedUniverse 92ec126dca Fix Windows unit test path normalization (#9742) 2026-03-09 13:23:47 -07:00
Ara c4c8b16afb chore: remove changesets bot artifacts (#9739) 2026-03-09 12:26:48 -07:00
Max 2eed79dcd7 use setSessionOverride instead of setGlobalState (#9707)
- cli was storing fields to persistent state when it shouldn't be. The
value of these flags should only live for the duration of the CLI
session

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-03-09 11:20:57 -07:00
shey-cline d39a53feed Add Padding to Retry Message (#9635) 2026-03-09 09:29:27 -07:00
Dominic Cooney cae9bff416 test: rebaseline vertex_gemini3.tools.snap (#9731)
Commit 55569efb7 changed the list_code_definition_names path parameter
description but did not update the snapshot baseline.
2026-03-09 07:57:05 -07:00
Saoud Rizwan 36618fb327 fix(cli): remount TUI only on width resize (#9736) 2026-03-09 04:03:59 -07:00
Saoud Rizwan a335b5cb3e fix(cli): prevent startup prompt replay on resize remount (#9735) 2026-03-09 03:30:01 -07:00
Saoud Rizwan bce71b4448 feat(cli): add --continue for current directory (#9726)
* feat: add cli continue flag for current directory

* docs(cli): clarify continue command examples
2026-03-08 19:54:44 -07:00
Robin Newhouse f6d2b4d9ac Add --auto-condense CLI flag to enable AI-powered context compaction (#9705)
Exposes the existing useAutoCondense setting as a CLI flag, following
the same pattern as --double-check-completion. This allows enabling
auto-condense in eval runs (e.g. SWE-bench via Harbor) to reduce
context exhaustion failures.

Made-with: Cursor
2026-03-08 16:28:48 -07:00
Robin Newhouse 911fcfda47 gemini-hc: add parameter descriptions to Gemini tool schemas (#9681)
The Gemini converter was the only provider that didn't include
parameter-level descriptions in native tool call schemas. Anthropic
and OpenAI converters both resolve param.instruction into each
parameter's description field. This was missing for Google/Gemini,
meaning the model only saw parameter names and types with no
explanation of what each parameter expects.

Made-with: Cursor
2026-03-08 16:27:50 -07:00
Robin Newhouse 55569efb74 fix(tools): prevent crash when list_files/list_code_definition_names receives a file path (#9680)
listFiles() passed unvalidated paths as globby's `cwd`, crashing with
"The cwd option must be a path to a directory" when the model provided a
file path instead of a directory. This affected ~22% of SWE-bench tasks.

- Add isDirectory guard in listFiles() before calling globby
- Fix listFiles() to use resolved absolutePath for cwd instead of raw dirPath
- Return actionable error in parseSourceCodeForDefinitionsTopLevel when
  path is a file, guiding the model to use read_file instead
- Clarify list_code_definition_names parameter description to
  distinguish directory input from file input

Made-with: Cursor
2026-03-08 16:07:03 -07:00
Robin Newhouse 18561ed59d prompt: add test verification rules and make CLI_RULES language-agnostic (#9679)
- S1: Don't modify test assertions to match buggy code
- S2: Run project's existing test suite to verify fixes
- CLI_RULES: Remove Node.js-specific examples (npm/tsc)

Made-with: Cursor
2026-03-08 15:58:13 -07:00
Saoud Rizwan fa7265fa33 feat: add Anthropic Opus 4.6 fast mode variants (#9725)
* feat: add Anthropic Opus 4.6 fast mode variants

* refactor: localize Anthropic fast mode beta constant

* fix: correct Anthropic 1M fast mode pricing
2026-03-08 15:31:37 -07:00
M.Yoshida(Jyuko Co.,Ltd) bf96223639 docs: add .github/copilot-instructions.md for AI coding agents (#9606)
* docs: add .github/copilot-instructions.md for AI coding agents

* docs: update copilot-instructions with provider, state, and CLI guidance
2026-03-08 14:51:55 -07:00
Saoud Rizwan c489f79508 fix(cli): apply task flags before welcome TUI mount (#9721) 2026-03-07 11:20:53 -08:00
CandiedUniverse 6ccd662a1f Hooks: Add feature toggle (toggled off by default) (#9671)
* Add implementation plan doc

* feat(hooks): reintroduce runtime hooks feature toggle

* fix: thread effective hooks toggle through hook execution

* test: cover hooks feature toggle visibility and settings wiring

* Remove implementation plan doc

* Move Hooks toggle to Advanced section in Feature Settings

* Fixes as per PR feedback

* Clarifying hooksEnabled

* Make hooksEnabled true by default

* Further fixes as per Greptile feedback

* Further fixes as per Greptile feedback

* Fix failing tests
2026-03-06 13:49:03 -08:00
Tomás Barreiro a2fa4d3b92 [ENG-1571] Enable CLI Error autocapture (#9686)
* Introduce the enableErrorAutocapture option

* Enable capturing CLI extension

* Capture exception immediately

* Handled uncaptured exceptions

* refactor

* Add tests

* Capture unhandledExceptions

* Add an error boundary to the ink app

* Wrap the App in the ErrorBoundary

* Check for consent before capturing error

* Add context to the error capturing

* Fix tests

* refactor

* Remove `unref`
2026-03-06 20:39:44 +01:00
CandiedUniverse c8f81374a3 Fix flaky hooks tests on Windows (#9690)
* test(hooks): reduce Windows hook-runner launch overhead

test(hooks): make Windows hook tests deterministic

refactor(hooks): use platform-agnostic launcher cache naming

Improvements as per Cline code review feedback

test(hooks): remove direct-node acceleration path and stabilize windows timings

* test(hooks): add deterministic launcher cache concurrency coverage

* Improvements as per Cline code review feedback

* Update src/core/hooks/__tests__/hookprocess.test.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Improvements as per Greptile feedback

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-06 10:46:34 -08:00
ClineXDiego eb25634bd4 fix(bedrock): handle thinking and redacted_thinking blocks in message conversion and streaming (#9424)
Fixes #9269 - Thinking blocks missing in Bedrock Opus 4.6

Changes:
- Add explicit handling for 'thinking' and 'redacted_thinking' content types
  in formatMessagesForConverseAPI() so they are silently skipped instead of
  triggering 'Unsupported content type: thinking' warnings
- Capture signature from additionalModelResponseFields thinking responses
- Add signature_delta handling in contentBlockDelta for streaming
- Add redacted_thinking block handling in contentBlockStart for streaming
- Extend ContentBlockStart/Delta interfaces with signature and data fields
- Add 'redacted_thinking' and 'document' to SupportedContentType union
- Add tests for thinking/redacted_thinking block filtering in message conversion
2026-03-06 10:41:43 -08:00
Max 1753d9dc15 release changelog and version bump (#9706)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-03-06 09:45:20 -08:00
Saoud Rizwan a562868cb9 feat(cli): add --auto-approve-all flag for interactive mode (#9698) 2026-03-06 02:08:59 -08:00
Saoud Rizwan bf5265758f feat(hooks): add Notification hook for attention boundaries (#9699)
* feat(hooks): add Notification hook for attention and completion

* chore(hooks): use default Notification template

* Revert "chore(hooks): use default Notification template"

This reverts commit 85f4e942fc.

* fix(hooks): escape JSON quotes in bash templates

* Revert "fix(hooks): escape JSON quotes in bash templates"

This reverts commit 29dfb9e01e.

* chore(hooks): preserve single-backslash template escaping

* fix(hooks): keep single-backslash JSON escaping in templates

* Revert "fix(hooks): keep single-backslash JSON escaping in templates"

This reverts commit b4c829489f.

* fix(hooks): keep escaped JSON echo template pattern
2026-03-06 02:07:25 -08:00
Saoud Rizwan 469752a201 feat(cli): add --hooks-dir flag for runtime hook injection (#9658)
* feat(cli): add --hooks-dir flag for runtime hook injection

Adds a --hooks-dir <path> CLI flag that allows passing an additional
hooks directory at spawn time. This enables orchestration tools (like
Kanbanana) to inject per-session lifecycle hooks without mutating
the user's global or workspace hooks directories.

The runtime hooks directory is included alongside existing global
(~/Documents/Cline/Hooks/) and workspace (.clinerules/hooks/)
directories during hook discovery. All hooks from all directories
are merged and run in parallel, so runtime hooks are purely additive.

* fix(cli): initialize runtime hooks before interactive startup
2026-03-05 23:33:41 -08:00
Ara 8fb2e8a3aa Adding gpt 5.4 models to chatgpt subscripiton (#9692)
* Adding gpt-5.4 to chatgpt subscription

* Fixing stuff

* Apply suggestion from @greptile-apps[bot]

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-05 18:06:17 -08:00
ClineXDiego aef32f52f9 fix: bypass git hooks on checkpoint initial commit (#9688)
Add --no-verify to the initial checkpoint commit in
CheckpointGitOperations.ts. This was already used for subsequent
commits in CheckpointTracker.ts but was missing from the initial
empty commit, causing Cline to fail to initialize when users have
global pre-commit hooks (e.g., conventional commits enforcement).

Fixes #9672
2026-03-05 19:02:00 -03:00
Dominic Cooney 2baf966db7 fix: handle streamableHttp reconnects and preserve OAuth redirect URIs across sessions (#9642)
- Make redirect URIs with dynamic ports valid, or reregister.
- Handle reconnects for streaming HTTP MCP servers.
2026-03-05 09:00:20 +09:00
alex-lum 152ba674da feat: add OTel tracking for AI output line/file metrics (lines added/deleted/changed, files created/deleted/moved) (#9562)
* feat: add telemetry for AI output accepted/rejected across tool handlers

Add line-level diff stats and file operation tracking to telemetry
events when users accept or reject tool outputs. Introduces a shared
`computeLineDiffStats` utility and `captureAiOutputAccepted`/
`captureAiOutputRejected` methods on the telemetry service, wired
into ApplyPatch, WriteToFile, ExecuteCommand, InsertContent, and
SearchAndReplace handlers.

* feat(telemetry): add source tracking for agent vs human edits

Add telemetry differentiation between agent-generated changes and
human modifications to capture more granular edit metrics:

- Add 'source' field to captureAiOutputAccepted telemetry events
- Track human edits by computing diff stats between agent's proposed
  content and final saved content
- Apply source tracking to ApplyPatchHandler and WriteToFileToolHandler
- Enable separate analytics for agent vs human contributions

This allows measuring how often and to what extent users modify
AI-generated code, providing insights into AI output quality and
user trust patterns.

* refactor(telemetry): centralize ai output attribution across file edit handlers

- add shared `AiOutputTelemetry` utility for accepted/rejected events
- refactor `WriteToFileToolHandler` and `ApplyPatchHandler` to use shared helpers
- preserve existing telemetry behavior (`source: "agent" | "human"`) while reducing duplication
- keep line diff/file-op attribution semantics unchanged

* fix(telemetry): use pre-save content for human edit line diff stats

The source:"human" telemetry was diffing agent content against
finalContent (post-save), which includes auto-formatting changes
from the editor. This inflated linesChanged/linesDeleted counts
when the formatter modified lines alongside the user's actual edits.

Use diff.applyPatch() to reconstruct the user's pre-save content
from the existing userEdits patch, excluding formatter noise from
the line diff stats.

* fixing syntax error

* refactor(telemetry): make next-hunk bounds check explicit

* remove comment

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

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-03-04 14:45:57 -08:00
Max 12f5dc2e9e update changelog and bump version numbers (#9664)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-03-04 13:39:15 -08:00
Saoud Rizwan 28d806a4e4 fix(openrouter): stop sending max_tokens in stream requests (#9634) 2026-03-04 18:48:59 +01:00
Ara e92c7de8c0 Restrict /test-jetbrains workflow trigger to authorized users (#9657)
Add author_association check so only MEMBER, OWNER, and COLLABORATOR
users can trigger the JetBrains test workflow via issue comments.
Previously any GitHub user could trigger it, allowing unauthorized
use of the GitHub App token and Actions minutes.

Fixes GHSA-5fq9-fh5x-w83r (SEC-29)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 09:13:41 -08:00
CandiedUniverse 718e5b53f6 Add model identifier to the JSON payload that hooks receive (#9646)
* Add provider/model context to all hook payloads

* Fixes as per Greptile feedback

* Further fixes as per Greptile feedback

* Further fixes as per Greptile feedback

* further fixes as per Greptile feedback

* Fix flapping hooks tests on Windows
2026-03-03 19:08:41 -08:00
Saoud Rizwan e484534bcb fix(task): process usage chunks independently from non-usage stream flow (#9576) 2026-03-03 12:27:20 -08:00
Dominic Cooney 2822723495 fix: stop infinite getLatestMcpServers RPC loop when opening MCP servers panel (#9643)
* fix: stop infinite getLatestMcpServers RPC loop when opening MCP servers panel

The ServersToggleModal useEffect had setMcpServers in its dependency array,
but the context provided an unstable inline wrapper around the useState setter,
creating a new function reference on every render. This caused the effect to
re-fire on every context re-render while the modal was visible, producing 14+
RPC calls in ~15ms.

- Remove setMcpServers from useEffect deps in ServersToggleModal (the effect
  should only fire when visibility changes)
- Replace inline arrow wrappers in ExtensionStateContext with direct references
  to the stable useState setters (setMcpServers, setRequestyModels,
  setHuggingFaceModels, setMcpMarketplaceCatalog)

* address review feedback: add setMcpServers back to deps, use property shorthand

- Add setMcpServers back to useEffect deps in ServersToggleModal now that the
  context passes the stable useState setter directly (per Copilot review)
- Remove eslint-disable comment since it's no longer needed
- Use property shorthand for setGroqModels and setBasetenModels in context value
2026-03-03 09:08:34 -08:00
Saoud Rizwan b5c0cc18d8 fix(subagent): fix subagents erroring out by handling context-window limit errors (#9637)
* fix(subagent): align error handling with main loop behavior

* fix(subagent): persist context truncation state across retries
2026-03-02 22:13:32 -08:00
Dominic Cooney fb04a9bd15 Log RPC size histogram. (#9626) 2026-03-03 14:53:30 +09:00
Renee Huang 6def83a5d9 [doc] api doc changes (#9581)
* initial doc changes

* rm general api endpoint

* Add API documentation section with endpoint reference pages

- Add new API docs: overview, getting-started, authentication, models,
  chat-completions, errors, and SDK examples
- Update api/reference.mdx with expanded endpoint documentation
- Update enterprise-solutions/api-reference.mdx with improvements
- Update docs.json with new API section navigation entries

---------

Co-authored-by: Juan Pablo <juan@cline.bot>
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2026-03-02 16:22:39 -08:00
CandiedUniverse fc3d986d05 Release: version bump and changelog updates (#9640)
* Update changelog for release

* Version bump the package*.json files for release
2026-03-02 15:53:06 -08:00
Saoud Rizwan 520ddb83bb fix(checkpoints): retry nested git restore and prevent silent .git_disabled leftovers (#9620)
* fix(checkpoints): harden nested git repo restore cleanup

* Fix checkpoint initialization to take less time

---------

Co-authored-by: cline-test <132302818+candieduniverse@users.noreply.github.com>
2026-03-02 12:22:01 -08:00
Ara d96c5d4b40 workflow: add default auto-tag flow for Publish Release (#9584)
* workflow: add auto-tag mode to publish release

* workflow: pin auto-tag release to tested commit sha

* workflow: clarify publish release input semantics

* workflow: constrain publish tag input to refs/tags
2026-03-02 11:38:48 -08:00
Br1an e6cbae0edc fix: prevent Chinese filename escaping in diff view (#9612)
* fix: prevent Chinese filename escaping in diff view

Use Uri.parse() instead of Uri.from() for the diff view URI to prevent
non-ASCII characters (e.g. Chinese) in filenames from being
percent-encoded. This is consistent with how other diff URIs are created
in openMultiFileDiff.ts and VscodeCommentReviewController.ts.

Uri.from() encodes the path component, turning Chinese characters into
percent-encoded sequences like %E7%A0%94..., which causes the diff view
to display escaped filenames and fail to open properly.

* fix: encode URI-reserved delimiters in filename before Uri.parse

Encode %, #, and ? in the filename before passing to Uri.parse() to
prevent them from being interpreted as URI delimiters. This handles
edge cases where filenames contain these characters (valid on macOS/Linux)
while preserving non-ASCII characters like Chinese.
2026-03-02 10:35:48 -08:00
Saoud Rizwan 76bd0926e6 fix: trigger auto-compaction on OpenRouter context overflow errors (#9633)
* fix(context): detect wrapped OpenRouter 400 context errors

* fix(openrouter): preserve status for context overflow detection

* docs(context): clarify OpenRouter error-shape handling

* Revert "docs(context): clarify OpenRouter error-shape handling"

This reverts commit 9458d4472b.

* Revert "fix(openrouter): preserve status for context overflow detection"

This reverts commit a2c76d1693.

* Revert "fix(context): detect wrapped OpenRouter 400 context errors"

This reverts commit 3e8fb10b9e.

* Reapply "fix(context): detect wrapped OpenRouter 400 context errors"

This reverts commit 6df27d6853.

* Reapply "docs(context): clarify OpenRouter error-shape handling"

This reverts commit beb52e1429.

* fix(context): narrow OpenRouter status parsing fallback

* fix(context): align OpenRouter status parsing with agreed shape
2026-03-02 10:34:27 -08:00
Renee Huang 819f9ce00d show sdk docs in cline page (#9597) 2026-03-02 10:14:41 -08:00
Max fd8cecddd5 update cline sdk docs (#9532) 2026-02-27 11:28:48 -08:00
CandiedUniverse a502bd8653 WIP: Make hooks work on Windows PowerShell (#9552)
* feat(hooks): add Windows hook execution via PowerShell

* chore(changeset): add release note for Windows hooks

* Get hooks working on Windows

Remove changeset file (we no longer use changeset files)

feat(hooks): support Windows PowerShell hook resolution and management

feat(hooks): complete windows powershell hook support and tests

Detect linux-style hooks only on macOS and linux and detect PowerShell-style hooks only on Windows

Fixes for failing unit tests on Windows in CI

Fix failing unit tests on Windows in CI

Fix unit tests for hooks on Windows

Be clear about .ps1 file extension for hooks in PowerShell vs. bash/binary for linux-style hooks

Remove separate test suite step

Reapply hooks-specific test suite

Fix failing hooks tests

* Harden Windows hook PowerShell runtime and test coverage

* test: centralize hook test env and platform overrides

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-02-27 10:51:46 -08:00
Robin Newhouse d48d5ee74d fix: restore gpt-oss native file editing on OpenAI-compatible models (#9434)
* fix(core): enable gpt-oss native file editing

* test(evals): add gpt-oss openai-compat smoke coverage
2026-02-27 10:18:25 -08:00
Tomás Barreiro cd320ea01f Add User-Agent to requests to the Cline back-end (#9583) 2026-02-26 18:52:31 -08:00
CandiedUniverse 60485277c4 Version bump and changelog for release (#9577) 2026-02-26 15:57:14 -08:00
ClineXDiego 0a8f1ef248 fix: clear all OCA secrets on auth refresh failure to prevent re-auth loop (#9569)
When OCA token refresh fails with 400 invalid_grant or 401, legacy secrets
ocaAccessToken and ocaTokenSet (from older Cline versions) were left in VS
Code's secret storage. clearAuth() only cleared ocaApiKey and ocaRefreshToken,
causing every subsequent re-auth attempt to fail in a loop requiring manual
SQLite deletion to recover.

Fix:
- Add ocaAccessToken and ocaTokenSet to SecretKeys in state-keys.ts
- Update OcaAuthProvider.clearAuth() to clear all 4 OCA secrets

Fixes #9567
2026-02-26 20:12:48 -03:00
ClineXDiego 4b2619daf7 fix: resolve "Could not find the file context" error in Explain Changes (#9449)
* fix: resolve 'Could not find the file context' error in Explain Changes

Both handleCommentReply() in explainChangesShared.ts and the onCommentStart
callback in explainChanges.ts were using a strict absolutePath-only match
when looking up files in changedFiles. If the VS Code comment controller
returns a path in a different format (relative vs absolute, different
separators on Windows), the lookup would silently fail and show
'Error: Could not find the file context'.

Add relativePath as a fallback in both lookup sites, making them
consistent with the already-correct logic in streamAIExplanationComments.

Fixes #9382

* Refactor to use parseInt instead of Number.parseInt
2026-02-26 20:12:37 -03:00
Ara 913cf4b74d feat: add dynamic Cline provider model fetching from Cline endpoint (#9102)
* Adding 1m

* fix: wire cline model proto fields for api config

* fix: wire cline picker to shared recommended model logic

* fix: address Cline model picker parity and startup model-info sync

* remove OpenRouter preset model ID support

* rename Cline endpoint feature flag

* Fixing stuff

* Fixing stuff

* Fixing stuff

* refactor: gate cline models endpoint behind feature flag

- Update refreshClineModels to use the EXTENSION_CLINE_MODELS_ENDPOINT feature flag instead of a hardcoded boolean, allowing controlled rollouts of the endpoint source.
- Remove recommended/free models fallback logic, featured model cards, and the initialTab property from OpenRouterModelPicker to simplify the UI component.
2026-02-26 14:58:45 -08:00
Robin Newhouse 8e5be3f648 fix: use JSON_SCHEMA for yaml.load to prevent unsafe deserialization (#9500)
* fix: use JSON_SCHEMA for yaml.load to prevent unsafe deserialization

Add { schema: yaml.JSON_SCHEMA } to both yaml.load() calls to reject
custom YAML tags (e.g. !!js/function) that could enable code execution
from untrusted .clinerules or skills files.

Add security tests verifying custom tags are rejected.

* add changeset
2026-02-26 14:48:58 -08:00
CandiedUniverse 6c519ff6e5 Increase timeout of flaky test; this is not the long term solution but it will be quick and easy today (#9568) 2026-02-26 12:45:18 -08:00
Robin Newhouse c61f9a9394 fix: fetch model info from API in CLI headless auth for Cline and Vercel providers (#9547)
The CLI's applyProviderConfig() was reading model info from a disk
cache (controller.readOpenRouterModels) instead of fetching from
the provider API. In headless/Docker environments (e.g., terminal-bench)
the cache doesn't exist, so model info was never set. Both handlers
then fell back to openRouterDefaultModelInfo with maxTokens: 8192,
causing write_to_file truncation on large outputs.

Changes:
- Replace controller.readOpenRouterModels() (disk cache) with
  refreshOpenRouterModels() (fetches from API, with cache fallback)
- Add vercel-ai-gateway to the model info fetch path using
  refreshVercelAiGatewayModels()

Relates to #7998

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-26 12:42:34 -08:00
Raushan Singh fa53f301a4 fix: generate commit message from staged changes only when staging exists (#9529)
The "Generate Commit Message" feature was using all changes instead of
only staged changes. Now prioritizes staged changes via getGitDiffStagedFirst(),
falling back to all changes only when nothing is staged.

Closes #5749

Co-authored-by: Raushan Singh <raushrak@Raushans-MacBook-Air.local>
2026-02-26 18:53:33 +01:00
Robin Newhouse c36e375af5 fix: update stale maxTokens values for Claude 3.7+ models across Anthropic, Bedrock, Vertex, and SAP AI Core (#9545)
* fix: update stale maxTokens values for Claude 3.7+ models

Every Claude model from 3.7 Sonnet onward had maxTokens set to 8192
in the static model definitions. These values were correct for Claude
3.5 and earlier, but Anthropic has significantly increased output
limits for newer models:

- Claude Opus 4.6: 128K (was 8192, 15.6x too low)
- Claude 3.7 Sonnet: 128K (was 8192, 15.6x too low)
- Claude Sonnet 4.6/4.5/4, Haiku 4.5, Opus 4.5: 64K (was 8192)
- Claude Opus 4, Opus 4.1: 32K (was 8192)

These static definitions are the source of truth for Anthropic direct,
Bedrock, Vertex, and SAP AI Core providers. With the old values, any
write_to_file call exceeding 8192 output tokens would be silently
truncated, producing a missing 'content' parameter error.

Values verified against Anthropic docs, AWS Bedrock docs, Google
Vertex AI docs, and the Vercel AI Gateway API.

Relates to #7998

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: update openRouterDefaultModelInfo.maxTokens to 64K

This fallback ModelInfo (representing claude-sonnet-4.5) is used
when dynamic model info isn't available — notably by the Cline and
Vercel providers in the CLI when the model cache is empty (e.g.,
fresh Docker containers in terminal-bench).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-26 09:44:25 -08:00
Robin Newhouse 94b02bf052 fix: use model.info.maxTokens for OpenRouter instead of hardcoded 8192 (#9544)
The OpenRouter stream transform had a 30-line switch statement that
hardcoded max_tokens=8192 for every Claude model. This was written when
8192 was the actual max output for Claude, but modern Claude models
support much higher limits (e.g. 128K for Sonnet 4.6, 64K for others).

OpenRouter's API already reports the correct max_completion_tokens per
model, and model.info.maxTokens reflects this (128000 for Sonnet 4.6).
The hardcoded switch was silently overriding the dynamic value.

This caused write_to_file failures on OpenRouter (and the Cline
provider, which shares this code path) whenever the tool call content
exceeded 8192 output tokens. The response was truncated
(finish_reason: "length"), producing incomplete JSON that lost the
content parameter.

Runtime evidence:
- Before: max_tokens=8192 sent, completion_tokens=8192 (ceiling),
  finish_reason="length", write_to_file content missing
- After: max_tokens=128000 sent, completion_tokens=9824 (needed more
  than 8192), finish_reason="tool_calls", write_to_file succeeded

Fixes #7998

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 21:57:30 -08:00
shey-cline f10b6f39be Add Additional Markdown Formatting in CLI (#9392) 2026-02-24 14:43:53 -08:00
shey-cline 42e6a24d0f Add Focus Indicator on Action Buttons in Extension (#9487) 2026-02-24 14:43:16 -08:00
CandiedUniverse 452733c3fd Release changeset PR (#9528)
* Update package.json and package-lock.json version numbers for patch release

* Patch fix changeset PR

* update cli package.json

* fixup! Patch fix changeset PR

---------

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-24 14:10:39 -08:00
Juan Pablo Flores 7fadcfaa3f feat: add thinking to MiniMax M2.5 and add the M2.5-highspeed model to MiniMax provider (#9394)
* feat: add MiniMax M2.5 model to MiniMax provider

- Add MiniMax-M2.5 to minimaxModels with 192K context, 128K max tokens,
  prompt caching, and reasoning/thinking support
- Update minimaxDefaultModelId to MiniMax-M2.5
- Add minimax/minimax-m2.5 to OpenRouter prompt caching switch

Closes #9391

* fix: add temperature: 1 to MiniMax M2.5 for reasoning support

* docs: update MiniMax provider docs with M2.5 model

* feat: wire up thinking/reasoning support for MiniMax M2.5

- Pass thinkingBudgetTokens from factory to MinimaxHandler
- Use thinking param in API call when reasoning is enabled
- Disable temperature and forced tool_choice when thinking is on
- Add ThinkingBudgetSlider to MiniMaxProvider UI for M2.5

* Add MiniMax-M2.5-highspeed

* Add thinking for highspeed

* Refactor thinking logic

---------

Co-authored-by: BarreiroT <tomasmbarreiroi@gmail.com>
Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-02-24 22:24:41 +01:00
Tomás Barreiro 9989225b69 Parse CLINE_OTEL_EXPORTER_OTLP_HEADERS headers and force the build constant ones (#9534) 2026-02-24 22:07:55 +01:00
Ara 8a73f63189 feat: update recommended model from GPT-5.2 Codex to GPT-5.3 Codex (#9533)
- Update model ID and name from gpt-5.2-codex to gpt-5.3-codex
- Change tag from "HOT" to "NEW" for the updated model
- Add What's New banner entry promoting Codex 5.3 availability
2026-02-24 12:49:20 -08:00
Ara 31e8c85f0a Remove voice mode UI and disable dictation (#9511)
* remove voice mode UI and disable dictation flags

* remove legacy dictation settings path and dead voice recorder

* remove dictation feature stack and state/proto hooks
2026-02-24 12:26:15 -08:00
Bee 5b9916866d fix: remove placeholder tools from final native tool list (#9499)
This commit ensures that internal placeholder tools, specifically `focus_chain`, are filtered out from the final list of native tools exposed to the LLM.

- Added a test case in `PromptRegistry.test.ts` to verify `focus_chain` is excluded from native tools output.
- Updated snapshot files for various models (OpenAI GPT-5, Vertex Gemini 3, etc.) to reflect the removal of the `focus_chain` tool definition.
2026-02-24 12:07:55 -08:00
Tomás Barreiro f001e735f8 Add isLocatedInPath tests (#9526)
* Add isLocatedInPath tests

* Add another test case
2026-02-24 19:22:55 +01:00
Tomás Barreiro 32893ee343 Fix OpenAI Codex by setting Store to false (#9523) 2026-02-24 18:28:32 +01:00
Raushan Singh 0d4e47e5c3 fix: use isLocatedInPath() instead of string.includes() for path containment check (#9519)
Fixes false positives in getReadablePath() when directories share a prefix
(e.g., /home/user/project matching /home/user/project-backup). The existing
isLocatedInPath() function correctly handles path boundaries using path.relative().

Closes #8761

Co-authored-by: Raushan Singh <raushrak@Raushans-MacBook-Air.local>
2026-02-24 18:23:29 +01:00
Max c1a43482e7 sdk lib (#9259)
* sdk lib

* improve cline sdk api surface

- better api design and messages

* fix some types, fix session id retrieval, improve wording

* hide controller from sdk surface completely

---------

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-23 22:30:54 -08:00
Bee ea65383e16 chore: replace baseUrl with explicit relative paths in tsconfig files (#9508)
* chore: replace baseUrl with explicit relative paths in tsconfig files

Remove `baseUrl: "."` from tsconfig configurations and update all path aliases to use explicit relative paths (e.g., `./src/*` instead of `src/*`). This makes path resolution more explicit and avoids potential ambiguity in module resolution across the main project and webview-ui configurations.

* update package-lock.json
2026-02-23 18:00:09 -08:00
Ara b97d1487a7 Release V3.67.0 (#9509)
* Release V3.67.0

Bump version from 3.66.0 to 3.67.0 in package.json and
package-lock.json. Add changelog entry for v3.67.0 covering new
features (subagent skills, AgentConfigLoader, Responses API, websocket
preconnect, CLI /q command), bug fixes (reasoning delta crash, OpenAI
tool ID, auth checks, Gemini 3.1 Pro), and other changes. Update
WhatsNewItems fallback banners to reflect current promotions.

* Fixing stuff
2026-02-23 17:25:30 -08:00
Robin Newhouse 091cf945e4 Move PR skill to .agents/skills (#9505)
* Move PR skill to .agents/skills and add changeset guidance

* Remove changeset guidance from PR skill
2026-02-23 16:31:32 -08:00
Bee df4f551ba7 feat: add support for skills and optional modelId in subagent config (ENG-1564) (#9502)
* refactor: consolidate subagent request usage tracking into state object

Replace scattered per-request token tracking variables with a structured
`SubagentUsageState` interface containing `currentRequest` and
`lastRequest` states. This improves code organization by grouping related
token metrics (input, output, cache write/read, total tokens, cost) into
a cohesive `SubagentRequestUsageState` object, reducing variable sprawl
and making the usage lifecycle (current → last) more explicit.

* feat(subagent): add support for skills and optional modelId in agent config

- Update `AgentBaseConfigSchema` and `AgentConfigFrontmatterSchema` to include an optional `skills` field and make `modelId` optional.
- Implement `parseSkills` and `normalizeSkillName` in `AgentConfigLoader` to handle skill parsing from YAML frontmatter.
- Update `SubagentBuilder` to provide access to configured skills.
- Modify `SubagentRunner` to filter available skills based on the agent's configuration, falling back to all available skills if none are specified.
- Update host retrieval to use `HostRegistryInfo` instead of `HostProvider`.

This allows subagents to be restricted to specific skills and provides more flexibility in model configuration.

* update unit test
2026-02-23 16:23:36 -08:00
Ara 88da4ddf89 feat: fetch featured models from backend with local fallback (#9495)
* feat(cli): fetch featured models from backend with local fallback

- Add async getFeaturedModelsForCline() to fetch models via controller
- Load featured models dynamically in AuthView with useEffect
- Update FeaturedModelPicker to accept featuredModels as optional prop
- Refactor helper functions to accept models parameter for flexibility
- Keep local hardcoded models as fallback when backend fetch fails

* Fixing stuff

* Fixing stuff

* Fixing stuff
2026-02-23 16:13:51 -08:00
CandiedUniverse 93eb607e6d Remove all traces of changeset-converter.yml GitHub Action and npm run changeset (#9506) 2026-02-23 15:53:56 -08:00
Tony Loehr 810b5b78f5 added mcp enterprise configuration details (#9501)
Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2026-02-23 15:51:05 -08:00
Tony Loehr 38ea422f6a Sso video (#9496)
* docs: add CVE scan sample to navigation, fix accordion labels, clarify --yolo flag

* added sso video

* Remove CVE scanner changes from SSO video PR
2026-02-23 15:29:48 -08:00
Robin Newhouse a7a35c0138 ci: add automatic retries for smoke test jobs (#9503) 2026-02-23 14:55:38 -08:00
Bee 01547ba1f4 feat: add AgentConfigLoader for file-based agent configs (ENG-1547) (#9245)
* refactor: centralize tool handler registration and filter by allowed tools

- Create centralized toolHandlersMap for all tool handler instantiation
- Add registerToolHandlers method to register only allowed tools from config
- Filter subagent tools to only include allowed tools from allowedTools config
- Remove scattered tool handler registration logic in favor of single source of truth
- Improve maintainability by consolidating tool handler creation in one place

This refactoring ensures subagents only have access to explicitly allowed tools
and makes the tool registration process more maintainable and consistent.

It also improves separation of concerns by having the coordinator manage all tool handler registration, while the executor focuses on orchestration. The allowedTools parameter enables runtime filtering of available tools for different contexts.

Also update PromptRegistry to load synchronous and simplify variant lookup

- Convert async load() to synchronous, called in constructor as both loadVariants and loadComponents are not async functions
- Remove health check logic and loaded state tracking
- Extract getVariant() method with proper generic fallback
- Add getComponents() accessor and simplify component loading
- Convert variant/component loaders from async to synchronous
- Remove unnecessary await calls throughout the codebase
- Add PromptRegistry tests for variant resolution and components

* fix test

* feat: add AgentConfigLoader for file-based agent configs

Add AgentConfigLoader singleton to manage agent configurations loaded from
YAML files in the agents directory. Supports hot-reloading via file watcher,
validates config schema with Zod, and integrates with extension lifecycle
(StateManager initialization and tearDown disposal).

* add tests

* add missing export

* update tests

* feat(tools): implement dynamic tool registration for subagents

Updates the tool system to support dynamically registered subagents as individual tools.

- Modifies `ClineToolSet` to generate specific tool definitions for configured subagents via `AgentConfigLoader`.
- Updates `parseAssistantMessageV2` to use `getToolUseNames()` instead of a static list, enabling the parser to recognize dynamic tool tags.
- Replaces the generic `USE_SUBAGENTS` tool with specific subagent instances when available in the system prompt context.

* update config path and refine tool descriptions

- Relocate the subagent configuration directory from `~/.cline/data/agents` to `~/Documents/Cline/Agents` to improve user accessibility.
- Update subagent tool descriptions and parameter instructions in the system prompt to be more descriptive and helpful for the model.

* revert unrelated changes

* revert unrelated changes

* update unit test

* fix: await AgentConfigLoader initialization before StateManager completes

Ensure agent configs are fully loaded during StateManager initialization
by awaiting the `ready()` promise. Previously, `AgentConfigLoader` was
instantiated without waiting for the initial load to complete, causing
potential race conditions where configs might not be available when
needed.

- Add `initialLoadPromise` field to track the async initial load
- Expose a `ready()` method to allow callers to await initialization
- Await `AgentConfigLoader.getInstance().ready()` in StateManager

* set previousRequestTotalTokens
2026-02-23 13:26:41 -08:00
Robin Newhouse 7f1632f09f fix: prevent reasoning delta crash on usage-only stream chunks (#9432)
* fix: guard missing delta in reasoning streams

* test: isolate litellm prompt cache call-count assertions
2026-02-23 12:29:34 -08:00
Han Wang 1b0ab3d01b sambanova provider: update models list (#9479)
* Add changeset

* Allow temperature config

* update issues summary

* Update SambaNova docs

* Update list of sambanova models

* Update minimax m2.5

* remove 2 models

* Remove residual
2026-02-23 11:27:36 -08:00
Chaitanya Eranki dce0902596 Oca Messages API implementation for new Claude Models (#9447)
* Made messages api changes

* Made changes

* Added changes

* Made maxTokens point to the right thing

* Removed deprecated max_tokens field

* Reverted the change

* Making an additional change to not cause any issues with chat completions

* reverting changes so we can make them in the backend

* Added changeset

* Fixed changes based on AI comments
2026-02-23 11:20:05 -08:00
Bee 9e7a30bd34 feat: preconnect websocket to reduce response latency (#9458)
Warm up the OpenAI WebSocket connection early in WebSocket mode to avoid handshake latency on the first response.create call. This introduces a responsesWsReadyPromise to track the connection state and prevent duplicate connection attempts while the initial connection is in flight.
2026-02-23 11:17:03 -08:00
Bee 2b1b1d1cf2 fix: restrict OpenAI tool ID transformation to native provider (#9459)
* fix: restrict OpenAI tool ID transformation to native provider

Update `convertToOpenAiMessages` and `transformToolCallId` to only apply tool ID transformations when the provider is explicitly set to `openai-native`. This prevents unintended ID modifications for other providers (like OpenRouter or local LLMs) that use the OpenAI format but may have different tool ID requirements or already provide compatible IDs.

* update tests

* transformToolCallIdForNativeApi
2026-02-23 11:16:55 -08:00
Max fcf3792f63 fix auth check for acp mode (#9491)
- acp code wasn't using the proper 'isAuthConfigured' method for
checking auth status

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-23 09:41:56 -08:00
shey-cline 0e833ade82 Add /q command to quit CLI (#9400)
* init

* changeset

* Apply suggestion from @greptile-apps[bot]

oops

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* add tests

* add /q info to help panel

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-23 07:37:34 -08:00
Ara 4455db5198 Pull Cline's recommended from internal endpoint (#9376)
* feat(cline): fetch recommended models from API endpoint

* Adding 1m

* Adding 1m

* Adding 1m

* fix: harden model tag label handling and tab init

* fix(models): add retry-safe fetch, id canonicalization, and shared filtering

* chore: trigger PR head refresh

* refactor(models): remove canonical alias map for OpenRouter IDs

* refactor(webview): remove redundant cline fetch on mount

* Adding 1m
2026-02-22 22:28:55 -08:00
Bee 03ab2968a6 feat: responses api for openai native provider (#9411)
* fix: openai native provider token usage mapping

- Add `store` parameter support to OpenAI native provider options to allow persisting completions.
- Fix incorrect mapping of `cached_tokens` and `reasoning_tokens` in usage statistics.
- Include `thoughtsTokenCount` in the final usage report to track reasoning model performance and costs.

* feat: add websocket support for OpenAI Responses API

This commit introduces WebSocket support for the OpenAI Native provider's Responses API, providing an alternative to the standard HTTP streaming.

- Implement `createResponseStreamWebsocket` in `OpenAiNativeHandler` with a fallback to HTTP on failure.
- Refactor `OpenAiNativeHandler` to modularize tool mapping and parameter construction for the Responses API.
- Update `OcaHandler` to explicitly disable `previousResponseId` when using the Responses API and add validation for model information.
- Integrate `undici` WebSocket for better compatibility in the extension environment.

* disablePreviousResponseId

* feat: add timestamp to conversation messages for response chaining

Add `ts` field to `ClineStorageMessage` to track when messages were
created. Use this timestamp to enforce a 23-hour validity window when
chaining OpenAI responses via `previousResponseId`, since the API only
retains responses for 24 hours. Also fix non-null assertion operators
in tests to use optional chaining for safer access.

* add OpenAI Responses Websocket Mode ApiFormat support

- Add `OPENAI_RESPONSES_WEBSOCKET_MODE` to the `ApiFormat` enum in proto definitions.
- Update `OpenAiNativeHandler` to use the new API format for determining when to use websocket mode, replacing previous environment-based logic.
- Refactor tool mapping for OpenAI Responses to support strict mode and correctly handle null parameters.
- Ensure the `store` option is disabled when `previous_response_id` is present in websocket mode.
- Bump version to 2.4.1 and update package dependencies.

* use abortController

* add support for websocket mode to openai-codex

* set behind feature flag
2026-02-20 17:17:54 -08:00
Max a0d52d4d59 cli yolo mode should not persist yolo setting to disk ever (#9370)
- added a method to StateManager, setSessionOverride, which overrides
state settings while the statemanager lives in memory

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-20 11:16:29 -08:00
Max 75fbeb4aad fix cline auth with acp flag (#9405)
- was missing a check for "cline:clineAccountId" in the isAuthed method
of acp agent

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-20 11:15:45 -08:00
Bee 70db6bde34 fix: inline focus-chain slider within its feature row (#9444)
* fix: inline focus-chain slider within its feature row

Moves the focus-chain reminder interval `SettingsSlider` from a
standalone element rendered after all experimental feature rows to
being rendered directly beneath the focus-chain `FeatureRow`. The
slider now renders conditionally when `feature.id === "focus-chain"`
and the feature is enabled, improving UI cohesion and making the
relationship between the toggle and its configuration more explicit.

Additionally:
- Relocates focus-chain from `experimentalFeatures` to `agentFeatures`
- Removes the `isExperimental` prop and "Experimental:" label badge
  from `FeatureRow` and related feature toggle definitions
- Simplifies `SettingsSlider` markup by removing the wrapper card
  styling, making it suitable for inline embedding
  - Removes unused line from common.ts

* nestedKey
2026-02-20 10:58:46 -08:00
Saoud Rizwan 02c2601e0e fix(gemini): add 3.1 pro while keeping 3.0 compatibility (#9438) 2026-02-20 09:18:40 -08:00
Juan Pablo Flores 94692b5091 docs: add MCP support documentation for Cline CLI (#9390) 2026-02-20 09:39:02 -06:00
Robin Newhouse a2794c680f fix(evals): restore missing smoke eval npm scripts (#9429) 2026-02-19 14:49:27 -08:00
CandiedUniverse 6d3f8e1d5d fix(release-eng): Pin VSCode nightly build to node version 22 (#9423)
* fix(release-eng): Pin VSCode nightlybuild to node version 22

* fix(release-eng): Pin publish.yml GitHub workflow to node version 22
2026-02-19 12:04:14 -08:00
cryptoque 3e5847890b feat: add dynamic flag to adjust banner cache duration (#9421) 2026-02-19 11:03:50 -08:00
CandiedUniverse 0eab54ab12 fix(release-eng): Fix nightly extension publish failure caused by workspace self-link mismatch (#9420) 2026-02-19 10:40:45 -08:00
github-actions[bot] 7fa0a4924b Changeset version bump (#9413)
* changeset version bump

* Updating CHANGELOG.md format

* Adding 1m

* Adding 1m

* Adding 1m

* Adding 1m

---------

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: Arafatkatze <arafat.da.khan@gmail.com>
2026-02-19 10:36:21 -08:00
Junjie Tang 8680218e0e Update sap-ai-sdk version (#9417) 2026-02-19 06:46:09 -08:00
Dominic Cooney 8787ab35b9 Update package-lock.json. (#9414) 2026-02-18 22:56:49 -08:00
Dominic Cooney 6ed3944f04 Export global, workspace and secrets from VSCode to share with CLI (#9227)
Caveat: Task history, tasks, etc. are not written to the same place by all clients yet. This is just about globalState, workspaceState and secrets.
2026-02-19 15:46:23 +09:00
Bee 1dd8e763d1 fix(chat): make Cmd/Ctrl+A select-all deterministic (#9408)
Handle plain Cmd/Ctrl+A directly in `ChatTextArea` keydown to force
textarea-wide selection via `setSelectionRange`, while preventing default
and propagation. This avoids intermittent failures caused by global shortcut
listener races, and keeps Cmd/Ctrl+Shift+A behavior unchanged.fix(chat): make Cmd/Ctrl+A select-all deterministic

Handle plain Cmd/Ctrl+A directly in `ChatTextArea` keydown to force
textarea-wide selection via `setSelectionRange`, while preventing default
and propagation. This avoids intermittent failures caused by global shortcut
listener races, and keeps Cmd/Ctrl+Shift+A behavior unchanged.
2026-02-18 20:55:57 -08:00
Bee 28e6297769 fix: flaky Cancel behavior by preventing duplicate cancel actions (CLINE-1380) (#9409)
* fix: flaky Cancel behavior by preventing duplicate cancel actions

This PR fixes chat cancel behavior where users sometimes had to click Cancel multiple times, and repeated clicks could accidentally transition into Resume/restart behavior.

* move to finally
2026-02-18 20:55:41 -08:00
Bee 5a2a5d1c0a refactor: replace non-null assertions with checks in PatchParser (#9402)
* refactor: replace non-null assertions with safe null checks in PatchParser

Replace all forbidden non-null assertions (`!`) in PatchParser.ts with
safe alternatives using optional chaining (`?.`) and nullish coalescing
(`?? ""`/`?? 0`). Also refactor the Levenshtein distance matrix from a
2D array to a flat array to eliminate index-based non-null assertions,
improving type safety and code robustness.

No feature behavior changes.

* simplify Levenshtein matrix indexing

Initialize the distance matrix with zeroes and add `at`/`set` helpers for flat-array access in `levenshteinDistance`.

This removes repeated index math and nullish fallbacks, making the algorithm easier to read while keeping bounds-safe access and identical behavior.refactor(patch-parser): simplify Levenshtein matrix indexing

Initialize the distance matrix with zeroes and add `at`/`set` helpers for flat-array access in `levenshteinDistance`.

This removes repeated index math and nullish fallbacks, making the algorithm easier to read while keeping bounds-safe access and identical behavior.
2026-02-18 19:35:48 -08:00
Max 113039a259 CLI 2.0: allow custom inference profile arn for bedrock provider (#9271) 2026-02-18 19:16:32 -08:00
Max 4023c18257 remove default timeout (#9401) 2026-02-18 17:28:50 -08:00
cryptoque 7c95b53892 Add support for DB backed Welcome Banner (#9315)
* feat: add welcome banner support from backend

* make DB banner format conform with existing banners

* add support for welcome banner actions

* remove debugging helper that bypass dismissal, dismissal should work again

* undo changes to make welcome banner always appear during debugging

* remove console logs for debugging

* clean up bannerservice

* clean up welcomesection.tsx

* add new tests for ide type filtering

* add welcome banner own feature flag and conditionally display between hard coded welcome banner and DB backed ones

* turn on welcome banner flag locally by default

* close welcome banners when clicking on actions

* apply bot review suggestion, fix memory leak

* address feedback: use p without span

* split welcome banners into a seperate component to keep whatsnewmodal clean

* get action through api schema instead of extractin it from rules_json

* use only bannerWaitTimeoutRef, remove waitingForBannersRef

* resolve new merge conflict

* linter

* cerebra
2026-02-18 14:52:02 -08:00
Bee 9fd2b99be4 chore: remove autoCondenseThreshold setting and related code (#9396)
- Remove `auto_condense_threshold` from `Settings` and `UpdateSettingsRequest` in `state.proto`.
- Remove `autoCondenseThreshold` from `ApiProviderInfo` interface.
- Update `generate-state-proto.mjs` to remove double field handling and improve integer parsing.
- Add error handling to `ContextManager` when parsing previous request JSON to prevent crashes on malformed data.
2026-02-18 12:43:30 -08:00
github-actions[bot] 7c782abaf4 Changeset version bump (#9364)
* changeset version bump

* Updating CHANGELOG.md format

* update package versions

---------

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: Max Paulus 🥪 <max@cline.bot>
2026-02-18 12:22:53 -08:00
Ara 3a14a88f4f fix: include root workspace for changesets release (#9393) 2026-02-18 11:40:02 -08:00
Saoud Rizwan 28d60a83a4 fix(models): keep Sonnet 4.5 as default for now (#9389)
* fix(models): keep Sonnet 4.5 as default

* chore(changeset): add release note for Sonnet 4.5 default

* fix(models): remove Sonnet 4.6 from curated model lists

* fix(models): restore Sonnet 4.6 in web recommended list
2026-02-18 10:53:07 -08:00
Saoud Rizwan ae6468b161 fix(models): reinstate minimax m2.5 free promo surfaces (#9387) 2026-02-18 10:28:54 -08:00
Saoud Rizwan af93e31862 feat(models): make sonnet 4.6 default and remove free promo positioning (#9377) 2026-02-18 10:07:20 -08:00
Tomás Barreiro ca154eb8f5 Add MiniMax M2.5 to the MiniMax provider (#9381)
* Add MiniMax M2.5 to the MiniMax provider

* Add changeset

* Update default model
2026-02-18 09:16:23 -08:00
Tomás Barreiro 1d8497c6bf Prevent error messages when displaying featured models in the CLI (#9379)
* Fix the featured models key

* Add changeset
2026-02-18 16:51:29 +01:00
Seb Duerr 5871fd02b1 feat(cerebras): remove deprecated llama-3.3-70b and qwen-3-32b models (#9345)
* feat(cerebras): remove deprecated llama-3.3-70b and qwen-3-32b models

These models have been deprecated from the Cerebras inference platform.

- Remove llama-3.3-70b and qwen-3-32b from cerebrasModels in api.ts
- Update supported models documentation in cerebras.mdx
- Add changeset for the deprecation

* fix: remove stale llama-3.3-70b and qwen-3-32b references from rate limits

Remove dead switch cases in getRateLimits() that referenced deprecated models
no longer present in cerebrasModels.
2026-02-17 23:39:38 -08:00
alex-lum 2d81c310d2 Alex/inf 413 bug no telemetry for versions greater than 20 (#9372) 2026-02-17 18:55:07 -08:00
Robin Newhouse 0c691f72d2 feat(cli): add /skills slash command (#9089)
* feat(cli): add /skills slash command for managing skills

- Add /skills to CLI_ONLY_COMMANDS in slashCommands.ts
- Create SkillsPanelContent component with:
  - Display global and workspace skills with toggle indicators
  - Enter to use skill (inserts @path into input)
  - Space to toggle skill enabled/disabled
  - Selectable marketplace link to skills.sh
  - Keyboard navigation with arrow keys and vim keys
- Wire up panel in ChatView.tsx
- Add comprehensive tests for keyboard interactions

* refactor(cli): use static skill controller imports

* fix(cli): add React import to skills panel test

* fix(cli): suppress required React import lint in skills test

* fix(cli): harden /skills panel interactions

Revert optimistic skill toggle state when persistence fails, and surface a fallback URL when opening the marketplace fails. Also tighten and extend tests to verify exact marketplace URL handling and rollback behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 17:13:51 -08:00
Robin Newhouse a8409137b3 fix: disable click-to-set auto-condense threshold and hardcode default (#9348)
* fix: disable click-to-set auto-condense threshold and hardcode default

Clicking anywhere on the context window progress bar silently set
autoCondenseThreshold to a value based on click position (e.g. 0.05),
persisting in globalState. This caused compaction to fire at ~10K tokens
instead of the intended ~150K, resulting in ~20 context resets per task.

- Comment out click and keyboard handlers on progress bar (keep components
  for future release with proper UX)
- Hardcode threshold to 0.75 default, ignoring corrupted stored values

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: add shouldCompactContextWindow unit tests

Cover threshold math including the accidental low-threshold bug case,
undefined/zero fallbacks, cache token inclusion, and maxAllowedSize cap.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: hardcode autoCondenseThreshold in all remaining callsites

Address Greptile review: SubagentRunner.ts, task/index.ts display
logic, and controller/index.ts webview state all still read the
corrupted value from globalState. Hardcode 0.75 everywhere.

Co-authored-by: Cursor <cursoragent@cursor.com>

* style: remove unnecessary union type on hardcoded threshold

Drop `number | undefined` annotation from the hardcoded 0.75 literal
in SubagentRunner.ts per Greptile review feedback.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: use SETTINGS_DEFAULTS constant, remove commented-out code, clarify test

- Replace hardcoded 0.75 with SETTINGS_DEFAULTS.autoCondenseThreshold
  across all 4 callsites for a single source of truth
- Delete commented-out click/keyboard handlers in ContextWindow.tsx,
  replace with TODO referencing PR #9348
- Make bug-case test self-documenting by deriving token values from
  the threshold calculation

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 16:32:13 -08:00
Saoud Rizwan 34a21b8e26 docs: add security policy (#9365) 2026-02-17 16:00:01 -08:00
ClineXDiego eb9f53edf4 fix: smarter retry for write_to_file missing content parameter (#9276)
* fix: smarter retry for write_to_file missing content parameter (#7998)

Replace generic 'missing parameter' error with progressive guidance when
write_to_file fails due to empty content parameter. This breaks the
infinite retry loop where the model repeatedly attempts the same
write_to_file call that exceeds output token limits.

Changes:
- Add writeToFileMissingContentError() to formatResponse with 3 tiers:
  1st failure: suggestions (use skeleton + replace_in_file)
  2nd failure: strong directive (stop retrying write_to_file)
  3rd+ failure: CRITICAL stop, forces alternative strategies
- Add context window awareness: warns model when >50% context used
- Add getContextUsagePercent() helper to WriteToFileToolHandler
- Add 22 unit tests covering progressive escalation and context awareness

Fixes #7998

* add changeset for write_to_file retry fix

* refactor: simplify write_to_file error handling per review

- Simplify writeToFileMissingContentError to single-tier error following
  existing diffError pattern (no progressive escalation)
- Use shared getLastApiReqTotalTokens() for context window awareness
- Remove private getContextUsagePercent() method from handler
- Add proactive skeleton + replace_in_file guidance to write_to_file
  tool description for all variants
- Simplify tests to match new API (11 tests)

* test: update system prompt snapshots

* chore: revert write_to_file prompt guidance

* feat: restore progressive 3-tier guidance for write_to_file missing content

Restore the progressive escalation that was removed in dd3c12d4e:
- Tier 1 (1st failure): Gentle suggestions (skeleton + replace_in_file)
- Tier 2 (2nd failure): Strong directive, 'Do NOT attempt full write again'
- Tier 3 (3rd+ failure): CRITICAL stop, forces alternative strategies
- Context window warning when >50% full
- Dynamic UI message: 'Retrying...' vs 'multiple times — different approach'
- 21 tests covering all tiers and context awareness

* nit: extract context window warning threshold to named constant

Also replace emoji with plain text in warning message for consistency.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 19:08:42 -03:00
github-actions[bot] c60f18d907 Adding 1m (#9346)
Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-02-17 11:11:54 -08:00
Saoud Rizwan 36c68a6ab9 fix: remove expired MiniMax free promo surfaces (#9361)
* fix: remove expired MiniMax free promo surfaces

* fix: remove MiniMax M2.5 from recommended models

* chore: update GLM 5 whats-new promo wording
2026-02-17 10:57:19 -08:00
Saoud Rizwan 80dfce0f60 docs: remove stale Claude 5 mention from Auto Compact docs (#9360)
* docs: remove stale Claude 5 wording from auto compact docs

* Remove stale Claude 5 mention from docs
2026-02-17 10:48:23 -08:00
Saoud Rizwan 955ae2f62f feat: add Claude Sonnet 4.6 support and surface it as free (#9356)
* feat: add Sonnet 5 support and make it default across surfaces

* feat: surface Sonnet 5 as free while keeping Sonnet 4.5 defaults

* fix: rename Sonnet 5 support to Sonnet 4.6 across providers and UI

* fix: allow duplicate onboarding model ids across free and frontier

* chore: update Sonnet 4.6 banner to limited-time free messaging

* fix: align Bedrock Sonnet 4.6 model ids with AWS format

* feat: update whats new promo to Sonnet 4.6 free offer

* chore: update Sonnet 4.6 promo copy and timing
2026-02-17 10:43:24 -08:00
Dominic Cooney 8cb0c6d236 Fix e2e tests. (#9350) 2026-02-17 15:06:40 +09:00
github-actions[bot] bb05b2f7b0 changeset version bump (#9316)
Updating CHANGELOG.md format

update changelog

update banner and bump version

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-16 12:46:01 -08:00
alex-lum 1a911f4232 fix(telemetry): refresh OTEL org attributes on identify (#9318)
* fix(telemetry): refresh OTEL user/org attributes on every identify

* fix(telemetry): refresh OTEL user/org attributes on every identify

* test(telemetry): cover OTEL identifyUser org refresh scenarios

* refactor(telemetry): rename member_roles to member_role (singular)

* Apply suggestion from @BarreiroT

simpler commenting

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

* removing verbose comments

/**
 * Helper to build a ClineAccountUserInfo with an active organization.
 */

* removing verbose comments

* removing unnecessary logger

* assert -> chai expect

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-02-16 12:45:31 -08:00
Ara 1cfd560921 feat(cline): add z-ai/glm-5 to free model recommendations (#9341)
* feat: add z-ai/glm-5 to free models list

Include Z.AI's GLM 5 in the free model whitelist for zero-cost usage
and update the model picker UI to display the free label.

* Adding thinking

* Adding thinking

* Adding thinking
2026-02-16 11:59:09 -08:00
Juan Pablo Flores 203ff8f549 docs: enrich Quick Start guide with more context for new users (#9338)
* docs: enrich Quick Start guide with more context for new users

* docs: add Antigravity to full installation guide
2026-02-16 09:00:50 -08:00
Saoud Rizwan e920f1de02 fix(chat): keep reasoning visible before low-stakes tool groups (#9335)
* fix(chat): keep reasoning visible before low-stakes tool groups

* chore(changeset): add patch note for tool-group reasoning visibility

* fix(chat): keep thinking loader visibility aligned with waiting states

* fix(chat): avoid clipping descenders in thinking label
2026-02-15 17:14:41 -08:00
Saoud Rizwan b266475d0a fix(chat): prevent partial row churn during native tool arg streaming (#9334)
* fix(chat): prevent partial text flicker during native tool streaming

* fix(chat): revert act mode partial dedupe change
2026-02-15 15:40:54 -08:00
Saoud Rizwan 402361c482 fix(chat): restore reasoning traces and polish thinking UX (#9330)
* fix(chat): restore reasoning traces and polish thinking UX

* chore(changeset): add patch note for reasoning trace UX fixes
2026-02-15 01:19:59 -08:00
Renee Huang e884699d24 New Cline Docs (#9280)
* only doc changes

* merge

* fix installtion page redirects

* fix redirect, remove unused parts

* rm irrelevant info

* clean up terminal guides

* docs: add home page and reorganize navigation

* chore: remove 71 unused docs files not referenced in navigation

Remove .mdx files that are no longer referenced in docs.json navigation
and only existed as stale content from previous documentation restructuring.
These files were either completely orphaned or only served as redirect
source pages (Mintlify handles redirects at the routing level without
needing the source file to exist).

Updated docs.json redirects that previously pointed to archive/ pages
to point to current equivalents instead:
  - /archive/understanding-context-management → /model-config/context-windows
  - /archive/prompt-engineering-guide → /customization/cline-rules
  - /archive/telemetry → /enterprise-solutions/monitoring/telemetry

Deleted files by category:

Archive (entire directory removed):
  - archive/prompt-engineering-guide.mdx
  - archive/telemetry.mdx
  - archive/understanding-context-management.mdx

Cline CLI:
  - cline-cli/cli-reference-deprecated.mdx

Enterprise Solutions (16 files):
  - enterprise-solutions/bundled-endpoints.mdx
  - enterprise-solutions/configuration/overview.mdx
  - enterprise-solutions/configuration/choosing-your-deployment.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/rules.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/workflows.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/control-other-cline-features/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/mcp/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/mcp/mcp-marketplace.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/mcp/remote-mcp-servers.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/providers/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/providers/custom.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/providers/aws-bedrock/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/providers/google-vertex/overview.mdx
  - enterprise-solutions/configuration/infrastructure-configuration/providers/litellm/overview.mdx
  - enterprise-solutions/monitoring/opentelemetry_override.mdx

Exploring Cline's Tools (entire directory removed):
  - exploring-clines-tools/cline-tools-guide.mdx
  - exploring-clines-tools/new-task-tool.mdx
  - exploring-clines-tools/remote-browser-support.mdx

Features — old pages consolidated into core-workflows/ and customization/ (37 files):
  - features/checkpoints.mdx
  - features/drag-and-drop.mdx
  - features/editing-messages.mdx
  - features/explain-changes.mdx
  - features/skills.mdx
  - features/yolo-mode.mdx
  - features/at-mentions/ (7 files — all consolidated into core-workflows/working-with-files)
  - features/cline-rules/ (2 files — consolidated into customization/cline-rules)
  - features/commands-and-shortcuts/ (5 files — consolidated into core-workflows/using-commands)
  - features/customization/ (2 files)
  - features/hooks/ (3 files — consolidated into customization/hooks)
  - features/slash-commands/ (7 files)
  - features/slash-commands/workflows/ (3 files — consolidated into customization/workflows)
  - features/tasks/ (2 files — consolidated into core-workflows/task-management)

Introduction (entire directory removed):
  - introduction/overview.mdx
  - introduction/welcome.mdx

MCP:
  - mcp/adding-mcp-servers-from-github.mdx
  - mcp/configuring-mcp-servers.mdx

More Info (entire directory removed):
  - more-info/telemetry.mdx

Prompting (entire directory removed):
  - prompting/cline-memory-bank.mdx
  - prompting/prompt-engineering-guide.mdx
  - prompting/understanding-context-management.mdx

Provider Config:
  - provider-config/fireworks-ai.mdx
  - provider-config/ollama.mdx

Getting Started:
  - getting-started/selecting-your-model.mdx

Total: 71 files deleted, 12,344 lines removed.

* docs: update and add documentation pages

* revert unintended formatting changes to src files

* new first project docs

---------

Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2026-02-14 22:02:22 -08:00
Saoud Rizwan f59d950ac6 fix: open Cline sidebar for task deeplinks (#9320)
* fix: open Cline sidebar for task deeplinks

* refactor: share task URI path constant
2026-02-14 01:15:13 -08:00
Ara d2e4f1c7b9 feat(zai): add glm-5 pricing and make it default (#9253) 2026-02-13 20:42:49 -08:00
Ara 49975fd0a3 feat(cli): support Moonshot provider across CLI flows (#9314)
* feat(cli): add moonshot provider support across CLI flows

* Update cli/man/cline.1

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

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-13 16:10:10 -08:00
shey-cline c0020e10b1 Allow Custom AWS Regions in Bedrock (CLI) (#9103)
* init

* changeset

* prevent regoinIndex = -1 when navigating with arrow keys while filteredRegions.length = 0

* refactor

* content fix
2026-02-13 15:46:36 -08:00
Ara 8dc5e15ee0 chore: bump version to 3.62.0 (#9313) 2026-02-13 15:13:36 -08:00
github-actions[bot] 276cb4c3a4 Changeset version bump (#9312)
* changeset version bump

* v3.62.0 Release Notes

- Banners now display immediately when opening the extension instead of requiring user interaction first
- Resolved 17 security vulnerabilities including high-severity DoS issues in dependencies (body-parser, axios, qs, tar, and others)

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
2026-02-13 14:24:54 -08:00
Saoud Rizwan 8169abbc74 fix(e2e): stabilize banner and code action assertions (#9311) 2026-02-13 14:11:55 -08:00
Ara a47ad46824 fix: rename package from "claude-dev" to "cline" in changesets (#9309)
Update changeset metadata files to use the correct package name
"cline" instead of the legacy "claude-dev" identifier.
2026-02-13 14:08:57 -08:00
Saoud Rizwan 7896e6d896 feat: promote MiniMax M2.5 in top banner and route CTA to free tab (#9307)
* feat: add minimax promo banner and free-tab model routing

* Add changeset for promoting MiniMax M2.5
2026-02-13 13:20:22 -08:00
aikido-autofix[bot] 166ec38d26 fix(security): update dependencies (#9234)
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
2026-02-13 12:42:06 -08:00
Tomás Barreiro e44ea9d772 Post state to webview after fetching the banners (#9306)
* Post state to webview after fetching

* Test post state to webview is called

* refactors
2026-02-13 21:18:32 +01:00
Ara fcca1d4fe3 v3.61.0 Release Notes (#9305) 2026-02-13 10:35:16 -08:00
github-actions[bot] 34f0795217 v3.60.0 Release Notes (#9274)
- Fixes for Minimax model family
- Fixes for Response chaining for OpenAI's Responses API

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-13 09:02:46 -08:00
Bee 0648ed42b2 feat: make response ID chaining configurable (#9285)
Add an optional `usePreviousResponseId` flag to
`convertToOpenAIResponsesInput` and gate previous assistant-response
lookup behind it.

This makes response chaining opt-in instead of always-on, so providers
can control whether to continue from the latest stored OpenAI response
ID.feat(openai): make response ID chaining configurable

Add an optional `usePreviousResponseId` flag to
`convertToOpenAIResponsesInput` and gate previous assistant-response
lookup behind it.

This makes response chaining opt-in instead of always-on, so providers
can control whether to continue from the latest stored OpenAI response
ID.
2026-02-13 08:40:02 -08:00
Saoud Rizwan f32dde2c16 chore: update codex environment config 2026-02-13 04:17:07 -08:00
Saoud Rizwan 605c497eaf chore: update codex environment config 2026-02-13 04:14:22 -08:00
Saoud Rizwan a8322eec44 fix(task): avoid duplicate partial text from reentrant presentation (#9302) 2026-02-13 03:47:56 -08:00
Saoud Rizwan 974a7a748a fix(webview): add spacing before ask followup options 2026-02-13 02:31:14 -08:00
Saoud Rizwan fb2d092301 fix(hooks): preserve streaming tool rows in combineHookSequences (#9301) 2026-02-13 02:10:27 -08:00
Saoud Rizwan 45b3eb4833 fix(chat): stabilize tool-group text and thinking footer behavior (#9300)
* fix(chat): ignore streamed text after tool group starts

* fix(chat): suppress thinking during ask and completion handoff

* fix(chat): prevent thinking footer shimmer remount flicker
2026-02-13 02:03:32 -08:00
Bee a5048189e5 fix: remove focused BannerService test to run full suite (#9299)
The unit test suite currenlt is running the BannerService tests only when it should run the full suite.
Also update package-lock.json that wentout of sync.
2026-02-13 01:08:30 -08:00
Saoud Rizwan 897e842eb4 fix(task): ignore interleaved reasoning UI after text starts (#9298) 2026-02-13 00:25:08 -08:00
Saoud Rizwan 0389d4de07 Revert "fix(task): prevent duplicate streamed text rows after completion (#9235)" (#9297)
This reverts commit b514f18e4f.
2026-02-13 00:20:33 -08:00
Saoud Rizwan d99eec15d8 fix(minimax): emit single reasoning chunk on thinking start (#9290) 2026-02-12 23:46:53 -08:00
Ara 98ed009e69 fix: add missing name fields to free featured models and improve type safety (#9291)
- Add `name` property to minimax, kat-coder-pro, and trinity-large-preview
  models that were previously missing it
- Move type annotation from `as FeaturedModel[]` casts to the variable
  declaration for proper type checking at assignment time
- Add test to verify all featured models include a display name
2026-02-12 23:18:51 -08:00
Saoud Rizwan 8fb7b94297 Revert "Jose/thinking and flicker fix (#9148)" (#9292)
This reverts commit d8397c71b2.
2026-02-12 22:54:07 -08:00
Jose R. Perez d8397c71b2 Jose/thinking and flicker fix (#9148)
* feat: persistant thinking loader at bottom of stream during any cline activity with no visual feedback

* feat: thinking and flicker fix

* refactor: remove multi-layer throttling, use single canonical throttle point

Collapse 4 independent throttle layers (up to ~500ms added latency) into
a single 50ms debounce in subscribeToPartialMessage. Replace index-based
partial message tracking with stable ts-based tracking. Remove webview
queue/timer/flush system in favor of cheap equality dedup.

* fix: Add production-grade improvements to flicker fix

- Fix global mutable state bug in subscribeToPartialMessage.ts
- Add comprehensive test coverage (51 tests passing)
- Rename ThrottledApiHandler → SanitizedApiHandler
- Remove incomplete OpenAI reasoning effort code

* Fix test failures

* PR changes as per Greptile feedback

* Fixes as per feedback during PR review

---------

Co-authored-by: cline-test <132302818+candieduniverse@users.noreply.github.com>
2026-02-12 22:28:46 -08:00
Robin Newhouse 3899469d76 feat(evals): comprehensive LLM evaluation framework with CI (#8909)
* chore(evals): reorganize eval structure with purpose-based naming

- Move evals/diff-edits/ → evals/benchmarks/tool-precision/replace-in-file/
- Move evals/cli/ → evals/legacy/cli/ (preserve for reference)
- Create evals/benchmarks/real-world/ directory
- Create evals/benchmarks/coding-exercises/cases/ directory
- Create evals/analysis/ directory structure

Note: No repositories/exercism/ directory found to move.
Skipping pre-commit hook as this is a reorganization of legacy code.

* chore(evals): remove legacy evaluation code

Remove abandoned evaluation infrastructure:
- evals/benchmarks/tool-precision/ - Dashboard, database, diff implementations
- evals/legacy/cli/ - Old HTTP-based eval harness

This functionality is superseded by the new testing pyramid:
- Tool precision is now covered by contract tests in src/core/
- E2E testing uses the cline-bench framework

* feat(evals): add analysis framework for benchmark results

Add shared infrastructure for analyzing evaluation results:
- TypeScript schemas for Harbor and analysis output formats
- Parsers for Harbor, tool-precision, and exercise results
- Failure classifier with pattern matching (cline-failures.yaml)
- Metrics calculator (pass@k, consistency, latency)
- JSON and Markdown reporters
- CLI with analyze and compare commands
- Unit tests for classifier and metrics

This framework is used by both smoke tests and E2E evaluations
to provide consistent metrics and failure categorization.

* feat(evals): add contract tests for API transforms

Add tests to verify API response transformations preserve data correctly:
- thinking-traces.test.ts: Tests thinking block extraction and formatting
- tool-parsing.test.ts: Tests tool call parsing across providers

These contract tests catch regressions when modifying transform logic,
ensuring API responses are correctly processed regardless of provider.
Run with: npm run test:unit

* feat(evals): add provider smoke tests with pass@k metrics

Add lightweight smoke tests that validate provider integrations work
correctly with real LLM calls:

Scenarios (5 curated tests):
- 01-create-file: Tests write_to_file tool
- 02-edit-file: Tests replace_in_file tool
- 03-read-summarize: Tests read_file tool
- 04-multi-file: Tests multi-file edits
- 05-typescript-function: Tests code generation

Features:
- CLI-based runner using the cline CLI
- Multiple trials per scenario for reliability testing
- pass@k metrics (solution finding) and pass^k (consistency)
- Results storage with logs and latest symlink
- Adaptive metric display based on trial count

Run locally: npm run eval:smoke

* feat(evals): add E2E runner with cline-bench

Add end-to-end testing infrastructure using real-world production bugs:

- cline-bench submodule: 12 curated tasks from actual Cline sessions
  - Complex multi-file refactors
  - Bug fixes requiring deep context understanding
  - Cross-language/framework tasks

- E2E runner (evals/e2e/run-cline-bench.ts):
  - Integrates with Harbor for containerized execution
  - Supports single task or full suite runs
  - Pass/fail metrics with detailed logging

Run: npm run eval:e2e -- --task discord-trivia

Note: E2E tests require Docker and are intended for weekly/release
testing, not per-commit CI (each task takes 20-30 minutes).

* feat(evals): add CI workflow and documentation

CI Workflow (.github/workflows/cline-evals-regression.yml):
- Triggers on push/PR to main (src/core, src/shared, proto, evals paths)
- Builds CLI from source with Go 1.24
- Runs 5 smoke test scenarios in parallel
- Uses Anthropic API with claude-sonnet-4
- Uploads results as artifacts with summary

npm scripts:
- eval:smoke - Run smoke tests locally (builds CLI first)
- eval:smoke:run - Run smoke tests (assumes CLI is built)
- eval:e2e - Run cline-bench E2E tests

Documentation:
- ARCHITECTURE.md: Testing pyramid overview with ASCII diagrams
- EVALS_OVERVIEW.md: High-level introduction for mixed audience
- Updated README.md with current structure and usage

* chore(evals): restore tool-precision as deprecated legacy

Restore the diff edit evaluation framework for @ara's use case.
Marked as DEPRECATED - target removal Q2 2026 when cline-bench
is fully operational for model comparison.

Note: Skipping linter as this is legacy code being preserved as-is.

* feat(evals): add per-scenario model support and apply_patch test

Also honor --model overrides and prune stubs.

* chore(evals): update smoke tests for CLI 2.0

- Remove Go setup from workflow (CLI 2.0 is TypeScript)
- Build CLI via `npm run build` in cli/ directory
- Install CLI via `npm link` to test built code from PR
- Update CLI flags: -y -m model --json (remove -o and -s)
- Provider configured via `cline auth` before tests run

* chore(evals): add auth check and CLI 2.0 flags

- Add configureAuth() that runs cline auth non-interactively
- Require CLINE_API_KEY env var or use existing ~/.cline auth
- Add --config flag to use shared config directory
- Add -t timeout flag to CLI args
- Reduce scenario timeout to 30s for faster iteration
- Remove --json flag (CLI doesn't output errors in json mode)

* feat(evals): add parallel execution and move workspaces to results

- Add --parallel flag to run scenarios concurrently (default limit: 4)
- Move trial workspaces from scenarios/ to results/ directory
- Workspaces now cleaned up with `npm run eval:smoke:clean`
- Keeps scenarios/ clean and version-controllable

* ci: add smoke tests workflow with parallel execution

- Single job runs all 7 scenarios in parallel using test runner's --parallel flag
- Builds CLI in-job (no artifact passing needed)
- Outputs summary.md to GitHub step summary
- Syncs package-lock.json for tiktoken/commander deps

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(evals): increase 01-create-file timeout to 120s

The 30s timeout was too short for reliable execution.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: restore changesets deleted during rebase

These changesets belong to the already-merged CLI fix (#9073)
and should not be deleted by this branch.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(evals): remove unused dependencies from package.json

Drop execa, node-fetch, ora, sqlite, uuid, yargs and their types.
These were leftovers from the old CLI-based eval runner. The smoke
tests use Node builtins and the tool-precision benchmark only needs
axios, better-sqlite3, chalk, commander, dotenv, tiktoken.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add TypeScript build info files to .gitignore

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-02-12 22:23:35 -06:00
Robin Newhouse e85332319e feat: add .agents/skills directory support for skill discovery (#9074)
* feat: add .agents/skills directory support for skill discovery

Add compatibility for the standardized .agents/skills directory pattern,
both globally (~/.agents/skills) and locally (.agents/skills in workspace).

* feat: make .agents/skills the default for new skills

New skills are now created in .agents/skills (local) and ~/.agents/skills
(global) by default. These directories also have highest priority in
skill discovery, overriding skills with the same name from other locations.

* docs: update skills documentation for .agents/skills directories

* refactor skills directory helpers
2026-02-12 22:08:30 -06:00
Bee 1a29d428ae refactor: BannerService initialization and cache management (#8969)
* increases banner cache duration to 24 hours so we make one api calls per day per user; implements a circuit breaker that stops retrying after 3 consecutive failures

* add new tests

* Clear banner cache when auth status changes

* revert 5898bc6e0e

* Fixing circuit breaker

* fix: reset circuitBreakerOpenedAt on failed half-open recovery

Previously, circuitBreakerOpenedAt was only set when consecutiveFailures
reached exactly MAX_CONSECUTIVE_FAILURES. This meant that after a failed
half-open recovery attempt, the timestamp wasn't updated, causing the
circuit breaker to immediately enter half-open state again on the next call.

Now circuitBreakerOpenedAt is updated on every failure once the circuit
breaker is tripped, ensuring proper timeout between recovery attempts.

* refactor: BannerService initialization and cache management

- Move BannerService initialization from common.ts to AuthService (which is initialized in controller)
- Re-initialize BannerService after auth state updates to ensure user context
- Add HostRegistryInfo to centralize host/platform information collection
- Improve rate limiting with exponential backoff (5min → 15min → 30min)
- Refactor error handling to better distinguish between rate limits and server errors
- Remove temporary disabled banner fetching comments

This change ensures banners are only fetched when user authentication is
available and implements more robust rate limiting to prevent API hammering.
The banner service now properly tracks user context and respects server
rate limits with progressive backoff delays.

* refactor(banner): simplify banner service initialization and usage

- Remove `getBanners()` wrapper method from Controller class
- Call `BannerService.get().getActiveBanners()` directly in Controller
- Change `BannerService.initialize()` to synchronous, returns instance immediately
- Make banner fetching non-blocking by moving to background
- Remove unused `BannerCardData` import from Controller
- Update tests to handle asynchronous background fetching with timeouts
- Clean up AuthService banner service initialization comment

This change simplifies the banner service API by removing unnecessary abstraction layers and making initialization non-blocking. The service now fetches banners in the background rather than blocking on initialization, improving application startup performance.

* clean up

* apply feedback

* un-skip unit test

* mock

* mock env

* clean up and add debounce fetch

* log fetch time

* revert

* feature flag: remote-banners

* fix loop in authService on auth update

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

* Fix tests

* small fixes

* use .? for banner

* moves initializeDistinctId to StateManager

* initializeDistinctId

* use v2 endpoint

---------

Co-authored-by: Zhongying Qiao <cryptoque@users.noreply.github.com>
Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
Co-authored-by: Tomás Barreiro <BarreiroT@users.noreply.github.com>
Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
Co-authored-by: BarreiroT <tomasmbarreiroi@gmail.com>
2026-02-12 18:28:12 -08:00
Saoud Rizwan 92cf03e42c feat(subagents): simplify research output guidance and command workflow (#9284) 2026-02-12 16:00:02 -08:00
Bee 3ea393a5e9 fix: openai native provider token usage mapping (#9272)
* fix: openai native provider token usage mapping

- Add `store` parameter support to OpenAI native provider options to allow persisting completions.
- Fix incorrect mapping of `cached_tokens` and `reasoning_tokens` in usage statistics.
- Include `thoughtsTokenCount` in the final usage report to track reasoning model performance and costs.

* Update src/core/api/providers/openai-native.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-12 14:26:35 -08:00
Max 9829e7d49e restore yolo mode to what it was before cline cli started (#9205)
Apply suggestions from code review

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-12 11:10:24 -08:00
Max 56de96e5ff fix oca auth (#9145)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-12 10:20:28 -08:00
github-actions[bot] ecde79cf08 v3.59.0 Release Notes (#9263)
- Added Minimax 2.5 Free Promo
- Fixed Response chaining for OpenAI's Responses API

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-12 10:20:19 -08:00
Bee ff36cbcb87 feat: implement response chaining for Responses API (#9270)
* feat: implement response chaining for Responses API

Implement response chaining by tracking and passing previous_response_id
to continue conversations from the last assistant message. This enables
the Responses API to maintain context across multiple turns.

Key changes:
- Search backwards through messages to find last assistant message with ID
- Only send new messages after the chained response
- Track function call metadata (call_id, name, id) across chunks
- Include call_id in tool_call events for proper correlation
- Clean up debug logging and remove commented code
- Remove redundant "Ran out of tokens" log message

This improves conversation continuity and ensures function calls are
properly tracked with their associated IDs throughout the streaming
response lifecycle.

* clean up

* update oca

* codex
2026-02-12 10:01:34 -08:00
shey-cline 5a75f08118 Prevent Parent Container Scrolling In Dropdowns (#9146)
* init

* missed some dropdowns & make scroll behavior work for scrolling nested elements

* add changeset

* add combobox roles
2026-02-12 10:00:40 -08:00
shey-cline 120754c2fe Allow Custom AWS Regions in Bedrock (Extension) (#9104)
* init

* changeset

* addressed comments – add onBlur, aria attributes and redundant useMemo
2026-02-12 09:57:04 -08:00
Saoud Rizwan 5d048d09f8 fix(subagents): retry initial stream bootstrap failures (#9264)
* fix(subagents): retry initial stream bootstrap failures

* fix(subagents): align initial retry classification with main loop

* fix(subagents): compact context on window limit during startup

* fix(subagents): proactively compact context at token thresholds

* feat(subagents): optimize file reads before context truncation
2026-02-12 06:34:43 -08:00
Saoud Rizwan 36580ce086 chore(codex): update environment to use launch script and simplify reinstall
Point the VS Code action at the new run-extension-host.sh script and
drop the git checkout of lock files from the reinstall action.
2026-02-12 05:53:25 -08:00
Saoud Rizwan c584bf4185 feat(dev): add tmux-based extension host launch script
Replaces the inline VS Code launch command with a proper dev script that:
- Builds protos and webview upfront
- Runs esbuild, tsc, and webview watchers in parallel tmux panes
- Waits for dist/extension.js before launching the extension host
- Cleans up all processes and closes the dev window on Ctrl+C
2026-02-12 05:53:18 -08:00
Saoud Rizwan 8133babf41 fix(chat): keep focus chain placeholder visible to prevent layout jump (#9266)
* fix(webview): stabilize focus chain header space and placeholder

* fix(chat): add follow-up bottom scroll to avoid short scroll

* style(chat): refine markdown spacing and tool group summary tone

* fix(chat): retry auto-scroll at 40ms and 70ms

* fix(chat): keep focus chain placeholder visible until checklist exists
2026-02-12 03:50:01 -08:00
Saoud Rizwan 741f524da7 chore(deps): upgrade openai sdk to 6.21.0 for xhigh reasoning (#9267) 2026-02-12 03:48:13 -08:00
Robin Newhouse d3918dd7df fix(task): canonicalize attempt_completion result parameter (#9262) 2026-02-12 00:37:27 -06:00
alex-lum 024bb65443 Add organization attributes to telemetry metrics (#9242) 2026-02-11 16:51:24 -08:00
github-actions[bot] 58ebbdbf80 Changeset version bump (#9252)
* changeset version bump

* Updating CHANGELOG.md format

* changeset version bump

* Updating CHANGELOG.md format

* Eve manually updating the banner and the release version

* Manually update the changelog

* Fix GLM 5 model ID in banner

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: cline-test <132302818+candieduniverse@users.noreply.github.com>
2026-02-11 16:30:14 -08:00
Juan Pablo Flores cee74d2f3a docs: add subagents feature documentation (#9258)
* docs: add subagents feature documentation

Add new documentation page covering the Subagents feature, including
how it works, enabling/configuring, auto-approve behavior, available
tools, and usage guidance. Register the page in docs.json sidebar nav.

* docs: remove hardcoded subagent limit from subagents page

Remove references to 'up to five' subagents, as the limit is no longer
fixed. Updates both the intro paragraph and the How It Works section.
2026-02-11 15:54:57 -08:00
Ara a6f3b9f856 Revert "fix MCP OAuth: add missing scope parameter (#9117)" (#9256)
This reverts commit 401358374f.
2026-02-11 15:07:34 -08:00
Ara 0e524ffc3a feat(zai): add glm-5 pricing and make it default (#9254)
* feat(zai): add glm-5 pricing and make it default

* fix(zai,qwen): fallback model id when apiModelId is invalid
2026-02-11 14:05:50 -08:00
Ara 95ca14fa2a Fixing changeset files (#9251) 2026-02-11 12:38:31 -08:00
Max a6c57a4ce5 print task id in headless modes (#9229)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-11 12:21:02 -08:00
Tomás Barreiro 9470cf19cd Add headers to the Remotely Configured MCP server schema (#9238) 2026-02-11 18:53:44 +01:00
Saoud Rizwan acf34860bb chore: fix codex desktop app configuration 2026-02-11 02:34:33 -08:00
Saoud Rizwan 49cad88aca chore: fix codex desktop app configuration 2026-02-11 02:25:59 -08:00
Saoud Rizwan 3c65cbc7f2 chore: add codex desktop app configuration 2026-02-11 02:22:29 -08:00
Saoud Rizwan 12603d4be1 feat: replace legacy CLI subagents with native use_subagents tool (#9208)
* feat: checkpoint subagent tool workflow and approval UX

* feat: support subagent tool execution without native tool calls

* fix: expose use_subagents when native tool calling is disabled

* fix: stabilize subagent command UX and suppress nested command rows

* chore: tune subagent prompt guidance for context-heavy exploration

* fix: align subagent row spacing with chat row conventions

* fix: keep cancelled subagent state during immediate resume

* feat: implement subagent message rendering for approval prompts and progress updates

* feat: enhance SubagentRunner with tool use ID resolution and fallback handling

* fix: stabilize subagent cline requests with ulid and initial workspace metadata

* refactor: unify subagent chat row rendering

* feat: surface subagent costs in task metrics and status rows

* fix: refine cli subagent tree alignment and wrapping

* fix: refine subagent streaming rows in cli and webview

* fix: ensure unique act mode hint keys in CLI chat

* feat: add subagents settings toggle wiring across webview and cli

* fix(webview): stream subagent stats per prompt while constructing prompts

* fix: remove duplicate subagentsEnabled declaration after rebase

* chore: restore package lockfiles to main

* fix: harden task history usage parsing and clean prompt separators

* chore: refine subagent response formatting guidance

* feat: collapse subagent prompts with show more

* feat: show latest subagent tool call in status rows

* fix: fall back to non-native mode for subagents when native tools are unavailable

* fix: retry empty subagent responses before failing

* fix(subagents): require attempt_completion and dedupe tool result formatting

* feat(subagents): polish prompt guidance and webview status row
2026-02-11 02:17:45 -08:00
Robin Newhouse b514f18e4f fix(task): prevent duplicate streamed text rows after completion (#9235)
* fix(task): prevent duplicate partial text rows after completion

Avoid adding a new partial text message when the latest text row is already completed with the same content. This stops a presenter race from rendering duplicate streamed text lines for MiniMax-style timing.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(task): cover duplicate partial text dedupe behavior

Add a Task.say unit test that reproduces the duplicate-partial-after-complete scenario and verifies we skip creating a second text row with identical content.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-10 23:44:01 -08:00
Saoud Rizwan ce85d7d414 fix(cli): preserve OAuth callback paths in auth redirects (#9237) 2026-02-10 19:28:28 -08:00
Saoud Rizwan 739d75afe3 fix(claude-code): add opus 4.6 1m model option (#9231)
* fix(claude-code): add opus 4.6 1m model option

* fix(claude-code): support opus[1m] alias and align opus alias

* fix(claude-code): add sonnet[1m] model support
2026-02-11 04:19:44 +01:00
Max fc1be2baac add more shortcuts to help output (#9204)
* add more shortcuts to help output

* Apply suggestions from code review

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

---------

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-10 16:14:11 -08:00
Saoud Rizwan 5dcaa8c8cc fix(vertex): add opus 4.6 1m model support on Vertex (#9230)
* fix(vertex): add opus 4.6 1m and global endpoint support

* fix(vertex): enable thinking for opus 4.6 1m in webview
2026-02-10 15:30:12 -08:00
CandiedUniverse 79cf77db0a Finish adding Amazon Bedrock to isNexGenModelProvider() list [CLINE-1291] (#9216)
* Add Bedrock to the list in isNextGenModelProvider()

* feat(bedrock): Remove testing script used to develop isNextGenModelProvider() change against

* refactor: extract shared isParallelToolCallingEnabled into model-utils

Consolidate duplicated parallel tool calling logic from ToolExecutor.ts
and task/index.ts into a single exported function in model-utils.ts.

Both callers now delegate to the shared function, eliminating the need
to maintain identical checks in two places.
2026-02-10 14:39:48 -08:00
Robin Newhouse 4b61799df5 docs: improve PR creation skill to use --body-file flag (#8789)
Replaces inline --body with --body-file approach in the PR creation skill documentation. This avoids shell escaping issues, newline problems, and command-line flakiness when creating PRs with complex markdown content.

Related to #8785
2026-02-10 15:52:05 -06:00
cryptoque 806708e802 feat: enable sync-ed deletion for remote mcp servers from remote config to extension (#9210)
* feat: enable sync-ed deletion for remote mcp servers from remote config to extension

* chore: add tests for syncing remote mcp server adding and removal

* address comments
2026-02-10 10:24:19 -08:00
Max 642ea849e3 fix publish-cli-trusted workflow (#9220)
- parent workflow needs to request permissions for children workflows

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 21:53:40 -08:00
Max dff8193de5 make trusted npm publish workflow (#9219)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 21:40:04 -08:00
Max a05c1c5e53 store input text on remount (#9124)
- my input was getting cleared when i resized the screen. this fixes
that

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 21:06:59 -08:00
Max 9a11976d27 improve cline config command (#9212)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 18:15:05 -08:00
Tomás Barreiro b54647ab17 [PF-389] Render remote config options and add test buttons (#9051)
* WIP - Render a Remote Config secttion and add an option to refresh

* Add the different remote config sections and test them

* fixes

* refactor

* Add proper wrapping

* Stack more values

* Properly report errors when prompt uploading fails

* Add a better error message for the otel test button

* clean

* Fix option rendering

* Render less options if they aren't configured
2026-02-10 02:46:40 +01:00
ClineXDiego 6e253dfa9a Fix/vscode web oauth callback (#9173)
* fix: use vscode.env.asExternalUri for web OAuth callbacks

In VS Code Web (Codespaces, code serve-web), OAuth callbacks using
http://127.0.0.1:PORT break because the extension host runs remotely.

Changes:
- getCallbackUrl now accepts a path parameter
- Desktop: uses vscode://extension-id/path directly
- Web (UIKind.Web): uses vscode.env.asExternalUri() for web-reachable URL
- Updated all callers (/auth, /openrouter, /hicap, /requesty, MCP) to
  pass path and use URL+searchParams for proper encoding
- Added regression test asserting web callback URL is not 127.0.0.1
- AuthHandler (localhost HTTP) now only used by CLI/standalone mode

* fix: use URL.searchParams for proper callback URL encoding

Callers were using template literal interpolation to embed callback URLs
into query strings, which breaks when the URL contains special characters
(e.g. from asExternalUri with query params). Use URL+searchParams.set()
which automatically encodes values.

* chore: revert unrelated whitespace change in account.proto

* revert: remove non-essential URL encoding changes in auth callers

Keep only the core fix (getCallbackUrl path parameter + asExternalUri for web).
Revert the URL+searchParams encoding improvement to minimize diff.

* fix: URL-encode callback_url in auth callers, add encoding test

In VS Code Web, callback URLs from asExternalUri can contain their own
query params (?tkn=...&extra=...). String-interpolating them into
callback_url= causes everything after the first & to be parsed as
top-level params, truncating the callback URL.

Use URL + searchParams.set() in openrouter, hicap, and requesty callers.
Replace tautology test with deterministic round-trip encoding assertions.
2026-02-09 16:43:24 -08:00
Ara 7236d02ebb feat(tools): add auto-approval support for attempt_completion commands (#8926)
* feat(tools): add auto-approval support for attempt_completion commands

- Add auto-approval logic for bash commands in AttemptCompletionHandler
- Show commands as 'say' instead of 'ask' when auto-approved
- Display notification prompting user approval when manual approval needed
- Add 30-second timeout notification for long-running auto-approved commands
- Fix Logger import path from @/shared to @shared

* Send to cline provider
2026-02-09 15:57:29 -08:00
Saoud Rizwan 84fef6fe1f chore(ci): remove ai review workflows and publish caching (#9211) 2026-02-09 15:42:44 -08:00
CandiedUniverse 7bdbf0a9a7 feat(bedrock): Support parallel tool calling in Amazon Bedrock [CLINE-1291] (#9150)
* feat(bedrock): Create agent implementation plan for supporting parallel tool calling.

* Add Bedrock tool calling support

* Improve Bedrock tool calling test guidance

* Add Bedrock CLI parallel tool calling test script

* fix: add ALLOW_AWS_DEFAULT_CHAIN support to live integration test script

* chore: add changeset for Bedrock parallel tool calling

* feat(bedrock): enable native parallel tool calling for Bedrock provider

- Add 'bedrock' to isNextGenModelProvider() so native tool calling is enabled
- Add 'bedrock' to getNativeConverter() to use Anthropic-format tool specs (input_schema)
- Fix empty tool description validation error in mapClineToolsToBedrockToolConfig
  (Bedrock requires description length >= 1)
- Update CLI test to use Sonnet 4.5 (Haiku too small for native tool calling)
- Add <invoke> XML detection to CLI test to catch XML fallback

Verified: conversation history shows 3 native tool_use blocks in a single
assistant response with 3 matching tool_result blocks — true parallel
tool calling via Bedrock Converse API.

* docs: mark all phases complete in bedrock parallel tool calling implementation plan

* chore: switch test scripts default model to Haiku 4.5 (cheaper for testing)

* feat: enhance CLI verification suite with 3 test cases (single, parallel, round-trip)

* Remove bedrock parallel tool calling implementation plan doc.

* refactor: simplify to single CLI verification script for bedrock parallel tool calling

Remove the handler-level test script (test-bedrock-tool-calling.ts) and consolidate
into a single focused CLI test that proves parallel tool calling works end-to-end:
- Spawns Cline CLI with Bedrock config
- Asks it to read 3 files
- Verifies ≥2 parallel native tool calls (not XML fallback)
- Task completion proves tool result round-trip works

* refactor(bedrock): improve type safety and code quality for parallel tool calling

- Add typed interfaces (ToolUseStart, ToolUseDelta) for Bedrock stream
  events instead of relying on `as any` casts
- Extend ContentBlockStart and ContentBlockDelta interfaces with toolUse
  fields so stream parsing uses typed property access
- Remove dead `inputBuffer` field from activeToolCalls Map (was tracked
  but never read — tool input deltas are yielded immediately)
- Add JSDoc to mapClineToolsToBedrockToolConfig explaining its purpose
  and return semantics
- Document why createDeepseekMessage intentionally ignores the tools
  parameter (DeepSeek R1 uses InvokeModel, not Converse API)

* refactor(scripts): improve test script readability and resource cleanup

- Add try/finally with cleanupDirs() to remove temp workspace and config
  dirs after each run (previously accumulated in $TMPDIR)
- Extract named constants for CLI_TIMEOUT_SECONDS and HEARTBEAT_INTERVAL_MS
- Add CliResult interface for the runCli return type
- Rename cryptic variables: hb → heartbeatInterval, c → chunk, p/d → filePath/data
- Add JSDoc to parseReadFilePaths and hasXmlFallback
- Add explanatory comments to empty catch blocks
- Log stderr on non-zero exit code for easier debugging
- Extract createTestWorkspace() to separate workspace setup from main flow
- Add section separator comments for visual structure

* test(bedrock): add missing edge-case tests and remove dead describe block

- Add tests for mapClineToolsToBedrockToolConfig edge cases:
  undefined/empty input returns undefined, tools without input_schema
  are silently dropped
- Add test for formatMessagesForConverseAPI with array tool_result
  content (multi-block text responses)
- Add test for tool_result is_error → status:'error' mapping
- Remove empty 'reasoning content handling (deprecated)' describe block

35 tests passing (was 31).

* test(bedrock): add integration-level tests covering E2E script gaps

Add 'native tool calling integration' test suite that validates the
concerns previously only covered by the live E2E CLI script:

- Bedrock + Claude 4 is recognized as native tool calling eligible
  (catches silent regression if Bedrock is removed from
  isNextGenModelProvider or Claude 4 from isNextGenModelFamily)
- Bedrock + Claude 3.x correctly does NOT qualify (pre-4.0 guard)
- Native tool calling disabled when user setting is off
- createAnthropicMessage passes toolConfig to ConverseStreamCommand
  (catches the tool spec not reaching the API)
- Full multi-turn tool call round-trip formatting (tool_use in
  assistant → tool_result in user → reformatted for next API call)

40 tests passing (was 35).

* Remove functional verification script before code review
2026-02-09 15:23:56 -08:00
Max bab336f172 use cline provider for cline pr review workflow. use npx instead of npm install (#9202)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 10:21:32 -08:00
Max 967342999f if yolo mode is on, don't ask permission to use mcp tools (#9100)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-09 10:12:30 -08:00
Jose R. Perez d19a8779e7 feat: consolidate ViewHeader and styling (#8989)
* feat: consolidate ViewHeader and styling

* feat: changeset

* fix: added back environment variables for color differentiation

* fix: co-pilot fixes

* feat: github copilot fix
2026-02-09 10:02:16 -08:00
Saoud Rizwan 5c04fa3aa3 fix(cli): flush telemetry on shutdown and include activation metadata (#9195) 2026-02-08 22:00:45 -08:00
Saoud Rizwan 7c31c1d02a fix: restore reasoning behavior parity after #9168 (#9188)
* fix: restore reasoning parity after #9168

* fix: restore webview reasoning support compatibility checks

fix: simplify reasoning support model matching
2026-02-08 19:43:23 -08:00
Saoud Rizwan 740f99400b feat(cli): add max-consecutive-mistakes task flag (#9194) 2026-02-08 18:52:45 -08:00
Igor Tceglevskii 195294f389 feat: bundled endpoints.json (#9113) 2026-02-08 18:31:01 -08:00
Saoud Rizwan 2cc070eee2 fix(api): preserve vercel model id when metadata is missing (#9192) 2026-02-08 18:00:13 -08:00
Saoud Rizwan 627838243e fix(e2e): increase test timeout for Windows CI runners (#9185)
The diff editor e2e test flakes consistently on Windows CI because the
40s test timeout is too tight. The test does signin, message send,
history verification, then a second message send before the diff
assertion -- on slow Windows runners this setup alone can eat most of
the budget. Bumping to 60s gives enough headroom.
2026-02-08 11:27:48 -08:00
Saoud Rizwan f8a1f75664 feat: add output precision and threshold rules to double-check prompt (#9184)
Add Terminal-Bench-proven rules as items 5 and 6 in the double-check
re-verification checklist, so they're enforced at completion
verification time rather than in the system prompt.
2026-02-08 11:09:27 -08:00
Saoud Rizwan 54aeba1fee feat: add double-check completion experimental feature (#9180)
* feat: add double-check completion experimental feature

When enabled, the first attempt_completion call in a task is rejected
with a tool error that instructs the model to re-verify its work
against the original task requirements. The rejection includes the
initial task text for context. The second call proceeds normally.

This is opt-in (default off) and available via:
- Settings > Features > Experimental > Double-Check Completion
- CLI flag: --double-check-completion
- CLI TUI settings panel toggle

Adds completionAttemptCount to TaskState, plumbs the setting through
TaskConfig/ToolExecutor following existing patterns, and includes
9 unit tests.

* chore: add cli:run script for quick CLI testing

* fix: increase task preview to 8000 chars, revert unintended regex change

* fix: preserve existing proto field numbers

The auto-generator renumbered open_ai_headers (175->177) and
openai_codex_oauth_credentials (46->48), and dropped the reserved 146
comment. Restore original field numbers to avoid breaking wire-format
compatibility.

* fix: remove partial completion_result message on double-check rejection

During streaming, handlePartialBlock shows the completion_result in
the chat view. When we reject the first attempt, we need to clean up
that partial message so the user doesn't see a stale completion that
was actually rejected.

* refactor: switch from counter to boolean toggle for double-check

Use a boolean pending flag instead of a counter so that every
attempt_completion gets double-checked, not just the first one in
a task. The flag toggles: reject (set pending), accept (clear pending),
so if the model does more work and tries to complete again later, it
gets double-checked again.
2026-02-08 10:56:10 -08:00
Robin Newhouse a03642ba4a fix(prompt): add output precision and threshold iteration rules (#9178)
* fix(prompt): add output precision and threshold iteration rules

Two concise rules proven effective via Terminal-Bench testing:

1. Output precision: produce exactly what's specified, no extra columns/fields/debug output
2. Threshold iteration: verify results meet numerical criteria before completing

Tested on 6 targeted Terminal-Bench tasks (job 2026-02-07__16-15-00):
- log-summary-date-ranges: FAIL→PASS (output precision rule eliminated extra columns)
- dna-insert: FAIL→PASS (iterate rule helped agent meet Tm threshold)

A third rule (no-cleanup) was tested and deliberately excluded: it failed to
prevent self-sabotage on configure-git-webserver despite STRICTLY FORBIDDEN
language, and caused a side-effect on polyglot-c-py by preventing legitimate
build artifact cleanup. The cleanup behavior is too deeply trained to override
via prompt rules alone.

* test: update prompt snapshots for new rules
2026-02-08 09:37:04 -08:00
Saoud Rizwan b65435fc55 fix(cli): route PostHog networking through shared fetch (#9149)
* fix(cli): route PostHog networking through shared fetch

* remove unnecessary `as RequestInit` casts from PostHog fetch wrappers

PostHogFetchOptions is a structural subset of RequestInit, so the cast
is unnecessary. Also removes a stale comment about shared client support
in PostHogErrorProvider.
2026-02-07 18:26:23 -08:00
Saoud Rizwan 88694d39fa feat(cli): allow --thinking flag to accept custom token budget (#9177)
The --thinking flag now accepts an optional number argument to set a
custom thinking budget instead of always using the 1024 default.

  cline "prompt" --thinking         # 1024 tokens (default)
  cline "prompt" --thinking 8000    # 8000 tokens

Invalid values get a warning and fall back to 1024.
2026-02-07 17:06:33 -08:00
Saoud Rizwan 6c53daa88e feat: move reasoning effort to model config and settings UX (#9168)
* feat: move reasoning effort to model config and update model selection UX

* refactor: dedupe reasoning effort handling and drop lockfile churn

* refactor: default reasoning effort to low

* refactor(cli): sync mode-scoped thinking and reasoning writes

* fix: centralize reasoning effort normalization and avoid implicit openai effort

* fix: restore proto field number for codex credentials and reserve removed fields

- Keep openai_codex_oauth_credentials at field 46 (was incorrectly
  changed to 47)
- Add reserved 146 in Settings for removed openai_reasoning_effort
- Add reserved 15 in UpdateSettingsRequest for removed openai_reasoning_effort
- Remove stale openai_reasoning_effort field from UpdateSettingsRequest

* fix: map medium reasoning effort to LOW for Gemini models

Gemini API only accepts LOW and HIGH thinking levels. MEDIUM exists in
the SDK enum but is rejected at the API level. Map medium to LOW and
update the default fallback accordingly.
2026-02-07 16:58:10 -08:00
Ara 1f3c00c613 feat(task): add support for writing prompt metadata artifacts (#9158)
Introduces a mechanism to save system prompts and task metadata to disk for debugging and analysis purposes.

- Added `writePromptMetadataArtifacts` to the `Task` class.
- Feature is enabled via the `CLINE_WRITE_PROMPT_ARTIFACTS` environment variable.
- Artifacts are saved to `.cline-prompt-artifacts` or a custom path defined by `CLINE_PROMPT_ARTIFACT_DIR`.
- Writes both a JSON manifest (containing task ID, model info, and timestamp) and the raw system prompt for every API request.
2026-02-07 15:21:41 -08:00
Saoud Rizwan 4d455ea015 fix(terminal): tune execute_command timeout strategy for long-running tasks (#9159)
* fix(terminal): tune managed timeout policy for long-running commands

* Reduce default command timeout from 120 to 30 seconds

* Update ExecuteCommandToolHandler.timeout.test.ts

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2026-02-07 14:47:26 -08:00
Saoud Rizwan 3daf24662e fix(prompt): add guidance to use -- for leading-dash positional args (#9161) 2026-02-07 14:18:55 -08:00
Saoud Rizwan 942fcf5762 fix(terminal): surface command exit codes in results (#9156) 2026-02-07 13:31:22 -08:00
ClineXDiego 70a99047ed fix: use vscode.env.asExternalUri for auth callback URLs in VS Code Web (#9144)
* fix: use vscode.env.asExternalUri for auth callback URLs in VS Code Web

The OAuth callback redirect was broken in VS Code Web (code serve-web)
environments because the callback URL used a raw vscode:// URI scheme,
which the OS would route to the local desktop VS Code app instead of
the web instance.

This change wraps both getCallbackUrl() and getIdeRedirectUri() with
vscode.env.asExternalUri() which properly transforms URIs based on the
environment:
- Desktop VS Code: unchanged (vscode://...)
- VS Code Remote SSH: adds remote authority for proper routing
- VS Code Web: transforms to HTTPS URL that routes through the web server

Fixes #5109 (remaining callback redirect issue)
Related: #2152

* fix: use HTTP-based auth callback for VS Code Web mode

In VS Code Web (code serve-web), vscode:// URIs redirect to the desktop
app instead of staying in the browser. This change uses AuthHandler
(local HTTP server) for the auth callback in web mode, matching how
CLI/standalone already handles auth.

- getCallbackUrl: use AuthHandler when UIKind.Web
- getIdeRedirectUri: return empty in web mode to avoid vscode:// redirect

* fix: add fallback for openExternal RPC for JetBrains compatibility

The openExternal host bridge RPC is not implemented in the JetBrains
plugin, causing sign-in to fail silently. This adds a fallback to the
'open' npm package when the host RPC fails with UNIMPLEMENTED.

Fixes #9164, #9137, #9138
2026-02-07 10:25:14 -08:00
Robin Newhouse 844038084c feat: add CLI build workflow for testing from any commit (#9131) 2026-02-07 05:23:22 -08:00
Robin Newhouse 0c6f77ea46 Remove accidentally committed implementation_plan.md (#9160) 2026-02-07 00:11:02 -06:00
Saoud Rizwan 9b70f94174 fix(prompt): require verification before completion (#9154)
* fix(prompt): require verification before completion

* fix(prompt): align gemini verification-first completion guidance
2026-02-06 19:22:40 -08:00
Saoud Rizwan 0a4f939ecb chore(ci): tag bot PR reviews with workflow footer (#9152) 2026-02-06 15:08:38 -08:00
Tomás Barreiro 095ee24288 Limit the CLI provider list to what's remotely configured (#9135)
* Limit the CLI provider list to what's remotely configured

* Refactor

* fix react
2026-02-06 09:14:29 -08:00
Saoud Rizwan 523dd9ef7d fix(ui): add loading indicator and fix api_req_started rendering (#9133)
The chat streaming UI refactor removed the loading indicator that
previously showed when an API request was in progress. This left users
staring at a frozen UI during the latency between sending a message
and receiving the first streamed content.

Changes:
- Add "Thinking..." shimmer in the Virtuoso Footer as the sole loading
  indicator, covering both pre-api_req_started (backend processing) and
  post-api_req_started (waiting for model response) states
- Filter out api_req_started messages that have no visible content
  (no error/cancel). These rows rendered as invisible padding since
  the PR removed the old API request accordion UI. Reasoning messages
  already render as their own standalone ChatRows.
- Thread footerActive flag to MessageRenderer so the last message skips
  pb-2.5 when the Footer is showing, keeping spacing consistent with
  the pt-2.5 on every ChatRow
2026-02-05 16:38:21 -08:00
Robin Newhouse 6d8fb8507b fix(cli): handle stdin redirection in CI environments (#9121)
- Add stdinIsTTY check to shouldUsePlainTextMode() - Ink requires raw mode on stdin
- Only error on empty stdin when no prompt is provided (allows: cline 'prompt' < /dev/null)
- Fixes crash in GitHub Actions and other CI environments
2026-02-05 13:32:52 -08:00
Max edc93f35f1 update changelog for 3.57.1 (#9130)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-05 13:12:54 -08:00
ckrause 401358374f fix MCP OAuth: add missing scope parameter (#9117)
* fix MCP OAuth: add missing scope parameter

* Update src/services/mcp/McpOAuthManager.ts

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

* fix

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-05 13:06:01 -08:00
Max f8bcad16a5 update package-lock.json (#9127)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-05 12:44:46 -08:00
AJ Juaire 26391c94e9 Correct Bedrock Opus 4.6 model id (#9126) 2026-02-05 12:21:37 -08:00
Ara 462438ece5 Update changelog wording (#9125) 2026-02-05 11:53:48 -08:00
github-actions[bot] 92521ed279 Release Notes for v3.57.0 (#8980)
- Cline CLI 2.0 now available. Install with `npm install -g cline`
- Anthopic Opus 4.6
- Minimax-2.1 and Kimi-k2.5 now available for free for a limited time promo
- Codex-5.3 through OpenAI Codex provider

- Fix read file tool to support reading large files
- Fix decimal input crash in OpenAI Compatible price fields (#8129)
- Fix build complete handlers when updating the api config
- Fixed missing provider from list
- Fixed Favorite Icon / Star from getting clipped in the task history view

- Make skills always enabled and remove feature toggle setting

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-02-05 11:35:58 -08:00
Max 08aa81f798 add taskId flag to CLI (#9095)
- allows you to resume a session headlessly or interactively with a
taskId

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-05 11:32:54 -08:00
Tomás Barreiro e025995177 Revert LiteLLM model name change and use the rawModel name (#9123)
* Revert LiteLLM model name change and use the rawModel name

* Add both to the list
2026-02-05 11:15:17 -08:00
Saoud Rizwan ee361ef3ae feat: add GPT-5.3 Codex model for ChatGPT subscription users (#9122)
* feat: add GPT-5.3 Codex model for ChatGPT subscription users

OpenAI released GPT-5.3 Codex today. Adding it to the OpenAI Codex
provider (ChatGPT Plus/Pro subscription) model list and setting it
as the new default.

Changes:
- Add gpt-5.3-codex to openAiCodexModels with same specs as 5.2
- Update default model to gpt-5.3-codex
- Update featured models in CLI and webview OpenRouter picker

* revert: remove gpt-5.3-codex from OpenRouter featured models

GPT-5.3 Codex is only available via ChatGPT subscription, not through
the OpenAI API or OpenRouter. Reverting featured model changes.
2026-02-05 11:05:00 -08:00
Max c8ef342c19 cli multi label support. new featured model (#9118)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-05 10:51:54 -08:00
Saoud Rizwan 7c8701799d feat: add Claude Opus 4.6 model support (#9119)
* feat: add Claude Opus 4.6 model support with 1M context window

Adds support for Claude Opus 4.6, Anthropic's latest model with:
- 200K base context window with optional 1M context variant
- Tiered pricing for >200K context (2x input/output pricing)
- Extended thinking/reasoning support
- Prompt caching support

Changes:
- Added model definitions for Anthropic, Bedrock, and Vertex providers
- Added OpenRouter 1M variant support
- Updated thinking models lists across all provider UIs
- Added context window switcher for Opus 4.6
- Updated JP cross-region inference models list

* feat: update featured model to Opus 4.6 in model picker

* chore: add changeset for Claude Opus 4.6

* fix: correct Opus 4.6 model IDs (no date suffix)

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
2026-02-05 10:38:54 -08:00
Ara fbcf63ad71 fixing large model (#9110) 2026-02-05 09:16:25 -08:00
Saoud Rizwan fffe626b3a Bump CLI version from 2.0.3 to 2.0.4 2026-02-05 02:07:38 -08:00
Saoud Rizwan 2dccd6f6f6 fix(cli): use value import for React instead of type-only import
JSX requires React as a value when using jsx: react in tsconfig.
2026-02-05 02:04:22 -08:00
Saoud Rizwan 39971128cb fix(cli): use value import for React instead of type-only import 2026-02-05 02:00:43 -08:00
Saoud Rizwan b725490582 fix(cli): fix cursor position after pasting text
Use refs instead of state values in useInput callback to avoid stale
closures. Also manually update textInputRef before calling setCursorPos
so the bounds check uses the correct new text length.
2026-02-05 01:51:25 -08:00
Saoud Rizwan 8f78645154 fix(cli): show default model name when no model configured
ChatView was returning empty string when the model ID key didn't exist
in state, causing first-time CLI users to see a blank model name. Added
fallback to getProviderDefaultModelId() to match WelcomeView's behavior.
2026-02-05 01:33:24 -08:00
Saoud Rizwan 0ef1c0bf47 fix(cli): make robot animation static on click or drag
Previously the animated robot only became static when the user scrolled.
Now it also becomes static when clicking or dragging, giving users more
ways to dismiss the animation. Renamed onScroll to onInteraction to
reflect the broader scope.
2026-02-05 01:23:02 -08:00
Bee 4c07df370b chore: update biome configuration and linting rules (#9109)
* chore: update biome configuration and linting rules

Update @biomejs/biome package to latest version: 2.3.14

- Change $schema to point to local node_modules for better IDE performance and stability.
- Enable and promote several linting rules from "off" to "info" or "warn" across correctness, style, suspicious, and complexity categories.
- Update file inclusion/exclusion patterns to use more explicit formatting and set ignoreUnknown to true.
- Improve code quality enforcement by surfacing potential issues such as non-null assertions, useless constructors, and implicit any types.

* package-lock udpate

* includes tailwind

* useIterableCallbackReturn
2026-02-04 19:40:38 -08:00
ClineXDiego f440f3a5dd fix: use vscode.env.openExternal for auth in remote environments (#9111)
* fix: use vscode.env.openExternal for auth in remote environments

Fixes #5109

The OAuth authentication flow was broken in VS Code Server and remote
environments because the code used the npm 'open' package directly, which
tries to launch a browser on the server itself (which has no display).

This change routes browser URL opening through VS Code's native
vscode.env.openExternal() API via the HostBridge pattern, which properly
forwards URLs to the user's local machine in remote environments.

Changes:
- Added openExternal RPC to proto/host/env.proto
- Created VS Code handler using vscode.env.openExternal()
- Updated src/utils/env.ts to use HostProvider.env.openExternal()
- Added openExternal to CLI CliEnvServiceClient (uses npm 'open')
- Added openExternal to CLI ACPEnvServiceClient (uses npm 'open')

Related issues: #5394, #2152, #7971

* chore: add changeset for vscode server auth fix

* refactor: extract shared openUrlInBrowser utility for CLI
2026-02-04 19:31:20 -08:00
Tomás Barreiro 3ce1ad3504 Parse remotely configured R2 options (#9090)
* Parse remotely configured R2 options

* Fix R2 options
2026-02-05 03:53:44 +01:00
Tomás Barreiro 00bc38d4e0 Add Workspace Configuration to commit generation (#9107) 2026-02-05 02:25:17 +01:00
Tomás Barreiro a1f2601fe0 Replace the LiteLLM model selector with autocomplete (#9075)
* Replace the LiteLLM model selector with autocomplete

* Add changeset

* refactor
2026-02-04 12:42:08 -08:00
Max 8e3689a5d6 tag released cli versions (#9071)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-04 12:10:02 -08:00
Tomás Barreiro a64f46a5f4 Lock remotely configured Anthropic options (#9087)
* Add Anthropic to the remote config provider settings

* Lock the Anthropic Base URL when it's remotely configured
2026-02-04 19:42:02 +01:00
Tomás Barreiro 507483b2c3 Add Anthropic to the remote config provider settings (#9084) 2026-02-04 19:34:18 +01:00
Marco Alejandro Chavez Santos 42ce100143 Add Authentication Button on HICAP provider to get API KEY (#9098)
* add auth option to get API-KEY for hicap from hicap dashboard website

* remove default hicap model selection

* change url hicap get api keys, add useEffect when update hicapApiKey

* add changeset
2026-02-04 10:29:03 -08:00
CandiedUniverse 7be4e6c6d3 Remove isExperimental flag from Parallel Tool Calls feature setting. (#9097) 2026-02-04 09:47:41 -08:00
Ara 09b91a1ea5 chore: update CODEOWNERS assignments (#9096)
- Remove /docs/ from code ownership
- Update /.github/ owners to @arafatkatze, @maxpaulus43, @candieduniverse
- Update /README.md owner to @juanpflores
- Remove former owners @garoth, @sjf, @nickbaumann98
2026-02-04 09:29:15 -08:00
Tomás Barreiro 7127a2ffa7 Clean old API keys that are stored in secrets (#9091) 2026-02-04 12:02:17 -03:00
Bee d6987d4578 chore: update package-lock.json (#9079) 2026-02-03 21:09:56 -08:00
Tomás Barreiro 7b59cbcb5c Add r2 Blob storage options (#9052) 2026-02-04 03:49:10 +01:00
Ara 0e26ba46d0 fix(ci): always run npm ci regardless of cache hit status (#9078)
Remove conditional checks that skipped dependency installation when
cache was hit. The npm cache speeds up npm ci but does not replace
the need to run it - node_modules still needs to be populated.
2026-02-03 16:34:57 -08:00
Max 3b313ae41f remove prepublish script (#9077)
- this was breaking the publish npm workflow when we try to run npm
publish from the dist-standalone folder (dist-standalone doesn't have
the esbuilt.ts file)
- we don't need this script anyway because we use the npm-main.yaml
workflow to publish the cli

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-03 15:54:37 -08:00
CandiedUniverse 7e74f35f23 feat(hooks): Call combineHookSequences() properly from the CLI. (#9066) 2026-02-03 14:19:56 -08:00
Saoud Rizwan 59c05f4b84 Update copyright year to 2026 2026-02-03 13:51:23 -08:00
Saoud Rizwan 5d6424682f Update README.md 2026-02-03 13:50:49 -08:00
Robin Newhouse b1a8db252a fix(cli): prevent hang when spawned without TTY (#9073)
* fix(cli): prevent hang when spawned without TTY

When the CLI is spawned as a child process without a TTY (e.g., from
spawn() in smoke tests or CI), process.stdin.isTTY is false even when
nothing is piped to stdin. This caused readStdinIfPiped() to wait up
to 5 minutes for input that would never arrive.

Fix by using fs.fstatSync(0) to check if stdin is actually a FIFO
(pipe) or file before waiting. This correctly handles:
- Spawned processes without TTY → returns immediately
- Actual piped input (echo "x" | cline) → waits and reads
- stdin from /dev/null → returns immediately

* chore: add changeset

* test(cli): add tests for stdin type detection
2026-02-03 13:45:56 -08:00
Tony Loehr 5ae47fb90b Update docs for CLI 2.0 and fix workflow (#9068)
* Add ACP editor integrations documentation with JetBrains and Neovim video demos

* Add Model Orchestration documentation with --config and --thinking flags

- Document --config and --thinking flags in CLI reference
- Create new model-orchestration.mdx sample page
- Add patterns for CI/CD review, task phase optimization, and multi-model consensus
- Link to production GitHub Actions workflow
- Update samples overview with new card
- Update docs navigation

* Add Worktree Workflows documentation with --cwd flag

- Document --cwd flag in CLI reference
- Create comprehensive worktree-workflows.mdx sample page
- Add patterns for parallel execution and cross-worktree piping
- Include real-world examples and best practices
- Add CLI section to features/worktrees.mdx for discoverability
- Update samples overview and navigation
- Cross-link between CLI and VS Code worktree docs

* Remove broken image references from worktrees documentation

- Remove worktrees-overview.png Frame (image not available)
- Remove worktrees-merge.png Frame (image not available)
- Documentation remains fully functional with comprehensive text explanations

* Remove accidentally committed local test file

- Delete src/test/verify-platformio-mcp.ts which was causing CI failures
- File contained TypeScript errors and hardcoded local paths
- Was meant for local testing only, should not have been committed

* Add native JetBrains plugin recommendation to ACP docs

- Add prominent Note recommending native JetBrains plugin
- Link directly to JetBrains installation section
- Position ACP setup as an alternative approach
- Keep all existing ACP content and video

* docs: refine CLI reference formatting and ACP title

Improve CLI reference readability with clearer headings and descriptions, and clarify the ACP editor integration page title for better discovery.docs: refine CLI reference formatting and ACP title

Improve CLI reference readability with clearer headings and descriptions, and clarify the ACP editor integration page title for better discovery.

* Fix CLI 2.0 syntax in model-orchestration.mdx

- Updated issue analysis pipeline to use shell variables for passing context
- Added explanatory note about why direct piping doesn't work
- Corrected example to complete each phase before starting the next
- All examples now use proper CLI 2.0 syntax

* Completely rewrite cli-reference.mdx with accurate CLI 2.0 information

- Removed all outdated CLI 1.0 content (instance management, Cline Core architecture, gRPC references)
- Added accurate CLI 2.0 commands: task, history, config, auth, update, version, dev
- Corrected all command flags and options based on actual man page
- Added proper examples for all commands
- Included environment variables documentation (CLINE_DIR, CLINE_COMMAND_PERMISSIONS)
- Added shell completion instructions
- Removed incorrect three-layer architecture description
- All content now matches cli/man/cline.1.md source of truth

Fixes outdated documentation issue mentioned in PR#9036

* Fix MDX syntax error in cli-reference.mdx

- Replace angle bracket URLs with proper markdown links
- MDX parser was interpreting <https://...> as invalid HTML tags
- Now uses [url](url) format which is proper MDX syntax

Fixes deployment validation error

* docs: Add GitHub PR Review sample and modernize Actions integration

* fix: Add cline installation step to PR review workflow

- Fix CI/CD failure by actually installing cline before running it
- Update docs model ID to match workflow (claude-opus-4-5-20251101)
- Change from 'npx cline version' to 'npm install -g cline' + 'cline version'

---------

Co-authored-by: Renee Huang <renee@cline.bot>
2026-02-03 13:31:35 -08:00
Tomás Barreiro 28c2697ae1 Refresh LiteLLM models (#9070)
* Refresh LiteLLM models

* return promise

* Disable button while loading

* Loading

* Await the fetch
2026-02-03 21:57:06 +01:00
Saoud Rizwan cf01317885 fix(cli): await applyProviderConfig in handleProviderSelect
applyProviderConfig is async and for Cline/OpenRouter providers it
awaits fetching model data before setting state. When switching to
an already-configured provider (Cline, OCA), the call wasn't awaited,
so refreshModelIds() ran before the model ID was set in state,
causing the model to not update to the default.
2026-02-03 12:56:32 -08:00
Saoud Rizwan 7d5eebe192 Bump CLI version from 2.0.2 to 2.0.3 2026-02-03 12:52:21 -08:00
Saoud Rizwan 91a3636356 refactor(cli): add applyBedrockConfig utility, simplify saveConfiguration
- Added applyBedrockConfig to provider-config.ts for AWS Bedrock setup
- AuthView saveConfiguration now uses applyProviderConfig/applyBedrockConfig
- SettingsPanelContent handleBedrockComplete now uses applyBedrockConfig
- Removed duplicate Bedrock config building code from both components
- Cleaned up unused imports

# Conflicts:
#	cli/src/components/SettingsPanelContent.tsx
2026-02-03 12:39:41 -08:00
Saoud Rizwan 5d02eea9cd refactor(cli): use applyProviderConfig in ImportView, remove legacy apiProvider
- ImportView now uses applyProviderConfig instead of manual config building
- Removed legacy apiProvider field from AuthView, ImportView, SettingsPanelContent
  (it's unused - runtime reads actModeApiProvider/planModeApiProvider instead)
2026-02-03 12:39:41 -08:00
Saoud Rizwan 45b2786dbf fix(cli): ensure welcomeViewCompleted is flushed after applyProviderConfig
applyProviderConfig calls flushPendingState internally, so any state
set after it needs its own flush. Added explicit flush after setting
welcomeViewCompleted in OCA and OpenAI Codex auth success handlers.
2026-02-03 12:39:41 -08:00
Saoud Rizwan 4924192b64 refactor(cli): use applyProviderConfig for auth success handlers
Simplifies OCA, Cline, and OpenAI Codex auth success handlers in
AuthView to use the shared applyProviderConfig utility instead of
manually constructing provider config objects.

This removes duplicated logic around mode-specific provider keys
and model ID keys that applyProviderConfig already handles.
2026-02-03 12:39:41 -08:00
Max 28c548b3ee simplify package-npm script (#9067)
cli/package.json is already formatted correctly for publishing

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-03 12:36:47 -08:00
Bee 9b9035ea4a feat: add authentication support to oca provider in CLI (#9059)
* feat: add authentication support to oca provider in CLI

This change integrates the OcaAuthService into the AuthView component. It adds a new 'oca_auth' step to the authentication flow, allowing users to select 'oca' as a provider and initiate the authentication request via OcaAuthService.

* fix(cli): add subscription to OCA auth status updates

The OCA auth flow was missing the subscription mechanism to know when
browser auth completes. Without this, the CLI would spin indefinitely
after opening the browser.

Added a useEffect that subscribes to OcaAuthService.subscribeToAuthStatusUpdate
when in oca_auth step. When auth succeeds (user.uid present), saves the
provider config and transitions to success.

* fix(cli): add OCA auth support to SettingsPanelContent

AuthView only handles onboarding. Users also need to be able to switch
to OCA provider from the settings panel after initial setup.

Added:
- handleOcaLogin callback to start OAuth flow
- useEffect subscription to OCA auth status updates
- Case in handleProviderSelect for "oca" provider
- Escape key handling to cancel OCA auth
- UI for "Waiting for OCA sign-in..." state
- isWaitingForOcaAuth to input disabled check

* refactor(cli): extract OCA auth logic into useOcaAuth hook

Reduces code duplication between AuthView and SettingsPanelContent by
extracting the OCA auth subscription and state management into a
reusable hook.

The hook handles:
- Starting the OAuth flow (initialize + createAuthRequest)
- Subscribing to auth status updates
- Tracking waiting state
- Calling onSuccess callback when auth completes
- Exposing isAuthenticated for checking existing sessions

Both components now use the hook with their own onSuccess handlers
for component-specific state updates.

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-02-03 12:28:26 -08:00
Bee e4b39aeb22 fix: apply models cache retrieval across model refresh functions (#8976)
* fix: apply models cache retrieval across model refresh functions

This change introduces a unified caching mechanism for model information retrieved from various API providers (Groq, OpenRouter, Vercel). Each service now first checks if the data is available in the shared StateManager's cache before making an API request. This improves performance by leveraging cached results and reduces redundant network calls when refreshing models multiple times. The cache is stored in memory for quick access during subsequent calls within a single execution context.

Changes made:
1. Added import of `StateManager` to each relevant model refresh file.
2. Implemented initial cache check logic at the beginning of each function.
3. Updated error handling and logging consistency across services.
4. Added storage back into StateManager's cache after successful API retrieval for Groq, Vercel AI Gateway only (OpenRouter update already handled).

* promises

* add vercelModels

* feat: add 1-hour TTL to model cache

Adds a time-to-live mechanism to the model info cache so that:
- Duplicate fetches are still prevented within a reasonable window
- Users can get new models after 1 hour without restarting VS Code

Changes:
- Add MODEL_CACHE_TTL_MS constant (1 hour)
- Update cache structure to include timestamp alongside data
- Update setModelsCache to store timestamp with data
- Update getModelsCache to check TTL and invalidate expired cache
- Update getModelInfo to also respect TTL

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-02-03 12:18:21 -08:00
Max f7c54e964f cli version bump (#9064)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-03 11:42:46 -08:00
Bee d116ac5dcf feat: render markdown table in UI (#9056)
* feat: display markdown table in UI

Simplify the handlePartialBlock method in AttemptCompletionHandler by:
- Removing conditional logic for command vs no-command cases
- Always displaying partial result if present
- Deferring command handling to the final execution step
This fixes an issue where attempt completion response doesn't get streamed to the UI during partial result.

Also replaced react-remark with react-markdown and remark-gfm dependencies to MarkdownBlock in UI for enhanced markdown rendering support with GitHub Flavored Markdown features, including displaying table.

* add changeset

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

handlePartialBlock hard-codes the partial flag to true when calling uiHelpers.say(...). For consistency with other tool handlers and to avoid incorrect behavior if this method is ever invoked with a non-partial block, pass block.partial through instead.

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

---------

Co-authored-by: Robin Newhouse <robin@cline.bot>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-03 11:41:25 -08:00
Bee ac22d5d81a chore: add CLI type checking and caching to ci workflow (#9049)
* chore: add CLI type checking and caching to ci workflow

- Added a new cache step for CLI dependencies in the GitHub Actions test workflow to improve build performance.
- Included a step to install CLI dependencies using `npm ci`.
- Updated the `ci:check-all` script in `package.json` to include CLI type checking.
- Added a `cli:typecheck` script to handle type checking within the CLI directory.

* Fix type and import issues for cli

* Includes CI tests in test workflow

* use npx npm-run-all

* update ci:check-all

* ci: skip npm ci steps on cache hit in test workflow

Update the test workflow to conditionally run npm installation steps only when a cache hit is not found. This optimization reduces CI execution time by avoiding redundant dependency installations when the node_modules are already restored from cache.

* ci: update cache keys and add dependency verification in test workflow

Updated the cache keys for root, webview-ui, cli, and testing-platform dependencies by adding a version prefix (v1). This ensures a clean cache state and helps avoid potential corruption or mismatch issues.

Additionally, added a verification step in the test job to log cache hit status and check for the presence of key dependencies like biome and globby. This helps diagnose issues where the cache might be restored but dependencies are not correctly available for subsequent steps.

* update Verify and fix root dependencies

* fix type check script

* add isSettingsKey check

* update settingskey set

* apply feedback

* npx

* feat: flashing dot for streaming chat messages in CI (#9054)

Introduce an ink-spinner to the DotRow component to provide visual feedback when messages are being streamed. This improves the CLI user experience by clearly indicating that a tool call or message is currently in progress.

- Add `flashing` prop to `DotRow` component
- Replace static dot with `toggle8` spinner when `flashing` is true
- Update `ChatMessage` to pass `flashing` state based on `isStreaming` and `partial` message properties

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>

* ci: simplify dependency caching using built-in npm cache

Replace manual actions/cache steps with setup-node's built-in npm caching feature across all workflow jobs. This change:

- Removes redundant cache action steps for root, webview-ui, cli, and testing-platform dependencies
- Uses setup-node's native `cache: 'npm'` option with `cache-dependency-path` to handle multiple package-lock.json files
- Eliminates conditional installation steps based on cache hits
- Reduces workflow complexity and maintenance overhead while maintaining caching functionality

The built-in caching provides the same performance benefits with less configuration and better integration with the Node.js setup action.

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-02-04 03:34:14 +08:00
Juan Pablo Flores b57aefb5a1 Cli 2.0 docs (#9060)
* docs: restructure CLI reference to web-friendly format

Replace embedded man page format with structured markdown sections
for better readability. Simplify description, reorganize commands and
options into clear categories, and update Next Steps navigation cards.

* Add ACP editor integrations documentation (#9036)

* Add ACP editor integrations documentation with JetBrains and Neovim video demos

* Add Model Orchestration documentation with --config and --thinking flags

- Document --config and --thinking flags in CLI reference
- Create new model-orchestration.mdx sample page
- Add patterns for CI/CD review, task phase optimization, and multi-model consensus
- Link to production GitHub Actions workflow
- Update samples overview with new card
- Update docs navigation

* Add Worktree Workflows documentation with --cwd flag

- Document --cwd flag in CLI reference
- Create comprehensive worktree-workflows.mdx sample page
- Add patterns for parallel execution and cross-worktree piping
- Include real-world examples and best practices
- Add CLI section to features/worktrees.mdx for discoverability
- Update samples overview and navigation
- Cross-link between CLI and VS Code worktree docs

* Remove broken image references from worktrees documentation

- Remove worktrees-overview.png Frame (image not available)
- Remove worktrees-merge.png Frame (image not available)
- Documentation remains fully functional with comprehensive text explanations

* Remove accidentally committed local test file

- Delete src/test/verify-platformio-mcp.ts which was causing CI failures
- File contained TypeScript errors and hardcoded local paths
- Was meant for local testing only, should not have been committed

* Add native JetBrains plugin recommendation to ACP docs

- Add prominent Note recommending native JetBrains plugin
- Link directly to JetBrains installation section
- Position ACP setup as an alternative approach
- Keep all existing ACP content and video

* docs: refine CLI reference formatting and ACP title

Improve CLI reference readability with clearer headings and descriptions, and clarify the ACP editor integration page title for better discovery.docs: refine CLI reference formatting and ACP title

Improve CLI reference readability with clearer headings and descriptions, and clarify the ACP editor integration page title for better discovery.

* Fix CLI 2.0 syntax in model-orchestration.mdx

- Updated issue analysis pipeline to use shell variables for passing context
- Added explanatory note about why direct piping doesn't work
- Corrected example to complete each phase before starting the next
- All examples now use proper CLI 2.0 syntax

* Completely rewrite cli-reference.mdx with accurate CLI 2.0 information

- Removed all outdated CLI 1.0 content (instance management, Cline Core architecture, gRPC references)
- Added accurate CLI 2.0 commands: task, history, config, auth, update, version, dev
- Corrected all command flags and options based on actual man page
- Added proper examples for all commands
- Included environment variables documentation (CLINE_DIR, CLINE_COMMAND_PERMISSIONS)
- Added shell completion instructions
- Removed incorrect three-layer architecture description
- All content now matches cli/man/cline.1.md source of truth

Fixes outdated documentation issue mentioned in PR#9036

* Fix MDX syntax error in cli-reference.mdx

- Replace angle bracket URLs with proper markdown links
- MDX parser was interpreting <https://...> as invalid HTML tags
- Now uses [url](url) format which is proper MDX syntax

Fixes deployment validation error

---------

Co-authored-by: Renee Huang <renee@cline.bot>

* docs: enhance interactive mode documentation with structured settings overview

* docs: restructure and improve CLI reference documentation

- Reorganize command structure with clearer global options section
- Add mode behavior table explaining interactive vs plain text modes
- Improve option descriptions with consistent formatting
- Add horizontal rules between sections for better readability
- Document timeout option and environment variables more clearly
- Add Tips & Tricks section for common usage patterns
- Update frontmatter description to reflect content changes

* docs: improve ACP editor integrations page with editor descriptions

- Update page title to be more concise ("ACP: Editor Integrations")
- Remove redundant H1 header that duplicated the title
- Add introductory descriptions for JetBrains, Neovim, and Zed sections
- Rename "Zed Editor" section to just "Zed" for consistency

* docs: expand CLI reference with modes of operation and agent behavior

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

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

---------

Co-authored-by: Tony Loehr <turingxo@gmail.com>
Co-authored-by: Renee Huang <renee@cline.bot>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-03 11:29:15 -08:00
Max 11da3ee89e add windows to cli publish package json (#9063)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-03 11:24:07 -08:00
Bee e4e63912dd feat: add API key support for Cline provider (#9057)
* feat: add API key support for Cline provider

Add support for authenticating with Cline provider using an API key as an alternative to account-based authentication. This change allows users to configure Cline with either a direct API key or through the existing account authentication flow.

Changes:
- Add `clineApiKey` option to ClineHandler and pass through API configuration
- Update authentication check to accept either API key or account ID
- Modify provider configuration detection to check both auth methods
- Remove automatic Cline auth flow trigger on provider selection
- Add `clineApiKey` to provider-to-API-key mapping for proper key management

This provides more flexibility in authentication methods while maintaining backward compatibility with existing account-based authentication.

* promise all

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-02-03 10:56:04 -08:00
Tomás Barreiro f17d523b2e Fix OTEL endpoints (#9050)
* Fix OTEL endpoints

* refactor
2026-02-03 19:24:01 +01:00
Max edbba8b7f6 return empty mcp config if cline_mcp_settings.json doesn't exist or is empty file (#9061)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-02-03 10:12:52 -08:00
999 changed files with 75303 additions and 43749 deletions
@@ -1,6 +1,6 @@
---
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.
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, PR template usage, and PR creation using the gh CLI tool.
---
# Create Pull Request
@@ -147,14 +147,29 @@ When filling out the template:
### Create PR with gh CLI
**Use a temporary file for the PR body** to avoid shell escaping issues, newline problems, and other command-line flakiness:
1. Write the PR body to a temporary file:
```
/tmp/pr-body.md
```
2. Create the PR using the file:
```bash
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main
```
3. Clean up the temporary file:
```bash
rm /tmp/pr-body.md
```
For draft PRs:
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main --draft
```
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
```
**Why use a file?** Passing complex markdown with newlines, special characters, and checkboxes directly via `--body` is error-prone. The `--body-file` flag handles all content reliably.
## Post-Creation
-8
View File
@@ -1,8 +0,0 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
-11
View File
@@ -1,11 +0,0 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.0.5/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix decimal input crash in OpenAI Compatible price fields (#8129)
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
fix: build complete handlers when upadting the api config
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Updating script documentation and removing unnecessary continue on error
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixed missing provider from list
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
feat(skills): Make skills always enabled and remove feature toggle setting
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixed Favorite Icon / Star from getting clipped in the task history view
-26
View File
@@ -1,26 +0,0 @@
changesDir: .changes
unreleasedDir: unreleased
headerPath: header.tpl.md
changelogPath: CHANGELOG.md
versionExt: md
versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
kindFormat: "### {{.Kind}}"
changeFormat: "* {{.Body}}"
kinds:
- label: Added
auto: minor
- label: Changed
auto: major
- label: Deprecated
auto: minor
- label: Removed
auto: major
- label: Fixed
auto: patch
- label: Security
auto: patch
newlines:
afterChangelogHeader: 1
beforeChangelogVersion: 1
endOfVersion: 1
envPrefix: CHANGIE_
+12 -1
View File
@@ -14,7 +14,7 @@ This file is the secret sauce for working effectively in this codebase. It captu
## 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 creating PRs, contributors should not create changelog-entry files. Maintainers handle release versioning and changelog curation during the release process.
- 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
@@ -147,6 +147,17 @@ Required steps:
Common mistake: Adding only the return value without the `context.globalState.get()` call. This compiles but the value is always `undefined` on load.
Settings plumbing gotcha: if a key is user-toggleable from settings, wire both controller update paths:
- `src/core/controller/state/updateSettings.ts` for webview `updateSetting(...)`
- `src/core/controller/state/updateSettingsCli.ts` for CLI/ACP settings updates
Missing one path causes a toggle to appear to change in one surface while the backend state stays unchanged.
Webview toggle gotcha: settings changes must also round-trip back in state payloads.
- Add the field to `UpdateSettingsRequest` in `proto/cline/state.proto` (for webview update requests), then run `npm run protos`
- Include the key in `Controller.getStateToPostToWebview()` (`src/core/controller/index.ts`)
- Ensure `ExtensionState` and webview defaults include the key (`src/shared/ExtensionMessage.ts`, `webview-ui/src/context/ExtensionStateContext.tsx`)
If this round-trip wiring is missing, the backend value can update but the toggle in webview appears stuck or reverts.
## 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()`.
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "PostToolUse running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "PostToolUse response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "PostToolUse hook custom errorMessage"
}
EOF
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "PreToolUse running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "PreToolUse response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "PreToolUse hook custom errorMessage"
}
EOF
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "TaskCancel running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "TaskCancel response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "TaskCancel hook custom errorMessage"
}
EOF
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "TaskResume running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "TaskResume response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "TaskResume hook custom errorMessage"
}
EOF
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "TaskStart running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "TaskStart response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "TaskStart hook custom errorMessage"
}
EOF
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
echo "UserPromptSubmit running inside local cline/.clinerules/hooks/ directory"
input=$(cat)
echo $input | jq .
for i in {1..5}; do
sleep 1
echo "$i"
done
cat <<EOF
{
"cancel": false,
"contextModification": "UserPromptSubmit response from the local cline/.clinerules/hooks/ directory.",
"errorMessage": "UserPromptSubmit hook custom errorMessage"
}
EOF
+64
View File
@@ -0,0 +1,64 @@
# Storage Architecture
Global settings, secrets and workspace state are stored in **file-backed JSON stores** under `~/.cline/data/`. This is the shared storage layer used by VSCode, CLI, and JetBrains.
## Key Abstractions
### `StorageContext` (src/shared/storage/storage-context.ts)
The entry point. Created via `createStorageContext()` and passed to `StateManager.initialize()`. Contains three `ClineFileStorage` instances:
- `globalState``~/.cline/data/globalState.json`
- `secrets``~/.cline/data/secrets.json` (mode 0o600)
- `workspaceState``~/.cline/data/workspaces/<hash>/workspaceState.json`
### `ClineFileStorage` (src/shared/storage/ClineFileStorage.ts)
Synchronous JSON key-value store backed by a single file. Supports `get()`, `set()`, `setBatch()`, `delete()`. Writes are atomic (write-then-rename).
### `StateManager` (src/core/storage/StateManager.ts)
In-memory cache on top of `StorageContext`. All runtime reads hit the cache; writes update cache immediately and debounce-flush to disk.
## ⚠️ Do NOT Use VSCode's ExtensionContext for Storage
**Do not** read from or write to `context.globalState`, `context.workspaceState`, or `context.secrets` for persistent data. These are VSCode-specific and not available on CLI or JetBrains.
Instead, use:
```typescript
// Reading state
StateManager.get().getGlobalStateKey("myKey")
StateManager.get().getSecretKey("mySecretKey")
StateManager.get().getWorkspaceStateKey("myWsKey")
// Writing state
StateManager.get().setGlobalState("myKey", value)
StateManager.get().setSecret("mySecretKey", value)
StateManager.get().setWorkspaceState("myWsKey", value)
```
Remember that your data may be read by a different client than the one that wrote it. For example, a value written by Cline in JetBrains may be read by Cline CLI.
## VSCode Migration (src/hosts/vscode/vscode-to-file-migration.ts)
On VSCode startup, a migration copies data from VSCode's `ExtensionContext` storage into the file-backed stores. This runs in `src/common.ts` before `StateManager.initialize()`.
- **Sentinel**: `__vscodeMigrationVersion` key in global state and workspace state — prevents re-migration.
- **Merge strategy**: File store wins. Existing values are never overwritten.
- **Safe downgrade**: VSCode storage is NOT cleared, so older extension versions still work.
## Adding New Storage Keys
1. Add to `src/shared/storage/state-keys.ts` (see existing patterns)
2. Read/write via `StateManager` (NOT via `context.globalState`)
3. If adding a secret, add to `SecretKeys` array in `state-keys.ts`
## File Layout
```
~/.cline/
data/
globalState.json # Global settings & state
secrets.json # API keys (mode 0o600)
tasks/
taskHistory.json # Task history (separate file)
workspaces/
<hash>/
workspaceState.json # Per-workspace toggles
```
+1 -1
View File
@@ -19,7 +19,7 @@ Review and address all comments on the current branch's PR.
- 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.).
4. Present a summary of all comments with your recommendation for each (apply, skip, or respond). Ignore bot noise (release automation, CI status, etc.).
5. **Wait for my approval** before proceeding.
-549
View File
@@ -1,549 +0,0 @@
The goal of this workflow is to take a changeset for a release of Cline, an autonomous coding agent extension that plugs right into your IDE, and write the updated announcement component, and the updated changelog.
For reference, here are some examples of how we converted previous changesets to announcement components / changelogs.
- 3.14
<changeset>
This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or setup this action to publish automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.
Releases
claude-dev@3.14.0
Minor Changes
77c9863: create clinerules folder if its currently a file and creating new rule
0ffb7dd: disabling shift hint for now & improving tooltip behavior
79b76fd: Add support for custom model ID in AWS Bedrock provider, enabling use of Application Inference Profile.
eb6e481: Full support for LaTeX rendering
df37f29: Add support for custom API request timeout. Previously, timeouts were hardcoded to 30 seconds for providers like Ollama or 15 seconds for OpenRouter and Cline. Now users can set a custom timeout value in milliseconds through the settings interface.
e4d26be: allow cursorrules and windsurfrules
c5de50f: Fix Handle @withRetry() SyntaxError when running extension locally issue
61d2f42: enabled pricing calculation for gemini and vertex + more robust caching & cache tracking for gemini & vertex
aed152b: add truncation notice when truncating manually
2fe2405: Migrate Cline Tools Section to new docs
19cc8bc: Add a timeout setting for the terminal connection, allowing users to adjust this if they are having timeout issues
03d4410: Added copy button to code blocks.
c78fe23: addressed race condition in terminal command usage
91e222f: add checkpoints after more messages
14230e7: add newrule slash command
1c7d33a: Add remote config with posthog allowing for disabling new features until they're reading, making for a better developer experience.
4196c14: add cache ui for open router and cline provider
d97424f: showing expanded task by default
5294e78: Refactor to not pass a message for showing the MCP View from the servers modal
70cc437: Fix Windows path issue: Correct handling of import.meta.url to avoid leading slash in pathname
4b697d8: Migrate the addRemoteServer to protobus
Patch Changes
c63d9a1: updated drag and drop text to say "drop" instead of "drag"
459adf0: Add markdown copy to chat
74ec823: Minor UX improvement to drag and drop ux
b0961f4: Remove linear pull request action
e9ce384: searchCommits protobus migration
5802b68: createRuleFile protobus migration
df7f9fc: Add dependsOn to more blocks in the tasks.json
41ae732: Fix for git commit mentions in repos with no git commits
7e78445: Adding args to allow Cursor to open workspaces (for checkpoint testing/development)
bdfda6f: feat(bedrock): Introduce Amazon Nova Premier
65243ad: Introduce UI library for future UI development
4565e06: checkIsImageURL migrated to protobus
5a8e9d8: protobus migration for openImage
deeda6e: Lowering Gemini cache TTL time
db0b022: Adding UI to show openrouter balance next to provider
4650ffa: deleteRuleFile protobus migration
d4bd755: fix cost calculation
</changeset>
<changelog>
## [3.14.0]
- Add UI to show openrouter balance next to provider
- Add support for custom model ID in AWS Bedrock provider, enabling use of Application Inference Profile (Thanks @clicube!)
- Add more robust caching & cache tracking for gemini & vertex providers
- Add support for LaTeX rendering
- Add support for custom API request timeout. Timeouts were 15-30s, but can now be configured via settings for OpenRouter/Cline & Ollama (Thanks @WingsDrafterwork!)
- Add truncation notice when truncating manually
- Add a timeout setting for the terminal connection, allowing users to set a time to wait for terminal startup
- Add copy button to code blocks
- Add copy button to markdown blocks (Thanks @weshoke!)
- Add checkpoints to more messages
- Add slash command to create a new rules file (/newrule)
- Add cache ui for open router and cline provider
- Add Amazon Nova Premier model to Bedrock (Thanks @watany!)
- Add support for cursorrules and windsurfrules
- Add support for batch history deletion (Thanks @danix800!)
- Improve Drag & Drop experience
- Create clinerules folder creating new rule if it's needed
- Enable pricing calculation for gemini and vertex providers
- Refactor message handling to not show the MCP View of the server modal
- Migrate the addRemoteServer to protobus (Thanks @DaveFres!)
- Update task header to be expanded by default
- Update Gemini cache TTL time to 15 minutes
- Fix race condition in terminal command usage
- Fix to correctly handle `import.meta.url`, avoiding leading slash in pathname for Windows (Thanks @DaveFres!)
- Fix @withRetry() decoration syntax error when running extension locally (Thanks @DaveFres!)
- Fix for git commit mentions in repos with no git commits
- Fix cost calculation (Thanks @BarreiroT!)
</changelog>
<announcement-component>
const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => {
const minorVersion = version.split(".").slice(0, 2).join(".") // 2.0.0 -> 2.0
return (
<div style={containerStyle}>
<VSCodeButton appearance="icon" onClick={hideAnnouncement} style={closeIconStyle}>
<span className="codicon codicon-close"></span>
</VSCodeButton>
<h3 style={h3TitleStyle}>
🎉{" "}New in v{minorVersion}
</h3>
<ul style={ulStyle}>
<li>
<b>Gemini prompt caching:</b> Gemini and Vertex providers now support prompt caching and price tracking for
Gemini models.
</li>
<li>
<b>Copy Buttons:</b> Buttons were added to Markdown and Code blocks that allow you to copy their contents
easily.
</li>
<li>
<b>/newrule command:</b> New slash command to have cline write your .clinerules for you based on your
workflow.
</li>
<li>
<b>Drag and drop improvements:</b> Don't forget to hold shift while dragging files!
</li>
<li>Added more checkpoints across the task, allowing you to restore from more than just file changes.</li>
<li>Added support for rendering LaTeX in message responses. (Try asking Cline to show the quadratic formula)</li>
</ul>
<Accordion isCompact className="pl-0">
<AccordionItem
key="1"
aria-label="Previous Updates"
title="Previous Updates:"
classNames={{
trigger: "bg-transparent border-0 pl-0 pb-0 w-fit",
title: "font-bold text-(--vscode-foreground)",
indicator:
"text-(--vscode-foreground) mb-0.5 -rotate-180 data-[open=true]:-rotate-90 rtl:rotate-0 rtl:data-[open=true]:-rotate-90",
}}>
<ul style={ulStyle}>
<li>
<b>Global Cline Rules:</b> store multiple rules files in Documents/Cline/Rules to share between
projects.
</li>
<li>
<b>Cline Rules Popup:</b> New button in the chat area to view workspace and global cline rules files
to plug and play specific rules for the task
</li>
<li>
<b>Slash Commands:</b> Type <code>/</code> in chat to see the list of quick actions, like starting a
new task (more coming soon!)
</li>
<li>
<b>Edit Messages:</b> You can now edit a message you sent previously by clicking on it. Optionally
restore your project when the message was sent!
</li>
</ul>
</AccordionItem>
</Accordion>
{/*
// Leave this here for an example of how to structure the announcement
<ul style={{ margin: "0 0 8px", paddingLeft: "12px" }}>
<li>
OpenRouter now supports prompt caching! They also have much higher rate limits than other providers,
so I recommend trying them out.
<br />
{!apiConfiguration?.openRouterApiKey && (
<VSCodeButtonLink
href={getOpenRouterAuthUrl(vscodeUriScheme)}
style={{
transform: "scale(0.85)",
transformOrigin: "left center",
margin: "4px -30px 2px 0",
}}>
Get OpenRouter API Key
</VSCodeButtonLink>
)}
{apiConfiguration?.openRouterApiKey && apiConfiguration?.apiProvider !== "openrouter" && (
<VSCodeButton
onClick={() => {
vscode.postMessage({
type: "apiConfiguration",
apiConfiguration: { ...apiConfiguration, apiProvider: "openrouter" },
})
}}
style={{
transform: "scale(0.85)",
transformOrigin: "left center",
margin: "4px -30px 2px 0",
}}>
Switch to OpenRouter
</VSCodeButton>
)}
</li>
<li>
<b>Edit Cline's changes before accepting!</b> When he creates or edits a file, you can modify his
changes directly in the right side of the diff view (+ hover over the 'Revert Block' arrow button in
the center to undo "<code>{"// rest of code here"}</code>" shenanigans)
</li>
<li>
New <code>search_files</code> tool that lets Cline perform regex searches in your project, letting
him refactor code, address TODOs and FIXMEs, remove dead code, and more!
</li>
<li>
When Cline runs commands, you can now type directly in the terminal (+ support for Python
environments)
</li>
</ul>*/}
<div style={hrStyle} />
<p style={linkContainerStyle}>
Join us on{" "}
<VSCodeLink style={linkStyle} href="https://x.com/cline">
X,
</VSCodeLink>{" "}
<VSCodeLink style={linkStyle} href="https://discord.gg/cline">
discord,
</VSCodeLink>{" "}
or{" "}
<VSCodeLink style={linkStyle} href="https://www.reddit.com/r/cline/">
r/cline
</VSCodeLink>
for more updates!
</p>
</div>
)
}
</announcement-component>
- 3.13
<changeset>
Minor Changes
2964388: Added copy button to MermaidBlock component
75143a7: Add the ability to fetch from global cline rules files
Patch Changes
a0252e7: convert inline style to tailwind css of file SettingsView.tsx
ab59bd9: Add stream options back to xai provider
7276f50: Icons to indicate an action is occuring outside of the users workspace
0b19ba6: update to NEW model
</changeset>
<changelog>
## [3.13.0]
- Add Cline rules popover under the chat field, allowing you to easily add, enable & disable workspace level or global rule files
- Add new slash command menu letting you type “/“ to do quick actions like creating new tasks
- Add ability to edit past messages, with options to restore your workspace back to that point
- Allow sending a message when selecting an option provided by the question or plan tool
- Add command to jump to Cline's chat input
- Add support for OpenAI o3 & 4o-mini (Thanks @PeterDaveHello and @arafatkatze!)
- Add baseURL option for Google Gemini provider (Thanks @owengo and @olivierhub!)
- Add support for Azure's DeepSeek model. (Thanks @yt3trees!)
- Add ability for models that support it to receive image responses from MCP servers (Thanks @rikaaa0928!)
- Improve search and replace diff editing by making it more flexible with models that fail to follow structured output instructions. (Thanks @chi-cat!)
- Add detection of Ctrl+C termination in terminal, improving output reading issues
- Fix issue where some commands with large output would cause UI to freeze
- Fix token usage tracking issues with vertex provider (Thanks @mzsima!)
- Fix issue with xAI reasoning content not being parsed (Thanks @mrubens!)
</changelog>
<announcement-component>
const Announcement = ({ version, hideAnnouncement }: AnnouncementProps) => {
const minorVersion = version.split(".").slice(0, 2).join(".") // 2.0.0 -> 2.0
return (
<div style={containerStyle}>
<VSCodeButton appearance="icon" onClick={hideAnnouncement} style={closeIconStyle}>
<span className="codicon codicon-close"></span>
</VSCodeButton>
<h3 style={h3TitleStyle}>
🎉{" "}New in v{minorVersion}
</h3>
<ul style={ulStyle}>
<li>
<b>Global Cline Rules:</b> store multiple rules files in Documents/Cline/Rules to share between projects.
</li>
<li>
<b>Cline Rules Popup:</b> New button in the chat area to view workspace and global cline rules files to plug
and play specific rules for the task
</li>
<li>
<b>Slash Commands:</b> Type <code>/</code> in chat to see the list of quick actions, like starting a new task
(more coming soon!)
</li>
<li>
<b>Edit Messages:</b> You can now edit a message you sent previously by clicking on it. Optionally restore
your project when the message was sent!
</li>
</ul>
<h4 style={{ margin: "5px 0 5px" }}>Previous Updates:</h4>
<ul style={ulStyle}>
<li>
<b>Model Favorites:</b> You can now mark your favorite models when using Cline & OpenRouter providers for
quick access!
</li>
<li>
<b>Faster Diff Editing:</b> Improved animation performance for large files, plus a new indicator in chat
showing the number of edits Cline makes.
</li>
<li>
<b>New Auto-Approve Options:</b> Turn off Cline's ability to read and edit files outside your workspace.
</li>
</ul>
{/*
// Leave this here for an example of how to structure the announcement
<ul style={{ margin: "0 0 8px", paddingLeft: "12px" }}>
<li>
OpenRouter now supports prompt caching! They also have much higher rate limits than other providers,
so I recommend trying them out.
<br />
{!apiConfiguration?.openRouterApiKey && (
<VSCodeButtonLink
href={getOpenRouterAuthUrl(vscodeUriScheme)}
style={{
transform: "scale(0.85)",
transformOrigin: "left center",
margin: "4px -30px 2px 0",
}}>
Get OpenRouter API Key
</VSCodeButtonLink>
)}
{apiConfiguration?.openRouterApiKey && apiConfiguration?.apiProvider !== "openrouter" && (
<VSCodeButton
onClick={() => {
vscode.postMessage({
type: "apiConfiguration",
apiConfiguration: { ...apiConfiguration, apiProvider: "openrouter" },
})
}}
style={{
transform: "scale(0.85)",
transformOrigin: "left center",
margin: "4px -30px 2px 0",
}}>
Switch to OpenRouter
</VSCodeButton>
)}
</li>
<li>
<b>Edit Cline's changes before accepting!</b> When he creates or edits a file, you can modify his
changes directly in the right side of the diff view (+ hover over the 'Revert Block' arrow button in
the center to undo "<code>{"// rest of code here"}</code>" shenanigans)
</li>
<li>
New <code>search_files</code> tool that lets Cline perform regex searches in your project, letting
him refactor code, address TODOs and FIXMEs, remove dead code, and more!
</li>
<li>
When Cline runs commands, you can now type directly in the terminal (+ support for Python
environments)
</li>
</ul>*/}
<div style={hrStyle} />
<p style={linkContainerStyle}>
Join us on{" "}
<VSCodeLink style={linkStyle} href="https://x.com/cline">
X,
</VSCodeLink>{" "}
<VSCodeLink style={linkStyle} href="https://discord.gg/cline">
discord,
</VSCodeLink>{" "}
or{" "}
<VSCodeLink style={linkStyle} href="https://www.reddit.com/r/cline/">
r/cline
</VSCodeLink>
for more updates!
</p>
</div>
)
}
</announcement-component>
We have a changeset PR that automatically generated as new unreleased PRs are merged into main, the PR is always called "Changeset version bump" and the author is github-actions.
The Changeset PR description looks something like this:
<changeset-pr-description>
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.
# Releases
## claude-dev@3.16.0
### Minor Changes
- c6e8b04: Recent task list is now collapsible, allowing users to hide their recent tasks (e.g. when sharing their screen).
- aabe4ae: Add detection for new users to display special components
- 6c18d51: adds global endpoint for vertex ai users
- 080ed7c: Add Tailwind CSS IntelliSense to the the recommended extensions list
- 5147e28: new workflow feature
### Patch Changes
- c0b3c69: fix eternal loading states when the last message is a checkpoint
- 570ece3: selectImages protos migration
- 8d8452e: askResponse protobus migration
- cd1ff2a: Finishing the migration of Vscode Advanced settings to Settings Webview
</changeset-pr-description>
The changeset pr is ALWAYS on the following branch: `changeset-release/main`.
I have the `gh` command line tool set up and authenticated, so you have everything you need.
The first step is to get the full diff from the changeset PR to look at the changes that were automatically made to the `CHANGELOG.md` file. By default it will automatically add a new section to the changelog.md file with the new version. The problem with the automatically generated section is that it just takes the text that the developers threw into their changeset files for each corresponding PR, and they can be pretty vague and bad. Additionally there's some stuff that is totally irrelevant for the end user, like minor refactoring changes. So I manually typically go in and update this section to be a proper changelog that will show up in our patchnotes. You can look at how the rest of the file is done because those are all good examples of us updating this to use good language for the end user. We usually put new features up top (and the most exciting flagship features at the very top), and then bug fixes/improvements at the bottom. Having some basic organization to the ordering of the bullet points by content is nice. But use common sense.
To handle this process effectively, do the following:
For each of the automatically generated bullet points in the Changelog.md, you should
1. Take the commit hash at the start of the bullet point, and use the `gh` command line tool find the PR that it was associated with.
2. Use the `gh` command to get the PR title/description/discussion to understand the context surrounding the PR.
3. Use the `gh` command line tool to get the full PR diff to fully understand the changes made in the code.
4. Synthesize that knowledge to determine (a) whether or not this change is relevant to end users and (b) what the text & ordering of the line should be.
5. Update the `CHANGELOG.md` accordingly
Do this for every single item in the list from the autogenerated bullet points. We want to be diligent and have a full understanding of every feature so we can make the best changelog ever!
Here are some principles for good changelogs from keepchangelog.com, a handy guide:
<keepachangelog-pinciples-for-good-changelogs>
### Guiding Principles
- Changelogs are for humans, not machines.
- There should be an entry for every single version.
- The same types of changes should be grouped.
- The latest version comes first.
### Bullet points in the changelog should follow these principles:
- Types of changes
- Added for new features.
- Changed for changes in existing functionality.
- Deprecated for soon-to-be removed features.
- Removed for now removed features.
- Fixed for any bug fixes.
- Security in case of vulnerabilities.
</keepachangelog-pinciples-for-good-changelogs>
Lastly, when developers make a PR, they typically make a changeset. And they have 3 options when making the changeset:
1. Patch
2. Minor
3. Major
Sometimes they label something as minor when really it should just be a patch. Or vice versa. Because of this, the automatic version bump may be incorrect. So when starting out this workflow, you should use the <ask_followup_question> tool to confirm with me whether or not this should be a patch bump (show the old version number and what the proposed new version number would be) or a minor bump. Part of the release process is making sure the version in package.json that is automatically changed actually corresponds with what we decided the bump should actually be based on the features. ALL these modifications happen in the `changeset-release/main` branch btw.
<important_note>
Before doing any of this, make sure you check out the `changeset-release/main` and pull the most recent up to date changes. Then perform all this work in that branch.
New announcement banners should ONLY be made for minor version bumps or higher. That's another reason why double checking if the changelog warrants the bump is important.
Also, SUPER important: For any external contributors that aren't part of the cline github organization, we always want to add a (Thanks @username!) at the end of the changelog to attribute them properly. We're an open source project and it's ethical to do this.
</important_note>
Once the changelog looks good, and the version number looks good, we gotta double check that the version number in the changelog has the brackets around it. And as a final step, double check the package.json version number matches the latest number in the changelog. And as the ultimate final step we run `npm run install:all` to make sure the package version number permiates through the lock file.
<detailed_sequence_of_steps>
# Cline Release Process - Detailed Sequence of Steps
## Before Starting
1. First, examine the changeset PR without checking it out:
```bash
gh pr view changeset-release/main
```
2. View the PR diff to see the auto-generated CHANGELOG.md changes:
```bash
gh pr diff changeset-release/main > changeset-diff.txt
cat changeset-diff.txt | grep -A 50 "CHANGELOG.md"
```
## Initial Setup
3. Once you're ready to start, checkout and update the changeset release branch:
```bash
git checkout changeset-release/main
git pull origin changeset-release/main
```
## Analyzing Each Change
4. For each commit hash in the auto-generated changelog entries:
a. Find the PR number associated with a commit hash:
```bash
gh pr list --search "<commit-hash>" --state merged
```
b. Get PR details for better context:
```bash
gh pr view <PR-number>
```
c. Check if the contributor is external to determine if attribution is needed:
```bash
# Extract username from PR
USERNAME=$(gh pr view <PR-number> --json author --jq .author.login)
# Check if user is a member of the Cline organization
# this command is a bit finnicky, but it 100% works.
# if you see a `Error executing command: The command ran successfully, but we couldn't capture its output. Please proceed accordingly.` error, just retry it until you actually get the output
# don't make any assumptions, just retry the command to actually get the output and determine if they're external or not.
# no output means they are an external contributor, otherwise if there is output they are an internal contributor (part of our github org)
gh api "orgs/cline/members" --jq "map(.login)" | grep -i "pashpashpash"
```
d. View the full PR diff to understand code changes:
```bash
gh pr diff <PR-number> > pr-diff-<PR-number>.txt
cat pr-diff-<PR-number>.txt
```
## Updating the Changelog
5. Based on PR analysis, update the CHANGELOG.md with user-friendly descriptions:
- Use the `<replace_in_file>` tool to edit the CHANGELOG.md file
- Group by feature type (Added, Changed, Fixed)
- Put most exciting features at the top
- Move bug fixes and small improvements to the bottom
- Use clear, end-user focused language
- For external contributors, add attribution at the end of the relevant entry: `(Thanks @username!)`
## Version Number Verification
6. Confirm the version bump is appropriate:
- Check package.json to verify the auto-generated version number:
```bash
cat package.json | grep "\"version\""
```
- If the feature set doesn't warrant a minor bump, use the `<replace_in_file>` tool to modify package.json
7. Ensure the version in CHANGELOG.md has brackets around it:
```
## [3.16.0]
```
## Creating the Announcement (for minor/major versions only)
8. If this is a minor version bump, create/update the announcement component:
- Use the `<replace_in_file>` tool to edit the src/views/components/announcement.tsx file
- Update the highlights based on key features
- Move previous version highlights to the "Previous Updates" section
- Use the previous announcement components as reference for structure
## Finalizing the Release
9. Update dependencies with the new version number:
```bash
npm run install:all
```
10. Commit your changes:
```bash
git add CHANGELOG.md package.json package-lock.json src/views/components/announcement.tsx
git commit -m "Update CHANGELOG.md and announcement for version 3.16.0"
```
11. Push your changes to the changeset branch:
```bash
git push origin changeset-release/main
```
12. Check that your changes pushed successfully:
```bash
git status
```
</detailed_sequence_of_steps>
+3 -10
View File
@@ -89,16 +89,9 @@ On the main branch, create a commit that updates:
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.
3. No changelog-entry file cleanup is needed. Contributors do not create changelog-entry files in this repo.
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.
**Skip running `npm run install:all`** - release automation handles lockfile consistency as needed.
Commit with message format: `v{VERSION} Release Notes (hotfix)`
@@ -107,7 +100,7 @@ In the commit body, mention:
- List the cherry-picked commits that will be included
```bash
git add CHANGELOG.md package.json .changeset/
git add CHANGELOG.md package.json
git commit -m "v3.40.1 Release Notes (hotfix)
Hotfix release including:
-2
View File
@@ -347,8 +347,6 @@ A few notes:
So until the settings page is update, and this is added to settings in a way that's clean and doesn't confuse new users, I don't think we can merge this. Please bear with us.
</request_changes_comment>
<request_changes_comment>
Also, don't forget to add a changeset since this fixes a user-facing bug.
The architectural change is solid - moving the focus logic to the command handlers makes sense. Just don't want to introduce subtle timing issues by removing those timeouts.
</request_changes_comment>
</example_comments_that_i_have_written_before>
+40 -208
View File
@@ -1,232 +1,64 @@
# Release
Prepare and publish a release from the open changeset PR.
Prepare and publish a release directly from `main`.
## 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
1. Select/confirm the target version
2. Curate `CHANGELOG.md` entries manually for end users
3. Ensure `package.json` version matches the changelog
4. Create and push a release commit + tag
5. Trigger publish workflow
6. Update GitHub release notes and share a summary
## Step 1: Find the Changeset PR
## Process
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:
### 1) Sync and determine version
```bash
git checkout main
git pull origin main
cat package.json | grep '"version"'
```
**IMPORTANT: Verify the latest commit is the release commit before tagging:**
Confirm the release version with the maintainer (patch/minor/major).
### 2) Curate changelog and version
- Edit `CHANGELOG.md` for the target version using human-friendly release notes.
- Ensure version headers use bracket format, e.g. `## [3.66.1]`.
- Update `package.json` version to the same value.
### 3) Commit and tag
```bash
git log -1 --oneline
git add CHANGELOG.md package.json package-lock.json
git commit -m "v<version> Release Notes"
git push origin main
git tag v<version>
git push origin v<version>
```
Confirm the commit message matches `v{VERSION} Release Notes` (e.g., `v3.44.1 Release Notes`). Do NOT blindly tag HEAD without verification.
### 4) Trigger publish workflow
Once verified, tag and push:
Tell the maintainer to run:
https://github.com/cline/cline/actions/workflows/publish.yml
Use `v<version>` as the release tag.
### 5) Update GitHub release notes
After publish completes:
```bash
VERSION=<version>
git tag v${VERSION}
git push origin v${VERSION}
gh release view v<version> --json body --jq '.body'
gh release edit v<version> --notes "<final curated release notes>"
```
## Step 8: Trigger Publish Workflow
### 6) Final summary
**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
Provide:
- Released version/tag
- Link to release page
- Summary of top end-user changes
+49
View File
@@ -0,0 +1,49 @@
# THIS IS AUTOGENERATED. DO NOT EDIT MANUALLY
version = 1
name = "cline"
[setup]
script = '''
if [ ! -d "node_modules" ]; then
MAIN_WORKTREE="$(git worktree list | head -n1 | awk '{print $1}')"
ln -s "$MAIN_WORKTREE/node_modules" node_modules
ln -s "$MAIN_WORKTREE/webview-ui/node_modules" webview-ui/node_modules
fi
'''
[[actions]]
name = "VS Code"
icon = "run"
command = "chmod +x ./scripts/run-extension-host.sh && ./scripts/run-extension-host.sh production"
[[actions]]
name = "CLI"
icon = "run"
command = '''
npm run cli:build
npm run cli:run
'''
[[actions]]
name = "npm install"
icon = "tool"
command = '''
rm node_modules
rm webview-ui/node_modules
npm run install:all
'''
[[actions]]
name = "pull main"
icon = "tool"
command = '''
git fetch origin main
if ! git merge-base --is-ancestor main origin/main; then
echo "Local main has commits not on origin/main. Aborting..."
exit 1
fi
git update-ref refs/heads/main refs/remotes/origin/main
echo "main updated to $(git rev-parse --short main)"
'''
+1
View File
@@ -1,4 +1,5 @@
demo.gif filter=lfs diff=lfs merge=lfs -text
assets/docs/demo.gif filter=lfs diff=lfs merge=lfs -text
webview-ui/src/assets/cline_kanban_demo.webm filter=lfs diff=lfs merge=lfs -text
* text=auto eol=lf
+2 -3
View File
@@ -1,3 +1,2 @@
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
/.github/ @saoudrizwan @arafatkatze @maxpaulus43 @candieduniverse
/README.md @saoudrizwan @juanpflores
+58
View File
@@ -0,0 +1,58 @@
# Copilot Instructions for Cline
This is a VS Code extension. Read `.clinerules/general.md` for tribal knowledge and nuanced patterns.
## Architecture
- **Core** (`src/`): `extension.ts``WebviewProvider``Controller` (single source of truth) → `Task` (agent loop).
- **Webview** (`webview-ui/`): React/Vite app. State via `ExtensionStateContext.tsx`, synced through message passing.
- **CLI** (`cli/`): React Ink terminal UI sharing core logic. Update CLI when changing webview features.
- **Communication**: Protobuf-defined gRPC-like protocol over VS Code message passing. Schemas in `proto/`.
- **MCP**: `src/services/mcp/McpHub.ts`.
## Build & Test (Critical — non-obvious commands)
- **Build**: `npm run compile` — NOT `npm run build`.
- **Watch**: `npm run watch` (extension + webview).
- **Protos**: `npm run protos` — run **immediately** after any `.proto` change. Generates into `src/shared/proto/`, `src/generated/`.
- **Tests**: `npm run test:unit`. After prompt/tool changes: `UPDATE_SNAPSHOTS=true npm run test:unit`.
## Protobuf RPC Workflow (4 steps)
1. **Define** in `proto/cline/*.proto`. Naming: `PascalCaseService`, `camelCase` RPCs, `PascalCase` Messages. Use `common.proto` shared types for simple data.
2. **Generate**: `npm run protos`.
3. **Backend handler**: `src/core/controller/<domain>/`.
4. **Frontend call**: `UiServiceClient.myMethod(Request.create({...}))`.
- Adding enums (e.g. `ClineSay`) → also update `src/shared/proto-conversions/cline-message.ts`.
## Adding API Providers (silent failure risk)
Three proto conversion updates are **required** or the provider silently resets to Anthropic:
1. `proto/cline/models.proto` — add to `ApiProvider` enum.
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts`.
3. `convertProtoToApiProvider()` in the same file.
Also update: `src/shared/api.ts`, `src/shared/providers/providers.json`, `src/core/api/index.ts`, `webview-ui/.../providerUtils.ts`, `webview-ui/.../validate.ts`, `webview-ui/.../ApiOptions.tsx`, and `cli/src/components/ModelPicker.tsx`.
For Responses API providers: add to `isNextGenModelProvider()` in `src/utils/model-utils.ts` and set `apiFormat: ApiFormat.OPENAI_RESPONSES` on models.
## Adding Tools to System Prompt (5+ file chain)
1. Add enum to `ClineDefaultTool` in `src/shared/tools.ts`.
2. Create definition in `src/core/prompts/system-prompt/tools/` (export `[GENERIC]` minimum).
3. Register in `src/core/prompts/system-prompt/tools/init.ts`.
4. Whitelist in `src/core/prompts/system-prompt/variants/*/config.ts` for each model family.
5. Handler in `src/core/task/tools/handlers/`, wire in `ToolExecutor.ts`.
6. If tool has UI: add `ClineSay` enum in proto → `ExtensionMessage.ts``cline-message.ts``ChatRow.tsx`.
7. Regenerate snapshots: `UPDATE_SNAPSHOTS=true npm run test:unit`.
## Modifying System Prompt
Modular: `components/` (shared) + `variants/` (model-specific) + `templates/` (`{{PLACEHOLDER}}`). Variants override components via `componentOverrides` in `config.ts` or custom `template.ts`. XS variant is heavily condensed inline. Always regenerate snapshots after changes.
## Global State Keys (silent failure risk)
Adding a key requires: type in `src/shared/storage/state-keys.ts`, read via `context.globalState.get()` in `src/core/storage/utils/state-helpers.ts` `readGlobalStateFromDisk()`, and add to return object. Missing the `.get()` call compiles fine but value is always `undefined`.
## Slash Commands (3 places)
- `src/core/slash-commands/index.ts` — definitions.
- `src/core/prompts/commands.ts` — system prompt integration.
- `webview-ui/src/utils/slash-commands.ts` — webview autocomplete.
## Conventions
- **Paths**: Always use `src/utils/path` helpers (`toPosixString`) for cross-platform compatibility.
- **Logging**: `src/shared/services/Logger.ts`.
- **Feature flags**: See PR #7566 as reference pattern.
-1
View File
@@ -60,7 +60,6 @@ We're not looking for exhaustive documentation - just evidence that you've thoug
- [ ] Changes are limited to a single feature, bugfix or chore (split larger changes into separate PRs)
- [ ] Tests are passing (`npm test`) and code is formatted and linted (`npm run format && npm run lint`)
- [ ] I have created a changeset using `npm run changeset` (required for user-facing changes)
- [ ] I have reviewed [contributor guidelines](https://github.com/cline/cline/blob/main/CONTRIBUTING.md)
### Screenshots
@@ -1,79 +0,0 @@
"""
This script updates a specific version's release notes section in CHANGELOG.md with new content
or reformats existing content.
The script:
1. Takes a version number, changelog path, and optionally new content as input from environment variables
2. Finds the section in the changelog for the specified version
3. Either:
a) Replaces the content with new content if provided, or
b) Reformats existing content by:
- Removing the first two lines of the changeset format
- Ensuring version numbers are wrapped in square brackets
4. Writes the updated changelog back to the file
Environment Variables:
CHANGELOG_PATH: Path to the changelog file (defaults to 'CHANGELOG.md')
VERSION: The version number to update/format
PREV_VERSION: The previous version number (used to locate section boundaries)
NEW_CONTENT: Optional new content to insert for this version
"""
#!/usr/bin/env python3
import os
CHANGELOG_PATH = os.environ.get("CHANGELOG_PATH", "CHANGELOG.md")
VERSION = os.environ['VERSION']
PREV_VERSION = os.environ.get("PREV_VERSION", "")
NEW_CONTENT = os.environ.get("NEW_CONTENT", "")
def overwrite_changelog_section(changelog_text: str, new_content: str):
# Find the section for the specified version
version_pattern = f"## {VERSION}\n"
unformmatted_prev_version_pattern = f"## {PREV_VERSION}\n"
prev_version_pattern = f"## [{PREV_VERSION}]\n"
print(f"latest version: {VERSION}")
print(f"prev_version: {PREV_VERSION}")
notes_start_index = changelog_text.find(version_pattern) + len(version_pattern)
notes_end_index = changelog_text.find(prev_version_pattern, notes_start_index) if PREV_VERSION and (prev_version_pattern in changelog_text or unformmatted_prev_version_pattern in changelog_text) else len(changelog_text)
if new_content:
return changelog_text[:notes_start_index] + f"{new_content}\n" + changelog_text[notes_end_index:]
else:
changeset_lines = changelog_text[notes_start_index:notes_end_index].split("\n")
filtered_lines = []
for line in changeset_lines:
# If the previous line is a changeset format
if len(filtered_lines) > 1 and filtered_lines[-1].startswith("### "):
# Remove the last two lines from the filted_lines
filtered_lines.pop()
filtered_lines.pop()
else:
filtered_lines.append(line.strip())
# Prepend a new line to the first line of filtered_lines
if filtered_lines:
filtered_lines[0] = "\n" + filtered_lines[0]
# Print filted_lines wiht a "\n" at the end of each line
for line in filtered_lines:
print(line.strip())
parsed_lines = "\n".join(line for line in filtered_lines)
updated_changelog = changelog_text[:notes_start_index] + parsed_lines + changelog_text[notes_end_index:]
return updated_changelog
with open(CHANGELOG_PATH, 'r') as f:
changelog_content = f.read()
new_changelog = overwrite_changelog_section(changelog_content, NEW_CONTENT)
# print("----------------------------------------------------------------------------------")
# print(new_changelog)
# print("----------------------------------------------------------------------------------")
# Write back to CHANGELOG.md
with open(CHANGELOG_PATH, 'w') as f:
f.write(new_changelog)
print(f"{CHANGELOG_PATH} updated successfully!")
-113
View File
@@ -1,113 +0,0 @@
name: Changeset Converter
run-name: Changeset Conversion
on:
workflow_dispatch:
pull_request:
types: [closed]
env:
REPO_PATH: ${{ github.repository }}
GIT_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || 'main' }}
NODE_VERSION: 20.18.1
jobs:
# Job 1: Create version bump PR when changesets are merged to main
changeset-pr-version-bump:
if: |
github.event_name == 'workflow_dispatch' ||
(
github.event_name == 'pull_request' &&
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'main' &&
github.actor != 'github-actions'
)
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Check user for team affiliation
id: team_check
if: github.event_name == 'workflow_dispatch'
uses: morfien101/actions-authorized-user@4a3cfbf0bcb3cafe4a71710a278920c5d94bb38b
with:
username: ${{ github.actor }}
org: ${{ github.repository_owner }}
team: "deployer"
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Check if user is authorized
if: github.event_name == 'workflow_dispatch'
run: |
if [ "${{ steps.team_check.outputs.authorized }}" != "true" ]; then
echo "User is not authorized to run this workflow."
exit 1
fi
- name: Git Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ env.GIT_REF }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: "npm"
- name: Install Dependencies
run: npm ci
# Check if there are any new changesets to process
- name: Check for changesets
id: check-changesets
run: |
NEW_CHANGESETS=$(find .changeset -name "*.md" ! -name "README.md" | wc -l | tr -d ' ')
echo "Changesets diff with previous version: $NEW_CHANGESETS"
echo "new_changesets=$NEW_CHANGESETS" >> $GITHUB_OUTPUT
# Create version bump PR using changesets/action if there are new changesets
- name: Create Changeset Pull Request
if: steps.check-changesets.outputs.new_changesets != '0'
uses: changesets/action@v1
with:
commit: "changeset version bump"
title: "Changeset version bump"
version: npm run version-packages # This performs the changeset version bump
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Get current and previous versions to edit changelog entry
- name: Get version
id: get_version
run: |
VERSION=$(git show HEAD:package.json | jq -r '.version')
echo "version=$VERSION" >> $GITHUB_OUTPUT
PREV_VERSION=$(git show origin/main:package.json | jq -r '.version')
echo "prev_version=$PREV_VERSION" >> $GITHUB_OUTPUT
echo "version=$VERSION"
echo "prev_version=$PREV_VERSION"
# Update CHANGELOG.md with proper format
- name: Update Changelog Format
env:
VERSION: ${{ steps.get_version.outputs.version }}
PREV_VERSION: ${{ steps.get_version.outputs.prev_version }}
run: python .github/scripts/overwrite_changeset_changelog.py
# Commit and push changelog updates
- name: Push Changelog updates to Pull Request
run: |
git config user.name "github-actions"
git config user.email github-actions@github.com
echo "Running git add and commit..."
git add CHANGELOG.md
git commit -m "Updating CHANGELOG.md format"
git status
echo "--------------------------------------------------------------------------------"
echo "Pushing to remote..."
echo "--------------------------------------------------------------------------------"
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
git push origin $CURRENT_BRANCH
-173
View File
@@ -1,173 +0,0 @@
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.
-284
View File
@@ -1,284 +0,0 @@
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: Print HEAD commit
run: |
echo "HEAD is at: $(git rev-parse HEAD)"
echo "Short: $(git rev-parse --short HEAD)"
git log -1 --format="Commit: %H%nAuthor: %an <%ae>%nDate: %ad%nMessage: %s"
- 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 by noting the commit hash you reviewed:
```bash
git rev-parse --short HEAD
```
Include this at the top of your comment: "Reviewed at commit: <short hash>"
Then thank them 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
+83
View File
@@ -0,0 +1,83 @@
name: CLI TUI Tests
on:
pull_request:
branches:
- main
workflow_dispatch:
workflow_call:
permissions:
contents: read
jobs:
cli-tui-tests:
name: CLI TUI Tests
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install dependencies
run: npm ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build CLI
run: npm run cli:build
- name: Run TUI Tests
id: tui_tests
run: |
npm run test:e2e:cli:tui 2>&1 | tee tui-test-output.log
exit_code=${PIPESTATUS[0]}
echo "tui_exit_code=$exit_code" >> $GITHUB_OUTPUT
exit $exit_code
- name: Write failure summary
if: always() && steps.tui_tests.outcome != 'success' && steps.tui_tests.outcome != 'skipped'
run: |
echo "## ❌ CLI TUI Tests Failed" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Step outcome:** \`${{ steps.tui_tests.outcome }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Test Output" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
if [ -f tui-test-output.log ]; then
cat tui-test-output.log >> $GITHUB_STEP_SUMMARY
else
echo "(no test output captured — process may have been killed before output was flushed)" >> $GITHUB_STEP_SUMMARY
fi
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Debugging" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "- **TUI traces** are attached as artifacts below — download and inspect them to see terminal state at the point of failure." >> $GITHUB_STEP_SUMMARY
echo "- **To view a trace replay/Run a TUI Trace: ** run \`npx tui-test show-trace path/to/trace/file\` in your terminal" >> $GITHUB_STEP_SUMMARY
echo "- **Full test log** is also attached as an artifact." >> $GITHUB_STEP_SUMMARY
echo "- Tests run with \`retries: 2\` so any failure shown is a consistent failure, not a flake." >> $GITHUB_STEP_SUMMARY
- name: Upload TUI traces
if: always() && steps.tui_tests.outcome != 'success' && steps.tui_tests.outcome != 'skipped'
uses: actions/upload-artifact@v4
with:
name: tui-test-traces
path: tests/e2e/cli/tui-traces/
retention-days: 14
if-no-files-found: warn
- name: Upload test log
if: always() && steps.tui_tests.outcome != 'success' && steps.tui_tests.outcome != 'skipped'
uses: actions/upload-artifact@v4
with:
name: tui-test-log
path: tui-test-output.log
retention-days: 14
if-no-files-found: warn
@@ -0,0 +1,85 @@
name: Smoke Tests
on:
push:
branches: [main]
paths:
- 'src/core/**'
- 'src/shared/**'
- 'proto/**'
- 'evals/**'
- '.github/workflows/cline-evals-regression.yml'
pull_request:
paths:
- 'src/core/**'
- 'src/shared/**'
- 'proto/**'
- 'evals/**'
- '.github/workflows/cline-evals-regression.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: smoke-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
smoke-tests:
name: Smoke Tests
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build and install CLI
run: |
npm run protos
cd cli && npm install && npm run build && npm link
echo "$(npm config get prefix)/bin" >> $GITHUB_PATH
- name: Verify CLI
run: cline --version
- name: Run smoke tests
env:
CLINE_API_KEY: ${{ secrets.CLINE_API_KEY }}
run: |
cline auth -p cline -k "$CLINE_API_KEY" -m "anthropic/claude-sonnet-4.5"
max_attempts=3
for attempt in $(seq 1 $max_attempts); do
echo "::group::Attempt $attempt of $max_attempts"
if npx tsx evals/smoke-tests/run-smoke-tests.ts --trials 1 --parallel; then
echo "::endgroup::"
echo "Smoke tests passed on attempt $attempt"
exit 0
fi
echo "::endgroup::"
if [ $attempt -lt $max_attempts ]; then
echo "::warning::Smoke tests failed on attempt $attempt, retrying..."
sleep 10
fi
done
echo "::error::Smoke tests failed after $max_attempts attempts"
exit 1
- name: Generate summary
if: always()
run: cat evals/smoke-tests/results/latest/summary.md >> $GITHUB_STEP_SUMMARY
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: smoke-test-results-${{ github.run_id }}
path: evals/smoke-tests/results/latest/
retention-days: 30
-324
View File
@@ -1,324 +0,0 @@
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: Print HEAD commit
run: |
echo "HEAD is at: $(git rev-parse HEAD)"
echo "Short: $(git rev-parse --short HEAD)"
git log -1 --format="Commit: %H%nAuthor: %an <%ae>%nDate: %ad%nMessage: %s"
- 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 by noting the commit hash you reviewed:
```bash
git rev-parse --short HEAD
```
Include this at the top of your comment: "Reviewed at commit: <short hash>"
Then thank them 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'
+12 -15
View File
@@ -1,7 +1,7 @@
name: Publish NPM Release
on:
workflow_dispatch:
workflow_call:
inputs:
confirm_publish:
description: 'Type "publish" to confirm you want to publish to NPM'
@@ -9,7 +9,8 @@ on:
type: string
permissions:
contents: read
contents: write # Required for pushing tags
id-token: write # Required for npm trusted publishing (OIDC)
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
@@ -20,7 +21,7 @@ jobs:
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'
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && inputs.confirm_publish == 'publish'
runs-on: ubuntu-latest
steps:
@@ -30,19 +31,10 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20.x"
node-version: "24.x"
registry-url: "https://registry.npmjs.org"
# 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') }}
- name: Install root dependencies and CLI dependencies
if: steps.check_commits.outputs.skip != 'true'
run: npm ci --include=optional # this will also install cli deps because "cli" in included in root package.json workspaces field
- name: Generate Protos
@@ -81,13 +73,18 @@ jobs:
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: Tag release
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag "v${{ steps.version.outputs.version }}-cli"
git push origin "v${{ steps.version.outputs.version }}-cli"
- name: Summary
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'latest'"
+15 -15
View File
@@ -1,12 +1,17 @@
name: Publish NPM Nightly
on:
schedule:
- cron: "0 12 * * *" # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
workflow_call:
inputs:
force_publish:
description: "Force publish even if there are no commits in the last 24 hours"
required: false
type: boolean
default: false
permissions:
contents: read
id-token: write # Required for npm trusted publishing (OIDC)
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
@@ -27,6 +32,12 @@ jobs:
- name: Check for recent commits
id: check_commits
run: |
if [ "${{ inputs.force_publish }}" = "true" ]; then
echo "force_publish enabled, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
exit 0
fi
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
@@ -39,18 +50,9 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: "20.x"
node-version: "24.x"
registry-url: "https://registry.npmjs.org"
# 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') }}
- name: Install root dependencies and CLI dependencies
if: steps.check_commits.outputs.skip != 'true'
run: npm ci --include=optional # this will also install cli deps because "cli" in included in root package.json workspaces field
@@ -118,8 +120,6 @@ jobs:
- 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
+215
View File
@@ -0,0 +1,215 @@
# Build and Pack CLI
#
# Builds a CLI tarball from any branch/commit and publishes it as a GitHub Release.
# Requires write access to the repository (maintainers/collaborators only).
#
# Security: Split into two jobs to isolate untrusted build code from write tokens.
# The build job runs arbitrary ref code with zero permissions. The release job
# only runs trusted GitHub Actions with write scope.
#
# Usage (helper script, auto-detects current branch):
# ./scripts/build-cli-artifact.sh
# ./scripts/build-cli-artifact.sh feature/my-changes
# ./scripts/build-cli-artifact.sh feature/my-changes 1234 # comments on PR
#
# Usage (gh CLI directly):
# gh workflow run pack-cli.yml -f ref=main
# gh workflow run pack-cli.yml -f ref=abc123 -f pr_number=1234
#
# Install the built CLI (no auth required):
# npm install -g https://github.com/cline/cline/releases/download/cli-build-<sha>/cline-<ver>.tgz
#
# Find releases:
# gh release list --limit 10
name: Build and Pack CLI
permissions:
contents: read
on:
workflow_dispatch:
inputs:
ref:
description: 'Branch, tag, or commit SHA to build (leave empty for default branch)'
required: false
type: string
pr_number:
description: 'PR number to comment on with install instructions (optional)'
required: false
type: number
jobs:
# ── Build job: runs untrusted ref code with ZERO permissions ──
build:
name: Build CLI
runs-on: ubuntu-latest
permissions: {}
outputs:
commit_sha: ${{ steps.commit.outputs.sha }}
tarball: ${{ steps.pack.outputs.tarball }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.ref }}
persist-credentials: false
- name: Get commit SHA
id: commit
run: |
COMMIT_SHA=$(git rev-parse --short HEAD)
echo "sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
echo "Building from commit: $COMMIT_SHA"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20.x"
- name: Install dependencies
run: npm ci --include=optional
- name: Generate Protos
run: npm run protos
- name: Build standalone package
run: node scripts/package-npm.mjs
- name: Create Tarball
id: pack
run: |
cd dist-standalone
TARBALL=$(npm pack)
echo "tarball=$TARBALL" >> $GITHUB_OUTPUT
echo "Created tarball: $TARBALL"
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: cli-tarball
path: dist-standalone/*.tgz
# ── Release job: only trusted Actions code, with write permissions ──
release:
name: Release CLI
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
steps:
- name: Download artifact
uses: actions/download-artifact@v4
with:
name: cli-tarball
path: dist-standalone
- name: Create GitHub Release
id: create_release
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const path = require('path');
const commit = '${{ needs.build.outputs.commit_sha }}';
const tarball = '${{ needs.build.outputs.tarball }}';
// Delete existing release/tag if re-running for the same commit
const tagName = `cli-build-${commit}`;
try {
const existing = await github.rest.repos.getReleaseByTag({
owner: context.repo.owner,
repo: context.repo.repo,
tag: tagName
});
await github.rest.repos.deleteRelease({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: existing.data.id
});
await github.rest.git.deleteRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `tags/${tagName}`
});
core.info(`Deleted existing release for ${tagName}`);
} catch (e) {
// Release doesn't exist yet, that's fine
}
// Create a release
const release = await github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: tagName,
name: `CLI Build (${commit})`,
body: `Automated CLI build from commit ${commit}\n\nInstall with:\n\`\`\`bash\nnpm install -g https://github.com/${context.repo.owner}/${context.repo.repo}/releases/download/${tagName}/${tarball}\n\`\`\``,
draft: false,
prerelease: true
});
// Upload the tarball as a release asset
const tarballPath = path.join('dist-standalone', tarball);
const tarballData = fs.readFileSync(tarballPath);
await github.rest.repos.uploadReleaseAsset({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: release.data.id,
name: tarball,
data: tarballData
});
const downloadUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/releases/download/${tagName}/${tarball}`;
core.setOutput('release_url', release.data.html_url);
core.setOutput('download_url', downloadUrl);
- name: Comment on PR with download instructions
if: inputs.pr_number != ''
uses: actions/github-script@v7
with:
script: |
const commit = '${{ needs.build.outputs.commit_sha }}';
const releaseUrl = '${{ steps.create_release.outputs.release_url }}';
const downloadUrl = '${{ steps.create_release.outputs.download_url }}';
const prNumber = ${{ inputs.pr_number || 0 }};
if (!prNumber) return;
const comment = `## 📦 CLI Build Ready
A CLI build has been created for commit \`${commit}\`.
### Install Directly from URL (No Authentication Required!)
\`\`\`bash
npm install -g ${downloadUrl}
\`\`\`
### Alternative: Download and Install
\`\`\`bash
curl -L ${downloadUrl} -o cline.tgz
npm install -g ./cline.tgz
\`\`\`
📦 [View Release](${releaseUrl})
`;
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
- name: Summary
run: |
echo "✅ CLI build complete!"
echo ""
echo "📦 Release: ${{ steps.create_release.outputs.release_url }}"
echo "🔗 Download URL: ${{ steps.create_release.outputs.download_url }}"
echo ""
echo "Install from anywhere (no authentication required):"
echo " npm install -g ${{ steps.create_release.outputs.download_url }}"
@@ -0,0 +1,60 @@
name: Publish CLI (Trusted)
on:
schedule:
- cron: "0 12 * * *" # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
inputs:
publish_target:
description: "Which publish flow to run"
required: true
default: "main"
type: choice
options:
- main
- nightly
confirm_publish:
description: 'Required when publish_target=main. Type "publish" to confirm release publish.'
required: false
type: string
force_nightly_publish:
description: "Force nightly publish even with no commits in last 24h"
required: false
type: boolean
default: false
permissions:
id-token: write # Required for npm trusted publishing (OIDC)
contents: write # Required because npm-main creates/pushes git tags
checks: write # Required by nested reusable test workflow
pull-requests: write # Required by nested reusable test workflow
jobs:
cli-tui-tests:
uses: ./.github/workflows/cli-tui-tests.yml
publish-main:
needs: cli-tui-tests
if: |
github.repository == 'cline/cline' && (
github.event_name == 'workflow_dispatch' &&
github.event.inputs.publish_target == 'main' &&
github.event.inputs.confirm_publish == 'publish' &&
!endsWith(github.actor, '[bot]')
)
uses: ./.github/workflows/npm-main.yaml
secrets: inherit
with:
confirm_publish: ${{ github.event.inputs.confirm_publish }}
publish-nightly:
needs: cli-tui-tests
if: |
github.repository == 'cline/cline' && (
github.event_name == 'schedule' ||
(github.event_name == 'workflow_dispatch' && github.event.inputs.publish_target == 'nightly')
)
uses: ./.github/workflows/npm-nightly.yaml
secrets: inherit
with:
force_publish: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.force_nightly_publish == 'true' }}
+13 -19
View File
@@ -24,6 +24,8 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
lfs: true
- name: Check for recent commits
run: |
@@ -36,35 +38,27 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "lts/*"
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
# Keep publish environment aligned with test workflow/tooling lockfile expectations.
# Newer LTS (Node 24 / npm 11) can make `npm list` fail with ELSPROBLEMS during vsce packaging.
node-version: 22
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
- name: Verify LFS media assets are resolved
run: |
FILE="webview-ui/src/assets/cline_kanban_demo.webm"
if grep -q "git-lfs.github.com/spec/v1" "$FILE"; then
echo "Error: $FILE is still a Git LFS pointer in CI checkout"
exit 1
fi
- name: Publish Extension as Pre-release
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
+84 -34
View File
@@ -11,8 +11,13 @@ on:
options:
- pre-release
- release
auto_create_tag_from_main:
description: "Auto-create and push the provided tag from the tested main commit (recommended)"
required: true
default: true
type: boolean
tag:
description: "Enter existing tag to publish (e.g., v3.1.2)"
description: "Tag to publish (required in both modes, e.g., v3.1.2)"
required: true
type: string
@@ -35,37 +40,79 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag }}
ref: main
fetch-depth: 0
fetch-tags: true
lfs: true
- name: Resolve Release Tag
id: resolve_tag
run: |
TAG="${{ github.event.inputs.tag }}"
AUTO_CREATE="${{ github.event.inputs.auto_create_tag_from_main }}"
TESTED_SHA="${{ github.sha }}"
WORKFLOW_REF="${{ github.ref }}"
if [[ -z "$TAG" ]]; then
echo "Error: tag input is required"
exit 1
fi
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.]+)?$ ]]; then
echo "Error: tag must match vX.Y.Z (optionally with -suffix or .suffix)"
exit 1
fi
TAG_REF="refs/tags/$TAG"
git fetch origin main --tags
if [[ "$AUTO_CREATE" == "true" ]]; then
if [[ "$WORKFLOW_REF" != "refs/heads/main" ]]; then
echo "Error: auto-create mode requires dispatching from main (current ref: $WORKFLOW_REF)"
exit 1
fi
echo "Auto-create enabled. Using tested workflow SHA: $TESTED_SHA"
if ! git merge-base --is-ancestor "$TESTED_SHA" origin/main; then
echo "Error: tested SHA $TESTED_SHA is not on origin/main"
exit 1
fi
if git show-ref --verify --quiet "$TAG_REF"; then
TAG_SHA=$(git rev-list -n 1 "$TAG_REF^{commit}")
if [[ "$TAG_SHA" != "$TESTED_SHA" ]]; then
echo "Error: tag '$TAG' already exists at $TAG_SHA, not at tested SHA ($TESTED_SHA)"
exit 1
fi
echo "Tag '$TAG' already exists at tested SHA. Continuing."
else
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag "$TAG" "$TESTED_SHA"
git push origin "$TAG_REF"
echo "Created and pushed tag '$TAG' from tested SHA $TESTED_SHA."
fi
else
if ! git show-ref --verify --quiet "$TAG_REF"; then
echo "Error: tag '$TAG' does not exist in the repository"
exit 1
fi
echo "Using existing tag '$TAG'."
fi
git checkout --detach "$TAG_REF^{commit}"
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "resolved_sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "lts/*"
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
node-version: 22
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm install --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm install --include=optional
- name: Install Publishing Tools
@@ -77,20 +124,23 @@ jobs:
VERSION=$(node -p "require('./package.json').version")
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Validate Tag
id: validate_tag
- name: Verify Tag Matches Package Version
run: |
TAG="${{ github.event.inputs.tag }}"
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "Using existing tag: $TAG"
# Verify the tag exists
if ! git rev-parse "$TAG" >/dev/null 2>&1; then
echo "Error: Tag '$TAG' does not exist in the repository"
TAG="${{ steps.resolve_tag.outputs.tag }}"
VERSION="v${{ steps.get_version.outputs.version }}"
if [[ "$TAG" != "$VERSION" ]]; then
echo "Error: tag '$TAG' does not match package version '$VERSION'"
exit 1
fi
echo "Tag and package version match: $TAG"
echo "Tag '$TAG' validated successfully"
- name: Verify LFS media assets are resolved
run: |
FILE="webview-ui/src/assets/cline_kanban_demo.webm"
if grep -q "git-lfs.github.com/spec/v1" "$FILE"; then
echo "Error: $FILE is still a Git LFS pointer in CI checkout"
exit 1
fi
- name: Package and Publish Extension
env:
@@ -121,7 +171,7 @@ jobs:
- name: Get Previous Tag
id: prev_tag
run: |
CURRENT_TAG="${{ steps.validate_tag.outputs.tag }}"
CURRENT_TAG="${{ steps.resolve_tag.outputs.tag }}"
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
@@ -137,12 +187,12 @@ jobs:
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.validate_tag.outputs.tag }}
tag_name: ${{ steps.resolve_tag.outputs.tag }}
files: "*.vsix"
body: |
${{ steps.changelog.outputs.content }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.validate_tag.outputs.tag }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.resolve_tag.outputs.tag }}
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+18 -50
View File
@@ -28,20 +28,10 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
- name: Install root dependencies
run: npm ci
@@ -73,20 +63,10 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
- name: Install root dependencies
run: npm ci
@@ -135,6 +115,11 @@ jobs:
cd webview-ui
npm run test:coverage
- name: CLI Tests
id: cli_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: cd cli && npm run test:run
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
@@ -156,28 +141,11 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
# Cache testing-platform dependencies
- name: Cache testing-platform dependencies
uses: actions/cache@v4
id: testing-platform-cache
with:
path: testing-platform/node_modules
key: ${{ runner.os }}-npm-testing-platform-${{ hashFiles('testing-platform/package-lock.json') }}
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
testing-platform/package-lock.json
- name: Install root dependencies
run: npm ci
@@ -20,7 +20,8 @@ jobs:
github.event_name == 'pull_request_target' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '/test-jetbrains'))
contains(github.event.comment.body, '/test-jetbrains') &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association))
steps:
- name: Generate GitHub App Token
id: app-token
+8
View File
@@ -48,3 +48,11 @@ test-results
.secrets
*.tsbuildinfo
# Smoke test results (generated)
evals/smoke-tests/results/
.tui-test
secrets.json
tui-traces
tests/**/cache
+3
View File
@@ -0,0 +1,3 @@
[submodule "evals/cline-bench"]
path = evals/cline-bench
url = https://github.com/cline/cline-bench.git
+2 -1
View File
@@ -16,7 +16,8 @@
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
"${workspaceFolder}",
"--disable-extensions"
],
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
-2
View File
@@ -35,11 +35,9 @@ cli/**
eslint-rules/
old_docs/
evals/
.changie.yaml
.codespellrc
.mocharc.json
buf.yaml
.changeset/
.clinerules/
# Ignore all webview-ui files except the build directory (https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/frameworks/hello-world-react-cra/.vscodeignore)
+317 -11
View File
@@ -1,26 +1,332 @@
# Changelog
## [3.76.0]
### Added
- Add Cline Kanban launch modal in webview; CLI now launches Kanban by default with a migration view
- Add toggle to disable feature tips in chat
- Add repeated tool call loop detection to prevent infinite loops wasting tokens
### Fixed
- Fix CLI Kanban spawn on Windows by enabling shell mode for `npx.cmd`
## [3.75.0]
### Added
- Latency improvements for remote workspaces
### Fixed
- Stabilize flaky hooks tests
### Changed
- Remove example hooks in favor of reading the docs
## [3.74.0]
### Added
- Implement dynamic free model detection for Cline API
- Add file read deduplication cache to prevent repeated reads
- Add feature tips tooltip during thinking state
### Fixed
- Replace error message when not logged in to Cline
- Align ClineRulesToggleModal padding with ServersToggleModal
- Skip WebP for GLM and Devstral models running through llama.cpp
- Respect user-configured context window in LiteLLM getModel()
- Honor explicit model IDs outside static catalog in W&B provider
- Add missing Fireworks serverless models and pricing
## [3.73.0]
### Added
- Added W&B Inference by CoreWeave as a new API provider with 17 models
- Improved parallel tool calling support for OpenRouter and Cline providers
### Fixed
- Claude Code Provider: handle rate limit events, empty content arrays, error results, and unknown content types without crashing
- Tool handlers (`read_file`, `list_files`, `list_code_definition_names`, `search_files`) now return graceful errors instead of crashing
## [3.72.0]
### Added
- Added Anthropic Opus 4.6 fast mode variants
### Fixed
- Resolved native tool placeholder interpolation in prompts
- Gemini: capped Flash output tokens to 8192 across providers
- Fixed Windows unit test path normalization
- Fixed flaky hooks tests on Windows
- Bedrock: handle thinking and redacted_thinking blocks correctly in message conversion and streaming
- Prevent crash when `list_files` or `list_code_definition_names` receives a file path
### Changed
- Updated Jupyter Notebook GIFs
- Markdown image loading now requires user consent
- Added `.github/copilot-instructions.md` for coding agents
- Hooks: reintroduced feature toggle
## [3.71.0]
### Added
- Added GPT-5.4 models for ChatGPT subscription users
- Hooks: Added a `Notification` hook for attention and completion boundaries
### Fixed
- Handle streamable HTTP MCP reconnects more reliably after disconnects
## [3.70.0]
### Added
- New Cline API docs: Getting Started, Auth, Chat Completions, Models, Errors, and SDK Examples
- Hook payloads now include `model.provider` and `model.slug`
- Token/cost updates now happen immediately as usage chunks arrive, not after tool execution
### Fixed
- Improve subagent context compaction logic
- Subagent stream retry delay increased to reduce noise from transient failures
- State serialization errors are now caught and logged instead of crashing
- Removed incorrect `max_tokens` from OpenRouter requests
### Changed
- Windows test cleanup now retries on locked files and applies per-test timeouts
- Updated hooks docs
## [3.69.0]
### Added
- Add `User-Agent` header to requests sent to the Cline backend
- Add default auto-tag workflow for publish release flow
- Show Cline SDK docs on the Cline page
### Fixed
- Retry nested git restore and prevent silent `.git_disabled` leftovers in checkpoints
- Prevent Chinese filename escaping in diff view
- Trigger auto-compaction on OpenRouter context overflow errors
- Restore GPT-OSS native file editing on OpenAI-compatible models
### Changed
- Update Cline SDK docs
- Improve hooks support for Windows PowerShell
## [3.68.0]
### Added
- Add dynamic Cline provider model fetching from Cline endpoint
- Add additional Markdown formatting in CLI
- Add focus indicator on action buttons in extension
### Fixed
- Clear all OCA secrets on auth refresh failure to prevent re-auth loops
- Resolve "Could not find the file context" error in Explain Changes
- Use `JSON_SCHEMA` for `yaml.load` to prevent unsafe deserialization
- Fetch model info from API in CLI headless auth for Cline and Vercel providers
- Generate commit message from staged changes only when staging exists
- Update stale `maxTokens` values for Claude 3.7+ models across Anthropic, Bedrock, Vertex, and SAP AI Core
- Use `model.info.maxTokens` for OpenRouter instead of hardcoded `8192`
### Changed
- Increase timeout for a flaky test to reduce short-term test instability
## [3.67.1]
### Added
- Added Cline SDK API interface for programmatic access to Cline features and tools, enabling integration into custom applications.
- Added Codex 5.3 model support
### Fixed
- Fix OpenAI Codex by setting `store` to `false`
- Use `isLocatedInPath()` instead of string matching for path containment checks
## [3.67.0]
### Added
- Add support for skills and optional modelId in subagent configuration
- Add AgentConfigLoader for file-based agent configs
- Add Responses API support for OpenAI native provider
- Preconnect websocket to reduce response latency
- Fetch featured models from backend with local fallback
- Add /q command to quit CLI
- Add MCP enterprise configuration details
- Pull Cline's recommended models from internal endpoint
- Add dynamic flag to adjust banner cache duration
### Fixed
- Fix reasoning delta crash on usage-only stream chunks
- Fix OpenAI tool ID transformation restricted to native provider only
- Fix auth check for ACP mode
- Fix CLI yolo mode to not persist yolo setting to disk
- Fix inline focus-chain slider within its feature row
- Fix Gemini 3.1 Pro compatibility
- Fix Cline auth with ACP flag
### Changed
- Move PR skill to .agents/skills
- SambaNova provider: update models list
- Remove changeset-converter GitHub Action and npm run changeset
## [3.66.0]
### Added
- Gemini-3.1 Pro Preview
## [3.65.0]
### Added
- Add /skills slash command to CLI for viewing and managing installed skills
### Fixed
- Fix aggressive context compaction caused by accidental clicks on the context window progress bar silently setting a very low auto-condense threshold
- Fix infinite retry loop when write_to_file fails with missing content parameter.
- Fixed default claude model
## [3.64.0]
### Added
- Added sonnet 4.6
## [3.63.0]
### Added
- added zai GLM 5 Free promo
### Fixed
- Restore reasoning trace visibility in chat and improve the thinking row UX so reasoning is visible, then collapsible after completion.
## [3.62.0]
### Fixed
- Banners now display immediately when opening the extension instead of requiring user interaction first
- Resolved 17 security vulnerabilities including high-severity DoS issues in dependencies (body-parser, axios, qs, tar, and others)
## [3.61.0]
- UI/UX fixes with minimax model family
## [3.60.0]
- Fixes for Minimax model family
## [3.59.0]
- Added Minimax 2.5 Free Promo
- Fixed Response chaining for OpenAI's Responses API
## [3.58.0]
### Added
- Subagent: replace legacy subagents with the native `use_subagents` tool
- Bundle `endpoints.json` support so packaged distributions can ship required endpoints out-of-the-box
- Amazon Bedrock: support parallel tool calling
- New "double-check completion" experimental feature to verify work before marking tasks complete
- CLI: new task controls/flags including custom `--thinking` token budget and `--max-consecutive-mistakes` for yolo runs
- Remote config: new UI/options (including connection/test buttons) and support for syncing deletion of remotely configured MCP servers
- Vertex / Claude Code: add 1M context model options for Claude Opus 4.6
- ZAI/GLM: add GLM-5
### Fixed
- CLI: handle stdin redirection correctly in CI/headless environments
- CLI: preserve OAuth callback paths during auth redirects
- VS Code Web: generate auth callback URLs via `vscode.env.asExternalUri` (OAuth callback reliability)
- Terminal: surface command exit codes in results and improve long-running `execute_command` timeout behavior
- UI: add loading indicator and fix `api_req_started` rendering
- Task streaming: prevent duplicate streamed text rows after completion
- API: preserve selected Vercel model when model metadata is missing
- Telemetry: route PostHog networking through proxy-aware shared fetch and ensure telemetry flushes on shutdown
- CI: increase Windows E2E test timeout to reduce flakiness
### Changed
- Settings/model UX: move "reasoning effort" into model configuration and expose it in settings
- CLI provider selection: limit provider list to those remotely configured
- UI: consolidate ViewHeader component/styling across views
- Tools: add auto-approval support for `attempt_completion` commands
- Remotely configured MCP server schema now supports custom headers
## [3.57.1]
### Fixed
- Fixed Opus 4.6 for bedrock provider
## [3.57.0]
### Added
- Cline CLI 2.0 now available. Install with `npm install -g cline`
- Anthopic Opus 4.6
- Minimax-2.1 and Kimi-k2.5 now available for free for a limited time promo
- Codex-5.3 through ChatGPT subscription
### Fixed
- Fix read file tool to support reading large files
- Fix decimal input crash in OpenAI Compatible price fields (#8129)
- Fix build complete handlers when updating the api config
- Fixed missing provider from list
- Fixed Favorite Icon / Star from getting clipped in the task history view
### Changed
- Make skills always enabled and remove feature toggle setting
## [3.56.0]
### Added
- __CLI authentication:__ Added Vercel AI Gateway and Cline API key provider support for headless CI/automation workflows
- __New model:__ Added Kimi-K2.5 model to Moonshot provider (262K context, image support, prompt caching)
- __Prompt variant:__ Added Trinity Large prompt variant for improved tool-calling support
- __OpenTelemetry:__ Added support for custom headers on metrics and logs endpoints
- __Social links:__ Added community icons (X, Discord, GitHub, Reddit, LinkedIn) to the What's New modal
- **CLI authentication:** Added Vercel AI Gateway and Cline API key provider support for headless CI/automation workflows
- **New model:** Added Kimi-K2.5 model to Moonshot provider (262K context, image support, prompt caching)
- **Prompt variant:** Added Trinity Large prompt variant for improved tool-calling support
- **OpenTelemetry:** Added support for custom headers on metrics and logs endpoints
- **Social links:** Added community icons (X, Discord, GitHub, Reddit, LinkedIn) to the What's New modal
### Fixed
- __LiteLLM:__ Fixed thinking configuration not appearing for reasoning-capable models
- __OpenTelemetry:__ Fixed endpoint path handling (no longer incorrectly appends `/v1/logs` or `/v1/metrics`) and ensured logs are sent regardless of VSCode telemetry settings
- __CLI auth:__ Fixed `cline auth` displaying incorrect provider information after configuration
- **LiteLLM:** Fixed thinking configuration not appearing for reasoning-capable models
- **OpenTelemetry:** Fixed endpoint path handling (no longer incorrectly appends `/v1/logs` or `/v1/metrics`) and ensured logs are sent regardless of VSCode telemetry settings
- **CLI auth:** Fixed `cline auth` displaying incorrect provider information after configuration
### Changed
- __Hooks:__ Hook scripts now run from the workspace repository root instead of filesystem root
- __Default settings:__ Enabled multi-root workspaces, parallel tool calling, and skills by default; disabled strict plan mode by default
- __Settings UI:__ Refreshed feature settings section with collapsible design
- **Hooks:** Hook scripts now run from the workspace repository root instead of filesystem root
- **Default settings:** Enabled multi-root workspaces, parallel tool calling, and skills by default; disabled strict plan mode by default
- **Settings UI:** Refreshed feature settings section with collapsible design
## [3.55.0]
+6 -25
View File
@@ -57,25 +57,11 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
### Creating a Pull Request
1. Before creating a PR, generate a changeset entry:
```bash
npm run changeset
```
This will prompt you for:
- Type of change (major, minor, patch)
- `major` → breaking changes (1.0.0 → 2.0.0)
- `minor` → new features (1.0.0 → 1.1.0)
- `patch` → bug fixes (1.0.0 → 1.0.1)
- Description of your changes
1. Commit your changes.
2. Commit your changes and the generated `.changeset` file
3. Push your branch and create a PR on GitHub. Our CI will:
2. Push your branch and create a PR on GitHub. Our CI will:
- Run tests and checks
- Changesetbot will create a comment showing the version impact
- When merged to main, changesetbot will create a Version Packages PR
- When the Version Packages PR is merged, a new release will be published
4. Testing
3. Testing
- Run `npm run test` to run tests locally.
- Before submitting PR, run `npm run format:fix` to format your code
@@ -192,15 +178,10 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
- Temporary workspaces with test fixtures
- Video recording for failed tests
4. **Version Management with Changesets**
4. **Versioning & Changelog Notes**
- Create a changeset for any user-facing changes using `npm run changeset`
- Choose the appropriate version bump:
- `major` for breaking changes (1.0.0 → 2.0.0)
- `minor` for new features (1.0.0 → 1.1.0)
- `patch` for bug fixes (1.0.0 → 1.0.1)
- Write clear, descriptive changeset messages that explain the impact
- Documentation-only changes don't require changesets
- Contributors do not need to create changelog-entry files as part of PRs.
- Maintainers handle release versioning and changelog curation during the release process.
5. **Commit Guidelines**
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Cline Bot Inc.
Copyright 2026 Cline Bot Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+1 -1
View File
@@ -148,4 +148,4 @@ Get the same Cline experience with enterprise-grade controls: SSO (SAML/OIDC), g
## License
[Apache 2.0 © 2025 Cline Bot Inc.](./LICENSE)
[Apache 2.0 © 2026 Cline Bot Inc.](./LICENSE)
+27
View File
@@ -0,0 +1,27 @@
# Security Policy
## Supported Versions
We actively patch only the most recent minor release of Cline. Older versions receive fixes at our discretion.
## Reporting a Vulnerability
We appreciate your efforts to responsibly disclose your findings and will make every effort to acknowledge your contributions.
To report a security issue, please use the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/cline/cline/security/advisories/new) tab.
The team will send a response indicating the next steps in handling your report. After the initial reply, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
When reporting, please include:
- A short summary of the issue
- Steps to reproduce or a proof of concept
- Any logs, stack traces, or screenshots that might help us understand the problem
We acknowledge reports within 48 hours and aim to release a fix or mitigation within 30 days. While we work on a resolution, please keep the details private.
## Escalation
If you do not receive an acknowledgement of your report within 5 business days, you may send an email to security@cline.bot.
Thank you for helping us keep Cline users safe.
+76 -67
View File
@@ -1,5 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.1.4/schema.json",
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
@@ -28,19 +28,19 @@
"rules": {
"recommended": true,
"correctness": {
"useExhaustiveDependencies": "off",
"useExhaustiveDependencies": "info",
"noUndeclaredVariables": "off",
"noEmptyPattern": "off",
"noEmptyPattern": "info",
"useJsxKeyInIterable": "off",
"noInnerDeclarations": "off",
"useHookAtTopLevel": "off",
"useYield": "off",
"useHookAtTopLevel": "info",
"useYield": "info",
"noConstructorReturn": "off",
"noInvalidPositionAtImportRule": "off",
"noSwitchDeclarations": "off",
"noUnusedImports": "error"
},
"a11y": "off",
"a11y": "info",
"style": {
"useNodejsImportProtocol": "off",
"useImportType": "off",
@@ -51,35 +51,36 @@
"noParameterAssign": "off",
"useAsConstAssertion": "off",
"useDefaultParameterLast": "off",
"noNonNullAssertion": "off",
"noNonNullAssertion": "info",
"useEnumInitializers": "off",
"useSelfClosingElements": "off",
"useSelfClosingElements": "info",
"useSingleVarDeclarator": "off",
"useNumberNamespace": "off",
"noInferrableTypes": "off",
"useTemplate": "off",
"noUselessElse": "off"
"useNumberNamespace": "info",
"noInferrableTypes": "info",
"useTemplate": "info",
"noUselessElse": "info"
},
"suspicious": {
"noDoubleEquals": "warn",
"noImplicitAnyLet": "info",
"noThenProperty": "off",
"noAsyncPromiseExecutor": "off",
"noAsyncPromiseExecutor": "info",
"noImportAssign": "off",
"noExplicitAny": "off",
"noControlCharactersInRegex": "off",
"noExplicitAny": "info",
"noControlCharactersInRegex": "warn",
"noShadowRestrictedNames": "off",
"noArrayIndexKey": "info",
"noAssignInExpressions": "info"
"noAssignInExpressions": "info",
"useIterableCallbackReturn": "info"
},
"complexity": {
"noUselessConstructor": "off",
"useOptionalChain": "off",
"noBannedTypes": "off",
"useLiteralKeys": "off",
"noUselessCatch": "off",
"noUselessSwitchCase": "off",
"noStaticOnlyClass": "off"
"noUselessConstructor": "info",
"useOptionalChain": "info",
"noBannedTypes": "warn",
"useLiteralKeys": "info",
"noUselessCatch": "info",
"noUselessSwitchCase": "info",
"noStaticOnlyClass": "info"
},
"security": {
"noDangerouslySetInnerHtml": "info"
@@ -94,6 +95,11 @@
"lineEnding": "lf",
"formatWithErrors": true
},
"css": {
"parser": {
"tailwindDirectives": true
}
},
"javascript": {
"formatter": {
"semicolons": "asNeeded",
@@ -112,19 +118,21 @@
}
},
"files": {
"ignoreUnknown": true,
"includes": [
"**",
"!**/dist",
"!**/dist-*",
"!**/out",
"!**/evals",
"!**/playwright",
"!**/test-results",
"!**/node_modules",
"!**/webview-ui/build",
"!**/generated",
"!**/proto",
"!**/tests/specs"
// explicitly force files to be ignored by the scanner with !!
"!!**/dist",
"!!**/dist-*",
"!!**/out",
"!!**/evals",
"!!**/playwright",
"!!**/test-results",
"!!**/node_modules",
"!!**/webview-ui/build",
"!!**/generated",
"!!**/proto",
"!!**/tests/specs"
]
},
"plugins": [
@@ -134,14 +142,15 @@
{
"includes": [
"**",
"!**/hosts/vscode/**",
"!**/test/**",
"!**/*.test.ts",
"!src/dev/**",
"!src/extension.ts",
"!src/integrations/git/commit-message-generator.ts",
"!src/integrations/terminal/**",
"!src/core/controller/ui/openWalkthrough.ts"
"!!**/dist",
"!!**/hosts/vscode/**",
"!!**/test/**",
"!!**/*.test.ts",
"!!src/dev/**",
"!!src/extension.ts",
"!!src/integrations/git/commit-message-generator.ts",
"!!src/integrations/terminal/**",
"!!src/core/controller/ui/openWalkthrough.ts"
],
"plugins": [
"src/dev/grit/vscode-api.grit"
@@ -154,37 +163,37 @@
],
"includes": [
"**",
"!**/esbuild.*",
"!**/*.mts",
"!**/webview-ui/**",
"!**/evals/**",
"!**/standalone/**",
"!**/cli/**",
"!**/e2e/**",
"!**/test/**",
"!**/__tests__/**",
"!**/*.test.ts",
"!**/*.stories.ts",
"!src/dev/**",
"!**/*.mjs",
"!**/*.js",
"!**/scripts/**",
"!**/*.tsx",
"!**/testing-platform/**",
"!!**/esbuild.*",
"!!**/*.mts",
"!!**/webview-ui/**",
"!!**/evals/**",
"!!**/standalone/**",
"!!**/cli/**",
"!!**/e2e/**",
"!!**/test/**",
"!!**/__tests__/**",
"!!**/*.test.ts",
"!!**/*.stories.ts",
"!!src/dev/**",
"!!**/*.mjs",
"!!**/*.js",
"!!**/scripts/**",
"!!**/*.tsx",
"!!**/testing-platform/**",
// ACP mode must redirect console to stderr - this is intentional
"!cli/src/acp/index.ts"
"!!cli/src/acp/index.ts"
]
},
{
"includes": [
"**",
"!src/core/storage/state-migrations.ts",
"!src/core/storage/FileContextTracker.ts",
"!src/core/context/context-tracking/FileContextTracker.ts",
"!src/common.ts",
"!src/services/logging/distinctId.ts",
"!src/core/storage/utils/state-helpers.ts",
"!src/extension.ts"
"!!src/core/storage/state-migrations.ts",
"!!src/core/storage/FileContextTracker.ts",
"!!src/core/context/context-tracking/FileContextTracker.ts",
"!!src/common.ts",
"!!src/services/logging/distinctId.ts",
"!!src/core/storage/utils/state-helpers.ts",
"!!src/extension.ts"
],
"plugins": [
"src/dev/grit/use-cache-service.grit"
+242
View File
@@ -0,0 +1,242 @@
# cline
## [2.9.0]
### Added
- Latency improvements for remote workspaces
## [2.8.2]
### Fixed
- Use `kanban@latest` in `cline kanban` to always fetch the newest version
## [2.8.1]
### Added
- Implement dynamic free model detection for Cline API
- Add file read deduplication cache to prevent repeated reads
- Add feature tips tooltip during thinking state
### Fixed
- Fix flaky CLI Enter-key handling across Windows/test environments
- Replace error message when not logged in to Cline
- Align ClineRulesToggleModal padding with ServersToggleModal
- Skip WebP for GLM and Devstral models running through llama.cpp
- Respect user-configured context window in LiteLLM getModel()
- Honor explicit model IDs outside static catalog in W&B provider
- Add missing Fireworks serverless models and pricing
## [2.8.0]
### Added
- Added W&B Inference by CoreWeave as a new API provider with 17 models including DeepSeek-V3.1, Llama 4, and Qwen3-Coder
- Added CLI TUI end-to-end test suite
### Fixed
- Claude Code: handle rate limit events, empty content arrays, error results, and unknown content types without crashing
- CLI: `/q` and `/exit` slash commands now execute immediately on Enter without requiring the slash menu to be visible
- CLI: slash command filtering now prioritizes exact and prefix matches over fuzzy matches
## [2.7.0]
### Added
- Added MCP add shortcuts for stdio and HTTP servers
- Added `--continue` for the current directory
- Added `--auto-condense` flag for AI-powered context compaction
- Added `--hooks-dir` flag for runtime hook injection
- Enabled error autocapture
- Prompt rules now include test verification guidance and make `CLI_RULES` language-agnostic
### Fixed
- Fixed remount behavior so TUI remounts only on width resize
- Fixed startup prompt replay on resize remount
- Fixed task flags so they are applied before the welcome TUI mounts
### Changed
- Hooks: reintroduced feature toggle
## [2.6.1]
### Added
- Added GPT-5.4 models for ChatGPT subscription users
- Hooks: Added a `Notification` hook for attention and completion boundaries
- Added `--hooks-dir` CLI flag for runtime hook injection
- Added `--auto-approve-all` CLI flag for interactive mode
### Fixed
- Handle streamable HTTP MCP reconnects more reliably
## [2.6.0]
### Added
- Hook payloads now include `model.provider` and `model.slug`
- Token/cost updates now happen immediately as usage chunks arrive, not after tool execution
### Fixed
- Improve subagent context compaction logic
- Subagent stream retry delay increased to reduce noise from transient failures
- State serialization errors are now caught and logged instead of crashing
- Removed incorrect `max_tokens` from OpenRouter requests
## [2.5.2]
### Added
- Added Windows PowerShell support for hooks (execution, resolution, and management), improving hook behavior on Windows for CLI and shared core workflows.
### Fixed
- Restored GPT-OSS native file editing for OpenAI-compatible models used through shared core tooling.
- Improved OpenRouter context overflow error handling so auto-compaction triggers correctly for wrapped 400 errors.
- Hardened checkpoint recovery by retrying nested git restore and preventing silent `.git_disabled` leftovers.
- Added a User-Agent header for requests to the Cline back-end to improve request handling consistency.
## [2.5.1]
### Added
- Expanded CLI markdown rendering support (headings, lists, blockquotes, fenced code blocks, links, and nested lists).
### Fixed
- Fixed CLI headless auth provider model metadata loading for Cline and Vercel AI Gateway by fetching model info from API with cache fallback.
- Increased flaky CLI import test timeout on Windows CI to reduce intermittent test failures.
## [2.5.0]
### Added
- Added Cline SDK API interface for programmatic access to Cline features and tools, enabling integration into custom applications.
- Added Codex 5.3 model support
### Fixed
- Fix OpenAI Codex by setting `store` to `false`
- Use `isLocatedInPath()` instead of string matching for path containment checks
## [2.4.3]
### Added
- Add /q command to quit CLI
- Fetch featured models from backend with local fallback
### Fixed
- Fix auth check for ACP mode
- Fix Cline auth with ACP flag
- Fix yolo mode to not persist yolo setting to disk
## [2.4.2]
### Added
- Gemini-3.1 Pro Preview
### Patch Changes
- VSCode uses shared files for global, workspace and secret state.
## [2.4.1]
### Fixed
- Fix infinite retry loop when write_to_file fails with missing content parameter. Provides progressive guidance to the model, escalating from suggestions to hard stops, with context window awareness to break the loop.
## [2.4.0]
### Added
- Adding Anthropic Sonnet 4.6
- Allows users to enter custom aws region when selecting bedrock as a provider in CLI
- Keep reasoning rows visible when low-stakes tool groups start immediately after reasoning.
- Restore reasoning trace visibility in chat and improve the thinking row UX so streamed reasoning is visible, then collapsible after completion.
### Fixed
- Banners now display immediately when opening the extension instead of requiring user interaction first
- Resolved 17 security vulnerabilities including high-severity DoS issues in dependencies (body-parser, axios, qs, tar, and others)
## [2.2.2]
- Allows users to enter custom aws region when selecting bedrock as a provider
- Prevent Parent Container Scrolling In Dropdowns
## [2.2.1]
- Added Minimax 2.5 Free Promo
- Fixed Response chaining for OpenAI's Responses API
## [2.2.0]
### Added
- Subagent: replace legacy subagents with the native `use_subagents` tool
- Bundle `endpoints.json` support so packaged distributions can ship required endpoints out-of-the-box
- Amazon Bedrock: support parallel tool calling
- New "double-check completion" experimental feature to verify work before marking tasks complete
- CLI: new task controls/flags including custom `--thinking` token budget and `--max-consecutive-mistakes` for yolo runs
- Remote config: new UI/options (including connection/test buttons) and support for syncing deletion of remotely configured MCP servers
- Vertex / Claude Code: add 1M context model options for Claude Opus 4.6
- ZAI/GLM: add GLM-5
### Fixed
- CLI: handle stdin redirection correctly in CI/headless environments
- CLI: preserve OAuth callback paths during auth redirects
- VS Code Web: generate auth callback URLs via `vscode.env.asExternalUri` (OAuth callback reliability)
- Terminal: surface command exit codes in results and improve long-running `execute_command` timeout behavior
- UI: add loading indicator and fix `api_req_started` rendering
- Task streaming: prevent duplicate streamed text rows after completion
- API: preserve selected Vercel model when model metadata is missing
- Telemetry: route PostHog networking through proxy-aware shared fetch and ensure telemetry flushes on shutdown
- CI: increase Windows E2E test timeout to reduce flakiness
### Changed
- Settings/model UX: move "reasoning effort" into model configuration and expose it in settings
- CLI provider selection: limit provider list to those remotely configured
- UI: consolidate ViewHeader component/styling across views
- Tools: add auto-approval support for `attempt_completion` commands
- Remotely configured MCP server schema now supports custom headers
## [2.1.0]
### Minor Changes
- 42ce100: Add Generate API Key on Hicap Provider selection
### Patch Changes
- 195294f: Add support for bundled endpoints.json in enterprise distributions. Extensions can now include a pre-configured endpoints.json file that automatically switches Cline to self-hosted mode. Includes packaging scripts for VSIX, NPM, and JetBrains plugins.
- a1f2601: Replace the LiteLLM model list with a selector
- 739d75a: Add Claude Code provider support for Claude Opus 4.6 and Sonnet 4.5 1M variants via both full model names and aliases (`opus[1m]`, `sonnet[1m]`), and align the `opus` alias with Opus 4.6.
- 8440380: Add GitHub Actions workflow to build CLI from any commit for testing
- b1a8db2: fix(cli): prevent hang when spawned without TTY
- 7c87017: Add Claude Opus 4.6 model support
- d116ac5: Supports rendering markdown table in chat view.
- 6d8fb85: Fix CLI crashing in CI environments and with stdin redirection (e.g., `cline "prompt" < /dev/null`). Now checks both stdin and stdout TTY status before using Ink, and only errors on empty stdin when no prompt is provided.
- 70a9904: Fix JetBrains sign-in regression by adding fallback for openExternal RPC
- f440f3a: fix: use vscode.env.openExternal for auth in remote environments
Fixes OAuth authentication in VS Code Server and remote environments by routing browser URL opening through VS Code's native openExternal API instead of the npm 'open' package.
- 70a9904: fix: use vscode.env.asExternalUri for auth callback URLs only in VS Code Web
Fixes OAuth callback redirect in VS Code Web (`code serve-web`, Codespaces) by using `vscode.env.asExternalUri()` to resolve the callback URI. This is gated behind a `vscode.env.uiKind === UIKind.Web` check so regular desktop VS Code continues to use the `vscode://` URI directly. The `getCallbackUrl` API now accepts a `path` parameter so the full callback URI (including route) is resolved correctly, and callers pass their path directly instead of appending after.
- 5308ded: Updating script documentation and removing unnecessary continue on error
- b514f18: Prevent duplicate streamed text rows when a partial text update arrives after the same text was already finalized.
- 26391c9: Fix Bedrock model id
- d19a877: Unify ViewHeader Styles Across All Views
- 5dcaa8c: Add Vertex Claude Opus 4.6 1M model option and global endpoint support, and pass the 1M beta header for Vertex Claude requests.
+1 -2
View File
@@ -45,7 +45,7 @@ cline
### Use any API and Model
Cline supports API providers like ChatGPT, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras and Groq. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using a Cline Account, you'll always have access to the newest models as soon as they're available.
Cline supports API providers like ChatGPT, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras, Groq, and Moonshot. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using a Cline Account, you'll always have access to the newest models as soon as they're available.
<!-- Transparent pixel to create line break after floating image -->
@@ -79,4 +79,3 @@ Get the same Cline experience with enterprise-grade controls: SSO (SAML/OIDC), g
## License
[Apache 2.0 © 2026 Cline Bot Inc.](./LICENSE)
+42 -10
View File
@@ -186,6 +186,7 @@ const buildEnvVars: Record<string, string> = {
const buildTimeEnvs = [
"TELEMETRY_SERVICE_API_KEY",
"ERROR_SERVICE_API_KEY",
"ENABLE_ERROR_AUTOCAPTURE",
"POSTHOG_TELEMETRY_ENABLED",
"OTEL_TELEMETRY_ENABLED",
"OTEL_LOGS_EXPORTER",
@@ -208,8 +209,8 @@ if (production) {
buildEnvVars["process.env.IS_DEV"] = "false"
}
const config: esbuild.BuildOptions = {
entryPoints: [path.join(__dirname, "src", "index.ts")],
// Shared build options
const sharedOptions: Partial<esbuild.BuildOptions> = {
bundle: true,
minify: production,
sourcemap: !production,
@@ -221,7 +222,6 @@ const config: esbuild.BuildOptions = {
sourcesContent: false,
platform: "node",
target: "node20",
outfile: path.join(__dirname, "dist", "cli.mjs"),
// These modules need to load files from the module directory at runtime
external: [
"@grpc/reflection",
@@ -237,6 +237,13 @@ const config: esbuild.BuildOptions = {
"@vscode/ripgrep", // Uses __dirname to locate the binary
],
supported: { "top-level-await": true },
}
// CLI executable configuration
const cliConfig: esbuild.BuildOptions = {
...sharedOptions,
entryPoints: [path.join(__dirname, "src", "index.ts")],
outfile: path.join(__dirname, "dist", "cli.mjs"),
banner: {
js: `#!/usr/bin/env node
// Suppress all Node.js warnings (deprecation, experimental, etc.)
@@ -250,19 +257,44 @@ const __dirname = _dirname(__filename);`,
},
}
// Library configuration for programmatic use
const libConfig: esbuild.BuildOptions = {
...sharedOptions,
entryPoints: [path.join(__dirname, "src", "exports.ts")],
outfile: path.join(__dirname, "dist", "lib.mjs"),
banner: {
js: `// Cline Library - Programmatic API
import { createRequire as _createRequire } from 'module';
import { fileURLToPath as _fileURLToPath } from 'url';
import { dirname as _dirname } from 'path';
const require = _createRequire(import.meta.url);
const __filename = _fileURLToPath(import.meta.url);
const __dirname = _dirname(__filename);`,
},
}
async function main() {
const ctx = await esbuild.context(config)
if (watch) {
// In watch mode, only watch the CLI (primary use case for development)
const ctx = await esbuild.context(cliConfig)
await ctx.watch()
console.log("[cli] Watching for changes...")
} else {
await ctx.rebuild()
await ctx.dispose()
// Build both CLI and library
console.log("[cli esbuild] Building CLI executable...")
const cliCtx = await esbuild.context(cliConfig)
await cliCtx.rebuild()
await cliCtx.dispose()
// Make the output executable
const outfile = path.join(__dirname, "dist", "cli.mjs")
if (fs.existsSync(outfile)) {
fs.chmodSync(outfile, "755")
console.log("[cli esbuild] Building library bundle...")
const libCtx = await esbuild.context(libConfig)
await libCtx.rebuild()
await libCtx.dispose()
// Make the CLI output executable
const cliOutfile = path.join(__dirname, "dist", "cli.mjs")
if (fs.existsSync(cliOutfile)) {
fs.chmodSync(cliOutfile, "755")
}
}
}
+43 -15
View File
@@ -88,6 +88,10 @@ directory
\f[B]\-\-thinking\f[R] : Enable extended thinking (1024 token budget)
.PP
\f[B]\-\-json\f[R] : Output messages as JSON instead of styled text
.PP
\f[B]\-T\f[R], \f[B]\-\-taskId\f[R] \f[I]id\f[R] : Resume an existing
task by ID.
The prompt argument becomes an optional follow\-up message.
.SS history (alias: h)
List task history with pagination.
.PP
@@ -121,13 +125,13 @@ authentication wizard, or use quick setup flags.
Options:
.PP
\f[B]\-p\f[R], \f[B]\-\-provider\f[R] \f[I]id\f[R] : Provider ID for
quick setup (e.g., openai\-native, anthropic, openrouter)
quick setup (e.g., openai\-native, anthropic, openrouter, moonshot)
.PP
\f[B]\-k\f[R], \f[B]\-\-apikey\f[R] \f[I]key\f[R] : API key for the
provider
.PP
\f[B]\-m\f[R], \f[B]\-\-modelid\f[R] \f[I]id\f[R] : Model ID to
configure (e.g., gpt\-4o, claude\-sonnet\-4\-5\-20250929)
configure (e.g., gpt\-4o, claude\-sonnet\-4\-5\-20250929, kimi\-k2.5)
.PP
\f[B]\-b\f[R], \f[B]\-\-baseurl\f[R] \f[I]url\f[R] : Base URL (optional,
for OpenAI\-compatible providers)
@@ -179,6 +183,10 @@ the task
.PP
\f[B]\-\-json\f[R] : Output messages as JSON instead of styled text.
Forces plain text mode.
.PP
\f[B]\-T\f[R], \f[B]\-\-taskId\f[R] \f[I]id\f[R] : Resume an existing
task by ID instead of starting a new one.
The prompt becomes an optional follow\-up message.
.SH JSON OUTPUT FORMAT
When using \f[B]\-\-json\f[R], each message is output as a JSON object
with these fields:
@@ -234,6 +242,9 @@ cline \-m claude\-sonnet\-4\-5\-20250929 \(dqRefactor this function\(dq
\f[I]# Quick auth setup with model\f[R]
cline auth \-p anthropic \-k sk\-ant\-xxxxx \-m claude\-sonnet\-4\-5\-20250929
\f[I]# Quick auth setup for Moonshot\f[R]
cline auth \-p moonshot \-k sk\-xxxxx \-m kimi\-k2.5
.EE
.SS Including Images
.IP
@@ -274,6 +285,21 @@ cline history
\f[I]# Show more tasks with pagination\f[R]
cline history \-n 20 \-p 2
.EE
.SS Resuming Tasks
.IP
.EX
\f[I]# Resume a task by ID (get IDs from cline history)\f[R]
cline \-T abc123def
\f[I]# Resume a task with a follow\-up message\f[R]
cline \-T abc123def \(dqNow add unit tests for the changes\(dq
\f[I]# Resume in plan mode to review before continuing\f[R]
cline \-T abc123def \-p \(dqWhat\(aqs left to do?\(dq
\f[I]# Resume with yolo mode for automated continuation\f[R]
cline \-T abc123def \-y \(dqContinue with the implementation\(dq
.EE
.SS Authentication
.IP
.EX
@@ -286,6 +312,9 @@ cline auth \-p anthropic \-k sk\-ant\-api\-xxxxx
\f[I]# Quick setup for OpenAI\f[R]
cline auth \-p openai\-native \-k sk\-xxxxx \-m gpt\-4o
\f[I]# Quick setup for Moonshot\f[R]
cline auth \-p moonshot \-k sk\-xxxxx \-m kimi\-k2.5
\f[I]# OpenAI\-compatible provider with custom base URL\f[R]
cline auth \-p openai \-k your\-api\-key \-b https://api.example.com/v1
.EE
@@ -348,20 +377,19 @@ export CLINE_COMMAND_PERMISSIONS=\(aq{\(dqallow\(dq: [\(dqnpm *\(dq, \(dqgit *\(
\f[I]# Allow file operations with redirects\f[R]
export CLINE_COMMAND_PERMISSIONS=\(aq{\(dqallow\(dq: [\(dqcat *\(dq, \(dqecho *\(dq], \(dqallowRedirects\(dq: true}\(aq
.EE
.SH FILES
\f[B]\(ti/.cline/data/\f[R] : Default configuration directory
containing:
.SH CONFIGURATION FILES
.IP
.EX
\(ti/.cline/
├── data/ # Default configuration directory
│ ├── globalState.json # Global settings and state
│ ├── secrets.json # API keys and secrets (stored securely)
│ ├── workspace/ # Workspace\-specific state
│ └── tasks/ # Task history and conversation data
└── log/ # Log files for debugging
.EE
.PP
\f[B]globalState.json\f[R] : Global settings and state
.PP
\f[B]secrets.json\f[R] : API keys and secrets (stored securely)
.PP
\f[B]workspace/\f[R] : Workspace\-specific state
.PP
\f[B]tasks/\f[R] : Task history and conversation data
.PP
\f[B]\(ti/.cline/log/\f[R] : Log files for debugging.
View with \f[CR]cline dev log\f[R].
View logs with \f[CR]cline dev log\f[R].
.SH BUGS
Report bugs at: \c
.UR https://github.com/cline/cline/issues
+29
View File
@@ -56,6 +56,8 @@ Run a new task with a prompt.
**-y**, **\--yolo** : Enable yolo/yes mode (auto-approve all actions, output in plain mode, exit process automatically when task complete)
**-t**, **\--timeout** *seconds* : Optional timeout in seconds. Only applied when explicitly provided.
**-m**, **\--model** *model* : Model to use for the task
**-i**, **\--images** *paths...* : Image file paths to include with the task
@@ -70,6 +72,8 @@ Run a new task with a prompt.
**\--json** : Output messages as JSON instead of styled text
**-T**, **\--taskId** *id* : Resume an existing task by ID. The prompt argument becomes an optional follow-up message.
## history (alias: h)
List task history with pagination.
@@ -142,6 +146,8 @@ When running **cline** with just a prompt (no subcommand), these options are ava
**-y**, **\--yolo** : Enable yolo mode (auto-approve all actions). Also forces plain text output mode.
**-t**, **\--timeout** *seconds* : Optional timeout in seconds. Only applied when explicitly provided.
**-m**, **\--model** *model* : Model to use for the task
**-v**, **\--verbose** : Show verbose output
@@ -154,6 +160,10 @@ When running **cline** with just a prompt (no subcommand), these options are ava
**\--json** : Output messages as JSON instead of styled text. Forces plain text mode.
**-T**, **\--taskId** *id* : Resume an existing task by ID instead of starting a new one. The prompt becomes an optional follow-up message.
**\--continue** : Resume the most recent task from the current working directory instead of starting a new one.
# JSON OUTPUT FORMAT
When using **\--json**, each message is output as a JSON object with these fields:
@@ -251,6 +261,25 @@ cline history
cline history -n 20 -p 2
```
## Resuming Tasks
```bash
# Resume a task by ID (get IDs from cline history)
cline -T abc123def
# Resume a task with a follow-up message
cline -T abc123def "Now add unit tests for the changes"
# Resume the most recent task from the current directory
cline --continue
# Resume in plan mode to review before continuing
cline -T abc123def -p "What's left to do?"
# Resume with yolo mode for automated continuation
cline -T abc123def -y "Continue with the implementation"
```
## Authentication
```bash
-2950
View File
File diff suppressed because it is too large Load Diff
+25 -7
View File
@@ -1,26 +1,42 @@
{
"name": "cline",
"version": "2.0.1",
"version": "2.11.0",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"main": "dist/cli.mjs",
"main": "dist/lib.mjs",
"types": "dist/lib.d.ts",
"bin": {
"cline": "./dist/cli.mjs"
},
"exports": {
".": {
"import": "./dist/lib.mjs",
"types": "./dist/lib.d.ts"
}
},
"os": [
"darwin",
"linux",
"win32"
],
"cpu": [
"x64",
"arm64"
],
"man": "./man/cline.1",
"type": "module",
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"prepublishOnly": "npm run build:production",
"package:brew": "npx tsx ./scripts/update-brew-formula.mts",
"package": "npm pack --pack-destination ./dist",
"build": "npx tsx esbuild.mts",
"build:production": "npx tsx esbuild.mts --production",
"build": "npm run typecheck && npx tsx esbuild.mts && npm run build:types",
"build:production": "npm run typecheck && npx tsx esbuild.mts --production && npm run build:types",
"build:types": "(npx tsc -p tsconfig.lib.json || true) && cp dist/types/cli/src/exports.d.ts dist/lib.d.ts && mkdir -p dist/agent && cp dist/types/cli/src/agent/ClineAgent.d.ts dist/types/cli/src/agent/ClineSessionEmitter.d.ts dist/types/cli/src/agent/public-types.d.ts dist/agent/ && rm -rf dist/types",
"watch": "npx tsx esbuild.mts --watch",
"dev": "IS_DEV=true && npm run link && npm run watch ; npm run unlink",
"clean": "rimraf dist",
"typecheck": "tsc --noEmit",
"typecheck": "npx tsc --noEmit",
"link": "npm run build && npm link",
"unlink": "npm unlink -g cline",
"test": "vitest",
@@ -54,6 +70,7 @@
"url": "https://github.com/cline/cline/issues"
},
"devDependencies": {
"@types/marked": "^5.0.2",
"@types/node": "20.x",
"@types/prompts": "^2.4.9",
"@types/react": "^19.2.9",
@@ -73,8 +90,9 @@
"ink": "npm:@jrichman/ink@6.4.7",
"ink-picture": "^1.3.3",
"ink-spinner": "^5.0.0",
"ora": "^8.0.1",
"marked": "^17.0.3",
"nanoid": "^5.1.6",
"ora": "^8.0.1",
"pino": "^10.0.0",
"pino-roll": "^4.0.0",
"prompts": "^2.4.2",
+12 -6
View File
@@ -108,11 +108,7 @@ class ACPDiffServiceClient implements DiffServiceClientInterface {
class ACPEnvServiceClient implements EnvServiceClientInterface {
private readonly version: string
constructor(
_clientCapabilities: acp.ClientCapabilities | undefined,
_sessionIdResolver: SessionIdResolver,
version: string = "1.0.0",
) {
constructor(_clientCapabilities: acp.ClientCapabilities | undefined, _sessionIdResolver: SessionIdResolver, version: string) {
this.version = version
}
@@ -172,6 +168,16 @@ class ACPEnvServiceClient implements EnvServiceClientInterface {
Logger.debug("[ACPEnvServiceClient] shutdown called (stub)")
return proto.cline.Empty.create()
}
async openExternal(request: proto.cline.StringRequest): Promise<proto.cline.Empty> {
const url = request.value || ""
if (url) {
Logger.debug(`[ACPEnvServiceClient] openExternal: ${url}`)
const { openUrlInBrowser } = await import("../utils/browser")
await openUrlInBrowser(url)
}
return proto.cline.Empty.create()
}
}
/**
@@ -392,7 +398,7 @@ export class ACPHostBridgeClientProvider implements HostBridgeClientProvider {
clientCapabilities: acp.ClientCapabilities | undefined,
sessionIdResolver: SessionIdResolver,
cwdResolver: CwdResolver,
version: string = "1.0.0",
version: string,
) {
this.workspaceClient = new ACPWorkspaceServiceClient(clientCapabilities, sessionIdResolver, cwdResolver)
this.envClient = new ACPEnvServiceClient(clientCapabilities, sessionIdResolver, version)
+5 -21
View File
@@ -15,7 +15,7 @@
import type * as acp from "@agentclientprotocol/sdk"
import { Logger } from "@/shared/services/Logger.js"
import { ClineAgent } from "../agent/ClineAgent.js"
import type { AcpAgentOptions, SessionUpdateType } from "../agent/types.js"
import { type AcpAgentOptions, type SessionUpdateType } from "../agent/types.js"
/**
* ACP Agent wrapper that bridges stdio connection to ClineAgent.
@@ -39,37 +39,21 @@ export class AcpAgent implements acp.Agent {
this.clineAgent = new ClineAgent(options)
// Wire up the permission handler to use the connection
this.clineAgent.setPermissionHandler(async (request, resolve) => {
this.clineAgent.setPermissionHandler(async (request) => {
try {
Logger.debug("[AcpAgent] Forwarding permission request to connection")
const response = await this.connection.requestPermission({
sessionId: this.getCurrentSessionId() ?? "",
return await this.connection.requestPermission({
sessionId: request.sessionId,
toolCall: request.toolCall,
options: request.options,
})
resolve(response)
} catch (error) {
Logger.debug("[AcpAgent] Error requesting permission:", error)
resolve({ outcome: "rejected" as unknown as acp.RequestPermissionOutcome })
return { outcome: { outcome: "cancelled" } }
}
})
}
/**
* Get the current active session ID from the ClineAgent.
*/
private getCurrentSessionId(): string | undefined {
// Find the session that's currently processing
for (const [sessionId, session] of this.clineAgent.sessions) {
if (session.controller?.task) {
return sessionId
}
}
// Fall back to the first session if none is actively processing
const firstSession = this.clineAgent.sessions.keys().next()
return firstSession.done ? undefined : firstSession.value
}
/**
* Subscribe to session events and forward them to the connection.
*/
+10 -28
View File
@@ -12,11 +12,7 @@
import type * as acp from "@agentclientprotocol/sdk"
import type { TerminalHandle } from "@agentclientprotocol/sdk"
import {
DEFAULT_SUBAGENT_TERMINAL_OUTPUT_LINE_LIMIT,
DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT,
PROCESS_HOT_TIMEOUT_NORMAL,
} from "@integrations/terminal/constants"
import { DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT, PROCESS_HOT_TIMEOUT_NORMAL } from "@integrations/terminal/constants"
import type {
ITerminal,
ITerminalManager,
@@ -142,12 +138,12 @@ export interface ManagedTerminal {
* Wraps ACP terminal operations and emits events compatible with ITerminalProcess.
*/
class AcpTerminalProcess extends EventEmitter<TerminalProcessEvents> implements ITerminalProcess {
isHot: boolean = false
waitForShellIntegration: boolean = false
isHot = false
waitForShellIntegration = false
private _unretrievedOutput: string = ""
private _continued: boolean = false
private _completed: boolean = false
private _unretrievedOutput = ""
private _continued = false
private _completed = false
private _hotTimeout: NodeJS.Timeout | null = null
private _exitWaitTimeout: NodeJS.Timeout | null = null
private readonly manager: AcpTerminalManager
@@ -397,7 +393,7 @@ export class AcpTerminalManager implements ITerminalManager {
private readonly numericIdToStringId: Map<number, string> = new Map()
/** Next numeric ID to assign */
private nextNumericId: number = 1
private nextNumericId = 1
/** Active processes indexed by numeric terminal ID */
private readonly processes: Map<number, AcpTerminalProcess> = new Map()
@@ -406,9 +402,8 @@ export class AcpTerminalManager implements ITerminalManager {
private readonly terminalInfos: Map<number, TerminalInfo> = new Map()
// Configuration options for ITerminalManager
private terminalReuseEnabled: boolean = true
private terminalReuseEnabled = true
private terminalOutputLineLimit: number = DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT
private subagentTerminalOutputLineLimit: number = DEFAULT_SUBAGENT_TERMINAL_OUTPUT_LINE_LIMIT
/**
* Creates a new AcpTerminalManager.
@@ -667,14 +662,6 @@ export class AcpTerminalManager implements ITerminalManager {
this.terminalOutputLineLimit = limit
}
/**
* Set the maximum number of output lines for subagent commands.
* @param limit Maximum number of lines
*/
setSubagentTerminalOutputLineLimit(limit: number): void {
this.subagentTerminalOutputLineLimit = limit
}
/**
* Set the default terminal profile.
* @param profile The profile identifier
@@ -687,15 +674,10 @@ export class AcpTerminalManager implements ITerminalManager {
* Process output lines, potentially truncating if over limit.
* @param outputLines Array of output lines
* @param overrideLimit Optional limit override
* @param isSubagentCommand Whether this is a subagent command
* @returns Processed output string
*/
processOutput(outputLines: string[], overrideLimit?: number, isSubagentCommand?: boolean): string {
const limit = isSubagentCommand
? overrideLimit !== undefined
? overrideLimit
: this.subagentTerminalOutputLineLimit
: this.terminalOutputLineLimit
processOutput(outputLines: string[], overrideLimit?: number): string {
const limit = overrideLimit !== undefined ? overrideLimit : this.terminalOutputLineLimit
if (outputLines.length > limit) {
const halfLimit = Math.floor(limit / 2)
+3 -5
View File
@@ -15,22 +15,18 @@
import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk"
import { Logger } from "@/shared/services/Logger"
import { version as CLI_VERSION } from "../../../package.json"
import { AcpAgent } from "./AcpAgent.js"
import { nodeToWebReadable, nodeToWebWritable } from "./streamUtils.js"
// Re-export classes for programmatic use
export { ClineAgent } from "../agent/ClineAgent.js"
export { ClineSessionEmitter } from "../agent/ClineSessionEmitter.js"
// Re-export types
export type {
AcpAgentOptions,
AcpSessionState,
ClineAcpSession,
ClineAgentOptions,
ClineSessionEvents,
PermissionHandler,
PermissionResolver,
} from "../agent/types.js"
export { AcpAgent } from "./AcpAgent.js"
@@ -73,6 +69,8 @@ export interface AcpModeOptions {
config?: string
/** Working directory (default: process.cwd()) */
cwd?: string
/** Additional runtime hooks directory */
hooksDir?: string
/** Enable verbose/debug logging to stderr */
verbose?: boolean
}
@@ -99,8 +97,8 @@ export async function runAcpMode(options: AcpModeOptions = {}): Promise<void> {
new AgentSideConnection((conn) => {
agent = new AcpAgent(conn, {
version: CLI_VERSION,
debug: Boolean(options.verbose),
hooksDir: options.hooksDir,
})
return agent
}, stream)
+61 -88
View File
@@ -28,6 +28,8 @@ import {
groqModels,
mistralDefaultModelId,
mistralModels,
moonshotDefaultModelId,
moonshotModels,
openAiCodexDefaultModelId,
openAiNativeDefaultModelId,
openAiNativeModels,
@@ -36,11 +38,11 @@ import {
} from "@shared/api"
import type { ClineAsk, ClineMessage as ClineMessageType } from "@shared/ExtensionMessage"
import { CLI_ONLY_COMMANDS, VSCODE_ONLY_COMMANDS } from "@shared/slashCommands"
import { ProviderToApiKeyMap } from "@shared/storage"
import { getProviderModelIdKey } from "@shared/storage/provider-keys"
import { ClineEndpoint } from "@/config.js"
import { Controller } from "@/core/controller"
import { getAvailableSlashCommands } from "@/core/controller/slash/getAvailableSlashCommands"
import { setRuntimeHooksDir } from "@/core/storage/disk"
import { StateManager } from "@/core/storage/StateManager"
import { AuthHandler } from "@/hosts/external/AuthHandler.js"
import { ExternalCommentReviewController } from "@/hosts/external/ExternalCommentReviewController.js"
@@ -51,18 +53,21 @@ import { openAiCodexOAuthManager } from "@/integrations/openai-codex/oauth"
import { StandaloneTerminalManager } from "@/integrations/terminal/index.js"
import { AuthService } from "@/services/auth/AuthService.js"
import { Logger } from "@/shared/services/Logger.js"
import { secretStorage } from "@/shared/storage/ClineSecretStorage"
import type { Mode } from "@/shared/storage/types"
import { openExternal } from "@/utils/env"
import { version as AGENT_VERSION } from "../../package.json"
import { ACPDiffViewProvider } from "../acp/ACPDiffViewProvider.js"
import { ACPHostBridgeClientProvider } from "../acp/ACPHostBridgeClientProvider.js"
import { AcpTerminalManager } from "../acp/AcpTerminalManager.js"
import { isAuthConfigured } from "../utils/auth"
import { fetchOpenRouterModels, usesOpenRouterModels } from "../utils/openrouter-models"
import { CliContextResult, initializeCliContext } from "../vscode-context.js"
import { ClineSessionEmitter } from "./ClineSessionEmitter.js"
import { translateMessage } from "./messageTranslator.js"
import { handlePermissionResponse } from "./permissionHandler.js"
import type { AcpSessionState, ClineAcpSession, ClineAgentOptions, PermissionHandler } from "./types.js"
import type { ClineAcpSession, ClineAgentOptions, PermissionHandler } from "./public-types.js"
import { AcpSessionStatus } from "./public-types.js"
import { type AcpSessionState } from "./types.js"
// Map providers to their static model lists and defaults (copied from ModelPicker.tsx)
const providerModels: Record<string, { models: Record<string, unknown>; defaultId: string }> = {
@@ -72,6 +77,7 @@ const providerModels: Record<string, { models: Record<string, unknown>; defaultI
bedrock: { models: bedrockModels, defaultId: bedrockDefaultModelId },
deepseek: { models: deepSeekModels, defaultId: deepSeekDefaultModelId },
mistral: { models: mistralModels, defaultId: mistralDefaultModelId },
moonshot: { models: moonshotModels, defaultId: moonshotDefaultModelId },
groq: { models: groqModels, defaultId: groqDefaultModelId },
xai: { models: xaiModels, defaultId: xaiDefaultModelId },
}
@@ -102,7 +108,12 @@ function getModelList(provider: string): string[] {
export class ClineAgent implements acp.Agent {
private readonly options: ClineAgentOptions
private readonly ctx: CliContextResult
readonly sessions: Map<string, ClineAcpSession> = new Map()
/** Map of active sessions by session ID */
public readonly sessions: Map<string, ClineAcpSession> = new Map()
/** WeakMap to associate ClineAcpSession with its Controller without exposing it to consumers */
readonly #sessionControllers = new WeakMap<ClineAcpSession, Controller>()
/** Runtime state for active sessions */
private readonly sessionStates: Map<string, AcpSessionState> = new Map()
@@ -130,7 +141,8 @@ export class ClineAgent implements acp.Agent {
constructor(options: ClineAgentOptions) {
this.options = options
this.ctx = initializeCliContext()
setRuntimeHooksDir(options.hooksDir)
this.ctx = initializeCliContext({ clineDir: options.clineDir })
}
/**
@@ -173,8 +185,8 @@ export class ClineAgent implements acp.Agent {
async initialize(params: acp.InitializeRequest, connection?: acp.AgentSideConnection): Promise<acp.InitializeResponse> {
this.clientCapabilities = params.clientCapabilities
this.initializeHostProvider(this.clientCapabilities, connection)
await ClineEndpoint.initialize()
await StateManager.initialize(this.ctx.extensionContext)
await ClineEndpoint.initialize(this.ctx.EXTENSION_DIR)
await StateManager.initialize(this.ctx.storageContext)
return {
protocolVersion: PROTOCOL_VERSION,
@@ -192,7 +204,7 @@ export class ClineAgent implements acp.Agent {
},
agentInfo: {
name: "cline",
version: this.options.version,
version: AGENT_VERSION,
},
authMethods: [
{
@@ -224,7 +236,7 @@ export class ClineAgent implements acp.Agent {
clientCapabilities,
() => this.currentActiveSessionId,
() => this.sessions.get(this.currentActiveSessionId ?? "")?.cwd ?? process.cwd(),
this.options.version,
AGENT_VERSION,
)
HostProvider.initialize(
@@ -246,8 +258,8 @@ export class ClineAgent implements acp.Agent {
},
hostBridgeClientProvider,
(message: string) => Logger.info(message),
async () => {
return AuthHandler.getInstance().getCallbackUrl()
async (path: string) => {
return AuthHandler.getInstance().getCallbackUrl(path)
},
async () => "", // get binary location not needed in ACP mode
this.ctx.EXTENSION_DIR,
@@ -263,7 +275,7 @@ export class ClineAgent implements acp.Agent {
*/
async newSession(params: acp.NewSessionRequest): Promise<acp.NewSessionResponse> {
// Check if authentication is required
const isAuthenticated = await this.isAuthConfigured()
const isAuthenticated = await isAuthConfigured()
if (!isAuthenticated) {
throw RequestError.authRequired()
}
@@ -287,16 +299,16 @@ export class ClineAgent implements acp.Agent {
mcpServers: params.mcpServers ?? [],
createdAt: Date.now(),
lastActivityAt: Date.now(),
controller,
}
this.#sessionControllers.set(session, controller)
this.sessions.set(sessionId, session)
// Initialize session state
const sessionState: AcpSessionState = {
sessionId,
isProcessing: false,
cancelled: false,
status: AcpSessionStatus.Idle,
pendingToolCalls: new Map(),
}
@@ -337,9 +349,7 @@ export class ClineAgent implements acp.Agent {
// Use provider-specific model ID key (e.g., cline uses actModeOpenRouterModelId)
const modelKey = currentProvider ? getProviderModelIdKey(currentProvider, mode) : null
const currentModelId = modelKey
? (stateManager.getGlobalSettingsKey(modelKey as string) as string | undefined)
: undefined
const currentModelId = modelKey ? stateManager.getGlobalSettingsKey(modelKey) : undefined
// Build the current model ID in provider/model format
const currentFullModelId =
@@ -435,11 +445,11 @@ export class ClineAgent implements acp.Agent {
*
* The prompt flow:
* 1. Extract content from the ACP prompt (text, images, files)
* 2. Set up state broadcasting (subscribe to controller updates)
* 3. Initialize or continue task with Controller
* 2. Set up internal cline state subsription
* 3. Initialize or continue cline task
* 4. Translate ClineMessages to ACP SessionUpdates
* 5. Handle permission requests for tools/commands
* 6. Return when task completes, is cancelled, or needs user input
* 6. Return when cline task completes, is cancelled, or needs user input
*/
async prompt(params: acp.PromptRequest): Promise<acp.PromptResponse> {
const session = this.sessions.get(params.sessionId)
@@ -449,11 +459,11 @@ export class ClineAgent implements acp.Agent {
throw new Error(`Session not found: ${params.sessionId}`)
}
if (sessionState.isProcessing) {
if (sessionState.status === AcpSessionStatus.Processing) {
throw new Error(`Session ${params.sessionId} is already processing a prompt`)
}
const controller = session.controller
const controller = this.#sessionControllers.get(session)
if (!controller) {
throw new Error("Controller not initialized for session. This is a bug in the ACP agent setup.")
}
@@ -464,8 +474,7 @@ export class ClineAgent implements acp.Agent {
})
// Mark session as processing and set as current active session
sessionState.isProcessing = true
sessionState.cancelled = false
sessionState.status = AcpSessionStatus.Processing
session.lastActivityAt = Date.now()
this.currentActiveSessionId = params.sessionId
@@ -586,7 +595,7 @@ export class ClineAgent implements acp.Agent {
Logger.debug("[ClineAgent] Error during cleanup:", error)
}
}
sessionState.isProcessing = false
sessionState.status = AcpSessionStatus.Idle
}
}
@@ -648,7 +657,13 @@ export class ClineAgent implements acp.Agent {
permissionRequest: Omit<acp.RequestPermissionRequest, "sessionId">,
): Promise<void> {
const session = this.sessions.get(sessionId)
const controller = session?.controller
if (!session) {
Logger.debug("[ClineAgent] No session found for permission request")
return
}
const controller = this.#sessionControllers.get(session)
if (!controller?.task) {
Logger.debug("[ClineAgent] No active task for permission request")
@@ -829,7 +844,7 @@ export class ClineAgent implements acp.Agent {
await this.emitSessionUpdate(sessionId, {
sessionUpdate,
content: { type: "text", text: needsNewline ? "\n" + textDelta : textDelta },
content: { type: "text", text: needsNewline ? `\n${textDelta}` : textDelta },
})
}
@@ -882,18 +897,22 @@ export class ClineAgent implements acp.Agent {
*/
async cancel(params: acp.CancelNotification): Promise<void> {
const session = this.sessions.get(params.sessionId)
if (!session) {
Logger.debug("[ClineAgent] cancel called for non-existent session:", params.sessionId)
return
}
const sessionState = this.sessionStates.get(params.sessionId)
Logger.debug("[ClineAgent] cancel called:", {
sessionId: params.sessionId,
isProcessing: sessionState?.isProcessing,
status: sessionState?.status,
})
if (sessionState) {
sessionState.cancelled = true
sessionState.status = AcpSessionStatus.Cancelled
// If we have an active controller task, cancel it
const controller = session?.controller
const controller = this.#sessionControllers.get(session)
if (controller?.task) {
try {
await controller.cancelTask()
@@ -934,7 +953,7 @@ export class ClineAgent implements acp.Agent {
session.lastActivityAt = Date.now()
// Update Controller mode if active
const controller = session.controller
const controller = this.#sessionControllers.get(session)
if (controller) {
controller.stateManager.setGlobalState("mode", session.mode)
@@ -975,7 +994,7 @@ export class ClineAgent implements acp.Agent {
// Get the callback URL first to ensure the server is ready
let callbackUrl: string
try {
callbackUrl = await authHandler.getCallbackUrl()
callbackUrl = await authHandler.getCallbackUrl("/auth")
Logger.debug("[ClineAgent] Callback URL ready:", callbackUrl)
} catch (error) {
Logger.error("[ClineAgent] Failed to get callback URL:", error)
@@ -1006,13 +1025,14 @@ export class ClineAgent implements acp.Agent {
const startTime = Date.now()
while (Date.now() - startTime < AUTH_TIMEOUT_MS) {
const stateManager = StateManager.get()
// Check if auth data has been stored
const authData = await secretStorage.get("cline:clineAccountId")
const authData = stateManager.getSecretKey("cline:clineAccountId")
if (authData) {
Logger.debug("[ClineAgent] Authentication successful")
// Set up the provider configuration for cline
const stateManager = StateManager.get()
stateManager.setGlobalState("actModeApiProvider", "cline")
stateManager.setGlobalState("planModeApiProvider", "cline")
await stateManager.flushPendingState()
@@ -1064,7 +1084,7 @@ export class ClineAgent implements acp.Agent {
* @returns The permission response from the client
*/
protected async requestPermission(
_sessionId: string,
sessionId: string,
toolCall: acp.ToolCallUpdate,
options: acp.PermissionOption[],
): Promise<acp.RequestPermissionResponse> {
@@ -1079,17 +1099,15 @@ export class ClineAgent implements acp.Agent {
return { outcome: "rejected" as unknown as acp.RequestPermissionOutcome }
}
// Use the permission handler callback pattern
return new Promise<acp.RequestPermissionResponse>((resolve) => {
this.permissionHandler!({ toolCall, options }, resolve)
})
return await this.permissionHandler({ sessionId, toolCall, options })
}
async shutdown(): Promise<void> {
for (const [sessionId, session] of this.sessions) {
await session.controller?.task?.abortTask()
await session.controller?.stateManager.flushPendingState()
await session.controller?.dispose()
const controller = this.#sessionControllers.get(session)
await controller?.task?.abortTask()
await controller?.stateManager.flushPendingState()
await controller?.dispose()
this.sessions.delete(sessionId)
this.sessionStates.delete(sessionId)
}
@@ -1145,48 +1163,6 @@ export class ClineAgent implements acp.Agent {
}
}
/**
* Check if the user has authentication configured.
* Returns true if they have either:
* - Cline provider with stored auth data
* - OpenAI Codex provider with OAuth credentials
* - BYO provider with an API key configured
*/
private async isAuthConfigured(): Promise<boolean> {
const stateManager = StateManager.get()
const mode = stateManager.getGlobalSettingsKey("mode") as string
const providerKey = mode === "act" ? "actModeApiProvider" : "planModeApiProvider"
const currentProvider = (stateManager.getGlobalSettingsKey(providerKey) as string) || "cline"
if (currentProvider === "cline") {
// For Cline provider, check if we have stored auth data
const authData = await secretStorage.get("cline:clineAccountId")
return !!authData
}
// For OpenAI Codex provider, check OAuth credentials
if (currentProvider === "openai-codex") {
openAiCodexOAuthManager.initialize(this.ctx.extensionContext)
return await openAiCodexOAuthManager.isAuthenticated()
}
// For BYO providers, check if the API key is configured
const keyField = ProviderToApiKeyMap[currentProvider as keyof typeof ProviderToApiKeyMap]
if (!keyField) {
return false
}
const fields = Array.isArray(keyField) ? keyField : [keyField]
for (const field of fields) {
const value = await secretStorage.get(field)
if (value) {
return true
}
}
return false
}
/**
* Handle OpenAI Codex OAuth authentication flow.
*
@@ -1200,9 +1176,6 @@ export class ClineAgent implements acp.Agent {
Logger.debug("[ClineAgent] Starting OpenAI Codex OAuth flow...")
try {
// Initialize the OAuth manager with extension context
openAiCodexOAuthManager.initialize(this.ctx.extensionContext)
// Get the authorization URL and start the callback server
const authUrl = openAiCodexOAuthManager.startAuthorizationFlow()
+1 -1
View File
@@ -8,7 +8,7 @@
*/
import { EventEmitter } from "events"
import type { ClineSessionEvents } from "./types.js"
import type { ClineSessionEvents } from "./public-types.js"
/**
* Type-safe EventEmitter for ClineAgent session events.
+4 -4
View File
@@ -12,6 +12,7 @@ import type { ClineMessage } from "@shared/ExtensionMessage"
import { beforeEach, describe, expect, it } from "vitest"
import { createSessionState, translateMessage, translateMessages } from "./messageTranslator"
import type { AcpSessionState } from "./types"
import { AcpSessionStatus } from "./types"
// =============================================================================
// Test Helpers
@@ -175,8 +176,7 @@ describe("createSessionState", () => {
const state = createSessionState("my-session-123")
expect(state.sessionId).toBe("my-session-123")
expect(state.isProcessing).toBe(false)
expect(state.cancelled).toBe(false)
expect(state.status).toBe(AcpSessionStatus.Idle)
expect(state.pendingToolCalls).toBeInstanceOf(Map)
expect(state.pendingToolCalls.size).toBe(0)
expect(state.currentToolCallId).toBeUndefined()
@@ -187,11 +187,11 @@ describe("createSessionState", () => {
const state2 = createSessionState("session-2")
// Modify state1
state1.isProcessing = true
state1.status = AcpSessionStatus.Processing
state1.pendingToolCalls.set("tool-1", {} as acp.ToolCall)
// state2 should be unaffected
expect(state2.isProcessing).toBe(false)
expect(state2.status).toBe(AcpSessionStatus.Idle)
expect(state2.pendingToolCalls.size).toBe(0)
})
})
+6 -2
View File
@@ -11,6 +11,7 @@
import type * as acp from "@agentclientprotocol/sdk"
import type { ClineMessage, ClineSayBrowserAction, ClineSayTool } from "@shared/ExtensionMessage"
import type { AcpSessionState, TranslatedMessage } from "./types.js"
import { AcpSessionStatus } from "./types.js"
/**
* Maps Cline tool types to ACP ToolKind values.
@@ -312,6 +313,10 @@ function translateSayMessage(
// API request finished - no specific update needed
break
case "subagent_usage":
// Hidden aggregate metrics event used for task-level accounting.
break
case "task":
// Task started - don't echo the user's prompt back to them
// The ACP client already knows what they typed
@@ -1015,8 +1020,7 @@ export function translateMessages(messages: ClineMessage[], sessionState: AcpSes
export function createSessionState(sessionId: string): AcpSessionState {
return {
sessionId,
isProcessing: false,
cancelled: false,
status: AcpSessionStatus.Idle,
pendingToolCalls: new Map(),
}
}
+258
View File
@@ -0,0 +1,258 @@
/**
* Public types for the Cline library API.
*
* This file contains types that are safe to export to library consumers.
* It must NOT import any internal types (Controller, StateManager, etc.)
* to keep the generated declaration files clean.
*
* Internal-only extensions of these types live in ./types.ts.
*/
import type * as acp from "@agentclientprotocol/sdk"
// ============================================================
// Session Update Type Utilities
// ============================================================
/**
* Different types of updates that can be sent during session processing.
*
* These updates provide real-time feedback about the agent's progress.
*
* See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)
*/
export type SessionUpdateType = acp.SessionUpdate["sessionUpdate"]
/**
* Different types of update payloads that can be sent during session processing.
*
* Each update type has a corresponding payload structure defined in the ACP SessionUpdate union.
*/
export type SessionUpdatePayload<T extends SessionUpdateType> = Omit<
Extract<acp.SessionUpdate, { sessionUpdate: T }>,
"sessionUpdate"
>
// ============================================================
// Permission Handler Callback Types
// ============================================================
/**
* Handler function for permission requests.
* Called when the agent needs permission for a tool call.
* The handler should present the request to the user and call resolve() with their response.
*/
export type PermissionHandler = (request: acp.RequestPermissionRequest) => Promise<acp.RequestPermissionResponse>
// ============================================================
// Session Event Emitter Types
// ============================================================
/**
* Maps ACP SessionUpdate types to their event listener signatures.
* Uses the sessionUpdate discriminator to derive event names and payload types.
*/
export type ClineSessionEvents = {
[K in SessionUpdateType]: (payload: SessionUpdatePayload<K>) => void
} & {
/** Error event for session-level errors (not part of ACP SessionUpdate) */
error: (error: Error) => void
}
// ============================================================
// ClineAgent Options
// ============================================================
/**
* Options for creating a ClineAgent instance.
*/
export interface ClineAgentOptions {
/** Whether debug logging is enabled */
debug?: boolean
/** Cline Config Directory (defaults to ~/.cline) */
clineDir?: string
/** Additional runtime hooks directory */
hooksDir?: string
}
/**
* Options for creating an ACP agent instance.
*/
export interface AcpAgentOptions {
/** Whether debug logging is enabled */
debug?: boolean
/** Additional runtime hooks directory */
hooksDir?: string
}
// ============================================================
// Session Types
// ============================================================
export type SessionID = string
/**
* Extended session data stored by Cline for ACP sessions.
*/
export interface ClineAcpSession {
/** Unique session ID */
sessionId: SessionID
/** Working directory for the session */
cwd: string
/** Current mode (plan/act) */
mode: "plan" | "act"
/** MCP servers passed from the client */
mcpServers: acp.McpServer[]
/** Timestamp when session was created */
createdAt: number
/** Timestamp of last activity */
lastActivityAt: number
/** Whether this session was loaded from history (needs resume on first prompt) */
isLoadedFromHistory?: boolean
/** Model ID override for plan mode (format: "provider/modelId") */
planModeModelId?: string
/** Model ID override for act mode (format: "provider/modelId") */
actModeModelId?: string
}
/**
* Lifecycle status of an ACP session.
*
* Represents the state machine:
* Idle → Processing → Idle (normal completion)
* Idle → Processing → Cancelled (cancellation, then back to Idle on next prompt)
*/
export enum AcpSessionStatus {
/** Session is idle, waiting for a prompt */
Idle = "idle",
/** Session is actively processing a prompt */
Processing = "processing",
/** Session processing was cancelled */
Cancelled = "cancelled",
}
/**
* State tracking for an active ACP session within Cline.
*/
export interface AcpSessionState {
/** Session ID */
sessionId: SessionID
/** Current lifecycle status of the session */
status: AcpSessionStatus
/** Current tool call ID being executed (if any) */
currentToolCallId?: string
/** Accumulated tool calls for permission batching */
pendingToolCalls: Map<string, acp.ToolCall>
}
// ============================================================
// Agent Capabilities
// ============================================================
/**
* Cline-specific agent capabilities extending the ACP base capabilities.
*/
export interface ClineAgentCapabilities {
/** Support for loading sessions from disk */
loadSession: boolean
/** Prompt capabilities for the agent */
promptCapabilities: {
/** Support for image inputs */
image: boolean
/** Support for audio inputs */
audio: boolean
/** Support for embedded context (file resources) */
embeddedContext: boolean
}
/** MCP server passthrough capabilities */
mcpCapabilities: {
/** Support for HTTP MCP servers */
http: boolean
/** Support for SSE MCP servers */
sse: boolean
}
}
/**
* Cline agent info for ACP initialization response.
*/
export interface ClineAgentInfo {
name: "cline"
title: "Cline"
version: string
}
// ============================================================
// Permission Options
// ============================================================
/**
* Permission option as presented to the ACP client.
*/
export interface ClinePermissionOption {
kind: acp.PermissionOptionKind
name: string
optionId: string
}
// ============================================================
// Message Translation
// ============================================================
/**
* Result of translating a Cline message to ACP session update(s).
* A single Cline message may produce multiple ACP updates.
*/
export interface TranslatedMessage {
/** The session updates to send */
updates: acp.SessionUpdate[]
/** Whether this message requires a permission request */
requiresPermission?: boolean
/** Permission request details if required */
permissionRequest?: Omit<acp.RequestPermissionRequest, "sessionId">
/** The toolCallId that was created/used (for tracking across streaming updates) */
toolCallId?: string
}
// ============================================================
// Re-exported ACP Types
// ============================================================
export type {
Agent,
AgentSideConnection,
AudioContent,
CancelNotification,
ClientCapabilities,
ContentBlock,
ImageContent,
InitializeRequest,
InitializeResponse,
LoadSessionRequest,
LoadSessionResponse,
McpServer,
ModelInfo,
NewSessionRequest,
NewSessionResponse,
PermissionOption,
PermissionOptionKind,
PromptRequest,
PromptResponse,
RequestPermissionRequest,
RequestPermissionResponse,
SessionConfigOption,
SessionModelState,
SessionNotification,
SessionUpdate,
SetSessionConfigOptionRequest,
SetSessionConfigOptionResponse,
SetSessionModelRequest,
SetSessionModelResponse,
SetSessionModeRequest,
SetSessionModeResponse,
StopReason,
TextContent,
ToolCall,
ToolCallStatus,
ToolCallUpdate,
ToolKind,
} from "@agentclientprotocol/sdk"
+20 -199
View File
@@ -1,76 +1,13 @@
/**
* Custom types and extensions for ACP integration with Cline CLI.
* Internal types for ACP integration with Cline CLI.
*
* This file extends the base ACP types with Cline-specific functionality.
* This file re-exports all public types from ./public-types.ts and adds
* internal-only Types that reference core modules (Controller, etc.).
*
* Library consumers should never import from this file directly — they
* get the public types via the library entrypoint (exports.ts).
*/
import type * as acp from "@agentclientprotocol/sdk"
import type { Controller } from "@/core/controller"
// ============================================================
// Session Update Type Utilities
// ============================================================
/**
* Extract the sessionUpdate discriminator value from a SessionUpdate variant.
*/
export type SessionUpdateType = acp.SessionUpdate["sessionUpdate"]
/**
* Extract the payload type for a given sessionUpdate discriminator value.
* This removes the `sessionUpdate` discriminator field from the type.
*/
export type SessionUpdatePayload<T extends SessionUpdateType> = Omit<
Extract<acp.SessionUpdate, { sessionUpdate: T }>,
"sessionUpdate"
>
// ============================================================
// Permission Handler Callback Types
// ============================================================
/**
* Callback to resolve a permission request with the user's response.
*/
export type PermissionResolver = (response: acp.RequestPermissionResponse) => void
/**
* Handler function for permission requests.
* Called when the agent needs permission for a tool call.
* The handler should present the request to the user and call resolve() with their response.
*/
export type PermissionHandler = (request: Omit<acp.RequestPermissionRequest, "sessionId">, resolve: PermissionResolver) => void
// ============================================================
// Session Event Emitter Types
// ============================================================
/**
* Maps ACP SessionUpdate types to their event listener signatures.
* Uses the sessionUpdate discriminator to derive event names and payload types.
*/
export type ClineSessionEvents = {
[K in SessionUpdateType]: (payload: SessionUpdatePayload<K>) => void
} & {
/** Error event for session-level errors (not part of ACP SessionUpdate) */
error: (error: Error) => void
}
// ============================================================
// ClineAgent Options (decoupled from connection)
// ============================================================
/**
* Options for creating a ClineAgent instance (decoupled from connection).
*/
export interface ClineAgentOptions {
/** CLI version string */
version: string
/** Whether debug logging is enabled */
debug?: boolean
}
// Re-export common ACP types for convenience
export type {
Agent,
AgentSideConnection,
@@ -114,134 +51,18 @@ export type {
WriteTextFileResponse,
} from "@agentclientprotocol/sdk"
/**
* Cline-specific agent capabilities extending the ACP base capabilities.
*/
export interface ClineAgentCapabilities {
/** Support for loading sessions from disk */
loadSession: boolean
/** Prompt capabilities for the agent */
promptCapabilities: {
/** Support for image inputs */
image: boolean
/** Support for audio inputs */
audio: boolean
/** Support for embedded context (file resources) */
embeddedContext: boolean
}
/** MCP server passthrough capabilities */
mcpCapabilities: {
/** Support for HTTP MCP servers */
http: boolean
/** Support for SSE MCP servers */
sse: boolean
}
}
export type {
AcpAgentOptions,
AcpSessionState,
ClineAgentCapabilities,
ClineAgentInfo,
ClineAgentOptions,
ClinePermissionOption,
ClineSessionEvents,
PermissionHandler,
SessionUpdatePayload,
SessionUpdateType,
TranslatedMessage,
} from "./public-types.js"
/**
* Cline agent info for ACP initialization response.
*/
export interface ClineAgentInfo {
name: "cline"
title: "Cline"
version: string
}
/**
* Extended session data stored by Cline for ACP sessions.
* Maps to Cline's task history structure.
*/
export interface ClineAcpSession {
/** Unique session/task ID */
sessionId: string
/** Working directory for the session */
cwd: string
/** Current mode (plan/act) */
mode: "plan" | "act"
/** MCP servers passed from the client */
mcpServers: acp.McpServer[]
/** Timestamp when session was created */
createdAt: number
/** Timestamp of last activity */
lastActivityAt: number
/** Whether this session was loaded from history (needs resume on first prompt) */
isLoadedFromHistory?: boolean
/** Controller instance for this session (manages task execution) */
controller?: Controller
/** Model ID override for plan mode (format: "provider/modelId") */
planModeModelId?: string
/** Model ID override for act mode (format: "provider/modelId") */
actModeModelId?: string
}
/**
* Permission option as presented to the ACP client.
*/
export interface ClinePermissionOption {
kind: acp.PermissionOptionKind
name: string
optionId: string
}
/**
* Mapping of Cline message types to their ACP session update equivalents.
*/
export type ClineToAcpUpdateMapping = {
/** Text messages from the agent */
text: "agent_message_chunk"
/** Reasoning/thinking from the agent */
reasoning: "agent_thought_chunk"
/** Markdown content from the agent */
markdown: "agent_message_chunk"
/** Tool execution */
tool: "tool_call"
/** Command execution */
command: "tool_call"
/** Command output */
command_output: "tool_call_update"
/** Task completion */
completion_result: "end_turn"
/** Error messages */
error: "tool_call_update" | "error"
}
/**
* Options for creating an ACP agent instance.
*/
export interface AcpAgentOptions {
/** CLI version string */
version: string
/** Whether debug logging is enabled */
debug?: boolean
}
/**
* Result of translating a Cline message to ACP session update(s).
* A single Cline message may produce multiple ACP updates.
*/
export interface TranslatedMessage {
/** The session updates to send */
updates: acp.SessionUpdate[]
/** Whether this message requires a permission request */
requiresPermission?: boolean
/** Permission request details if required */
permissionRequest?: Omit<acp.RequestPermissionRequest, "sessionId">
/** The toolCallId that was created/used (for tracking across streaming updates) */
toolCallId?: string
}
/**
* State tracking for an active ACP session within Cline.
*/
export interface AcpSessionState {
/** Session ID */
sessionId: string
/** Whether the session is currently processing a prompt */
isProcessing: boolean
/** Current tool call ID being executed (if any) */
currentToolCallId?: string
/** Whether the session has been cancelled */
cancelled: boolean
/** Accumulated tool calls for permission batching */
pendingToolCalls: Map<string, acp.ToolCall>
}
export { AcpSessionStatus } from "./public-types.js"
+2 -2
View File
@@ -7,7 +7,7 @@ import { Box, Text, useInput } from "ink"
import React from "react"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
import { isMouseEscapeSequence } from "../utils/input"
import { isEnterKey, isMouseEscapeSequence } from "../utils/input"
interface ApiKeyInputProps {
providerName: string
@@ -39,7 +39,7 @@ export const ApiKeyInput: React.FC<ApiKeyInputProps> = ({
onCancel()
return
}
if (key.return) {
if (isEnterKey(input, key)) {
onSubmit(value)
return
}
@@ -0,0 +1,136 @@
import { Text } from "ink"
import { render } from "ink-testing-library"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { App } from "./App"
const CLEAR_SEQUENCE = "\x1b[2J\x1b[3J\x1b[H"
function setTerminalSize(columns: number, rows: number) {
Object.defineProperty(process.stdout, "columns", {
configurable: true,
writable: true,
value: columns,
})
Object.defineProperty(process.stdout, "rows", {
configurable: true,
writable: true,
value: rows,
})
}
function hasClearSequenceCall(calls: unknown[][]): boolean {
return calls.some((call) => call[0] === CLEAR_SEQUENCE)
}
vi.mock("./ChatView", () => ({
ChatView: ({ controller, initialPrompt, initialImages }: any) => {
React.useEffect(() => {
if (initialPrompt || (initialImages && initialImages.length > 0)) {
controller?.initTask(initialPrompt || "", initialImages)
}
}, [])
return React.createElement(Text, null, "ChatView")
},
}))
vi.mock("./TaskJsonView", () => ({
TaskJsonView: () => React.createElement(Text, null, "TaskJsonView"),
}))
vi.mock("./HistoryView", () => ({
HistoryView: () => React.createElement(Text, null, "HistoryView"),
}))
vi.mock("./ConfigView", () => ({
ConfigView: () => React.createElement(Text, null, "ConfigView"),
}))
vi.mock("./AuthView", () => ({
AuthView: () => React.createElement(Text, null, "AuthView"),
}))
vi.mock("../context/TaskContext", () => ({
TaskContextProvider: ({ children }: any) => children,
}))
vi.mock("../context/StdinContext", () => ({
StdinProvider: ({ children }: any) => children,
}))
describe("App startup prompt resize behavior", () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
delete (process.stdout as any).columns
delete (process.stdout as any).rows
})
it("does not replay initialPrompt after a width resize", async () => {
const initTask = vi.fn()
setTerminalSize(120, 40)
const writeSpy = vi.spyOn(process.stdout, "write").mockImplementation(((...args: any[]) => {
const callback = args.find((arg) => typeof arg === "function")
if (callback) {
callback()
}
return true
}) as any)
const { unmount } = render(
<App controller={{ initTask }} initialPrompt="hello" isRawModeSupported={true} view="welcome" />,
)
await vi.advanceTimersByTimeAsync(0)
expect(initTask).toHaveBeenCalledTimes(1)
writeSpy.mockClear()
setTerminalSize(121, 40)
process.stdout.emit("resize")
await vi.advanceTimersByTimeAsync(350)
await vi.advanceTimersByTimeAsync(0)
expect(initTask).toHaveBeenCalledTimes(1)
expect(hasClearSequenceCall(writeSpy.mock.calls as unknown[][])).toBe(true)
unmount()
})
it("does not remount on height-only resize", async () => {
const initTask = vi.fn()
setTerminalSize(120, 40)
const writeSpy = vi.spyOn(process.stdout, "write").mockImplementation(((...args: any[]) => {
const callback = args.find((arg) => typeof arg === "function")
if (callback) {
callback()
}
return true
}) as any)
const { unmount } = render(
<App controller={{ initTask }} initialPrompt="hello" isRawModeSupported={true} view="welcome" />,
)
await vi.advanceTimersByTimeAsync(0)
expect(initTask).toHaveBeenCalledTimes(1)
writeSpy.mockClear()
setTerminalSize(120, 45)
process.stdout.emit("resize")
await vi.advanceTimersByTimeAsync(350)
await vi.advanceTimersByTimeAsync(0)
expect(initTask).toHaveBeenCalledTimes(1)
expect(hasClearSequenceCall(writeSpy.mock.calls as unknown[][])).toBe(false)
unmount()
})
})
+27 -5
View File
@@ -3,14 +3,15 @@
* Routes between different views (task, history, config)
*/
import { Box } from "ink"
import React, { ReactNode, useCallback, useState } from "react"
import { Box, useApp } from "ink"
import React, { ReactNode, useCallback, useEffect, useState } from "react"
import { StdinProvider } from "../context/StdinContext"
import { TaskContextProvider } from "../context/TaskContext"
import { useTerminalSize } from "../hooks/useTerminalSize"
import { AuthView } from "./AuthView"
import { ChatView } from "./ChatView"
import { ConfigView } from "./ConfigView"
import { ErrorBoundary } from "./ErrorBoundary"
import { HistoryView } from "./HistoryView"
import { TaskJsonView } from "./TaskJsonView"
@@ -90,7 +91,17 @@ interface AppProps {
isRawModeSupported?: boolean
}
export const App: React.FC<AppProps> = ({
export const App: React.FC<AppProps> = (props) => {
const { exit } = useApp()
return (
<ErrorBoundary exit={exit}>
<InternalApp {...props} />
</ErrorBoundary>
)
}
const InternalApp: React.FC<AppProps> = ({
view: initialView,
taskId,
verbose = false,
@@ -135,6 +146,17 @@ export const App: React.FC<AppProps> = ({
const { resizeKey } = useTerminalSize()
const [currentView, setCurrentView] = useState<ViewType>(initialView)
const [selectedTaskId, setSelectedTaskId] = useState<string | undefined>(taskId)
const [pendingInitialPrompt, setPendingInitialPrompt] = useState<string | undefined>(initialPrompt)
const [pendingInitialImages, setPendingInitialImages] = useState<string[] | undefined>(initialImages)
useEffect(() => {
if (!pendingInitialPrompt && (!pendingInitialImages || pendingInitialImages.length === 0)) {
return
}
setPendingInitialPrompt(undefined)
setPendingInitialImages(undefined)
}, [pendingInitialPrompt, pendingInitialImages])
const handleSelectTask = useCallback((taskId: string) => {
setSelectedTaskId(taskId)
@@ -242,8 +264,8 @@ export const App: React.FC<AppProps> = ({
) : (
<ChatView
controller={controller}
initialImages={initialImages}
initialPrompt={initialPrompt}
initialImages={pendingInitialImages}
initialPrompt={pendingInitialPrompt}
onComplete={onComplete}
onError={onError}
onExit={onWelcomeExit}
+14 -8
View File
@@ -34,7 +34,7 @@ type AsciiMotionCliProps = {
autoPlay?: boolean;
loop?: boolean;
onReady?: (api: PlaybackAPI) => void;
onScroll?: () => void; // Called when user scrolls (scroll wheel)
onInteraction?: () => void; // Called when user scrolls, clicks, or drags
};
const FRAMES: FrameData[] = [
@@ -333364,7 +333364,7 @@ const FRAME_BOTTOM_RIGHT = 128;
export const AsciiMotionCli: React.FC<AsciiMotionCliProps> = ({
hasDarkBackground = true,
onScroll,
onInteraction,
}) => {
const [frameIndex, setFrameIndex] = useState(0);
const [targetFrame, setTargetFrame] = useState(0);
@@ -333390,13 +333390,13 @@ export const AsciiMotionCli: React.FC<AsciiMotionCliProps> = ({
// Stop animation on terminal resize to prevent visual glitches
useEffect(() => {
const handleResize = () => {
onScroll?.();
onInteraction?.();
};
process.stdout.on("resize", handleResize);
return () => {
process.stdout.off("resize", handleResize);
};
}, [onScroll]);
}, [onInteraction]);
// Mouse tracking - gracefully handle environments without tty support
useEffect(() => {
@@ -333417,13 +333417,19 @@ export const AsciiMotionCli: React.FC<AsciiMotionCliProps> = ({
const handleData = (data: Buffer) => {
const str = data.toString();
// Parse mouse events: \x1b[<button;x;yM
// Parse mouse events: \x1b[<button;x;yM (M=press, m=release)
const mouseMatch = str.match(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/);
if (mouseMatch) {
const button = parseInt(mouseMatch[1], 10);
// Button 64 = scroll up, 65 = scroll down
if (button === 64 || button === 65) {
onScroll?.();
const isPress = mouseMatch[4] === "M";
// Button 64/65 = scroll up/down
// Button 0-2 = left/middle/right click (on press)
// Button 32-34 = drag with left/middle/right button held
const isScroll = button === 64 || button === 65;
const isClick = isPress && button >= 0 && button <= 2;
const isDrag = button >= 32 && button <= 34;
if (isScroll || isClick || isDrag) {
onInteraction?.();
}
// Throttle cursor updates to ~20fps to reduce re-renders
const now = Date.now();
+76 -8
View File
@@ -3,15 +3,14 @@
* Handles different types of user interactions (text input, confirmations, choices)
*/
import type { ClineAsk } from "@shared/ExtensionMessage"
import type { ClineAsk, ClineMessage } from "@shared/ExtensionMessage"
import { Box, Text, useApp, useInput } from "ink"
import React, { useCallback, useEffect, useRef, useState } from "react"
import { useStdinContext } from "../context/StdinContext"
import { useTaskController } from "../context/TaskContext"
import { useLastCompletedAskMessage } from "../hooks/useStateSubscriber"
import { isMouseEscapeSequence } from "../utils/input"
import { isEnterKey, isMouseEscapeSequence } from "../utils/input"
import { jsonParseSafe } from "../utils/parser"
import { getCliMessagePrefixIcon } from "./MessageRow"
interface AskPromptProps {
onRespond?: (response: string) => void
@@ -137,7 +136,7 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
} else if (promptType === "options") {
// Number selection for options, or free text input
const parts = jsonParseSafe(text, { options: [] as string[] })
if (key.return) {
if (isEnterKey(input, key)) {
// Submit free text on Enter
if (textInput.trim()) {
sendResponse("messageResponse", textInput.trim())
@@ -146,7 +145,7 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
setTextInput((prev) => prev.slice(0, -1))
} else if (input && !key.ctrl && !key.meta) {
// Check if it's a number for option selection (only when no text typed yet)
const num = parseInt(input, 10)
const num = Number.parseInt(input, 10)
if (textInput === "" && !Number.isNaN(num) && num >= 1 && num <= parts.options.length) {
const selectedOption = parts.options[num - 1]
sendResponse("messageResponse", selectedOption)
@@ -157,7 +156,7 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
}
} else if (promptType === "text") {
// Text input mode
if (key.return) {
if (isEnterKey(input, key)) {
// Submit on Enter
if (textInput.trim()) {
sendResponse("messageResponse", textInput.trim())
@@ -170,7 +169,7 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
}
} else if (promptType === "plan_mode_text") {
// Plan mode text input - allows text response or toggle to Act mode
if (key.return) {
if (isEnterKey(input, key)) {
// Submit on Enter
if (textInput.trim()) {
sendResponse("messageResponse", textInput.trim())
@@ -186,7 +185,7 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
}
} else if (promptType === "completion") {
// Task completed - allow follow-up question or exit
if (key.return) {
if (isEnterKey(input, key)) {
if (textInput.trim()) {
// Send follow-up question
sendResponse("messageResponse", textInput.trim())
@@ -372,3 +371,72 @@ export const AskPrompt: React.FC<AskPromptProps> = ({ onRespond }) => {
return null
}
}
/**
* Get emoji icon for message type
*/
function getCliMessagePrefixIcon(message: ClineMessage): string {
if (message.type === "ask") {
switch (message.ask) {
case "followup":
return "❓"
case "command":
case "command_output":
return "⚙️"
case "tool":
return "🔧"
case "completion_result":
return "✅"
case "api_req_failed":
return "❌"
case "resume_task":
case "resume_completed_task":
return "▶️"
case "browser_action_launch":
return "🌐"
case "use_mcp_server":
return "🔌"
case "plan_mode_respond":
return "📋"
default:
return "❔"
}
}
switch (message.say) {
case "task":
return "📋"
case "error":
return "❌"
case "text":
return "💬"
case "reasoning":
return "🧠"
case "completion_result":
return "✅"
case "user_feedback":
return "👤"
case "command":
case "command_output":
return "⚙️"
case "tool":
return "🔧"
case "browser_action":
case "browser_action_launch":
case "browser_action_result":
return "🌐"
case "mcp_server_request_started":
case "mcp_server_response":
return "🔌"
case "api_req_started":
case "api_req_finished":
return "🔄"
case "checkpoint_created":
return "💾"
case "info":
return "️"
case "generate_explanation":
return "📝"
default:
return " "
}
}
+149 -108
View File
@@ -6,21 +6,25 @@
import { Box, Text, useApp, useInput } from "ink"
import Spinner from "ink-spinner"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { refreshOcaModels } from "@/core/controller/models/refreshOcaModels"
import { StateManager } from "@/core/storage/StateManager"
import { openAiCodexOAuthManager } from "@/integrations/openai-codex/oauth"
import { AuthService } from "@/services/auth/AuthService"
import type { ApiProvider } from "@/shared/api"
import { openAiCodexDefaultModelId, openRouterDefaultModelId } from "@/shared/api"
import { getProviderModelIdKey, ProviderToApiKeyMap } from "@/shared/storage"
import { StringRequest } from "@/shared/proto/cline/common"
import { openExternal } from "@/utils/env"
import { COLORS } from "../constants/colors"
import { getAllFeaturedModels } from "../constants/featured-models"
import { useStdinContext } from "../context/StdinContext"
import { useClineFeaturedModels } from "../hooks/useClineFeaturedModels"
import { useOcaAuth } from "../hooks/useOcaAuth"
import { useScrollableList } from "../hooks/useScrollableList"
import { type DetectedSources, detectImportSources, type ImportSource } from "../utils/import-configs"
import { isMouseEscapeSequence } from "../utils/input"
import { isEnterKey, isMouseEscapeSequence } from "../utils/input"
import { applyBedrockConfig, applyProviderConfig } from "../utils/provider-config"
import { useValidProviders } from "../utils/providers"
import { ApiKeyInput } from "./ApiKeyInput"
import { StaticRobotFrame } from "./AsciiMotionCli"
import { BedrockCustomModelFlow } from "./BedrockCustomModelFlow"
import { type BedrockConfig, BedrockSetup } from "./BedrockSetup"
import {
FeaturedModelPicker,
@@ -29,8 +33,9 @@ import {
isBrowseAllSelected,
} from "./FeaturedModelPicker"
import { ImportView } from "./ImportView"
import { getDefaultModelId, hasModelPicker, ModelPicker } from "./ModelPicker"
import { CLI_EXCLUDED_PROVIDERS, getProviderLabel, getProviderOrder } from "./ProviderPicker"
import { CUSTOM_MODEL_ID, getDefaultModelId, hasModelPicker, ModelPicker } from "./ModelPicker"
import { OcaEmployeeCheck } from "./OcaEmployeeCheck"
import { getProviderLabel } from "./ProviderPicker"
type AuthStep =
| "menu"
@@ -42,13 +47,13 @@ type AuthStep =
| "success"
| "error"
| "cline_auth"
| "oca_employee_check"
| "oca_auth"
| "cline_model"
| "openai_codex_auth"
| "bedrock"
| "import"
// Featured models loaded from shared constants
const featuredModels = getAllFeaturedModels()
| "bedrock_custom"
interface AuthViewProps {
controller: any
@@ -79,7 +84,7 @@ const Select: React.FC<{
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1))
} else if (key.downArrow) {
setSelectedIndex((prev) => (prev < items.length - 1 ? prev + 1 : 0))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
onSelect(items[selectedIndex].value)
}
},
@@ -125,7 +130,7 @@ const TextInput: React.FC<{
return
}
if (key.return) {
if (isEnterKey(input, key)) {
onSubmit(value)
} else if (key.backspace || key.delete) {
onChange(value.slice(0, -1))
@@ -140,7 +145,11 @@ const TextInput: React.FC<{
return (
<Box>
<Text color="white">{displayValue || placeholder || ""}</Text>
{!displayValue && placeholder ? (
<Text color="gray">e.g. {placeholder}</Text>
) : (
<Text color="white">{displayValue || ""}</Text>
)}
<Text inverse> </Text>
</Box>
)
@@ -148,6 +157,9 @@ const TextInput: React.FC<{
export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onError, onNavigateToWelcome }) => {
const { exit } = useApp()
const providers = useValidProviders()
const [step, setStep] = useState<AuthStep>("menu")
const [selectedProvider, setSelectedProvider] = useState<string>(
StateManager.get().getApiConfiguration().actModeApiProvider ||
@@ -158,19 +170,40 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const [modelId, setModelId] = useState("")
const [baseUrl, setBaseUrl] = useState("")
const [errorMessage, setErrorMessage] = useState("")
const [authStatus, setAuthStatus] = useState<string>("")
const [providerSearch, setProviderSearch] = useState("")
const [providerIndex, setProviderIndex] = useState(0)
const [clineModelIndex, setClineModelIndex] = useState(0)
const featuredModels = useClineFeaturedModels()
const [importSources, setImportSources] = useState<DetectedSources>({ codex: false, opencode: false })
const [importSource, setImportSource] = useState<ImportSource | null>(null)
const [bedrockConfig, setBedrockConfig] = useState<BedrockConfig | null>(null)
// Use providers.json order, filtered to exclude CLI-incompatible providers
const sortedProviders = useMemo(() => {
return getProviderOrder().filter((p) => !CLI_EXCLUDED_PROVIDERS.has(p))
// OCA auth hook - enabled when step is oca_auth
const handleOcaAuthSuccess = useCallback(async () => {
await applyProviderConfig({ providerId: "oca", controller })
// Fetch OCA models from the API - this sets actModeOcaModelId/planModeOcaModelId in state
await refreshOcaModels(controller, StringRequest.create({ value: "" }))
const stateManager = StateManager.get()
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
setSelectedProvider("oca")
const actModelId = stateManager.getGlobalSettingsKey("actModeOcaModelId") || ""
setModelId(actModelId)
setStep("success")
}, [controller])
const handleOcaAuthError = useCallback((error: Error) => {
setErrorMessage(error.message)
setStep("error")
}, [])
const { startAuth: initiateOcaAuth } = useOcaAuth({
controller,
enabled: step === "oca_auth",
onSuccess: handleOcaAuthSuccess,
onError: handleOcaAuthError,
})
// Main menu items - conditionally include import options
const mainMenuItems: SelectItem[] = useMemo(() => {
const items: SelectItem[] = [{ label: "Sign in with Cline", value: "cline_auth" }]
@@ -196,15 +229,13 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const providerItems: SelectItem[] = useMemo(() => {
const search = providerSearch.toLowerCase()
const filtered = providerSearch
? sortedProviders.filter(
(p) => p.toLowerCase().includes(search) || getProviderLabel(p).toLowerCase().includes(search),
)
: sortedProviders
? providers.filter((p) => p.toLowerCase().includes(search) || getProviderLabel(p).toLowerCase().includes(search))
: providers
return filtered.map((p: string) => ({
label: getProviderLabel(p),
value: p,
}))
}, [sortedProviders, providerSearch])
}, [providers, providerSearch])
// Use shared scrollable list hook for provider windowing
const TOTAL_PROVIDER_ROWS = 8
@@ -225,6 +256,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
}, [])
// Reset provider index when search changes
// biome-ignore lint/correctness/useExhaustiveDependencies: we want to reset here
useEffect(() => {
setProviderIndex(0)
}, [providerSearch])
@@ -250,23 +282,9 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
return
}
if (authState.user && authState.user.email) {
// Auth succeeded - save configuration and transition to success
const stateManager = StateManager.get()
const mode = stateManager.getGlobalSettingsKey("mode") || "act"
const providerKey = mode === "act" ? "actModeApiProvider" : "planModeApiProvider"
// Use provider-specific model ID key (cline uses OpenRouterModelId)
const modelIdKey = getProviderModelIdKey("cline" as ApiProvider, mode as "act" | "plan")
const config: Record<string, string> = {
actModeApiProvider: "cline",
[providerKey]: "cline",
}
if (modelIdKey) {
config[modelIdKey] = openRouterDefaultModelId
}
stateManager.setApiConfiguration(config)
stateManager.flushPendingState()
if (authState.user?.email) {
// Auth succeeded - save configuration and transition to model selection
await applyProviderConfig({ providerId: "cline", controller })
setSelectedProvider("cline")
setModelId(openRouterDefaultModelId)
setStep("cline_model")
@@ -295,23 +313,10 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
await openAiCodexOAuthManager.waitForCallback()
// Success - save configuration
await applyProviderConfig({ providerId: "openai-codex", controller })
const stateManager = StateManager.get()
const mode = stateManager.getGlobalSettingsKey("mode") || "act"
const providerKey = mode === "act" ? "actModeApiProvider" : "planModeApiProvider"
// Use provider-specific model ID key (openai-codex uses generic apiModelId)
const modelIdKey = getProviderModelIdKey("openai-codex" as ApiProvider, mode as "act" | "plan")
const config: Record<string, string> = {
actModeApiProvider: "openai-codex",
planModeApiProvider: "openai-codex",
[providerKey]: "openai-codex",
}
if (modelIdKey) {
config[modelIdKey] = openAiCodexDefaultModelId
}
stateManager.setApiConfiguration(config)
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
setSelectedProvider("openai-codex")
setModelId(openAiCodexDefaultModelId)
setStep("success")
@@ -326,7 +331,6 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const startClineAuth = useCallback(async () => {
try {
setStep("cline_auth")
setAuthStatus("Starting authentication...")
await AuthService.getInstance(controller).createAuthRequest()
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : String(error))
@@ -334,6 +338,11 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
}
}, [controller])
const startOcaAuth = useCallback(() => {
setStep("oca_auth")
initiateOcaAuth()
}, [initiateOcaAuth])
const handleMainMenuSelect = useCallback(
(value: string) => {
if (value === "exit") {
@@ -360,8 +369,9 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const handleProviderSelect = useCallback(
(value: string) => {
setSelectedProvider(value)
if (value === "cline") {
startClineAuth()
if (value === "oca") {
// Show employee check screen before starting auth
setStep("oca_employee_check")
} else if (value === "openai-codex") {
setStep("openai_codex_auth")
startOpenAiCodexAuth()
@@ -371,7 +381,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setStep("apikey")
}
},
[startClineAuth, startOpenAiCodexAuth],
[startOcaAuth, startOpenAiCodexAuth],
)
const handleApiKeySubmit = useCallback(
@@ -388,55 +398,53 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
[selectedProvider],
)
// Save custom Bedrock ARN configuration with base model for capability detection
const saveCustomBedrockConfiguration = useCallback(
async (arn: string, baseModelId: string) => {
try {
if (!bedrockConfig) {
throw new Error("Bedrock configuration is missing")
}
await applyBedrockConfig({
bedrockConfig,
modelId: arn,
customModelBaseId: baseModelId,
controller,
})
const stateManager = StateManager.get()
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
setStep("success")
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : String(error))
setStep("error")
}
},
[bedrockConfig, controller],
)
const saveConfiguration = useCallback(
async (model: string, base: string) => {
try {
const stateManager = StateManager.get()
// Use provider-specific model ID keys (e.g., cline uses actModeOpenRouterModelId)
const actModelKey = getProviderModelIdKey(selectedProvider as ApiProvider, "act")
const planModelKey = getProviderModelIdKey(selectedProvider as ApiProvider, "plan")
const config: Record<string, string> = {
actModeApiProvider: selectedProvider,
planModeApiProvider: selectedProvider,
apiProvider: selectedProvider,
}
if (actModelKey) config[actModelKey] = model
if (planModelKey) config[planModelKey] = model
// For cline/openrouter, also set model info (required for getModel() to return correct model)
if (selectedProvider === "cline" || selectedProvider === "openrouter") {
const openRouterModels = await controller?.readOpenRouterModels()
const modelInfo = openRouterModels?.[model]
if (modelInfo) {
stateManager.setGlobalState("actModeOpenRouterModelInfo", modelInfo)
stateManager.setGlobalState("planModeOpenRouterModelInfo", modelInfo)
}
}
// Add API key or Bedrock-specific config
if (selectedProvider === "bedrock" && bedrockConfig) {
const bedrockFields: Record<string, unknown> = {
awsAuthentication: bedrockConfig.awsAuthentication,
awsRegion: bedrockConfig.awsRegion,
awsUseCrossRegionInference: bedrockConfig.awsUseCrossRegionInference,
}
if (bedrockConfig.awsProfile !== undefined) bedrockFields.awsProfile = bedrockConfig.awsProfile
if (bedrockConfig.awsAccessKey) bedrockFields.awsAccessKey = bedrockConfig.awsAccessKey
if (bedrockConfig.awsSecretKey) bedrockFields.awsSecretKey = bedrockConfig.awsSecretKey
if (bedrockConfig.awsSessionToken) bedrockFields.awsSessionToken = bedrockConfig.awsSessionToken
Object.assign(config, bedrockFields)
} else if (apiKey) {
const keyField = ProviderToApiKeyMap[selectedProvider as keyof typeof ProviderToApiKeyMap]
if (keyField) {
const fields = Array.isArray(keyField) ? keyField : [keyField]
config[fields[0]] = apiKey
}
await applyBedrockConfig({
bedrockConfig,
modelId: model,
controller,
})
} else {
await applyProviderConfig({
providerId: selectedProvider,
apiKey,
modelId: model,
baseUrl: base,
controller,
})
}
if (base) {
config.openAiBaseUrl = base
}
stateManager.setApiConfiguration(config)
const stateManager = StateManager.get()
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
@@ -451,6 +459,12 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const handleModelIdSubmit = useCallback(
(value: string) => {
// Intercept "Custom" selection for Bedrock — redirect to custom ARN input flow
if (value === CUSTOM_MODEL_ID && selectedProvider === "bedrock") {
setStep("bedrock_custom")
return
}
if (value.trim()) {
setModelId(value)
}
@@ -558,6 +572,9 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
// Go back to cline_model if we came from there (Cline provider)
if (selectedProvider === "cline") {
setStep("cline_model")
} else if (selectedProvider === "bedrock") {
// Bedrock skips the API key step — go back to Bedrock setup
setStep("bedrock")
} else {
setStep("apikey")
}
@@ -566,6 +583,12 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setBaseUrl("")
setStep("modelid")
break
case "oca_employee_check":
setStep("provider")
break
case "oca_auth":
setStep("oca_employee_check")
break
case "cline_auth":
setStep("menu")
break
@@ -668,7 +691,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
<Box flexDirection="column">
<Text color="white">Model ID</Text>
<Text> </Text>
<Text color="gray">e.g., claude-sonnet-4-20250514, gpt-4o</Text>
<Text color="gray">e.g., claude-sonnet-4-6, gpt-4o</Text>
<Text> </Text>
<TextInput onChange={setModelId} onSubmit={handleModelIdSubmit} placeholder="model-id" value={modelId} />
<Text> </Text>
@@ -704,6 +727,10 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
</Box>
)
case "oca_employee_check":
return <OcaEmployeeCheck isActive={step === "oca_employee_check"} onCancel={goBack} onSignIn={startOcaAuth} />
case "oca_auth":
case "cline_auth":
return (
<Box flexDirection="column">
@@ -742,7 +769,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
<Box flexDirection="column">
<Text color="white">Choose a model</Text>
<Text> </Text>
<FeaturedModelPicker selectedIndex={clineModelIndex} />
<FeaturedModelPicker featuredModels={featuredModels} selectedIndex={clineModelIndex} />
</Box>
)
}
@@ -759,6 +786,18 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
/>
)
case "bedrock_custom":
return (
<BedrockCustomModelFlow
isActive={step === "bedrock_custom"}
onCancel={() => setStep("modelid")}
onComplete={(arn, baseModelId) => {
setStep("saving")
saveCustomBedrockConfiguration(arn, baseModelId)
}}
/>
)
case "import":
if (!importSource) {
return null
@@ -788,11 +827,13 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const [menuIndex, setMenuIndex] = useState(0)
// Steps that allow going back with escape (apikey handled by ApiKeyInput component)
// OcaEmployeeCheck handles its own escape key, so oca_employee_check is not in this list
const canGoBack = [
"provider",
"modelid",
"baseurl",
"cline_auth",
"oca_auth",
"cline_model",
"openai_codex_auth",
"bedrock",
@@ -812,7 +853,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setMenuIndex((prev) => (prev > 0 ? prev - 1 : mainMenuItems.length - 1))
} else if (key.downArrow) {
setMenuIndex((prev) => (prev < mainMenuItems.length - 1 ? prev + 1 : 0))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
handleMainMenuSelect(mainMenuItems[menuIndex].value)
}
} else if (step === "provider") {
@@ -820,7 +861,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setProviderIndex((prev) => (prev > 0 ? prev - 1 : providerItems.length - 1))
} else if (key.downArrow) {
setProviderIndex((prev) => (prev < providerItems.length - 1 ? prev + 1 : 0))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
if (providerItems[providerIndex]) {
handleProviderSelect(providerItems[providerIndex].value)
}
@@ -830,17 +871,17 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setProviderSearch((prev) => prev + input)
}
} else if (step === "cline_model") {
const maxIndex = getFeaturedModelMaxIndex()
const maxIndex = getFeaturedModelMaxIndex(featuredModels)
if (key.upArrow) {
setClineModelIndex((prev) => (prev > 0 ? prev - 1 : maxIndex))
} else if (key.downArrow) {
setClineModelIndex((prev) => (prev < maxIndex ? prev + 1 : 0))
} else if (key.return) {
if (isBrowseAllSelected(clineModelIndex)) {
} else if (isEnterKey(input, key)) {
if (isBrowseAllSelected(clineModelIndex, featuredModels)) {
setStep("modelid")
} else {
const selectedModel = getFeaturedModelAtIndex(clineModelIndex)
const selectedModel = getFeaturedModelAtIndex(clineModelIndex, featuredModels)
if (selectedModel) {
handleClineModelSelect(selectedModel.id)
}
@@ -885,7 +926,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
{index === menuIndex ? " " : " "}
{item.label}
</Text>
{item.value === "cline_auth" && <Text color="yellow"> (try Kimi K2.5 free!)</Text>}
{item.value === "cline_auth" && <Text color="yellow"> (try Opus 4.6!)</Text>}
</Text>
</Box>
))}
@@ -0,0 +1,112 @@
/**
* Bedrock Custom Model Flow component
* Two-step flow: ARN/custom model ID input → base model selection for capability detection.
* Used by both AuthView (onboarding) and SettingsPanelContent (/settings).
*/
import { Box, Text, useInput } from "ink"
// biome-ignore lint/correctness/noUnusedImports: React is needed for JSX at runtime
import React, { useCallback, useState } from "react"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
import { isEnterKey } from "../utils/input"
import { getModelList } from "./ModelPicker"
import { SearchableList } from "./SearchableList"
type FlowStep = "arn_input" | "base_model"
interface BedrockCustomModelFlowProps {
/** Whether this component should capture keyboard input */
isActive: boolean
/** Called when the user completes both steps (ARN + base model selection) */
onComplete: (arn: string, baseModelId: string) => void
/** Called when the user presses Escape on the first step (ARN input) */
onCancel: () => void
}
export const BedrockCustomModelFlow: React.FC<BedrockCustomModelFlowProps> = ({ isActive, onComplete, onCancel }) => {
const { isRawModeSupported } = useStdinContext()
const [step, setStep] = useState<FlowStep>("arn_input")
const [customArn, setCustomArn] = useState("")
const handleArnSubmit = useCallback(() => {
if (customArn.trim()) {
setStep("base_model")
}
}, [customArn])
const handleBaseModelCancel = useCallback(() => {
setStep("arn_input")
}, [])
useInput(
(input, key) => {
if (step === "arn_input") {
if (key.escape) {
onCancel()
} else if (isEnterKey(input, key)) {
handleArnSubmit()
} else if (key.backspace || key.delete) {
setCustomArn((prev) => prev.slice(0, -1))
} else if (input && !key.ctrl && !key.meta) {
setCustomArn((prev) => prev + input)
}
return
}
if (step === "base_model") {
if (key.escape) {
handleBaseModelCancel()
}
// Other input is handled by SearchableList
}
},
{ isActive: isActive && isRawModeSupported },
)
if (step === "arn_input") {
return (
<Box flexDirection="column">
<Text bold color={COLORS.primaryBlue}>
Custom Model ID
</Text>
<Box marginTop={1}>
<Text color="gray">Enter your Application Inference Profile ARN or custom model ID</Text>
</Box>
<Box marginTop={1}>
{customArn ? (
<Text color="white">{customArn}</Text>
) : (
<Text color="gray">e.g. arn:aws:bedrock:region:account:application-inference-profile/...</Text>
)}
<Text inverse> </Text>
</Box>
<Box marginTop={1}>
<Text color="gray">Enter to continue, Esc to go back</Text>
</Box>
</Box>
)
}
// step === "base_model"
return (
<Box flexDirection="column">
<Text bold color={COLORS.primaryBlue}>
Base Inference Model
</Text>
<Text color="gray">Select the base model your inference profile uses (for capability detection)</Text>
<Box marginTop={1}>
<SearchableList
isActive={isActive && step === "base_model"}
items={getModelList("bedrock").map((id) => ({ id, label: id }))}
onSelect={(item) => {
onComplete(customArn, item.id)
}}
/>
</Box>
<Box marginTop={1}>
<Text color="gray">Type to search, arrows to navigate, Enter to select, Esc to go back</Text>
</Box>
</Box>
)
}
+19 -9
View File
@@ -114,8 +114,11 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
// Filtered regions
const filteredRegions = useMemo(() => {
const search = regionSearch.toLowerCase()
return search ? AWS_REGIONS.filter((r) => r.includes(search)) : AWS_REGIONS
const search = regionSearch.toLowerCase().trim()
if (!search) {
return AWS_REGIONS
}
return AWS_REGIONS.filter((r) => r.toLowerCase().includes(search))
}, [regionSearch])
const {
@@ -170,10 +173,18 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
}
}, [step, authMethod, onCancel])
const getSelectedRegion = useCallback(() => {
if (filteredRegions.length > 0 && regionIndex >= 0 && regionIndex < filteredRegions.length) {
return filteredRegions[regionIndex]
}
// If no matches, use the search term as custom region
return regionSearch.trim() || "us-east-1"
}, [filteredRegions, regionIndex, regionSearch])
const finish = useCallback(() => {
const config: BedrockConfig = {
awsAuthentication: authMethod === "default" ? "credentials" : authMethod,
awsRegion: filteredRegions[regionIndex] || "us-east-1",
awsRegion: getSelectedRegion(),
awsUseCrossRegionInference: crossRegion,
}
if (authMethod === "profile") {
@@ -184,7 +195,7 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
if (sessionToken) config.awsSessionToken = sessionToken
}
onComplete(config)
}, [authMethod, profileName, accessKey, secretKey, sessionToken, filteredRegions, regionIndex, crossRegion, onComplete])
}, [authMethod, profileName, accessKey, secretKey, sessionToken, getSelectedRegion, crossRegion, onComplete])
// Handle input for auth_method, region, and options steps
useInput(
@@ -204,11 +215,11 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
} else if (step === "region") {
if (key.escape) {
goBack()
} else if (key.upArrow) {
} else if (key.upArrow && filteredRegions.length > 0) {
setRegionIndex((prev) => (prev > 0 ? prev - 1 : filteredRegions.length - 1))
} else if (key.downArrow) {
} else if (key.downArrow && filteredRegions.length > 0) {
setRegionIndex((prev) => (prev < filteredRegions.length - 1 ? prev + 1 : 0))
} else if (key.return && filteredRegions.length > 0) {
} else if (key.return && (filteredRegions.length > 0 || regionSearch.trim())) {
setStep("options")
} else if (key.backspace || key.delete) {
setRegionSearch((prev) => prev.slice(0, -1))
@@ -330,7 +341,7 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
<Text color="white">AWS Region</Text>
<Text> </Text>
<Box>
<Text color="gray">Search: </Text>
<Text color="gray">Search or enter custom region: </Text>
<Text color="white">{regionSearch}</Text>
<Text inverse> </Text>
</Box>
@@ -350,7 +361,6 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
{showRegionBottom && (
<Text color="gray">... {filteredRegions.length - regionVisibleStart - regionVisibleCount} more below</Text>
)}
{filteredRegions.length === 0 && <Text color="gray">No regions match "{regionSearch}"</Text>}
<Text> </Text>
<Text color="gray">Type to search, arrows to navigate, Enter to select, Esc to go back</Text>
</Box>
@@ -0,0 +1,53 @@
import type { ClineMessage } from "@shared/ExtensionMessage"
import { render } from "ink-testing-library"
import React from "react"
import { describe, expect, it, vi } from "vitest"
import { ChatMessage } from "./ChatMessage"
vi.mock("../hooks/useTerminalSize", () => ({
useTerminalSize: () => ({
columns: 120,
rows: 40,
resizeKey: 0,
}),
}))
describe("ChatMessage markdown rendering", () => {
it("renders basic markdown elements correctly with appropriate styling", () => {
const message: ClineMessage = {
ts: Date.now(),
type: "say",
say: "text",
text: "# Heading 1\n\nThis is a **bold** and *italic* text with `inline code`.\n\n- List item 1\n- List item 2\n\n> Blockquote\n\n```javascript\nconst x = 1;\n```",
}
const { lastFrame } = render(React.createElement(ChatMessage, { message, mode: "act" }))
const frame = lastFrame() || ""
// Check for heading (bold)
// \x1B[1m is the ANSI escape code for bold
expect(frame).toMatch(/\x1B\[1mHeading 1\x1B\[22m/)
// Check for bold text
expect(frame).toMatch(/\x1B\[1mbold\x1B\[22m/)
// Check for italic text
// \x1B[3m is the ANSI escape code for italic
expect(frame).toMatch(/\x1B\[3mitalic\x1B\[23m/)
// Check for inline code (no special styling in the current implementation, just text)
expect(frame).toContain("inline code")
// Check for list items (gray bullet)
// \x1B[90m is the ANSI escape code for gray
expect(frame).toMatch(/\x1B\[90m• \x1B\[39mList item 1/)
expect(frame).toMatch(/\x1B\[90m• \x1B\[39mList item 2/)
// Check for blockquote (gray pipe)
expect(frame).toMatch(/\x1B\[90m│ \x1B\[39mBlockquote/)
// Check for code block (cyan text)
// \x1B[36m is the ANSI escape code for cyan
expect(frame).toMatch(/\x1B\[36mconst x = 1;\x1B\[39m/)
})
})
+106
View File
@@ -0,0 +1,106 @@
import type { ClineMessage } from "@shared/ExtensionMessage"
import { render } from "ink-testing-library"
import React from "react"
import { describe, expect, it, vi } from "vitest"
import { ChatMessage } from "./ChatMessage"
vi.mock("../hooks/useTerminalSize", () => ({
useTerminalSize: () => ({
columns: 120,
rows: 40,
resizeKey: 0,
}),
}))
describe("ChatMessage subagent rendering", () => {
it("renders subagent approval prompts as a tree", () => {
const message: ClineMessage = {
ts: Date.now(),
type: "ask",
ask: "use_subagents",
text: JSON.stringify({
prompts: [
"Find codebase stats and size",
"Find funny comments and easter eggs",
"Find unusual patterns and history",
],
}),
}
const { lastFrame } = render(React.createElement(ChatMessage, { message, mode: "act" }))
const frame = lastFrame() || ""
expect(frame).toContain("Cline wants to run subagents")
expect(frame).toContain("├─ Find codebase stats and size")
expect(frame).toContain("├─ Find funny comments and easter eggs")
expect(frame).toContain("└─ Find unusual patterns and history")
})
it("renders subagent progress rows with compact token stats and completion checks", () => {
const message: ClineMessage = {
ts: Date.now(),
type: "say",
say: "subagent",
text: JSON.stringify({
status: "running",
total: 3,
completed: 1,
successes: 1,
failures: 0,
toolCalls: 21,
inputTokens: 0,
outputTokens: 0,
contextWindow: 0,
maxContextTokens: 0,
maxContextUsagePercentage: 0,
items: [
{
index: 1,
prompt: "Find codebase stats and size",
status: "completed",
toolCalls: 5,
inputTokens: 0,
outputTokens: 0,
totalCost: 0.034,
contextTokens: 24400,
contextWindow: 200000,
contextUsagePercentage: 12.2,
},
{
index: 2,
prompt: "Find funny comments and easter eggs",
status: "running",
toolCalls: 11,
inputTokens: 0,
outputTokens: 0,
totalCost: 0.056,
contextTokens: 31600,
contextWindow: 200000,
contextUsagePercentage: 15.8,
},
{
index: 3,
prompt: "Find unusual patterns and history",
status: "pending",
toolCalls: 5,
inputTokens: 0,
outputTokens: 0,
totalCost: 0,
contextTokens: 28900,
contextWindow: 200000,
contextUsagePercentage: 14.4,
},
],
}),
}
const { lastFrame } = render(React.createElement(ChatMessage, { isStreaming: true, message, mode: "act" }))
const frame = lastFrame() || ""
expect(frame).toContain("Cline is running subagents")
expect(frame).toContain("✓ Find codebase stats and size")
expect(frame).toContain("5 tool uses · 24.4k tokens · $0.03")
expect(frame).toContain("11 tool uses · 31.6k tokens · $0.06")
expect(frame).toContain("5 tool uses · 28.9k tokens · $0.00")
})
})
+175 -85
View File
@@ -10,21 +10,21 @@ import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@shared/ClineAccount"
import { COMMAND_OUTPUT_STRING } from "@shared/combineCommandSequences"
import type { ClineAskUseMcpServer, ClineMessage } from "@shared/ExtensionMessage"
import { Box, Text } from "ink"
import Spinner from "ink-spinner"
import { lexer, type Token, type Tokens } from "marked"
import React from "react"
import { COLORS } from "../constants/colors"
import { useTerminalSize } from "../hooks/useTerminalSize"
import { jsonParseSafe } from "../utils/parser"
import { getToolDescription, isFileEditTool, parseToolFromMessage } from "../utils/tools"
import { DiffView } from "./DiffView"
import { SubagentMessage } from "./SubagentMessage"
/**
* Add "(Tab)" hint after "Act mode" mentions.
* Add "(Tab)" hint after "Act mode" mentions in plain text.
* Case-insensitive, avoids double-adding if already present.
* Matches just "Act mode" without requiring "to " prefix because markdown
* processing may split "toggle to **Act mode**" into separate text chunks.
*/
function addActModeHint(text: string): React.ReactNode[] {
// Match "Act mode" in various capitalizations, but not if already followed by (Tab)
function addActModeHint(text: string, keyPrefix: string): React.ReactNode[] {
const actModeRegex = /\bact\s+mode\b(?!\s*\(tab\))/gi
const parts = text.split(actModeRegex)
const matches = text.match(actModeRegex)
@@ -35,82 +35,156 @@ function addActModeHint(text: string): React.ReactNode[] {
const nodes: React.ReactNode[] = []
parts.forEach((part, i) => {
if (part) {
nodes.push(part)
}
if (part) nodes.push(part)
if (matches[i]) {
nodes.push(
<React.Fragment key={`act-mode-${i}`}>
<React.Fragment key={`${keyPrefix}-act-mode-${i}`}>
{matches[i]}
<Text color="gray"> (Tab)</Text>
</React.Fragment>,
)
}
})
return nodes
}
/**
* Render inline markdown: **bold**, *italic*, `code`
* Also adds "(Tab)" hints after "Act mode" mentions.
* Returns array of React nodes with appropriate styling
* Render an array of marked tokens as Ink React nodes.
* This is the entry point for recursive rendering — each token may
* contain child tokens (e.g. a paragraph contains inline tokens,
* a list contains items, etc.).
*/
function renderInlineMarkdown(text: string): React.ReactNode[] {
const nodes: React.ReactNode[] = []
// Match **bold**, *italic*, or `code` - order matters (** before *)
const regex = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`)/g
let lastIndex = 0
let match
while ((match = regex.exec(text)) !== null) {
// Add text before match (with Act Mode hint processing)
if (match.index > lastIndex) {
const beforeText = text.slice(lastIndex, match.index)
nodes.push(...addActModeHint(beforeText))
}
const fullMatch = match[0]
const key = `md-${match.index}`
if (fullMatch.startsWith("**") && fullMatch.endsWith("**")) {
// Bold - also process for Act Mode hints inside bold text
const boldContent = fullMatch.slice(2, -2)
const hintedContent = addActModeHint(boldContent)
nodes.push(
<Text bold key={key}>
{hintedContent}
</Text>,
)
} else if (fullMatch.startsWith("*") && fullMatch.endsWith("*")) {
// Italic
nodes.push(
<Text italic key={key}>
{fullMatch.slice(1, -1)}
</Text>,
)
} else if (fullMatch.startsWith("`") && fullMatch.endsWith("`")) {
// Inline code
nodes.push(<Text key={key}>{fullMatch.slice(1, -1)}</Text>)
}
lastIndex = regex.lastIndex
}
// Add remaining text (with Act Mode hint processing)
if (lastIndex < text.length) {
nodes.push(...addActModeHint(text.slice(lastIndex)))
}
return nodes.length > 0 ? nodes : addActModeHint(text)
function renderTokens(tokens: Token[], color?: string): React.ReactNode[] {
return tokens.map((token, i) => renderToken(token, i, color))
}
/**
* Render text with inline markdown support
* Render a single marked token (block or inline) as an Ink React node.
* Handles both block-level tokens (heading, paragraph, list, code, etc.)
* and inline tokens (strong, em, codespan, link, text).
*/
function renderToken(token: Token, key: number, color?: string): React.ReactNode {
switch (token.type) {
// --- Block tokens ---
case "heading": {
const { depth, tokens } = token as Tokens.Heading
return (
<Box key={key} marginY={depth === 1 ? 1 : 0}>
<Text bold color={color}>
{renderTokens(tokens, color)}
</Text>
</Box>
)
}
case "paragraph":
return (
<Text color={color} key={key}>
{renderTokens((token as Tokens.Paragraph).tokens, color)}
</Text>
)
case "code":
return (
<Box flexDirection="column" key={key} marginY={1}>
{(token as Tokens.Code).text.split("\n").map((line, i) => (
<Text color="cyan" key={i}>
{line || " "}
</Text>
))}
</Box>
)
case "list": {
const { ordered, start, items } = token as Tokens.List
return (
<Box flexDirection="column" key={key}>
{items.map((item, i) => (
<Box flexDirection="row" key={i}>
<Text color="gray">{ordered ? `${Number(start ?? 1) + i}. ` : "• "}</Text>
<Box flexDirection="column" flexGrow={1}>
{renderTokens(item.tokens, color)}
</Box>
</Box>
))}
</Box>
)
}
case "blockquote":
return (
<Box flexDirection="row" key={key}>
<Text color="gray"> </Text>
<Box flexDirection="column">{renderTokens((token as Tokens.Blockquote).tokens, color)}</Box>
</Box>
)
case "space":
return <Text key={key}> </Text>
// --- Inline tokens ---
case "strong":
return (
<Text bold color={color} key={key}>
{renderTokens((token as Tokens.Strong).tokens, color)}
</Text>
)
case "em":
return (
<Text color={color} italic key={key}>
{renderTokens((token as Tokens.Em).tokens, color)}
</Text>
)
case "codespan":
return <Text key={key}>{(token as Tokens.Codespan).text}</Text>
case "link": {
const { text, href } = token as Tokens.Link
return (
<Text color={color} key={key}>
{text && text !== href ? `${text} (${href})` : href}
</Text>
)
}
case "text": {
const { text, tokens } = token as Tokens.Text
if (tokens?.length) {
return (
<Text color={color} key={key}>
{renderTokens(tokens, color)}
</Text>
)
}
return (
<Text color={color} key={key}>
{addActModeHint(text, `${key}`)}
</Text>
)
}
// Fallback for any unhandled token type
default:
return "raw" in token ? (
<Text color={color} key={key}>
{(token as { raw: string }).raw}
</Text>
) : null
}
}
/**
* Render a markdown string as Ink components.
* Uses marked's lexer to parse markdown into tokens, then renders
* each token to the appropriate Ink component.
*/
const MarkdownText: React.FC<{ children: string; color?: string }> = ({ children, color }) => {
const nodes = renderInlineMarkdown(children)
return <Text color={color}>{nodes}</Text>
const tokens = lexer(children)
return <Box flexDirection="column">{renderTokens(tokens, color)}</Box>
}
interface ChatMessageProps {
@@ -126,10 +200,20 @@ interface ChatMessageProps {
* For this to work properly, parent containers must have width="100%"
* so flexGrow={1} on the content box has a reference width to fill.
*/
const DotRow: React.FC<{ children: React.ReactNode; color?: string }> = ({ children, color }) => (
const DotRow: React.FC<{ children: React.ReactNode; color?: string; flashing?: boolean }> = ({
children,
color,
flashing = false,
}) => (
<Box flexDirection="row">
<Box width={2}>
<Text color={color}></Text>
{flashing ? (
<Text color={color}>
<Spinner type="toggle8" />
</Text>
) : (
<Text color={color}></Text>
)}
</Box>
<Box flexGrow={1}>{children}</Box>
</Box>
@@ -213,7 +297,7 @@ function truncate(text: string, maxLength: number): string {
/**
* Format tool result for display
*/
function formatToolResult(result: string, maxLines: number = 5): string[] {
function formatToolResult(result: string, maxLines = 5): string[] {
const lines = result.split("\n")
if (lines.length <= maxLines) {
return lines
@@ -223,8 +307,8 @@ function formatToolResult(result: string, maxLines: number = 5): string[] {
return displayLines
}
export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
const { type, ask, say, text } = message
export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode, isStreaming }) => {
const { type, ask, say, text, partial } = message
const toolColor = mode === "plan" ? "yellow" : COLORS.primaryBlue
const { columns: terminalWidth } = useTerminalSize()
@@ -280,11 +364,11 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (isFileEditTool(toolInfo.toolName) && filePath && toolInfo.args.content) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<ToolCallText args={toolInfo.args} isAsk={isToolAsk} mode={mode} toolName={toolInfo.toolName} />
</DotRow>
<Box marginLeft={2}>
<DiffView content={toolInfo.args.content} filePath={filePath as string | undefined} />
<DiffView content={toolInfo.args.content as string} filePath={filePath as string | undefined} />
</Box>
</Box>
)
@@ -299,7 +383,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<ToolCallText args={toolInfo.args} isAsk={isToolAsk} mode={mode} toolName={toolInfo.toolName} />
</DotRow>
{contentLines.length > 0 && (
@@ -318,7 +402,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (isToolSay) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text color={toolColor}>{truncate(text, 100)}</Text>
</DotRow>
</Box>
@@ -340,7 +424,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text>
<Text color={toolColor}>{label}</Text>
<Text>{truncate(command, 120)}</Text>
@@ -379,12 +463,12 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if ((type === "ask" && ask === "use_mcp_server") || say === "use_mcp_server") {
const isAsk = type === "ask"
const parsed = text
? jsonParseSafe<ClineAskUseMcpServer>(text, {
type: undefined as ClineAskUseMcpServer["type"] | undefined,
? jsonParseSafe<Partial<ClineAskUseMcpServer> & { serverName: string }>(text, {
type: undefined,
serverName: "unknown server",
toolName: undefined as string | undefined,
arguments: undefined as string | undefined,
uri: undefined as string | undefined,
toolName: undefined,
arguments: undefined,
uri: undefined,
})
: undefined
@@ -410,7 +494,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text>
<Text color={toolColor}>{actionLabel}</Text>
<Text>{`: ${serverName}`}</Text>
@@ -435,12 +519,16 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
)
}
if ((type === "ask" && ask === "use_subagents") || say === "use_subagents" || say === "subagent") {
return <SubagentMessage isStreaming={isStreaming} message={message} mode={mode} />
}
// MCP response
if (say === "mcp_server_response" && text) {
const lines = formatToolResult(text, 8)
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text color={toolColor}>MCP response</Text>
</DotRow>
<Box flexDirection="column" marginLeft={2} width="100%">
@@ -581,7 +669,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (say === "browser_action" || say === "browser_action_launch") {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text>
<Text color={toolColor}>Cline used the browser</Text>
{text && (
@@ -600,7 +688,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (say === "mcp_server_request_started") {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text>
<Text color={toolColor}>Cline is using an MCP tool</Text>
{text && (
@@ -728,7 +816,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (type === "ask" && ask === "condense" && text) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={COLORS.primaryBlue}>
<DotRow color={COLORS.primaryBlue} flashing={partial === true && isStreaming}>
<Text bold color={COLORS.primaryBlue}>
Cline wants to condense your conversation:
</Text>
@@ -744,7 +832,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (type === "ask" && ask === "summarize_task" && text) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={COLORS.primaryBlue}>
<DotRow color={COLORS.primaryBlue} flashing={partial === true && isStreaming}>
<Text bold color={COLORS.primaryBlue}>
Cline wants to summarize the task:
</Text>
@@ -760,7 +848,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode }) => {
if (type === "ask" && ask === "report_bug" && text) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={COLORS.primaryBlue}>
<DotRow color={COLORS.primaryBlue} flashing={partial === true && isStreaming}>
<Text bold color={COLORS.primaryBlue}>
Cline wants to create a Github issue:
</Text>
@@ -789,6 +877,8 @@ export const ChatMessageList: React.FC<ChatMessageListProps> = ({ messages, maxM
const displayMessages = messages.filter((m) => {
// Skip api_req_finished, they're just markers
if (m.say === "api_req_finished") return false
// Skip hidden aggregated usage messages
if (m.say === "subagent_usage") return false
// Skip empty text messages
if (m.say === "text" && !m.text?.trim()) return false
// Skip checkpoint messages
+54 -48
View File
@@ -1,7 +1,7 @@
/**
* Tests for ChatView component exit and cleanup behavior
*
* These tests verify that when the user exits (via Ctrl+C or other means),
* These tests verify that when the user exits (via shutdown event or other means),
* the input field is properly hidden before the app terminates.
*/
@@ -12,8 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { ChatView } from "./ChatView"
// Helper to wait for async state updates
// Using 60ms since handleExit has a 50ms setTimeout
const delay = (ms: number = 60) => new Promise((resolve) => setTimeout(resolve, ms))
const delay = (ms = 60) => new Promise((resolve) => setTimeout(resolve, ms))
// Type for our exit mock function
type ExitMockFn = ReturnType<typeof vi.fn> & (() => void)
@@ -127,12 +126,16 @@ vi.mock("../utils/file-search", () => ({
searchWorkspaceFiles: vi.fn(async () => []),
}))
vi.mock("../utils/slash-commands", () => ({
extractSlashQuery: vi.fn(() => ({ inSlashMode: false, query: "", slashIndex: -1 })),
filterCommands: vi.fn(() => []),
insertSlashCommand: vi.fn((text: string) => text),
sortCommandsWorkflowsFirst: vi.fn((cmds: unknown[]) => cmds),
}))
vi.mock("../utils/slash-commands", async (importOriginal) => {
const actual = await importOriginal<typeof import("../utils/slash-commands")>()
return {
...actual,
extractSlashQuery: vi.fn(() => ({ inSlashMode: false, query: "", slashIndex: -1 })),
filterCommands: vi.fn(() => []),
insertSlashCommand: vi.fn((text: string) => text),
sortCommandsWorkflowsFirst: vi.fn((cmds: unknown[]) => cmds),
}
})
vi.mock("../utils/input", () => ({
isMouseEscapeSequence: vi.fn(() => false),
@@ -175,12 +178,21 @@ vi.mock("@shared/getApiMetrics", () => ({
totalTokensOut: 0,
totalCost: 0,
})),
getLastApiReqTotalTokens: vi.fn(() => 0),
}))
vi.mock("child_process", () => ({
exec: vi.fn(),
execSync: vi.fn(() => "main"),
}))
// Mock telemetry service to prevent HostProvider errors in shutdown handler
vi.mock("@/services/telemetry", () => ({
telemetryService: {
captureHostEvent: vi.fn(),
},
}))
// Helper to create a typed mock for onExit
const createExitMock = (): ExitMockFn => vi.fn() as ExitMockFn
@@ -213,33 +225,6 @@ describe("ChatView Exit and Cleanup", () => {
})
})
describe("Ctrl+C exit handling", () => {
it("should hide input but keep footer, then call onExit", async () => {
const { lastFrame, stdin } = render(<ChatView onExit={mockOnExit} />)
// Verify UI visible before Ctrl+C
expect(lastFrame()).toContain("Input:")
expect(lastFrame()).toContain("@ for files")
// Simulate Ctrl+C
stdin.write("\x03")
// onExit should not be called immediately
expect(mockOnExit).not.toHaveBeenCalled()
// Wait for state update and callback
await delay()
// Input should be hidden, but footer should remain
const frameAfter = lastFrame()
expect(frameAfter).not.toContain("Input:")
expect(frameAfter).toContain("@ for files")
// onExit should have been called
expect(mockOnExit).toHaveBeenCalledTimes(1)
})
})
describe("Shutdown event handling", () => {
it("should subscribe on mount and unsubscribe on unmount", () => {
const { unmount } = render(<ChatView onExit={mockOnExit} />)
@@ -249,39 +234,59 @@ describe("ChatView Exit and Cleanup", () => {
expect(shutdownMockState.listeners.length).toBe(0)
})
it("should hide UI when shutdown event fires", async () => {
it("should hide input when shutdown event fires", async () => {
const { lastFrame } = render(<ChatView onExit={mockOnExit} />)
// Input should be visible initially
expect(lastFrame()).toContain("Input:")
// Fire shutdown event (simulates Ctrl+C)
shutdownMockState.fire()
await delay()
// Input should be hidden after shutdown
expect(lastFrame()).not.toContain("Input:")
})
it("should preserve footer when shutdown event fires", async () => {
const { lastFrame } = render(<ChatView onExit={mockOnExit} />)
// Footer should be visible initially
expect(lastFrame()).toContain("@ for files")
// Fire shutdown event
shutdownMockState.fire()
await delay()
// Footer should still be present (only input is hidden)
expect(lastFrame()).toContain("@ for files")
})
})
describe("Edge cases", () => {
it("should handle exit when onExit prop is undefined", async () => {
const { lastFrame, stdin } = render(<ChatView />)
it("should handle shutdown event when onExit prop is undefined", async () => {
const { lastFrame } = render(<ChatView />)
stdin.write("\x03")
// Fire shutdown event
shutdownMockState.fire()
await delay()
// Should not throw, UI should still hide
expect(lastFrame()).not.toContain("Input:")
})
it("should handle multiple Ctrl+C presses gracefully", async () => {
const { stdin } = render(<ChatView onExit={mockOnExit} />)
it("should handle multiple shutdown events gracefully", async () => {
const { lastFrame } = render(<ChatView onExit={mockOnExit} />)
stdin.write("\x03")
stdin.write("\x03")
stdin.write("\x03")
// Fire multiple shutdown events
shutdownMockState.fire()
shutdownMockState.fire()
shutdownMockState.fire()
await delay()
expect(mockOnExit).toHaveBeenCalled()
// UI should still hide properly
expect(lastFrame()).not.toContain("Input:")
})
})
})
@@ -294,14 +299,15 @@ describe("ChatView UI State During Exit", () => {
it("should preserve static content and footer, only hide input during exit", async () => {
const onExit = createExitMock()
const { lastFrame, stdin } = render(<ChatView onExit={onExit} />)
const { lastFrame } = render(<ChatView onExit={onExit} />)
// Footer contains auto-approve toggle
expect(lastFrame()).toContain("Auto-approve")
expect(lastFrame()).toContain("What can I do for you?")
expect(lastFrame()).toContain("Input:")
stdin.write("\x03")
// Fire shutdown event
shutdownMockState.fire()
await delay()
const frameAfter = lastFrame()
+240 -97
View File
@@ -103,15 +103,16 @@
import type { ApiProvider, ModelInfo } from "@shared/api"
import { combineCommandSequences } from "@shared/combineCommandSequences"
import { combineHookSequences } from "@shared/combineHookSequences"
import type { ClineAsk, ClineMessage } from "@shared/ExtensionMessage"
import { getApiMetrics, getLastApiReqTotalTokens } from "@shared/getApiMetrics"
import { EmptyRequest, StringRequest } from "@shared/proto/cline/common"
import type { SlashCommandInfo } from "@shared/proto/cline/slash"
import { CLI_ONLY_COMMANDS } from "@shared/slashCommands"
import { getProviderModelIdKey } from "@shared/storage"
import { getProviderDefaultModelId, getProviderModelIdKey } from "@shared/storage"
import type { Mode } from "@shared/storage/types"
import { execSync } from "child_process"
import { Box, Static, Text, useApp, useInput } from "ink"
// biome-ignore lint/style/useImportType: JSX requires React as a value (jsx: "react" in tsconfig)
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { getAvailableSlashCommands } from "@/core/controller/slash/getAvailableSlashCommands"
import { showTaskWithId } from "@/core/controller/task/showTaskWithId"
@@ -135,7 +136,15 @@ import {
} from "../utils/file-search"
import { isMouseEscapeSequence } from "../utils/input"
import { jsonParseSafe, parseImagesFromInput } from "../utils/parser"
import { extractSlashQuery, filterCommands, insertSlashCommand, sortCommandsWorkflowsFirst } from "../utils/slash-commands"
import {
createCliOnlySlashCommands,
extractSlashQuery,
filterCommands,
getStandaloneSlashCommandToExecute,
insertSlashCommand,
sortCommandsWorkflowsFirst,
} from "../utils/slash-commands"
import { waitFor } from "../utils/timeout"
import { isFileEditTool, parseToolFromMessage } from "../utils/tools"
import { shutdownEvent } from "../vscode-shim"
import { ActionButtons, type ButtonActionType, getButtonConfig, getVisibleButtons } from "./ActionButtons"
@@ -147,9 +156,28 @@ import { HighlightedInput } from "./HighlightedInput"
import { HistoryPanelContent } from "./HistoryPanelContent"
import { providerModels } from "./ModelPicker"
import { SettingsPanelContent } from "./SettingsPanelContent"
import { SkillsPanelContent } from "./SkillsPanelContent"
import { SlashCommandMenu } from "./SlashCommandMenu"
import { ThinkingIndicator } from "./ThinkingIndicator"
/**
* Persistent input storage that survives React remounts (e.g., during terminal resize).
* Keyed by a stable identifier so each task/session maintains its own input state.
*/
interface PersistedInputState {
text: string
cursorPos: number
pastedTexts: Map<number, string>
pasteCounter: number
}
const inputStateStorage = new Map<string, PersistedInputState>()
function getInputStorageKey(controller: any, taskId?: string): string {
// Use taskId if available, otherwise fall back to controller instance
return taskId || (controller?.task?.taskId ?? "default")
}
interface ChatViewProps {
controller?: any
onExit?: () => void
@@ -208,9 +236,9 @@ function getGitDiffStats(cwd?: string): GitDiffStats | null {
const delMatch = output.match(/(\d+) deletion/)
return {
files: filesMatch ? parseInt(filesMatch[1], 10) : 0,
additions: addMatch ? parseInt(addMatch[1], 10) : 0,
deletions: delMatch ? parseInt(delMatch[1], 10) : 0,
files: filesMatch ? Number.parseInt(filesMatch[1], 10) : 0,
additions: addMatch ? Number.parseInt(addMatch[1], 10) : 0,
deletions: delMatch ? Number.parseInt(delMatch[1], 10) : 0,
}
} catch {
return null
@@ -221,7 +249,7 @@ function getGitDiffStats(cwd?: string): GitDiffStats | null {
* Create a progress bar for context window usage
* Returns { filled, empty } strings to allow different coloring
*/
function createContextBar(used: number, total: number, width: number = 8): { filled: string; empty: string } {
function createContextBar(used: number, total: number, width = 8): { filled: string; empty: string } {
const ratio = Math.min(used / total, 1)
// Use ceil so any usage > 0 shows at least one bar
const filledCount = used > 0 ? Math.max(1, Math.ceil(ratio * width)) : 0
@@ -311,7 +339,7 @@ function parseAskOptions(text: string): string[] {
*/
function expandPastedTexts(text: string, pastedTexts: Map<number, string>): string {
return text.replace(/\[Pasted text #(\d+) \+\d+ lines\]/g, (match, num) => {
const content = pastedTexts.get(parseInt(num, 10))
const content = pastedTexts.get(Number.parseInt(num, 10))
return content ?? match
})
}
@@ -348,9 +376,14 @@ export const ChatView: React.FC<ChatViewProps> = ({
insertText: insertTextAtCursor,
} = useTextInput()
// Ref for text input (used by useHomeEndKeys)
// Get storage key for persisting input across remounts
const storageKey = useMemo(() => getInputStorageKey(ctrl, taskId), [ctrl, taskId])
// Refs for text input and cursor position (used by useHomeEndKeys and to avoid stale closures in useInput)
const textInputRef = useRef(textInput)
textInputRef.current = textInput
const cursorPosRef = useRef(cursorPos)
cursorPosRef.current = cursorPos
const [fileResults, setFileResults] = useState<FileSearchResult[]>([])
const [selectedIndex, setSelectedIndex] = useState(0) // For file menu
@@ -362,8 +395,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
const [userScrolled, setUserScrolled] = useState(false)
// Pasted text storage - maps placeholder number to full pasted content
const [pastedTexts, setPastedTexts] = useState<Map<number, string>>(new Map())
const pasteCounterRef = useRef(0)
const [pastedTexts, setPastedTexts] = useState<Map<number, string>>(() => {
return inputStateStorage.get(storageKey)?.pastedTexts ?? new Map()
})
const pasteCounterRef = useRef<number>(inputStateStorage.get(storageKey)?.pasteCounter ?? 0)
// Track paste timing to combine chunks that arrive in rapid succession
const lastPasteTimeRef = useRef<number>(0)
const activePasteNumRef = useRef<number>(0)
@@ -374,7 +409,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
const PASTE_UPDATE_DEBOUNCE_MS = 50 // Debounce visual updates to avoid flicker
// Slash command state
const [availableCommands, setAvailableCommands] = useState<SlashCommandInfo[]>([])
const [availableCommands, setAvailableCommands] = useState<SlashCommandInfo[]>(() => createCliOnlySlashCommands())
const [selectedSlashIndex, setSelectedSlashIndex] = useState(0)
const [slashMenuDismissed, setSlashMenuDismissed] = useState(false)
const lastSlashIndexRef = useRef<number>(-1)
@@ -384,6 +419,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
| { type: "settings"; initialMode?: "model-picker" | "featured-models"; initialModelKey?: "actModelId" | "planModelId" }
| { type: "history" }
| { type: "help" }
| { type: "skills" }
| null
>(null)
@@ -397,6 +433,29 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Track when we're exiting to hide UI elements before exit
const [isExiting, setIsExiting] = useState(false)
// Restore input state from storage on mount (after resize remount)
useEffect(() => {
const stored = inputStateStorage.get(storageKey)
if (stored) {
setTextInput(stored.text)
setCursorPos(stored.cursorPos)
setPastedTexts(stored.pastedTexts)
pasteCounterRef.current = stored.pasteCounter
}
}, [storageKey, setTextInput, setCursorPos])
// Persist input state to storage whenever it changes (survives remount)
useEffect(() => {
if (textInput || pastedTexts.size > 0) {
inputStateStorage.set(storageKey, {
text: textInput,
cursorPos,
pastedTexts: new Map(pastedTexts),
pasteCounter: pasteCounterRef.current,
})
}
}, [storageKey, textInput, cursorPos, pastedTexts])
// Task switch handling: when switching tasks via /history, we clear the terminal and
// increment a counter used as the root Box's key. This forces React to remount the tree,
// giving us a fresh Static instance. Mirrors how App.tsx handles resize with resizeKey.
@@ -423,7 +482,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
return stateManager.getGlobalSettingsKey("mode") || "act"
})
const [yolo, setYolo] = useState<boolean>(() => StateManager.get().getGlobalSettingsKey("yoloModeToggled") ?? false)
const [yolo, _setYolo] = useState<boolean>(() => StateManager.get().getGlobalSettingsKey("yoloModeToggled") ?? false)
const [autoApproveAll, setAutoApproveAll] = useState<boolean>(
() => StateManager.get().getGlobalSettingsKey("autoApproveAllToggled") ?? false,
)
@@ -451,11 +510,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Get model ID based on current mode and provider
// Different providers use different state keys (e.g., cline uses actModeOpenRouterModelId)
// Re-read when activePanel changes (settings panel closes) to pick up changes
// Falls back to provider's default model if no model has been explicitly set
const modelId = useMemo(() => {
if (!provider) return ""
const stateManager = StateManager.get()
const modelKey = getProviderModelIdKey(provider as ApiProvider, mode)
return (stateManager.getGlobalSettingsKey(modelKey as string) as string) || ""
return (stateManager.getGlobalSettingsKey(modelKey) as string) || getProviderDefaultModelId(provider as ApiProvider) || ""
}, [mode, provider, activePanel])
const toggleMode = useCallback(async () => {
@@ -488,12 +548,14 @@ export const ChatView: React.FC<ChatViewProps> = ({
clearState() // Force clear React state (bypasses empty messages check)
setTextInput("")
setCursorPos(0)
// Clear persisted state
inputStateStorage.delete(storageKey)
// Post the now-empty state
if (ctrl) {
ctrl.postStateToWebview()
}
}, [ctrl, clearState])
}, [ctrl, clearState, storageKey])
const refs = useRef({
searchTimeout: null as NodeJS.Timeout | null,
@@ -558,16 +620,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
try {
const response = await getAvailableSlashCommands(ctrl, EmptyRequest.create())
const cliCommands = response.commands.filter((cmd) => cmd.cliCompatible !== false)
// Add CLI-only commands (like /settings) that are handled locally
const cliOnlyCommands: SlashCommandInfo[] = CLI_ONLY_COMMANDS.map((cmd) => ({
name: cmd.name,
description: cmd.description || "",
section: cmd.section || "default",
cliCompatible: true,
}))
// Add CLI-only commands (like /settings) that are handled locally.
// Seed these synchronously on first render so locally handled commands like
// /q and /exit are immediately available, even before the async command
// fetch completes. This avoids a race that can make the quit command tests
// flaky on slower Windows CI runners.
const cliOnlyCommands = createCliOnlySlashCommands()
setAvailableCommands([...cliOnlyCommands, ...sortCommandsWorkflowsFirst(cliCommands)])
} catch {
// Fallback: commands will be empty, menu won't show
// Keep CLI-only commands available even if backend command loading fails.
}
}
loadCommands()
@@ -604,8 +665,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
return true
})
// Combine command messages with their output (like webview does)
return combineCommandSequences(filtered)
// Combine hook messages with their output, then command messages (like webview does)
// CLI always has hooks enabled, so we always apply combineHookSequences
const withHooks = combineHookSequences(filtered)
return combineCommandSequences(withHooks)
}, [messages])
// Detect task switches by watching first message timestamp change.
@@ -752,6 +815,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
setCursorPos(0)
setPastedTexts(new Map()) // Clear stored pastes
pasteCounterRef.current = 0
// Clear persisted state
inputStateStorage.delete(storageKey)
try {
await ctrl.task.handleWebviewAskResponse(responseType, expandedText)
@@ -759,7 +824,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Controller may be disposed
}
},
[ctrl, pendingAsk, pastedTexts],
[ctrl, pendingAsk, pastedTexts, storageKey],
)
// Handle cancel/interrupt
@@ -783,6 +848,77 @@ export const ChatView: React.FC<ChatViewProps> = ({
}, 150)
}, [inkExit, onExit])
const handleCliOnlySlashCommand = useCallback(
(commandName: string): boolean => {
if (commandName === "help") {
setActivePanel({ type: "help" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "settings") {
setActivePanel({ type: "settings" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "models") {
const apiConfig = StateManager.get().getApiConfiguration()
const provider =
mode === "act"
? apiConfig.actModeApiProvider || apiConfig.planModeApiProvider
: apiConfig.planModeApiProvider || apiConfig.actModeApiProvider
const initialMode = !provider ? undefined : provider === "cline" ? "featured-models" : "model-picker"
const initialModelKey = mode === "act" ? "actModelId" : "planModelId"
setActivePanel({ type: "settings", initialMode, initialModelKey })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "history") {
setActivePanel({ type: "history" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "skills") {
setActivePanel({ type: "skills" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "clear") {
void clearViewAndResetTask()
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return true
}
if (commandName === "exit" || commandName === "q") {
handleExit()
return true
}
return false
},
[clearViewAndResetTask, handleExit, mode, setCursorPos, setTextInput],
)
// Get button config based on the last message state
const buttonConfig = useMemo(() => {
const lastMsg = messages[messages.length - 1] as ClineMessage | undefined
@@ -850,6 +986,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
setCursorPos(0)
setPastedTexts(new Map()) // Clear stored pastes
pasteCounterRef.current = 0
// Clear persisted state
inputStateStorage.delete(storageKey)
try {
// Convert image paths to data URLs if needed
@@ -877,10 +1015,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
onError?.()
}
},
[ctrl, onError, pastedTexts],
[ctrl, onError, pastedTexts, storageKey],
)
// Auto-submit initial prompt if provided
// When taskId is also provided, this sends the prompt to resume the existing task
// When no taskId, this creates a new task with the prompt
useEffect(() => {
const autoSubmit = async () => {
if (!initialPrompt && (!initialImages || initialImages.length === 0)) {
@@ -901,8 +1041,32 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (initialPrompt) {
setTerminalTitle(initialPrompt)
}
// initialImages are already data URLs from index.ts processing
await ctrl.initTask(initialPrompt || "", initialImages && initialImages.length > 0 ? initialImages : undefined)
if (taskId) {
// Resuming an existing task with a prompt - wait for task to load first
// The task loading happens in the other useEffect via showTaskWithId
// We need to wait for it to complete before sending the resume message
const task = await waitFor(() => ctrl.task, 5000)
if (task) {
// Send the prompt as a message to resume the task
await task.handleWebviewAskResponse("messageResponse", initialPrompt || "")
} else {
// Task failed to load, fall back to creating new task
Logger.error(`Failed to load task ${taskId} for resume, creating new task instead`)
await ctrl.initTask(
initialPrompt || "",
initialImages && initialImages.length > 0 ? initialImages : undefined,
)
}
} else {
// New task - use initTask
// initialImages are already data URLs from index.ts processing
await ctrl.initTask(
initialPrompt || "",
initialImages && initialImages.length > 0 ? initialImages : undefined,
)
}
} catch (_error) {
onError?.()
}
@@ -998,11 +1162,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
// 3. Handle Option+arrow via key.meta (backup - Ink sometimes parses these instead of passing raw sequence)
if (key.meta) {
if (key.leftArrow) {
setCursorPos(findWordStart(textInput, cursorPos))
setCursorPos(findWordStart(textInputRef.current, cursorPosRef.current))
return
}
if (key.rightArrow) {
setCursorPos(findWordEnd(textInput, cursorPos))
setCursorPos(findWordEnd(textInputRef.current, cursorPosRef.current))
return
}
}
@@ -1014,6 +1178,17 @@ export const ChatView: React.FC<ChatViewProps> = ({
const inSlashMenu = slashInfo.inSlashMode && filteredCommands.length > 0 && !slashMenuDismissed
const inFileMenu = mentionInfo.inMentionMode && fileResults.length > 0 && !inSlashMenu
const standaloneSlashCommand = getStandaloneSlashCommandToExecute({
prompt,
inSlashMode: slashInfo.inSlashMode,
hasSlashMenu: inSlashMenu,
hasPendingAsk: !!pendingAsk,
isSpinnerActive,
})
if (key.return && standaloneSlashCommand && handleCliOnlySlashCommand(standaloneSlashCommand)) {
return
}
// 5. Slash command menu navigation (takes priority over file menu)
if (inSlashMenu) {
@@ -1028,56 +1203,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (key.tab || key.return) {
const cmd = filteredCommands[selectedSlashIndex]
if (cmd) {
// Handle CLI-only commands locally
if (cmd.name === "help") {
setActivePanel({ type: "help" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "settings") {
setActivePanel({ type: "settings" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "models") {
const apiConfig = StateManager.get().getApiConfiguration()
// Use current mode's provider to determine picker type
const provider =
mode === "act"
? apiConfig.actModeApiProvider || apiConfig.planModeApiProvider
: apiConfig.planModeApiProvider || apiConfig.actModeApiProvider
const initialMode = !provider ? undefined : provider === "cline" ? "featured-models" : "model-picker"
// Set model for current mode (plan or act)
const initialModelKey = mode === "act" ? "actModelId" : "planModelId"
setActivePanel({ type: "settings", initialMode, initialModelKey })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "history") {
setActivePanel({ type: "history" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "clear") {
clearViewAndResetTask()
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "exit") {
handleExit()
if (handleCliOnlySlashCommand(cmd.name)) {
return
}
const newText = insertSlashCommand(textInput, slashInfo.slashIndex, cmd.name)
@@ -1188,7 +1314,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (hasPrimary && buttonConfig.primaryAction) {
handleButtonAction(buttonConfig.primaryAction, true)
return
} else if (hasSecondary && !hasPrimary && buttonConfig.secondaryAction) {
}
if (hasSecondary && !hasPrimary && buttonConfig.secondaryAction) {
handleButtonAction(buttonConfig.secondaryAction, false)
return
}
@@ -1209,7 +1336,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
// Number selection for options (only when no text typed yet)
if (askType === "options") {
const num = parseInt(input, 10)
const num = Number.parseInt(input, 10)
if (textInput === "" && !Number.isNaN(num) && num >= 1 && num <= askOptions.length) {
const selectedOption = askOptions[num - 1]
sendAskResponse("messageResponse", selectedOption)
@@ -1251,10 +1378,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
pasteUpdateTimeoutRef.current = setTimeout(() => {
const newPlaceholder = `[Pasted text #${pasteNum} +${activePasteLinesRef.current} lines]`
setTextInput((prev) => {
const pattern = new RegExp(`\\[Pasted text #${pasteNum} \\+\\d+ lines\\]`)
return prev.replace(pattern, newPlaceholder)
})
const pattern = new RegExp(`\\[Pasted text #${pasteNum} \\+\\d+ lines\\]`)
const newText = textInputRef.current.replace(pattern, newPlaceholder)
textInputRef.current = newText // Update ref immediately so setCursorPos bounds check works
setTextInput(newText)
// Update cursor to be right after the placeholder
setCursorPos(activePasteStartPosRef.current + newPlaceholder.length)
Logger.info(`Paste #${pasteNum} complete: ${activePasteLinesRef.current} lines`)
@@ -1267,7 +1394,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
pasteCounterRef.current += 1
const pasteNum = pasteCounterRef.current
activePasteNumRef.current = pasteNum
activePasteStartPosRef.current = cursorPos // Track where placeholder starts
const currentCursorPos = cursorPosRef.current // Use ref to avoid stale closure
activePasteStartPosRef.current = currentCursorPos // Track where placeholder starts
// Count line breaks in the pasted content (handle both \n and \r)
const extraLines = input.match(/[\r\n]/g)?.length || 0
activePasteLinesRef.current = extraLines // Track total lines
@@ -1279,8 +1407,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
return next
})
setTextInput((prev) => prev.slice(0, cursorPos) + placeholder + prev.slice(cursorPos))
setCursorPos(cursorPos + placeholder.length)
const newText =
textInputRef.current.slice(0, currentCursorPos) + placeholder + textInputRef.current.slice(currentCursorPos)
textInputRef.current = newText // Update ref immediately so setCursorPos bounds check works
setTextInput(newText)
setCursorPos(currentCursorPos + placeholder.length)
return // Exit early - don't also add the raw input via normal handling below
}
@@ -1309,15 +1440,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
return
}
if (key.rightArrow && !inSlashMenu && !inFileMenu) {
setCursorPos((pos) => Math.min(textInput.length, pos + 1))
setCursorPos((pos) => Math.min(textInputRef.current.length, pos + 1))
return
}
if (key.upArrow && !inSlashMenu && !inFileMenu) {
setCursorPos(moveCursorUp(textInput, cursorPos))
setCursorPos(moveCursorUp(textInputRef.current, cursorPosRef.current))
return
}
if (key.downArrow && !inSlashMenu && !inFileMenu) {
setCursorPos(moveCursorDown(textInput, cursorPos))
setCursorPos(moveCursorDown(textInputRef.current, cursorPosRef.current))
return
}
// Normal input (single char or short paste)
@@ -1361,13 +1492,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (item.type === "header") {
// Show static robot frame in header (first frame, looking straight ahead)
return (
<Box flexDirection="column" key="header">
<Box flexDirection="column" key="header" marginBottom={1}>
<StaticRobotFrame />
<Text> </Text>
<Text bold color="white">
{centerText("What can I do for you?")}
</Text>
<Text> </Text>
</Box>
)
}
@@ -1383,10 +1513,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Dynamic region - only current streaming message + input */}
<Box flexDirection="column" width="100%">
{/* Animated robot and welcome text - only shown before messages start and user hasn't scrolled */}
{/* Animated robot and welcome text - only shown before messages start and user hasn't interacted */}
{isWelcomeState && (
<Box flexDirection="column" marginBottom={1}>
<AsciiMotionCli onScroll={() => setUserScrolled(true)} />
<AsciiMotionCli onInteraction={() => setUserScrolled(true)} />
<Text> </Text>
<Text bold color="white">
{centerText("What can I do for you?")}
@@ -1454,6 +1584,19 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Help panel */}
{activePanel?.type === "help" && <HelpPanelContent onClose={() => setActivePanel(null)} />}
{/* Skills panel */}
{activePanel?.type === "skills" && ctrl && (
<SkillsPanelContent
controller={ctrl}
onClose={() => setActivePanel(null)}
onUseSkill={(skillPath) => {
setActivePanel(null)
setTextInput(`@${skillPath} `)
setCursorPos(skillPath.length + 2)
}}
/>
)}
{/* Slash command menu - below input (takes priority over file menu) */}
{showSlashMenu && !activePanel && (
<Box paddingLeft={1} paddingRight={1}>
+4 -3
View File
@@ -7,6 +7,7 @@ import type { ClineMessage } from "@shared/ExtensionMessage"
import { Box, Text, useInput } from "ink"
import React, { useState } from "react"
import { useStdinContext } from "../context/StdinContext"
import { isEnterKey } from "../utils/input"
export type RestoreType = "task" | "workspace" | "taskAndWorkspace"
@@ -101,7 +102,7 @@ export const CheckpointMenu: React.FC<CheckpointMenuProps> = ({ messages, onSele
setSelectedCheckpoint((i) => Math.max(0, i - 1))
} else if (key.downArrow) {
setSelectedCheckpoint((i) => Math.min(checkpoints.length - 1, i + 1))
} else if (key.return && checkpoints.length > 0) {
} else if (isEnterKey(input, key) && checkpoints.length > 0) {
setStage("restoreType")
}
} else if (stage === "restoreType") {
@@ -109,7 +110,7 @@ export const CheckpointMenu: React.FC<CheckpointMenuProps> = ({ messages, onSele
setSelectedRestoreType((i) => Math.max(0, i - 1))
} else if (key.downArrow) {
setSelectedRestoreType((i) => Math.min(RESTORE_TYPE_OPTIONS.length - 1, i + 1))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
const checkpoint = checkpoints[selectedCheckpoint]
const restoreType = RESTORE_TYPE_OPTIONS[selectedRestoreType]
if (checkpoint && restoreType) {
@@ -120,7 +121,7 @@ export const CheckpointMenu: React.FC<CheckpointMenuProps> = ({ messages, onSele
// Quick number selection for checkpoints
if (stage === "checkpoint") {
const num = parseInt(input, 10)
const num = Number.parseInt(input, 10)
if (!Number.isNaN(num) && num >= 1 && num <= checkpoints.length) {
setSelectedCheckpoint(num - 1)
setStage("restoreType")
+10
View File
@@ -84,6 +84,16 @@ describe("ConfigView", () => {
)
expect(lastFrame()).toContain("Global Settings")
})
it("hides Hooks tab when hooks are disabled", () => {
const { lastFrame } = render(<ConfigView {...defaultProps} hooksEnabled={false} skillsEnabled={true} />)
expect(lastFrame()).not.toContain("Hooks")
})
it("shows Hooks tab when hooks are enabled", () => {
const { lastFrame } = render(<ConfigView {...defaultProps} hooksEnabled={true} skillsEnabled={true} />)
expect(lastFrame()).toContain("Hooks")
})
})
describe("value formatting", () => {
+124 -18
View File
@@ -13,6 +13,7 @@ import {
import { Box, Text, useApp, useInput } from "ink"
import React, { useMemo, useState } from "react"
import { useStdinContext } from "../context/StdinContext"
import { fuzzyFilter } from "../utils/fuzzy-search"
import {
BooleanSelect,
buildConfigEntries,
@@ -21,6 +22,8 @@ import {
HookInfo,
HookRow,
MAX_VISIBLE,
ObjectEditorPanel,
ObjectEditorState,
parseValue,
SEPARATOR,
SectionHeader,
@@ -105,6 +108,8 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
const [isEditing, setIsEditing] = useState(false)
const [selectedIndex, setSelectedIndex] = useState(0)
const [editValue, setEditValue] = useState("")
const [searchQuery, setSearchQuery] = useState("")
const [objectEditor, setObjectEditor] = useState<ObjectEditorState | null>(null)
// Build entries for settings tab
const configEntries = useMemo(
@@ -112,6 +117,13 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
[globalState, workspaceState],
)
const filteredConfigEntries = useMemo(() => {
if (!searchQuery.trim()) {
return configEntries
}
return fuzzyFilter(configEntries, searchQuery, (entry) => `${entry.key} ${String(entry.value ?? "")}`)
}, [configEntries, searchQuery])
// Build entries for rules tab
const ruleEntries = useMemo(() => {
const entries: ToggleEntry[] = []
@@ -159,7 +171,7 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
const currentListLength = useMemo(() => {
switch (currentTab) {
case "settings":
return configEntries.length
return filteredConfigEntries.length
case "rules":
return ruleEntries.length
case "workflows":
@@ -171,7 +183,14 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
default:
return 0
}
}, [currentTab, configEntries.length, ruleEntries.length, workflowEntries.length, hookEntries.length, skillEntries.length])
}, [
currentTab,
filteredConfigEntries.length,
ruleEntries.length,
workflowEntries.length,
hookEntries.length,
skillEntries.length,
])
// Get available tabs
const availableTabs = useMemo(() => {
@@ -191,10 +210,11 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
setCurrentTab(newTab)
setSelectedIndex(0)
setIsEditing(false)
setObjectEditor(null)
}
// Settings tab handlers
const selectedConfigEntry = configEntries[selectedIndex]
const selectedConfigEntry = filteredConfigEntries[selectedIndex]
const handleSettingsSave = (value: string | boolean) => {
if (!selectedConfigEntry) {
@@ -210,6 +230,43 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
setIsEditing(false)
}
const getObjectAtPath = (root: Record<string, unknown>, path: string[]): Record<string, unknown> => {
let current: unknown = root
for (const segment of path) {
if (!current || typeof current !== "object") {
return {}
}
current = (current as Record<string, unknown>)[segment]
}
return current && typeof current === "object" ? (current as Record<string, unknown>) : {}
}
const setObjectValueAtPath = (
root: Record<string, unknown>,
path: string[],
key: string,
value: unknown,
): Record<string, unknown> => {
if (path.length === 0) {
return { ...root, [key]: value }
}
const [head, ...rest] = path
const child = root[head]
const childObj = child && typeof child === "object" ? (child as Record<string, unknown>) : {}
return {
...root,
[head]: setObjectValueAtPath(childObj, rest, key, value),
}
}
const persistObjectEditor = (nextObject: Record<string, unknown>, source: "global" | "workspace", key: string) => {
if (source === "global" && onUpdateGlobal) {
onUpdateGlobal(key as GlobalStateAndSettingsKey, nextObject as never)
} else if (source === "workspace" && onUpdateWorkspace) {
onUpdateWorkspace(key as LocalStateKey, nextObject as never)
}
}
const handleSettingsReset = () => {
if (!selectedConfigEntry?.isEditable || selectedConfigEntry.source !== "global") {
return
@@ -240,15 +297,22 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
// Input handling
useInput(
(input, key) => {
if (input.toLowerCase() === "q" || key.escape) {
if (objectEditor) {
return
}
if (key.escape) {
exit()
}
// Tab navigation with Tab key or number keys
if (key.tab || (input >= "1" && input <= "5")) {
const targetIdx = key.tab
? (availableTabs.findIndex((t) => t.key === currentTab) + 1) % availableTabs.length
: parseInt(input) - 1
if (key.leftArrow || key.rightArrow || (input >= "1" && input <= "5")) {
const currentTabIndex = availableTabs.findIndex((t) => t.key === currentTab)
const targetIdx =
input >= "1" && input <= "5"
? Number.parseInt(input) - 1
: key.leftArrow
? (currentTabIndex - 1 + availableTabs.length) % availableTabs.length
: (currentTabIndex + 1) % availableTabs.length
if (targetIdx >= 0 && targetIdx < availableTabs.length) {
handleTabChange(availableTabs[targetIdx].key)
}
@@ -256,21 +320,45 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
}
// List navigation (arrow keys and vim-style j/k)
if (key.upArrow || input === "k") {
if (key.upArrow) {
setSelectedIndex((i) => (i > 0 ? i - 1 : currentListLength - 1))
} else if (key.downArrow || input === "j") {
} else if (key.downArrow) {
setSelectedIndex((i) => (i < currentListLength - 1 ? i + 1 : 0))
}
// Tab-specific actions
if (currentTab === "settings") {
if ((key.return || input === "e") && selectedConfigEntry?.isEditable) {
if ((key.return || key.tab) && selectedConfigEntry?.isEditable) {
if (selectedConfigEntry.type === "boolean") {
handleSettingsSave(!selectedConfigEntry.value)
return
}
if (selectedConfigEntry.type === "object") {
const value =
selectedConfigEntry.value && typeof selectedConfigEntry.value === "object"
? (selectedConfigEntry.value as Record<string, unknown>)
: {}
setObjectEditor({
source: selectedConfigEntry.source,
key: selectedConfigEntry.key,
path: [],
value,
selectedIndex: 0,
isEditingValue: false,
editValue: "",
})
return
}
setEditValue(selectedConfigEntry.value !== undefined ? String(selectedConfigEntry.value) : "")
setIsEditing(true)
} else if (input === "r") {
} else if (key.ctrl && input.toLowerCase() === "r") {
handleSettingsReset()
} else if (key.backspace || key.delete) {
setSearchQuery((prev) => prev.slice(0, -1))
} else if (input && !key.ctrl && !key.meta && !key.escape && !key.upArrow && !key.downArrow) {
setSearchQuery((prev) => prev + input)
}
} else if (key.return || input === " ") {
} else if (key.return || key.tab || input === " ") {
// Toggle for rules/workflows/hooks/skills
handleToggle()
}
@@ -338,13 +426,31 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
)
}
if (objectEditor && currentTab === "settings") {
return (
<ObjectEditorPanel
getObjectAtPath={getObjectAtPath}
onClose={() => setObjectEditor(null)}
onPersist={(nextObject) => persistObjectEditor(nextObject, objectEditor.source, objectEditor.key)}
setObjectValueAtPath={setObjectValueAtPath}
setState={setObjectEditor}
state={objectEditor}
/>
)
}
// Render tab content
const renderTabContent = () => {
switch (currentTab) {
case "settings": {
const visibleEntries = configEntries.slice(startIndex, startIndex + MAX_VISIBLE)
const visibleEntries = filteredConfigEntries.slice(startIndex, startIndex + MAX_VISIBLE)
return (
<React.Fragment>
<Box>
<Text>Search: </Text>
<Text color="white">{searchQuery}</Text>
<Text inverse> </Text>
</Box>
<Box>
<Text>Data directory: </Text>
<Text color="blue" underline>
@@ -507,12 +613,12 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
// Help text based on current tab
const getHelpText = () => {
const base = "↑/↓/j/k Navigate • Tab/1-5 Switch tabs • q/Esc Exit"
const base = "↑/↓ Navigate • ←/→ tabs • 1-5 tabs • Esc Exit"
if (currentTab === "settings") {
return `${base} • Enter/e Edit • r Reset`
return `${base} Type to search • Enter/Tab Edit (booleans toggle) • Backspace clear search • Ctrl+R Reset`
}
const openFolder = onOpenFolder ? " • o Open folder" : ""
return `${base} • Enter/Space Toggle${openFolder}`
return `${base} • Enter/Tab/Space Toggle${openFolder}`
}
return (
+180 -5
View File
@@ -46,16 +46,25 @@ export interface SkillInfo {
enabled: boolean
}
export interface ObjectEditorState {
source: "global" | "workspace"
key: string
path: string[]
value: Record<string, unknown>
selectedIndex: number
isEditingValue: boolean
editValue: string
}
export const EXCLUDED_KEYS = new Set([
"taskHistory",
"primaryRootIndex",
"subagentsEnabled",
"subagentTerminalOutputLineLimit",
"welcomeViewCompleted",
"isNewUser",
"cliKanbanMigrationAnnouncementShown",
])
export const EDITABLE_TYPES: Set<ValueType> = new Set(["string", "number", "boolean"])
export const EDITABLE_TYPES: Set<ValueType> = new Set(["string", "number", "boolean", "object"])
export const MAX_VISIBLE = 12
export const SEPARATOR = "─".repeat(80)
@@ -135,7 +144,7 @@ export function parseValue(input: string, type: ValueType): unknown {
return input.toLowerCase() === "true" || input === "1"
}
if (type === "number") {
const num = parseFloat(input)
const num = Number.parseFloat(input)
return Number.isNaN(num) ? 0 : num
}
if (type === "object") {
@@ -217,7 +226,7 @@ export const TextInput: React.FC<TextInputProps> = ({ label, onChange, onCancel,
</Text>
<Box>
<Text color="white">{value}</Text>
<Text inverse> </Text>
<Text color="cyan">|</Text>
</Box>
<Text color="gray">Type: {type} Enter to save Esc to cancel</Text>
</Box>
@@ -379,3 +388,169 @@ export const SectionHeader: React.FC<{ title: string }> = ({ title }) => (
</Text>
</Box>
)
interface ObjectEditorPanelProps {
state: ObjectEditorState
setState: React.Dispatch<React.SetStateAction<ObjectEditorState | null>>
onClose: () => void
onPersist: (nextObject: Record<string, unknown>) => void
getObjectAtPath: (root: Record<string, unknown>, path: string[]) => Record<string, unknown>
setObjectValueAtPath: (root: Record<string, unknown>, path: string[], key: string, value: unknown) => Record<string, unknown>
}
export const ObjectEditorPanel: React.FC<ObjectEditorPanelProps> = ({
state,
setState,
onClose,
onPersist,
getObjectAtPath,
setObjectValueAtPath,
}) => {
const { isRawModeSupported } = useStdinContext()
const currentNode = getObjectAtPath(state.value, state.path)
const objectEntries = Object.entries(currentNode).sort(([a], [b]) => a.localeCompare(b))
const selectedEntry = objectEntries[state.selectedIndex]
const breadcrumb = [state.key, ...state.path].join(" ")
useInput(
(input, key) => {
if (state.isEditingValue) {
if (key.escape) {
setState((prev) => (prev ? { ...prev, isEditingValue: false, editValue: "" } : prev))
return
}
if (key.return) {
if (!selectedEntry) {
setState((prev) => (prev ? { ...prev, isEditingValue: false, editValue: "" } : prev))
return
}
const [entryKey, entryValue] = selectedEntry
let parsed: unknown = state.editValue
if (typeof entryValue === "boolean") {
parsed = state.editValue.toLowerCase() === "true" || state.editValue === "1"
} else if (typeof entryValue === "number") {
const maybeNum = Number(state.editValue)
parsed = Number.isNaN(maybeNum) ? 0 : maybeNum
}
const nextObject = setObjectValueAtPath(state.value, state.path, entryKey, parsed)
onPersist(nextObject)
setState((prev) => (prev ? { ...prev, value: nextObject, isEditingValue: false, editValue: "" } : prev))
return
}
if (key.backspace || key.delete) {
setState((prev) => (prev ? { ...prev, editValue: prev.editValue.slice(0, -1) } : prev))
return
}
if (input && !key.ctrl && !key.meta) {
setState((prev) => (prev ? { ...prev, editValue: prev.editValue + input } : prev))
}
return
}
if (key.escape) {
if (state.path.length > 0) {
setState((prev) => (prev ? { ...prev, path: prev.path.slice(0, -1), selectedIndex: 0 } : prev))
} else {
onClose()
}
return
}
if (key.upArrow || input === "k") {
setState((prev) =>
prev
? {
...prev,
selectedIndex:
objectEntries.length > 0
? prev.selectedIndex > 0
? prev.selectedIndex - 1
: objectEntries.length - 1
: 0,
}
: prev,
)
return
}
if (key.downArrow || input === "j") {
setState((prev) =>
prev
? {
...prev,
selectedIndex:
objectEntries.length > 0
? prev.selectedIndex < objectEntries.length - 1
? prev.selectedIndex + 1
: 0
: 0,
}
: prev,
)
return
}
if (key.return || key.tab) {
if (!selectedEntry) {
return
}
const [entryKey, entryValue] = selectedEntry
if (typeof entryValue === "boolean") {
const nextObject = setObjectValueAtPath(state.value, state.path, entryKey, !entryValue)
onPersist(nextObject)
setState((prev) => (prev ? { ...prev, value: nextObject } : prev))
return
}
if (entryValue && typeof entryValue === "object" && !Array.isArray(entryValue)) {
setState((prev) => (prev ? { ...prev, path: [...prev.path, entryKey], selectedIndex: 0 } : prev))
return
}
setState((prev) =>
prev
? { ...prev, isEditingValue: true, editValue: entryValue !== undefined ? String(entryValue) : "" }
: prev,
)
}
},
{ isActive: isRawModeSupported },
)
return (
<Box flexDirection="column">
<Text bold color="white">
Edit Nested Object
</Text>
<Text color="gray">{SEPARATOR}</Text>
<Text color="cyan">{breadcrumb}</Text>
{state.isEditingValue ? (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text color="white">{state.editValue}</Text>
<Text color="cyan">|</Text>
</Box>
<Text color="gray">Enter to save Esc to cancel</Text>
</Box>
) : (
<Box flexDirection="column" marginTop={1}>
{objectEntries.length === 0 ? (
<Text color="gray">No nested keys at this level.</Text>
) : (
objectEntries.map(([key, value], idx) => {
const isSelected = idx === state.selectedIndex
const valueText =
value && typeof value === "object" && !Array.isArray(value) ? "{...}" : String(value)
return (
<Text color={isSelected ? "cyan" : undefined} key={key}>
{isSelected ? " " : " "}
<Text color="cyan">{key}</Text>
<Text color="gray">: </Text>
<Text color="white">{valueText}</Text>
</Text>
)
})
)}
<Text color="gray">/ Navigate Enter/Tab Edit or drill in Esc Back/Close</Text>
</Box>
)}
</Box>
)
}
+51
View File
@@ -0,0 +1,51 @@
import { Box, Text } from "ink"
import React from "react"
import { ErrorService } from "@/services/error"
import { StaticRobotFrame } from "./AsciiMotionCli"
type Props = React.PropsWithChildren<{ exit: (error?: Error) => void }>
async function onReactError(props: Props, error: Error, errorInfo: React.ErrorInfo) {
try {
await ErrorService.get().captureException(error, { context: "ErrorBoundary", errorInfo })
await ErrorService.get().dispose()
} catch {
// Ignore errors
} finally {
props.exit(error)
}
}
export class ErrorBoundary extends React.Component<Props, { hasError: boolean }> {
override state = { hasError: false }
constructor(props: Props) {
super(props)
}
override componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
onReactError(this.props, error, errorInfo)
}
static getDerivedStateFromError() {
return { hasError: true }
}
override render() {
if (this.state.hasError) {
return (
<Box flexDirection="column" height="100%" key="header" width="100%">
<StaticRobotFrame />
<Text> </Text>
<Text bold color="white">
Something went wrong. We're sorry.
</Text>
<Text color="white">Please check the logs for more details.</Text>
<Text> </Text>
</Box>
)
}
return this.props.children
}
}
+117
View File
@@ -0,0 +1,117 @@
/**
* Rotating feature tips shown during thinking/acting phases.
* Appears after a brief delay and cycles through tips to educate users
* about Cline features while they wait.
*/
import { Box, Text } from "ink"
import React, { useCallback, useEffect, useRef, useState } from "react"
interface FeatureTipItem {
text: string
}
const FEATURE_TIPS: FeatureTipItem[] = [
{
text: 'Enable "Double-Check Completion" in settings to have Cline verify its work before finishing a task.',
},
{
text: "Add a .clinerules file to your project root to give Cline project-specific instructions.",
},
{
text: "Press Tab to switch between Plan and Act mode — plan an approach before Cline takes action.",
},
{
text: "Use @ in the chat input to add files, folders, or URLs as context for your task.",
},
{
text: "Set up MCP Servers to give Cline access to external tools and APIs.",
},
{
text: "Cline creates checkpoints after changes — you can always restore to a previous state.",
},
{
text: "Use /compact to condense long conversations and free up context window space.",
},
{
text: "Enable auto-approve for read-only tools like file reads to speed up exploration.",
},
{
text: "Use /settings to configure your API provider and model without leaving the terminal.",
},
{
text: "You can pass images with --images flag or paste image file paths in the chat.",
},
{
text: "Cline can browse websites — ask it to test your local dev server in the browser.",
},
{
text: "Use /reportbug to quickly file a GitHub issue with diagnostic context included.",
},
{
text: "Try 'npm i -g cline' to manage tasks on a Kankan board — orchestrate coding agents across worktrees.",
},
{
text: "Use Shift+Tab to toggle auto-approve all — let Cline work uninterrupted on trusted tasks.",
},
{
text: "Press Up/Down arrows in an empty input to browse your previous task prompts.",
},
{
text: "Type / to see all available commands — /history, /compact, /settings, and more.",
},
{
text: "Use /skills to browse and attach reusable skill files that guide Cline's behavior.",
},
{
text: 'You can disable these tips in /settings → Features → "Feature tips".',
},
]
const SHOW_DELAY_MS = 2000
const CYCLE_INTERVAL_MS = 8000
/**
* Shows rotating feature tips below the thinking indicator.
* Appears after a brief delay and cycles through tips while Cline is thinking/acting.
*/
export const FeatureTip: React.FC = React.memo(() => {
const [isVisible, setIsVisible] = useState(false)
const [tipIndex, setTipIndex] = useState(Math.floor(Math.random() * FEATURE_TIPS.length))
const cycleTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const currentTip = FEATURE_TIPS[tipIndex]
const advanceTip = useCallback(() => {
setTipIndex((prev) => (prev + 1) % FEATURE_TIPS.length)
}, [])
useEffect(() => {
showTimerRef.current = setTimeout(() => {
setIsVisible(true)
cycleTimerRef.current = setInterval(advanceTip, CYCLE_INTERVAL_MS)
}, SHOW_DELAY_MS)
return () => {
if (showTimerRef.current) {
clearTimeout(showTimerRef.current)
}
if (cycleTimerRef.current) {
clearInterval(cycleTimerRef.current)
}
}
}, [advanceTip])
if (!isVisible) {
return null
}
return (
<Box paddingLeft={1}>
<Text color="gray">
💡 <Text bold>Tip:</Text> {currentTip.text}
</Text>
</Box>
)
})
+19 -20
View File
@@ -7,13 +7,14 @@
import { Box, Text } from "ink"
import React from "react"
import { COLORS } from "../constants/colors"
import { type FeaturedModel, getAllFeaturedModels } from "../constants/featured-models"
import type { FeaturedModel } from "../constants/featured-models"
interface FeaturedModelPickerProps {
selectedIndex: number
title?: string
showBrowseAll?: boolean
helpText?: string
featuredModels: FeaturedModel[]
}
export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
@@ -21,39 +22,40 @@ export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
title,
showBrowseAll = true,
helpText = "Arrows to navigate, Enter to select",
featuredModels,
}) => {
const featuredModels = getAllFeaturedModels()
const models = featuredModels
return (
<Box flexDirection="column">
{title && (
<>
<Text>
<Text bold color={COLORS.primaryBlue}>
{title}
</Text>
<Text> </Text>
</>
</Text>
)}
{featuredModels.map((model, i) => {
{models.map((model, i) => {
const isSelected = i === selectedIndex
return (
<Box flexDirection="column" key={model.id} marginBottom={1}>
<Box flexDirection="column" key={`${model.id}-${model.labels[0] || "default"}`} marginBottom={1}>
<Box>
<Text color={isSelected ? COLORS.primaryBlue : undefined}>{isSelected ? " " : " "}</Text>
<Text bold color={isSelected ? COLORS.primaryBlue : "white"}>
{model.name}
</Text>
{model.label && (
<>
{model.labels.map((label) => (
<Text key={label}>
<Text> </Text>
<Text backgroundColor={model.label === "FREE" ? "gray" : COLORS.primaryBlue} color="black">
<Text backgroundColor={label === "FREE" ? "gray" : COLORS.primaryBlue} color="black">
{" "}
{model.label}{" "}
{label}{" "}
</Text>
</>
)}
</Text>
))}
</Box>
<Box paddingLeft={2}>
<Text color="gray">{model.description}</Text>
@@ -64,8 +66,8 @@ export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
{showBrowseAll && (
<Box>
<Text color={selectedIndex === featuredModels.length ? COLORS.primaryBlue : "white"}>
{selectedIndex === featuredModels.length ? " " : " "}
<Text color={selectedIndex === models.length ? COLORS.primaryBlue : "white"}>
{selectedIndex === models.length ? " " : " "}
Browse all models...
</Text>
</Box>
@@ -81,24 +83,21 @@ export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
* Get the maximum valid index for the featured model picker
* (includes "Browse all" option if showBrowseAll is true)
*/
export function getFeaturedModelMaxIndex(showBrowseAll: boolean = true): number {
const featuredModels = getAllFeaturedModels()
export function getFeaturedModelMaxIndex(featuredModels: FeaturedModel[], showBrowseAll = true): number {
return showBrowseAll ? featuredModels.length : featuredModels.length - 1
}
/**
* Check if the selected index is the "Browse all" option
*/
export function isBrowseAllSelected(selectedIndex: number): boolean {
const featuredModels = getAllFeaturedModels()
export function isBrowseAllSelected(selectedIndex: number, featuredModels: FeaturedModel[]): boolean {
return selectedIndex === featuredModels.length
}
/**
* Get the featured model at the given index, or null if "Browse all" is selected
*/
export function getFeaturedModelAtIndex(index: number): FeaturedModel | null {
const featuredModels = getAllFeaturedModels()
export function getFeaturedModelAtIndex(index: number, featuredModels: FeaturedModel[]): FeaturedModel | null {
if (index >= 0 && index < featuredModels.length) {
return featuredModels[index]
}
+28
View File
@@ -43,6 +43,30 @@ export const HelpPanelContent: React.FC<HelpPanelContentProps> = ({ onClose }) =
</Text>
</Box>
<Box flexDirection="column">
<Text bold>Keyboard Shortcuts</Text>
<Text>
{" "}
<Text color="white">Ctrl+U</Text> - Clear entire input (delete to start)
</Text>
<Text>
{" "}
<Text color="white">Ctrl+K</Text> - Delete from cursor to end
</Text>
<Text>
{" "}
<Text color="white">Ctrl+W</Text> - Delete word backwards
</Text>
<Text>
{" "}
<Text color="white">Ctrl+A / Ctrl+E</Text> - Jump to start / end of input
</Text>
<Text>
{" "}
<Text color="white">Alt/Option+/</Text> - Move by word
</Text>
</Box>
<Box flexDirection="column">
<Text bold>Slash Commands</Text>
<Text>
@@ -64,6 +88,10 @@ export const HelpPanelContent: React.FC<HelpPanelContentProps> = ({ onClose }) =
{" "}
<Text color="white">/clear</Text> - Start a fresh task
</Text>
<Text>
{" "}
<Text color="white">/q</Text> - Quit Cline
</Text>
</Box>
<Text>
+2 -2
View File
@@ -13,7 +13,7 @@ import { showTaskWithId } from "@/core/controller/task/showTaskWithId"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
import { useTerminalSize } from "../hooks/useTerminalSize"
import { isMouseEscapeSequence } from "../utils/input"
import { isEnterKey, isMouseEscapeSequence } from "../utils/input"
import { Panel } from "./Panel"
interface TaskHistoryItem {
@@ -142,7 +142,7 @@ export const HistoryPanelContent: React.FC<HistoryPanelContentProps> = ({ onClos
return
}
if (key.return && items[selectedIndex]) {
if (isEnterKey(input, key) && items[selectedIndex]) {
handleSelect(items[selectedIndex])
return
}
+3 -2
View File
@@ -10,6 +10,7 @@ import { showTaskWithId } from "@/core/controller/task/showTaskWithId"
import { StringRequest } from "@/shared/proto/cline/common"
import { useStdinContext } from "../context/StdinContext"
import { useTerminalSize } from "../hooks/useTerminalSize"
import { isEnterKey } from "../utils/input"
interface TaskHistoryItem {
id: string
@@ -40,7 +41,7 @@ interface HistoryViewProps {
/**
* Format separator
*/
function formatSeparator(char: string = "─", width: number = 80): string {
function formatSeparator(char = "─", width = 80): string {
return char.repeat(Math.max(width, 10))
}
@@ -111,7 +112,7 @@ export const HistoryView: React.FC<HistoryViewProps> = ({
setSelectedIndex((prev) => Math.max(0, prev - 1))
} else if (key.downArrow || input === "j") {
setSelectedIndex((prev) => Math.min(pageItems.length - 1, prev + 1))
} else if (key.return && pageItems[selectedIndex]) {
} else if (isEnterKey(input, key) && pageItems[selectedIndex]) {
onSelect(pageItems[selectedIndex])
} else if (key.leftArrow && hasPrevPage) {
handlePageChange(currentPage - 1)
+10 -23
View File
@@ -6,8 +6,6 @@
import { Box, Text, useInput } from "ink"
import React, { useCallback, useEffect, useState } from "react"
import { StateManager } from "@/core/storage/StateManager"
import type { ApiProvider } from "@/shared/api"
import { getProviderModelIdKey } from "@/shared/storage"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
import {
@@ -18,6 +16,8 @@ import {
importFromCodex,
importFromOpenCode,
} from "../utils/import-configs"
import { isEnterKey } from "../utils/input"
import { applyProviderConfig } from "../utils/provider-config"
type ImportStep = "select" | "confirm" | "saving" | "error"
@@ -61,25 +61,12 @@ export const ImportView: React.FC<ImportViewProps> = ({ source, onComplete, onCa
return
}
await applyProviderConfig({
providerId: selectedKey.provider,
apiKey: selectedKey.key,
modelId: selectedKey.modelId,
})
const stateManager = StateManager.get()
const config: Record<string, string> = {
actModeApiProvider: selectedKey.provider,
planModeApiProvider: selectedKey.provider,
apiProvider: selectedKey.provider,
}
// Set API key
config[selectedKey.keyField] = selectedKey.key
// Set model ID if available (use provider-specific keys)
if (selectedKey.modelId) {
const actModelKey = getProviderModelIdKey(selectedKey.provider as ApiProvider, "act")
const planModelKey = getProviderModelIdKey(selectedKey.provider as ApiProvider, "plan")
if (actModelKey) config[actModelKey] = selectedKey.modelId
if (planModelKey) config[planModelKey] = selectedKey.modelId
}
stateManager.setApiConfiguration(config)
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
@@ -109,13 +96,13 @@ export const ImportView: React.FC<ImportViewProps> = ({ source, onComplete, onCa
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : keys.length - 1))
} else if (key.downArrow) {
setSelectedIndex((prev) => (prev < keys.length - 1 ? prev + 1 : 0))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
setStep("confirm")
}
} else if (step === "confirm") {
if (key.upArrow || key.downArrow) {
setConfirmIndex((prev) => (prev === 0 ? 1 : 0))
} else if (key.return) {
} else if (isEnterKey(input, key)) {
if (confirmIndex === 0) {
handleConfirm()
} else {
@@ -123,7 +110,7 @@ export const ImportView: React.FC<ImportViewProps> = ({ source, onComplete, onCa
}
}
} else if (step === "error") {
if (key.return) {
if (isEnterKey(input, key)) {
onCancel()
}
}
@@ -0,0 +1,27 @@
import { render } from "ink-testing-library"
import { createElement } from "react"
import { describe, expect, it, vi } from "vitest"
import { KanbanMigrationView } from "./KanbanMigrationView"
describe("KanbanMigrationView", () => {
it("renders the migration options", () => {
const onSelect = vi.fn()
const { lastFrame } = render(createElement(KanbanMigrationView, { isRawModeSupported: true, onSelect }))
expect(lastFrame()).toContain("Cline is moving out of the terminal. Introducing Cline Kanban.")
expect(lastFrame()).toContain("Open the new experience")
expect(lastFrame()).toContain("Launch Cline Kanban and start there by default.")
expect(lastFrame()).toContain("cline --tui")
expect(lastFrame()).toContain("Close and rerun with cline --tui if you want the old CLI.")
expect(lastFrame()).toContain("Exit")
})
it("selects the highlighted option with Enter", () => {
const onSelect = vi.fn()
const { stdin } = render(createElement(KanbanMigrationView, { isRawModeSupported: true, onSelect }))
stdin.write("\r")
expect(onSelect).toHaveBeenCalledWith("kanban")
})
})
@@ -0,0 +1,95 @@
import { Box, Text, useApp, useInput } from "ink"
import React, { useMemo, useState } from "react"
import { COLORS } from "../constants/colors"
import { StdinProvider, useStdinContext } from "../context/StdinContext"
import { isEnterKey } from "../utils/input"
import { type KanbanMigrationAction } from "../utils/kanban"
import { StaticRobotFrame } from "./AsciiMotionCli"
import { ErrorBoundary } from "./ErrorBoundary"
interface KanbanMigrationViewProps {
isRawModeSupported: boolean
onSelect: (action: KanbanMigrationAction) => void
}
interface MigrationMenuItem {
label: string
description: string
value: KanbanMigrationAction
}
const InternalKanbanMigrationView: React.FC<Pick<KanbanMigrationViewProps, "onSelect">> = ({ onSelect }) => {
const { exit } = useApp()
const { isRawModeSupported } = useStdinContext()
const items = useMemo<MigrationMenuItem[]>(
() => [
{
label: "Open the new experience",
description: "Launch Cline Kanban and start there by default.",
value: "kanban",
},
{
label: "Exit",
description: "Close and rerun with cline --tui if you want the old CLI.",
value: "exit",
},
],
[],
)
const [selectedIndex, setSelectedIndex] = useState(0)
useInput(
(input, key) => {
if (key.escape) {
onSelect("exit")
exit()
} else if (key.upArrow) {
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1))
} else if (key.downArrow) {
setSelectedIndex((prev) => (prev < items.length - 1 ? prev + 1 : 0))
} else if (isEnterKey(input, key)) {
onSelect(items[selectedIndex].value)
exit()
}
},
{ isActive: isRawModeSupported },
)
return (
<Box flexDirection="column" width="100%">
<StaticRobotFrame />
<Text> </Text>
<Text bold color="white">
Cline is moving out of the terminal. Introducing Cline Kanban.
</Text>
<Text color="gray">A board for orchestrating coding agents across worktrees, right from your browser.</Text>
<Text> </Text>
{items.map((item, index) => {
const isSelected = index === selectedIndex
return (
<Box flexDirection="column" key={item.value} marginBottom={1}>
<Text color={isSelected ? COLORS.primaryBlue : undefined}>
{isSelected ? " " : " "}
{item.label}
</Text>
<Text color="gray"> {item.description}</Text>
</Box>
)
})}
<Text> </Text>
<Text color="gray">Use arrow keys to navigate, Enter to select, Esc or Ctrl+C to exit</Text>
</Box>
)
}
export const KanbanMigrationView: React.FC<KanbanMigrationViewProps> = ({ isRawModeSupported, onSelect }) => {
const { exit } = useApp()
return (
<ErrorBoundary exit={exit}>
<StdinProvider isRawModeSupported={isRawModeSupported}>
<InternalKanbanMigrationView onSelect={onSelect} />
</StdinProvider>
</ErrorBoundary>
)
}
+37 -6
View File
@@ -6,6 +6,7 @@
import { Box, Text } from "ink"
import Spinner from "ink-spinner"
import React, { useEffect, useMemo, useState } from "react"
import { refreshOcaModels } from "@/core/controller/models/refreshOcaModels"
import { refreshOpenRouterModels } from "@/core/controller/models/refreshOpenRouterModels"
import {
type ApiProvider,
@@ -61,14 +62,20 @@ import {
sapAiCoreModels,
vertexDefaultModelId,
vertexModels,
wandbDefaultModelId,
wandbModels,
xaiDefaultModelId,
xaiModels,
} from "@/shared/api"
import { StringRequest } from "@/shared/proto/cline/common"
import { filterOpenRouterModelIds } from "@/shared/utils/model-filters"
import { COLORS } from "../constants/colors"
import { getOpenRouterDefaultModelId, usesOpenRouterModels } from "../utils/openrouter-models"
import { SearchableList, SearchableListItem } from "./SearchableList"
// Special ID used to indicate the user wants to enter a custom model ID / ARN
export const CUSTOM_MODEL_ID = "__custom__"
// Map providers to their static model lists and defaults
export const providerModels: Record<string, { models: Record<string, unknown>; defaultId: string }> = {
anthropic: { models: anthropicModels, defaultId: anthropicDefaultModelId },
@@ -96,6 +103,7 @@ export const providerModels: Record<string, { models: Record<string, unknown>; d
sambanova: { models: sambanovaModels, defaultId: sambanovaDefaultModelId },
sapaicore: { models: sapAiCoreModels, defaultId: sapAiCoreDefaultModelId },
vertex: { models: vertexModels, defaultId: vertexDefaultModelId },
wandb: { models: wandbModels, defaultId: wandbDefaultModelId },
xai: { models: xaiModels, defaultId: xaiDefaultModelId },
zai: { models: internationalZAiModels, defaultId: internationalZAiDefaultModelId },
}
@@ -105,7 +113,7 @@ export function hasStaticModels(provider: string): boolean {
}
export function hasModelPicker(provider: string): boolean {
return hasStaticModels(provider) || usesOpenRouterModels(provider)
return hasStaticModels(provider) || usesOpenRouterModels(provider) || provider === "oca"
}
export function getDefaultModelId(provider: string): string {
@@ -132,7 +140,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
const [isLoading, setIsLoading] = useState(false)
const [asyncModels, setAsyncModels] = useState<string[]>([])
// Fetch OpenRouter models when needed using shared core function
// Fetch async models (OpenRouter or OCA) when needed
useEffect(() => {
if (usesOpenRouterModels(provider)) {
setIsLoading(true)
@@ -145,22 +153,45 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
.finally(() => {
setIsLoading(false)
})
} else if (provider === "oca") {
setIsLoading(true)
refreshOcaModels(controller, StringRequest.create({ value: "" }))
.then((result) => {
if (result.models) {
const modelIds = Object.keys(result.models).sort((a, b) => a.localeCompare(b))
setAsyncModels(modelIds)
}
})
.finally(() => {
setIsLoading(false)
})
}
}, [provider, controller])
const modelList = useMemo(() => {
if (usesOpenRouterModels(provider)) {
if (usesOpenRouterModels(provider) || provider === "oca") {
return asyncModels
}
return getModelList(provider)
}, [provider, asyncModels])
// Providers that support custom model IDs (e.g., Bedrock Application Inference Profiles)
const supportsCustomModel = provider === "bedrock"
const items: SearchableListItem[] = useMemo(() => {
return modelList.map((modelId) => ({
const list = modelList.map((modelId) => ({
id: modelId,
label: modelId,
}))
}, [modelList])
// Add "Custom" option at the end for providers that support it
if (supportsCustomModel) {
list.push({
id: CUSTOM_MODEL_ID,
label: "Custom (ARN / Inference Profile)",
})
}
return list
}, [modelList, supportsCustomModel])
// For providers without a model picker, render nothing
if (!hasModelPicker(provider)) {
@@ -180,7 +211,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
}
// If async fetch returned no models, render nothing
if (usesOpenRouterModels(provider) && modelList.length === 0) {
if ((usesOpenRouterModels(provider) || provider === "oca") && modelList.length === 0) {
return null
}
+88
View File
@@ -0,0 +1,88 @@
/**
* OCA (Oracle Cloud Assist) employee check component.
* Shows a checkbox for "I'm an Oracle Employee" and a sign-in button.
* Sets ocaMode in state before triggering the OAuth flow.
*/
import { Box, Text, useInput } from "ink"
// biome-ignore lint/style/useImportType: React is used as a value by JSX (jsx: "react" in tsconfig)
import React, { useCallback, useState } from "react"
import { StateManager } from "@/core/storage/StateManager"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
interface OcaEmployeeCheckProps {
/** Whether this component is active and should handle input */
isActive: boolean
/** Called when user confirms and wants to proceed with sign-in */
onSignIn: () => void
/** Called when user presses Escape to go back */
onCancel: () => void
}
export const OcaEmployeeCheck: React.FC<OcaEmployeeCheckProps> = ({ isActive, onSignIn, onCancel }) => {
const { isRawModeSupported } = useStdinContext()
const [isEmployee, setIsEmployee] = useState(true) // Default to checked (internal), matching extension behavior
const [selectedIndex, setSelectedIndex] = useState(0) // 0 = checkbox, 1 = sign in button
const ITEM_COUNT = 2
const handleSignIn = useCallback(async () => {
// Persist ocaMode to state before starting auth
const stateManager = StateManager.get()
stateManager.setGlobalState("ocaMode", isEmployee ? "internal" : "external")
await stateManager.flushPendingState()
onSignIn()
}, [isEmployee, onSignIn])
useInput(
(_input, key) => {
if (key.escape) {
onCancel()
return
}
if (key.upArrow) {
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : ITEM_COUNT - 1))
} else if (key.downArrow) {
setSelectedIndex((prev) => (prev < ITEM_COUNT - 1 ? prev + 1 : 0))
} else if (key.tab || (key.return && selectedIndex === 0)) {
// Toggle checkbox when Tab is pressed or Enter on checkbox item
if (selectedIndex === 0) {
setIsEmployee((prev) => !prev)
}
} else if (key.return && selectedIndex === 1) {
// Sign in button
handleSignIn()
}
},
{ isActive: isRawModeSupported && isActive },
)
return (
<Box flexDirection="column">
<Text color="white">Oracle Code Assist</Text>
<Text> </Text>
{/* Checkbox: I'm an Oracle Employee */}
<Text>
<Text bold color={selectedIndex === 0 ? COLORS.primaryBlue : undefined}>
{selectedIndex === 0 ? "" : " "}{" "}
</Text>
<Text color={selectedIndex === 0 || isEmployee ? COLORS.primaryBlue : "gray"}>{isEmployee ? "[✓]" : "[ ]"}</Text>
<Text color={selectedIndex === 0 ? COLORS.primaryBlue : "white"}> I'm an Oracle Employee</Text>
{selectedIndex === 0 && <Text color="gray"> (Tab to toggle)</Text>}
</Text>
{/* Sign in button */}
<Text>
<Text bold color={selectedIndex === 1 ? COLORS.primaryBlue : undefined}>
{selectedIndex === 1 ? "" : " "}{" "}
</Text>
<Text color={selectedIndex === 1 ? COLORS.primaryBlue : "white"}>Sign in with Oracle Code Assist</Text>
{selectedIndex === 1 && <Text color="gray"> (Enter)</Text>}
</Text>
<Text> </Text>
<Text color="gray">Please ask your IT administrator to set up Oracle Code Assist as a model provider.</Text>
<Text> </Text>
<Text color="gray">Arrows to navigate, Tab to toggle, Enter to continue, Esc to go back</Text>
</Box>
)
}
+7 -8
View File
@@ -5,11 +5,11 @@
import React, { useMemo } from "react"
import { StateManager } from "@/core/storage/StateManager"
import type { ApiConfiguration } from "@/shared/api"
import { CLI_EXCLUDED_PROVIDERS, getProviderLabel, getProviderOrder } from "../utils/providers"
import { SearchableList, SearchableListItem } from "./SearchableList"
import { getProviderLabel, useValidProviders } from "../utils/providers"
import { SearchableList, type SearchableListItem } from "./SearchableList"
// Re-export for backwards compatibility
export { CLI_EXCLUDED_PROVIDERS, getProviderLabel, getProviderOrder }
export { getProviderLabel }
/**
* Check if a provider is configured (has required credentials/settings)
@@ -18,8 +18,8 @@ export { CLI_EXCLUDED_PROVIDERS, getProviderLabel, getProviderOrder }
function isProviderConfigured(providerId: string, config: ApiConfiguration): boolean {
switch (providerId) {
case "cline":
// Check if user has Cline account auth data stored
return !!(config as Record<string, unknown>)["cline:clineAccountId"]
// Check if user has Cline API key or Cline account auth data stored
return !!(config.clineApiKey ?? config["cline:clineAccountId"])
case "anthropic":
return !!config.apiKey
case "openrouter":
@@ -125,17 +125,16 @@ interface ProviderPickerProps {
export const ProviderPicker: React.FC<ProviderPickerProps> = ({ onSelect, isActive = true }) => {
// Get API configuration to check which providers are configured
const apiConfig = StateManager.get().getApiConfiguration()
const sorted = useValidProviders()
// Use providers.json order, filtered to exclude CLI-incompatible providers
const items: SearchableListItem[] = useMemo(() => {
const sorted = getProviderOrder().filter((p: string) => !CLI_EXCLUDED_PROVIDERS.has(p))
return sorted.map((providerId: string) => ({
id: providerId,
label: getProviderLabel(providerId),
suffix: isProviderConfigured(providerId, apiConfig) ? "(Configured)" : undefined,
}))
}, [apiConfig])
}, [apiConfig, sorted])
return <SearchableList isActive={isActive} items={items} onSelect={(item) => onSelect(item.id)} />
}
+38
View File
@@ -0,0 +1,38 @@
import { CLI_ONLY_COMMANDS } from "@shared/slashCommands"
import { describe, expect, it } from "vitest"
import { filterCommands, getStandaloneSlashCommandName, getStandaloneSlashCommandToExecute } from "../utils/slash-commands"
const cliOnlySlashCommands = CLI_ONLY_COMMANDS.map((cmd) => ({
name: cmd.name,
description: cmd.description || "",
section: cmd.section || "default",
cliCompatible: true,
}))
describe("Quit Command (/q and /exit)", () => {
it("prioritizes /q as the selected slash command for an exact q query", () => {
const result = filterCommands(cliOnlySlashCommands, "q")
expect(result[0]?.name).toBe("q")
})
it("detects /q as a standalone slash command", () => {
expect(getStandaloneSlashCommandName("/q")).toBe("q")
})
it("detects /exit as a standalone slash command", () => {
expect(getStandaloneSlashCommandName("/exit")).toBe("exit")
})
it("resolves /q to direct execution when no slash menu is active", () => {
expect(
getStandaloneSlashCommandToExecute({
prompt: "/q",
inSlashMode: true,
hasSlashMenu: false,
hasPendingAsk: false,
isSpinnerActive: false,
}),
).toBe("q")
})
})

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