Compare commits

...

302 Commits

Author SHA1 Message Date
Saoud Rizwan 8eb5f3d57f Default web search on for the desktop app (#13725)
* Default web search on for the desktop app

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

* Make desktop web search default seed best-effort

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-31 19:23:26 -07:00
Saoud Rizwan 0852992f3b Clarify model-facing message when user rejects a tool call (#12673)
* Clarify model-facing message when user rejects a tool call

* Include the rejected tool's name in denial reasons

* Move user-rejected tool reason into @cline/shared

* Route new user-rejection approval paths through shared reason builder

Since the original PR, several new approval surfaces landed on main with
their own terse denial strings (CLI connectors, ACP permissions, Cline Hub
webview, desktop webview, example VS Code extension). Route all of them
through buildUserRejectedToolReason so the model sees a consistent,
non-error rejection message.

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

* Add buildUserRejectedToolReason to the @cline/shared integration-test stub

The VS Code integration tests run the tsc-built CJS tree and stub the
ESM-only @cline/shared package in test-setup.js; the stub was missing the
new export, so tool-approval-denial.js threw at module load in CI.

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

* Trim scope back to the minimal rejection-copy fix

Restore the connector deniedReason plumbing, ACP permission strings,
desktop webview reason, example extension reason, and hub server fallback
to their main versions. Those surfaces already attribute the denial to a
user and are outside ENG-2329. Keep the Cline Hub webview change since
that path emits its own rejection string the model sees.

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

* Move rejection guidance suffix into agent runtime per review

* Apply review suggestions: neutral fallback reason and -- separator before rejection suffix

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-31 18:39:51 -07:00
Saoud Rizwan 4ab091b959 fix(cli): keep markdown streaming prop stable to stop settle flash (#13719)
Flipping the <markdown> streaming prop from true to false when an
assistant text segment settles makes MarkdownRenderable call
updateBlocks(true), which skips every block-reuse path and destroys and
recreates all block renderables. Until tree-sitter re-highlights them
the whole message renders blank/unhighlighted, which users see as the
text flashing at the end of each response. Keep streaming={true} for
the transcript markdown (opencode's TUI does the same); entry.streaming
still drives the spinner glyph.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-31 18:37:17 -07:00
Dominic Cooney 7a6beb9f0d fix(llms): translate gateway capabilities in one place (#13584)
* fix(core): stop an empty capability list from stripping image input

`modelHasCapability` documents a missing or empty capability list as
carrying no signal, so each gate declares its own default. Two readers
bypassed it and read `capabilities` directly, where an empty list is not
nullish but `[].includes(x)` is false:

- the session runtime's `modelSupportsImages` metadata used
  `capabilities?.includes("images") ?? true`, so the intended fail-open
  never fired for an empty list and the file-read tool silently dropped
  every image from the request;
- `toProviderModel` projected an empty list onto `false`, telling pickers
  a model definitively lacks vision, attachments, and reasoning when
  nothing had been declared.

Both now route through the shared helpers, which state their unspecified
default explicitly: `modelSupportsImageInput` fails open for a capability
gate, and `declaredCapability` preserves `undefined` for `ProviderModel`'s
tri-state booleans. A populated list stays authoritative in both.

A thinking config now short-circuits `supportsReasoning` instead of being
OR-ed with the capability read, so its absence no longer collapses the
tri-state to `false`.

* fix(llms): translate gateway capabilities in one place

Three producers built gateway model definitions from catalog `ModelInfo`,
and each carried its own hand-written `switch` over the capability list.
Nothing tied them together, so they drifted:

- builtin providers always emitted a capability list, so a model whose
  catalog entry declares no capabilities became `["text"]` where the other
  producers emitted `undefined`. `modelSupportsToolCalling` fails open only
  for an absent or empty list, so that list read as an authoritative denial
  and stripped every tool definition from requests to the affected language
  models (dify, sapaicore, opencode, and the Codex CLI);
- the OpenAI-compatible path mapped an `audio` capability that
  `ModelCapabilitySchema` does not define, while the other two dropped it;
- the pass-through capabilities (`streaming`, `files`, `temperature`, ...)
  were enumerated explicitly in one, folded into `default:` in another,
  and ignored in the third.

One exported `toGatewayModelCapabilities` now serves every producer. It is
built on a `Record<ModelCapability, GatewayModelCapability | null>` rather
than a `switch`, so extending `ModelCapabilitySchema` without deciding the
new capability's mapping fails to compile instead of silently falling
through to a default.

The conformance tests walk the capability state space taken from
`ModelCapabilitySchema` itself and assert the real producers agree with the
translator, so a future producer that maps capabilities on its own fails
even when the translator's own unit tests still pass.

---------

Co-authored-by: Cline Agent <cline-agent@users.noreply.github.com>
Co-authored-by: Ara <arafat.da.khan@gmail.com>
2026-08-31 15:17:31 -07:00
Dominic Cooney f5370ad4cf fix(core): stop an empty capability list from stripping image input (#13583)
`modelHasCapability` documents a missing or empty capability list as
carrying no signal, so each gate declares its own default. Two readers
bypassed it and read `capabilities` directly, where an empty list is not
nullish but `[].includes(x)` is false:

- the session runtime's `modelSupportsImages` metadata used
  `capabilities?.includes("images") ?? true`, so the intended fail-open
  never fired for an empty list and the file-read tool silently dropped
  every image from the request;
- `toProviderModel` projected an empty list onto `false`, telling pickers
  a model definitively lacks vision, attachments, and reasoning when
  nothing had been declared.

Both now route through the shared helpers, which state their unspecified
default explicitly: `modelSupportsImageInput` fails open for a capability
gate, and `declaredCapability` preserves `undefined` for `ProviderModel`'s
tri-state booleans. A populated list stays authoritative in both.

A thinking config now short-circuits `supportsReasoning` instead of being
OR-ed with the capability read, so its absence no longer collapses the
tri-state to `false`.

Co-authored-by: Cline Agent <cline-agent@users.noreply.github.com>
2026-08-31 14:58:38 -07:00
Saoud Rizwan a7a57509e2 chore(desktop): release v0.0.21 2026-08-31 14:23:28 -07:00
Saoud Rizwan c4e09725f8 Fix ask-question option text not wrapping (#13718)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-31 13:40:13 -07:00
Mikołaj Kondratek 34f803fad4 fix: sanitize stored API keys and make provider credential rejections actionable (#13549)
* fix(vscode): sanitize pasted provider API keys at the settings write boundary

Clipboards smuggle control and invisible formatting characters (newlines,
zero-width spaces, BOM) into pasted API keys. The masked key field hides
the corruption and providers reject the key with a 401 indistinguishable
from a genuinely wrong key. Strip those characters and surrounding
whitespace once in the provider config store write path, so both backing
stores (legacy state secrets and providers.json) receive the clean value.
A whitespace-only value now clears the key.

* feat(llms,vscode): classify provider 401/403 as auth errors and surface actionable guidance

Add an "auth" ProviderErrorClass, assigned when the HTTP layer reports
401/403 — status-only on purpose, since provider bodies can quote words
like "unauthorized" without the request being an auth failure. The class
rides the existing errorClass plumbing (finish -> run-failed ->
AgentErrorEvent), so every host receives it with no new wiring.

In the VS Code chat surface, rewrite classified credential rejections
from BYOK providers into actionable text pointing at the API key
configuration, keeping the provider's raw body as a diagnostic tail.
Raw bodies alone are dead ends: Mistral, for example, answers an
identical {"detail":"Invalid API Key"} for a wrong, empty, or
wrong-scope key. Cline-account providers keep the JSON path so the
webview still renders their auth failures as a sign-in card.
2026-08-31 22:27:24 +02:00
John Choi bcfa7c7e4d fix(desktop): keep Stop available for running child agents (#13678)
* fix(desktop): keep Stop available for running child agents

* fix(desktop): reconcile aborted tool activity

* fix(desktop): guard abort and agent polling races

* fix(desktop): preserve authoritative abort status

* fix(desktop): track queue-verified completion

* test(desktop): trim duplicate abort coverage

* fix(desktop): settle delayed queue verification
2026-08-31 12:09:01 -07:00
John Choi c64743eb36 fix(core): propagate parent aborts to delegated subagents (#13677)
* fix(core): propagate parent aborts to delegated subagents

* docs(core): narrow delegated abort guarantees

* fix(core): release delegated sessions after execution

* fix(core): scope abort listeners to active runs

* fix(core): inherit parent runtime pid for subagents
2026-08-31 11:45:53 -07:00
Saoud Rizwan c096030ace Desktop marketplace redesign: two-pane explorer with full catalog metadata (#13653)
* feat(desktop): add marketplace design exploration prototypes (storefront, explorer, registry)

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

* fix(desktop): render catalog icon tiles without percentage padding

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

* feat(desktop): drop placeholder icon tiles from explorer marketplace direction

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

* feat(desktop): make explorer the marketplace view, drop design exploration harness

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

* feat(desktop): add category tag filters to marketplace explorer

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

* feat(desktop): collapse marketplace category pills behind a more toggle

* feat(desktop): remove maturity badges and CLI install section from marketplace

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-31 11:45:33 -07:00
Mikołaj Kondratek 48d6385274 fix(vscode): thread task id into hook runner creation so execution telemetry fires (#13547)
The SDK hooks adapter created every hook runner without a task id, and
StdioHookRunner gates all captureHookExecution calls on one being set —
so the next variant emitted zero hooks.execution events while discovery
telemetry fired normally. Pass the task id (and tool name for the tool
hooks) at all five factory.create call sites, and pin the threading
with a regression test.
2026-08-29 17:04:00 +02:00
Mikołaj Kondratek cea134be06 fix(vscode): prevent hook spawn failures from crashing the core process (#13422)
* fix(vscode): prevent hook spawn failures from crashing the core process

A hook child-process spawn failure emitted "error" on HookProcess with no
listener registered, which Node's EventEmitter turns into an uncaught
exception - killing the entire cline-core process instead of failing the
one hook open. Guard the emit behind listenerCount so the rejection (which
StdioHookRunner handles) is the only propagation path.

The trigger was a workspace root that no longer exists on disk passed as
the spawn cwd: Node reports a nonexistent cwd as a misleading ENOENT on
the launcher binary ("spawn /bin/sh ENOENT"). Validate cwd existence in
HookProcess right before spawning - falling back to no explicit cwd with
a warning that names the missing directory - and when a spawn still fails
ENOENT because the directory vanished in between, name it in the error
message instead of blaming the shell.

* fix(vscode): fail hooks with a missing working directory instead of relocating them

Running a hook whose assigned cwd no longer exists from the host
process's own working directory would let its relative paths read and
write an unrelated location (e.g. the IDE install directory). Reject
before spawning, with an error naming the missing directory; the runner
reports the hook as failed and the task continues. Also carry pre-spawn
failure messages into HookExecutionError details so the cause is not
reduced to a bare "exited with code 1".
2026-08-29 09:07:30 +02:00
Bee 1986fa56de fix(llms): make Langfuse tracer detection survive minified release builds (#13680)
* fix(llms): recognize direct tracer providers

* fix(llms): make Langfuse tracer detection survive minified release builds

Release binaries are compiled with minify enabled, which renames classes,
so initializeLangfuseTelemetry's constructor-name guard never matched
"ProxyTracerProvider" and silently returned readiness=false in every
production build (hub log: "creating span processor" followed by
"initialized readiness=false" with no branch message in between). Dev runs
execute unminified source, which is why the same env vars worked there.

Replace every constructor-name comparison with checks that survive
minification: detect the proxy structurally via getDelegate, distinguish a
recording provider from the no-op fallback by its lifecycle methods, and
confirm our NodeTracerProvider registration by object identity. When a
foreign provider already owns the global slot, attach the Langfuse span
processor to it when it accepts processors, and otherwise shut down the
orphaned provider and report the rejection instead of bailing silently.

Verified by bundling the module with Bun minify:true against the real
OpenTelemetry packages: the previous code reproduces readiness=false
(provider class name mangles to "H2"), the new code initializes with
readiness=true.
2026-08-28 19:44:15 -07:00
TheRealSpencer 27350f243c Chore/bump undici mermaid (#13675)
* chore(deps): bump mermaid to 11.16.1 and raise undici floor to 7.29.0

* chore(deps): patch js-yaml and body-parser in the npm-managed subprojects
2026-08-29 02:25:25 +02:00
John Choi 60c74bc727 feat(ui): share attachment drop zone (#13672)
* feat(ui): share attachment drop zone

* fix(ui): cancel disabled attachment drops

* chore(ui): simplify drop zone surface

* chore(ui): release v0.2.0-next.8
2026-08-28 16:21:32 -07:00
Bee aa815cd41a fix(core): refresh Cline models from live catalog (#13670) 2026-08-29 01:19:26 +02:00
Harrison 1fbcfab05d test: cover session search fallback on hub timeout and rejection (#13642)
* feat: add searchable session history

Rebased onto main and updated to supersede the sidebar search dialog
from #13533: the sidebar search icon now opens the indexed command bar
(Cmd/Ctrl+P) instead of a sidebar-local cmdk dialog that eagerly loaded
the entire session history via loadAllSessions(). CommandDialog gains a
shouldFilter passthrough so server-ranked FTS hits are displayed as-is.

* fix: harden session history search

* fix: evict failed restoration sessions from search

* fix: preserve deletion when search eviction fails

* fix: address session search review feedback

* fix: preserve search suppression during reconciliation

* test: cover sidecar search fallback on hub timeout and rejection

The existing search_sessions tests only exercised the index-hit and
empty-index-fallback paths with an immediately-resolved hub reply.
Add coverage for the two other realistic Hub-connection failure
modes the fallback is meant to tolerate: the hub call rejecting, and
the hub call hanging past the 750ms withSearchDeadline race.

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2026-08-28 19:06:47 +02:00
Bee ce71fe5eb9 chore(llms): built-in model list update 1787907289186 (#13663)
* chore(llms): built-in model list update 1787907289186

Result of `bun run build:models`.
Includes updated model list and fixed formatting issues across codebase.

* test(llms): update GLM reasoning toggle expectation
2026-08-28 02:45:05 -07:00
Bee aa4753f4ab fix(llms): use AI SDK 7 Langfuse telemetry (#13651)
* fix(llms): use AI SDK 7 Langfuse telemetry

* test(llms): cover Langfuse runtime context
2026-08-27 21:17:39 -07:00
John Choi 52d5e1a515 ENG-2490: Propagate session aborts to teammates (#13647)
* fix(core): propagate session abort to teammates

* fix(core): persist aborted teammate tasks as cancelled

* fix(core): settle teammate work on session abort

* fix(core): isolate replacement runs from stale aborts

* refactor(core): narrow teammate task status metadata

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
2026-08-27 19:52:01 -07:00
Bee 2208d185a4 feat(sdk): add discovery boundary ahead of Agent Plugins support (#13017) 2026-08-27 18:22:48 -07:00
Saoud Rizwan 936c018689 chore(desktop): release v0.0.20 2026-08-27 18:15:36 -07:00
Bee 957a4bf5d9 feat(desktop): render tool output images as attachments (#13643)
* fix(desktop): render tool output images as attachments

Add support for displaying media returned by tool calls (e.g. screenshots)
as rendered images with expand-to-fullscreen capability instead of raw
base64 text. Introduces an `ImageCarousel` component for navigating
multiple images, propagates the expand handler to tool message blocks,
and extracts/validates output media in tool summaries.

* test: cover multi-image and canonical media extraction in tool output (#13645)

extractOutputMedia and the desktop tool-message rendering path were only
ever exercised with exactly one distinct valid image, and
canonicalInlineMedia (MCP-style type: "media" blocks for audio/video/file)
had zero coverage. Add tests for: multiple distinct images in one tool
result (parser + desktop carousel navigation), inline audio via the
mime_type key spelling, canonical video/file media blocks, and rejection
of an invalid canonical image block.

---------

Co-authored-by: Harrison <harrison@cline.bot>
2026-08-27 17:55:29 -07:00
Saoud Rizwan b532b174ba fix(ci): stop e2e worker teardown timeouts and deflake hub daemon e2e on Windows (#13646)
* fix(e2e): stop VS Code e2e worker teardown from timing out

The ext-vscode-test-e2e job has been failing on main with 'Worker teardown
timeout of 60000ms exceeded' even though every test passes. Playwright only
reports an Electron app as closed once the process exits AND every holder of
its stdio pipes is gone (ChildProcess 'close' waits on the extra fd3/fd4
pipes Playwright creates for Electron). Any VS Code descendant that outlives
the main process (chrome_crashpad_handler, GLib's 'dconf watch' helper,
xdg-open browser handlers, VS Code 1.135's agent host CLI subprocess that
logs 'unable to kill the process') keeps those pipes open, so app.close()
never resolves and the worker teardown hangs on it until its 60s timeout
fails the job.

Harness fixes, each removing one source of that wedge:

- closeAppForTeardown now SIGKILLs the whole process group (taskkill /T on
  Windows) when app.close() times out, instead of only the main pid — and
  does so even when the main process already exited, which is exactly the
  wedged state. Playwright launches Electron detached, so pid == pgid.
- Launch VS Code with --disable-crash-reporter so no crashpad handler
  outlives the app holding the harness pipes.
- Seed the fresh user-data-dir with chat.disableAIFeatures: true so VS
  Code's own AI features (rolled out via server-side experiments, so CI
  breaks without any repo change) never start their agent host process.
- Drop the page.close() teardown: closing VS Code's last window quits the
  whole app, and ElectronApplication.close() on an already-exited app
  deadlocks; the app fixture's app.close() closes windows itself while the
  app is alive.
- Codex sign-in no longer opens a real external browser under E2E_TEST; the
  codex-oauth test drives the OAuth callback itself, and the browser was an
  orphaned process holding the harness pipes on the runner.

* fix(core): deflake hub daemon e2e tests on Windows runners

sdk-test on windows-latest fails intermittently in the hub daemon e2e
files:

- shutdown.e2e.test.ts dies with a bare 'Error: socket hang up'. That
  message is the ws handshake (http.ClientRequest) failing, not the
  /shutdown fetch (an undici failure prints 'TypeError: fetch failed'):
  a freshly spawned bun daemon on a loaded 2-core Windows runner
  occasionally drops its first accepted connection before writing the
  upgrade response. Real hub clients reconnect with backoff, and the test
  asserts shutdown behavior rather than first-connection reliability, so
  openAuthenticatedSocket now retries transient handshake failures within
  a 15s budget.
- singleton.e2e.test.ts times out waiting for daemon discovery: it still
  used the 10s hang guard that 0cfc90158 already raised to 30s in
  shutdown.e2e.test.ts for the same reason. Use the same 30s guard.
- Raise the e2e testTimeout to 60s so a test that legitimately spawns two
  daemons back to back can survive slow-runner startups instead of the
  discovery hang guard being cut off by the test timeout.
2026-08-27 17:40:21 -07:00
Tomás Barreiro b78f6d16d0 Add a GitHub integration step to the onboarding (#13225)
* Add feature flags to the app

* React to account updates

* Address comments

* Add a GitHub integration step to the onboarding

* validate domain and fix errors on auth

* Hide the step behind a feature flag

* update version

---------

Co-authored-by: John Choi <john.choi@cline.bot>
2026-08-27 17:29:08 -07:00
John Choi 839074d7c1 test(vscode): prevent E2E worker teardown hangs (#13644)
* test(vscode): capture external URLs in E2E runs

* docs(test): clarify browser capture rationale
2026-08-27 17:06:47 -07:00
Saoud Rizwan 9e7c1a3f9a Fix CLI crash when a remote MCP server is offline but enabled (#13639)
Remote (SSE/streamable HTTP) MCP connects run on the session.create
critical path, which the hub caps at 30s. Without a connect budget an
unreachable server spent the full 60s default request timeout (with the
SSE transport stuck in a reconnect loop), stalling session.create past
the hub deadline and tearing the whole session down - the interactive
TUI exited and one-shot runs failed. Stdio servers already have a
bounded initialize budget for exactly this reason; give URL clients the
same treatment with a 10s default connect budget that an explicit
timeout overrides in either direction.

Fixes #13597

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 16:13:38 -07:00
Bee 29530caa58 feat: add searchable session history (#13420)
* feat: add searchable session history

Rebased onto main and updated to supersede the sidebar search dialog
from #13533: the sidebar search icon now opens the indexed command bar
(Cmd/Ctrl+P) instead of a sidebar-local cmdk dialog that eagerly loaded
the entire session history via loadAllSessions(). CommandDialog gains a
shouldFilter passthrough so server-ranked FTS hits are displayed as-is.

* fix: harden session history search

* fix: evict failed restoration sessions from search

* fix: preserve deletion when search eviction fails

* fix: address session search review feedback

* fix: preserve search suppression during reconciliation

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-27 15:55:22 -07:00
Saoud Rizwan 691fcb6b67 fix(shared): discover global rules at ~/Cline/Rules (#13614)
The VS Code Rules tab resolves the Documents folder via
'xdg-user-dir DOCUMENTS', which prints bare $HOME when no user-dirs
config exists (WSL/headless installs), so it reads and writes global
rules at ~/Cline/Rules. The SDK's rule search paths only covered
~/Documents/Cline/Rules, so those rules never reached the system prompt.
Add the missing path to the search list.

Fixes #13542

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 14:44:25 -07:00
Saoud Rizwan c97e4af8fa Fix scheduled tasks disappearing after desktop app updates (#13627)
* Fix hub-managed schedules being wiped by cron reconciliation on hub restart

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

* Require the virtual hub/schedules path when exempting specs from removal reconciliation

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

* Treat recorded source mtime as proof a spec is file-backed, closing the hub/schedules spoof gap

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 13:59:08 -07:00
Mikołaj Kondratek 889010b0b9 fix: hide history cost estimates for subscription-billed tasks (#13562)
* fix(vscode): hide history cost estimates for subscription-billed tasks

The task-header fix for subscription providers cannot reach history:
history rows render the stored totalCost (an API-rate estimate) and do
not know which provider ran the task, so the history page printed
$X.XXXX on every row and the recent-task chips in an empty chat view
rendered a $ chip even for subscription-billed tasks.

The SDK session records already persist the provider — the CLI's
history view uses it for exactly this — but the VS Code mappers dropped
it. Map it through both transports (HistoryItem.apiProvider for the
state-pushed taskHistory, TaskItem.api_provider for getTaskHistory) and
suppress the dollar figure per row when that provider's
usageCostDisplay is not "show", via a new useUsageCostVisibility
predicate shared by both surfaces.

Rows without a recorded provider (tasks predating the field, legacy
imports) keep showing the stored value — there is nothing to key
suppression on.

* test(vscode): e2e-verify history cost suppression in real VS Code

Seeds SDK session records (one openai-codex subscription task, one
anthropic usage-billed task) into the isolated CLINE_DIR before the
webview loads, then asserts in a real VS Code instance that both the
recent-task chips and the full history page render the dollar figure
only for the usage-billed task. Covers the two boundaries the unit
tests stub: on-disk records reaching getTaskHistory with provider
populated, and the provider listings delivering the subscription mark
to the webview.
2026-08-27 22:58:22 +02:00
Saoud Rizwan 89c2efa970 fix(core): refuse checkpoint workspace restore when HEAD moved past the checkpoint (#13626)
* fix(core): refuse checkpoint workspace restore when HEAD moved past the checkpoint

Restoring a checkpoint runs git reset --hard, which moves the current
branch pointer. If commits were made after the checkpoint (by the user
or by the agent), the reset silently knocked them off the branch,
leaving them reachable only through the reflog.

Guard the reset: if HEAD no longer matches the commit the checkpoint
was created on, throw a descriptive error (including how many commits
would be dropped) instead of destroying history. Chat-only restore is
unaffected, and users who really want to discard the commits can reset
the branch manually first.

Fixes #13550

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

* fix(core): close the guard-to-reset race with an atomic ref update

The moved-HEAD guard read HEAD, ran further git commands, then reset
unconditionally, so a commit landing in that window could still be
knocked off the branch. Replace the reset's branch move with git's
native compare-and-swap (git update-ref HEAD <new> <old>), which fails
if HEAD no longer points at the verified commit, and follow with a bare
reset --hard to sync the index and worktree to the already-moved HEAD.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 13:47:50 -07:00
Saoud Rizwan f753a01d85 fix(desktop): don't show providers as configured without real credentials (#13608)
* fix(desktop): don't show providers as configured without real credentials

The desktop settings marked any provider with a persisted settings entry
as Configured, but legacy VS Code migration and empty saves can seed
entries (e.g. qwen-code, sapaicore) holding only a default model and no
credentials. Move the CLI's isProviderSettingsUsable readiness check into
@cline/core, expose it as a computed 'configured' flag on the provider
catalog, and use it in the desktop's isProviderConnected.

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

* fix(desktop): resync catalog after saves so Configured badge updates live

Optimistic provider mutations can't know the sidecar-computed 'configured'
flag, so after connecting a keyless provider or saving cloud credentials
(e.g. a Vertex project id) the row stayed 'Not configured' until remount.
Silently refetch the catalog after each successful save, guarded by the
existing generation counter so newer edits discard stale responses.

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

* fix(desktop): claim a generation in post-save resync so overlapping refreshes can't apply stale snapshots

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

* fix(desktop): bump catalog generation on OAuth login success

Every other optimistic provider mutation claims a new generation; the
OAuth success path didn't, so a catalog load or resync still in flight
could arrive late and overwrite the just-connected state.

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

* fix(desktop): resync catalog after OAuth login instead of bare generation bump

The resync claims a new generation (discarding any stale in-flight
response) and its own fetch covers both the new OAuth connection and any
provider saved moments earlier, matching the post-save path.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 13:45:44 -07:00
Bee 908e09815e feat(core): anchor agent-created schedules in the user's .cline schedules home (#13634)
* feat(core): anchor agent-created schedules in the user's .cline schedules home

Agent-created schedules inherited whichever workspace folder the chat
session happened to run in, scattering user-level routines across chat
and project folders. They were invisible to workspace-scoped listings
elsewhere, tied to folders that may be cleaned up, and each chat's
tasks tool saw a different set when checking for duplicates.

Anchor them in ~/.cline/schedules instead: the hub's scheduled-task
session defaults now resolve to that home (created on demand), so
agent-created schedules live and run in one stable user-level scope.
The tasks tool guidance now tells agents that scheduled sessions run in
the schedules home, so prompts must carry absolute paths to any project
they operate on.

Schedules created explicitly with a workspace (CLI --workspace, desktop
routine wizard) are unchanged, and existing rows keep their current
workspaceRoot - they stay visible through the all-workspaces listing
paths (#13613, #13633).

* test(core): restore any pre-existing CLINE_DIR after the agenda hub test

The test's cleanup deleted CLINE_DIR outright, so an environment that
had it configured would leave later tests in the same worker on the
default storage directory. Save the previous value and restore it.

* test(core): restore CLINE_DIR even when hub test setup throws early

Restoring the override in the try/finally missed failures thrown during
transport construction or start(), before the try was entered. Register
the restore with onTestFinished instead, which runs regardless of where
the test fails.
2026-08-27 13:18:57 -07:00
Saoud Rizwan 8eca7575b4 fix: make OpenAI Codex (ChatGPT subscription) sign-in fail loudly instead of silently dead-ending (#13537)
* fix: make OpenAI Codex sign-in fail loudly instead of silently dead-ending

When callback port 1455 is already in use (e.g. by the Codex CLI or a
previous pending sign-in), startLocalOAuthServer returns a no-op server
and loginOpenAICodex would open the browser anyway, then dead-end:
the callback could never be received, and in the VS Code extension the
user just saw nothing happen after clicking 'Sign in to OpenAI Codex'.

- loginOpenAICodex now fails fast with an actionable 'port in use'
  error before opening the browser, unless the host provides manual
  code entry (the CLI's paste fallback keeps working)
- surface OAuth redirect errors (e.g. access_denied) instead of
  collapsing them into 'Missing authorization code'
- the extension dedupes concurrent sign-in clicks: a re-click re-opens
  the auth page of the pending flow instead of spawning a second flow
  that would collide with our own callback server
- browser-open failures now show an error message with the URL to
  open manually instead of only logging
- abandoned-flow timeouts no longer surface a confusing 'Missing
  authorization code' toast

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

* refactor: drop host-side codex login dedupe, keep flow identical to CLI

The SDK owns the failure handling now (fail-fast on an unbindable
callback port), so the extension keeps the exact same simple
loginOpenAICodex call the CLI uses. A second click while a flow is
pending gets the SDK's clear port-in-use error, same as running
'cline auth openai-codex' twice would. Keep only the CLI-parallel
onOpenUrlError surfacing (the CLI prints 'open the URL above
manually'; the extension's equivalent is an error toast with the
URL).

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

* test(e2e): cover Codex sign-in callback-port failure and redirect errors

Two driven-VS Code tests for the OpenAI Codex (ChatGPT subscription)
sign-in flow:

- with port 1455 occupied on both loopback families, clicking the
  sign-in button surfaces the fail-fast port-in-use toast
- with the port free, the callback server binds and an OAuth redirect
  error (access_denied) propagates to a visible error toast

The second test opens a real browser tab to the OpenAI auth page as a
side effect of the genuine sign-in click.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
Co-authored-by: Mikołaj Kondratek <19799111+mkondratek@users.noreply.github.com>
2026-08-27 22:10:35 +02:00
Mikołaj Kondratek 006de710d5 fix(sdk): don't log out Codex/OCA users when token refresh fails transiently (#13565)
* fix(sdk): don't log out Codex/OCA users when token refresh fails transiently

Port the cline-provider refresh semantics to openai-codex and oca:
a transient refresh failure (network error, timeout, server 5xx) with an
already-expired access token now rethrows instead of returning null.
A null return means the refresh token was REJECTED and re-auth is
required; treating an outage blip as a rejection is what turned it into
a forced 'openai-codex requires re-authentication.' task stop while the
settings UI still showed the user as signed in.

Both providers also emit user.auth_refresh_soft_failure telemetry on
transient failures (the 'prevented logout' counter the cline provider
already has) and attach status/errorCode details to the genuine
invalid_grant logout event.

* refactor: collapse duplicate soft-failure telemetry branches and test

Review feedback: compute tokenExpired once and emit the soft-failure
event once in both providers, then return current credentials or
rethrow. Fold the codex soft-failure telemetry assertions into the
existing still-usable-token test instead of a near-duplicate case.
2026-08-27 22:10:00 +02:00
Bee 62f471f233 fix(core): stop watching agenda spec dirs while the todo tool is disabled (#13629)
* fix(core): stop watching agenda spec dirs while the todo tool is disabled

Since #13530 disabled the agent todo tool, the Agenda UI, and the
automation pump, the hub still created fs.watch watchers on the global
agenda specs dir and on every workspace root recorded in the task store
(at startup and on scope access). Nothing consumes the watcher-driven
task events while the feature is off, and the task.* hub commands
already reconcile spec files on demand, so the watchers are pure
overhead - one OS watch handle per known workspace.

Wire watchFiles to AGENDA_TODO_TOOL_ENABLED the same way
automationEnabled is, preserving a host's explicit watchFiles opt-out
for when the flag is turned back on. Schedules are unaffected: the
schedule list has no file watcher and updates through hub commands and
published schedule events.

* fix(core): reconcile external spec edits inside updateTask

With the spec watchers off there is no background reconciliation, so a
task spec edited directly on disk made every same-store task.update fail
the signature check with "task spec changed outside the manager" until
an unrelated task.get or task.list happened to reconcile the scope.

Reconcile the task's scope at the start of updateTask (mirroring what
refreshAndVerifyTaskIntent already does for approve/run), skipping it
when the file reconciler itself is the caller to avoid recursing from
reconcileFileStore. An external edit now surfaces as the store's normal
stale-revision conflict, and a re-read-and-retry succeeds. This also
closes the pre-existing watcher debounce race for updates.
2026-08-27 13:00:24 -07:00
Saoud Rizwan c017c7016e fix(desktop): make the Tauri shell work on Windows (#13632)
- Defer updater installation to the user-initiated restart on Windows:
  install() launches the NSIS installer and exits the process immediately,
  so the background cycle now downloads only and stages the bytes, and
  restart_to_apply_update installs them after stopping the sidecar.
- Spawn child processes (sidecar, git, cmd /C start) with CREATE_NO_WINDOW
  so the GUI-subsystem app doesn't pop visible console windows.
- Fall back to USERPROFILE when HOME is unset resolving the MCP settings
  path, matching the sidecar's homedir().
- Reap the sidecar after the Windows hard-kill so its exe file lock is
  released before the NSIS installer replaces it.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 12:04:53 -07:00
Saoud Rizwan 4bfef7087f Remove box shadow from chat message actions row (#13630)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-27 11:51:07 -07:00
Saoud Rizwan 1d5d3b0055 Add tooltips explaining Live and After recording badges on voice input models (#13610)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 23:39:15 -07:00
Saoud Rizwan 80dd573156 Desktop: surface scheduled-task final output — auto-expand submit_and_exit and render its summary as markdown (#13612)
* desktop: auto-expand submit_and_exit and render its summary as markdown

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

* desktop: render submit summary in full foreground color

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

* desktop: label the submit row 'Scheduled task completed'

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

* desktop: label errored submit_and_exit rows as failed

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 23:38:05 -07:00
Saoud Rizwan ce2f7a00bb Make suggested routine template prompts prescriptive about their final output (#13611)
* Make bug hunter routine template prescriptive about its final report

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

* Make remaining routine templates prescriptive about their final output

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 23:37:20 -07:00
Saoud Rizwan ad1408636e fix(desktop): show agent-created schedules on the Schedules page (#13613)
* fix(desktop): show agent-created schedules on the Schedules page

Schedule hub commands are scoped to the workspace registered by the
connection, but the desktop app's hub client registers the app launch
directory while agent-created schedules live under each chat's own
workspace folder - so they never appeared on the Schedules page.

Grant token-authenticated hub connections (which can already bind any
workspace at registration) explicit cross-workspace schedule access via
an allWorkspaces payload flag, and have the desktop sidecar request it
for routine schedule commands. Workspace-bound clients (local browser
origins) and default CLI behavior stay scoped.

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

* refactor(core): strip allWorkspaces flag from schedule inputs and pin it in the sidecar payload

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 23:23:08 -07:00
Saoud Rizwan 8981079a43 Build and Authenticode-sign a Windows x64 desktop installer in desktop releases (#13607)
* feat(desktop): build and Authenticode-sign a Windows x64 NSIS installer in desktop releases

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

* fix(desktop): pin OIDC-adjacent actions to commit SHAs in the Windows signing job

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

* fix(desktop): pin checkout and upload-artifact to commit SHAs in the Windows signing job

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 23:07:50 -07:00
Dominic Cooney b4fd4ee0cd Tunnel ProtoBus over the existing Host Bridge (#13218)
* feat(core): tunnel ProtoBus over Host Bridge

* fix(core): harden Host Bridge stream lifecycle

* fix(core): serialize concurrent chunked responses per request

Streaming handlers deliver updates fire-and-forget, so two logical
responses for one request_id can be in flight at once. Chunked payloads
made forwarding non-atomic: each chunk write is an await, so concurrent
forwards could interleave their chunk sequences and the receiver --
which reassembles purely by arrival order -- would splice two payloads
into one. Route all forwards for a request through one promise chain; a
failed write rejects every later forward so a torn payload is never
followed by more chunks.

Rename the lock manager's instanceAddress to instanceOwner: it holds an
opaque per-spawn instance ID on the token path and a listener address
only on the CLI-harness path. Delete the caller-less getInstanceByPort
query that interpreted the owner as an address.

Also: document message_json as a legal wire encoding for small
payloads, close the gRPC client when startup fails, note the
intentional discard of the cancellation confirmation, and add the
proto's trailing newline.

---------

Co-authored-by: Cline Agent <cline-agent@users.noreply.github.com>
2026-08-27 09:24:28 +09:00
Saoud Rizwan 89970ea794 Sign Windows CLI binaries with Azure Trusted Signing; surface app-control launch errors (#13021)
* feat(cli): sign Windows binaries with Azure Trusted Signing and surface app-control launch errors

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

* fix(cli): use _CLI-suffixed signing profile secret, normalize endpoint, fail loud on partial config

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-26 16:13:23 -07:00
John Choi ee0982cb98 fix(desktop): keep the window title bar draggable across views (#13572)
* fix(desktop): keep window title bar persistent

* fix(desktop): reserve persistent title bar space

* fix(desktop): polish persistent title bar layout
2026-08-26 15:58:58 -07:00
Mikołaj Kondratek 7718142ef2 fix(tools): preserve a file's own CRLF line endings across apply_patch updates (#13512) 2026-08-26 21:18:32 +02:00
John Choi 70654acc3e feat(ui): share agent welcome hero (#13567)
* feat(ui): share agent welcome hero

* test(ui): cover welcome hero pointer states

* refactor(ui): keep welcome hero API minimal

* test(ui): verify welcome hero package assets

* fix(ui): inline welcome hero masks
2026-08-26 11:37:52 -07:00
Saoud Rizwan c8f1caa88c fix(vscode): stop pinning DeepSeek model count in catalog smoke test (#13600) 2026-08-26 11:05:35 -07:00
𝓜𝓲𝓼𝓼𝓪𝓻𝓲 𝓐𝓱𝓲𝓵 🌿 7673b30e4d fix(vscode): avoid render crash on malformed api_req payloads in combineApiRequests (#13560) 2026-08-26 16:19:59 +02:00
Saoud Rizwan c0c37a1587 chore(cli): release v3.0.60 2026-08-26 02:25:12 -07:00
Saoud Rizwan ebdabe65ce chore(sdk): release v0.0.81 2026-08-26 02:21:57 -07:00
Saoud Rizwan 40c3a4dbd8 chore(desktop): release v0.0.19 2026-08-26 02:14:21 -07:00
Saoud Rizwan 6859d00e51 fix(hub): stop shipping full transcripts inside broadcast hub events (#13587)
* fix(hub): stop shipping full transcripts inside broadcast hub events

Every session.updated (and session.created/detached/run.started) event
embedded the session's ENTIRE message transcript via readCoreSessionSnapshot,
even though no consumer reads snapshot.messages off an event — clients fetch
messages with the session.messages command. For a multi-megabyte transcript
this turns every status flip into megabytes per subscriber, floods the
durable event log, and (until the send-queue backpressure fix lands) lets a
slow subscriber balloon the hub process by one full transcript copy per
event — reported as a 25GB cline process on a 16GB Mac.

Strip snapshot.messages centrally in HubServerTransport.publish() so every
current and future event publisher is covered, the event log stores slim
envelopes, and cursor replay stays byte-identical with live fan-out. All
other snapshot fields (status, usage, model, workspace, checkpoint) are kept,
and command replies are untouched.

* fix(hub): never capture the transcript into event/reply snapshots

Replaces the publish-boundary strip with the real fix: don't build
message-bearing snapshots in the first place. emitSessionSnapshot no longer
re-reads the entire transcript from disk on every status flip, and
readCoreSessionSnapshot no longer reads it for any event or reply — a
snapshot is a state notification (status, usage, model, workspace,
checkpoint); the transcript is fetched via the session.messages command.
Checkpoint-restore snapshots (session-versioning-service) are untouched:
restore replies carry messages in their own dedicated field.
2026-08-26 02:07:28 -07:00
Saoud Rizwan 6ba9b9d7b4 chore(cli): release v3.0.59 2026-08-26 01:49:10 -07:00
Saoud Rizwan 4c8cd98351 chore(sdk): release v0.0.80 2026-08-26 01:30:02 -07:00
Saoud Rizwan ebee8ca912 chore(vscode): release v4.1.16 2026-08-26 01:18:34 -07:00
Saoud Rizwan c0d6301884 chore(desktop): release v0.0.18 2026-08-26 00:56:19 -07:00
Saoud Rizwan d71f097656 fix(desktop): install marketplace plugins and MCP servers in-process instead of spawning a cline binary (#13585)
* fix: install marketplace plugins and MCP servers in-process instead of spawning a cline binary

The desktop app sidecar and cline-hub shelled out to 'cline plugin install'
and 'cline mcp install' for marketplace installs. Packaged GUI apps inherit
launchd's minimal PATH on macOS and most desktop users have no cline CLI
installed at all, so installs failed with a red
'Executable not found in $PATH: "cline"' error.

Install via @cline/core's installPlugin/installMcpServer in-process instead,
matching what the VS Code extension already does. Also fix
parseMcpInstallArgs in @cline/core to treat the marketplace catalog's '--'
separator as end-of-options; previously the separator itself became the
stdio command.

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

* refactor: drop test-injection plumbing from marketplace installers

Call @cline/core's installPlugin directly instead of threading an
installer option through the marketplace entry points; tests stub the
core module instead.

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

* revert: keep cline-hub marketplace installs CLI-backed

The hub dashboard is launched via 'cline dashboard', so a CLI is always
present and CLINE_WRAPPER_PATH resolves it; the PATH bug only affects
the desktop app, which does not ship a CLI.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-26 00:14:55 -07:00
Saoud Rizwan 6539f4deea feat(desktop): hover trash button on sidebar session rows (#13582)
Each session row shows a trash icon on the right while hovered (or
when the button itself is focused), opening the same delete
confirmation dialog the row's context menu uses. The row is a button
and buttons cannot nest, so the trash is an absolutely positioned
sibling inside a group/row wrapper, overlaid where the timestamp sits:
row hover hides the timestamp, shows the trash, and moves the row's
hover background to the wrapper group so it holds while the pointer is
on the trash itself.
2026-08-26 00:01:00 -07:00
Saoud Rizwan 036fc75b1f fix(desktop): don't block the main thread on quit while stopping the sidecar (#13566)
Quitting the mac app beach-balled for ~5-7s. The shutdown POST was
built from the ws transport URL (appending /shutdown lands inside the
query string), so the sidecar was never told to exit, and stop() then
polled the child for up to 7s on the main thread - on macOS inside
applicationWillTerminate - before SIGKILLing it.

stop() now sends SIGTERM and returns immediately. The sidecar handles
SIGTERM with the same bounded (5s) graceful shutdown as the /shutdown
endpoint and exits itself, finishing session persistence as an orphan.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-25 23:40:07 -07:00
Saoud Rizwan 6fc40127a6 feat(desktop): scheduled sessions UX — unified details dialog, run-now handoff, hidden steering, stuck-thinking fix (#13573)
* feat(desktop): merge schedule details into one view and open run-now sessions

The schedule details dialog drops its Overview/Runs tabs: one scrollable
column with the meta grid, the configuration JSON (capped at max-h-64
with internal scroll so it cannot crowd out what follows), and a Runs
section beneath it showing the three most recent runs with a ghost
"Show all N runs" expander (collapsed again whenever a different
schedule's details open). The "Full configuration for this schedule"
subtext is gone; the dialog passes aria-describedby={undefined} so
Radix does not warn about the missing description.

Run now hands you into the session it starts. The trigger command
queues the run and returns before the runner attaches a session id, so
after the toast the handler polls the schedule overview once a second
for up to 15 seconds — which doubles as keeping the page's run status
fresh (refreshSchedules now returns the fetched overview to make that
single-stream) — until the triggered execution reports its session id,
then calls onOpenSession. Guarded so it never auto-navigates after the
user left the page.

* feat(desktop): hide runtime steering messages from transcripts

Scheduled/automation runs inject user-role steering messages each
iteration ("[SYSTEM] This run is not complete until you call
submit_and_exit...", plus a team-obligations variant). The chat view
rendered them as user bubbles, as if the person had typed them — in a
scheduled session the transcript was mostly [SYSTEM] noise.

They are machinery talking to the model, not something the person said
or needs to read, so the transcript now hides them entirely:
MessageBubble renders null for any [SYSTEM]-prefixed user message.
Grouping still treats them as working-row machinery via a single
isSystemSteeringMessage predicate — they collapse into the run's work
span, are never a turn boundary, can never be mistaken for a run's
answer, and never advance the run count even when metadata is missing —
so work-block folding and checkpoint/edit run numbering stay correct.
A finished scheduled session now reads as prompt, work summary, answer.

* fix(desktop): poll history while an attached session's event stream is dead

Opening a scheduled session while (or right after) it runs left the
view stuck on the thinking shimmer until the user switched away and
back. Root cause is in core: the hub daemon executes scheduled runs on
a private LocalRuntimeHost inside createLocalHubScheduleRuntimeHandlers,
while the hub server only projects live events from its own session
host — so session.attach succeeds but no assistant/tool/status events
ever flow. And since multiple hub daemons share cron.db, a run claimed
by a different daemon is invisible to this hub regardless. The proper
core rewiring is tracked as ENG-2474.

Client-side heal that covers every case: while an attached history
session reports a busy status and no chat_event chunk has arrived for
five seconds (and no assistant bubble is mid-stream), poll every three
seconds — re-read canonical history, merged through the same dedupe
path hydration uses, and the session record's status — so the
transcript and the thinking indicator settle in place. Locally driven
turns keep chunks flowing, so the quiet-window guard keeps the fallback
inert there.

* chore(desktop): format workspace selector components

Biome formatting drift that landed on main; picked up by a formatter
pass over components/views/chat.

* fix(desktop): keep stale-stream poll inert during locally driven turns

The fallback poll could fire between a local submit and the model's
first chunk (optimistic user bubble added, stream quiet past the
window, no assistant bubble yet). It then replaced the optimistic
bubble — raw prompt text — with its canonical history twin, which is
stored wrapped in a user_input envelope. The rekey handler that runs
when the stream starts looks for a trailing user bubble matching the
raw prompt, finds only the wrapped copy, and appends a second bubble:
duplicated messages in normal interactive chat.

The poll now stays inert while a local turn is in flight
(turnEpoch !== turnSettledEpoch, or outstanding optimistic user
messages), checked both before polling and again after the snapshot
returns. Hydration marks the turn settled — the mount defaults
(epoch 0, settled -1) otherwise read as an open turn and would keep
the fallback inert forever for the scheduled-session case it exists
for. Applying a polled snapshot also rebuilds the live tool routing
keys, same as hydration, so later tool events update canonical rows
in place instead of appending.

* fix(desktop): keep the working indicator alive for narrating scheduled runs

Watching a scheduled run live: the first tool row appeared, then the
thinking indicator vanished with nothing streaming, and the rest of
the run (final answer, submit_and_exit) only showed up seconds later
in one lump.

inferHydratedChatStatus treats a "running" session record whose
transcript ends on an assistant message as a session that died without
a status flip and reports "completed". That heuristic is right for
stale records, but scheduled/automation models narrate between tool
calls, so a polled snapshot can genuinely end on assistant text
mid-run — the completed flip hid the working indicator, folded the
run early, and disarmed the stale-stream poll (status left the busy
set), dead-ending live updates until an in-flight poll happened to
deliver the finished run.

The heuristic now only applies once the transcript has actually gone
quiet (newest message older than two minutes — comfortably past model
latency plus tool runs). A recently active transcript keeps the
record's "running" verdict, so the indicator stays up and polling
stays armed until the record itself settles.

* fix(desktop): stale-stream poll mirrors the session record instead of inferring

Replaces the previous fix for the vanishing working indicator (the
time-window guard added to inferHydratedChatStatus) with a version
that adds no inference at all: the heuristic is restored to exactly
its long-standing form, and the poll now maps the session record's
status verbatim (mapSessionRecordStatus).

The record is the right authority in the poll's context: the sessions
this fallback serves have a live host maintaining their record, and it
flips to a terminal status when the run ends. Transcript-shape
inference belongs only where it has always lived — hydrating sessions
whose records may be orphaned — and would misread a mid-run snapshot
ending on assistant narration as a finished session, hiding the
working indicator and disarming the poll.

* fix(desktop): address review findings on steering detection and run-now matching

Steering detection additionally requires the injected-message marker
(meta.userRunSpan === 0) beside the [SYSTEM] prefix, so a person's
genuine prompt that happens to start with "[SYSTEM]" stays visible
and turn-counted. The failure direction is deliberate: an unstamped
injected reminder would merely show as a user bubble, while the
content-only check could hide a real prompt.

Run-now only follows the execution id the trigger reply itself named;
the newest-execution-for-this-schedule fallback could open a previous
run's session when the trigger failed to enqueue one.

* fix(desktop): report a failed run-now instead of confirming a start

A trigger reply without an execution means no run was enqueued (the
schedule may have been disabled or deleted since the page loaded). The
handler previously toasted "Run started" regardless and then silently
skipped the session-open polling. It now shows a destructive
"Run not started" toast, refreshes the schedule list so the row
reflects reality, and skips the polling entirely.
2026-08-25 23:28:21 -07:00
Saoud Rizwan 110138b540 feat(desktop): sidebar time view, Customize/Marketplace split, and schedule page UX (#13570)
* feat(desktop): split Customize into Installed and Marketplace pages

The Customize hub previously embedded a Browse section inside every tab
that had a catalog. That inlining made each tab long and buried the
catalog. Customize is now the installed inventory only (skills, MCP,
plugins, rules, hooks, tools tabs pass marketplaceVariant="installed"
to the embedded MarketplaceView; McpServersContent grew the same prop),
with an outline Marketplace button in the header.

Browsing moved to a dedicated Marketplace settings section that renders
the previously dead "directory" variant of MarketplaceView: one list
across all catalog types with type-filter chips, wrapping tag chips,
and light rules separating the filter tiers from each other and from
the results. The Clear control now renders inline at the end of the tag
row only while a tag is active, the Updated date is gone, and the
header hosts an Installed button mirroring the one on the Customize
page. Directory subheader copy: "A curated set of plugins, MCP
servers, and skills from the Cline community."

Tag and type chips wrap to new lines instead of scrolling
horizontally.

* feat(desktop): sidebar time view with sections, sort toggle, and scheduled detection

Restores the time-sorted session list as the default sidebar view, with
collapsible Pinned / Scheduled / Tasks sections (headers appear only
once something is pinned or scheduled) and the page-fill effect that
grows the fetched history window until a Show-more click makes visible
progress. Project grouping stays as the alternate mode behind a
one-click sort toggle whose icon reflects the active mode — the old
dropdown cost an extra click for a two-option choice.

Scheduled sessions are detected two ways: the hub-schedule origin
trigger in session metadata, plus a fallback that asks the hub which
session ids belong to schedule executions (list_routine_schedules,
fetched on mount and every two minutes, merged into a rolling set).
The fallback matters because locally executed scheduled runs do not
reliably stamp the trigger into session metadata — a real scheduled
session created today carried only {mode:"user"} provenance. The
scheduled clock icon now leads the row, left of the title; pin and
timestamp stay on the right.

The initial visible page grows from 10 to 30 rows so a tall sidebar
fills instead of stranding a stub of rows over empty space (history
fetches already start at 50).

The expanded sidebar's Customize row now hosts indented Installed and
Marketplace sub-tabs while a customize section is open; the active
sub-tab carries the full selected background while the parent keeps a
subtler one so the two simultaneous highlights read differently.

Also fixes the hover-card flash on click (logo card and session-row
cards): Radix HoverCardContent sits on a DismissableLayer, so a click
on the trigger registers as a pointer-down outside the card and
dismisses it, and the trigger's focus event immediately reopens it.
onPointerDownOutside preventDefault suppresses the dismissal; cards
still close on pointer leave.

* feat(desktop): schedule page row, dialog, and details UX polish

Schedule cards are now click targets: clicking anywhere on a card
outside its controls opens the details dialog (guarded via
closest("button,...") since every inline control, including the Radix
switch, renders a button element), with Enter/Space keyboard support.
The redundant eye button is gone. The remaining edit / run / pause /
delete buttons grow from the 12px icon-sm size to 28px targets with
16px icons, sized consistently with the adjacent enable toggle — the
icons use explicit size-4 classes so the Button base svg rule cannot
shrink them back.

The new/edit dialog gains breathing room between field labels and their
inputs (space-y-2 per field wrapper).

The details dialog no longer scrolls as a whole when the schedule JSON
is long: the dialog is a flex column capped at 85vh, the JSON pre
shrinks to the remaining space (min-h-0) and scrolls internally, and
the Runs tab list scrolls inside the tab the same way.
2026-08-25 15:19:29 -07:00
Haley Park 3497391c5a feat(desktop): customize macOS DMG install window (#13563)
* feat(desktop): add Retina DMG background tooling

* feat(desktop): customize the macOS DMG layout

* ci(desktop): validate DMG background assets

* fix(desktop): adjust DMG Applications icon position

* ci(desktop): drop redundant DMG artwork validation from publish workflow

Tauri's beforeBuildCommand already runs dmg:background (with its own
validation) at the start of the build/sign/notarize step, and the
release/beta config overlays do not override the build section, so this
step duplicated work the publish job performs anyway. PR-time coverage
lives in desktop-test.yml.

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

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-25 14:30:59 -07:00
Mikołaj Kondratek 9154a54a0e fix: stop showing cost estimates for subscription-billed providers (#13552)
* fix(vscode): stop showing cost estimates for subscription-billed providers

Providers whose usage is covered by a flat-rate subscription (ChatGPT
Plus/Pro via openai-codex, ClinePass) are marked with
metadata.usageCostDisplay = "subscription" in the SDK, and the CLI
already suppresses dollar figures for them. The VS Code host collapsed
that value into "show" before it reached the webview, so the task
header and model pricing rows rendered API-rate cost estimates that
users read as real charges on top of their subscription.

Pass all three usageCostDisplay values ("show" | "hide" |
"subscription") through the catalog listing and render cost only when
the value is "show", matching the CLI's shouldShowCliUsageCost
policy.

* feat(llms): mark Claude Code as a subscription-billed provider

Claude Code is typically authenticated with a Claude Pro/Max
subscription, but its models reuse Anthropic API pricing metadata, so
Cline rendered per-token prices and API-rate cost estimates for usage
that is covered by the subscription. Set usageCostDisplay =
"subscription" on the provider (picked up by the CLI and the VS Code
webview) and suppress the price rows in the Claude Code settings card.

The Claude Code CLI can also run on API-key billing, where a real cost
exists; the provider cannot distinguish the two, so we prefer showing
no number over a misleading one.

* fix(vscode): suppress cost display until provider listings load

While the ListProviders request is in flight (or after it fails), the
usage-cost hook had no listing to consult and fell back to "show",
flashing the API-rate estimate at subscription users on every chat-view
mount — the exact display the previous commit removes. Return
"unknown" whenever listings are absent; consumers already render cost
only for "show", so they suppress it during that window with no
changes. Briefly hiding a real cost is harmless, briefly showing a fake
charge is not.
2026-08-25 19:17:14 +02:00
Tomás Barreiro 7d004f8dc7 Hide task costs on vscode when ClinePass is selected (#13515) 2026-08-25 18:11:41 +02:00
Max 432e00eaa6 fix(vscode): include rich workspace metadata in system prompt (#13518)
* capture richer workspace information for vs code extension

* fix(shared): redact credentials from workspace remotes

* fix(shared): avoid regex backtracking in remote redaction

---------

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-08-25 09:02:49 -07:00
Mikołaj Kondratek 095385b985 fix(desktop): unblock sdk-test lint on the voice-input model picker (#13553)
The model picker renders a radiogroup of styled buttons with role=radio
and aria-checked; biome's useSemanticElements flags the role as an
error, which fails the sdk-test Quality Checks lint for every PR
touching sdk/ or apps/ paths. Suppress with a justification — switching
to input type=radio needs a restyle and belongs to the desktop settings
work.
2026-08-25 08:58:23 -07:00
Saoud Rizwan 491b30b806 chore(desktop): release v0.0.17 2026-08-25 01:49:58 -07:00
Saoud Rizwan 8b046d04f9 feat(desktop): Customize hub, sidebar overhaul, and settings polish (#13538)
* feat(desktop): merge customization pages into a Customize hub with inline marketplace

Replaces the Plugins page and the dedicated Marketplace page with a single
Customize hub. Tabs: Skills, MCP, Plugins, Rules, Hooks, Tools, each with
live counts. Tabs backed by a marketplace catalog render the installed
items followed by an inline browsable Browse section (CLI-hub style), so
installing from the catalog immediately reflects in Installed above.

- Installed cards restyled to mirror the browse-card anatomy: bg-card p-4
  containers, absolute top-right xs Uninstall matching Install, truncating
  semibold titles, primary-tinted icons, real Badge components instead of
  ad-hoc bordered spans, un-indented line-clamped descriptions
- Rules/Hooks/Tools rows brought into the same card language; redundant
  intro paragraphs (duplicating the page description) removed; Tools group
  headers match the Installed header style with counts
- Marketplace section header renamed to Browse; duplicate 'N results' row
  removed (the header count is the single source)
- MCP embedded view now shows the full marketplace instead of
  installed-only

* feat(desktop): overhaul sidebar sessions and navigation

Sessions list:
- Sort toggle removed; sessions are always grouped by project, with pinned
  sessions leading each group (both subsets ordered by recency). The
  Pinned/Scheduled/Tasks category sections and their time-mode paging
  machinery (page-fill effect included) are deleted
- Scheduled sessions get an inline clock icon next to the pin position;
  pin + clock render together when both apply, and the running/unread
  status dot now coexists with them
- One font size (text-sm) across the list: titles, timestamps, project
  headers, show-more buttons, empty states. sidebarText needed !text-sm
  because the default button size's text-base wins the twMerge conflict
- Gradient fade under the Sessions header once the list scrolls, so rows
  fade out instead of hard-clipping
- The session-detail hover card is controlled from the sidebar and closes
  on scroll (Radix receives no pointer events while scrolling, so it used
  to float over moving content)
- Sidebar min resize width raised 224->260px; the per-project show-more
  label truncates so its nowrap text can't force rows to overflow and clip
  timestamps at narrow widths

Navigation:
- Customize replaces the Plugins/Marketplace/Hooks/Rules/Tools sidebar
  entries; Schedules and Customize are hidden from the expanded settings
  nav (their top rows cover them) but stay reachable when collapsed
- The settings gear always opens General instead of resuming the last
  section; the Account no-op hover special case is gone
- The New row highlights (aria-current) while the fresh not-yet-started
  task page is showing and hands off to the session row once the task
  starts; hitting New also focuses the prompt input via a window-event
  signal (lib/prompt-input-focus.ts) since the sidebar and composer sit in
  distant subtrees
- Fixed the xs button size collapsing any icon-bearing button to 12x12
  (leftover has-[>svg]:size-3 from when xs was a micro button) — this was
  why Uninstall buttons rendered broken next to Install

* feat(desktop): polish settings pages and chat composer

Models page:
- The provider detail panel is always open: no X button, no empty
  no-selection state. It defaults to the first connected provider (falling
  back to the first in the catalog), which also removes the layout shift
  that happened when the page swapped between full-width and panel
  variants on selection
- Fixed the list pane becoming unscrollable while the panel was open:
  grid items default to min-size auto, so the pane grew past its track
  inside the overflow-hidden grid and its ScrollArea had nothing to
  scroll; wrapped it in a min-h-0 min-w-0 cell
- Add Provider opens a Dialog instead of swapping the page
  (AddProviderContent gained a dialog variant that renders only the form)
- Embedded inputs (provider search, model search, detail fields) share one
  EMBEDDED_INPUT_CLASS stripping the Input component's own border/dark bg
  tint/shadow/ring, which rendered as a mismatched inner box; the model
  search box uses the same h-9/px-3 frame as the provider search
- Model list flows with the page instead of a max-h capped inner scroller

Other pages:
- Account uses the shared PageFrame/PageHeader: left-aligned, text-3xl
  title, Sign Out in the header actions slot
- Desktop notifications is one General section: header row plus the
  Event/Notify/Sound matrix nested in a card, so its rows no longer read
  as top-level peers of Dark mode; 'Available in the desktop app' label
  removed
- Schedule page retitled from Schedules with a real description; Customize
  description rewritten

Chat composer:
- The voice dictation button only renders once a voice model is
  configured (Settings -> Voice); the unconfigured deep-link state is
  gone (prop type kept for an easy restore)
2026-08-25 01:43:58 -07:00
Saoud Rizwan 8a6c6f8afe Redesign desktop Model Providers page and split voice input into its own settings page (#13531)
* Redesign desktop Model Providers page and split voice input into its own settings page

- Group providers into Connected / Popular / All with auth-kind hints and
  connection status instead of per-row enable toggles
- Show browser sign-in (not an API key field) for OAuth providers, with a
  collapsed manual-key escape hatch where supported, plus explicit
  Connect / Disconnect / Sign out actions
- Move voice input to a dedicated Settings > Voice page that only offers
  connected transcription-capable providers, preselects a default model
  (streaming preferred), and stays disabled in the sidebar until a
  provider is connected

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

* Show native tooltip on the disabled Voice settings nav item

Disabled buttons drop pointer events, so the 'connect a model provider'
hint moves to a wrapping span for the browser tooltip to render.

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

* Drop letter avatars and gray provider ids from provider rows and voice chips

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

* Drop model counts from provider list rows

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

* Rename provider Connected status to Configured and drop the green styling

A settings entry is configuration, not a live connection; neutral gray
text avoids implying an active link, since the user still picks which
configured provider to use per chat.

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

* Resync provider catalog from disk when a settings save fails

Connect/disconnect/credential edits update the list optimistically; a
failed save now reloads the catalog instead of leaving the optimistic
state (and the view's module cache) claiming a configuration that was
never persisted.

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

* Rename oauthProvider test fixture to dodge CodeQL name heuristic

CodeQL's clear-text-storage query flags any identifier matching 'oauth'
as a credential source and traced the fixture's provider id into the
favorite-models localStorage write, which stores only provider/model id
strings. Renaming the fixture removes the false-positive source.

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

* Guard catalog reloads against races and resync detail drafts on failed saves

Optimistic provider mutations now bump a generation that discards any
in-flight catalog response, so a failed-save recovery reload can't
overwrite a newer edit with an older disk snapshot. The recovery also
remounts the provider detail panel via a reset token so its local field
drafts reflect the reloaded on-disk state instead of unpersisted edits
or an optimistically cleared disconnect.

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

* Fix failed-save recovery ordering and retry superseded reloads

Remount the provider detail only after the authoritative catalog reload
lands, so its drafts re-seed from disk state rather than the optimistic
values that failed to persist. When a concurrent edit supersedes the
recovery's in-flight response, retry the reload (bounded) instead of
dropping it, since that edit performs no reload of its own.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 23:54:09 -07:00
Saoud Rizwan 4f5f238407 Desktop app: organize sidebar sessions into Pinned, Scheduled, and Tasks sections (#13528)
* Add Pinned/Scheduled/Tasks categories to desktop app sidebar

Replace the Schedules and Favorites filter-menu options with visible
collapsible category sections in the session sidebar, and rename the
Favorite action to Pin across the sidebar and sessions view.

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

* Grow full history window when Tasks show-more outpaces loaded tasks

loadMoreSessions treats its argument as a limit on all sessions, but the
Tasks show-more count only tracks Task rows, so once pinned/scheduled
rows pushed the loaded total past the requested count the call no-oped
and clicks went dead. Grow the whole history window via
loadOlderSessions instead, and only when the loaded tasks cannot fill
the next page. Addresses Greptile review on #13528.

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

* Auto-fill the Tasks page instead of fetching once per show-more click

A single 50-session window growth can consist entirely of pinned or
scheduled sessions, leaving a show-more click with no visible Tasks
progress. Replace the one-shot fetch with a page-fill effect that keeps
growing the history window until the requested Tasks page fills or
history runs out. Addresses the follow-up Greptile review on #13528.

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

* Halt page-fill retries after a failed history fetch

A failed fetch leaves the task count and has-more state unchanged,
which are exactly the conditions the page-fill effect fires on, so one
failing request would retry and re-toast forever. Halt the effect after
a failure and let the next explicit show-more click retry. Addresses
the third Greptile review on #13528.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 22:51:00 -07:00
Saoud Rizwan 8f69880ac4 Hide Channels and Agents sections from desktop app sidebar (#13527)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 21:54:59 -07:00
Saoud Rizwan a0c341e93c desktop: sidebar navigation cleanup with New/Schedule/Customize rows and dialog-based search (#13533)
* desktop: clean up sidebar navigation chrome

- Give New Task its own full-width labeled row below the logo row
  instead of an ambiguous icon next to the agenda toggle
- Wire the New Task row to the home action so starting a new task
  clearly takes you home (the logo still works as a fallback)
- Swap back/forward chevrons for browser-style arrow icons and
  bump their size

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

* desktop: sidebar New/Schedule/Customize rows and always-visible search

- Stack New (plus icon), Schedule, and Customize as full-width labeled
  rows below the logo; whole row highlights on hover via sidebarItem
- New starts a fresh task (home), Schedule opens Settings > Schedules,
  Customize opens the Customizations sections (Plugins first)
- Show the session search bar permanently above the sessions list
  instead of hiding it behind a search icon toggle

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

* desktop: move session search into a dialog behind a logo-row icon

- Replace the inline sidebar search bar with a search icon in the
  logo row that opens a cmdk command dialog listing sessions
- Selecting a result opens that session and closes the dialog
- Remove the agenda/tasks toggle the icon replaces, along with the
  now-unreachable sidebar Agenda panel (the welcome screen still
  surfaces agenda tasks)

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

* desktop: load full session history when the search dialog opens

Addresses Greptile review on #13533: the dialog only searched the
currently loaded history batch, so older unloaded sessions could not
be found. Opening search now kicks off loadAllSessions() (the hook's
purpose-built global-search loader), and the empty state reads
'Searching older sessions...' while more history is streaming in.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 21:53:47 -07:00
Saoud Rizwan f91af30401 Add Desktop App and Cloud Platform to bug report issue template (#13532)
* Add Desktop App and Cloud Platform to bug report surfaces

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

* Rename Surface Diagnostics field to Diagnostics

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 19:49:47 -07:00
Saoud Rizwan 83b2588c9c Disable the agent todo tool and hide the Agenda UI in the desktop app (#13530)
* remove todo tool and Agenda UI, keep schedule-only tasks tool

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

* chore: biome formatting fixes

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

* restore agenda backend; disable todo kind behind a flag instead of deleting

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

* keep agenda automation pump idle while the todo tool is disabled

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

* remove todo tool and Agenda UI altogether (revert the disable-flag hybrid)

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

* restore all agenda code to main state

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

* disable agent todo tool and hide Agenda UI behind flags

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 19:35:51 -07:00
Saoud Rizwan 6e09e81a79 Add suggested schedule templates to the desktop Schedules page (#13529)
* Add suggested schedule templates to desktop Schedules page

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

* Fix unreadable selected text in inputs caused by selection utility conflict

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

* Restyle Suggested section label as small gray uppercase

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

* Hide suggested schedule cards that match an existing schedule name

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 18:14:01 -07:00
Saoud Rizwan dc43a57fd7 fix(tools): create new files with the platform-native line ending (#13521)
* fix(tools): use platform-native EOL for new files and preserve CRLF in apply_patch updates

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

* simplify to the minimal new-file EOL fix

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

* extract shared normalizeNewFileLineEndings helper

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 17:54:54 -07:00
Saoud Rizwan 833cc891b5 chore(vscode): hide per-tool MCP auto-approve checkboxes behind a flag (#13522)
* chore(vscode): remove per-tool MCP auto-approve checkboxes from webview

MCP auto-approval is now governed solely by the global 'Use MCP servers'
toggle; the SDK approval path (shared with the CLI and desktop app) has no
per-tool granularity, so the per-tool and 'Auto-approve all tools'
checkboxes were no-ops that implied control that no longer exists. Remove
them from the MCP settings view and chat tool rows. The autoApprove arrays
in cline_mcp_settings.json and the toggleToolAutoApprove RPC are left
intact for the legacy extension.

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

* chore(vscode): hide per-tool MCP auto-approve checkboxes behind a flag

Keep the checkbox components, handlers, and RPC plumbing intact but gate
rendering behind SHOW_MCP_PER_TOOL_AUTO_APPROVE=false: the SDK approval
path (shared with the CLI and desktop app) is all-or-nothing via the
global 'Use MCP servers' toggle, so the per-tool checkboxes were no-ops.
Flip the flag back on if the SDK gains per-tool approval granularity.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 17:47:15 -07:00
Saoud Rizwan a2fb1d15ca fix(core): prevent search_codebase from crashing the process on giant single-line files (#13525)
* fix(core): prevent search_codebase from crashing the process on giant single-line files

searchWithRipgrep buffered all of rg's --json stdout into one string. Each
JSON event embeds the full text of the matched line (--max-columns is
ignored in JSON mode), so searching a directory of serialized trace dumps
(single-line multi-hundred-MB JSON files) accumulated gigabytes of stdout
until string concatenation threw RangeError: Out of memory inside the
stream data handler. That throw is outside the tool's try/catch, so it
escalated to an uncaughtException and killed the CLI/hub daemon.

Parse rg's JSON events incrementally line by line, drop events larger
than 256KB, truncate matched/context lines to MAX_LINE_CHARS, and stop
reading once maxResults is reached. The fallback regex scan now skips
files larger than 10MB (reporting the skip count) and truncates its
context lines the same way.

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

* simplify search_codebase crash fix to a minimal diff

Replace the incremental JSON-event parser with three small guards: stop
buffering rg stdout past 10MB, drop the trailing partial event before
parsing, and slice fallback context lines to MAX_LINE_CHARS. Drops the
fallback file-size skip and skip-count reporting.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 17:45:59 -07:00
Saoud Rizwan 8e7a55498b chore(cli): release v3.0.58 2026-08-24 15:44:16 -07:00
Saoud Rizwan 0cfc901589 fix(hub): flush the /shutdown 202 before daemon teardown
The /shutdown handler queued teardown on a microtask, which runs before
the event loop's write phase, so the daemon could process.exit() before
the accepted 202 was handed to the socket. Unix masked it (uv_try_write
lands small loopback writes synchronously); Windows has no such fast
path and lost the race regularly — the recurring shutdown.e2e.test.ts
'socket hang up' failures on windows-latest. Start teardown from the
response's write callback instead, with an idempotent 1s fallback so a
client that vanishes mid-write cannot strand the daemon, and send
Connection: close so the client gets a FIN rather than an abort.

Since the flakiness this compensated for is fixed at the source, restore
maxWorkers: 2 for the Windows core suite (serializing it cost ~3 min of
CI per run), and raise the e2e daemon discovery hang guard 10s→30s —
it guards against hangs, not runner speed.
2026-08-24 15:43:44 -07:00
Saoud Rizwan a5c3181b78 fix(vscode): don't steal last-used provider from ClinePass on credential refresh (#13520)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 15:18:04 -07:00
Saoud Rizwan 8cb60caf0c chore(sdk): release v0.0.79 2026-08-24 14:55:30 -07:00
Mikołaj Kondratek c03e452315 fix(sdk): carry root overrides into the Node smoke-test sandbox (#13517)
ci-node-smoke.ts installs the packed SDK tarballs with a plain npm
install in a fresh temp dir, where the repo root package.json overrides
do not apply. When @sap-cloud-sdk 4.9.0 shipped (2026-08-24) it broke
@sap-ai-sdk/ai-api 2.14.0 (via @jerome-benoit/sap-ai-provider in
@cline/llms) with ERR_PACKAGE_PATH_NOT_EXPORTED, failing the smoke step
on every PR even though the root already pins @sap-cloud-sdk/* to 4.6.0.

Copy the root overrides block into the generated sandbox package.json
so the smoke install resolves the same pinned versions as the repo and
future third-party releases cannot break it independently.
2026-08-24 23:49:52 +02:00
Saoud Rizwan 83ff8fd2f5 fix(hub): cap hub-events db size so it can't fill the disk (#13516)
* fix(hub): cap hub-events db size so it can't fill the disk

Row/time retention alone didn't bound disk usage: envelopes carrying
full session snapshots reach hundreds of KB each, so retained rows
could total tens of GB, sweeps only ran hourly, and DELETE never
shrinks a SQLite file. Enforce a 64 MiB size budget in prune() (oldest
rows first, VACUUM to return the space), and also prune after every
16 MiB appended so bursts can't outrun the hourly timer.

Fixes #13505

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

* fix(hub): tolerate VACUUM failure on a full disk

VACUUM needs scratch space and can fail in exactly the state a
ballooned event log causes. The byte-budget deletes already bound live
data, so swallow the error and let the next sweep retry the reclaim
instead of aborting startup pruning and disabling the durable log.

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

* fix(hub): count the size budget in UTF-8 bytes, not characters

envelopeJson.length (UTF-16 units) and SQLite LENGTH() (characters)
undercount multibyte text by up to 3x, which could leave a CJK-heavy
log settled above budget and re-running VACUUM every sweep. Use
Buffer.byteLength and LENGTH(CAST(... AS BLOB)) instead.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-24 14:47:26 -07:00
Mikołaj Kondratek 397a6a3341 fix(vscode): resolve hook workspace identity from the window, not shared global state (#13352)
* fix(vscode): resolve hook workspace identity from the window, not shared global state

Hook discovery, hook cwd selection, and the workspaceRoots metadata passed
to hook scripts all read the workspaceRoots/primaryRootIndex global state
keys. Global state lives in ~/.cline and is shared by every Cline instance
(all VS Code windows, the CLI, the JetBrains plugin), and nothing writes
these keys anymore, so hooks resolved against whatever project some other
or older instance last recorded. With a second window open on another
project, a workspace's .clinerules/hooks scripts were never discovered.

Resolve workspace roots via a single guarded helper backed by
HostProvider.workspace.getWorkspacePaths() (in-process, window-scoped,
same as refreshHooks): blank paths are filtered, a host-bridge failure
degrades to no workspace roots instead of silently disabling global hooks
or skipping blocking PreToolUse guards, and one resolution is threaded
through hooks-dir discovery, cache misses, cwd selection, and hook input
metadata so they can't disagree (previously up to four host lookups per
hook execution — real gRPC round trips in the standalone host). Roots and
hooks dirs are matched on whole path segments with the longest root
winning, so prefix-sharing or nested workspace roots resolve to the right
project. The adapter creates the runner once per event and skips no-op
runners, making creation the single resolution point; the separate
hasHook/getHookInfo checks are removed. The dead workspaceRoots and
primaryRootIndex state keys are dropped, and the four hand-rolled
HostProvider.workspace test stubs are consolidated into one shared
helper.

* test(vscode): add e2e coverage for workspace-scoped hook discovery

Boots real VS Code with the packaged extension against the workspace
fixture, sends a prompt, and asserts the fixture's UserPromptSubmit hook
was discovered from the open window's workspace, executed with that
workspace root as its cwd, and received the same root in its
workspaceRoots input — the end-to-end contract the hook workspace
identity fix establishes.

* test(vscode): isolate the e2e hook fixture from the shared workspace

The UserPromptSubmit fixture hook lived in the shared e2e workspace, so
every prompt-sending spec executed it (hooksEnabled defaults to true) —
and its cold PowerShell spawn on Windows pushed chat.test.ts past the
5s expect timeout. hooks.test.ts now overrides workspaceDir to a
dedicated workspace-hooks fixture, so only the hooks spec pays the hook
spawn.
2026-08-24 23:28:11 +02:00
Saoud Rizwan c9b75155ea fix(cli): remove the $4.99 ClinePass promo copy (#13514)
The $4.99 first-month promo is ending, so the CLI's first-launch "Try ClinePass" dialog should no longer advertise it. Also drops the leftover CLI_PROMO_CODE plumbing, which has been an empty string since the promo-code flow was removed.
2026-08-24 13:09:42 -07:00
Saoud Rizwan 09ee902639 chore(vscode): release v4.1.15 2026-08-23 12:33:23 -07:00
Saoud Rizwan 2b7b01328a fix(vscode): auto-approve all MCP tool calls when the MCP toggle is on (#13498)
* fix(vscode): honor MCP auto-approve settings for SDK tool calls

The SDK extension required both the global 'Use MCP servers' auto-approve
toggle AND each tool's per-tool autoApprove flag before silently approving
an MCP call, while the legacy extension treated them as either/or. Restore
the legacy OR semantics so toggling MCP auto-approve works again.

Also key toolPolicies by the registered SDK tool name (via
defaultMcpToolNameTransform, now exported from @cline/core) instead of raw
server__tool. Servers whose names contain sanitized characters (e.g.
marketplace names like github.com/user/repo) or exceed 64 chars produced
policy keys that never matched the registered tool, so those MCP tools ran
without any approval gate; the live auto-approve lookup now re-applies the
transform instead of string-splitting the name.

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

* Revert "fix(vscode): honor MCP auto-approve settings for SDK tool calls"

This reverts commit 86c568fbba.

* fix(vscode): auto-approve all MCP tool calls when the MCP toggle is on

The SDK extension only auto-approved an MCP call when the global 'Use MCP
servers' auto-approve toggle AND that tool's per-tool autoApprove flag were
both set, so toggling MCP auto-approve appeared to do nothing and users had
to opt in each tool individually. The toggle alone now governs all MCP
tools; the per-tool flag is no longer consulted.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-23 12:12:32 -07:00
Saoud Rizwan be8b984d10 chore(vscode): release v4.1.14 2026-08-23 02:41:04 -07:00
Saoud Rizwan c870116d1d fix(telemetry): emit task.completed from every session teardown path (#13489)
The task.completed fallback lived only inside shutdownSession, but
stopSession/dispose route interactive sessions with a terminal reported
status through releaseSessionRuntime, which never emitted. Truthful
session-status reporting (shipped in 4.1.11) re-routed a large share of
interactive stops onto that branch and silently dropped the event.

Route the emission through a single choke point,
emitTaskCompletedOnTeardown, called from both shutdownSession and
releaseSessionRuntime. The completion criterion no longer reads
session.status: interactive sessions use the recorded final-turn
outcome (lastInteractiveTurnFinishReason), non-interactive sessions
keep the existing input.status === "completed" logic. A new
taskCompletedEmitted flag (also set by the submit_and_exit observer)
enforces exactly one task.completed per session. failSession now
records the errored final turn so a stale "completed" from an earlier
turn can never leak into the teardown emission. Telemetry only; no
user-facing behavior changes.
2026-08-23 02:34:26 -07:00
Saoud Rizwan 4f836ae7d0 test(sdk): give windows-sensitive suites realistic timeouts
Four consecutive SDK publish runs failed on windows-latest, each on a
different test, all of them plain timeouts: two @cline/shared SQLite
tests at the 5s vitest default, core's bash executor at 10s, and the hub
singleton endpoint test at 10s. The 2-core Windows runner spawns forks
and takes SQLite locks slowly enough to blow those budgets under load.

These timeouts guard against hangs; they are not timing assertions (the
one suite that does assert elapsed time, shutdown.e2e, was fixed by
removing file-level parallelism instead). Raise core to 20s and give
@cline/shared an explicit 15s in place of the inherited 5s default.
2026-08-22 16:39:19 -07:00
Saoud Rizwan 6cb653a362 chore(desktop): release v0.0.16 2026-08-22 16:34:23 -07:00
Saoud Rizwan 5077fe8697 fix(core): run hub e2e files serially so daemon timing budgets survive CI contention
singleton.e2e.test.ts (added in #13468) spawns real daemons and runs for
~15s. Vitest's default file parallelism let it run alongside
shutdown.e2e.test.ts, whose assertions are wall-clock bound: discovery
within 10s, exit within 5s, and a 2s shutdown watchdog. On the 2-core
windows-latest runner that contention alone broke those budgets, failing
the shutdown test two different ways across runs — once never observing
discovery, once with the daemon forced to exit before its HTTP 202
flushed (socket hang up). The test passed on Windows before #13468 and
has failed every SDK publish run since.
2026-08-22 15:18:04 -07:00
Saoud Rizwan 2266fe8cf4 chore(cli): release v3.0.57 2026-08-22 13:25:40 -07:00
Saoud Rizwan 21cb8d2525 chore(sdk): release v0.0.78 2026-08-22 13:03:18 -07:00
Saoud Rizwan 68ad354b52 chore(vscode): prepare 4.1.13 release 2026-08-22 12:50:54 -07:00
Saoud Rizwan e098a8ed0d fix(core): stop stored capability lists from silently revoking tool calling for custom models (#13476)
* fix(core): seed tools capability when custom model capabilities are synthesized from boolean flags

For a models.json entry with no explicit capabilities list, toStoredModelInfo
synthesized a capability array purely from boolean convenience flags (e.g.
supportsReasoning: true -> ["reasoning"]). modelSupportsToolCalling fails open
only for a missing or empty list, so the synthesized non-empty list read as an
authoritative denial and silently stripped every tool definition from requests
to custom OpenAI-compatible models (#13463).

Seed "tools" whenever the list was not explicitly authored and the boolean
projections made it non-empty, preserving the fail-open contract. Explicitly
authored capability lists remain authoritative and can still disable tools.

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

* test(core): cover stale catalog capability overrides

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

* fix: treat stored capability lists as non-authoritative for tool calling

The hasExplicitCapabilities guard still let two producers of tool-less
lists through:

- The VS Code legacy-override migration (legacyModelInfoToOverrides)
  persists explicit partial lists like ["prompt-cache"] into models.json
  for custom OpenAI-compatible models, which then read as an authoritative
  "cannot call tools" and drop every tool - same symptom as #13463.
- Any hand- or UI-authored partial list on a non-catalog model.

Stored entries and user-authored provider metadata have no way to declare
"cannot call tools" (there is no supportsTools field, and every writer
that authors a full list includes "tools"), so seed "tools" into any
non-empty list for a language model. Only generated catalog capabilities
remain authoritative - a genuine no-tools catalog model stays that way -
and non-language models (e.g. image generation) never gain a tools claim.

Also make legacyModelInfoToOverrides write "tools" into the arrays it
fabricates, matching the providers.json migration, so models.json stops
being poisoned for older readers.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-22 12:42:09 -07:00
Bee 1de61b178a feat(hub): add drain and upgrade commands with replay support (#13468)
* feat(hub): add drain and upgrade commands with replay support

* handles disconnection

* feat(hub): wire bot profiles, drain, and durable event/run-queue into the live transport

Completes the wiring the previous commits' primitives needed:
HubServerTransport gains isDraining(), hub.drain/hub.status/profile.get
command handling, and replayEventsAfter() (backed by the durable event
log), plus the sequence/sinceSequence wire types they depend on in
shared/hub.ts. run-queue-handlers.ts reads the active bot profile's
plugin roots when executing durable runs.

Also adds hub/profiles/: profile.json (identity/rules/plugins) ->
system prompt composition, --profile / CLINE_HUB_BOT_PROFILE
resolution, and the bundled cline-dad profile with its
cline_hub_support read-only diagnostics tool.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Revert "feat(hub): wire bot profiles, drain, and durable event/run-queue into the live transport"

This reverts commit 6696d5d202.

* fix(hub): dedupe replayed events by eventId, not just sequence

HubEventLogStore.append() returns a new envelope stamped with a
sequence rather than mutating the input, so a pending approval
re-issued sequence-less by subscribe() (it predates any durable-log
append) and its later sequence-stamped copy from the durable log are
two different objects carrying the same eventId. The replay-then-live
buffer in browser-websocket.ts only deduped by sequence, so the
sequence-less copy's guard never tripped and it was delivered a second
time when the buffer flushed after replay.

Track delivered eventIds alongside the sequence cursor; eventId
survives the append/stamp round-trip unchanged, so this dedupes the
exact-same logical event regardless of which copy arrives first.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(hub): wire drain, durable event log, and run queue into the live transport

CI on this branch failed bun run build:sdk: browser-websocket.ts,
client/index.ts, and hub-websocket-server.ts (already on this branch)
reference sequence/sinceSequence, HubServerTransport.isDraining(), and
the "hub.drain" command — but the commit that reverted bot profiles
out of this branch also reverted this wiring, since it shared a commit
with the profiles work. That wiring is a hub concern, not a
bot-profiles one; split it back out.

- shared/hub.ts: sequence/sinceSequence types, run.enqueue/run.list/
  hub.drain/hub.status/stream.replay capability, command, and event
  names. profile.get intentionally excluded — stays bot-profiles-only.
- context.ts: isDraining() on HubTransportContext. botProfile field
  intentionally excluded.
- hub-server-transport.ts: eventLog/runQueue fields and start/stop
  lifecycle, publish() appends to the durable log, handleCommand cases
  for run.enqueue/run.list/hub.drain/hub.status, drain-refusal check,
  replayEventsAfter()/lastEventSequence(). startBotProfile()/
  startHubSupportTool() and the profile.get case intentionally
  excluded.
- run-queue-handlers.ts: added without handleProfileGet (needs
  ctx.botProfile, which doesn't exist here).
- hub-upgrades.test.ts: added without its two bot-profile-injection
  tests (they need a resolved bot profile to assert against).

Verified bun run build:sdk exits 0 (the exact CI command) and
bunx vitest run src/hub passes (311/312; the one failure is the
same pre-existing environment-timing flake already present before
this change).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(hub): export instance-lock, event-log, and run-queue from the hub barrel

These landed as internal modules only; hub-server-transport.ts and
hub-websocket-server.ts import them by direct path, but nothing
re-exported them from the public @cline/core/hub surface the way
sibling discovery/server modules already are.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(hub): wire the instance lock into the daemon entry point

The singleton lock (discovery/instance-lock.ts) and its consumption in
startHubWebSocketServer/ensureHubWebSocketServer were already on this
branch, but the daemon entry point's own half was not: retrying a bind
when a retiring predecessor still holds the lock, and exiting with a
distinct code (3) instead of the generic fatal path when a live Hub
already owns the data directory. Without this, a daemon racing a
retiring predecessor could fail outright instead of waiting the lock
out, and losing the singleton race looked identical to a crash.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(hub): address drain/upgrade review findings (#13478)

- cline hub upgrade: check idleness at least once (--wait 0 works), reject
  non-numeric --wait, and un-drain on every abort path so an aborted
  upgrade can never leave the hub refusing new work
- add cline hub drain --off and the off query param to requestHubDrain so
  POST /drain?off is reachable from shipped code
- HubEventLogStore/HubRunQueue: WAL journal mode + busy_timeout, and stamp
  sequences from lastInsertRowid instead of SELECT MAX(sequence)
- HubInstanceLock.acquire: degrade to an unheld lock when SQLite is
  unavailable instead of refusing hub startup; only BUSY/LOCKED still
  raises HubLockHeldError
- ensureHubWebSocketServer: retire an unusable discovered hub through the
  shared retireDiscoveredHub (busy hubs are attached to, drain precedes
  shutdown, discovery cleared only when the hub actually retired)
- replay adapter: advance the cursor past eventId-deduped events, cap
  replay pages, stop when the cursor stalls, and drop the dedupe set after
  the buffered flush so it cannot grow for the socket lifetime

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

* fix(hub): derive the singleton e2e challenger cwd portably

The challenger's working directory was derived by round-tripping the
discovery path through a file: URL and stripping the last pathname
segment. On Windows that yields a POSIX-style '/C:/...' path, which is
not a valid spawn cwd, so the spawn fails ENOENT before the singleton
lock is ever contested and the Windows SDK test job goes red.

The data dir is simply the discovery file's parent: use dirname().

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-21 21:49:21 -07:00
Saoud Rizwan e7ed29109b ci(vscode): make combined nightly manual-dispatch only
The PublishNightly environment gained required reviewers, so each cron
run parked on approval, held the workflow's concurrency group, and
silently cancelled every scheduled run queued behind it. 20 consecutive
scheduled nightlies died this way between 2026-07-31 and 2026-08-21;
the only nightlies that shipped in that window were manual dispatches.

Drop the cron rather than leave a trigger that cannot succeed unattended.
2026-08-21 17:01:56 -07:00
Bee 9316de6bb5 fix: propagate Langfuse session telemetry (#13473)
* fix telemetry session propagation

* feat telemetry client version metadata

* fix(core): address Langfuse review feedback — hub client identity + delegated agent session grouping (#13475)

* fix(core): rebuild hub session client identity from request headers

Hub-backed sessions do not transport extensionContext (it is local-only),
so the daemon's runtime built traces without the clientName/clientVersion
metadata even though the hub client bakes X-CLIENT-TYPE / X-CLIENT-VERSION
into the session's provider headers. Reconstruct extensionContext.client
from those headers during local runtime bootstrap so hub-backed Langfuse
traces carry the same client identity as local runtimes, and the daemon's
header re-resolution stops clobbering the original X-CLIENT-TYPE.

* fix(core): propagate parent distinctId/sessionId to delegated agents

Delegated agents (spawned sub-agents, configured agents, teammates) were
built without distinctId and sessionId, so their Langfuse traces had no
userId or sessionId and did not group with the parent user or session.
Thread the host-resolved distinctId through RuntimeBuilderInput and the
root sessionId through the delegated-agent config provider, and copy both
onto the delegated AgentConfig.

---------

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-21 16:34:21 -07:00
Tomás Barreiro fb58e340a2 Add feature flags to the desktop app (#13289)
* Add feature flags to the app

* React to account updates

* Address comments

* use a per-app file
2026-08-22 00:25:30 +02:00
Saoud Rizwan db6d18a98a chore(vscode): prepare 4.1.12 release 2026-08-21 13:53:56 -07:00
yzxcj797 2ea460fa46 Treat an empty preserved capability list as unspecified when seeding tools (#13465)
* Treat an empty preserved capability list as unspecified when seeding tools

toSdkModelInfo guarded the tools seeding with a strict
preservedCapabilities === undefined check, but modelHasCapability —
the runtime's own reader — treats undefined AND length === 0 as
"unspecified". A custom OpenAI-Compatible model whose stored
capabilities field is a defined-but-empty array (a config carried over
from before the field existed, or one round-tripped through a boundary
that defaults it to []) skipped the seeding; the first boolean
projection to run afterwards (e.g. supportsReasoning) then populated
the array, the runtime gate read the non-empty, tool-less list as
authoritative, and every tool definition was silently dropped from the
session (#13463).

The guard now covers the empty array too, matching the reader's
unspecified semantics.

* test: satisfy the store's isModelInfo gate so the empty-capabilities case actually reaches knownModels

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

---------

Co-authored-by: yzxcj797 <yzxcj797@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-21 13:42:01 -07:00
Saoud Rizwan 7d366ce7d4 fix(vscode): remote config MCP settings (#13466)
* fix(vscode): enforce enterprise MCP controls on the Customize marketplace

The unified Customize marketplace replaced the old MCP marketplace
without carrying over enterprise remote-config enforcement: the catalog
RPC returned every MCP entry and installs were never policy-checked,
so orgs with mcpMarketplaceEnabled=false or an allowedMCPServers
allowlist saw (and could install) all marketplace MCP servers.

- Filter MCP entries out of getMarketplaceCatalog when the marketplace
  is disabled, and restrict entries to the allowlist when configured
  (matching entry id, display name, installed server name, or source
  repo URL, mirroring legacy GitHub-URL allowlist ids)
- Reject installMarketplaceEntry requests that violate the policy
- Map the published catalog's repo/homepage fields onto
  sourceUrl/homepageUrl so URL-based allowlists can match
- Update the enterprise MCP server controls docs

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

* refactor: simplify MCP marketplace policy enforcement

Fold the policy check into marketplace-helpers, drop the dedicated
test suite, and trim the docs edit to the strictly necessary line.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-21 12:40:01 -07:00
Saoud Rizwan fb60f9e5fd chore(desktop): release v0.0.15 2026-08-20 22:42:08 -07:00
Saoud Rizwan 9e0015b78b chore(vscode): prepare 4.1.11 release 2026-08-20 22:07:44 -07:00
Saoud Rizwan 4a128d5f76 docs(cli): drop the tasks tool from the v3.0.56 notes, it is desktop-only 2026-08-20 21:38:16 -07:00
Saoud Rizwan b5cfe88846 chore(sdk): release v0.0.77 2026-08-20 21:38:02 -07:00
Bee 355ce11ae2 refactor: centralize client tool availability (#13451) 2026-08-20 21:34:38 -07:00
Haley Park 05da55857a feat(desktop): reskin first-run onboarding (#13441) 2026-08-20 20:48:34 -07:00
Haley Park 35583ee8bb feat(desktop): interactive welcome hero graphic (#13399)
* feat(desktop): add interactive welcome hero

* feat(desktop): support composable welcome hero variants
2026-08-20 20:47:52 -07:00
Saoud Rizwan a8d260f1bd docs(cli): scope the v3.0.56 release notes to CLI-visible changes 2026-08-20 19:52:20 -07:00
Saoud Rizwan 59ee1ea80e chore(cli): release v3.0.56 2026-08-20 19:39:45 -07:00
Saoud Rizwan bd218aa7bb chore(sdk): release v0.0.76 2026-08-20 19:23:35 -07:00
cline-cloud[bot] 80b3b0348e docs: remove duplicate GLM-5.3 rows in ClinePass tables (#13449)
Co-authored-by: cline-cloud[bot] <276134852+cline-cloud[bot]@users.noreply.github.com>
2026-08-20 19:13:56 -07:00
Renee Huang 401cf5e12a docs: simplify Open Cline step in installing guide (#13405) 2026-08-20 18:32:58 -07:00
Bee 48feb02ae9 chore(deps): update Langfuse packages and bump app versions (#13443)
* chore(deps): update Langfuse packages and bump app versions

Update @langfuse/otel to v5.10.1 and add @langfuse/vercel-ai-sdk v5.9.1 for improved observability with Vercel AI SDK.

Bump versions for @cline/code to 0.0.14 and @cline/ui to 0.2.0-next.6, updated via bun.lock.

Other Changes:
Added optional userId to AgentRuntimeConfig.
Propagated userId, sessionId, conversationId, runId, iteration, provider, and model context into AI SDK telemetry.
Added AI SDK 7 runtimeContext with explicit includeRuntimeContext.
Added stable OTEL_SERVICE_NAME=cline-sdk.
Added runtime metadata assertions in agent tests.

* add taskId

* Revert "add taskId"

This reverts commit f20d31d96d.
2026-08-20 18:17:33 -07:00
Saoud Rizwan eef7958cad fix(core): report truthful session status so desktop checkpoint restore stops wedging (#13418)
* fix(core): keep hub session status truthful across queue-drained turns

Queue-drained turns settle only through the event stream, but the hub
runtime host mistranslated their lifecycle in two ways:

- session.updated events carrying only a snapshot (persistence updates)
  defaulted the projected status to "running". When one trailed the
  final idle update after a turn, clients that track busy state from
  status events (the desktop sidecar's workspace restore gate) stayed
  busy forever. Use the snapshot's real status and emit nothing when
  neither source reports one.
- the per-run agent.done dedup was only reset by run.started, which the
  daemon-side queue drain never publishes, so a drained turn's done was
  swallowed as a duplicate of the previous turn's. Reset the dedup on
  session.pending_prompt_submitted, and suppress stale run.completed
  events that land inside a drained turn's window so they can neither
  emit a phantom done nor consume the drained turn's dedup slot.

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

* test(desktop): cover restore unlock after an event-settled queued turn

Exports the sidecar's core-session event handler so the queued-turn
lifecycle (busy via status events, cleared by the done agent event,
restore allowed afterwards) is testable end-to-end.

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

* fix(core): start interactive sessions without a prompt as idle

The runtime host reported every new session as "running" until its
first turn ended. Interactive hosts (the desktop app) start sessions
with no prompt and dispatch turns through separate send calls, so a
created-but-never-prompted session stayed "running" forever — wedging
clients that gate workspace operations (checkpoint restore, message
edit) on active turns.

Interactive no-prompt starts now begin idle, start emits the session's
actual status (resumed sessions no longer masquerade as running), and
markTurn* transitions keep tracking in-memory status for lazily
persisted sessions so the first turn still reports running -> idle.

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

* style: format hub-runtime-host test filter

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

* refactor: drop the drained-turn done bookkeeping, keep the minimal fix

The stuck restore is fully explained by the two status defects (fabricated
"running" from snapshot-only session.updated events, and never-prompted
interactive sessions reporting "running"). The done-dedup machinery for
queue-drained turns addressed a separate cosmetic gap (queued turns emit no
chat_done, pre-existing) and required fragile run-window heuristics, so it
is removed to keep this change reviewable. Sidecar test now settles the
queued turn through the status event, matching the shipped mechanism.

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

* docs(sdk): document the truthful session-status contract

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-20 18:17:19 -07:00
Saoud Rizwan 04e08187f3 fix(vscode): show the diff edit view for multi-line edits in CRLF files (#13417)
The edit preview computed proposed content with an exact old_text match, but
the SDK executor normalizes old/new text to the file's own line endings before
matching (#12305) - reads strip CR, so models emit LF-only text even for CRLF
files. Any multi-line old_text in a CRLF file therefore failed the preview's
match: the diff edit view silently never opened while the executor applied the
edit. Single-line edits (no line break in old_text) were unaffected, which is
why the diff view appeared to trigger inconsistently.

Mirror the executor's EOL normalization (and its literal $-sequence insertion)
in the preview computation.

Fixes #13296

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-20 14:55:19 -07:00
Saoud Rizwan fed502e3cf fix(vscode): honor the classic truncation range when migrating legacy tasks (#13419)
Classic Cline truncated long conversations by omitting an index range of
api_conversation_history from every API request (keep the first
user-assistant pair, drop everything through the range end, strip
orphaned tool_results from the first kept message). The range was
persisted on the history item while the full history stayed on disk.

legacyApiHistoryToSdkMessages ignored conversationHistoryDeletedRange
and converted the entire file, so resuming a migrated long task handed
the SDK an untruncated working context that could exceed the model's
context window by millions of tokens - every request failed with
'prompt is too long' and every compaction restarted from the full
history (#12996, confirmed by the reporter: the task was migrated from
an older version and broke after a restart, with each compaction
starting from ~3M tokens).

The migration now replays exactly what the classic extension sent:
slice out the deleted range and drop orphaned tool_results, mirroring
ContextManager.getTruncatedMessages (see origin/main). Malformed ranges
fall back to the full history (previous behavior).

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-20 13:33:24 -07:00
Mikołaj Kondratek e685ebfd04 fix(core): stop Windows CI worker crashes from the agenda spec watcher (#13428)
* fix(core): watch agenda task specs via the resolved long path

fs.watch on a path with 8.3 short components (e.g. C:\Users\RUNNER~1
temp dirs) trips a libuv assertion in fs-event.c on Windows and aborts
the whole process. Since the agenda task manager landed, every hub
server test spins up its spec watcher on such a path on hosted Windows
runners, killing the vitest worker and failing the sdk-test Windows job
on every branch. Resolve the specs dir with realpathSync.native before
watching so libuv only ever sees the long form.

* test(ui): stub ResizeObserver for @pierre/diffs in tool-diff tests

jsdom does not implement ResizeObserver, so every ToolFileDiff render
logged a ReferenceError from @pierre/diffs to stderr. Tests still
passed; this just silences the noise the same way the constructable
stylesheet shim does.

* fix(core): skip the agenda spec watcher when the dir does not resolve

Falling back to the raw path on realpath failure would reintroduce the
Windows short-path abort; log and go without the watcher instead.
2026-08-20 22:26:02 +02:00
Mikołaj Kondratek 9b9a067fb8 fix(hooks): collect PostToolUse hook output and honor its control (#13298)
* fix(hooks): collect PostToolUse hook output and honor its control

tool_result (PostToolUse) hooks ran fire-and-forget with stdout
ignored, so their entire JSON output — contextModification and cancel —
was discarded. Legacy awaited PostToolUse, injected its
contextModification into the conversation, and honored cancel.

- Run tool_result hook commands blocking (same 120s default timeout as
  tool_call) in both the hook-config-file layer and the agent-hook
  subprocess layer.
- Map their output: cancel stops the run with the hook's error message
  as the reason; otherwise context is injected via afterTool
  appendContext.

This restores legacy blocking semantics: tool results now wait for
tool_result hooks, but only in sessions that have one configured.

Ref: https://linear.app/cline-bot/issue/CLINE-2987

* fix(hooks): bound tool_result hook wait and isolate cancel reason

Address review findings:
- The agent-hook subprocess layer forwarded an unset timeoutMs
  unchanged, so a tool hook command that never exits would block the
  agent indefinitely. Default both tool_call and tool_result to the
  120s bound the hook-config-file layer already used.
- A cancelling hook's error message was folded into the same context
  field as other hooks' injectable context, so merging controls could
  leak unrelated hook context into the cancellation reason. Carry it as
  a separate cancelReason, and surface it as the stop reason for
  beforeTool cancels too.

* fix(hooks): prefer errorMessage as a cancelling hook's stop reason

When a cancelling hook returns both contextModification and
errorMessage, the context-first parse precedence made the injectable
context the cancel reason and discarded the actual error. Parse the two
fields separately: errorMessage wins as the cancel reason (matching
legacy), and a lone errorMessage still folds into injectable context
for non-cancelling hooks as before.

* fix(vscode): honor PostToolUse hook cancel and contextModification

The adapter awaited PostToolUse hooks but discarded their output
entirely. Map cancel to a stop control (with errorMessage as the
reason) and contextModification into the runtime appendContext channel,
matching the PreToolUse mapping and legacy semantics.

* fix(hooks): whitespace-only errorMessage no longer suppresses the cancel reason

A cancelling hook returning meaningful context alongside a blank
errorMessage lost both: the parsers selected the whitespace as the
reason and the result mappers trimmed it away. Require a non-blank
errorMessage before it wins, so context serves as the fallback reason.
Apply the same fallback in the extension adapter's stop mapping.
2026-08-20 21:09:51 +02:00
Mikołaj Kondratek 8fe5a196c4 fix(hooks): deliver tool hook contextModification to the model (#13297)
* fix(hooks): deliver tool hook contextModification to the model

On the next engine, a tool_call (PreToolUse) hook's contextModification
was parsed into HookControl.context and then silently dropped: the
runtime beforeTool/afterTool result contract had no channel for
injecting conversation context. Legacy consumed it (ToolExecutor /
ToolHookUtils pushed <hook_context> blocks into the next user turn), so
this was a regression of documented behavior.

- Add appendContext to AgentBeforeToolResult/AgentAfterToolResult.
- AgentRuntime collects appendContext across hooks during an
  iteration's tool executions and appends one <hook_context> user
  message after the tool results, keeping tool-result parts contiguous.
- Map HookControl.context into appendContext in both subprocess hook
  layers (skipped when the hook cancels, matching legacy, where the
  message doubled as the error).
- Truncate injected context at 50KB per hook output, matching legacy.
- Concatenate appendContext across merged hook layers.

tool_result (PostToolUse) hooks still run detached with stdout ignored;
making them blocking so their context can be collected is a follow-up.

Ref: https://linear.app/cline-bot/issue/CLINE-2987

* fix(hooks): stamp tool identity on injected hook context blocks

Contexts are batched into one message after the tool results, and
parallel tool execution collects them in completion order, so position
alone cannot attribute a block to its tool call. Add tool_name and
tool_call_id attributes to each <hook_context> block.

* fix(hooks): sanitize hook context block markup

Attribute values (tool_name, tool_call_id) are stripped of quote/angle
characters and embedded </hook_context> closers in hook output are
neutralized, so neither provider-supplied ids nor hook text can corrupt
or spoof a block's stamped identity.

* fix(hooks): neutralize forged opening hook_context tags in hook output

The previous sanitization only neutralized closing tags, so hook output
could still open a forged <hook_context> block claiming another tool's
identity. Escape both opening and closing embedded tags with one rule.

* fix(hooks): hide injected hook context from user-facing transcripts

Stamp the injected hook-context user message with displayRole 'system'
(the compaction-summary convention) so it reaches the model but does
not render as a user bubble in live or replayed transcripts. Without
this, resuming a session showed the raw <hook_context> block as if the
user had typed it.

* fix(hooks): neutralize case-variant embedded hook_context tags

The tag-neutralization regex was case-sensitive, so hook output could
still smuggle a forged tag as <HOOK_CONTEXT>. Match case-insensitively.

* fix(vscode): map PreToolUse contextModification into runtime appendContext

The extension's hooks adapter bridged file hooks into the SDK runtime
but forwarded only cancel/errorMessage, so a PreToolUse hook's
contextModification never reached the model. Map it into the runtime's
appendContext channel; HookFactory already truncates it at 50KB.

* fix(vscode): hide hook-injected context from replayed transcripts

Live sessions never rendered the injected <hook_context> user message,
but session reload replayed it as a user bubble (and post-resume turns
kept doing so). Treat these messages as synthetic in the user-message
mapping: honor the displayRole 'system' stamp the runtime sets, with a
text-prefix guard for paths where metadata is unavailable. This also
keeps edit/regenerate ordinal mapping aligned with visible bubbles.

* fix(hooks): run file hooks through exactly one layer per host

The VS Code extension registered two independent hook execution layers:
its own hooks adapter (config.hooks) and the SDK core's file-hook
extension from the runtime bootstrap. When both discover the same hook
files, every hook executes twice per event — and with context injection
wired, each contextModification would be injected twice.

Add a 'hooks' runtime config extension kind (in the default set, so the
CLI keeps core file hooks unchanged) and gate the bootstrap's file-hook
extension on it. The extension excludes 'hooks' at session start, so
its adapter — which also provides the hook status UI and the
hooksEnabled setting — is its single execution path.

* fix(vscode): discover hooks from the session workspace, not only global state

Hook discovery read workspaceRoots from global state shared across
every Cline instance, so another window repointing it made workspace
hooks silently stop being discovered. With the extension's adapter now
the single hook execution layer, that meant no hooks at all.

HookFactory takes an optional sessionWorkspaceRoot and unions that
root's .clinerules/hooks into discovery (and into cwd resolution), fed
from the session config's cwd. Shared-state discovery still works, so
behavior in the single-window case is unchanged.

* fix(hooks): keep sanitized hook attribute values distinguishable

Replacing every markup delimiter with the same underscore could
collapse two tool call ids that differ only by such a character into
identical stamps. Escape each delimiter with a distinct token instead.

* fix(hooks): make hook attribute sanitization injective

Escaping the underscore itself turns the attribute escaping into a
uniquely decodable code, so no two distinct tool call ids can collapse
to the same sanitized stamp (previously an id containing a literal
escape token could collide with an id containing the delimiter).

* fix(vscode): reconstruct hook status rows when replaying transcripts

hook_status messages are emitted live but never persisted, so reloading
a session dropped every hook row. The injected <hook_context> blocks
carry the hook source and tool name, so the replay translator now
rebuilds a completed hook status row from each block. The injection is
also no longer treated as a user turn boundary, so the final turn's
completion retag is unaffected by it.
2026-08-20 20:41:53 +02:00
Mikołaj Kondratek e70b3ffc4b ci(vscode): upload E2E failure recordings from the right path (#13427)
The job sets working-directory: apps/vscode, but that default applies to run
steps only, not to `uses:` steps. Since #10961 moved the extension under apps/
and added that default, the artifact path has resolved against the repo root,
matched nothing, and every failing run logged "No files were found with the
provided path: test-results/playwright/" instead of uploading recordings.

Widen to test-results/ so Playwright's error-context snapshots ship alongside
the videos.
2026-08-20 20:10:12 +02:00
Haley Park e6f4d5fef7 feat(desktop): refresh app icons and branding (#13400) 2026-08-20 08:42:50 -07:00
Saoud Rizwan 16875140fb fix(ui): update packed-Tailwind smoke contract for the picker's max-h-64 (#13421)
The ui-publish smoke check pins a set of Tailwind candidates the packed
sources must emit; #13410 grew the SearchCombobox options list from
max-h-56 to max-h-64, so the publish run failed on the stale candidate.
All other pinned candidates verified against the current sources.
2026-08-19 22:19:14 -07:00
Saoud Rizwan 7903c76812 feat(desktop): recommended-feed badges and descriptions in provider settings (#13416)
* feat(ui): sectioned model picker support in SearchCombobox

Adds option sections with headers, badges (NEW/Free pills), keyboard
navigation (arrows/Home/End/Enter with active-row tracking and
aria-activedescendant), substring match highlighting, a configurable
panel width, a trigger chevron, and a cleaner borderless search row.
All additions are backwards compatible; bumps @cline/ui to
0.2.0-next.6.

* feat(desktop): recommended and free model tiers in the composer picker

The composer's model selector showed raw provider/model ids and listed
the entire catalog alphabetized by id. It now labels providers and
models by display name and, for the cline provider, leads with the
Recommended and Free tiers from the recommended-models feed (NEW/Free
badges, descriptions) ahead of an All models section — matching the
CLI's featured picker and the kanban selector. cline-pass gets
Subscribed/Free tiers. A new list_cline_recommended_models sidecar
command exposes @cline/core's fetchClineRecommendedModels (display-ready
names, bundled offline fallback); feed ids resolve against the catalog
with a unique-slug fallback for Vercel/OpenRouter alias spellings, and
unresolvable entries are dropped rather than rendered unselectable.

* fix(desktop): widen the provider trigger for display names

Provider labels are now display names (e.g. "Cline Usage-Billing"),
which truncated badly at max-w-28.

* chore(desktop): drop unused featured-models test helper

* style(desktop): align workspace/branch picker search rows with the model picker

The composer's workspace/branch popover and the welcome screen's
workspace and branch pickers used a boxed inner search shell that now
clashed with the model picker's borderless search row sitting next to
them. Behavior unchanged.

* feat(ui): center the selected option when SearchCombobox opens

Opening a long list previously scrolled the selection just into view at
the panel edge; it now lands centered, and keyboard/hover navigation
falls back to minimal nearest-edge scrolling.

* style(desktop): picker row contrast, transparent search fields, centered open

The workspace/branch pickers' rows had a nearly invisible
surface-hover-lighter hover; rows now hover with surface-hover and mark
the current entry with the accent background plus check, matching the
model picker. The search inputs drop the Input base class's
dark:bg-input/30 tint that rendered a gray box inside the panel in dark
mode. Opening a picker now centers the current workspace/branch via a
shared scroll helper instead of starting at the top of the list.

* fix(ui): visible option hover/selected states and no scroll-jump on hover

The option row stacked bg-transparent with the conditional state
backgrounds; at equal specificity the later-sorted bg-transparent
utility won, so hover/selected rows rendered with no background at all.
The background classes are now mutually exclusive.

Mouse-driven active-row changes also reused the keyboard scroll-into-
view effect: hovering a row at the panel edge scrolled it into view,
which moved the list under the cursor and re-triggered hover — an
endless jump. Scroll mode is now per-source: center on open, nearest
for keyboard/typing, none for hover.

* fix(desktop): show only subscribed and free tiers in the cline-pass picker

The ClinePass offer is exactly the feed's subscribed + free tiers, but
stale bundled/cached catalog entries (e.g. a nemotron model) leaked
into an "All models" tier. Match the CLI's featured picker: hide
catalog leftovers, and only fall back to the full catalog when the
subscribed bucket is empty so a subscriber is never limited to free
models offline.

* fix(ui/desktop): strengthen the selected-row highlight in light mode

The selected row used the semantic accent surface (violet step 3),
which is nearly white in light mode. SearchCombobox and the desktop
workspace/branch pickers now highlight the selected/current row with
accent step 4 (with a fallback to --accent), which reads clearly in
both themes without touching the shared --accent token that shadcn
hover states depend on.

* fix(desktop): fit full provider display names in the composer trigger

"Cline Usage-Billing" — the default provider — truncated to
"Cline Usage-Bi…" at max-w-36; the trigger now allows up to max-w-56,
which fits the longest built-in provider names.

* style(ui/desktop): animate picker panels open like the shadcn dropdowns

The thinking-effort Select (shadcn/Radix) animates open while the
model/provider/workspace/branch pickers popped in instantly. All picker
panels now share the same open treatment — 150ms fade + slight zoom,
sliding from the trigger side. SearchCombobox uses a self-contained CSS
keyframe (consumers may not ship tw-animate-css); the desktop's custom
panels use the app's tw-animate utilities. Both respect
prefers-reduced-motion.

* chore(desktop): drop stale eslint-disable comments in picker search rows

This repo lints with biome; the jsx-a11y/no-autofocus disables were
inert leftovers. Flagged in review.

* refactor(core/desktop): stamp recommended-feed tiers onto ProviderModel in the SDK

Review feedback on the composer picker: tier joining should live where
the SDK serves model lists so each client doesn't fetch and join the
recommended-models feed itself (the CLI and now the desktop each did).

ProviderModel gains description and featured ({tier, rank, tags});
getLocalProviderModels overlays the feed's recommended/free tiers onto
cline models and subscribed/free onto cline-pass via
applyClineFeaturedModels, matching feed ids through the
Vercel/OpenRouter alias rules. The feed access is a new cached wrapper
(getCachedClineRecommendedModels, 5-minute TTL, in-flight dedupe) —
this path runs on every picker open, and the bundled offline fallback
is cached too so offline users don't re-pay the 5s timeout per list.

The desktop webview now reads tiers straight off the models: the
list_cline_recommended_models sidecar command, the webview feed fetch,
and its unique-slug alias matching are all deleted. toProviderModel
also carries ModelInfo.description generally.

* feat(desktop): recommended-feed badges and descriptions in provider settings

Review suggestion on #13410: the provider settings page has room for
more model detail than the composer's picker. The cline/cline-pass
provider cards now refresh their model list through
list_provider_models (the catalog snapshot deliberately skips the
recommended-feed overlay so the startup catalog fetch never blocks on
the feed) and render Recommended/Free tier badges plus feed tags (NEW)
next to the model name, with the model description underneath. The
refreshed list also surfaces the live entries instead of the bundled
snapshot.

* fix(ui): hand focus back to the combobox trigger on selection, close on Tab

Selecting an option (Enter or click) unmounted the focused search input
without a new focus target, dropping keyboard users' focus to <body> —
only Escape restored it. And since the search input is the panel's only
tabbable element, Tab always moved focus outside the component while
leaving the popup open behind the new focus target.

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

* fix(desktop): keep the composer model selection inside the picker's visible offer

The active/remembered model was validated against the provider's full
catalog while the picker can intentionally hide models (the ClinePass
offer is exactly its subscribed/free tiers), so a stale remembered model
could become the selection while being absent from the dropdown.

Remembered and default selections (including on provider switch) now
resolve against the picker's visible options, and an explicitly
configured model that falls outside the offer stays active but is
surfaced under a 'Current model' section so the selection is always
visible and re-selectable.

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

* fix(desktop): scope the settings featured model list to its provider and revision

The fetched featured list was unscoped component state: switching
between cline and cline-pass reused the component instance, so the
previous provider's models stayed visible while the new request was
pending (or forever, when it failed), and the retained copy shadowed
later provider.modelList updates — adding a second custom model
submitted the stale list as the complete configuration and dropped the
first addition.

The fetched list now only applies to the provider and modelList
revision it was fetched for (falling back to the catalog snapshot
otherwise and refetching on membership changes), and add-model submits
the union of the displayed and configured ids so an update can never
silently unconfigure existing entries.

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

* feat(core): stamp featured tiers onto the provider catalog synchronously

listLocalProviders deliberately skipped the feed overlay so the catalog
never blocks on the network — but that left the composer's very first
picker open after a cold boot rendering an untiered flat list until the
per-provider fetch landed. Blocking was never required: stamp tiers from
a synchronous peek at data already in memory (the cached live feed when
fresh, else the bundled fallback, whose recommended ids resolve against
the bundled cline catalog). The per-provider model-list path still
refreshes with live feed data moments later.

* fix(core): harden featured-tier matching and the feed cache reset

Review findings on the tier overlay:

Vendor-prefix mismatches now match by unambiguous id slug (two-pass, so
a catalog carrying both spellings of a model stamps one row, and a slug
shared by two feed entries stamps nothing) — the bundled fallback feed's
vendor-prefixed ids can otherwise miss cline-free/-prefixed catalog
entries, leaving them untiered in degraded mode.

resetClineRecommendedModelsCacheForTests now bumps a generation so an
in-flight feed request resolving after a reset cannot repopulate the
cache it just cleared.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 22:13:40 -07:00
Saoud Rizwan b060cecc05 refactor(core/desktop): stamp recommended-feed tiers onto ProviderModel in the SDK (#13415)
* feat(ui): sectioned model picker support in SearchCombobox

Adds option sections with headers, badges (NEW/Free pills), keyboard
navigation (arrows/Home/End/Enter with active-row tracking and
aria-activedescendant), substring match highlighting, a configurable
panel width, a trigger chevron, and a cleaner borderless search row.
All additions are backwards compatible; bumps @cline/ui to
0.2.0-next.6.

* feat(desktop): recommended and free model tiers in the composer picker

The composer's model selector showed raw provider/model ids and listed
the entire catalog alphabetized by id. It now labels providers and
models by display name and, for the cline provider, leads with the
Recommended and Free tiers from the recommended-models feed (NEW/Free
badges, descriptions) ahead of an All models section — matching the
CLI's featured picker and the kanban selector. cline-pass gets
Subscribed/Free tiers. A new list_cline_recommended_models sidecar
command exposes @cline/core's fetchClineRecommendedModels (display-ready
names, bundled offline fallback); feed ids resolve against the catalog
with a unique-slug fallback for Vercel/OpenRouter alias spellings, and
unresolvable entries are dropped rather than rendered unselectable.

* fix(desktop): widen the provider trigger for display names

Provider labels are now display names (e.g. "Cline Usage-Billing"),
which truncated badly at max-w-28.

* chore(desktop): drop unused featured-models test helper

* style(desktop): align workspace/branch picker search rows with the model picker

The composer's workspace/branch popover and the welcome screen's
workspace and branch pickers used a boxed inner search shell that now
clashed with the model picker's borderless search row sitting next to
them. Behavior unchanged.

* feat(ui): center the selected option when SearchCombobox opens

Opening a long list previously scrolled the selection just into view at
the panel edge; it now lands centered, and keyboard/hover navigation
falls back to minimal nearest-edge scrolling.

* style(desktop): picker row contrast, transparent search fields, centered open

The workspace/branch pickers' rows had a nearly invisible
surface-hover-lighter hover; rows now hover with surface-hover and mark
the current entry with the accent background plus check, matching the
model picker. The search inputs drop the Input base class's
dark:bg-input/30 tint that rendered a gray box inside the panel in dark
mode. Opening a picker now centers the current workspace/branch via a
shared scroll helper instead of starting at the top of the list.

* fix(ui): visible option hover/selected states and no scroll-jump on hover

The option row stacked bg-transparent with the conditional state
backgrounds; at equal specificity the later-sorted bg-transparent
utility won, so hover/selected rows rendered with no background at all.
The background classes are now mutually exclusive.

Mouse-driven active-row changes also reused the keyboard scroll-into-
view effect: hovering a row at the panel edge scrolled it into view,
which moved the list under the cursor and re-triggered hover — an
endless jump. Scroll mode is now per-source: center on open, nearest
for keyboard/typing, none for hover.

* fix(desktop): show only subscribed and free tiers in the cline-pass picker

The ClinePass offer is exactly the feed's subscribed + free tiers, but
stale bundled/cached catalog entries (e.g. a nemotron model) leaked
into an "All models" tier. Match the CLI's featured picker: hide
catalog leftovers, and only fall back to the full catalog when the
subscribed bucket is empty so a subscriber is never limited to free
models offline.

* fix(ui/desktop): strengthen the selected-row highlight in light mode

The selected row used the semantic accent surface (violet step 3),
which is nearly white in light mode. SearchCombobox and the desktop
workspace/branch pickers now highlight the selected/current row with
accent step 4 (with a fallback to --accent), which reads clearly in
both themes without touching the shared --accent token that shadcn
hover states depend on.

* fix(desktop): fit full provider display names in the composer trigger

"Cline Usage-Billing" — the default provider — truncated to
"Cline Usage-Bi…" at max-w-36; the trigger now allows up to max-w-56,
which fits the longest built-in provider names.

* style(ui/desktop): animate picker panels open like the shadcn dropdowns

The thinking-effort Select (shadcn/Radix) animates open while the
model/provider/workspace/branch pickers popped in instantly. All picker
panels now share the same open treatment — 150ms fade + slight zoom,
sliding from the trigger side. SearchCombobox uses a self-contained CSS
keyframe (consumers may not ship tw-animate-css); the desktop's custom
panels use the app's tw-animate utilities. Both respect
prefers-reduced-motion.

* chore(desktop): drop stale eslint-disable comments in picker search rows

This repo lints with biome; the jsx-a11y/no-autofocus disables were
inert leftovers. Flagged in review.

* refactor(core/desktop): stamp recommended-feed tiers onto ProviderModel in the SDK

Review feedback on the composer picker: tier joining should live where
the SDK serves model lists so each client doesn't fetch and join the
recommended-models feed itself (the CLI and now the desktop each did).

ProviderModel gains description and featured ({tier, rank, tags});
getLocalProviderModels overlays the feed's recommended/free tiers onto
cline models and subscribed/free onto cline-pass via
applyClineFeaturedModels, matching feed ids through the
Vercel/OpenRouter alias rules. The feed access is a new cached wrapper
(getCachedClineRecommendedModels, 5-minute TTL, in-flight dedupe) —
this path runs on every picker open, and the bundled offline fallback
is cached too so offline users don't re-pay the 5s timeout per list.

The desktop webview now reads tiers straight off the models: the
list_cline_recommended_models sidecar command, the webview feed fetch,
and its unique-slug alias matching are all deleted. toProviderModel
also carries ModelInfo.description generally.

* fix(ui): hand focus back to the combobox trigger on selection, close on Tab

Selecting an option (Enter or click) unmounted the focused search input
without a new focus target, dropping keyboard users' focus to <body> —
only Escape restored it. And since the search input is the panel's only
tabbable element, Tab always moved focus outside the component while
leaving the popup open behind the new focus target.

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

* fix(desktop): keep the composer model selection inside the picker's visible offer

The active/remembered model was validated against the provider's full
catalog while the picker can intentionally hide models (the ClinePass
offer is exactly its subscribed/free tiers), so a stale remembered model
could become the selection while being absent from the dropdown.

Remembered and default selections (including on provider switch) now
resolve against the picker's visible options, and an explicitly
configured model that falls outside the offer stays active but is
surfaced under a 'Current model' section so the selection is always
visible and re-selectable.

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

* feat(core): stamp featured tiers onto the provider catalog synchronously

listLocalProviders deliberately skipped the feed overlay so the catalog
never blocks on the network — but that left the composer's very first
picker open after a cold boot rendering an untiered flat list until the
per-provider fetch landed. Blocking was never required: stamp tiers from
a synchronous peek at data already in memory (the cached live feed when
fresh, else the bundled fallback, whose recommended ids resolve against
the bundled cline catalog). The per-provider model-list path still
refreshes with live feed data moments later.

* fix(core): harden featured-tier matching and the feed cache reset

Review findings on the tier overlay:

Vendor-prefix mismatches now match by unambiguous id slug (two-pass, so
a catalog carrying both spellings of a model stamps one row, and a slug
shared by two feed entries stamps nothing) — the bundled fallback feed's
vendor-prefixed ids can otherwise miss cline-free/-prefixed catalog
entries, leaving them untiered in degraded mode.

resetClineRecommendedModelsCacheForTests now bumps a generation so an
in-flight feed request resolving after a reset cannot repopulate the
cache it just cleared.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 22:10:41 -07:00
Saoud Rizwan 4d1bafc443 feat(desktop/ui): recommended and free model tiers in the composer model selector (#13410)
* feat(ui): sectioned model picker support in SearchCombobox

Adds option sections with headers, badges (NEW/Free pills), keyboard
navigation (arrows/Home/End/Enter with active-row tracking and
aria-activedescendant), substring match highlighting, a configurable
panel width, a trigger chevron, and a cleaner borderless search row.
All additions are backwards compatible; bumps @cline/ui to
0.2.0-next.6.

* feat(desktop): recommended and free model tiers in the composer picker

The composer's model selector showed raw provider/model ids and listed
the entire catalog alphabetized by id. It now labels providers and
models by display name and, for the cline provider, leads with the
Recommended and Free tiers from the recommended-models feed (NEW/Free
badges, descriptions) ahead of an All models section — matching the
CLI's featured picker and the kanban selector. cline-pass gets
Subscribed/Free tiers. A new list_cline_recommended_models sidecar
command exposes @cline/core's fetchClineRecommendedModels (display-ready
names, bundled offline fallback); feed ids resolve against the catalog
with a unique-slug fallback for Vercel/OpenRouter alias spellings, and
unresolvable entries are dropped rather than rendered unselectable.

* fix(desktop): widen the provider trigger for display names

Provider labels are now display names (e.g. "Cline Usage-Billing"),
which truncated badly at max-w-28.

* chore(desktop): drop unused featured-models test helper

* style(desktop): align workspace/branch picker search rows with the model picker

The composer's workspace/branch popover and the welcome screen's
workspace and branch pickers used a boxed inner search shell that now
clashed with the model picker's borderless search row sitting next to
them. Behavior unchanged.

* feat(ui): center the selected option when SearchCombobox opens

Opening a long list previously scrolled the selection just into view at
the panel edge; it now lands centered, and keyboard/hover navigation
falls back to minimal nearest-edge scrolling.

* style(desktop): picker row contrast, transparent search fields, centered open

The workspace/branch pickers' rows had a nearly invisible
surface-hover-lighter hover; rows now hover with surface-hover and mark
the current entry with the accent background plus check, matching the
model picker. The search inputs drop the Input base class's
dark:bg-input/30 tint that rendered a gray box inside the panel in dark
mode. Opening a picker now centers the current workspace/branch via a
shared scroll helper instead of starting at the top of the list.

* fix(ui): visible option hover/selected states and no scroll-jump on hover

The option row stacked bg-transparent with the conditional state
backgrounds; at equal specificity the later-sorted bg-transparent
utility won, so hover/selected rows rendered with no background at all.
The background classes are now mutually exclusive.

Mouse-driven active-row changes also reused the keyboard scroll-into-
view effect: hovering a row at the panel edge scrolled it into view,
which moved the list under the cursor and re-triggered hover — an
endless jump. Scroll mode is now per-source: center on open, nearest
for keyboard/typing, none for hover.

* fix(desktop): show only subscribed and free tiers in the cline-pass picker

The ClinePass offer is exactly the feed's subscribed + free tiers, but
stale bundled/cached catalog entries (e.g. a nemotron model) leaked
into an "All models" tier. Match the CLI's featured picker: hide
catalog leftovers, and only fall back to the full catalog when the
subscribed bucket is empty so a subscriber is never limited to free
models offline.

* fix(ui/desktop): strengthen the selected-row highlight in light mode

The selected row used the semantic accent surface (violet step 3),
which is nearly white in light mode. SearchCombobox and the desktop
workspace/branch pickers now highlight the selected/current row with
accent step 4 (with a fallback to --accent), which reads clearly in
both themes without touching the shared --accent token that shadcn
hover states depend on.

* fix(desktop): fit full provider display names in the composer trigger

"Cline Usage-Billing" — the default provider — truncated to
"Cline Usage-Bi…" at max-w-36; the trigger now allows up to max-w-56,
which fits the longest built-in provider names.

* style(ui/desktop): animate picker panels open like the shadcn dropdowns

The thinking-effort Select (shadcn/Radix) animates open while the
model/provider/workspace/branch pickers popped in instantly. All picker
panels now share the same open treatment — 150ms fade + slight zoom,
sliding from the trigger side. SearchCombobox uses a self-contained CSS
keyframe (consumers may not ship tw-animate-css); the desktop's custom
panels use the app's tw-animate utilities. Both respect
prefers-reduced-motion.

* chore(desktop): drop stale eslint-disable comments in picker search rows

This repo lints with biome; the jsx-a11y/no-autofocus disables were
inert leftovers. Flagged in review.

* fix(ui): hand focus back to the combobox trigger on selection, close on Tab

Selecting an option (Enter or click) unmounted the focused search input
without a new focus target, dropping keyboard users' focus to <body> —
only Escape restored it. And since the search input is the panel's only
tabbable element, Tab always moved focus outside the component while
leaving the popup open behind the new focus target.

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

* fix(desktop): keep the composer model selection inside the picker's visible offer

The active/remembered model was validated against the provider's full
catalog while the picker can intentionally hide models (the ClinePass
offer is exactly its subscribed/free tiers), so a stale remembered model
could become the selection while being absent from the dropdown.

Remembered and default selections (including on provider switch) now
resolve against the picker's visible options, and an explicitly
configured model that falls outside the offer stays active but is
surfaced under a 'Current model' section so the selection is always
visible and re-selectable.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 21:46:07 -07:00
Saoud Rizwan 74a8e06e41 Desktop: unify Plugins, MCP, and Skills into one Plugins hub with a dedicated Marketplace page (#13411)
* Unify desktop plugins, apps, MCP, and skills into one Plugins hub with a Browse directory mode

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

* Open the marketplace directory as a modal over the Plugins hub instead of swapping the page

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

* Rename directory to Marketplace: Browse Marketplace button, Marketplace modal title with icon, search placeholder

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

* Fix search input focus ring clipped by the Marketplace modal scroll container

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

* Address Greptile review: keep selected tag chip visible when its count drops to zero, and remount installed tab when a marketplace install completes after the modal closed

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

* Track marketplace modal mutation flag in a ref so a close click racing a queued render cannot skip the inventory remount

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

* Make Marketplace its own settings page under Customizations and restore Channels as a standalone page

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

* Remove icon from Marketplace page header for consistency with other settings pages

* Notify mounted inventory views when the marketplace invalidates the cache so late install completions refresh the Plugins hub

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 21:42:02 -07:00
Saoud Rizwan 94beb6c5f1 Fix code actions failing with "command not found" on VS Code 1.134 (#13402)
* Fix @ file mentions breaking on paths with spaces

Quote mentions generated by getFileMentionFromPath (Add to Cline /
Fix / Explain / Improve commands) when the relative path contains
spaces, so the mention regex no longer truncates the path at the
first space. Also quote the path part of workspace-prefixed mentions
(workspace:/path with spaces) inserted from the @ context menu, which
previously bypassed quoting because the value does not start with '/'.

Fixes #13338

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

* Fix import ordering in mentions test (biome organize imports)

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

* Reduce fix to minimal scope

Revert the webview quoting refactor and extra tests; keep only the
getFileMentionFromPath quoting fix with a single regression test.

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

* Normalize mention paths to posix separators for Windows

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

* Fix code actions failing with 'command not found' on VS Code 1.134

Code action commands carried arguments (expandedRange, diagnostics),
which routes them through VS Code's CommandsConverter cache. VS Code
1.134 disposes the cached entries before the clicked action executes,
so every lightbulb action failed with 'Actual command not found,
wanted to execute cline.addToChat'.

Drop the arguments so the command id is passed through directly, and
recover the context in the handler instead: getContextForCommand now
expands an empty selection by 3 surrounding lines (matching the old
provider behavior) and gathers document diagnostics intersecting the
range when none are passed explicitly.

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

* Scope gathered diagnostics to the selection/cursor

Match the old CodeActionContext.diagnostics behavior: only include
diagnostics intersecting the range the action was requested for, not
the surrounding lines the text gets expanded to.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 18:36:21 -07:00
Saoud Rizwan 8720363ba3 Fix @ file mentions breaking on paths with spaces (#13391)
* Fix @ file mentions breaking on paths with spaces

Quote mentions generated by getFileMentionFromPath (Add to Cline /
Fix / Explain / Improve commands) when the relative path contains
spaces, so the mention regex no longer truncates the path at the
first space. Also quote the path part of workspace-prefixed mentions
(workspace:/path with spaces) inserted from the @ context menu, which
previously bypassed quoting because the value does not start with '/'.

Fixes #13338

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

* Fix import ordering in mentions test (biome organize imports)

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

* Reduce fix to minimal scope

Revert the webview quoting refactor and extra tests; keep only the
getFileMentionFromPath quoting fix with a single regression test.

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

* Normalize mention paths to posix separators for Windows

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 17:59:16 -07:00
Saoud Rizwan f291a269a6 fix(desktop): don't show "No sessions found" while session history is still loading (#13414)
* fix(desktop): don't show 'No sessions found' while session history is still loading

Replace the isLoadingHistory flag with hasLoadedHistory, set only once the
backend has actually answered a list_discovered_sessions request. The sidebar
and Sessions view now keep their loading state until that first definitive
response, so the empty-state copy can no longer appear while history is still
being fetched (or while a failed fetch is being retried).

Also retry a failed initial fetch on the 2s event cadence instead of stranding
the UI until the 12s periodic poll, which is what stretched the misleading
empty state to ~10 seconds after a webview reload when the websocket lost the
race with the page load.

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

* fix(desktop): stop history fast-retry from re-arming after hook unmount

A failed initial fetch that settles after the hook unmounted could schedule a
new retry timer after cleanup had already cleared the refs, leaving the
abandoned hook polling the backend every 2s. Guard scheduleRefresh with a
disposed ref set by the mount effect's cleanup.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 17:57:49 -07:00
Saoud Rizwan 06013b9c08 fix(desktop): remove settings gear hover state while Account screen is open (#13408)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 17:53:47 -07:00
Saoud Rizwan c14cc2c696 fix(desktop): work summary undercounts wall time when pre-tool thinking attaches to the answer (#13413)
* fix(desktop): anchor work summary duration on the answer row, not attached pre-tool reasoning

The collapsed 'Worked for Xs' row undercounted wall time whenever a turn's
assistant message contained thinking + tool_use with no narration text: the
canonical projection emitted the reasoning-only row after the tool row (both
stamped before the tool executed), the webview attached that row to the final
answer, and collapseCompletedWork used the answer's earliest attached
reasoning timestamp as the end anchor - excluding the entire tool execution
(e.g. 'Worked for 5s' for a turn with an 8s command).

- webview: end the work span at the answer row's own timestamp, clamped to
  the last collapsed row so a fallback answer bubble with a synthetic early
  timestamp cannot shrink the duration either
- sidecar: flush pending thinking before a tool_use row so rehydrated
  transcripts keep the live-stream order (thinking before its tool call) and
  pre-tool reasoning no longer rides on the next answer

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

* fix(desktop): keep interleaved thinking between the tool calls it separates

Address Greptile review: when one assistant message interleaves thinking
between multiple tool_use blocks, each reasoning segment now projects at its
own position (attached to a text row from its own segment when present,
otherwise as its own row) instead of merging into the first reasoning row,
which displayed later thinking before a tool call it actually followed.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 17:52:02 -07:00
Saoud Rizwan 0a9f45a9c6 fix(ui): stack code block lines when streamdown lineNumbers is off (#13412)
streamdown renders each Shiki token line as a bare inline span with no
newline text between non-empty lines, and only applies its block line
class when lineNumbers is on. With lineNumbers off (the desktop app's
config) every multi-line fenced block collapsed into one run-on line.
Make the direct line spans under code-block-body display: block in the
shared markdown.css; empty lines keep their height via their lone "\n"
child under white-space: pre.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 17:45:41 -07:00
Saoud Rizwan 4a63821d57 fix(desktop): treat ClinePass as OAuth-managed in the chat credential gate (#13404)
* fix(desktop): treat ClinePass as OAuth-managed in chat credential gate

ClinePass shares the Cline account OAuth credentials (its auth handler
stores under the "cline" provider), so the webview never sees a plain
API key for it. The chat pre-flight check only exempted cline/oca/
openai-codex, so switching to ClinePass while signed in via OAuth
blocked with "Missing API key" even though the sidecar resolves the
stored access token fine (which is why the CLI worked).

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

* style: format helpers.test.ts with biome

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 16:50:39 -07:00
Bee ff14ab601f feat: allow agents to create scheduled tasks (#13331)
* feat(core, desktop): add durable todo agenda

* fix(desktop): secure todo approvals and track tool usage

* fix(desktop): clean up failed approval delivery

* fix(desktop): authenticate approval connections

* fix(desktop): cancel approvals on broadcast failure

* fix(desktop): authenticate development approvals

* fix(desktop): harden development approvals

* test(core): make task paths cross-platform

* fix(desktop): serialize approval readiness

* refactor(core): unify todo and schedule tools

* feat(core): distinguish user todos from agent suggestions

* fix(core): hide tasks tool in yolo mode

* fix(core): enforce schedule workspace scope

* fix(core): bind schedule scope to hub connection

* fix(core): establish task scope at hub startup

* fix(core): scope task automation by workspace

* test(core): normalize workspace path expectations

* test(core): serialize Windows CI workers

* fix(core): reject unregistered schedule authority

* fix(desktop): guard task execution commands

* fix(core): avoid polynomial regex in mention parsing

* fix(core): address schedule tool review feedback

* fix(core): bind websocket clients to hub workspace

* fix(core): flatten tasks tool input schema

* fix(core): authorize multi-workspace hub clients

* test(core): type hub transport authority mock

* fix(cli): register a workspace client for remote schedule commands (#13398)

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-19 16:45:19 -07:00
Mikołaj Kondratek a8841bf96c fix(llms): surface provider-executed tool activity as observational events (#13300)
* fix(llms): surface provider-executed tool activity as observational events

Provider-executed tool parts (e.g. every tool the Claude Code CLI runs
inside its own session) were dropped by the model-tool guard added for
web search: only declared model tools were re-emitted, everything else
hit continue with nothing yielded. Those sessions modified the workspace
with no tool activity in runtime events, transcripts, or the UI.

Route all providerExecuted parts onto the observational path instead:
emit execution-tagged tool-call-delta and tool-result events, matched by
tool-call ID for providers that omit the flag on the result half. They
stay out of AgentRuntime's execution/approval loop, and the runtime
already persists them as modelToolActivities and projects them for
display.

The AgentModelEvent tool-result variant widens toolName from
ModelToolName to string to carry the provider's own tool names.

* fix(agents): keep turns that are only provider-executed tool activity

A turn consisting solely of observational tool activity has an empty
assistant content array - the activity lives in message metadata, since
projecting it into content would replay tool_use blocks the model never
gets results for. The empty-content guard threw on such turns, erroring
the run and losing the activity from the transcript. Count model-tool
activity as content for the emptiness check (error finishes still
throw); replay stays safe through the codec's empty-content placeholder.
Also drop the trailing text delta from one gateway test so the tool-only
stream shape stays covered end to end.
2026-08-20 00:46:09 +02:00
Saoud Rizwan 878faf0a95 Rename desktop app from "Cline Code" to "Cline" (#13401)
* Rename desktop app from Cline Code to Cline

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

* Format touched Rust test assertions

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-19 15:29:00 -07:00
Saoud Rizwan 36397f47eb ci: tidy workflow cache config and job permissions (#13403)
Publish workflows now always do clean npm installs (no dependency
cache in their test gates), the e2e workflow's cache keys are
exact-match only, and the e2e job drops an id-token permission it
never used.
2026-08-19 14:31:41 -07:00
Saoud Rizwan 3f0c5cdc92 ci: stop over-long changelogs from silently dropping release Slack posts (#12955)
Slack section blocks reject text longer than 3000 characters. The Slack
action logs that rejection as ##[error] but does not fail the step, so an
over-long changelog drops the release announcement while the run stays
green — cline@3.0.50 (3272 chars) published to npm, tagged, and cut a
GitHub release with no Slack post and nothing red to notice.

Every publish workflow pasted the changelog section verbatim into one
section block, so all six were exposed; the SDK, desktop, and extension
sections were only 150-350 chars under the ceiling.

Add a slack_content output alongside content: unchanged when the section
fits, otherwise trimmed on a line boundary with a link to the full
release notes. Only the Slack payload uses it — GitHub release bodies and
the desktop updater manifest still get the whole section.
2026-08-19 13:34:40 -07:00
Saoud Rizwan d9bb22883d fix(shared): run PowerShell commands with fail-fast error semantics (#13358)
* fix(shared): run PowerShell commands with fail-fast error semantics

The run_commands PowerShell wrapper never set $ErrorActionPreference, so
the default 'Continue' applied: a pipeline erroring per item (e.g. a
malformed Where-Object over Get-ChildItem -Recurse) emitted one error
record per enumerated file - tens of thousands of stderr records on
large trees, looking like a hang - and could still resolve as SUCCESS
with exit 0.

Prepend $ErrorActionPreference='Stop'; to the script content executed
by the ScriptBlock so the first error terminates the command with a
non-zero exit and a single error message. Concatenated on the same line
as the user command so error line numbers stay unshifted.

Fixes #13285

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

* fix(shared): set the fail-fast preference in the bootstrap scope

Setting $ErrorActionPreference='Stop' by string-prepending it into the
scriptblock source displaced a leading param(...) from its mandatory
first-statement position, so scripts beginning with a param block failed
with CommandNotFoundException. Preference variables are dynamically
scoped, so setting Stop in the -Command bootstrap gives the invoked
scriptblock identical fail-fast semantics while keeping the user script
byte-identical (param works, error positions unshifted) and drops the
doubled-quote escaping.

* docs(shared): document the fail-fast tradeoffs in the PowerShell wrapper

Stop promotes every non-terminating error, not only per-item pipeline
floods: partial-result commands (recursive listings over access-denied
junctions) now stop at their first error, and Windows PowerShell 5.1
turns in-script stderr redirection of succeeding native commands fatal.
State this in the wrapper comment as a deliberate tradeoff, with the
GitHub Actions precedent and the per-command opt-outs.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
Co-authored-by: Mikołaj Kondratek <19799111+mkondratek@users.noreply.github.com>
2026-08-19 12:11:41 -07:00
Ara 398c1a1b8f fix(llms): display billed gateway cost (#13385) 2026-08-19 21:03:32 +02:00
Renee Huang 8a64372b54 docs: show DeepSeek V4 peak and off-peak pricing (#13312)
* docs: update DeepSeek V4 average pricing

* docs: show DeepSeek peak and off-peak pricing

* docs: add GLM-5.3 reference pricing (same as GLM-5.2)

* docs: add GLM-5.3 to ClinePass models table
2026-08-19 11:14:22 -07:00
Bee dfa34ecea8 fix(desktop): strip user_input envelope when copying a user message (#13369)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Bee <abeatrix@users.noreply.github.com>
2026-08-19 01:11:42 -07:00
Bee 98d3e52a02 fix(clients): filter non-chat models from chat pickers (#13317)
* fix(clients): filter non-chat models from chat pickers

* fix(clients): align chat model eligibility
2026-08-18 23:42:08 -07:00
Saoud Rizwan f80e6a5df8 chore(desktop): release v0.0.14 2026-08-18 23:02:41 -07:00
Saoud Rizwan 9cf60cd43a fix(desktop): finalize queued turns on chat_done with canonical history reconcile (#13330)
Turns that settle through the event stream (queued prompts, including the
first prompt of a fresh session) resolve their send() RPC early, so nothing
cleared the streaming shimmer or reconciled live-streamed content against
the persisted transcript at turn end. A turn whose deltas were incomplete
stayed visually streaming forever and only healed when a later non-queued
send rehydrated history.

chat_done (and chat_session_ended / the queue-drain double check) now clears
the active assistant streaming id and schedules a short-delayed
read_session_messages + applyCanonicalHistory, guarded by turn epoch,
session id, and in-flight send submissions so it never clobbers a newer
turn or duplicates the blocking send path's own finalization.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 22:44:55 -07:00
Bee 2fd8d0383a fix(desktop): align system prompt with session mode (#13361)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-18 22:40:41 -07:00
Saoud Rizwan 411282296c Use fixed selection chevron in account dialog to match other dialogs (#13364)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 22:23:54 -07:00
Saoud Rizwan 3705aec28f fix: skill slash commands load via the skills tool instead of expanding into the user message (#13327)
* fix(desktop): show typed slash command instead of expanded skill markdown

The sidecar expands /skill and /workflow tokens into their instructions
before dispatching, so the runtime's persisted transcript only contains the
expanded text. After a turn (and when reopening a session) the webview
re-hydrates from that history and rendered the whole SKILL.md body as the
user's message; queue events echoing the expanded prompt could also add a
second user bubble, and fresh sessions were titled with the markdown's first
line. The CLI never shows this because its TUI keeps the typed text in its
own transcript and only sends the expanded prompt to the model.

Mirror that separation inside the desktop sidecar's display boundaries:

- history projection (readSessionMessages) inverts user text that starts
  with a configured command's instructions back to '/name remainder',
  which also repairs sessions recorded before this fix
- queue snapshots and chat_queued_prompt_start events echo the typed
  prompt recorded at expansion time, so the webview's optimistic-bubble
  re-key matches again
- an untitled session sent an expanded prompt gets titled from the typed
  command instead of the instructions' first line

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

* fix(desktop): don't overwrite a mid-turn rename with the typed-command title

The untitled check ran before dispatch, so renaming a fresh slash-command
session while its first turn was running got clobbered by the post-turn
typed-command title. Re-check at write time and only replace a missing title
or the one the runtime auto-derived from the expanded prompt.

Also documents the inherent prefix-inversion ambiguity flagged in review:
text hand-typed with a command's exact instructions persists byte-identically
to that command's expansion, so stored history alone cannot distinguish them.

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

* fix(desktop): stop expanding skill commands; let the skills tool load them

Pasting the skill body into the prompt is why the transcript could ever show
it: the desktop webview re-hydrates from the runtime's persisted history, so
whatever the sidecar splices into the user message renders as if the user
typed it. The runtime already registers the skills tool, whose description
requires the model to invoke it whenever the user references a slash command
— so send the typed /skill text through and let the tool deliver the
instructions as a tool result (previously they arrived twice: pasted and via
the tool). The persisted user message, session title, and queue entries are
then simply the typed command, which deletes the typed-prompt registry, the
queue event/snapshot rewriting, and the title machinery from the previous
approach.

Workflows are not served by the skills tool and keep textual expansion, so
the read-time display inverter stays: it collapses expanded workflow prompts
— and skill prompts persisted before this change — back to the typed
/command in the history projection.

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

* feat(core): option to keep skill slash commands typed for the skills tool

resolveRuntimeSlashCommandFromWatcher (and the hub snapshot proxy) accept
expandSkillCommands: hosts whose sessions register the skills tool pass
false so the typed /skill goes through and the model loads the instructions
as a tool result, keeping the persisted transcript as what the user typed.
Workflows always expand — the tool does not serve them. isSkillsToolAvailable
exposes the catalog check hosts use to decide (yolo preset and the skills
tool toggle leave textual expansion as the only delivery path).

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

* fix(cli): skill slash commands load via the skills tool instead of expanding

The TUI user-command wrap and buildUserInputMessage now keep a typed /skill
as-is when the session's mode/toggles register the skills tool, matching the
desktop app; workflows keep expanding, and yolo (zen) keeps expanding skills
because its preset has no skills tool. This also fixes CLI resume/history
surfaces showing the skill body: the persisted user message is now the typed
command.

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

* fix(vscode): keep configured skill slash commands typed for the skills tool

expandSlashCommands no longer splices a configured skill's instructions into
the model text; the SDK session's skills tool delivers them as a tool result
(previously they arrived twice). Builtin pseudo-skills like /deep-planning
are not served by that tool and keep expanding, as do workflows.

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

* refactor(desktop): use the shared skill-expansion option in the sidecar

Replaces the sidecar's workflow-detection dance with core's
expandSkillCommands option and gates on isSkillsToolAvailable, restoring
textual expansion where the tool is missing (yolo mode or the skills tool
toggle) — a gap in the previous desktop-only change.

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

* refactor(desktop): drop the display inverter for expanded transcripts

Accepted trade-off to keep the change minimal: sessions recorded before
skills switched to the skills tool, workflow sends (deprecated), and
yolo-mode skill sends persist expanded instructions and now render that text
as-is instead of being collapsed back to the typed /command at projection
time.

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 22:22:36 -07:00
Saoud Rizwan 67e5115b85 fix(cli): make TUI dialog colors follow theme changes live (#13355)
* fix(cli): make TUI dialog colors follow theme changes live

Dialog content previously read the static palette constant, so open
dialogs (including the theme picker itself) kept the default dark-blue
accents while scrolling through theme previews. Add getDialogPalette /
useDialogPalette, which resolve dialog colors from the active theme's
dialog accents and re-render on every theme change, and migrate all
dialog-rendered components to it.

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

* feat(cli): derive dialog panel background from the active theme

Dark themes now lift their own background one OKLAB step for the dialog
surface, so panels keep the theme's hue instead of the library's fixed
#262626. DialogThemeSync pushes the surface into the dialog container
for new dialogs and repaints open panels, so the surface also follows
live theme previews. Light themes keep the neutral dark panel to match
the dark accent fallback and the light-on-dark dialog text.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 22:16:26 -07:00
Bee 61b95a62ee feat(desktop): stream run command output (#13179)
* feat(desktop): stream run command output

* fix(sdk): clean up detached command logs

* fix(sdk): reap detached logs after hub restarts

* fix(sdk): preserve live detached command logs

* fix(desktop): harden live command progress

* fix(sdk): recover detached logs for local hosts

* fix(desktop): reconcile command output tool rows

* fix(sdk): retain logs for surviving commands

* fix(core): prevent PID reuse from retaining detached logs

* fix(core): preserve detached logs on probe failures

* fix(core): retain detached logs during probe outages

* fix(desktop): resolve leftover merge conflict in messages projection test

Combine both sides of the assertion: main's incremented per-block
createdAt projection and this branch's toolCallId/hookEventName meta.

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 21:10:18 -07:00
Saoud Rizwan 6cc0328424 docs: add GLM-5.3 to ClinePass models and reference pricing (#13357)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 20:25:00 -07:00
Saoud Rizwan 90b32cb41d fix: normalize Gemini custom base URLs for legacy host-root values (#13329)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 20:21:51 -07:00
Saoud Rizwan 3c433d5a90 fix: run_commands object form without args routes through the shell instead of failing with ENOENT (#13336)
* fix: run_commands object form without args routes through the shell

The structured { command, args? } form of run_commands was always spawned
directly with shell: false. When a model emitted a full command line in
command with no args (e.g. { command: "echo hello" }), spawn failed with
ENOENT for any command containing a space, breaking command execution for
the whole session.

Direct exec now only applies when a non-empty args list is provided; the
object form without args is routed through getShellInvocation like the
string form. Schema descriptions are tightened so models put arguments in
args instead of embedding them in command.

Fixes #13279

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

* chore: trim structured-command schema descriptions

The union schema is only used for lenient validation of input the model
already sent; its descriptions never reach a model prompt. Keep them
short instead of restating executor behavior.

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

* chore: simplify direct-exec comment in shell executor

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

* revert: keep original structured-command schema description

The description never reaches a model prompt and the executor now handles
both shapes, so the wording change was cosmetic noise.

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

* fix: gate direct exec on args key presence, not array length

Review feedback: an explicit empty args array is intentionally structured
input and stays direct exec; only an object with no args key is treated
as a full shell command line. Matches the key-presence rule already used
by the VS Code host's formatCommandForTerminal. Also replaces the
empty-args shell test (which was PowerShell-incompatible) with a test
pinning the direct-exec contract.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 19:52:52 -07:00
Saoud Rizwan 76ac1c7f55 ci(ui-publish): build @cline/shared before ui typecheck (#13354)
@cline/ui's generated-media imports @cline/shared/browser, which resolves to
shared's dist output. The build-shared step sat after typecheck/test/build,
so the first ui-publish dispatch since #13025 failed at Typecheck UI with
TS2307. Move the step to right after install.
2026-08-18 18:01:10 -07:00
Saoud Rizwan be56c505e4 feat(ui): share the markdown pipeline, chat polish, and ThinkingBlock across products (#13323)
* feat(ui): share the markdown pipeline, chat polish CSS, and ThinkingBlock

The desktop app and the cloud dashboard both consume @cline/ui yet rendered
assistant output differently, because Markdown policy and the thinking-trace
row lived app-side. This moves the shareable parts into the package:

- components/markdown (new export): the lazy Shiki code highlighter (GitHub
  light/dark, pinned language set) and agentMarkdownControls — the standard
  Streamdown configuration. streamdown/shiki/@shikijs/* become optional peer
  dependencies, mirroring @pierre/diffs.
- components/markdown.css: the desktop's chat polish moves in — chat-scale
  headings, outside list markers, single quiet code blocks with a
  hover-revealed copy control, table cards. Kept unlayered so it beats
  Streamdown's layered Tailwind utilities without !important.
- ThinkingBlock + formatThoughtLabel in agent-chat: the standard thinking
  row (brain icon, Thinking/Thought-for-Ns label, streaming shimmer, rail
  presentation, capped scrollable body). The shimmer and the
  reasoning-hover-suppression rule move into agent-chat.css; triggers gain
  the color transition the desktop applied locally.

Version bumps to 0.2.0-next.5 for the dashboard to pick up.

* refactor(desktop): consume shared markdown and thinking primitives from @cline/ui

The local Shiki highlighter, Streamdown controls, chat markdown polish CSS,
streaming-title shimmer, and reasoning hover-suppression rule are deleted in
favor of the @cline/ui versions (the highlighter test moves to the package's
suite). ReasoningBlock becomes a thin wrapper that hands MemoizedMarkdown to
the shared ThinkingBlock, and formatThoughtLabel re-exports from the package
so grouping code and tests keep their import path.

globals.css now imports @cline/ui/components/markdown.css (unlayered, so the
polish keeps beating Streamdown's layered utilities); the app keeps only what
is genuinely app-specific: link/image policy in markdown.tsx, selectability
rules, accent palettes, and the view-enter transition.

* style(ui/desktop): make thinking-trace prose legible

Thinking body text rendered too faint: plain muted-foreground plus the
desktop's font-thin weight. The shared thinking content now leans 75% of the
way back toward the body text color (still slightly de-emphasized), and the
desktop drops the thin font weight.
2026-08-18 17:52:17 -07:00
Saoud Rizwan 3f9c9c3f33 feat(ui/desktop): collapse finished runs into a work summary and remove hover-state dead space (#13315)
* feat(ui): add WorkActivity collapsed-run summary and float message actions as a pill

WorkActivity/WorkActivityTrigger/WorkActivityContent fold a finished agent
run's working rows (tool calls, thinking traces, narration) behind a single
"Worked for 4m 12s · 14 tool calls" disclosure built on the shared animated
disclosure primitives, with formatWorkActivityLabel/formatWorkDuration
exported for consumers.

Message hover actions no longer rely on the transcript reserving blank space
below each message: the action row is now a self-backed pill (border,
blurred background, shadow) that floats over whatever follows, so
conversations can pack rows tightly without hover chrome colliding with the
next message.

* feat(desktop): collapse finished runs into a work summary and tighten chat spacing

collapseCompletedWork post-processes the grouped transcript: once a run ends
on assistant text with no further tool calls, its working rows fold into one
expandable WorkActivity row while the final answer stays visible. Runs are
delimited by user messages; the trailing run only collapses when the session
has stopped running and actually produced an answer, so live streams and
cancelled/failed tails keep their rows. Assistant messages carrying images
or media are treated as deliverables and never collapse.

The conversation list gap drops from gap-8 to gap-4 now that hover actions
are self-backed pills that need no reserved space, and user messages add
their own top margin so turn boundaries stay visually distinct.

* refactor(ui/desktop): work summary label wording, flat expansion, stable in-run rhythm

Feedback round on #13315:

- Label reads "Worked for 4m 12s and made 14 tool calls" instead of joining
  with a dot; without a duration it falls back to "Made N tool calls".
- Expanded work rows render at transcript level — no rail or extra indent —
  since tool rows and thinking traces already carry their own nesting when
  expanded. The work content keeps the tight working-row rhythm.
- Live working rows (thinking traces + tool calls) now group into a 'run'
  render item with the same tight 0.25rem rhythm, so there is no oversized
  gap under a "Thought for Ns" row and every row keeps its exact position
  when the finished run folds into the work summary. A trailing
  answer-in-progress stays outside the group at transcript level, and pure
  prose spans keep normal spacing.
- The transient "Thinking..." indicator moves inside the transcript column
  and mirrors a trigger row's geometry, so the first real row replaces it in
  place with no jump.

* style(ui/desktop): hover-pill metrics, right-pointing work chevron, scroll and spacing fixes

Another feedback round on #13315:

- Hover action pill: +2px internal padding, a trailing inset after the
  timestamp (it sat flush against the pill border), and more clearance
  between the message content and the pill (2px -> 6px; the hover bridge
  grows to match).
- The work summary chevron points right while collapsed and continues
  counterclockwise to point up when expanded.
- Conversation bottom padding drops pb-20 -> pb-8: the composer sits below
  the scroller, so the padding only needs to clear a pinned action pill.
- Sending a message scrolls back to the bottom even if the reader had
  scrolled up (new AutoScrollOnSend on the user-message count, which ignores
  optimistic-bubble re-keying; @cline/ui now exports useConversation for
  this).
- An assistant answer directly under its run's working rows pulls itself
  0.5rem closer than the full transcript gap.

* style(desktop): leave a visible gap between a pinned action pill and the composer

pb-8 exactly matched the pill's ~40px footprint, so the last row's hover
actions sat flush against the composer top; pb-12 restores ~8px of daylight.

* style(desktop): widen the gap between the pinned action pill and the composer to ~24px

pb-12 left only ~8px of daylight under the pill; pb-16 reads comfortable
without reverting to pb-20's dead space.

* fix(desktop): keep the thinking indicator at the working-row offset mid-run

The indicator matched a trigger row's geometry but sat a full transcript gap
(1rem) below the last working row, while the tool/thinking row replacing it
joins the tight run group at 0.25rem — a visible upward jump. When the last
transcript item is working rows (or streamed assistant output), the
indicator now pulls up to the same tight offset; only at the start of a run,
under the user message, does it keep the normal gap.

* style(ui): calm the hover actions surface per team feedback

Borderless rectangle instead of the bordered pill: radius drops to
var(--radius), the side padding goes entirely (the icon buttons carry their
own hit areas), and the vertical padding halves. Blurred background and
shadow stay so it remains legible over following content.

* feat(ui/desktop): full-band hover reveal and iOS-style disclosure easing

The hover actions only appeared while the pointer was inside the message
box itself. The invisible bridge under each message now spans the full
height of the band the floating actions occupy (full row width), so
hovering anywhere in that strip reveals them. Sibling row types
(.cline-chat-tool, .cline-chat-work, and the desktop's run/tool groups)
become position: relative so they paint above the bridge — their own
content keeps its hover and clicks, and the bridge only wins in the band's
genuinely empty space.

All expandable rows (work summary, tool panels, thinking) open and close on
a 240ms symmetric ease-in-out cubic-bezier instead of the 60ms snap, with
chevron rotation on the same curve. Reduced-motion still disables both.

* revert(ui/desktop): drop the full-band hover reveal; quicken disclosure easing to 180ms

The full-band hover bridge (and the position: relative changes that made it
safe) is reverted per feedback — back to the narrow bridge that only spans
the gap under the message. The iOS-style ease-in-out on disclosures stays
but speeds up from 240ms to 180ms.

* fix(ui): recover live tool diffs that mount as a blank pierre skeleton

Live-streamed edit rows could show an empty diff for the whole run, with the
diff only appearing after the collapsed work row was expanded (fresh mount).
Root cause, confirmed by driving a live session and inspecting the element:
React StrictMode double-invokes @pierre/diffs' ref callback; the first
instance's async highlight work aborts on its immediate cleanup, and the
second instance adopts the abandoned half-rendered shadow tree as if it were
complete prerendered output — zero height, no code, no theme stylesheet,
permanently. A rendered diff always carries style[data-theme-css] in its
shadow root, so ToolFileDiff now checks for it shortly after mount and
remounts FileDiff (bounded attempts) when missing; the fresh host element
takes the normal render path and recovers within ~400ms. Verified live: the
diff now renders during the run.

* fix(desktop): keep interrupted runs expanded even with partial trailing text

The trailing-run collapse gated on 'ended with assistant text', which
misread a Stop that landed mid-answer as a finished run and folded the tool
calls the user wants to inspect. The gate is now the terminal status itself:
only completed (or restored-idle) sessions collapse the trailing run;
cancelled/failed/error tails keep their rows regardless of partial text.
(Greptile P1 on #13315 — matches the PR's stated rule.)
2026-08-18 17:46:57 -07:00
Saoud Rizwan cf07572a07 feat(desktop): show provider web-search support under the settings toggle (#13328)
* feat(desktop): show provider web-search support under the settings toggle

The global Web search toggle silently does nothing unless the session's
provider offers native web search, which made the setting read as if it
worked with any provider. The desktop General settings row now explains
that only providers with built-in web search honor it, and shows a live
status line: which connected providers are ready to use it (no extra
setup needed), or an amber warning with a link to the Models section
when none of them support it.

Support is resolved in the webview via a new providerOffersModelTool
helper in @cline/llms (browser export), sharing the same builtin-manifest
source of truth as the runtime's supportsModelTool attachment check.

* fix(desktop): address review — refetch web-search status on catalog invalidation, clarify per-model support

Greptile P2: the one-time catalog fetch could race an in-flight provider
save and show stale status; the row now refetches when the provider
catalog cache is invalidated (fired after saves complete).

Greptile P1: the ready line implied every model on the provider works;
Vertex excludes Claude routes, so the copy now scopes the promise to
models that support it.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-18 17:20:55 -07:00
Mikołaj Kondratek a5ac26f279 fix(vscode): clear task-scoped settings overlay when task view is cleared or switched (#13310)
* fix(vscode): clear task-scoped settings overlay when task view is cleared or switched

Toggling an auto-approve setting while a task is open writes
autoApprovalSettings into the StateManager's task-settings overlay
(updateAutoApprovalSettings -> setTaskSettings). The SDK controller never
cleared that overlay on clearTask/showTaskWithId (the legacy controller
did), so after New Task the stale overlay kept shadowing global settings
in getGlobalSettingsKey(): toggle RPCs were accepted into global state,
but every posted state still carried the overlay's old version, which the
webview rejects as not newer - the auto-approve checkboxes froze forever.

Restore legacy parity in SdkTaskControlCoordinator: drop the overlay
(persisting pending writes first) in clearTask() and before installing a
different task's proxy in showTaskWithId().

Fixes #13260

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

* changeset

* test(vscode): add end-to-end regression test for auto-approve freeze after New Task

Wires the real StateManager, the real updateAutoApprovalSettings handler,
and the real SdkTaskControlCoordinator.clearTask() together with the
webview's version gate modeled on ExtensionStateContext, pinning the
end-to-end invariant behind #13260: checkbox toggles must keep reaching
the webview after a mid-task toggle followed by New Task. Verified the
test fails when the clearTaskSettings() call is removed from clearTask().

* fix implicit any in regression test

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-18 16:54:59 -07:00
Bee 508a5322af feat(desktop): native notifications (#13166)
* feat(desktop): native notifications

* macos target

* fix(desktop): isolate macOS dev app identity

* fix(desktop): address notification review feedback

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-18 16:46:25 -07:00
Max 38f8260bc3 fix(vscode): SDK remote-config parity — refresh coordination, session gating, and fail-closed opt-out (#13226) 2026-08-18 16:17:24 -07:00
Saoud Rizwan eeaed357ef fix(ci): lock the legacy publish workflow to the legacy-extension branch (#13350)
The branch dispatch input was a free-form string with no validation. Both
jobs checked it out and ran full npm lifecycle scripts from it: the publish
job next to VSCE_PAT/OVSX_PAT (and npm run publish:marketplace executes a
script from that same ref with the PATs in env), and the test job with NO
environment approval at all while inheriting the workflow-level
contents/packages/checks/pull-requests write grants. A dispatch pointing at
e.g. refs/pull/N/head would run outside-contributor code with the
marketplace keys behind one approval, or with a repo-write token behind
none.

Remove the input and hardcode the protected legacy-extension branch, drop
the workflow-level permissions to contents: read, and elevate only the
publish job to contents: write (tag push + GitHub release). The branch
input's default was legacy-extension, so normal publishes are unchanged.
publish-extension skill dispatch command updated to match.
2026-08-18 16:12:04 -07:00
Saoud Rizwan bca9b64206 fix(ci): always build the legacy bundle from the legacy-extension branch (#13349)
The combined-VSIX workflow took legacy-ref as a free-form dispatch input
with no publish-time validation (next-ref has one: publish requires main).
Any typed ref — a PR merge ref, an unprotected branch — would be built
into the published VSIX by the environment-less build job, and the publish
environment approver only ever sees an opaque prebuilt artifact, so the
approval protected the marketplace PAT but not the shipped bytes.

Remove the input entirely and hardcode the protected legacy-extension
branch, which makes that branch's protection rules load-bearing for
releases. The tested-sha pinning between test-legacy and build is
unchanged. publish-extension skill dispatch command updated to match.
2026-08-18 16:00:35 -07:00
Mikołaj Kondratek 8a038022a4 fix(vscode): point provider signup URLs at their API key pages (#13337)
* fix(vscode): point Mistral signup URL at the general API keys console

The Mistral provider's signup link led to the Codestral console, which
issues Codestral-scoped keys that fail with 401 on api.mistral.ai — the
endpoint the provider actually calls. Point it at the general API keys
page instead.

Fixes #13288

* fix(vscode): deep-link DeepSeek and Fireworks signup URLs to their API key pages

Both pointed at marketing homepages; link straight to the key-creation
pages instead, matching the rest of the registry and the desktop app's
provider-key-urls map.
2026-08-18 16:53:54 +02:00
JasmineLCY c2e293e293 fix(vscode): preserve LiteLLM input token limits (#13293)
* fix(vscode): preserve LiteLLM input token limits

* fix(vscode): prefer live LiteLLM model metadata

* fix(vscode): generalize private catalog metadata

* test(vscode): preserve llms exports in vscode lm mock
2026-08-18 12:00:33 +02:00
Saoud Rizwan b9efa96826 fix(vscode): continue the surviving session on resume instead of rebuilding with the original task text (#13175)
* fix(vscode): stop resubmitting the original task text on bare resume (#12975)

A bare Resume after Stop rebuilt the session from task history and
injected historyItem.task into the resumption prompt as 'New
instructions from the user'. The model treated the already-completed
original request as fresh instructions and re-executed it (e.g. re-ran
all terminal commands after stopping a queued follow-up turn).

The preserved conversation history is the source of truth on resume, so
the fallback prompt now just asks the model to reassess the history and
continue, matching the legacy resume prompt which also never resent the
original task. User-typed text still takes precedence when provided.

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

* fix(vscode): continue the surviving idle session on follow-ups instead of rebuilding

Stopping a turn keeps the session alive, but every idle follow-up (bare
Resume after Stop, and typed follow-ups after a completed turn) tore
that session down and rebuilt it from persisted task history before
sending. Continue the matching idle session in place instead, the same
way the CLI reuses the live session after an abort. Rebuilding from
history now only happens when no live session matches the displayed
task (task opened from history, extension host reload).

A bare resume still needs a prompt to start a turn, so it sends the
neutral [TASK RESUMPTION] prompt (shared with the rebuild fallback and
hidden from the transcript); user-typed content is echoed and sent
as-is. If the send lands while the abort is still settling, the runtime
auto-queues it and drains once the abort completes.

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

* refactor(vscode): consolidate follow-up send paths in SdkFollowupCoordinator

Now that idle follow-ups continue the live session in place, the
two-mode sendToActiveSession helper was redundant: its non-queued branch
duplicated continueIdleSession minus the bare-resume prompt. Split it
into a single-purpose queueToActiveSession and fold the idle no-task
send into continueIdleSession, flattening askResponse's decision tree
to: queue onto a running turn, continue a matching live idle session,
rebuild from history, or abandon.

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

* refactor(vscode): reuse the existing neutral resumption prompt for bare resumes

Drop the newly invented long resumption wording in favor of the phrase
that already existed as the no-history fallback and that the transcript
hiding logic and test fixtures recognize: '[TASK RESUMPTION] Please
continue where you left off.' The net change to resumeSessionFromTask
against main is now just deleting the branch that resubmitted
historyItem.task as new instructions.

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

* fix(vscode): stop resubmitting the original task text on bare resume (#12975)

A bare Resume after Stop rebuilds the session from task history and
injected historyItem.task into the resumption prompt as 'New
instructions from the user'. The model treated the already-completed
original request as fresh instructions and re-executed it (e.g. re-ran
all terminal commands after stopping a queued follow-up turn).

Bare resumes now always use the neutral prompt that already existed as
the no-history fallback; user-typed text still takes precedence. This
matches the legacy resume prompt (responses.taskResumption), which only
ever included user-supplied text as new instructions.

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

* fix(vscode): hide synthetic prompts from the queued-prompt echo

A send that races a settling abort is auto-queued by the runtime, so a
bare Resume can reach the pending_prompt_submitted echo carrying the
synthetic [TASK RESUMPTION] prompt. Echoing it leaked model-facing text
as a visible user bubble and shifted the visible-user-message ordinals
that edit/regenerate mapping relies on. Filter synthetic prompts with
isSyntheticUserPrompt, keeping user attachments visible (matching
isSyntheticSdkUserMessage semantics).

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-17 19:10:59 -07:00
Saoud Rizwan d4b415f8ab fix(desktop): trim the persisted transcript on checkpoint restore (#13259)
A restore that reuses the source session id rolled the workspace back but
left the persisted transcript describing the discarded turns, so the chat
kept showing turns whose file changes had just been reverted.

Before #13075 the restore reply carried the trimmed messages and the
webview rendered them directly. Now the webview always re-reads through
read_session_messages, which prefers the persisted file over the live
session, so the trimmed history the sidecar puts on the live session is
never read. Persist it as well.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-17 18:03:52 -07:00
Bee 6b3f034bce fix(desktop): align usage table columns CLINE-2996 (#13325)
* fix(desktop): align usage table columns

* fix(desktop): show usage link for empty history
2026-08-17 17:30:08 -07:00
Saoud Rizwan 05a6974ef8 feat(desktop): surface beta channel identity in-app (#13322)
Beta builds (prerelease versions from desktop-experimental, shipped as
'Cline Code Beta') now identify themselves everywhere users look: a Beta
pill in the sidebar footer, the product name in the sidebar hover card,
an About row in Settings > General with version + channel, the runtime
window title, and the tray menu/tooltip (via package_info, which carries
the overlay's productName).

Channel detection is a pure version-string check (-beta suffix) in the
new webview/lib/app-channel.ts — the version is baked into package.json
at build time and reported by the sidecar's get_process_context, so it
works in both the Tauri shell and web dev mode with no new plumbing.
Stable builds render no channel UI at all.
2026-08-17 17:24:22 -07:00
Saoud Rizwan 5ad2dd5fc8 feat(desktop): beta release channel from desktop-experimental branch (#13321)
* feat(desktop): add beta release channel from desktop-experimental branch

Adds a 'channel' input (stable|beta) to desktop-publish.yml. Beta releases
are tagged desktop-vX.Y.Z-beta.N on the desktop-experimental branch, built
with the tauri.beta.conf.json overlay (Cline Code Beta / bot.cline.app.beta,
side-by-side install with stable), published as prerelease GitHub releases,
and served by a separate rolling desktop-beta update feed. Both channels
dispatch from main so the PublishDesktop signing gates are unchanged.

Guards: stable channel now rejects prerelease tags (previously a beta tag
could clobber desktop-latest and auto-update every stable install onto it),
feed selection is fail-closed and cross-checked in the release job, and the
build asserts the compiled binary embeds exactly its own channel's feed URL.
Changelog extraction is exact-version now that stable and beta sections
interleave across branch merges.

Process doc in apps/examples/desktop-app/EXPERIMENTAL.md; publish-desktop
skill now asks stable-or-beta.

* docs(desktop): warn against renaming the desktop-latest feed

* docs(desktop): document the code-trust model for publish approvals

The beta dispatch-from-main invariant protects the workflow definition, not
the checked-out tag's build scripts, which run with signing secrets in scope
for stable and beta alike. Make explicit that the PublishDesktop reviewer
approval is the trust gate for that code, and that desktop-experimental
therefore needs main-grade merge controls.
2026-08-17 17:24:01 -07:00
Bee 87be867599 fix(desktop): make routine selectors clickable (#13324) 2026-08-17 17:05:33 -07:00
Bee 26cb0ec9eb test(llms): use Google language operation (#13318) 2026-08-17 15:35:56 -07:00
Haley Park eed78103a4 feat(ui): AskQuestion component redesign (#13236)
* feat(ui): support explicit follow-up question submission

* Fix Enter handling for question options

* Strengthen question keyboard regression test
2026-08-17 09:32:03 -07:00
Haley Park 456f86bb3a style(desktop): session hover cards styling (#13256)
* style(desktop): simplify session hover cards

* docs: add hover card screenshots

* chore: remove PR screenshot assets

* style(desktop): address hover card review
2026-08-17 09:31:56 -07:00
Haley Park e86d988234 feat(ui): add animated reasoning and tool disclosures (#13254)
* feat(ui): add animated disclosure presentation

* docs: add disclosure screenshots

* docs: remove PR screenshots

* fix(ui): support inert across React versions
2026-08-17 09:31:41 -07:00
Fnine59 041afb718b fix(vscode): restore Gemini custom base URL (#13247) 2026-08-17 13:16:43 +02:00
Bee 8bbdde2a5c feat(llms): add model-driven image generation (#13025)
* feat: add image generation support

* fix(llms): preserve mixed image model behavior

* fix(llms): validate generated image models

* fix(llms): preserve mixed image response streaming

* fix(llms): preserve runtime tool ownership

* fix(llms): address image generation review feedback

* fix(desktop): relay images for attached hub sessions

* chore(llms): regenerate provider and model catalog

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(vscode): preserve SDK model capabilities across the catalog boundary

The new modelSupportsToolCalling gate treats a populated capability list
without "tools" as authoritative. But the VS Code host round-trips model
metadata through the legacy ModelInfo shape, and toSdkModelInfo
reconstructed capability arrays from the legacy booleans alone — which
have no "tools" projection. Every model with any capability flag set
came back as "cannot call tools", so sessions registered zero tools and
the file-edit e2e failed on all platforms (the editor tool call resolved
to "Unknown tool" and the edit never reached disk).

Fix, following the modalities-passthrough pattern so stacked capability
PRs can reuse it:

- Preserve the SDK capability list verbatim on legacy ModelInfo at the
  catalog boundary (adaptSdkModelInfo); union user overrides into it
  without ever fabricating a list from overrides alone.
- Seed toSdkModelInfo from the preserved list, and when none survived,
  emit an explicit "tools" signal (honoring legacy supportsTools=false)
  so reconstructed arrays can never silently disable tool calling.
- Add a shared modelHasCapability(model, capability,
  {assumeWhenUnspecified}) helper: missing or empty capability lists
  carry no signal and each check declares its own default. Future
  capability gates should route through it instead of reading
  model.capabilities directly.

Verified: file-edit e2e (Single Root + Multi-Roots) passes locally;
shared/core/llms/model-catalog/session-factory suites and typechecks
pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(llms): refresh generated model catalog

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 12:58:53 -07:00
Bee da05eeb02d feat(desktop): add microphone transcription input (#13023)
* feat(desktop): add voice input

* fix(desktop): harden voice transcription input

* fix(llms): scope voice transcription models

* fix(desktop): guard batch voice transcripts

* refactor(voice): defer chat model filtering

* fix(desktop): invalidate stale streaming transcripts

* fix(desktop): preserve batch transcription lifecycle

* chore(llms): refresh voice model catalog

* Mic Icon

* Auto

* test(desktop): align speech input icon assertions
2026-08-14 10:57:29 -07:00
Saoud Rizwan 2be49cf91b chore(desktop): release v0.0.13 2026-08-14 10:18:33 -07:00
Haley Park b851cd86d1 docs(ui): expand agent component stories (#13235) 2026-08-14 09:49:22 -07:00
Saoud Rizwan 3e0aac53a2 chore(vscode): prepare 4.1.10 release 2026-08-14 01:44:30 -07:00
Saoud Rizwan ad442cbb6a chore(cli): release v3.0.55 2026-08-14 00:39:01 -07:00
Saoud Rizwan 225f65cc0e chore(sdk): release v0.0.75 2026-08-14 00:16:53 -07:00
Saoud Rizwan 8a619a9ea6 test(llms): decouple Vertex web-search coverage from the catalog default
The Vertex case asserted that a bare providerId resolves to a model
without web search, which only held because the generated catalog's
Vertex default happened to be a Claude route. models.dev has since moved
that default to gemini-3.7-flash, which does support native web search,
so the assertion failed on the next catalog regen while the behavior it
guarded was unchanged.

Drop the catalog-dependent case and cover the default-model fallback
against a synthetic manifest instead, where the excluded route is stated
by the test rather than inherited from upstream data.
2026-08-14 00:16:48 -07:00
Saoud Rizwan 2e46676952 style: apply biome formatting to files that drifted on main 2026-08-14 00:16:43 -07:00
Bee 102e08f5f4 fix(core): reclaim idle plugin sandbox processes (#13227)
* fix(core): reclaim idle plugin sandboxes

* fix(core): centralize sandbox idle shutdown

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-13 23:40:07 -07:00
Saoud Rizwan 942f76e8e7 feat: add web search settings toggle to VS Code extension and desktop app (#13245) 2026-08-13 23:18:18 -07:00
Saoud Rizwan 57eb181bab fix(cli): say nothing when the Hub is only finishing an update (#13249)
The outdated_hub notice reports a state the user cannot act on: this CLI
is already the newer build, the Hub is behind only because retiring it
would kill the sessions it is serving, and the swap happens on its own at
the next launch. A toast that interrupts to say "no action needed" is
still an interruption, and the desktop surface already concluded the same
thing by rendering nothing for this reason.

It also could not deliver the message it existed for. Toast caps at
maxWidth = Math.min(44, width - 4), and the 61-character string did not
wrap, so what actually rendered was "Update finishes the next time Cline"
- a sentence cut off before the reassuring half. Identical at 120 and 200
columns, so widening the terminal did not help.

The classification stays in core and still earns its keep at this call
site: outdated_hub is what stops the update-and-restart prompt from
firing at someone who has nothing to update. Only the rendering goes.
The build_mismatch direction, where the user does have something to do,
is untouched.
2026-08-13 23:01:34 -07:00
Saoud Rizwan 63e9c99031 fix(cli): stop streaming markdown from flashing raw text on every chunk (#13248)
Render assistant markdown with internalBlockMode="top-level" so each
top-level markdown block gets its own renderable. The default coalesced
mode merged the entire message into one block that was rebuilt and
re-highlighted on every streamed chunk, flashing settled headings and
links back to raw uncolored markdown (visible ###, unconcealed syntax)
until the async tree-sitter highlight landed, and re-wrapping rows so
the transcript jumped vertically.

Top-level blocks are reused by token identity, so settled content never
re-renders; only the trailing unstable block updates per chunk. Pass
tableOptions style=grid to keep the bordered table rendering coalesced
mode used by default.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-13 22:57:35 -07:00
Bee afab68f3a3 fix(core): defer replacing a Hub that is serving live sessions (#13231)
* fix(core): stop concurrent Hub installs from retiring each other

Two Cline installations on different builds would shut each other's Hub
daemon down in a loop, and every session died with an abnormal socket
close (code=1006) as its daemon was killed mid-handshake.

The retire decision was a one-sided predicate: each client independently
asked "may I reuse this Hub?", and two clients on differing builds both
answered no. #13177 added build-epoch ordering to break the tie, but left
every unordered case - missing epoch, missing build id - retiring as
before, so any pair involving a build from before epochs were embedded
still looped.

Derive the decision from a total order instead. compareHubBuilds orders
two builds by embedded epoch, then core release version, then build id,
and is antisymmetric by construction, so at most one side of a pair can
ever decide to retire. A Hub that is newer or cannot be ordered is
attached over the compatible wire protocol and left to the build-mismatch
watcher to prompt about. Genuine protocol incompatibility still replaces.

Identity is now read from the same fields on both sides. Filling in a
coreVersion locally that the wire record omits made a build's identity
depend on which role it was playing, and the two directions of a pair were
then decided by different tiers with both concluding they were newer -
a second, independent way to produce the loop.

Also:
- Scope the development Hub owner by build id, so differing dev builds run
  their own daemon side by side instead of contending for one record.
  Production keeps its singleton.
- Break the circuit after repeated retirements of the same URL, bounding
  any future ordering bug to a stale-build prompt rather than an
  unusable Hub.
- Report `cline doctor fix` honestly: separate processes that survived a
  kill from ones that appeared while the fix ran, name the live parent
  respawning a daemon, and mark a startup lock held by a running process
  as held rather than leaked.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(cli): only blame a live parent for processes seen during doctor fix

The advice printed under "started during fix" asserted that every such
process was respawned by a live parent, and told the user to go stop it. A
process can also start on its own mid-repair - someone opening a new
session - and then the instruction points at an unrelated process, or at
none at all.

Derive the wording from whether a live parent actually exists: name it
when every process has one, state the facts when none do, and split the
list when it is mixed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(core): order the builds in the stale-discovery hub server case

The case stubbed two build ids and expected the second to replace the
first, but supplied nothing that says which came first: no epochs, and both
servers report the same core version. Ordering therefore fell to the
build-id tiebreak, where "new-build" sorts before "old-build" and the
replacement was judged the older of the two.

Give the case the epochs its name implies, and add the missing sibling for
an unorderable pair, which is attached to rather than retired - the
behavior that keeps two installations from shutting each other down.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(core): defer replacing a Hub that is serving live sessions

Retiring a Hub kills its established WebSockets, so replacing one under a
running session ends that turn with an abnormal close (code=1006). The
replacement is correct - the newer build should own the Hub - but the
timing is not the user's to absorb mid-turn.

Defer instead while the Hub reports live sessions: the newer client
attaches to the older Hub over the compatible wire protocol, and the swap
happens once those sessions end. Attaching rather than spawning matters -
a second daemon would race the busy one for the port.

Deferring silently would be worse than the interruption it avoids, because
a long-lived session pins the Hub to old code indefinitely with nothing to
show for it. The build-mismatch watcher only ever prompted in the
direction where updating the client resolves the mismatch; its own comment
notes that older Hubs "are retired and replaced automatically, so
prompting would only flash a stale dialog", which stops being true once
replacement can be deferred.

Add the missing direction as `outdated_hub`, reported only when a mismatch
survives consecutive checks - an idle older Hub is replaced within moments
of being seen, so a single sighting would flash exactly the stale dialog
the original comment warns about. The CLI and desktop dialogs render it as
information rather than an update prompt: nothing to install, the Hub
swaps itself when the sessions end.

The direction is decided by compareHubBuilds rather than reusability,
because a Hub that is newer and one that carries too little metadata to
order are both "reusable" but need opposite advice.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(core): key the outdated-Hub check by daemon instance, not build

The consecutive-sighting check that keeps a routine replacement from
flashing an informational dialog was keyed by build id. Two daemons from
the same build share one, so an outdated Hub replaced by another daemon of
the same older build satisfied the check and reported exactly the churn the
check exists to hide.

Carry a hubInstanceId on the mismatch event - the Hub's own id, falling
back to pid and start time - and key the pending sighting by it. A
replacement instance now restarts the count instead of confirming it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(core): source Hub instance identity from the discovery record

The instance id added in the previous commit was read from the probe
response, but the watcher probes without an auth token and `/health`
deliberately reports only build and address fields - no hubId, pid, or
startedAt. So the id was always undefined in production and the check it
guards still conflated two daemons of the same build. The test missed it by
injecting a hubId into a mocked probe, a shape `/health` never returns.

Take identity from the discovery record instead, which every daemon version
writes with all three fields and which a replacement daemon rewrites as its
own. The probe is still preferred when it does carry an id, since that is
the process just spoken to.

The tests now use the real `/health` payload shape and vary identity through
the discovery record, including the pid-and-start-time fallback for records
written before Hubs carried an id.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(core): confirm the Hub record still describes the daemon just probed

Instance identity is read from discovery before the probe and build data
comes back after it, so a daemon replaced between those two steps was
described with its predecessor's identity - the replacement then satisfied
the prior daemon's pending sighting and emitted the notification the
consecutive-instance check exists to suppress.

Re-read discovery after the probe and report nothing when the record no
longer describes the same daemon. A Hub mid-swap is churn; the next check
sees whatever it settles into.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* revert(core): drop the watcher instance-identity hardening

Reverts the three follow-up commits that keyed the outdated-hub
consecutive-sighting check by daemon instance (42a83beae, 931431371,
9d634f7b3). They guarded one scenario - a different daemon of the same
outdated build swapping in between two watcher ticks - where the only
consequence is an informational dialog showing one interval early or
late. The unauthenticated probe carries no instance fields in
production, which is why the first attempt needed two more patches; the
original reason+buildId consecutive-sighting suppression from this PR's
base commit already covers the case that matters (not flashing a dialog
for a hub that is mid-replacement).

* fix(core): only count sessions that stopping the hub would actually harm

hasActiveHubSessions treated every non-terminal status as busy. But a
session's hub-side runtime outlives its client: a TUI that is killed or
crashes never stops its session, which then sits in the hub with no
participants and a status that never reaches a terminal state. Under the
defer-while-busy rule that pinned the displaced hub as "serving
sessions" forever - it was never retired, every new CLI kept attaching
to the old build, and the outdated-hub dialog recurred with a promise
("replaced once those sessions end") that could never come true.
Verified empirically: a cleanly detached+disposed client leaves its
session status "running" indefinitely.

Busy now means: someone is attached (participants), or a turn may be
executing hub-side (running/pending, which covers headless and scheduled
runs). An idle session with a confirmed-empty participant list is
resumable persisted state, not live work. Hubs from core < 0.0.75 omit
the participants field entirely, so idle stays conservative (busy)
there - an attached client cannot be ruled out.

updatedAt-freshness was considered and rejected as the discriminator:
the sessions row only updates on status transitions, so a single long
agentic turn looks stale while genuinely executing.

* fix(core): gate hub busyness on attached participants only

Simplifies the busy-check to the one signal that cannot go stale:
participants are live socket subscriptions the hub drops the moment a
client's connection closes, so a crashed client can never leave a ghost
that counts as busy. Session status is deliberately not consulted - a
client killed mid-turn strands its session in a non-terminal status
forever, and QA reproduced that pinning an outdated hub as "serving
sessions" until reboot. This replaces the earlier status+participants
heuristic (and drops the aging bound it was growing) with the rule the
deferred-update design stated from the start: the hub is busy while a
client is connected to a session, and replaceable otherwise.

The accepted cost: a participant-less background run executing at the
exact moment of a hub swap dies with the old hub. Rare, and its next
scheduled tick runs normally on the replacement.

* fix(cli): tell the truth about when the outdated Hub is replaced

The outdated-hub dialog and toast said the Hub is replaced "once those
sessions end". It is not: nothing retires a hub except a fresh launch
running the ensure path, so a user who quits the busy session and
watches sees the old hub stay put and concludes something is stuck
(observed in hands-on QA). Say what actually happens - the newer build
takes over the next time Cline starts after those sessions end.

* fix(cli): speak to users, not architecture, in the pending-update notice

"Cline Hub is running an older build" assumes the reader knows what the
Hub is and why builds differ. The user-relevant facts are only: your
update is not fully active yet, your work is safe, and it finishes by
itself. Say exactly that, in both the TUI and desktop dialogs and the
toast, with the version tucked in parentheses for bug reports.

* fix(cli): drop the outdated-hub dialog for a single quiet toast

The dialog interrupted the user to say that nothing is wrong and no
action is needed - the ideal number of modals for that message is zero.
The TUI now shows one info toast ("Update finishes the next time Cline
starts. No action needed.") and the desktop app shows nothing for the
outdated_hub reason; both dialog components return to their shipped
update-and-restart form, which still appears for the build_mismatch
direction where the user genuinely has something to do. The watcher
keeps reporting outdated_hub - surfaces decide, core informs.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-13 19:46:55 -07:00
Saoud Rizwan d3d3bd8749 fix(cli): defer auto-update install until no CLI is attached to the hub (#13233)
* fix(core): bridge protections for updates landing under pre-3.0.55 clients

Three pieces, each proven against real released artifacts:

- postinstall shield: CLI versions <= 3.0.54 restart the hub daemon after a
  background auto-update even while it serves live sessions, and their
  fingerprint check then rejects every replacement hub, bricking the running
  TUI. That code is on users' machines and cannot be patched — but it runs
  only after the install completes, and it bails out harmlessly when no hub
  discovery record exists. The newly installed package's postinstall sets
  the record aside so the old updater never fires.
- superseded-record fallback: the set-aside record is also the only source
  of the auth token and pid the next new-build launch needs to retire the
  displaced hub (a port probe carries neither); ensure reads it back.
- bind retry: a hub retired on the fixed port can hold it ~2s after acking
  shutdown (watchdog force-exit); the replacement daemon retries EADDRINUSE
  for up to 5s instead of dying and leaving no hub at all.

* fix(cli): defer auto-update install until no CLI is attached to the hub

Installing while cline processes run swaps the npm package under them:
their respawn paths break on the new build fingerprint, and the updater
then restarted the hub daemon out from under live sessions (the 'Hub
connection closed (code=1006)' incident). Guarding the restart treats the
symptom; the fix is to never install under a running process.

The startup check now only records that an update is available. The
install runs at process exit, and only when the hub confirms no other
cli* client is attached — desktop sidecars and connectors ship their own
binaries, so only cli* clients make the swap unsafe. With nothing old
running at install time, no hub restart is needed at all: the next launch
retires the stale hub through the existing ensure path. Deletes
restartHubServerIfRunning, ensureCliHubServerAfterUpdate, and their
support code; manual 'cline update' still installs immediately and now
just notes that the update applies on next start.

* fix(cli): apply deferred update from the entrypoint exit sequence

The CLI entrypoint always terminates with an explicit process.exit(),
which never emits beforeExit — the hook the deferred installer waited on,
so it would never have run (caught by review). Invoke applyDeferredUpdate
directly from the entrypoint's exit sequence after disposeAll(), where
every normal termination passes; crash paths deliberately skip it. Also
clear the pending update once an install spawns so the apply is
idempotent.

* test(cli): isolate unit tests from the real ~/.cline

A full vitest run could leave a real hub daemon running against the
developer's actual ~/.cline discovery record (observed while validating
this PR: a daemon spawned from the globally installed cline binary,
attached to the real data dir). Point CLINE_DIR, CLINE_DATA_DIR, and
CLINE_HUB_DISCOVERY_PATH at a per-worker temp dir and disable auto-update
before any test file loads; subprocesses inherit the isolation via env.

* fix(core): discard the superseded discovery record once consumed

The set-aside record is one-shot recovery metadata, but nothing deleted
it, and it feeds a pid into retireDiscoveredHub's SIGTERM. Weeks later a
launch that finds no live record (routine after any retirement) could
read the stale file and signal whatever process the OS recycled that pid
onto (review finding by @abeatrix). Unlink it at every ensure resolution
that ends with a live, verified hub; failure paths keep it for the next
attempt.

* fix(cli): harden the exit-time update gate

Three review findings on the deferred-apply path:

- A wedged hub could stall an otherwise-finished CLI for tens of seconds
  via the hub client's default timeouts; the whole exit-time query is now
  bounded to 3s, with timeout counting as attached (never install unless
  the hub positively confirms).
- Sub-second commands exited before the startup version check resolved
  and silently dropped the update every time for one-shot-only usage;
  exit now grants the in-flight check a 250ms grace.
- client.list can lose a TUI's registration during transport churn while
  its session connection survives, so an empty client list is not proof
  of safety; cross-check sessions with participants. Participants rather
  than session status: finished sessions linger idle forever and must
  not pin updates, and participant-less scheduled runs live in the hub
  process, which the binary swap does not touch. Verified live: a
  session-holding client invisible to client.list defers the install,
  and the gate opens once it disconnects.

* docs(cli): fix stale beforeExit reference in the exit-gate comment

* style(cli): apply biome formatting to update deferral code

* fix(cli): let doctor see a hub whose record the update shield set aside

During the shielded update window the discovery record is renamed to
.superseded so pre-3.0.55 updaters cannot restart a busy hub. Doctor
read only the primary record, so in that window it reported the live
daemon - the one serving the user's still-open old session - as a stale
hub daemon and advised 'cline doctor fix', which kills it and reproduces
the exact 1006 incident the shield exists to prevent (found by QA).
Doctor now falls back to the set-aside record the same way the ensure
path does, and doctor fix clears the set-aside file along with the
primary record so a deliberate reset does not leave stale retirement
metadata pointing at a recyclable pid.

* fix(core): keep shielded sessions on one Hub authority (#13244)

* fix(core): recover shielded busy hub discovery

* chore(core): instrument shielded hub recovery

* fix(core): recover shielded hubs with attached clients

* fix(cli): recognize shielded hubs in doctor

* refactor(core): keep shield recovery minimal

* fix(core): retain shared Hub idle helper semantics

* chore(core): align busyness helper with the #13231 wording

The participants-only hasActiveHubSessions here duplicates the change on
bee/hub-lifecycle (this branch needs its semantics for the participant
gate). Matching that version byte for byte lets the two merges resolve
cleanly instead of conflicting. Also restores the module-registry reset
comment this branch dropped - it documents a real local-vs-CI gotcha.
2026-08-13 19:39:44 -07:00
Bee afab86dcbd fix(core): stop concurrent Hub installs from retiring each other (#13230)
* fix(core): stop concurrent Hub installs from retiring each other

Two Cline installations on different builds would shut each other's Hub
daemon down in a loop, and every session died with an abnormal socket
close (code=1006) as its daemon was killed mid-handshake.

The retire decision was a one-sided predicate: each client independently
asked "may I reuse this Hub?", and two clients on differing builds both
answered no. #13177 added build-epoch ordering to break the tie, but left
every unordered case - missing epoch, missing build id - retiring as
before, so any pair involving a build from before epochs were embedded
still looped.

Derive the decision from a total order instead. compareHubBuilds orders
two builds by embedded epoch, then core release version, then build id,
and is antisymmetric by construction, so at most one side of a pair can
ever decide to retire. A Hub that is newer or cannot be ordered is
attached over the compatible wire protocol and left to the build-mismatch
watcher to prompt about. Genuine protocol incompatibility still replaces.

Identity is now read from the same fields on both sides. Filling in a
coreVersion locally that the wire record omits made a build's identity
depend on which role it was playing, and the two directions of a pair were
then decided by different tiers with both concluding they were newer -
a second, independent way to produce the loop.

Also:
- Scope the development Hub owner by build id, so differing dev builds run
  their own daemon side by side instead of contending for one record.
  Production keeps its singleton.
- Break the circuit after repeated retirements of the same URL, bounding
  any future ordering bug to a stale-build prompt rather than an
  unusable Hub.
- Report `cline doctor fix` honestly: separate processes that survived a
  kill from ones that appeared while the fix ran, name the live parent
  respawning a daemon, and mark a startup lock held by a running process
  as held rather than leaked.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(cli): only blame a live parent for processes seen during doctor fix

The advice printed under "started during fix" asserted that every such
process was respawned by a live parent, and told the user to go stop it. A
process can also start on its own mid-repair - someone opening a new
session - and then the instruction points at an unrelated process, or at
none at all.

Derive the wording from whether a live parent actually exists: name it
when every process has one, state the facts when none do, and split the
list when it is mixed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(core): order the builds in the stale-discovery hub server case

The case stubbed two build ids and expected the second to replace the
first, but supplied nothing that says which came first: no epochs, and both
servers report the same core version. Ordering therefore fell to the
build-id tiebreak, where "new-build" sorts before "old-build" and the
replacement was judged the older of the two.

Give the case the epochs its name implies, and add the missing sibling for
an unorderable pair, which is attached to rather than retired - the
behavior that keeps two installations from shutting each other down.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-13 19:39:18 -07:00
Bee 6d7e745fb7 feat(core, llms): add provider-aware web search tools (#13075)
* feat(core, llms): Cline custom provider & web search

* fix(llms): preserve reasoning model token parameter

* fix(llms): keep ClinePass provider options on the wire in the shared Cline provider

The shared Cline provider hardcoded the AI SDK provider name to "cline",
but the openai-compatible model reads request-body passthrough options from
providerOptions[<name>]. Option routing emits ClinePass options under the
"cline-pass"/"clinePass" buckets, so gateway reasoning (extended thinking
budgets) silently stopped reaching the wire for cline-pass after it moved
off the generic openai-compatible module.

Thread the gateway provider id through as the provider name, and restore
strictJsonSchema: false for the new "cline" provider-options target so the
wire format matches the previous openai-compatible behavior. Add cline-pass
coverage at both the option-routing and request-body levels.

* feat(sdk): persist provider-executed tool activity (#13077)

* feat(core, llms): Cline custom provider & web search

* fix(llms): preserve reasoning model token parameter

* feat(sdk): persist provider-executed tool activity

* fix(vscode): restore state proto and settings section reverted by merge

The merge of origin/bee/websearch into this branch resolved conflicts by
keeping this branch's pre-#13126 copies of apps/vscode files, which
deleted the auto_approve_all_toggled = 174 proto field (without reserving
the number) and dropped a formatting line in FeatureSettingsSection.tsx.
Neither file is in scope for this PR. Restore both to main's content so
the proto source matches the checked-in generated code again.

* chore(vscode): match main byte-for-byte in FeatureSettingsSection.tsx

The pre-commit biome hook strips a blank line that exists on main, which
kept this out-of-scope file in the PR diff. Commit the exact main content
with --no-verify so the PR no longer touches apps/vscode at all.

---------

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

* refactor(llms): key ClinePass provider options to the shared cline bucket

Both Cline gateway ids (cline and cline-pass) are served by the same
shared "cline" AI SDK provider and hit the same Cline API, so threading
the gateway provider id through as the AI SDK provider name (78dc6f3e7)
was unnecessary indirection. Revert the name threading and instead
normalize option-routing bucket keys: buildProviderAndAliasPatch now
keys both Cline gateway ids to the shared "cline" providerOptions
bucket, which is the only bucket the openai-compatible model reads for
request-body passthrough.

Also tighten the regression coverage that motivated the original fix:
the previous effort-based test rows were vacuously satisfied through the
portable-reasoning early return (effort reasoning never reaches provider
option buckets by design). The rows now use explicit reasoning budgets,
which do flow through the gateway bucket path, and the wire-level test
composes real provider options end to end instead of hand-feeding
buckets.

* revert(llms): drop the cline strictJsonSchema special case in generic-compatible

Restores buildCompatibleProviderOptions to its pre-78dc6f3e7 state. The
strictJsonSchema passthrough is verified inert for the gateway (nothing
in @cline/llms sets a response format), so keeping a hardcoded provider
target in the generic helper bought nothing. If structured outputs are
ever added, strictness for the cline target can be decided deliberately
then.

* fix(llms): claim native web search for openai-native, not the openai alias

supportsModelTool listed "openai", but that id aliases to
openai-compatible (PROVIDER_ID_ALIASES), whose module has no native web
search. The actual native OpenAI builtin id is "openai-native", which is
served by the OpenAI Responses module that does implement
buildModelTools with provider.tools.webSearch(). Without this, the
web_search tool was never offered to native OpenAI users, and was
wrongly offered for the compatible alias.

* refactor(llms): declare model tools in provider manifests

* feat(sdk): project provider tool activity in session history

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-13 18:12:10 -07:00
Bee fcd5a9e0fb feat(desktop): add app font size bootstrap script (#13232)
* feat: add app font size bootstrap script

- Import and inject APP_FONT_SIZE_BOOTSTRAP_SCRIPT in root layout
- Call syncAppFontSize on app initialization
- Add aria attributes (describedby, label, labelledby, valuetext) to Slider component
- Replace thumb key generation with useId hook for better stability
- Add settings view tests for font size functionality

* feat(desktop): add native zoom menu shortcuts
2026-08-13 14:08:09 -07:00
Saoud Rizwan c8afb44368 chore(vscode): prepare 4.1.9 release 2026-08-13 00:08:09 -07:00
Saoud Rizwan d30cce4cf1 chore(cli): release v3.0.54 2026-08-12 23:13:29 -07:00
Saoud Rizwan 3f39c46026 chore(sdk): release v0.0.74 2026-08-12 22:45:26 -07:00
Saoud Rizwan 274ad3bdb2 chore(desktop): release v0.0.12 2026-08-12 22:37:06 -07:00
Saoud Rizwan e6b1c3fbc8 chore(ui): bump @cline/ui to 0.2.0-next.4
Picks up the shared button primitives (#13164), the one-row-per-tool-call
chat rendering (#13186), the refined session chat layout (#13205), and the
@pierre/diffs hunk renderer (#13201) that landed since 0.2.0-next.3.
2026-08-12 20:40:03 -07:00
Bee 5b22490d41 fix(desktop): filter scheduled Core sessions (#13213) 2026-08-12 18:18:09 -07:00
Saoud Rizwan d03e88e50b Render desktop diff view hunks with the shared @pierre/diffs renderer (#13201)
* Render desktop diff view hunks with shared @pierre/diffs renderer

Replace DiffView's hand-rolled DiffHunk +/- line rows with ToolFileDiff
from @cline/ui (backed by @pierre/diffs), matching the chat tool rows.
Hunks carrying complete new contents (created files) render with real
line numbers; fragment hunks hide them, mirroring ToolCallRow. All of
DiffView's chrome (collapse, copy, open-in-editor, counts) is unchanged.

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

* Make ToolFileDiff syntax palette follow the app theme, not browser preference

@pierre/diffs declares 'color-scheme: light dark' on its shadow :host, so
its light-dark() token colors resolve from the browser's preferred scheme.
Apps themed by the .dark class (desktop app) got the light palette's
near-black text on dark surfaces. Inline colorScheme: inherit on the host
wins over the :host rule and follows the app's color-scheme, which the
@cline/ui theme already flips with .dark. Skipped when a caller pins an
explicit themeType.

Also key diff-view hunks by index so repeated same-shaped hunks (a file
created twice with identical contents) don't collide.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-12 18:06:44 -07:00
Sufiyan Khan 02a1bfd0a8 fix(webview): use editor foreground for diff block text colors (#13200) 2026-08-13 09:41:52 +09:00
Saoud Rizwan 4559f12c66 feat(desktop): temporarily disable welcome prompt suggestions and center input (#13170)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-12 14:59:03 -07:00
Saoud Rizwan 6d6f79f948 Fix Claude Code provider: anchor session on workspace, load user settings, allow edits (#13152)
The Claude Code provider was unusable for agentic work (#13146):
- The claude-code manifest lacked the provider-tools capability, so the
  gateway sent Cline's tool definitions (which the provider drops as
  unbridgeable) while the CLI's native tools stayed enabled with no
  approval plumbing - every write was refused and no prompt appeared.
- ai-sdk-provider-claude-code defaults settingSources to [], so the
  spawned session read neither ~/.claude/settings.json nor project
  settings, silently ignoring user-configured permission rules.
- No cwd was passed, so the session inherited the extension host's
  cwd (/ on macOS) and refused writes outside it.

Changes:
- Mark claude-code with provider-tools (same treatment as the Codex
  CLI provider): stop sending unbridgeable external tools and let the
  CLI execute its own, tagged executionMode=provider for the runtime.
- Forward the session workspace cwd from @cline/core into the
  claude-code gateway provider options and lift it into the agent
  session settings.
- Default settingSources to [user, project] and permissionMode to
  acceptEdits (file edits under cwd auto-approved; command execution
  stays gated by the user's own Claude settings), all overridable via
  explicit defaultSettings.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-12 14:51:37 -07:00
Saoud Rizwan cde49170db fix(desktop): first turn of a fresh session no longer wedges the composer (#13122)
* fix(desktop): don't let a stale queued send response wedge the composer

A fresh session is still busy while its interactive loop starts, so the
sidecar coerces the first send onto the pending-prompt queue and replies
{queued:true} with a queue snapshot taken at enqueue time. The turn itself
runs via the runtime's queue drain and completes through stream events
(chat_queued_prompt_start -> deltas -> chat_done). On cold/slow sidecars the
RPC response lands only after those events; the webview then applied the
stale snapshot and unconditionally set status back to "running", leaving
the composer on "Agent is working..." forever and resurrecting a phantom
queue entry.

Webview: capture the turn epoch at send dispatch; chat_queued_prompt_start
bumps it, so a mismatch when the queued response arrives means the stream
already advanced the turn lifecycle and the response is ignored. Aborts now
resolve the queued branch to "cancelled" like the direct path.

Sidecar: the queued send response no longer routes its enqueue-time snapshot
through applyPendingPrompts, which overwrote the event-maintained
session.promptsInQueue and rebroadcast the stale list to every webview.

Includes deterministic regression tests for the stale-response orderings
plus temporary [P0DBG] debug instrumentation (region-marked, to be removed
after runtime verification).

* fix(desktop): ignore stale hub 'running' status after turn settles

The sidecar core is hub-attached, so chat_session_status events are
asynchronous projections of the hub's session record. A stale 'running'
can trail the stream's chat_done and flip a settled turn back to busy,
wedging the composer on 'Agent is working…' with nothing left to
reconcile. Track the epoch at which the turn settled and drop 'running'
status events until a new turn bumps the epoch.

* chore: remove stray QA screenshot artifacts from repo root

* chore(desktop): remove P0 debug instrumentation and fault injection

Strips all [P0DBG] logging, the /p0dbg sidecar route, the webview log
mirror + heartbeat, and the P0DBG_STARTUP_BUSY_MS /
P0DBG_DELAY_QUEUED_RESPONSE_MS fault-injection paths used to reproduce
the stuck-composer P0. The two real fixes (stale queued-response epoch
guard + stale-running-after-settle guard in the webview, and the
sidecar's non-clobbering queued-send snapshot) and the regression tests
remain.

* refactor(desktop): replace turn-epoch guards with an explicit turn lifecycle

The stuck-composer fixes left the hook with two hand-rolled epoch refs
(turnEpochRef / turnSettledEpochRef) mutated and compared inline across
eight call sites. Extract the rules into a pure TurnLifecycle module that
is now the only writer of the session status:

- a settled turn cannot be reopened: stale hub 'running' projections and
  stale queued-send acknowledgements are dropped by the lifecycle instead
  of by inline epoch comparisons
- async work (send RPC responses, queue reconciliation) captures an opaque
  token and the lifecycle decides whether the world moved on, instead of
  handlers comparing counters
- every status write goes through a named operation (begin, turnStarted,
  settle, projectStatus, apply, reset), so the state machine is explicit
  and unit-testable in isolation

No behavior change: the 5 wedge regression tests and the full hook suite
pass unchanged, plus 10 new unit tests for the lifecycle module itself.

* Revert "refactor(desktop): replace turn-epoch guards with an explicit turn lifecycle"

This reverts commit c480aaabe8.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-12 14:50:39 -07:00
Haley Park e703f7af2a style(desktop): refine session chat layout (#13205)
* style(ui): refine chat message surfaces and actions

* feat(desktop): refine session transcript layout

* style(desktop): refine conversation composer

* style(ui): format chat theme changes
2026-08-12 14:38:50 -07:00
Saoud Rizwan 105d357b12 fix(vscode): stop legacy-task migration backlog telemetry spam (#13185)
* fix(vscode): stop legacy-migration backlog telemetry spam, emit real migration outcomes

* refactor(vscode): slim migration telemetry fix to minimal surface

* fix(vscode): emit legacy migration outcome only after seeded session start settles

The completed event fired at in-memory conversion time, before the
seeded session start persisted the migration, so a start/persistence
failure was misreported as a successful migration and never produced an
error outcome. Conversion now records a pending migration; the followup
and compaction coordinators settle it after the session start resolves
(completed) or rejects (error/session_start_failed).

* fix(vscode): surface seeded-persistence failures in migration outcomes

LocalRuntimeHost.startSession deliberately swallows seeded-message
persistence failures (the in-memory session still works), so a resolved
start was not proof the legacy conversion became durable. The start
result now reports seededMessagesPersistence, and the resume/compaction
coordinators settle the migration from that result: completed only when
the seed write succeeded, error/seed_persistence_failed when the start
resolved but the write failed, error/session_start_failed when the
start rejected. durationMs now spans conversion through settlement.

Adds the core boundary test forcing persistSessionMessages to fail and
asserting the start still resolves with the failure visible on the
result, plus coordinator tests for both failure modes.

* refactor(vscode): drop per-task migration outcome events, keep volume fixes only

Scope the PR down to the zero-behavioral-risk telemetry fixes, per
review: keep the backlog event transition gating and the one-line
migratedSdkTaskCount fix (counting resumed legacy sessions via their
legacyTask metadata), and revert the per-task terminal outcome
plumbing (pending-migration settlement, coordinator hooks, and the
core StartSessionResult.seededMessagesPersistence field) along with
the success->completed outcome rename on the now-uncalled
captureLegacyTaskMigration. The per-task outcome events can land
separately on the observable persistence boundary.
2026-08-12 14:22:28 -07:00
Sufiyan Khan 274e0c574f Fix silently repaired truncated tool-call JSON (#13015)
* fix(llms): reject truncated tool-call JSON with unterminated strings

* fix(llms): scope truncation guard to jsonrepair only and handle single quotes

* fix(shared): keep jsonrepair ahead of bare-object repair for typed literals

Restores main's precedence for inputs both strategies can handle:
{"flag": True} must repair to a typed true, not the string "True".
The truncation guard now gates only the jsonrepair step, which is the
only strategy that can invent a string terminator.

---------

Co-authored-by: Mikołaj Kondratek <19799111+mkondratek@users.noreply.github.com>
2026-08-12 22:32:03 +02:00
Saoud Rizwan 98d883bf6e fix(llms): replace all-empty-text messages with placeholder content (#13204)
A message whose content array held only empty text parts slipped past the
existing empty-content guards in formatMessagesForAiSdk (which cover
content: "" and content: []). The AI SDK then strips empty text parts,
producing {"role":"user","content":[]} on the wire, which strict
providers reject — seen in prod as Vercel 400s for kimi-k3:
"user message must have content".
2026-08-12 13:15:44 -07:00
Saoud Rizwan 6ff6a1ecbb fix(telemetry): emit per-request deltas in task.tokens on SDK surfaces (#13188)
* fix(telemetry): emit disjoint per-request token buckets in task.tokens

SDK usage events follow the AI SDK convention where inputTokens is the
full request input including cache reads/writes. task.tokens forwarded
that value as tokensIn while also reporting cacheReadTokens and
cacheWriteTokens, so every event re-counted the whole (mostly cached)
conversation context and per-task token sums inflated ~5x on
cache-heavy sessions relative to the legacy contract (tokensIn =
uncached input only, disjoint buckets).

task.tokens now subtracts the cache buckets from tokensIn at the
capture site (mirroring the webview's normalizeUsageEvent), defaults
the cache buckets to 0 instead of undefined, and stamps the provider
attribute for parity with the legacy event schema. Event and attribute
names are unchanged.

* fix(core): normalize registered ApiHandler usage to cache-inclusive inputTokens

Review follow-up: two producer contracts shared AgentUsage.inputTokens.
Native AI SDK usage reports the full cache-inclusive prompt size, but the
ApiHandler adapter forwarded classic disjoint chunk.inputTokens unchanged,
so the task.tokens cache subtraction would zero out real uncached input
for a cache-reporting registered handler.

Normalize at the adapter boundary (inputTokens + cacheReadTokens +
cacheWriteTokens) so every producer entering AgentUsage satisfies the
same cache-inclusive invariant, document that invariant on
AgentTokenUsage.inputTokens, and reframe the telemetry clamp as a
defensive guard rather than a supported producer shape. Adds an adapter
normalization test and a boundary test from an ApiStreamUsageChunk
through task.tokens asserting the disjoint buckets round-trip.

* Revert "fix(core): normalize registered ApiHandler usage to cache-inclusive inputTokens"

This reverts commit 9a9aff374a.
2026-08-12 12:53:50 -07:00
Saoud Rizwan 0f8d715dc7 fix(telemetry): report involuntary Cline logouts from the SDK auth service (#13183)
* fix(telemetry): report involuntary Cline logouts from the SDK auth service

The SDK auth service cleared credentials silently when a refresh token was
rejected (invalid grant), both mid-session and during startup restore, so
user.auth_logged_out never captured involuntary logouts on the next bundle.
Emit token_invalid at both credential-clearing sites and restore_error when
startup restore throws, matching the reason vocabulary the legacy bundle now
uses so the same warehouse query measures involuntary logouts across rollout
variants. Startup with no stored session still emits nothing.

* refactor(telemetry): trim logout-reason parity change to the minimum

* fix(telemetry): report Cline invalid-grant logouts as token_invalid in the SDK resolver

getValidClineCredentials is the single owner of the involuntary-logout
event for the Cline provider; normalize its reason to the legacy
extension's LogoutReason vocabulary (token_invalid) so warehouse queries
cover both bundles. The raw OAuth code stays in errorCode. Codex/OCA
paths keep emitting invalid_grant and are unaffected.

* fix(telemetry): let the SDK resolver own token_invalid; keep restore_error for real restore failures

Address review on the SDK-adapter half of the logout-reason split:
- drop both adapter-side token_invalid emissions - the SDK resolver
  already emits user.auth_logged_out on the same telemetry instance, so
  the adapter was double-counting the exact signal being measured
- transient failures refreshing the stored session on startup (resolver
  throws: network/timeout/5xx) no longer book as restore_error; stored
  credentials are kept and the SDK books auth_refresh_soft_failure, so
  an offline startup is not a logout
- single-source LogoutReason in services/auth/types.ts and re-export it
  from the SDK auth service instead of maintaining two parallel enums
- boundary test runs the real getValidClineCredentials and asserts
  exactly one auth_logged_out (reason=token_invalid) total, so a
  reintroduced adapter emission fails the suite
2026-08-12 12:52:01 -07:00
Saoud Rizwan 3d460d7add feat(hub): directional Hub upgrades with update-and-restart prompts in CLI and desktop (#13177)
* feat(hub): prompt update and restart when another install replaces the shared Hub

* feat(hub): make managed Hub build-watch interval configurable via CLINE_HUB_BUILD_WATCH_INTERVAL_MS

* feat(hub): reuse newer managed Hub builds instead of retiring them

Embed a build epoch alongside the deterministic runtime fingerprint so
managed-Hub compatibility can order builds in time. When fingerprints
differ, a Hub produced after the client's own build is attached over the
compatible wire protocol (and the build-mismatch watcher prompts the user
to update) instead of being retired, so concurrent installations converge
on the newest build rather than replacing each other's daemons. Older,
unordered, or metadata-less Hubs are retired and replaced as before.

* refactor(hub): simplify mismatch status derivation and dedupe sidecar event encoding

* fix(cli): only watch for managed Hub build mismatches in hub-attached sessions

Yolo and sandbox sessions force the local backend and never attach to the
shared managed Hub, so a newer Hub owned by another installation must not
interrupt them with the blocking update dialog.

* fix(desktop): stage an app update before hub-mismatch restart

'Update and restart' previously invoked restart_to_apply_update directly,
which only relaunches the current bundle. With no update staged by the
background 2h updater loop, the app came back on the same version, hit the
same newer Hub, and re-prompted immediately.

Add a check_for_update_now Tauri command that runs one updater
check/download/stage cycle on demand and reports the resulting status. The
dialog now stages the update first and restarts only when the updater
reports 'ready'; otherwise it stays open and explains that no update is
downloadable yet (or that the check failed) instead of restarting into the
same version. Addresses the outstanding Greptile P1 on the dialog.

* fix(desktop): reset the no-update hint when a new hub mismatch arrives

Without this, a dialog for a fresh mismatch reopened pre-set to 'Try again'
with the previous prompt's stale hint.

* fix(desktop): serialize updater cycles so overlapping checks cannot clobber a staged update

The periodic update loop and the on-demand check_for_update_now command
run the same check/download/stage cycle against shared state. Without
exclusion, two overlapping cycles could download the same bundle
concurrently, and the later one could overwrite a freshly staged "ready"
status with "idle" or "error" decided from its stale pre-await
ready_version snapshot - making the update dialog deny that a staged
update exists. A tokio::sync::Mutex now serializes whole cycles; the
ready_version snapshot is read under the lock, so it stays authoritative
for the cycle that took it.
2026-08-12 12:33:27 -07:00
Bee 24f66a4673 fix(core): harden Cline Hub daemon lifecycle (#13168)
* fix(core): harden Hub daemon lifecycle

* fix(core): wait for Hub listener before replacement

* fix(core): recover after Hub cleanup errors

* fix(core): assign the close memo handle before socket termination re-enters beginClose

On every shutdown with a connected client, the daemon logged
'unhandledRejection: AggregateError: hub server close failed' and exited
with code 1 instead of 0. Root cause: beginClose() terminated the
tracked WebSockets before assigning closeHandle. terminate() fires close
events whose microtask continuations advance the daemon coordinator's
deferred cleanup into server.beginClose() while the first invocation is
still mid-body, so the memo guard passes twice and a second set of
wss.close()/server.close() calls runs against the already-closing server,
rejecting with 'Server is not running' and spuriously failing the close
aggregate. The rejection then rode the daemon's unhandledRejection
fatal path and escalated the exit code.

Construct the close promises and assign the memo handle first, and only
then terminate sockets and run detach handlers; a re-entrant call now
hits the memo guard. Also observe the /shutdown handler's
fire-and-forget closeServer() so a genuine close failure is reported
solely by the owner's own await on the same memoized promise instead of
the unhandledRejection path.

Verified with a real daemon: shutdown with zero clients stays graceful
(exit 0, ~26ms); shutdown with a held-open authenticated WebSocket now
exits 0 with no unhandled rejection, still bounded by the 2s coordinator
deadline for the genuine Bun listener-close stall, with the discovery
record cleaned. Hub suites (228) and the shutdown e2e (5) pass.

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-12 12:33:27 -07:00
Saoud Rizwan 354c80df7b fix(llms): update AI SDK deps so streamed tool calls with non-zero indexes don't crash (hasFinished) (#13123)
* fix(llms): update AI SDK deps to fix streamed tool calls with non-zero indexes

LiteLLM's Anthropic passthrough emits chat-completions tool_call deltas
whose index mirrors the Anthropic content-block index (1 when a text
block precedes the tool call; see BerriAI/litellm#11580).
@ai-sdk/provider-utils 5.0.18 stored streamed tool calls in a sparse
array keyed by that index and crashed at stream flush with
"Cannot read properties of undefined (reading 'hasFinished')",
aborting the agent turn. Upstream fixed this in provider-utils 5.0.21
("Fix streamed tool calls with non-zero, non-contiguous, reused, or
missing indexes.").

Update the ai / @ai-sdk packages so every chat-completions streaming
path resolves @ai-sdk/provider-utils 5.0.25, and drop the root
">=4.0.0" override on @ai-sdk/provider-utils: with intersect semantics
it pinned the workspace to the already-locked 5.0.18 even after parents
began requiring 5.0.25, and it force-upgraded dify-ai-provider two
majors past its declared ^3 range. Each package now resolves the
version line it declares.

Fixes #13119

* test(llms): pin non-zero streamed tool_call index regression (#13119)

Wire-level regression test: an openai-compatible SSE stream whose only
tool_call delta carries index 1 (Anthropic content-block numbering via
LiteLLM) must complete and emit the tool-call part instead of throwing
at flush.

* fix: address review findings from merge-conflict resolution

- Restore apps/vscode/proto/cline/state.proto to main's version: the
  merge commit's pre-commit hook regenerated it with a stale generator,
  deleting auto_approve_all_toggled = 174 and moving a reserved line,
  creating drift against the checked-in descriptor. The deletion was
  never intended.
- Restore FeatureSettingsSection.tsx to main's version (the same hook
  reformatted main's file during the merge).
- Regenerate bun.lock narrowly from main's lockfile without --force so
  the diff contains only the @ai-sdk family and its direct transitives;
  drop the spurious webview-ui-scoped @radix-ui duplicate entries the
  previous install introduced (hoisted resolutions still satisfy
  webview-ui's unchanged ranges; verified with --frozen-lockfile).
- Align @ai-sdk/provider to ^4.0.7 in @cline/llms to match the rest of
  the AI SDK family and avoid parallel provider resolutions.

Revalidated: wire repro streams to finishReason=tool-calls, @cline/llms
suite passes incl. the index-1 regression test, all workspaces
typecheck, SDK builds clean.

* fix: restore FeatureSettingsSection.tsx to main's formatting

The branch's pre-commit biome hook (--semicolons=as-needed, --write
--staged) strips a blank line from this file whenever it is staged,
which is how the unintended diff appeared in the merge commit. Commit
with --no-verify to keep the file byte-identical to main; this PR does
not touch the VS Code webview.
2026-08-12 11:30:42 -07:00
John Choi 8437a01906 fix(hub): correlate run start acknowledgments (#13054) 2026-08-12 11:26:16 -07:00
Haley Park 986f0b010b feat(ui): add shared button primitives (#13164)
* feat(ui): add shared button primitives

* fix(ui): disable composed button links

* fix(ui): block disabled composed capture handlers

* fix(ui): protect composed disabled semantics
2026-08-12 10:57:12 -07:00
Haley Park 1be2d20349 refactor(desktop): extract chat message components to messages/ (#13155)
* refactor(desktop): extract chat transcript logic to messages/

Verbatim moves out of chat-messages.tsx (2,415 -> ~1,300 lines), with no behavior changes.

- Extract shared constants, grouping and reasoning helpers, tool summaries, and tool icons into messages/.
- Add unit tests for the extracted pure logic.
- Update test:chat-ui to include tests under messages/.

chat-messages.test.tsx remains unchanged and continues to pass.

* refactor(desktop): extract chat message components to messages/

Moves MessageBubble, ReasoningBlock, ToolMessageBlock, ToolApprovalPanel
(+ formatApprovalTimestamp and the ToolApprovalRequestItem type), and the
image lightbox out of chat-messages.tsx into their own modules under
messages/. Memo wrappers, comparators, and prop contracts are unchanged;
chat-messages.tsx keeps only the ChatMessages orchestration (~780 lines).
chat-messages.test.tsx is untouched and still passes.

* refactor(desktop): extract chat transcript logic to messages/

Verbatim moves out of chat-messages.tsx (2,415 -> ~1,300 lines), with no behavior changes.

- Extract shared constants, grouping and reasoning helpers, tool summaries, and tool icons into messages/.
- Add unit tests for the extracted pure logic.
- Update test:chat-ui to include tests under messages/.

chat-messages.test.tsx remains unchanged and continues to pass.

* refactor(desktop): extract chat message components to messages/

Moves MessageBubble, ReasoningBlock, ToolMessageBlock, ToolApprovalPanel
(+ formatApprovalTimestamp and the ToolApprovalRequestItem type), and the
image lightbox out of chat-messages.tsx into their own modules under
messages/. Memo wrappers, comparators, and prop contracts are unchanged;
chat-messages.tsx keeps only the ChatMessages orchestration (~780 lines).
chat-messages.test.tsx is untouched and still passes.

* refactor(desktop): extract chat message components to messages/

Moves MessageBubble, ReasoningBlock, ToolMessageBlock, ToolApprovalPanel
(+ formatApprovalTimestamp and the ToolApprovalRequestItem type), and the
image lightbox out of chat-messages.tsx into their own modules under
messages/. Memo wrappers, comparators, and prop contracts are unchanged;
chat-messages.tsx keeps only the ChatMessages orchestration (~780 lines).
chat-messages.test.tsx is untouched and still passes.
2026-08-12 10:39:17 -07:00
Saoud Rizwan a56af4efaf fix(telemetry): stop mirroring per-token stream deltas into telemetry (#13180)
* fix(telemetry): stop mirroring per-token stream deltas into telemetry

Gate assistant-text-delta, assistant-reasoning-delta, and tool-updated
runtime events out of the unconditional telemetry.capture mirror in
AgentRuntime.emit. These fire once per streamed token or tool progress
chunk and accounted for ~97% of all agent.* telemetry volume in the
field with no analytical value. Listeners, hooks.onEvent, and the
run-failed sdk.error reporting are unchanged; the gate is a static
Set lookup so no per-event allocation is added.

* refactor(telemetry): inline stream-delta telemetry gate as a switch

Replace the module-level Set constant with case labels directly at the
capture site; same behavior, less indirection.
2026-08-12 18:20:47 +09:00
Saoud Rizwan 10e5176ed8 refactor(ui): one row per tool call, terminal-style commands, and review fixes (#13186)
* feat(ui): styled label parts, terminal-style commands, and patch fidelity fixes

Label segments: ToolSummary gains labelParts ({text, code?}[]) so
consumers can render code-ish segments (file names, commands, queries,
URLs) in a monospace face. Single commands now read like a terminal
prompt — '$ bun test' — and an untruncated single command no longer
duplicates itself as a detail line.

Review fixes folded in:
- apply_patch preserves hunk boundaries: per-hunk oldText/newText on
  ApplyPatchFile and file items (re-diffing concatenated hunks let a
  deletion in one hunk pair with an addition in another), plus action
  metadata — Delete File labels as 'Deleted x' with no phantom diff,
  '*** Move to:' renames display as 'old → new'.
- run_commands accepts every RunCommandsInputUnionSchema shape (single
  entry, bare arrays, top-level {command,args}, {cmd}).
- makeUnifiedDiff treats empty text as zero lines, so creating an empty
  file or deleting all content no longer reports a phantom +1.
- parseWebFetchInput drops non-string urls instead of stringifying
  objects into labels.
- hoisted a double normalizeValue in the unknown-tool fallback.

* refactor(desktop): render each tool call as its own chat row

Drops the consecutive-call grouping ('Read 3 files · Ran 2 commands')
in favor of one row per tool call — each with its own icon, status,
disclosure, and treatment per kind:

- commands read like a terminal: '$ bun run test' in monospace, with
  the captured output in a capped scrollable mono block on expand and
  '$ '-prefixed detail lines for multi-command calls
- edit rows carry mono filenames, the +/- badge, and their pierre
  diffs pre-expanded (one diff per hunk for multi-hunk patches),
  keeping the user-toggle override from the grouped implementation
- reads/searches/fetches keep inline specifics with mono code segments
  via the shared labelParts

Also fixes the test:chat-ui exit-1 regression flagged in review:
@pierre/diffs' custom element calls CSSStyleSheet.replaceSync, which
jsdom lacks — a prototype polyfill in the suite keeps the real
component in the test tree (and the pre-expand assertions meaningful)
while letting the run exit 0. This suite gates ui-publish.yml.

* fix(desktop): keep the thinking indicator up during quiet turn stretches

The indicator only covered the gap right after a user message, so the
turn looked frozen while the model composed its next step — most
noticeably while streaming tool-call arguments, when neither text nor
a tool row is on screen. It now shows whenever the turn is running and
nothing else is visibly active (no streaming text, no in-progress tool
row, no pending approval/question).

* feat(ui): action-first tool labels

Every row leads with the plain action phrase — 'Ran command',
'Read file', 'Edited file', 'Created file', 'Deleted file' — with the
specifics (command, file name, line range) following as a monospace
segment. The mono segment renders at full size; the previous 0.92em
downscale made it look smaller than the surrounding prose.

* fix(desktop): chat polish — indicator alignment, action spacing, no expanded fade

- The Thinking indicator now mirrors the tool-row trigger metrics
  (min-h-7, py-1, gap-2, 16px icon, font-medium, 8px rhythm) so the
  text no longer shifts when the indicator swaps with an arriving
  tool row.
- The copy/fork/timestamp action row sat 4px up into the message text
  above it (-translate-y-1); it now rests 2px below the message block.
- Expanded reasoning/tool panels rendered at 70% opacity with
  hover-to-unfade; expanded content is what the user is reading, so it
  now renders at full opacity.

* feat(ui): violet active rows, gray finished rows, no green hover

Tool-row colors follow activity: running/pending rows (and the row
spinner) carry the brand violet, finished rows settle into
muted-foreground gray, and hover brightens toward the foreground
instead of hue-shifting to the success green. Errors stay red.

Also: maxInlineChars default raised 60 → 200 so real commands stop
getting truncated (the cap is now only a guard against pathological
payloads; layout handles overflow), and expanded editor rows lead with
the fuller file path above the diff, matching read rows.

* refactor(ui): let layout own label overflow instead of char caps

maxInlineChars now defaults to unlimited — labels carry the full
command/task/question text (whitespace collapsed to one line) and
.cline-chat-tool-label ellipsizes at the container edge via CSS
(nowrap + text-overflow) instead of wrapping. The cap remains as an
opt-in for width-constrained surfaces like TUIs. Since the label can
now be visually cut by layout, single-command rows always carry the
full command in their expanded details.

* fix(ui): drop stale green base color on tool triggers

The redesign moved finished tool rows to muted gray and running rows to
brand violet, but a leftover .cline-chat-tool-trigger { color:
var(--success-text) } rule later in the sheet overrode the gray base, so
every settled row still rendered green.

* fix(desktop): give message actions clear separation from message text

2px below the text read as touching; 6px (translate-y-1.5) gives the
copy/fork/timestamp row visible breathing room.

* feat(ui): spinner replaces the tool icon while a call is in flight

The progress ring used to append to the right of the label, so running
rows sprouted chrome instead of reading as one glyph + label. It now
takes the icon slot and fills the same 1rem box, so the label never
shifts when the icon swaps back in on completion.

* fix(desktop): align thinking indicator with the tool row that replaces it

The indicator sits outside the message column, so it already inherits the
conversation gap; its own mt-2 stacked on top and rendered it 8px lower
than the tool row that swaps in.

* style(desktop): message actions match chat text scale in a lighter gray

Copy/edit/restore/fork icons go from 12-14px to the 16px the rest of the
chat chrome uses, the timestamp moves from 11px to text-sm, and the whole
row renders at 70% muted-foreground so it reads as secondary chrome;
hover still brightens to full foreground.

* style(ui): running tool rows share the thinking indicator's gray

Violet-on-running read as a different system than the muted thinking
state it replaces; the spinner alone now signals activity. The progress
ring draws in currentColor so it stays gray on normal rows and red on
error rows without extra rules.

* style(desktop): nudge message actions down 2px and scale them down a step

Actions row moves from 6px to 8px below the message text; icons go
16px -> 14px and the timestamp text-sm -> text-xs after the previous
bump overshot.

* fix(ui): don't unstick conversation follow when content grows

Stick-to-bottom flipped off whenever a scroll event landed between a
content-height jump (tall diff rows mounting) and the resize observer's
re-pin: the handler read the new distance-from-bottom as the user having
left the bottom. Sticking is now released only by an actual upward
scroll and always restored on reaching the bottom, so the transcript
keeps following while rows stream in.

* feat(ui): user message bubbles on a filled brand-violet surface

The card-colored bubble sat too close to the app background to read at
a glance. New brand-violet-surface tokens (deep enough for near-white
text in both themes) fill the user bubble.

* style(desktop): give the conversation bottom padding above the composer

The last message (and its hover actions hanging below) butted against
the composer border.

* fix(desktop): composer keeps its two-line height when unfocused

Collapsing to one row on blur made the input and the conversation above
it jump on every focus change; the focus-tracking state existed only to
drive that resize.

* refactor(ui): simplify AgentAskQuestion and move it to the brand accent

The 'Follow-up question' heading, intro sentence, and box-in-box nesting
made a one-question prompt read like a form. The question now leads the
card directly (icon + text + option buttons) and the accent shifts from
blue to brand violet, with the section still labelled for assistive
tech.

* fix(desktop): pending questions and approvals render at the end of the transcript

They rendered above the whole conversation like a banner, so a follow-up
question appeared at the top of the chat instead of where the
conversation actually is.

* fix(desktop): keep message actions reachable and make hover/focus feedback instant

The 8px offset under a message was a translated gap — dead space that
dropped the parent's :hover midway to the buttons, hiding them before
they could be clicked. The offset is now padding on the actions element
so the hover chain stays unbroken. Also removes the opacity fade on the
actions row and the composer's focus border transition: both read as lag
rather than polish.
2026-08-11 21:00:04 -07:00
Saoud Rizwan a5611e8f6d feat(ui): shared tool-summary module for consistent tool-call chat rows (#13151)
* feat(ui): add shared tool-summary presentation module

Pure, framework-free tool-call presentation logic under
@cline/ui/components/agent-chat/tool-summary: buildToolSummary and
buildGroupedToolLabel turn raw {toolName, input, result} payloads into
rich row labels (file names with line ranges, inline commands, search
queries, URLs), per-item details, +/- diff counts, per-file unified
diffs (editor old/new text and apply_patch envelopes), team_* labels,
and MCP-aware output text extraction. Merges the desktop app's
buildToolSummary layer with the CLI's tool-parsing/diff utilities so
every @cline/ui consumer renders tool rows consistently.

Exports the new subpath from package.json, extends the packed-tarball
smoke test to cover it, documents the boundary change in ADOPTION.md,
and bumps the package to 0.2.0-next.3.

* refactor(desktop): adopt shared tool-summary for chat tool rows

Replaces ~950 lines of app-local tool extraction (buildToolSummary,
teamSummary, parsers, grouped-label logic) in chat-messages.tsx with
the @cline/ui tool-summary module. Desktop tool rows gain single-call
specifics inline (Read app.tsx (10-80), Ran bun test, Edited util.ts
with +/- badge), line ranges on reads, shortened paths with directory
context in expanded details, per-file unified diffs in the expanded
panel, and grouped labels joined with a middot. Detail keys switch to
index-based to fix duplicate-line key collisions. Icons re-key on the
shared ToolKind classification.

* fix(ui): stop fabricating line positions in fragment tool diffs

Editor str_replace payloads carry old_text/new_text as fragments of the
file, but makeUnifiedDiff treated them as whole files and emitted hunk
headers anchored at line 1, mislocating the change in expanded edit
rows (Greptile P1 on #13151). Fragment diffs now use a neutral
'@@ … @@' separator; only whole-file content (editor create,
apply_patch Add File sections) keeps real hunk positions.

File items also expose the raw oldText/newText (reconstructed from
hunks for apply_patch) plus a fragment flag, so rich diff renderers
can consume the texts directly instead of re-parsing unified output.

* feat(ui): render tool-row edit diffs with @pierre/diffs

Adds @cline/ui/components/agent-chat/tool-diff exporting ToolFileDiff,
a thin wrapper over @pierre/diffs (optional peer dependency) that
renders a tool-summary file item as a syntax-highlighted, theme-aware
unified diff. Fragment diffs hide line numbers instead of showing
misleading ones. The desktop chat renders edit diffs through it, and
tool groups containing an edit diff now open pre-expanded so the diff
is immediately visible.

ADOPTION.md reframes the shared-module story: extracting presentation
logic products would otherwise duplicate is the direction @cline/ui is
headed, with tool-summary and tool-diff as the first two modules. The
packed-tarball smoke test covers the new subpath in both consumers.

* fix(ui): blend tool diffs into the app surface

Two polish fixes to ToolFileDiff from design review:

- Normalize trailing newlines on both sides before diffing so tool
  payload fragments (which rarely end in a newline) don't litter every
  diff with 'No newline at end of file' markers.
- Map @pierre/diffs' background hooks (--diffs-light-bg/--diffs-dark-bg)
  to the host app's --background token (stock white/black fallback),
  so the diff surface and all its color-mixed tints (context lines,
  gutters, separators) derive from the app background instead of
  pierre's pure white/black. Overridable via a new background prop.

Storybook's ToolSummaries story now renders file items through
ToolFileDiff pre-expanded (matching the apps) and adds a multi-file
apply_patch fixture.

* fix(desktop): pre-expand tool groups when edit diffs arrive mid-stream

defaultOpen only applies at mount, but a streaming tool group mounts
with its first (often read) call and gains the edit later, so live runs
never saw the promised pre-expanded diff. Drive the disclosure with
controlled state that opens when a file diff first appears, unless the
user has toggled the row themselves. Covers the streaming path with a
rerender test.
2026-08-11 17:54:52 -07:00
Bee 66883f584c fix(desktop): top-align welcome chat input (#13174)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-11 14:41:41 -07:00
Haley Park e370732545 refactor(ui): migrate fonts to Inter and Geist Mono (#13142)
* chore(ui): replace font dependencies

* refactor(ui): migrate shared typography tokens

* refactor(ui): adopt Inter and Geist Mono in apps

* fix(hub): preserve variable font weight tokens

* feat(ui): tune font weights for dark mode

* docs(ui): add font migration screenshots

* (chore)ui: misc typography adjustments

* fix(hub): make dark-mode font-weight overrides take effect

Tailwind's @theme inline bakes literal values into utilities, so the
.dark --font-weight-* overrides were dead code and dark mode rendered
the heavier light-mode weights. Declare the weights in :root instead so
font-* utilities keep their var() references, matching the @cline/ui
tokens approach. Also rewrap --font-mono to satisfy biome format.

* fix(ui): restore light-mode semibold to 640 and pin weight scales in test

The PR intent is a 480/560/640/640 light scale with 400/500/600/600
dark overrides, and the Hub already uses 640; tokens.css had drifted to
600 for light semibold. Regenerate scoped-tokens.css and assert both
the light and dark weight scales in the theme contract test.

* chore(desktop): remove stray double space in provider header class

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-11 14:39:57 -07:00
Haley Park ee4adda2da refactor(desktop): extract chat transcript logic to messages/ (#13153)
Verbatim moves out of chat-messages.tsx (2,415 -> ~1,300 lines), with no behavior changes.

- Extract shared constants, grouping and reasoning helpers, tool summaries, and tool icons into messages/.
- Add unit tests for the extracted pure logic.
- Update test:chat-ui to include tests under messages/.

chat-messages.test.tsx remains unchanged and continues to pass.
2026-08-11 14:33:27 -07:00
Saoud Rizwan 651829b24a chore(cli): release v3.0.53 2026-08-11 11:32:41 -07:00
Saoud Rizwan 00ba2ff7da chore(sdk): release v0.0.73 2026-08-11 11:00:44 -07:00
Mikołaj Kondratek 3f03159737 fix(vscode): don't discard a successfully refreshed Cline token after expiry (#13139)
getAuthToken captured expiresAt before refreshing, then validated the new
token against that stale value. When the old token was already past expiry
(not just inside the 5-minute buffer), a successful refresh was thrown
away and null returned, so the first call after long idle failed despite
valid credentials. Re-read the expiry from the refreshed auth info.
2026-08-11 18:23:12 +02:00
Mikołaj Kondratek 3087bd3d32 fix(hub): recoverable agent errors must not end the turn in the dashboard (#12962)
* fix(hub): don't forward recoverable agent errors to dashboard peers

Recoverable error events are in-run notices, not turn outcomes: the
MistakeTracker emits one for every recorded mistake (e.g. a plan-mode
guard-blocked run_commands call) while the run continues. The hub
dashboard forwarded every error event to peers, so the webview dropped
out of the sending state and appended an error row mid-turn — the same
host bug fixed for VS Code and the CLI in #12953.

Gate the forward on recoverable, matching those hosts: the tool failure
is already shown inline via the failed tool_event, and the turn's
outcome stays decided by how it actually ends (turn_done or a
non-recoverable error). Recoverable errors are logged server-side.

* fix(hub): forward recoverable flag to peers instead of filtering server-side

Per review: the server is a translation layer between agent events and
the webview protocol, so it should not embed display policy or console
logging. Forward every agent error with its recoverable flag on the
peer message and let each peer decide — the webview keeps recoverable
errors out of the transcript and keeps the turn state, matching how the
CLI gates display on the same flag while the information stays
available to any peer that wants it.
2026-08-11 18:11:40 +02:00
Bee 9b59090967 fix(desktop): reconnecting to stale managed Hub daemons (#13145)
* fix(core): replace stale managed hub daemons

* fix(core): fingerprint hub runtime builds

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-11 01:34:00 -07:00
Saoud Rizwan 7e31fb9e0d chore(vscode): prepare 4.1.8 release 2026-08-10 20:03:53 -07:00
John Simone e0eb0167da feat(vscode): add Fable 5 + custom model IDs to Vertex; drop global-region picker filter (#12461)
* add custom model selection to the vertex provider

* fix race conditions from PR review

* fix linter warnings

* fix test failures

* refactor(vscode): drop Vertex global-endpoint picker filtering

The SDK catalog is live (models.dev), so a static host allowlist of
global-endpoint-capable models lags every model launch and silently hides
new models from users on vertexRegion=global. Remove the allowlist, the
host override that injected supportsGlobalEndpoint, and the picker filter;
show the full catalog for every region.

An unsupported pick now fails loudly at request time: map Vertex's
'model not available in region: global' (and Google's Publisher Model
locations/global not-found body) to recovery guidance in the error row.

Also drop Anthropic's universal pricing from the Vertex Fable 5 overlay —
Vertex bills region-dependently, so the copied price understated recorded
cost; the record now carries no pricing instead of a wrong one.

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-10 19:58:20 -07:00
Mikołaj Kondratek d5748b2939 fix: remove stale Double-Check Completion feature tip (#13147)
* fix: remove stale Double-Check Completion feature tip

The rotating feature tips still told users to enable "Double-Check
Completion" in settings, but that toggle was removed in the new UI —
the Features section now offers Auto Compact, Feature Tips, Background
Edit, Checkpoints, Worktrees and Hooks. Following the tip sent users
searching the settings panel for something that isn't there.

Drop the tip. The remaining ten were checked against the current UI and
all still hold, including the "Settings → Features → Feature Tips" path.

* chore: remove dead CLI settings e2e page object and orphaned test

`page-objects/settings.ts` asserted the CLI settings Features tab shows
"Double-check completion" — the same removed setting behind the stale
feature tip. Nothing in the live tui-test suite (apps/cli/src/tests)
imported it; only chat.ts and auth.ts page objects are in use.

Its one importer, apps/vscode/tests/e2e/cli/interactive.test.ts, is a
leftover from the pre-2026-06-02 SDK migration squash: all three of its
imports resolve to files that don't exist, there's no tui-test config in
that tree, and no npm script runs it. It cannot execute.
2026-08-11 00:54:41 +02:00
Mikołaj Kondratek ffd6a6b1db fix: respect user max output tokens in compaction summarizer requests (#13137)
* fix: respect user max output tokens in compaction summarizer requests

The compaction summarizer hardcoded max_tokens to 1024 and the VSCode host
never mirrored the user's Max Output Tokens onto providerConfig, so summary
requests were always capped at 1024 tokens. Reasoning models can spend that
entire budget thinking; the reasoning stream is discarded, so no summary
text arrives and compaction is skipped on every attempt.

- Mirror maxTokensPerTurn onto providerConfig.maxOutputTokens in the VSCode
  session factory so consumers that build handlers straight from it (the
  compaction summarizer) honor the user's setting, matching the CLI.
- Resolve the summarizer output budget from explicit config, then model
  info, then knownModels, before the default; raise the default to 4096.
- Log a diagnostic warning (reasoning chars, incompleteReason, likely
  cause) when the summarizer returns no summary text instead of silently
  skipping.

* fix: clamp summarizer default output budget by model metadata instead of adopting it

Model maxTokens is reported capability, not a product default: without an
explicit configuration the summarizer now requests the 4096 default, lowered
by model metadata when the model reports less, never raised by it. Explicit
values still win as-is.
2026-08-11 00:20:45 +02:00
cline-cloud[bot] 51784a3bf1 docs: add Qwen3.8 Max to ClinePass model list and reference pricing (#13144)
Co-authored-by: Cline <cline@users.noreply.github.com>
2026-08-10 14:52:43 -07:00
Saoud Rizwan 149abb0ddb feat(vscode): remove YOLO mode setting, migrate old users to auto-approve all (#13126)
* feat(vscode): remove YOLO mode setting, migrate old users to auto-approve all

The SDK extension's YOLO toggle was cosmetic: nothing in the approval
path read it, so runs were silently governed by the per-action
auto-approval settings underneath (cline/cline#13114). Instead of
keeping a parallel override system, remove the setting entirely and
make the auto-approve menu the single source of truth:

- drop yoloModeToggled (and the equally dead autoApproveAllToggled)
  from state keys, settings handlers, state posts, telemetry, the
  remote-config yoloModeAllowed transform, and the settings protos
  (field numbers reserved)
- remove the Yolo Mode toggle from Settings -> Features (the whole
  Experimental section, it was the only entry) and the
  "Auto-approve: YOLO" AutoApproveBar takeover
- add a v3 storage migration that folds a previously-enabled YOLO /
  auto-approve-all toggle into autoApprovalSettings by enabling every
  action, so previously-unattended setups keep running unattended;
  the dead keys are cleared from the file store

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

* refactor(vscode): keep dead yolo keys in place instead of clearing them

Current builds never read the removed keys (the state loader only visits
known keys), so deleting them buys nothing - and the file store is shared
with older builds that still know them, so clearing would flip YOLO off
for a user who downgrades. Same downgrade-safety rule as the v1 export.

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

* chore(vscode): rename wasUnattended to shouldEnableAllActions in yolo migration

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

* chore(vscode): drop dead toggleActModeForYoloMode and stale yoloModeAllowed comment

The method was a legacy-controller carryover nothing called, and it set
the mode without rebuilding the session, which is wrong for the SDK
architecture. The comment cited yoloModeAllowed as a live remote-config
example; it no longer maps to anything.

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

* chore(vscode): refresh checked-in proto descriptor_set.pb

The tracked descriptor set had not been regenerated since the repo
move and still advertised long-changed schemas (including the removed
yolo_mode_toggled fields) to gRPC reflection clients. Sync it with the
output of bun run protos.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-09 17:15:37 -07:00
Saoud Rizwan b3cee3f973 chore(desktop): release v0.0.11 2026-08-08 20:53:18 -07:00
Saoud Rizwan c68f553856 chore(vscode): prepare 4.1.7 release 2026-08-08 20:38:09 -07:00
Saoud Rizwan fd794ce3be chore(cli): release v3.0.52 2026-08-08 19:34:11 -07:00
Saoud Rizwan f5f1071af2 chore(sdk): release v0.0.72 2026-08-08 19:00:03 -07:00
Saoud Rizwan 4540390096 desktop: hide git jargon for non-git folders (CLIENTS-100) (#13059) 2026-08-08 15:57:00 -07:00
Saoud Rizwan b590e14b91 desktop: paste clipboard images into the composer (CLIENTS-78) (#13057)
* desktop: paste clipboard images into the composer as attachments (CLIENTS-78)

Pasting a screenshot into the composer did nothing: only drag-and-drop
and the paperclip file picker fed the attachment pipeline. Add an
onPaste handler on the composer textarea that extracts image files from
the clipboard, renames them to timestamped pasted-image-*.png files, and
routes them through the existing onAttachFiles flow. Text pastes are
untouched.

* desktop: only extract clipboard images in formats message serialization supports

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 15:56:27 -07:00
Saoud Rizwan 54cc156089 desktop: context-aware welcome suggestions for non-code folders (CLIENTS-98) (#13060)
* desktop: context-aware welcome suggestions for non-code folders (CLIENTS-98)

* desktop: treat pending branch discovery as its own state for welcome cards

The welcome-card classifier read the "no-git" sentinel as a confirmed
non-repo, but page.tsx also used that value for the initial state and
while a workspace switch was awaiting branch discovery, so a git repo
could briefly show the plain-folder cards. Branch state is now null
while discovery is pending: the welcome screen shows no cards until the
folder is classified, and chat-mode cards (which never depend on git
state) still show immediately. Other branch consumers keep the string
contract via a "no-git" fallback.

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

* desktop: carry nullable branch state to all consumers

Propagate the pending-discovery null through ChatInputBar,
WorkspaceSelector, and the welcome workspace controls instead of
coercing to "no-git" at the page boundary, so only display leaves
fall back and the welcome classifier is the single consumer that
distinguishes pending from confirmed non-repo.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 15:45:29 -07:00
Saoud Rizwan 6c599d18c3 desktop: surface folder picker failures and add manual path fallback (CLIENTS-73) (#13056)
* desktop: never let 'Add project…' fail silently; add manual folder path entry (CLIENTS-73)

- sidecar picker tries zenity then kdialog on Linux and throws a descriptive
  error when neither exists, instead of returning null (indistinguishable
  from user cancel); picked paths are trimmed of trailing separators
- picker failures now surface as visible error messages in both workspace
  selectors, with a manual path-entry fallback (typed absolute or ~ paths
  in the search box offer an 'Open folder' action)
- failed workspace switches (invalid/nonexistent paths) show an inline
  error instead of silently doing nothing
- validate_workspace_directory expands ~ and returns the resolved path

* desktop: keep workspace menu search/error state through catalog refreshes

The welcome-screen workspace picker reset its search text and error
message whenever onRefreshWorkspaces changed identity, which happens on
every session-history poll. Typing a path or reading an inline error
raced against the timer: the menu would silently wipe mid-interaction.
Hold the refresh callback in a ref so the reset only runs when the menu
actually opens.

* desktop: format welcome-workspace-controls test

* desktop: distinguish picker launch failures from user cancellation

A zenity/kdialog rejection with a non-ENOENT spawn error (EACCES, EMFILE,
ENOMEM) or a crash signal was classified as a user cancel, which skipped
the kdialog fallback and suppressed the inline error - recreating the
silent no-op this branch is meant to eliminate. Only a clean exit code 1
from a dialog that actually opened now counts as cancellation; broken
backends fall through to the next candidate and surface a descriptive
error otherwise. Picker logic moved to sidecar/workspace-picker.ts with
an injectable exec so the classification is unit-tested.

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

* Classify picker launch failures separately from user cancellation

zenity/kdialog failures like EACCES, EMFILE, or ENOMEM were treated as
user cancellation, suppressing the kdialog fallback and the inline
manual-entry error. Only a clean exit code 1 now counts as a cancel;
any other failure falls through to the next backend or throws the
picker-unavailable error. Picker logic moved to sidecar/folder-picker.ts
with an injectable exec so the classification is unit tested.

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

* Revert "Classify picker launch failures separately from user cancellation"

This reverts commit 24d27a004d.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 15:43:52 -07:00
Saoud Rizwan 513aacc0e6 fix(core): full-stop semantics and abort-window queue edits for surviving queues (#13100)
* fix(core): preserve queued prompts across user-initiated aborts

Pressing stop while prompts were queued silently destroyed them:
abort() called clearAborted(), which emptied the pending prompt queue
with no way to recover the typed input. The prompts vanished from the
UI, were never sent, and left no trace in session artifacts.

Aborting now only stops the in-flight turn. Queued prompts stay in the
queue and drain once the abort settles, matching the drain behavior
that already existed for self-aborted turns (loop detector / mistake
limit). The thrown-abort path (completeAbortedInteractiveTurn) now
schedules the same drain that runTurn schedules for turns resolving
with an aborted finish.

* fix(core): full-stop semantics and abort-window queue edits for surviving queues

Follow-up to the queued-prompt survival change: aborting a user turn keeps
the queue and auto-runs it, but two gaps remained.

1. No full stop: aborting a queue-initiated turn also kept draining, so
   every Escape consumed one queued prompt and started a fresh provider
   call - a session with queued messages could never be brought to rest.
   Aborting a drained turn now discards the remaining queue: the first
   Escape skips to your queued follow-ups, a second Escape stops the
   queued work too.

2. Queue operations were still rejected while an abort settled: a prompt
   typed right after Escape was silently dropped, and queued prompts were
   briefly uneditable and undeletable even though they were about to
   auto-run. enqueue/update/delete now work during the abort window;
   scheduleDrain/drain still wait for the abort to settle.
2026-08-08 12:37:18 -07:00
Saoud Rizwan ff2f860941 test(core): pin abort + hub-restart durability, and title seeded sessions (#13097)
* test(core): cover abort + host restart + seeded recovery durability

Adds an e2e regression guard for the reported "cancel a turn, lose the
conversation" failure: a cancelled turn, a daemon restart, a
client-side recovery seeded from disk, and a second restart before that
replacement ever runs a turn. Reverting the eager seeded-history
persistence makes the final read come back empty.

Materializing a seeded session at start also left its history row with
no prompt and no title, since there is no first prompt to derive one
from. Seed the title from the inherited transcript using the same
inference listSessionHistory hydration applies, so forks and recoveries
stay identifiable in unhydrated surfaces too.

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

* fix(core): retitle seeded sessions from their first user prompt

Eagerly-materialized seeded sessions kept the interim transcript-
inferred title forever, a behavior change from pre-eager persistence
where a fork's history row was titled by the first post-fork prompt.

The interim title now only covers the window where no turn has run
(previously those rows were simply absent), and the first user prompt
after the seed backfills the row's prompt and retitles it — unless the
user renamed the session in the meantime, in which case only the prompt
column is backfilled. The resident manifest and session metadata are
updated in step so the end-of-turn usage-metadata merge cannot clobber
the title back through a stale in-memory fallback.

The e2e mock's updateSession now mirrors the real persistence-service
contract (row + manifest file), and the durability e2e covers both the
retitle and the rename guard; removing the retitle call fails the
'now add tests' assertion.

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

* refactor(core): collapse seeded-session titling to the old mechanism

The interim transcript-derived title, retitle flags, rename comparison,
and resident-manifest syncing existed only to title forks that never
run a turn - a new nicety, not parity. Dropping it collapses the whole
design back to what rows did before eager persistence: the persistence
service derives the title from the prompt when a row gains one, so the
host only needs to backfill the promptless row with the first user
prompt via updateSession. Renames win automatically because the service
preserves an existing title when no explicit title is passed.

Net production change vs main is a single 20-line backfill block in
executeTurn. The e2e mock's updateSession now models the service's
title semantics (explicit title wins, existing title preserved,
untitled rows derive from prompt), and the durability e2e asserts the
raw row stays untitled until first prompt while history hydration
infers a display title from the transcript.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 12:30:30 -07:00
Saoud Rizwan 62a6b5a0b2 fix(core): preserve queued prompts across user-initiated aborts (#13090)
Pressing stop while prompts were queued silently destroyed them:
abort() called clearAborted(), which emptied the pending prompt queue
with no way to recover the typed input. The prompts vanished from the
UI, were never sent, and left no trace in session artifacts.

Aborting now only stops the in-flight turn. Queued prompts stay in the
queue and drain once the abort settles, matching the drain behavior
that already existed for self-aborted turns (loop detector / mistake
limit). The thrown-abort path (completeAbortedInteractiveTurn) now
schedules the same drain that runTurn schedules for turns resolving
with an aborted finish.
2026-08-08 12:20:08 -07:00
Saoud Rizwan 0caf617b50 fix(core): keep a hung MCP server from taking down session creation (#13086)
* fix(core): keep a hung MCP server from taking down session creation

A stdio MCP server that never finishes initializing used to hold its
connect open for the full DEFAULT_MCP_CONNECT_TIMEOUT_MS (doubled across
the newline/framed attempts). MCP tool discovery runs on the
session.create critical path, so that wait blew past the 30s hub command
timeout and the CLI tore the whole interactive session down instead of
just skipping the bad server.

- Bound MCP tool loading during session build with a startup budget that
  is safely under the hub command timeout. Servers that connect in time
  contribute their tools; slower/hung servers are skipped for the session
  (their error still surfaces via the MCP manager) instead of failing
  session creation. Budget is overridable via CLINE_MCP_STARTUP_BUDGET_MS
  for tests.
- Add StdioMcpClient.close() (and optional McpServerClient.close) that
  marks the client disposed so an in-flight connect() aborts its retry
  loop instead of respawning the framed fallback.
- Dispose the manager by closing clients up front, outside the per-server
  operation locks, so a server hung in initialize can no longer stall
  teardown for the full connect budget.

Adds regression tests covering both the non-blocking build and prompt
disposal while a client is hung in connect().

* refactor(core): simplify hung-MCP-server fix to a startup budget

Replace the bespoke per-server race/tracking in loadConfiguredMcpTools
with a small withStartupBudget() wrapper around the existing
Promise.allSettled: a server that exceeds the budget becomes a normal
rejection that the existing loop already logs and skips. The connect
budget, MCP settings display (initialize timeout 30s), and the rest of
the loader are left untouched.

The client close()/manager.dispose() cleanup is kept minimal: it is what
lets teardown abort a still-in-flight connect instead of blocking on the
per-server lock (and clears the pending request timer).

* fix(mcp): cap the default initialize budget at 3s to protect session creation

Supersedes the startup-budget approach on this branch with the simple
constant fix.

MCP initialize runs on the session.create critical path, which the hub
caps at 30s, and connect() can spend the budget twice (newline then
Content-Length framing). The 30s default from #13067 meant a server that
never initializes held session.create for up to 60s, so the hub RPC
timed out and the CLI tore the whole session down and exited.

Return to the pre-#13067 shape with a bigger probe: 3s instead of 1.5s.
That still covers the ~2s starters the old probe killed (#13035) and
keeps the worst case at ~6s per server, far under the hub deadline.
Genuinely slow starters (JVM-based servers like Oracle SQLcl) now need
an explicit timeout in cline_mcp_settings.json, which continues to
override the default in either direction.

Tests: update the slow-start regression tests to the new policy (2s
connects by default, 4s connects with a configured timeout), refresh the
displayed initialize-timeout assertions, and add an invariant test that
keeps the doubled default well under HUB_DEFAULT_COMMAND_TIMEOUT_MS so
the budget cannot silently creep past the session deadline again.
2026-08-08 12:18:11 -07:00
Saoud Rizwan 930575991d fix(desktop): stop opening a session from replacing the remembered model (#13091)
* fix(desktop): stop opening a session from replacing the remembered model

The composer's ModelSelector mirrored every provider/model prop change
into the remembered last selection (localStorage), which seeds new
sessions via getInitialChatConfig(). Opening an existing session drives
those props to that session's config, so merely viewing an old session
silently replaced the user's explicitly picked default model.

The remembered selection is now written only from the explicit picker
handlers (provider select and model select). Passive prop changes, such
as opening a session, no longer touch it.

* fix(desktop): re-seed remembered provider/model on chat reset

reset() kept the previous config's provider/model and only cleared the
session ID, so a chat pane that had hydrated a historical session could
carry that session's model into the next chat. Re-seed provider/model
(and apiKey when the provider changes) from the remembered defaults --
the same source a freshly mounted thread uses -- so reset and remount
behave identically.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 12:10:39 -07:00
Saoud Rizwan e40d7d44ae fix(desktop): stop treating leftover plugin install dirs as installed (#13095)
* fix(desktop): stop treating leftover plugin install dirs as installed

isOfficialPluginInstalled() only checked that the marketplace install
directory existed. A failed or interrupted install can leave that
directory behind with no plugin inside, and the next install attempt
then short-circuited with a fake 'already installed' success: the
marketplace button flipped to Uninstall with no error while nothing
actually worked, and the installed-entries listing kept reporting the
broken entry as installed.

The check now requires a loadable plugin module inside the directory
(via discoverPluginModulePaths) before reporting the entry as
installed, so partial directories fall through to a real install
attempt whose outcome is surfaced to the UI.

* fix(desktop): reclaim leftover partial plugin install dirs with --force
2026-08-08 12:06:35 -07:00
Saoud Rizwan e973ce4f33 fix(cli): make queued message text readable on light theme TUI (#13098)
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 12:00:50 -07:00
Saoud Rizwan 4f25692d70 fix(desktop): canonicalize diff panel paths against the session cwd (#13092)
* fix(desktop): canonicalize diff panel paths against the session cwd

Tool calls address the same file inconsistently across a session: one
edit uses a workspace-relative path (journal.txt), a later one the
absolute path (/tmp/ws/journal.txt). mergeToolDiffs keyed entries by the
raw string, so the same file was listed twice in the diff panel with
split +/- counts and inconsistent naming, most visibly after git was
initialized mid-session and the model switched to absolute paths.

Diff paths are now canonicalized against the session cwd before
merging: entries for the same file collapse into one, files inside the
cwd display as workspace-relative paths, and files outside it display
their resolved path. Without a cwd the previous raw-key behavior is
kept.

* style: collapse editorReplaceEvent signature per biome format

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

* fix(desktop): collapse dot segments and keep root cwd in diff path keys

* fix(desktop): compare Windows diff path keys case-insensitively

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-08 11:55:58 -07:00
Saoud Rizwan b0bba2e5d6 fix(vscode): hide View Changes on completion rows until there are changes to show (#13096)
* fix(vscode): hide View Changes on completion rows until there are changes to show

The button previously always rendered on the latest completion row, faded
and disabled when the count check came back 0 - which covers both 'nothing
changed since your last message' and 'no checkpoint to compare against'
(non-git workspace, repo with no commits, comparison failure). A dead
button with a misleading tooltip in the non-git case is worse than no
button: now the row renders nothing until the host confirms there are
actual changes, and the button is always enabled when shown.

* fix(vscode): reset View Changes state when showViewChanges toggles

Greptile review: a stale positive hasChanges from a previous evaluation
could flash the button before the host confirms the new comparison when
showViewChanges flips false and back true on the same row. Reset to
'still checking' whenever the effect re-runs.
2026-08-08 11:41:41 -07:00
Saoud Rizwan a6e2c0c431 fix(core): never run a foreign compiled plugin-sandbox bootstrap for a source host (#13094)
* fix(core): never run a foreign compiled plugin-sandbox bootstrap for a source host

When @cline/core runs from source (e.g. the desktop hub daemon in dev)
with CLINE_WRAPPER_PATH set, resolveBootstrap() picked the compiled
plugin-sandbox-bootstrap.js from a separately installed CLI platform
package (such as a published version sitting in the package-manager
cache) before falling back to the source bootstrap. That bootstrap
resolves modules against the other installation's layout, so every
plugin failed to load with "Cannot find module '@cline/core'" - and
the settings pipeline swallowed the failure, leaving Settings > Tools
showing "No plugin tools found" and plugins showing no contributions
even though the same plugins loaded fine in chat sessions.

Bootstrap selection now prefers, in order: a compiled bootstrap next to
this module (always matches the host build), the source bootstrap when
the host runs from source, and only then wrapper/executable-derived
bootstraps - which remain the path for compiled binaries where
import.meta points inside the bunfs bundle.

* chore(core): restore untouched settings-service formatting
2026-08-08 11:23:25 -07:00
Saoud Rizwan d011d049a1 fix(core): keep session context durable across aborts and hub restarts (#13078)
* fix(core): keep session context durable across aborts and hub restarts

Users on slow self-hosted endpoints reported sessions losing their entire
conversation after cancelling a long-running request: the TUI still showed
the transcript, but the next turn greeted them like a brand-new session.

Root cause is a stack of two failures:
1. The hub daemon exits on any unhandled rejection that is not an
   AgentRuntimeAbortError, so a floating abort-family rejection from a
   cancelled provider stream kills every resident session.
2. When the CLI recovers the missing session it rebuilds from the persisted
   messages file - but aborting a turn never flushed the transcript, and
   lazy session persistence (SDK 0.0.70) kept seeded history (mode-switch
   restarts, forks, previous recoveries) memory-only until the first
   completed turn. Recovery then seeds an empty session: silent context wipe.

Fixes:
- completeAbortedInteractiveTurn now flushes the transcript to disk, so an
  aborted exchange survives a hub restart.
- Sessions started with initialMessages persist them (and any compaction
  sidecar) immediately; brand-new empty sessions stay lazy, so closing an
  unused runtime still leaves no empty history entry.
- The hub daemon ignores abort-family unhandled rejections (DOMException
  AbortError, Node ABORT_ERR) the same way it already ignores
  AgentRuntimeAbortError, instead of exiting with every session resident.

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

* fix(core): write seeded history atomically with session materialization

Greptile review flagged a residual crash window in the seeded-session
persistence: ensureSessionPersisted created the session row (with an empty
messages file) and only then called persistSessionMessages, so a crash
between the two left a discoverable session whose seeded history was gone.

Close the window by threading initialMessages/systemPrompt through
createRootSessionWithArtifacts: the messages artifact is now written with
the seeded transcript before the session row is committed, so every crash
point leaves either nothing discoverable or complete data. The follow-up
persistSessionMessages call at session start is gone; the seed travels
inside session materialization.

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

* Revert "fix(core): write seeded history atomically with session materialization"

This reverts commit 5a7e0b37f1.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 21:44:40 -07:00
Saoud Rizwan e09afced69 fix(core/hub): report queued-turn failures as run.failed (#13074)
Turns drained from the pending-prompt queue resolve their errored
AgentResult inside PendingPromptsController.drain(), which discards it,
and the legacy 'error' agent event had no projection in the hub's
session-event projector — so a failed queued turn never produced any
terminal hub event. Interactive clients (e.g. the desktop app) hung on
'Thinking...' with no error shown.

The projector now publishes run.failed (with the error text and a core
session snapshot) for non-recoverable lead-agent error events, but only
when no RPC-driven turn is awaiting sessionHost.runTurn for that
session — the awaiting run.start handler already publishes the
authoritative terminal event, so this avoids double-reporting a turn
that resolves through both paths.
2026-08-07 20:52:01 -07:00
Saoud Rizwan 3f83be51a2 feat(vscode): fade View Changes button until changes since last message are confirmed (#13076) 2026-08-07 20:16:15 -07:00
Saoud Rizwan 1efe5577e1 fix(core/cli): drain queued prompts after self-aborted turns and surface the stop (#13061)
* fix(core/cli): drain queued prompts after self-aborted turns and surface the stop

When a run ends with finishReason "aborted" without a user abort request
(loop detector hard escalation or the consecutive-mistake safety stop),
runTurn skipped the pending-prompt drain, stranding user-queued messages
forever, and the CLI rendered nothing - the task appeared to silently
stop with queued messages never consumed (#13030).

- core: schedule the drain after every completed turn, including
  aborted/error finishes. User-initiated aborts are unaffected because
  abortSession() already clears the queue, and drain() stops after one
  failed send so an erroring provider cannot spin the queue.
- cli: when a turn comes back aborted without the user having requested
  an abort, append a "Task stopped before completion." status entry
  instead of ending the turn silently.

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

* fix(core): hold queued prompts on error finishes instead of consuming them

Addresses the Greptile P1 review on #13061: a drained prompt whose turn
resolved with finishReason "error" returned normally, so the
exception-only requeue path treated the send as successful - the failed
prompt was consumed and draining continued firing the remaining queue
into a failing provider.

- drain() now stops the chain when a drained send resolves with an
  error finish. The errored entry itself is not requeued (its turn ran:
  the prompt is in the conversation and the error is surfaced), but the
  rest of the queue is held.
- runTurn() no longer schedules a drain after "error" finishes (the
  skip is removed only for "aborted", which is the #13030 fix).
  Held prompts still drain via the existing enqueue/update/delete
  triggers or the next successful turn.
- Two new unit tests cover both layers.

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

* revert(cli): drop the 'Task stopped before completion' status line

Keep the change scoped to the queue-drain fix in @cline/core. The CLI
no longer prints a notice for non-user-initiated aborted finishes;
apps/cli is back to parity with main. When messages are queued, the
drain itself makes the stop visible (the queued message runs); richer
stop-reason surfacing can be a follow-up.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 19:27:47 -07:00
Saoud Rizwan 9cbc24d6e5 Restore "View Changes" on completion rows using SDK checkpoints (#13072)
* fix(core): read untracked-at-snapshot files from stash third parent in checkpoint diff

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

* feat(vscode): restore View Changes button on completion rows via SDK checkpoint diff

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

* refactor(vscode): integrate View Changes as a footer inside the completion card

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

* style(vscode): place the View Changes button inside the completion card

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 18:11:25 -07:00
Saoud Rizwan 551286d33b fix(cli): preserve binary MCP payloads in expanded TUI tool output (#13071)
* fix(cli): preserve binary MCP payloads in expanded TUI tool output

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

* simplify to minimal payload-preserving fix

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 18:10:28 -07:00
Saoud Rizwan 361ac90978 fix(llms): route LiteLLM through Chat Completions instead of the Responses API (#13053)
The litellm builtin spec pinned protocol: "openai-responses", so every
request went to POST {baseUrl}/responses. Self-hosted LiteLLM proxies
commonly implement only /chat/completions, so all prompts failed with
404 Not Found on the SDK path (CLI, and now the Next extension bundle).

Drop the override so litellm inherits the openai-compatible family
default (openai-chat -> /chat/completions), matching every sibling
openai-compatible builtin and the Legacy extension behavior.

Fixes #13003, fixes #10781
2026-08-08 02:06:46 +02:00
Saoud Rizwan 4eb7402334 fix(cli): render MCP tool result text instead of escaped JSON in TUI (#13066)
* fix(cli): render MCP tool result text instead of escaped JSON in TUI

MCP tools return {content: [{type: "text", text}]} which
extractFullOutputText JSON-stringified, escaping newlines into one giant
line that word-wrapped across the whole terminal and never triggered the
line-based collapse. Extract the text parts with real newlines so the
existing collapse works.

Fixes #13038

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

* fix(cli): keep placeholders for non-text blocks in mixed MCP results

Addresses Greptile review on #13066: text-only filtering silently
dropped image/resource/audio blocks from mixed MCP content. Render them
as [type] placeholders instead.

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

* fix(cli): surface non-text MCP block metadata in TUI output

Extract embedded resource text, and include resource/resource_link URIs
and image/audio mime types in placeholders so expanded mixed MCP
results keep identifying metadata.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 17:05:22 -07:00
Saoud Rizwan ffb61a865f fix(mcp): give unconfigured stdio servers a 30s initialize budget (#13067)
The stdio MCP client gave servers without a configured `timeout` only
1.5 seconds to answer initialize before killing the process, so
slow-starting servers (e.g. Oracle SQLcl's JVM-based `sql -mcp`) could
never load and were silently skipped at session start.

Raise the default connect budget to 30s, in line with the startup
budget other MCP clients allow. A configured `timeout` still overrides
it in either direction, dead commands still fail fast through the spawn
error/exit path, and the newline -> Content-Length framing fallback is
unchanged.

Fixes #13035

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 16:49:28 -07:00
Bee d3616b96ae feat(desktop): route /team prompts through core runtime (#12372)
* feat(desktop): route /team prompts through core runtime

Rewrite desktop `/team` commands as structured user command blocks before sending them to the core runtime. Validate task input and respect the globally disabled Teams tool setting.

Remove legacy agent spawn and team enablement flags from session configuration, and add coverage for prompt rewriting and disabled-tool behavior.

* fix(desktop): preserve team tool defaults

* fix(desktop): display queued /team prompts as their slash form

Queued prompts are stored in their runtime form, so a queued /team
command showed its raw <user_command> envelope in the prompt queue chip
and edit textarea. Fold queue items through formatDisplayUserInput for
display; saving an edit re-resolves the slash form through the sidecar,
so the round trip is lossless.

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

* chore(hub): align builtin tool catalog flags with the desktop sidecar

The desktop sidecar pins enableSpawnAgent/enableAgentTeams when listing
the builtin tool catalog; the hub's parallel listing did not, so the two
would drift if the preset defaults ever change. Pin the same flags in
the hub and cross-reference the two call sites.

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

* chore(desktop): drop inert enableSpawn/enableTeams config leftovers

buildCoreSessionConfig no longer reads these keys, so remove the dead
schema fields, default-config initializers, and chat-test payload
entries. The chat-session regression test still sends them on purpose
to prove legacy flags cannot override the runtime's tool presets.

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

* fix(desktop): reject /team when the mode's tool preset disables teams

The /team guard only checked the global disabled-tools setting, but the
runtime resolves tool availability from the mode's preset, so a preset
without team tools (yolo) would still send the model a spawn-a-team
instruction it cannot act on. Resolve the teams catalog entry for the
session's mode and reject /team when it is unavailable, mirroring the
runtime's own availability logic.

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

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 16:45:49 -07:00
Bee 98e5458b09 feat(hub): centralize plugin settings and contributions (#12942)
* fix(desktop): plugin package names

* feat(hub): centralize plugin settings and contributions

* fix(hub): address plugin settings review feedback

* fix(settings): make plugin snapshots host-aware

* fix(core): make host plugin toggles atomic

---------

Co-authored-by: cline-cloud[bot] <cline-cloud[bot]@users.noreply.github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-07 16:44:02 -07:00
Saoud Rizwan 031b8d94e1 fix(core): surface OAuth authorization for SSE MCP servers on 401 (#13050)
* fix(core): surface OAuth authorization for SSE MCP servers on 401

A 401 from an SSE MCP server never persisted authorizationRequired: the
fetch-boundary UnauthorizedError was consumed by EventSource and re-thrown
as a status-less SseError, so the instanceof check routed it to
markConnectionError and hosts never offered the OAuth connect action.

Give the SSE stream request a raw fetch so a 401 fails the connection with
the SDK's typed SseError(401), and recognize 401s across transports with a
single isMcpUnauthorizedError predicate at every detection site.

* style(core): apply biome formatting to MCP oauth changes
2026-08-07 16:42:43 -07:00
Saoud Rizwan e5bcba8ef9 fix(vscode): settle the turn phase when a mode switch aborts a running turn (#13063)
Toggling Plan/Act while a turn was streaming or waiting on a tool approval
aborted the turn but left the TurnStateTracker on its last live phase: the
aborted session's done event is fenced off as stale once the rebuild
unsubscribes it, so nothing ever settled the phase. The webview then kept
rendering that phase forever - an eternal Thinking spinner with the input
disabled (aborted while streaming), or dead Approve/Run Command buttons wired
to an approval that clearPending had already denied (aborted while awaiting
approval). Users experienced this as 'switched to act mode and nothing
happened / it never wrote the files'.

Mirror cancelTask: after aborting the turn for the mode change, append a
resume_task ask row and set the phase to resumable, so the footer offers
Resume Task with the input enabled in the new mode.

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 16:41:13 -07:00
Saoud Rizwan 83182c0d96 fix(llms): retry mid-stream network interruptions before any model output (#13052)
* fix(llms): retry mid-stream network interruptions before any model output

* fix(llms): scale network retry backoff by network retry count, not shared attempt number
2026-08-07 16:36:27 -07:00
Saoud Rizwan 40ebd09dfa desktop: native-feel polish, render-path performance, and transition fixes (#13028)
* desktop: native-feel polish and render-path performance fixes

- Suppress the WebView browser context menu on app chrome (keep it for
  editable fields and active text selections)
- Make UI chrome unselectable app-wide; opt chat messages, markdown,
  code, diffs, and error banners back into text selection
- Contain overscroll so inner scrollers don't rubber-band the window
- Lazy-load Settings/Sessions/Onboarding/Diff views out of the entry chunk
- Memoize ChatInputBar and AgentHeader; stabilize their props in the chat
  pane so stream flushes only re-render the affected message bubble
- Stop refocusing the composer textarea on every keystroke (caret flicker)
- Cache slash commands across menu opens (stale-while-revalidate)
- Avoid rebuilding reversed message arrays and ask-question JSX per render
- Drop core info/debug console logging on the streaming hot path behind a
  cline:debug-logs opt-in; remove leftover [webview:delete] debug logs
- SearchCombobox (provider/model picker): Escape closes and restores focus
- Remove unused @vercel/analytics, recharts, embla-carousel deps and the
  unused chart/carousel UI components

* desktop: surface failed-turn errors instead of leaving the chat blank

On a failed run the runtime reports its error string in result.text.
The webview rendered that as an assistant bubble, which the canonical
history rehydration then wiped (the failed turn is never persisted),
so provider errors like a retired model id left the user staring at a
silently empty chat. Route failed-turn text to a persistent error-role
message added after rehydration instead.

* desktop: fade the welcome/conversation swap instead of hard-cutting

Sending the first message replaced the hero layout with the message
grid in a single commit, which read as a white flash. A 180ms enter
animation now plays when either side becomes visible; disabled under
prefers-reduced-motion.

* desktop: render new-chat panes instantly from the last catalog load

Clicking + remounts ChatThreadPane, which refused to render until the
provider catalog (a large fetch) and workspace list resolved again —
about a second of blank pane plus boot spinner on every new chat.
Seed remounts from a module-level snapshot of the last successful
load; the mount effect still refreshes both in the background.

* desktop: invalidate the provider-catalog snapshot with the cache

Seeding remounted chat panes from the last catalog load left a window
where a pane created right after a credential change could act on the
old keys. The snapshot now lives in the catalog module and is dropped
by invalidateProviderCatalogCache(), so credential edits force the
next remount to wait for fresh data.
2026-08-07 16:18:47 -07:00
Saoud Rizwan 7bc18f7e15 Bring back a copy button on turn-final response rows with a subtle header (#13051)
* Add subtle response header with copy button to completion and plan rows

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

* Add changeset for response header copy button

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

* Rename turn-final headers to Completed and Plan

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 16:12:43 -07:00
Bee fad8006730 feat(hub): add execution context for scheduled run reports (#12718)
* feat(hub): add execution context for scheduled run reports

Add human-readable headers, schedule metadata, durations, and lifecycle error context to cron run reports. Resolve file-based definitions to real paths while clearly identifying Hub-managed schedules stored in cron.db.

* fix cron report formatting edge cases

* Escape schedule titles in reports

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-07 15:57:33 -07:00
Saoud Rizwan 28f35a2ec8 fix(cli): harden tool input/output formatters against malformed payloads (#13048)
* fix(cli): harden tool input/output formatters against malformed payloads

Tool inputs cross the model/tool boundary and may not match their
TypeScript annotations (e.g. run_commands with { command: null }).
truncate() called str.replace() on such values, crashing the TUI with
'.replace is not a function' and making persisted sessions containing
the payload non-resumable, since hydration replays the same input
through formatToolInput().

Normalize untrusted values at the formatting boundary: truncate() now
accepts unknown and safely stringifies null/undefined/objects (including
circular structures and throwing toJSON), formatStructuredCommand no
longer returns non-string commands verbatim, and fetch_web_content
request summaries tolerate malformed entries.

Fixes #13036

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

* fix(cli): keep valid empty-string args in structured command summaries

Greptile review: filtering normalized args by truthiness also dropped
genuine empty-string argv entries, so summaries could show a different
argument list than the one executed. Filter only nullish entries before
normalization instead.

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

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 15:53:01 -07:00
Saoud Rizwan 1e24807d1a fix(vscode): fall back to session cwd or Desktop for @-mention file search in empty windows (#12982)
* fix(vscode): fall back to session cwd/Desktop for @-mention search in empty windows

* fix(vscode): use the shared chat workspace as the no-folder fallback root
2026-08-07 15:38:43 -07:00
Saoud Rizwan a5f90e0d53 fix(core): pick up checkpoints when git is initialized mid-session (#13026)
ensureGitRepository cached a negative probe for the lifetime of the hook
instance, so a session started in a non-git folder never got checkpoints
even after the user ran git init. Cache only the positive answer and
re-probe otherwise; the probe runs at most once per user turn.
2026-08-07 15:25:11 -07:00
Saoud Rizwan adabfc6bd5 fix(desktop): treat signed-out state as a typed result instead of a command error (#12976)
* fix(desktop): treat signed-out state as a typed result instead of a command error

* fix(desktop): sign out when the organization balance fetch reports the typed signed-out result

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

* chore: retrigger checks after runner outage

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-07 15:06:45 -07:00
Saoud Rizwan 397d6f344f fix(desktop): resolve startup script-load SyntaxError and attribute webview errors to their source URL (#12974)
* fix(desktop): remove Vercel Analytics injection that breaks packaged webview startup

* fix(desktop): attribute webview uncaught errors to their source URL

* chore: drop unrelated claude-dev version bump from lockfile

* chore: retrigger checks after runner outage
2026-08-07 15:02:36 -07:00
Bee 8ca3068b73 refactor(desktop): update team tools component (#13047)
* refactor(desktop): update team tools component

* fix(desktop): address team tool review feedback
2026-08-07 22:58:06 +02:00
John Choi 6e6befdb65 fix(ui): remove nested tool output scrolling (#13043)
* fix(ui): remove nested tool output scrolling

* fix(desktop): avoid nested tool output scrolling

* chore(desktop): remove obsolete scroll utility

* fix(desktop): preserve multiline tool details
2026-08-07 13:44:23 -07:00
Haley Park 71536e55aa refactor(ui): introduce Cline-owned semantic color system (#12941)
* refactor(ui): introduce Cline-owned semantic color system

* refactor(desktop): adopt shared semantic theme roles

* refactor(ui): set 15px root and recalibrate xs/sm type scale

Scale rem steps so xs/sm stay 12/13px visually, and slightly lift dark-mode neutral-4.

* refactor(ui): align SearchCombobox with package type and hover tokens

Use host-safe cline-ui utilities and keep option font inheritance from CSS.

* fix(ui): use standard stroke-2 utility on approval spinner

* refactor(desktop): modernize shared UI primitives for Tailwind v4

Replace legacy arbitrary/has selectors with current utility syntax.

* refactor(desktop): bump chat chrome typography to text-sm

Keep composer controls and pickers on the shared sm type step.

* refactor(desktop): use max-w-344 for page frame content width

* chore(desktop): disable Next.js dev indicators

* chore: ignore desktop-app Cursor settings

* docs(pr): add before/after screenshots for #12941

* chore: retrigger checks

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-07 10:15:18 -07:00
Saoud Rizwan 7348ba1847 chore(desktop): release v0.0.10 2026-08-06 23:45:56 -07:00
Bee 3e96fc6112 feat(cli): add mcp uninstall command (#12985)
* feat(cli): add mcp uninstall command

* unit test wiring

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-06 19:40:45 -07:00
Saoud Rizwan d84d09c543 desktop: fix silent turn failures, message duplication, and stuck composer; add first-run setup guidance (#12984)
* desktop: fix silent turn failures, message duplication, and stuck composer; add first-run setup guidance

Findings from two full computer-use UX audits of the desktop app:

- Surface failed turns in the transcript: queued turns (incl. the first
  prompt of a fresh session) only signal errors via chat_done, which the
  UI previously ignored - sending a message with no credentials failed
  in complete silence. Failed turns now show an error message enriched
  with the latest core error log and a pointer to Settings -> Models.
- Fix duplicated user messages: a live send's optimistic user message
  was materialized a second time by the runtime's queued-prompt-start
  event.
- Fix composer stuck on 'Agent is working...': drop prompts from the
  local queue snapshot when they start, emit a fresh queue snapshot from
  the sidecar on pending_prompt_submitted, and double-check the server
  queue on turn completion.
- Add a 'Connect a model' notice on the welcome screen when no provider
  has credentials, with actions to reopen onboarding at the connect step
  or jump to model settings; it reacts live to credential changes.
- Add 'Get an API key' links for popular providers in onboarding and
  Settings -> Models (the catalog docUrl is never populated), and link
  the Cline dashboard from the Cline API key form.
- Explain what Cline is on the onboarding welcome step.
- Make the stop button visible (was 8px with no padding) and support
  Esc to stop; add Cmd/Ctrl+N (new session) and Cmd/Ctrl+, (settings).
- Remove leftover [webview:delete] console.error debug logging that
  surfaced an error badge after deleting a session.

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

* desktop: remove remaining delete debug logging in session history hook

The sidebar right-click delete path had the same leftover [webview:delete]
console.error instrumentation, which made the Next dev-mode issues badge
appear after every deletion.

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

* desktop: fix Biome a11y error in WelcomeSetupNotice

biome's lint/a11y/useSemanticElements errors on role="status" divs;
use the semantic <output> element (implicit status role) instead. This
was failing the repo's 'bun run lint'.

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

* desktop: count structured-config and keyless providers as connected

The welcome setup notice previously only recognized apiKey/OAuth
credentials, so users running Bedrock/Vertex (structured configValues)
or a deliberately enabled keyless local endpoint (e.g. Ollama) were
nagged to connect a model they already use. isProviderConnected now
also counts an enabled provider whose required config fields are all
filled, or an enabled provider that has no API-key field at all.

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

* desktop: keep re-key eligible when chat_done lands in the same batch as its prompt start

When a turn fails fast, chat_queued_prompt_start and chat_done can be
dispatched in one React batch. Clearing the outstanding-optimistic-
bubble registry synchronously in the chat_done handler ran before the
re-key updater enqueued by the prompt-start event, so the optimistic
bubble was appended a second time instead of re-keyed. Clear the
registry inside a state updater so it executes in event order after
the re-key. Caught by the queued-turn-failure regression test.

* desktop: make the queued-prompt re-key updater idempotent under StrictMode

React StrictMode double-invokes state updaters in dev. The
chat_queued_prompt_start re-key updater consumed the optimistic
bubble's id from outstandingOptimisticUserIdsRef on its first run, so
the second run against the same prev found no eligible candidate and
appended the same user message a second time (and, without a promptId,
makeId() minted a different id per invocation). Hoist the message id
out of the updater and remember which optimistic bubble each queued
message id re-keyed so a re-run reaches the identical result. The memo
resets alongside the outstanding set (error state, reset, hydration).

Root-caused with runtime instrumentation: the duplicate only appeared
on turns that exercised the queue-drain re-key path, and hydration
later collapsed it to one message because the duplicate never existed
in persisted state.

* desktop: preserve failure messages across post-send canonical hydration

Persisted history never contains UI-only error bubbles, so the two
post-send read_session_messages replacements in sendPrompt wiped the
failure explanation appended from chat_done ~40ms after it rendered
(confirmed with runtime instrumentation). Re-append the active
session's error messages after the canonical history. Includes a
regression test reproducing the chat_done-error-then-RPC-resolution
race.

* desktop: don't let an optional API-key field veto a connected provider

Greptile P1 follow-up: Bedrock's catalog entry carries an optional
apiKey field ('Optional Bedrock bearer token') alongside IAM/profile
authentication, and keyless local endpoints can also surface one — so
treating the mere presence of an apiKey field as proof of disconnection
kept nagging configured users. An enabled provider (the user
deliberately persisted settings for it) now counts as connected unless
a required config field is unmet; auth may legitimately live outside
the catalog (IAM, env vars, local endpoints). Brand-new users have no
enabled providers, so the first-run notice still shows for them.

* desktop: tighten credential-error guidance and stop re-pinning stale failure bubbles

* desktop: invalidate the shared provider catalog after settings OAuth login

Greptile P1 follow-up: runOAuthProviderLogin only updated the settings
view's local provider state, so the shared catalog cache and its
invalidation subscribers (the composer selector and the welcome
screen's 'Connect a model' notice) kept reporting the provider as
disconnected until an unrelated invalidation or a pane remount. Notify
the shared cache on successful OAuth login, like the account view and
the API-key save path already do.

* desktop: clear the remembered core error on turn end, reset, and hydration

Greptile flagged that turn-start events are the only thing clearing
lastCoreErrorBySessionRef, and websocket events are not replayed: a
transport interruption that drops a turn's start event lets a later
detail-less failure resurrect an earlier turn's error. The remembered
error belongs to exactly one turn, so clear it whenever a turn ends
(chat_done, any reason) as well as on reset() and history hydration.
Regression test covers the dropped-start-event sequence.

---------

Co-authored-by: Saoud Rizwan <saoudrizwan@users.noreply.github.com>
2026-08-06 19:25:42 -07:00
Bee 6f7f817d63 feat(core): support pre-registered OAuth clients for remote MCP (#12983)
* feat(core): support pre-registered OAuth clients for remote MCP

* fix(core): invalidate tokens when OAuth client changes

* fix(core): preserve compatible MCP OAuth sessions

* fix tests

* feat(desktop): wire mcp oauth in desktop

* UI update

* fix(core): reject stale mcp oauth callbacks

* fix(mcp): handle invalid settings and preserve state

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-06 18:58:52 -07:00
Bee c18d9478ba feat(cli): use saved provider settings for schedules (#10667)
Co-authored-by: Cline Agent <cline-agent@users.noreply.github.com>
2026-08-06 17:34:40 -07:00
Ara 574b8eb45e fix(llms): use configured fetch for Vertex ADC refreshes (#12981) (#12991) 2026-08-06 10:07:06 -07:00
Saoud Rizwan 81cce3d70e chore(vscode): prepare 4.1.6 release 2026-08-06 00:47:54 -07:00
Saoud Rizwan e1352fa709 chore(cli): release v3.0.51 2026-08-06 00:28:37 -07:00
Saoud Rizwan 394fb04518 chore(sdk): release v0.0.71 2026-08-06 00:14:21 -07:00
Saoud Rizwan f1aebbfd5a feat(llms): surface meta/muse-spark-1.2-contributor for the Cline provider (#12995)
* chore(llms): regenerate model catalog from models.dev

* feat(llms): surface meta/muse-spark-1.2-contributor for the Cline provider

* test(llms): guard Vercel-only Cline model allowlist
2026-08-06 00:04:16 -07:00
Saoud Rizwan 543dd0d818 fix(telemetry): attribute agent.run sdk.error events to the active model (#12972)
* fix(telemetry): attribute agent.run sdk.error events to the active model

* fix(telemetry): strip undefined values from sdk.error properties
2026-08-05 17:51:06 -07:00
Saoud Rizwan 1f2cbbeb9f chore(vscode): prepare 4.1.5 release 2026-08-05 14:04:04 -07:00
Saoud Rizwan b1a89156d6 feat(vscode): explain when a free model promotion ends (#12970)
* feat(vscode): explain when a free model promotion ends

Once a free promotion ends, the cline-free/ model is removed from the
catalog and the backend answers 'model not found' to requests against it.
The CLI has shown a dedicated 'Free model promotion ended' banner for this
since #12593; the extension instead rewrote the answer into generic
model-not-found guidance with no model-picker offramp.

Detect the case in the host where the active model id is known
(reshapeErrorForWebview, fed by a new MessageTranslatorState model-id
source), stamp the payload with a cline_free_promotion_ended code, and
render a dedicated card in the webview with a button into the model
picker. Classification is gated on the cline-free/ prefix so ordinary
model-not-found errors keep their generic path, and it runs before the
auth branch since the 404 status falls inside the generic auth range.

* fix(vscode): prefer the live task model over session-start metadata

A mid-task model-only switch updates the running session's model in place
(updateActiveSessionModel) and refreshes the task API shim, but never
touches the session's startConfig/manifest. Preferring the session-start
snapshot could therefore misclassify after such a switch: a genuine
retired-model 404 would miss the promotion-ended card, and the reverse
switch could show it for the wrong model. Provider switches restart the
session, so both sources agree there; the shim starts as "unknown"
(filtered out), so fresh sessions still resolve through start metadata.
2026-08-05 14:00:09 -07:00
Bee 1d7d9ce5e2 feat(llms): add portable reasoning resolution for AI SDK providers (#12946)
* feat(llms): add portable reasoning resolution for AI SDK providers

Introduce resolvePortableReasoning to map gateway reasoning requests
(effort levels, enabled/disabled flags) to the AI SDK's top-level
reasoning setting, applying it in buildAiSdkStreamConfig for supported
providers including Ollama.

- Defer exact token budgets to provider-specific options
- Omit reasoning when the caller expresses no explicit intent
- Replace manual provider-specific thinking overrides (e.g. Anthropic
  budget clamping, Moonshot/OpenAI-compatible toggles) with the
  portable reasoning path where applicable
- Add tests covering effort mapping, budget passthrough, and provider
  stream config integration

* fix(llms): prioritize explicit reasoning disable

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-08-05 12:17:49 -07:00
Mikołaj Kondratek 78b7c3d8ac fix(desktop): stop rendering the first chat message twice (#12779)
* fix(desktop): dedupe chat_queued_prompt_start emitted for the same prompt

PendingPromptService.drain() emits a pending_prompts snapshot (head
removed) and a pending_prompt_submitted event back-to-back for the same
prompt. The sidecar translated both into chat_queued_prompt_start, so
the webview rendered the user's message twice until the chat was
re-hydrated from history. Track the last announced prompt id per live
session and emit the start chunk once.

* fix(desktop): re-key optimistic user bubble when the runtime queues the prompt

The send path renders an optimistic user bubble for prompts dispatched
while the session is idle, keyed by a random id. When the runtime
routes that prompt through its pending queue (e.g. during session
startup), the queued-prompt-start event appended a second bubble under
queued_user_<promptId> — the same message rendered twice until the
chat was re-hydrated from history. Re-key the trailing optimistic
bubble to the event's id instead of appending.

* fix(desktop): re-key only outstanding optimistic bubbles on queued prompt start

Review follow-up: matching by content alone could swallow a new queued
prompt that repeats the text of a message left at the transcript tail
by an earlier cancelled/failed turn. Track in-flight optimistic bubble
ids explicitly (registered on optimistic append; cleared on re-key,
turn end, error, and history hydration) and only re-key those.
2026-08-05 14:49:05 +02:00
Saoud Rizwan d626cfb0b5 chore(vscode): prepare 4.1.4 release 2026-08-05 03:03:51 -07:00
Saoud Rizwan e14f354c59 chore(desktop): release v0.0.9 2026-08-05 02:29:46 -07:00
Saoud Rizwan 41ba332f0a chore(cli): release v3.0.50 2026-08-05 02:16:56 -07:00
1059 changed files with 160131 additions and 21391 deletions
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix auto-approve checkboxes freezing after "New Task": clear the task-scoped settings overlay when the task view is cleared or switched, so stale task settings no longer shadow global settings
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Bring back a copy button on turn-final response rows, under a new subtle "Completed" / "Plan" header
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Hide the "View Changes" button on completion rows until there are actually changes to show, instead of rendering it faded and disabled. Turns that changed nothing, non-git workspaces, and repos without commits no longer show a dead button with a misleading tooltip.
+1 -1
View File
@@ -7,7 +7,7 @@ description: Use when preparing, tagging, and publishing an apps/cli npm release
Use this skill when the user asks to release the CLI, publish `cline`, bump the CLI version, draft release notes, create a `cli-vX.Y.Z` tag, or trigger the CLI publish workflow.
The CLI is npm-only. Do not add alternate distribution or signing steps.
The CLI is npm-only. Do not add alternate distribution channels. Windows binaries are Authenticode-signed automatically by the publish workflow via Azure Trusted Signing (see the `.github/actions/sign-windows-cli` composite action and "Windows code signing" in `apps/cli/DISTRIBUTION.md`); if the signing secrets are not configured the workflow warns and publishes unsigned binaries. Local publishes (`bun release cli`) do not sign — prefer the GitHub Actions publish path for releases users run on Windows.
> Working directory: run every command below from the repository root. Paths and scripts (e.g. `apps/cli/package.json`, `sdk/packages/`, `bun release cli`, `bun run version`) are written relative to the repo root.
+38 -18
View File
@@ -1,28 +1,34 @@
---
name: publish-desktop
description: Use when preparing, tagging, and publishing a Cline Code desktop app (apps/examples/desktop-app) release. Guides changelog drafting, version bumps in package.json + tauri.conf.json, desktop-vX.Y.Z tags, and the desktop-publish GitHub workflow that builds, signs, notarizes, and updates the auto-update feed.
description: Use when preparing, tagging, and publishing a Cline desktop app (apps/examples/desktop-app) release — stable (desktop-vX.Y.Z from main) or beta (desktop-vX.Y.Z-beta.N from desktop-experimental, shipped as the side-by-side "Cline Beta" app). Guides changelog drafting, version bumps in package.json + tauri.conf.json, tagging, and the desktop-publish GitHub workflow that builds, signs, notarizes, and updates the per-channel auto-update feed.
---
# Desktop App Release
Use this skill when the user asks to release the desktop app, publish Cline Code, bump the desktop version, create a `desktop-vX.Y.Z` tag, or trigger the desktop publish workflow.
Use this skill when the user asks to release the desktop app, publish the Cline desktop app, cut a desktop beta, bump the desktop version, create a `desktop-vX.Y.Z` (or `desktop-vX.Y.Z-beta.N`) tag, or trigger the desktop publish workflow.
> Working directory: run every command below from the repository root.
Desktop releases are macOS-only today (a single signed + notarized universal DMG that runs natively on both Apple Silicon and Intel) and are built entirely in GitHub Actions — there is no local publish path. Installed apps discover new releases automatically through the Tauri updater, so publishing a release is what ships the update to every existing user.
Desktop releases ship two platforms, built entirely in GitHub Actions — there is no local publish path. macOS: a single signed + notarized universal DMG that runs natively on both Apple Silicon and Intel. Windows: an Authenticode-signed NSIS installer (`<Product>_<version>_x64-setup.exe`), signed via Azure Trusted Signing in the `build-windows` job (jsign through Tauri's `signCommand`, see `apps/examples/desktop-app/scripts/tauri-sign-windows.ps1`; requires the repo-level `AZURE_*` secrets including `AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_DESKTOP`, plus a `PublishDesktop`-environment federated credential on the `cline-cli-signing` Entra app). Installed apps discover new releases automatically through the Tauri updater, so publishing a release is what ships the update to every existing user **on that channel**.
## Release contract
- Two channels, one workflow (`channel` input on `desktop-publish.yml`):
- **stable** — tag `desktop-vX.Y.Z` (no suffix; the workflow rejects prerelease suffixes on this channel), cut from `main`, feeds the rolling `desktop-latest` release, ships as "Cline".
- **beta** — tag `desktop-vX.Y.Z-beta.N`, cut from `desktop-experimental`, feeds the rolling `desktop-beta` release, ships as "Cline Beta" (separate bundle identifier `bot.cline.app.beta`; installs side by side with stable). Built with the extra `src-tauri/tauri.beta.conf.json` overlay. Process background: `apps/examples/desktop-app/EXPERIMENTAL.md`.
- Version sources (must match each other and the tag): `apps/examples/desktop-app/package.json` and `apps/examples/desktop-app/src-tauri/tauri.conf.json`. (`src-tauri/Cargo.toml` has its own version but `tauri.conf.json` overrides it; no need to touch it.)
- Release tag: `desktop-vX.Y.Z`, where `X.Y.Z` matches both version files.
- Release prep includes approved release notes, the version bumps, and an `apps/examples/desktop-app/CHANGELOG.md` update.
- Publish path: `.github/workflows/desktop-publish.yml` (workflow_dispatch, requires the tag to exist, point at the checked-out commit, and be reachable from `origin/main`).
- The workflow creates the `desktop-vX.Y.Z` GitHub release (universal DMG + updater artifact + `latest.json`) and refreshes the rolling `desktop-latest` release, which is the static auto-update feed every installed app polls. Never delete the `desktop-latest` release or tag.
- The changelog's top `## X.Y.Z` section is extracted verbatim into the GitHub release body, the Slack announcement, and the updater manifest notes.
- Beta versions are prereleases of the **next** stable: stable `0.0.13` → betas `0.0.14-beta.1`, `-beta.2`, … Once a stable ≥ the beta base ships, the next beta bumps its base (`0.0.15-beta.1`).
- Release prep includes approved release notes, the version bumps, and an `apps/examples/desktop-app/CHANGELOG.md` update — committed on `main` for stable, on `desktop-experimental` for beta.
- Publish path: `.github/workflows/desktop-publish.yml` (workflow_dispatch, requires the tag to exist, point at the checked-out commit, and be reachable from the channel's branch — `origin/main` for stable, `origin/desktop-experimental` for beta).
- **Both channels dispatch from `main`.** This is a security invariant, not a convenience: the run executes `main`'s workflow copy and only the checkout points at the tag, so the signing-secret gates (the `github.ref == main` check and the PublishDesktop environment's main-only deployment-branch policy) hold for beta too. Never add `desktop-experimental` to the PublishDesktop deployment-branch policy.
- The workflow creates the tag's GitHub release (universal DMG + macOS updater artifact + Windows NSIS installer with its updater signature + `latest.json`; marked prerelease for beta) and refreshes the channel's rolling feed release, which is the static auto-update feed every installed app on that channel polls. Never delete the `desktop-latest` or `desktop-beta` release or tag.
- The changelog's `## <version>` section (exact-match, not "topmost") is extracted verbatim into the GitHub release body, the Slack announcement, and the updater manifest notes.
- Always ask before pushing commits or tags.
## Workflow
0. Ask which channel this release is for — **stable or beta** — if the user has not said. Everything below branches on it; never guess.
1. Gather context.
```sh
@@ -35,10 +41,15 @@ node -p "require('./apps/examples/desktop-app/src-tauri/tauri.conf.json').versio
If there is no `desktop-v*` tag yet, this is the first release; use the desktop app's first commit as the baseline and say the baseline is inferred.
For a **beta** release, work on `desktop-experimental` (check out `origin/desktop-experimental`; merge `origin/main` into it first if it is behind — see EXPERIMENTAL.md for the conflict policy) and read the version files from that branch. The last-tag baseline is the newest `desktop-v*` tag of either channel that is an ancestor of the branch.
2. Collect release commits.
```sh
# stable (on main):
git log <last-desktop-tag>..HEAD --oneline --no-merges -- apps/examples/desktop-app sdk/packages .github/workflows/desktop-publish.yml
# beta (on desktop-experimental):
git log <last-desktop-tag>..origin/desktop-experimental --oneline --no-merges -- apps/examples/desktop-app sdk/packages .github/workflows/desktop-publish.yml
```
The sidecar bundles `@cline/core` and friends from the monorepo, so SDK changes ship inside the desktop app too. Fold user-visible SDK changes (providers, models, behavior fixes) into the notes; skip purely internal ones.
@@ -49,13 +60,15 @@ Flat bullet list, user-facing language. Present the draft and wait for approval
4. Decide the version bump.
Ask whether this is patch, minor, major, or an explicit version. Do not guess if the user has not made it clear.
Stable: ask whether this is patch, minor, major, or an explicit version. Do not guess if the user has not made it clear.
5. Update release files.
Beta: apply the versioning rule — base = next stable version, increment `N` (`0.0.14-beta.1``0.0.14-beta.2`; after stable `0.0.14` ships, next is `0.0.15-beta.1`). Confirm the computed version with the user.
5. Update release files (on `main` for stable, on `desktop-experimental` for beta).
- `apps/examples/desktop-app/package.json` → new version
- `apps/examples/desktop-app/src-tauri/tauri.conf.json` → same version
- Prepend `## X.Y.Z` (no date) to `apps/examples/desktop-app/CHANGELOG.md` with the approved notes.
- Prepend `## X.Y.Z` (no date; `## X.Y.Z-beta.N` for beta) to `apps/examples/desktop-app/CHANGELOG.md` with the approved notes.
6. Verify before committing.
@@ -77,16 +90,20 @@ Ask before pushing the release commit, then before creating and pushing the tag:
```sh
git push origin HEAD
git tag -a desktop-vX.Y.Z -m "Desktop vX.Y.Z"
git tag -a desktop-vX.Y.Z -m "Desktop vX.Y.Z" # beta: desktop-vX.Y.Z-beta.N / "Desktop vX.Y.Z-beta.N"
git push origin refs/tags/desktop-vX.Y.Z
```
8. Publish.
The release commit must be on `main` and the tag pushed first.
The release commit must be on the channel's branch (`main` for stable, `desktop-experimental` for beta) and the tag pushed first. Dispatch from `main` for **both** channels (see the release contract for why).
```sh
gh workflow run desktop-publish.yml -f git_tag=desktop-vX.Y.Z -f confirm_publish=publish
# stable:
gh workflow run desktop-publish.yml --ref main -f git_tag=desktop-vX.Y.Z -f channel=stable -f confirm_publish=publish
# beta:
gh workflow run desktop-publish.yml --ref main -f git_tag=desktop-vX.Y.Z-beta.N -f channel=beta -f confirm_publish=publish
gh run list --workflow=desktop-publish.yml --limit=1 --json url,status,conclusion,createdAt --jq '.[0]'
```
@@ -103,21 +120,24 @@ gh api repos/cline/cline/actions/runs/<run-id>/pending_deployments \
Nothing after `validate` runs — and no signing key is readable — until then.
The workflow builds one universal macOS bundle (`tauri build --target universal-apple-darwin` lipos the aarch64 + x86_64 Rust binaries; the Bun sidecar is lipo'd by `build-sidecar-bin.ts`), verifies every Mach-O in the bundle carries both slices, signs with the Developer ID certificate, notarizes with the App Store Connect API key, signs the updater artifact with the Tauri updater key, creates the GitHub release, refreshes `desktop-latest/latest.json`, and posts to Slack. Notarization typically adds 210 minutes.
The workflow builds one universal macOS bundle (`tauri build --target universal-apple-darwin` lipos the aarch64 + x86_64 Rust binaries; the Bun sidecar is lipo'd by `build-sidecar-bin.ts`; beta adds the `tauri.beta.conf.json` overlay), verifies every Mach-O in the bundle carries both slices and that the compiled binary embeds exactly its own channel's feed URL, signs with the Developer ID certificate, notarizes with the App Store Connect API key, and signs the updater artifact with the Tauri updater key. In parallel, `build-windows` builds the x64 NSIS installer on a Windows runner, Authenticode-signs every binary via Azure Trusted Signing (Tauri `signCommand` -> `scripts/tauri-sign-windows.ps1`), runs the same feed-endpoint and telemetry guardrails, and verifies the shipped installer with `Get-AuthenticodeSignature`. The release job then creates the GitHub release (prerelease for beta), refreshes the channel's feed (`desktop-latest/latest.json` or `desktop-beta/latest.json`), and posts to Slack. Notarization typically adds 210 minutes.
If the workflow fails on missing credentials, see "Publish secrets (one-time setup)" below.
9. Verify the update feed after the run succeeds.
```sh
curl -sL https://github.com/cline/cline/releases/download/desktop-latest/latest.json | head -30
curl -sL https://github.com/cline/cline/releases/download/desktop-latest/latest.json | head -30 # stable
curl -sL https://github.com/cline/cline/releases/download/desktop-beta/latest.json | head -30 # beta
```
The `version` field must be the new release and both `darwin-aarch64` and `darwin-x86_64` entries must point at the same new `desktop-vX.Y.Z` universal `.app.tar.gz` asset (each slice of the fat binary requests its own arch key at runtime, so both keys serve the one artifact). Installed apps — including older per-arch installs — pick the update up on next launch or within 2 hours.
The `version` field must be the new release; both `darwin-aarch64` and `darwin-x86_64` entries must point at the same new universal `.app.tar.gz` asset under the release tag (each slice of the fat binary requests its own arch key at runtime, so both keys serve the one artifact), and the `windows-x86_64` entry must point at the new `*_x64-setup.exe` asset. Installed apps on that channel — including older per-arch installs — pick the update up on next launch or within 2 hours.
After a **beta** publish, also confirm the stable feed was not touched: `desktop-latest/latest.json` must still serve the previous stable version. (The workflow guards this fail-closed, but it is cheap to verify and catastrophic to miss — the updater comparator is a plain semver "newer than", so a beta manifest on `desktop-latest` would auto-update every stable install onto the beta.)
10. Final response.
Report: version, tag, changelog updated, commit hash, what was pushed, workflow URL, and the feed verification result.
Report: channel, version, tag, changelog updated, commit hash, what was pushed, workflow URL, and the feed verification result.
## Publish secrets (one-time setup)
+6 -2
View File
@@ -93,7 +93,9 @@ Release prep on `main` (PR, not direct push):
```bash
gh workflow run ext-vscode-ab-package.yml --ref main \
-f version=<VERSION> -f next-ref=main -f legacy-ref=legacy-extension -f publish=true
-f version=<VERSION> -f next-ref=main -f publish=true
# (the legacy bundle always builds from the protected legacy-extension branch;
# it is deliberately not an input)
# publish=false builds an installable .vsix artifact without publishing and
# needs NO environment approval — the ungated build job uploads the artifact
# and the run completes.
@@ -156,7 +158,9 @@ For shipping a fix on the `legacy-extension` branch — or as the **structural r
# versions, e.g. combined 4.1.0 live -> hotfix is 4.1.1, not 4.0.13),
# add the matching `## [x.y.z]` entry to root CHANGELOG.md, push.
gh workflow run ext-vscode-publish-legacy.yml --ref main \
-f release-type=release -f branch=legacy-extension
-f release-type=release
# (the branch is hardcoded to legacy-extension in the workflow; it is
# deliberately not an input)
```
npm test suite runs ungated; the publish job waits on the `Publish` environment. This workflow derives + pushes the `v<version>` tag itself and creates the GitHub release — no manual tagging. Publishes to Marketplace **and** Open VSX. The branch is the npm codebase: use `npm`, never `bun`, and expect the old monolith layout (`apps/vscode/src/core/...`).
+7 -3
View File
@@ -15,6 +15,8 @@ body:
- VSCode Extension
- JetBrains Plugin
- CLI
- Desktop App
- Cloud Platform
default: 0
validations:
required: true
@@ -62,13 +64,15 @@ body:
- type: textarea
id: ide-diagnostics
attributes:
label: IDE / CLI Diagnostics
label: Diagnostics
description: |
Paste the "About" diagnostics for your Cline surface. This captures the IDE build, runtime, and host details we need.
Paste the diagnostics for your Cline surface. This captures the build, runtime, and host details we need.
- VSCode Extension: open `Help → About` (Windows/Linux) or `Code → About Visual Studio Code` (macOS), then copy the info.
- JetBrains Plugin: open `Help → About` (Windows/Linux) or `<IDE name> → About` (macOS), then click `Copy` to grab build, runtime, OS, memory, and cores.
- CLI: there is no About dialog. Run `cline --version` and paste the output.
placeholder: Paste the copied About info or `cline --version` output here.
- Desktop App: paste the app version from the Settings view.
- Cloud Platform: paste your browser name and version, plus the page URL where the issue occurred.
placeholder: Paste the copied About info, `cline --version` output, or browser/app details here.
validations:
required: false
- type: textarea
+155
View File
@@ -0,0 +1,155 @@
name: Sign Windows CLI binaries
description: >
Authenticode-signs the compiled Windows CLI executables with Azure Trusted
Signing (via jsign, so it runs on Linux runners) and verifies the resulting
signatures. If the Azure Trusted Signing secrets are not configured, the
action logs a warning and exits successfully so releases keep working while
signing infrastructure is being provisioned.
inputs:
azure-client-id:
description: Client ID of the Entra app with the Trusted Signing Certificate Profile Signer role (OIDC federated credential, no client secret).
required: false
default: ""
azure-tenant-id:
description: Entra tenant ID.
required: false
default: ""
azure-subscription-id:
description: Azure subscription ID containing the Trusted Signing account.
required: false
default: ""
endpoint:
description: Trusted Signing account endpoint, for example https://eus.codesigning.azure.net.
required: false
default: ""
account:
description: Trusted Signing account name.
required: false
default: ""
certificate-profile:
description: Trusted Signing certificate profile name.
required: false
default: ""
files:
description: Newline-separated list of PE files to sign.
required: true
runs:
using: composite
steps:
- name: Check signing configuration
id: check
shell: bash
env:
AZURE_CLIENT_ID: ${{ inputs.azure-client-id }}
AZURE_TENANT_ID: ${{ inputs.azure-tenant-id }}
AZURE_SUBSCRIPTION_ID: ${{ inputs.azure-subscription-id }}
SIGNING_ENDPOINT: ${{ inputs.endpoint }}
SIGNING_ACCOUNT: ${{ inputs.account }}
SIGNING_PROFILE: ${{ inputs.certificate-profile }}
run: |
missing=()
set_count=0
for var in AZURE_CLIENT_ID AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID SIGNING_ENDPOINT SIGNING_ACCOUNT SIGNING_PROFILE; do
if [ -z "${!var}" ]; then
missing+=("$var")
else
set_count=$((set_count + 1))
fi
done
if [ "${#missing[@]}" -eq 0 ]; then
echo "Azure Trusted Signing is configured; Windows binaries will be signed."
echo "enabled=true" >> "$GITHUB_OUTPUT"
elif [ "$set_count" -eq 0 ]; then
echo "::warning::Azure Trusted Signing is not configured; publishing UNSIGNED Windows binaries. Set the AZURE_* and AZURE_TRUSTED_SIGNING_* repository secrets to enable signing."
echo "enabled=false" >> "$GITHUB_OUTPUT"
else
# Partial configuration is almost certainly a typo'd or renamed
# secret. Fail loudly instead of silently publishing unsigned.
echo "::error::Azure Trusted Signing is PARTIALLY configured; refusing to publish. Missing: ${missing[*]}"
exit 1
fi
- name: Azure login (OIDC)
if: steps.check.outputs.enabled == 'true'
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ inputs.azure-client-id }}
tenant-id: ${{ inputs.azure-tenant-id }}
subscription-id: ${{ inputs.azure-subscription-id }}
- name: Sign Windows binaries
if: steps.check.outputs.enabled == 'true'
shell: bash
env:
SIGNING_ENDPOINT: ${{ inputs.endpoint }}
SIGNING_ACCOUNT: ${{ inputs.account }}
SIGNING_PROFILE: ${{ inputs.certificate-profile }}
FILES: ${{ inputs.files }}
JSIGN_VERSION: "7.5"
JSIGN_SHA256: "602a51c3545a6dc4fb99bd2ea7152b26d1345916d0c93ddfbd5936cb735af91c"
run: |
set -euo pipefail
JSIGN_JAR="${RUNNER_TEMP}/jsign-${JSIGN_VERSION}.jar"
curl -fsSL -o "$JSIGN_JAR" "https://github.com/ebourg/jsign/releases/download/${JSIGN_VERSION}/jsign-${JSIGN_VERSION}.jar"
echo "${JSIGN_SHA256} ${JSIGN_JAR}" | sha256sum --check --strict
JSIGN_STOREPASS=$(az account get-access-token --resource https://codesigning.azure.net --query accessToken --output tsv)
echo "::add-mask::${JSIGN_STOREPASS}"
export JSIGN_STOREPASS
# jsign expects the endpoint host, not the URL. Tolerate both the
# portal's display form (trailing slash) and the bare form.
KEYSTORE="${SIGNING_ENDPOINT#https://}"
KEYSTORE="${KEYSTORE%/}"
while IFS= read -r file; do
[ -z "$file" ] && continue
echo "Signing ${file}"
java -jar "$JSIGN_JAR" \
--storetype TRUSTEDSIGNING \
--keystore "$KEYSTORE" \
--storepass env:JSIGN_STOREPASS \
--alias "${SIGNING_ACCOUNT}/${SIGNING_PROFILE}" \
--alg SHA-256 \
--tsaurl http://timestamp.acs.microsoft.com \
--tsmode RFC3161 \
--replace \
"$file"
done <<< "$FILES"
- name: Verify signatures
if: steps.check.outputs.enabled == 'true'
shell: bash
env:
FILES: ${{ inputs.files }}
# Authenticode chains anchor to the Microsoft Identity Verification
# Root CA 2020, which is not in the Mozilla TLS bundle, so fetch it
# explicitly (pinned) for osslsigncode chain validation.
MS_ROOT_URL: "https://www.microsoft.com/pkiops/certs/Microsoft%20Identity%20Verification%20Root%20Certificate%20Authority%202020.crt"
MS_ROOT_SHA256: "5367f20c7ade0e2bca790915056d086b720c33c1fa2a2661acf787e3292e1270"
run: |
set -euo pipefail
if ! command -v osslsigncode >/dev/null; then
sudo apt-get update -qq
sudo apt-get install -y -qq osslsigncode
fi
MS_ROOT_DER="${RUNNER_TEMP}/ms-identity-root-2020.crt"
MS_ROOT_PEM="${RUNNER_TEMP}/ms-identity-root-2020.pem"
curl -fsSL -o "$MS_ROOT_DER" "$MS_ROOT_URL"
echo "${MS_ROOT_SHA256} ${MS_ROOT_DER}" | sha256sum --check --strict
openssl x509 -inform DER -in "$MS_ROOT_DER" -out "$MS_ROOT_PEM"
while IFS= read -r file; do
[ -z "$file" ] && continue
echo "Verifying signature on ${file}"
# Timestamp countersignature chain is checked separately by Windows;
# -ignore-timestamp only skips TSA chain validation here, not the
# Authenticode chain itself.
osslsigncode verify -in "$file" -CAfile "$MS_ROOT_PEM" -ignore-timestamp
done <<< "$FILES"
+56 -1
View File
@@ -190,6 +190,19 @@ jobs:
ls -lh "$dir/bin/"
done
- name: Sign Windows binaries
uses: ./.github/actions/sign-windows-cli
with:
azure-client-id: ${{ secrets.AZURE_CLIENT_ID }}
azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }}
azure-subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
account: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
certificate-profile: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_CLI }}
files: |
apps/cli/dist/cli-windows-x64/bin/cline.exe
apps/cli/dist/cli-windows-arm64/bin/cline.exe
- name: Publish to NPM with latest tag
env:
NPM_CONFIG_PROVENANCE: "true"
@@ -206,6 +219,8 @@ jobs:
- name: Get Changelog Entry
id: changelog
env:
RELEASE_URL: https://github.com/${{ github.repository }}/releases/tag/${{ steps.version.outputs.tag }}
run: |
# Grab content between the first "## " header and the next one in apps/cli/CHANGELOG.md
CONTENT=$(awk '/^## [0-9]/{if(found) exit; found=1; next} found{print}' apps/cli/CHANGELOG.md)
@@ -213,6 +228,32 @@ jobs:
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Slack section blocks reject text longer than 3000 characters, and the
# Slack action logs that rejection WITHOUT failing the step - so an
# over-long changelog silently drops the release announcement while the
# run stays green (cline@3.0.50 hit this). Post a trimmed copy to Slack
# and link out to the full notes. The GitHub release body stays whole.
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
echo "slack_content<<SLACK_EOF" >> $GITHUB_OUTPUT
echo "$SLACK_CONTENT" >> $GITHUB_OUTPUT
echo "SLACK_EOF" >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
@@ -248,7 +289,7 @@ jobs:
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
@@ -419,6 +460,20 @@ jobs:
ls -lh "$dir/bin/"
done
- name: Sign Windows binaries
if: steps.check_commits.outputs.skip != 'true'
uses: ./.github/actions/sign-windows-cli
with:
azure-client-id: ${{ secrets.AZURE_CLIENT_ID }}
azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }}
azure-subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
account: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
certificate-profile: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_CLI }}
files: |
apps/cli/dist/cli-windows-x64/bin/cline.exe
apps/cli/dist/cli-windows-arm64/bin/cline.exe
- name: Publish to NPM with nightly tag
if: steps.check_commits.outputs.skip != 'true'
env:
+503 -30
View File
@@ -11,6 +11,14 @@ on:
description: 'Type "publish" to confirm the desktop release.'
required: true
type: string
channel:
description: "Release channel"
required: true
type: choice
options:
- stable
- beta
default: stable
permissions:
contents: read
@@ -30,6 +38,9 @@ jobs:
outputs:
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
channel: ${{ steps.version.outputs.channel }}
feed: ${{ steps.version.outputs.feed }}
product: ${{ steps.version.outputs.product }}
steps:
# Companion to the presence check in `build`, and the half that actually
# establishes scope. This job declares no environment, so a signing secret
@@ -81,11 +92,41 @@ jobs:
id: version
env:
TAG: ${{ github.event.inputs.git_tag }}
# inputs.* (not github.event.inputs.*) so the declared default
# applies when an API dispatch omits the channel input entirely.
CHANNEL: ${{ inputs.channel }}
run: |
if ! printf "%s\n" "$TAG" | grep -Eq '^desktop-v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
echo "git_tag must look like desktop-vX.Y.Z, got: ${TAG}"
exit 1
fi
# Fail-closed channel mapping: every channel defines its tag shape,
# its ancestry source, its feed, and its product name, and an unknown
# channel dies here. The feed assignment is the load-bearing one —
# the updater comparator is a plain semver "newer than", so a beta
# manifest landing on desktop-latest would auto-update every stable
# install onto the beta. The stable regex rejects prerelease
# suffixes for the same reason.
case "$CHANNEL" in
stable)
if ! printf "%s\n" "$TAG" | grep -Eq '^desktop-v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "stable git_tag must look like desktop-vX.Y.Z with no suffix, got: ${TAG}"
exit 1
fi
ANCESTOR_REF=main
FEED=desktop-latest
PRODUCT="Cline"
;;
beta)
if ! printf "%s\n" "$TAG" | grep -Eq '^desktop-v[0-9]+\.[0-9]+\.[0-9]+-beta\.[0-9]+$'; then
echo "beta git_tag must look like desktop-vX.Y.Z-beta.N, got: ${TAG}"
exit 1
fi
ANCESTOR_REF=desktop-experimental
FEED=desktop-beta
PRODUCT="Cline Beta"
;;
*)
echo "unknown channel: ${CHANNEL}"
exit 1
;;
esac
VERSION="${TAG#desktop-v}"
PACKAGE_VERSION=$(node -p "require('./apps/examples/desktop-app/package.json').version")
@@ -108,14 +149,17 @@ jobs:
exit 1
fi
git fetch origin +main:refs/remotes/origin/main
if ! git merge-base --is-ancestor "$HEAD_COMMIT" origin/main; then
echo "${TAG} is not reachable from origin/main"
git fetch origin "+${ANCESTOR_REF}:refs/remotes/origin/${ANCESTOR_REF}"
if ! git merge-base --is-ancestor "$HEAD_COMMIT" "origin/${ANCESTOR_REF}"; then
echo "${TAG} is not reachable from origin/${ANCESTOR_REF}"
exit 1
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT"
echo "feed=${FEED}" >> "$GITHUB_OUTPUT"
echo "product=${PRODUCT}" >> "$GITHUB_OUTPUT"
build:
name: Build macOS (universal)
@@ -126,6 +170,25 @@ jobs:
# run. Defense in depth: this `if` is advisory because a dispatched branch
# runs its own copy of this file; the enforced gate is the PublishDesktop
# environment's deployment-branch policy, which must also allow only main.
#
# Beta releases do not weaken this: a beta publish is ALSO dispatched from
# main (so this gate, the branch policy, and the workflow file executed all
# stay main's) — only the checked-out tag points into desktop-experimental,
# which validate pins via the ancestry check. A workflow copy edited on
# desktop-experimental can therefore never reach the signing secrets.
#
# What dispatch-from-main does NOT protect: the checked-out tag's own
# build scripts (bun install hooks, build:sdk, Tauri's beforeBuildCommand,
# build.rs) run inside this job with the signing secrets in scope, for
# stable and beta alike. The control for that is this environment's
# required-reviewer approval — the approver is vouching for the code the
# tag points at, not just for "a release happening". Two consequences:
# desktop-experimental must keep main-grade merge controls (branch
# protection, maintainer-only pushes), and an approval should only follow
# a look at what the tag actually contains. Building betas without these
# secrets is not an option: unsigned bundles fail Gatekeeper and updater
# artifacts must be signed with the same key or beta installs cannot
# verify their updates.
if: github.ref == 'refs/heads/main'
environment: PublishDesktop
runs-on: macos-latest
@@ -223,8 +286,13 @@ jobs:
- name: Build, sign, and notarize desktop bundle
working-directory: apps/examples/desktop-app
run: bunx tauri build --target universal-apple-darwin --config src-tauri/tauri.release.conf.json
# Tauri merges repeated --config flags in order, so the beta overlay
# (product name, bundle identifier, beta update feed) layers on top of
# the release overlay without duplicating it. $CONFIG_ARGS is
# deliberately unquoted: it must word-split into separate flags.
run: bunx tauri build --target universal-apple-darwin $CONFIG_ARGS
env:
CONFIG_ARGS: ${{ needs.validate.outputs.channel == 'beta' && '--config src-tauri/tauri.release.conf.json --config src-tauri/tauri.beta.conf.json' || '--config src-tauri/tauri.release.conf.json' }}
# Telemetry config for the sidecar binary. Tauri's beforeBuildCommand
# (`bun run build` -> build:sidecar:bin) compiles the sidecar during
# this step and inlines these values into the binary via `--define`
@@ -258,8 +326,10 @@ jobs:
# sidecar would otherwise ship fine and only crash on the other arch.
- name: Verify bundle is a universal binary
working-directory: apps/examples/desktop-app
env:
PRODUCT: ${{ needs.validate.outputs.product }}
run: |
APP="src-tauri/target/universal-apple-darwin/release/bundle/macos/Cline Code.app"
APP="src-tauri/target/universal-apple-darwin/release/bundle/macos/${PRODUCT}.app"
if [ ! -d "$APP" ]; then
echo "app bundle not found at $APP"
exit 1
@@ -276,6 +346,57 @@ jobs:
esac
done
# Guardrail: the updater endpoint is compiled into the main binary as a
# string literal (tauri-build embeds the merged config via codegen), so
# assert the bundle carries this channel's feed URL and not the other
# channel's, before anything gets signed into a release. This catches a
# --config overlay that silently failed to apply: a beta bundle polling
# desktop-latest would pull its users onto stable builds, and a stable
# bundle polling desktop-beta would push betas to every stable install.
- name: Verify updater feed endpoint
working-directory: apps/examples/desktop-app
env:
CHANNEL: ${{ needs.validate.outputs.channel }}
PRODUCT: ${{ needs.validate.outputs.product }}
run: |
APP="src-tauri/target/universal-apple-darwin/release/bundle/macos/${PRODUCT}.app"
case "$CHANNEL" in
stable)
WANT="releases/download/desktop-latest/latest.json"
FORBID="releases/download/desktop-beta/latest.json"
;;
beta)
WANT="releases/download/desktop-beta/latest.json"
FORBID="releases/download/desktop-latest/latest.json"
;;
*)
echo "unknown channel: ${CHANNEL}"
exit 1
;;
esac
# Plain grep >/dev/null rather than grep -q: -q exits at the first
# match, SIGPIPEs strings, and would read as a failed pipeline under
# pipefail.
found=0
for bin in "$APP/Contents/MacOS/"*; do
if strings -a "$bin" | grep "$FORBID" >/dev/null; then
echo "$bin embeds the other channel's feed URL (${FORBID})"
exit 1
fi
if strings -a "$bin" | grep "$WANT" >/dev/null; then
found=1
fi
done
if [ "$found" -ne 1 ]; then
echo "No binary in ${APP}/Contents/MacOS embeds ${WANT}."
echo "The updater endpoint overlay did not apply; check the"
echo "--config flags on the build step and tauri.beta.conf.json."
exit 1
fi
echo "Updater endpoint verified: ${WANT}"
# Guardrail: assert the telemetry config actually made it into the
# compiled sidecar. Missing env on the build step (or a regression in
# the --define inlining) would otherwise ship a release with telemetry
@@ -308,25 +429,29 @@ jobs:
working-directory: apps/examples/desktop-app
env:
VERSION: ${{ needs.validate.outputs.version }}
PRODUCT: ${{ needs.validate.outputs.product }}
run: |
BUNDLE_DIR="src-tauri/target/universal-apple-darwin/release/bundle"
OUT="dist/publish"
mkdir -p "$OUT"
# "Cline" -> Cline, "Cline Beta" -> Cline-Beta
PREFIX="${PRODUCT// /-}"
DMG=$(find "$BUNDLE_DIR/dmg" -name '*.dmg' -print -quit)
if [ -z "$DMG" ]; then
echo "no DMG produced under $BUNDLE_DIR/dmg"
exit 1
fi
cp "$DMG" "$OUT/Cline-Code_${VERSION}_universal.dmg"
cp "$DMG" "$OUT/${PREFIX}_${VERSION}_universal.dmg"
TARBALL=$(find "$BUNDLE_DIR/macos" -name '*.app.tar.gz' -print -quit)
if [ -z "$TARBALL" ] || [ ! -f "${TARBALL}.sig" ]; then
echo "updater artifact or signature missing under $BUNDLE_DIR/macos"
exit 1
fi
cp "$TARBALL" "$OUT/Cline-Code_${VERSION}_universal.app.tar.gz"
cp "${TARBALL}.sig" "$OUT/Cline-Code_${VERSION}_universal.app.tar.gz.sig"
cp "$TARBALL" "$OUT/${PREFIX}_${VERSION}_universal.app.tar.gz"
cp "${TARBALL}.sig" "$OUT/${PREFIX}_${VERSION}_universal.app.tar.gz.sig"
ls -lh "$OUT"
@@ -337,9 +462,282 @@ jobs:
path: apps/examples/desktop-app/dist/publish/*
if-no-files-found: error
build-windows:
name: Build Windows (x64)
needs: validate
# Same gate rationale as the macOS build job above. This job additionally
# needs id-token: write for Azure OIDC: Windows binaries are
# Authenticode-signed with Azure Trusted Signing, authenticated through the
# PublishDesktop-environment federated credential on the cline-cli-signing
# Entra app (subject repo:cline/cline:environment:PublishDesktop).
if: github.ref == 'refs/heads/main'
environment: PublishDesktop
runs-on: windows-latest
timeout-minutes: 90
permissions:
contents: read
id-token: write
steps:
# All-or-nothing: an unsigned Windows desktop build is never acceptable
# (Smart App Control / WDAC block unsigned exes and SmartScreen flags
# unsigned installers), and Tauri would skip updater-artifact signing
# silently if the updater key were missing. Unlike the CLI pipeline
# there is no unsigned fallback here.
- name: Verify signing secrets are present
shell: bash
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_DESKTOP: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_DESKTOP }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
missing=()
for name in AZURE_CLIENT_ID AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID \
AZURE_TRUSTED_SIGNING_ENDPOINT AZURE_TRUSTED_SIGNING_ACCOUNT_NAME \
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_DESKTOP \
TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
[ -n "${!name}" ] || missing+=("$name")
done
if [ ${#missing[@]} -gt 0 ]; then
echo "Missing signing secrets for the Windows desktop build:"
printf ' - %s\n' "${missing[@]}"
echo
echo "The AZURE_* names are repository secrets; the TAURI_* names"
echo "live in the PublishDesktop environment. Refusing to build an"
echo "unsigned Windows desktop release."
exit 1
fi
echo "All Windows signing secrets are present."
# Every action in this job is SHA-pinned (unlike elsewhere in this
# file): they run with id-token: write and the updater signing key in
# scope, so a hijacked upstream tag must not be able to reach the
# signing identity or tamper with what gets signed and uploaded.
- name: Checkout code
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ needs.validate.outputs.tag }}
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: "1.3.13"
- name: Setup Rust
uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable branch
with:
# With a SHA-pinned action the toolchain no longer comes from the
# ref name, so it must be set explicitly.
toolchain: stable
# No Rust build cache, mirroring the macOS job: this job holds the
# updater signing key and an Azure signing session, and a restored cache
# archive is attacker-controlled if the Actions cache is poisoned.
- name: Install dependencies
run: bun install
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build SDK packages
run: bun run build:sdk
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
- name: Azure login (OIDC)
uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
# Tauri invokes signCommand once per staged binary (main exe, sidecar,
# NSIS uninstaller, and the installer itself). The overlay is generated
# here rather than committed because signCommand needs an absolute path
# to the signing script on this runner.
- name: Write signing config overlay
shell: bash
run: |
SCRIPT_PATH="${GITHUB_WORKSPACE//\\//}/apps/examples/desktop-app/scripts/tauri-sign-windows.ps1"
SIGN_CONF="${RUNNER_TEMP//\\//}/tauri-windows-sign.conf.json"
cat > "$SIGN_CONF" <<EOF
{
"\$schema": "https://schema.tauri.app/config/2",
"bundle": {
"windows": {
"signCommand": "pwsh -NoLogo -NoProfile -ExecutionPolicy Bypass -File ${SCRIPT_PATH} %1"
}
}
}
EOF
cat "$SIGN_CONF"
echo "SIGN_CONF=${SIGN_CONF}" >> "$GITHUB_ENV"
- name: Build and sign desktop bundle
shell: bash
working-directory: apps/examples/desktop-app
# NSIS only: the MSI (WiX) target adds nothing for direct-download
# distribution and the updater uses the NSIS artifact. $CONFIG_ARGS is
# deliberately unquoted: it must word-split into separate flags.
run: bunx tauri build --bundles nsis $CONFIG_ARGS --config "$SIGN_CONF"
env:
CONFIG_ARGS: ${{ needs.validate.outputs.channel == 'beta' && '--config src-tauri/tauri.release.conf.json --config src-tauri/tauri.beta.conf.json' || '--config src-tauri/tauri.release.conf.json' }}
# Telemetry inlined into the sidecar at compile time, same as macOS.
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
# Authenticode signing via scripts/tauri-sign-windows.ps1 (jsign +
# Azure Trusted Signing; the token comes from the azure/login session)
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_DESKTOP }}
# Updater artifact signing (minisign keypair, same key as macOS)
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
# Same guardrail as the macOS job: assert the compiled binary embeds
# this channel's updater feed URL and not the other channel's. Checked
# on the unbundled main exe because NSIS compresses the installer
# contents, which defeats a string search on the installer itself.
- name: Verify updater feed endpoint
shell: bash
working-directory: apps/examples/desktop-app
env:
CHANNEL: ${{ needs.validate.outputs.channel }}
run: |
case "$CHANNEL" in
stable)
WANT="releases/download/desktop-latest/latest.json"
FORBID="releases/download/desktop-beta/latest.json"
;;
beta)
WANT="releases/download/desktop-beta/latest.json"
FORBID="releases/download/desktop-latest/latest.json"
;;
*)
echo "unknown channel: ${CHANNEL}"
exit 1
;;
esac
found=0
for bin in src-tauri/target/release/*.exe; do
if grep -a "$FORBID" "$bin" >/dev/null; then
echo "$bin embeds the other channel's feed URL (${FORBID})"
exit 1
fi
if grep -a "$WANT" "$bin" >/dev/null; then
found=1
fi
done
if [ "$found" -ne 1 ]; then
echo "No exe in src-tauri/target/release embeds ${WANT}."
echo "The updater endpoint overlay did not apply; check the"
echo "--config flags on the build step and tauri.beta.conf.json."
exit 1
fi
echo "Updater endpoint verified: ${WANT}"
# Same guardrail as the macOS job, run natively on the Windows sidecar.
- name: Verify sidecar telemetry config was inlined
shell: bash
working-directory: apps/examples/desktop-app
run: |
SELFCHECK=$(./src-tauri/bin/code-sidecar-x86_64-pc-windows-msvc.exe --telemetry-selfcheck)
echo "$SELFCHECK"
if ! printf '%s' "$SELFCHECK" | grep -q '"enabled":true'; then
echo "Packaged sidecar reports telemetry disabled."
echo "Check the OTEL_* / TELEMETRY_SERVICE_API_KEY env on the"
echo "'Build and sign desktop bundle' step and the --define"
echo "inlining in scripts/build-sidecar-bin.ts."
exit 1
fi
if printf '%s' "$SELFCHECK" | grep -Eq '"otlp_endpoint_host":"(invalid-endpoint-url)?"'; then
echo "Packaged sidecar reports telemetry enabled but its OTLP"
echo "endpoint is missing, unparseable, or not an http(s) URL."
echo "Check the OTEL_EXPORTER_OTLP_ENDPOINT secret."
exit 1
fi
- name: Collect artifacts
shell: bash
working-directory: apps/examples/desktop-app
env:
VERSION: ${{ needs.validate.outputs.version }}
PRODUCT: ${{ needs.validate.outputs.product }}
run: |
BUNDLE_DIR="src-tauri/target/release/bundle"
OUT="dist/publish"
mkdir -p "$OUT"
# "Cline" -> Cline, "Cline Beta" -> Cline-Beta
PREFIX="${PRODUCT// /-}"
SETUP=$(find "$BUNDLE_DIR/nsis" -name '*-setup.exe' -print -quit)
if [ -z "$SETUP" ]; then
echo "no NSIS installer produced under $BUNDLE_DIR/nsis"
exit 1
fi
# The .sig is the updater (minisign) signature; without it the
# manifest generator cannot publish a windows-x86_64 entry.
if [ ! -f "${SETUP}.sig" ]; then
echo "updater signature missing next to $SETUP"
exit 1
fi
cp "$SETUP" "$OUT/${PREFIX}_${VERSION}_x64-setup.exe"
cp "${SETUP}.sig" "$OUT/${PREFIX}_${VERSION}_x64-setup.exe.sig"
ls -lh "$OUT"
# Independent Authenticode gate on the exact artifact users download.
# The signing script already verifies each file it signs, but this step
# would still catch an installer that skipped signCommand entirely.
- name: Verify Authenticode signatures
shell: pwsh
working-directory: apps/examples/desktop-app
run: |
# The Tauri bundler signs the sidecar in place, so check it here too;
# a WDAC-locked machine blocks the app at runtime if the sidecar it
# spawns is unsigned, even when the installer itself is fine.
$files = @(Get-ChildItem dist/publish/*.exe) + @(Get-Item src-tauri/bin/code-sidecar-x86_64-pc-windows-msvc.exe)
if ($files.Count -lt 2) { throw "expected at least the installer and the sidecar to verify" }
foreach ($file in $files) {
$sig = Get-AuthenticodeSignature $file.FullName
if ($sig.Status -ne "Valid") {
throw "Invalid Authenticode signature for $($file.Name): $($sig.Status) - $($sig.StatusMessage)"
}
Write-Host "$($file.Name): Valid ($($sig.SignerCertificate.Subject))"
}
- name: Upload artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-windows-x64
path: apps/examples/desktop-app/dist/publish/*
if-no-files-found: error
release:
name: Create GitHub release
needs: [validate, build]
needs: [validate, build, build-windows]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -364,14 +762,50 @@ jobs:
- name: Get Changelog Entry
id: changelog
env:
VERSION: ${{ needs.validate.outputs.version }}
run: |
# Grab content between the first "## " header and the next one
CONTENT=$(awk '/^## [0-9]/{if(found) exit; found=1; next} found{print}' apps/examples/desktop-app/CHANGELOG.md)
# Grab content between this release's "## <version>" header and the
# next one. Exact match, not "first section": once main and
# desktop-experimental cross-merge, stable and beta sections
# interleave and the top section may belong to the other channel.
CONTENT=$(awk -v ver="$VERSION" '$0 == "## " ver {found=1; next} /^## [0-9]/ {if (found) exit} found {print}' apps/examples/desktop-app/CHANGELOG.md)
if [ -z "$CONTENT" ]; then
echo "No '## ${VERSION}' section found in apps/examples/desktop-app/CHANGELOG.md"
exit 1
fi
echo "content<<EOF" >> $GITHUB_OUTPUT
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
printf "%s\n" "$CONTENT" > "$RUNNER_TEMP/release-notes.md"
# Slack section blocks reject text longer than 3000 characters, and the
# Slack action logs that rejection WITHOUT failing the step - so an
# over-long changelog silently drops the release announcement while the
# run stays green. Post a trimmed copy to Slack and link out to the full
# notes. The GitHub release body and updater manifest stay whole.
RELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/${{ needs.validate.outputs.tag }}"
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
echo "slack_content<<SLACK_EOF" >> $GITHUB_OUTPUT
echo "$SLACK_CONTENT" >> $GITHUB_OUTPUT
echo "SLACK_EOF" >> $GITHUB_OUTPUT
- name: Generate updater manifest
env:
VERSION: ${{ needs.validate.outputs.version }}
@@ -390,8 +824,15 @@ jobs:
id: prev_tag
env:
CURRENT_TAG: ${{ needs.validate.outputs.tag }}
CHANNEL: ${{ needs.validate.outputs.channel }}
run: |
PREV_TAG=$(git describe --tags --abbrev=0 --match 'desktop-v*' "$CURRENT_TAG^" 2>/dev/null || echo "")
# Stable compare links skip beta tags so they read stable -> stable;
# beta compares against whatever shipped last on either channel.
if [ "$CHANNEL" = "stable" ]; then
PREV_TAG=$(git describe --tags --abbrev=0 --match 'desktop-v*' --exclude 'desktop-v*-beta*' "$CURRENT_TAG^" 2>/dev/null || echo "")
else
PREV_TAG=$(git describe --tags --abbrev=0 --match 'desktop-v*' "$CURRENT_TAG^" 2>/dev/null || echo "")
fi
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Create GitHub Release
@@ -402,6 +843,7 @@ jobs:
# The repo-wide "latest" release stays owned by CLI releases; the
# desktop auto-update feed is the rolling desktop-latest release.
make_latest: "false"
prerelease: ${{ needs.validate.outputs.channel == 'beta' }}
files: dist/desktop/*
body: |
${{ steps.changelog.outputs.content }}
@@ -410,27 +852,58 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update auto-update feed (desktop-latest)
- name: Update auto-update feed
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHANNEL: ${{ needs.validate.outputs.channel }}
FEED: ${{ needs.validate.outputs.feed }}
run: |
if ! gh release view desktop-latest >/dev/null 2>&1; then
gh release create desktop-latest \
--title "Cline Code desktop (auto-update feed)" \
--notes "Rolling release backing the desktop app auto-updater. The latest.json asset points at the newest desktop-vX.Y.Z release. Do not delete." \
--latest=false \
--target "$(git rev-parse HEAD)"
# Belt and braces: recompute the feed from the channel and require it
# to agree with validate's output, so no single threading bug can
# point a publish at the other channel's feed. Stable installs poll
# desktop-latest and beta installs poll desktop-beta; crossing the
# streams either pushes betas to every stable user or strands beta
# users on stale builds.
case "$CHANNEL" in
stable) EXPECTED_FEED=desktop-latest ;;
beta) EXPECTED_FEED=desktop-beta ;;
*)
echo "unknown channel: ${CHANNEL}"
exit 1
;;
esac
if [ "$FEED" != "$EXPECTED_FEED" ]; then
echo "feed mismatch: validate says '${FEED}' but channel '${CHANNEL}' expects '${EXPECTED_FEED}'"
exit 1
fi
gh release upload desktop-latest dist/desktop/latest.json --clobber
if ! gh release view "$FEED" >/dev/null 2>&1; then
if [ "$CHANNEL" = "beta" ]; then
gh release create "$FEED" \
--title "Cline desktop beta (auto-update feed)" \
--notes "Rolling release backing the beta desktop app auto-updater. The latest.json asset points at the newest desktop-vX.Y.Z-beta.N release. Only beta installs poll this feed; stable installs use desktop-latest. Do not delete." \
--latest=false \
--prerelease \
--target "$(git rev-parse HEAD)"
else
gh release create "$FEED" \
--title "Cline desktop (auto-update feed)" \
--notes "Rolling release backing the desktop app auto-updater. The latest.json asset points at the newest desktop-vX.Y.Z release. Do not delete." \
--latest=false \
--target "$(git rev-parse HEAD)"
fi
fi
gh release upload "$FEED" dist/desktop/latest.json --clobber
- name: Summary
env:
VERSION: ${{ needs.validate.outputs.version }}
TAG: ${{ needs.validate.outputs.tag }}
FEED: ${{ needs.validate.outputs.feed }}
run: |
echo "Published Cline Code desktop v${VERSION}"
echo "Published Cline desktop v${VERSION}"
echo "Release: https://github.com/${GITHUB_REPOSITORY}/releases/tag/${TAG}"
echo "Auto-update feed refreshed: https://github.com/${GITHUB_REPOSITORY}/releases/download/desktop-latest/latest.json"
echo "Auto-update feed refreshed: https://github.com/${GITHUB_REPOSITORY}/releases/download/${FEED}/latest.json"
- name: Post release to Slack
uses: slackapi/slack-github-action@v3.0.1
@@ -439,17 +912,17 @@ jobs:
token: ${{ secrets.SLACK_RELEASE_BOT_TOKEN }}
payload: |
channel: "C0APVKGGZFC"
text: "Cline Code desktop v${{ needs.validate.outputs.version }}"
text: "Cline desktop v${{ needs.validate.outputs.version }}${{ needs.validate.outputs.channel == 'beta' && ' (beta)' || '' }}"
blocks:
- type: "section"
text:
type: "mrkdwn"
text: "Cline Code desktop v${{ needs.validate.outputs.version }}"
text: "Cline desktop v${{ needs.validate.outputs.version }}${{ needs.validate.outputs.channel == 'beta' && ' (beta)' || '' }}"
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
text: "<https://github.com/${{ github.repository }}/releases/tag/${{ needs.validate.outputs.tag }}|Download DMG> — installed apps auto-update on next launch${{ steps.prev_tag.outputs.prev_tag != '' && format(' | Full Changelog: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, needs.validate.outputs.tag) || '' }}"
text: "<https://github.com/${{ github.repository }}/releases/tag/${{ needs.validate.outputs.tag }}|Download DMG> — ${{ needs.validate.outputs.channel == 'beta' && 'beta channel: installs side by side with the stable app and only beta installs auto-update; stable users are unaffected' || 'installed apps auto-update on next launch' }}${{ steps.prev_tag.outputs.prev_tag != '' && format(' | Full Changelog: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, needs.validate.outputs.tag) || '' }}"
+50
View File
@@ -0,0 +1,50 @@
name: desktop-test
on:
push:
branches:
- main
- desktop-experimental
paths:
- "apps/examples/desktop-app/package.json"
- "apps/examples/desktop-app/scripts/dmg-background.ts"
- "apps/examples/desktop-app/scripts/dmg-background.test.ts"
- "apps/examples/desktop-app/src-tauri/dmg/background.png"
- "apps/examples/desktop-app/src-tauri/dmg/background@2x.png"
- ".github/workflows/desktop-test.yml"
pull_request:
branches:
- main
- desktop-experimental
paths:
- "apps/examples/desktop-app/package.json"
- "apps/examples/desktop-app/scripts/dmg-background.ts"
- "apps/examples/desktop-app/scripts/dmg-background.test.ts"
- "apps/examples/desktop-app/src-tauri/dmg/background.png"
- "apps/examples/desktop-app/src-tauri/dmg/background@2x.png"
- ".github/workflows/desktop-test.yml"
workflow_dispatch:
permissions:
contents: read
jobs:
dmg-background:
name: Test DMG background tooling
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/examples/desktop-app
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: "1.3.13"
# The suite only uses Bun/Node built-ins and committed artwork, so it does
# not need a workspace dependency install or macOS runner.
- name: Test DMG background tooling
run: bun run test:dmg-background
+44 -14
View File
@@ -23,11 +23,6 @@ on:
required: true
default: "main"
type: string
legacy-ref:
description: "Ref to build the legacy bundle from"
required: true
default: "legacy-extension"
type: string
publish:
description: "Publish to the VS Code Marketplace and Open VSX (unchecked: just build the .vsix artifact)"
required: true
@@ -130,31 +125,37 @@ jobs:
name: Test legacy bundle
runs-on: ubuntu-latest
# The tested revision, exported so the build job builds EXACTLY what
# this suite ran against. legacy-ref is a mutable branch name and the
# build job starts later — re-resolving the name there could pick up
# commits this gate never saw.
# this suite ran against. legacy-extension is a mutable branch name and
# the build job starts later — re-resolving the name there could pick
# up commits this gate never saw.
outputs:
tested-sha: ${{ steps.rev.outputs.sha }}
defaults:
run:
working-directory: apps/vscode
steps:
# Always the protected legacy-extension branch — deliberately not
# an input. An arbitrary ref here would be built into the published
# VSIX by the environment-less build job, and the publish
# environment approver only ever sees an opaque prebuilt artifact:
# the approval would protect the marketplace PAT but not the
# shipped bytes. Hardcoding the branch makes its protection rules
# load-bearing for releases. Legacy hotfix testing has its own
# workflow (ext-vscode-publish-legacy.yml).
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.legacy-ref }}
ref: legacy-extension
- name: Record tested revision
id: rev
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# Deliberately no dependency cache here: publish workflows do clean
# installs and should not restore actions caches.
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
@@ -489,6 +490,35 @@ jobs:
echo "CHANGELOG_EOF"
} >> "$GITHUB_OUTPUT"
# Slack section blocks reject text longer than 3000 characters, and
# the Slack action logs that rejection WITHOUT failing the step - so
# an over-long changelog silently drops the release announcement
# while the run stays green. Post a trimmed copy to Slack and link
# out to the full notes. The GitHub release body stays whole.
RELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/v${{ github.event.inputs.version }}"
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
{
echo "slack_content<<CHANGELOG_EOF"
echo "$SLACK_CONTENT"
echo "CHANGELOG_EOF"
} >> "$GITHUB_OUTPUT"
- name: Resolve previous release tag
id: prev_tag
if: ${{ !cancelled() && steps.publish_marketplace.outcome == 'success' }}
@@ -544,7 +574,7 @@ jobs:
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
+53 -20
View File
@@ -21,20 +21,17 @@ on:
options:
- pre-release
- release
branch:
description: "Branch holding the legacy extension code"
required: true
default: "legacy-extension"
type: string
# Read-only by default. The publish job elevates itself to contents: write for
# the tag push and GitHub release; nothing here needs packages/checks/PR
# write. Keeping the default minimal matters doubly in this workflow because
# the test job runs BEFORE any environment approval — it must never hold a
# write token while executing checked-out code.
permissions:
contents: write
packages: write
checks: write
pull-requests: write
contents: read
concurrency:
group: ext-vscode-publish-legacy-${{ github.event.inputs.branch }}
group: ext-vscode-publish-legacy
cancel-in-progress: false
jobs:
@@ -50,18 +47,23 @@ jobs:
run:
working-directory: apps/vscode
steps:
# Always the protected legacy-extension branch — deliberately not
# an input. This job runs full npm lifecycle scripts from the
# checked-out code with no environment approval, and the publish
# job below does the same next to the marketplace PATs; an
# arbitrary ref here would hand both of them attacker-controlled
# code. Hardcoding the branch makes its protection rules
# load-bearing for releases.
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.branch }}
ref: legacy-extension
# Deliberately no dependency cache here: publish workflows do clean
# installs and should not restore actions caches.
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
@@ -99,16 +101,20 @@ jobs:
name: Publish Legacy Extension
runs-on: ubuntu-latest
environment: publish
# For the tag push in Resolve Release Tag and the GitHub release.
permissions:
contents: write
defaults:
run:
working-directory: apps/vscode
steps:
# Check out the legacy branch (NOT main). fetch-depth: 0 + tags so we
# can create/push the release tag and compute the previous tag.
# Check out the legacy branch (NOT main; hardcoded — see the test
# job's checkout comment). fetch-depth: 0 + tags so we can
# create/push the release tag and compute the previous tag.
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.branch }}
ref: legacy-extension
fetch-depth: 0
fetch-tags: true
lfs: true
@@ -117,7 +123,7 @@ jobs:
id: resolve_tag
working-directory: ${{ github.workspace }}
env:
BRANCH: ${{ github.event.inputs.branch }}
BRANCH: legacy-extension
run: |
# Tag is derived from the package version on the legacy branch.
VERSION=$(node -p "require('./apps/vscode/package.json').version")
@@ -258,6 +264,33 @@ jobs:
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Slack section blocks reject text longer than 3000 characters, and
# the Slack action logs that rejection WITHOUT failing the step - so
# an over-long changelog silently drops the release announcement
# while the run stays green. Post a trimmed copy to Slack and link
# out to the full notes. The GitHub release body stays whole.
RELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/${{ steps.resolve_tag.outputs.tag }}"
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
echo "slack_content<<SLACK_EOF" >> $GITHUB_OUTPUT
echo "$SLACK_CONTENT" >> $GITHUB_OUTPUT
echo "SLACK_EOF" >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
@@ -287,7 +320,7 @@ jobs:
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
@@ -14,9 +14,12 @@ name: ext-vscode-publish-nightly
# pre-release publishes.
on:
schedule:
# Every day at 4:00 AM PST (12:00 UTC)
- cron: "0 12 * * *"
# Manual dispatch only. The nightly cron was removed deliberately: the
# PublishNightly environment gained required reviewers, and an unattended
# cron run would just sit `waiting` on that approval, hold this workflow's
# concurrency group, and silently cancel every later scheduled run behind it
# (that is exactly what happened between 2026-07-31 and 2026-08-21, killing
# 20 consecutive nightlies). Cut a nightly by dispatching this workflow.
workflow_dispatch:
inputs:
legacy-ref:
@@ -74,8 +77,9 @@ jobs:
- name: Checkout legacy source
uses: actions/checkout@v4
with:
# NOTE: inputs are empty strings on `schedule` events, so the ||
# fallback (not the input's declared default) is what the cron uses.
# NOTE: the || fallback is retained so this stays correct if a
# non-dispatch trigger is ever added back (inputs are empty strings
# on e.g. `schedule` events, where the declared default does not apply).
ref: ${{ inputs.legacy-ref || 'legacy-extension' }}
path: legacy-src
lfs: true
@@ -234,6 +234,33 @@ jobs:
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Slack section blocks reject text longer than 3000 characters, and
# the Slack action logs that rejection WITHOUT failing the step - so
# an over-long changelog silently drops the release announcement
# while the run stays green. Post a trimmed copy to Slack and link
# out to the full notes. The GitHub release body stays whole.
RELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/${{ steps.resolve_tag.outputs.tag }}"
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
echo "slack_content<<SLACK_EOF" >> $GITHUB_OUTPUT
echo "$SLACK_CONTENT" >> $GITHUB_OUTPUT
echo "SLACK_EOF" >> $GITHUB_OUTPUT
- name: Package and Publish Extension
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
@@ -303,7 +330,7 @@ jobs:
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
+9 -8
View File
@@ -80,8 +80,9 @@ jobs:
include: ${{ fromJson(needs.matrix_prep.outputs.matrix) }}
runs-on: ${{ matrix.runner }}-latest
timeout-minutes: 20
# Nothing in this job uses OIDC, so it does not need an id-token
# permission.
permissions:
id-token: write
contents: read
defaults:
run:
@@ -93,6 +94,9 @@ jobs:
with:
bun-version: 1.3.14
# Cache keys below are exact-match only (no restore-keys prefix
# fallbacks); a miss just means a cold install, which is acceptable.
# Cache Bun's global install cache - keyed on the authoritative root bun.lock.
- name: Cache Bun install cache
uses: actions/cache@v4
@@ -100,8 +104,6 @@ jobs:
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
# Cache VS Code installation
- name: Cache VS Code
@@ -110,8 +112,6 @@ jobs:
with:
path: apps/vscode/.vscode-test
key: vscode-${{ runner.os }}-stable-${{ hashFiles('apps/vscode/.vscode-test.mjs', 'apps/vscode/package.json') }}
restore-keys: |
vscode-${{ runner.os }}-stable-
# Cache Playwright browsers
- name: Cache Playwright browsers
@@ -123,8 +123,6 @@ jobs:
~/Library/Caches/ms-playwright
~/AppData/Local/ms-playwright
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
playwright-browsers-${{ runner.os }}-
# Single root install resolves the entire bun workspace at once (replaces
# the per-package `npm ci` steps for apps/vscode + webview-ui).
@@ -171,9 +169,12 @@ jobs:
if: matrix.runner != 'ubuntu'
run: bun run test:e2e:optimal
# Repo-root relative: the job's `working-directory` default applies to `run`
# steps only, so an apps/vscode-relative path here silently matches nothing
# and every failing run uploads no recordings at all.
- uses: actions/upload-artifact@v4
if: ${{ failure() }}
with:
name: playwright-recordings-${{ matrix.runner }}
path: |
test-results/playwright/
apps/vscode/test-results/
+28 -1
View File
@@ -282,6 +282,33 @@ jobs:
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "${DELIMITER}" >> $GITHUB_OUTPUT
# Slack section blocks reject text longer than 3000 characters, and the
# Slack action logs that rejection WITHOUT failing the step - so an
# over-long changelog silently drops the release announcement while the
# run stays green. Post a trimmed copy to Slack and link out to the full
# notes. The GitHub release body stays whole.
RELEASE_URL="https://github.com/${GITHUB_REPOSITORY}/releases/tag/sdk/sdk/v${{ steps.version.outputs.version }}"
SLACK_CONTENT=$(CONTENT="$CONTENT" RELEASE_URL="$RELEASE_URL" python3 -c '
import os
content = os.environ["CONTENT"]
more = "\n\n… <%s|Read the full release notes>" % os.environ["RELEASE_URL"]
if len(content) <= 3000:
print(content, end="")
else:
budget = 3000 - len(more)
kept, used = [], 0
for line in content.splitlines(keepends=True):
if used + len(line) > budget:
break
kept.append(line)
used += len(line)
body = "".join(kept).rstrip() if kept else content[:budget].rstrip()
print(body + more, end="")
')
echo "slack_content<<${DELIMITER}" >> $GITHUB_OUTPUT
echo "$SLACK_CONTENT" >> $GITHUB_OUTPUT
echo "${DELIMITER}" >> $GITHUB_OUTPUT
- name: Create GitHub Release
if: steps.check_commits.outputs.skip != 'true' && steps.channel.outputs.channel == 'latest'
uses: softprops/action-gh-release@v1
@@ -333,7 +360,7 @@ jobs:
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: ${{ toJSON(steps.changelog.outputs.slack_content) }}
- type: "context"
elements:
- type: "mrkdwn"
+6 -5
View File
@@ -46,6 +46,12 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
# @cline/ui imports @cline/shared/browser (generated-media), which
# resolves to dist output — build it before anything typechecks or
# builds the ui package.
- name: Build shared package
run: bun -F @cline/shared build
- name: Typecheck UI
run: bun -F @cline/ui typecheck
@@ -58,11 +64,6 @@ jobs:
- name: Build UI package
run: bun -F @cline/ui build
# The desktop chat test imports @cline/shared/browser, which resolves to
# dist output that nothing else in this job builds.
- name: Build shared package
run: bun -F @cline/shared build
- name: Test desktop chat integration
run: bun -F @cline/code test:chat-ui
+2
View File
@@ -88,7 +88,9 @@ apps/vscode/tsconfig.test.generated.json
.next/dev/static
**/src-tauri/target/debug/.fingerprint
apps/examples/desktop-app/src-tauri/target
apps/examples/desktop-app/src-tauri/dmg/background.gen.tiff
apps/examples/desktop-app/webview/.next
# Next.js generated type shim (churns between dev and build)
apps/examples/desktop-app/webview/next-env.d.ts
apps/examples/desktop-app/.cursor/settings.json
+231
View File
@@ -1,5 +1,236 @@
# Changelog
## [4.1.16]
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
### Fixed
- Cost estimates are no longer shown for providers billed by a flat-rate subscription (ClinePass, ChatGPT via Codex, and Claude Code). The task header and model pricing rows rendered API-rate dollar figures that read as real charges on top of the subscription, including a flash of them on every chat-view mount while provider listings were loading.
- Signing back in no longer moves your last-used provider off ClinePass on credential refresh.
- Hooks now resolve their workspace from the VS Code window instead of shared global state in `~/.cline`. With a second window open on another project, a workspace's `.clinerules/hooks` scripts were never discovered, and hook cwd and the workspace paths passed to hook scripts resolved against whatever project some other or older Cline instance last recorded.
- New files are now created with your platform's native line endings.
- Fixed the codebase search tool crashing on files containing a single enormous line.
- Credentials embedded in git remote URLs are now redacted from the workspace information sent to the model, which also now carries richer workspace metadata.
- Installing an MCP server from the marketplace no longer misreads the catalog's `--` separator as part of the server command.
- The hub's event log can no longer grow until it fills your disk.
### Changed
- The per-tool MCP auto-approve checkboxes are hidden. MCP auto-approval is governed solely by the global "Use MCP servers" toggle — the per-tool checkboxes were no-ops that implied granularity the approval path does not have.
## [4.1.15]
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
### Fixed
- Auto-approve every MCP tool call while the "Use MCP servers" toggle is on. The toggle only took effect on tools that had also been opted in individually, so turning it on appeared to do nothing; it now governs all MCP tools on its own.
## [4.1.14]
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
### Added
- Refresh the built-in model catalog. New entries include Claude Fable 5, Grok 4.6 on Vertex, several DeepSeek V4 Flash variants (including the vision preview), MiMo v2.5, Qwen3.8 27B, Gemma 4 26B, LongCat 2.0, Nemotron 3.5 Lightning, and Thinking Machines' Inkling models.
### Fixed
- Restore task completion telemetry for interactive sessions. A share of interactive stops routed through a teardown path that never reported completion after 4.1.11 changed how session status is tracked; every session now reports it exactly once.
## [4.1.13]
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
### Fixed
- Restore tool calling for custom OpenAI-Compatible models whose capability list was inferred from convenience flags like `supportsReasoning`. The inferred list read as an authoritative denial and stripped every tool from the request; an explicitly authored capability list still decides.
- Keep Hub-backed sessions intact across a Hub restart or upgrade. Clients replay the events they missed while disconnected, and the same event is no longer delivered twice when the replay and live streams overlap.
- Carry session and client identity into Langfuse traces for Hub-backed and delegated-agent runs, which previously arrived without their session grouping or client version.
## [4.1.12]
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
### Fixed
- Enforce enterprise MCP controls on the Customize marketplace. MCP entries are now hidden when remote config disables the marketplace, and limited to `allowedMCPServers` when an allowlist is configured.
- Restore tool calling for custom OpenAI-Compatible models whose stored capability list was empty.
## [4.1.11]
Everything here lands through the SDK bundle, so it applies to windows running that bundle — except the last section, which is a legacy-bundle fix.
### Added
- Let models that support it generate images during a task. Generated images render inline in the conversation.
### Fixed
- Fix code actions failing with "command not found" on VS Code 1.134.
- Fix `@` file mentions breaking on paths that contain spaces.
- Show the diff edit view for multi-line edits in files with CRLF line endings.
- Continue the surviving session when resuming a task, instead of rebuilding it from the original task text.
- Clear the task-scoped settings overlay when the task view is cleared or switched, so one task's overrides no longer leak into the next.
- Honor the classic truncation range when migrating legacy tasks.
- Preserve LiteLLM input token limits instead of overwriting them with catalog values.
- Restore custom base URLs for Gemini, and normalize legacy host-root values so they keep working.
- Point provider signup links at each provider's API key page instead of a generic landing page.
- Load skill slash commands through the skills tool instead of pasting their instructions into your message, which previously delivered them twice.
- Stop offering image, voice, and other non-chat models in chat model pickers.
- Deliver a `PreToolUse` hook's `contextModification` to the model again, and wait for `PostToolUse` hooks so their output and `cancel` control are honored.
- Show tool activity a provider runs itself — every tool the Claude Code provider executes inside its own session — instead of dropping it from the conversation.
- Fix `run_commands` failing with ENOENT when a structured command carried a full command line with no arguments.
- Run PowerShell commands fail-fast, so a pipeline erroring per item stops at the first error instead of flooding output and still reporting success.
- Keep remote configuration in step with the SDK: coordinated refreshes, session gating, and a fail-closed opt-out.
### Changed
- Show the billed cost for Cline gateway usage.
- Refresh the model catalog, which adds AMD, Arcee, Echo, Jalapeno, Kosmik, LLM Gateway, RunInfra, and SCNet as providers and updates model lists, pricing, and per-provider default models across the board.
### Fixed (legacy bundle)
- Only treat an Anthropic `invalid_request_error` as a context-overflow when its message says so. An unrelated invalid request (bad tool schema, oversized image, unknown model id) no longer triggers context-overflow recovery.
## [4.1.10]
Everything in this release lands through the SDK bundle, so it applies to windows running that bundle and not the legacy one. The legacy bundle is unchanged from 4.1.9.
### Added
- Let models that support it search the web during a task, with a toggle in Feature Settings to turn it on. Search calls and their results appear in the conversation and persist across reloads.
### Fixed
- Stop two Cline installations on different builds from shutting each other's Hub daemon down in a loop, which killed live sessions with an abnormal socket close. Build identity is now compared through a total order, so at most one side of a pair can decide to retire the other.
- Leave a Hub that is still serving sessions in place instead of replacing it mid-handshake; the swap happens once it goes idle.
- Reclaim idle plugin sandbox processes instead of leaving them running for the life of the session.
### Changed
- Refresh the model catalog, which adds Crusoe as a provider and updates model lists and per-provider default models across the board.
## [4.1.9]
### Changed
- Use the editor's foreground color for diff block text, so diffs stay legible in themes where the previous hardcoded color washed them out.
- Switch the interface to Inter and Geist Mono.
### Fixed
- Don't discard a successfully refreshed Cline token when the old one was already past expiry, which made the first request after a long idle period fail despite valid credentials.
- Stop the legacy-task migration backlog from spamming telemetry, and record a migration outcome only once the seeded session actually persists, so a failed migration is no longer reported as a success.
- Report involuntary Cline logouts (a rejected refresh token) instead of clearing credentials silently.
### Fixed (SDK bundle only)
These land through SDK v0.0.74 and therefore apply to windows running the SDK bundle, not the legacy one.
- Fix the Claude Code provider being unusable for agentic work: it now runs its own native tools instead of receiving tool definitions it cannot bridge, anchors the session on your workspace directory, and loads `~/.claude` plus project settings so your permission rules apply.
- Reject truncated tool-call JSON instead of silently "repairing" it into wrong arguments.
- Fix strict providers rejecting a turn with "user message must have content" when a message's content held only empty text parts.
- Fix a mid-turn crash on streamed tool calls with non-zero or non-contiguous indexes, hit through LiteLLM's Anthropic passthrough.
- Report disjoint per-request token buckets instead of re-counting the whole cached conversation on every request, which inflated per-task totals roughly 5x on cache-heavy sessions.
## [4.1.8]
### Added
- Enter any Vertex model ID by hand, including models the catalog doesn't list yet.
- Support Fable 5 on Vertex.
### Changed
- Show the full model catalog for every Vertex region instead of filtering the picker down to a hardcoded list of global-endpoint models, which lagged behind every model launch. Picking a model the region doesn't serve now fails at request time with recovery guidance in the error row.
- Report Fable 5 cost on Vertex as unknown rather than applying Anthropic's list price, which understated what Vertex actually bills — its rates are region-dependent.
- Make the auto-approve menu the single source of truth for unattended runs and remove the Yolo Mode toggle, which was cosmetic: nothing in the approval path read it. Setups that had Yolo Mode (or auto-approve-all) turned on are migrated to auto-approving every action, so they keep running unattended.
### Fixed
- Respect your configured max output tokens when the compaction summarizer requests a summary.
- Remove the stale "Double-Check Completion" feature tip.
## [4.1.7]
### Added
- Restore the "View Changes" button on completion rows, backed by SDK checkpoints, so you can review everything a task touched from the completion card.
- Bring back a copy button on turn-final response rows.
- Support pre-registered OAuth clients for remote MCP servers, for setups where dynamic client registration isn't available.
### Changed
- Fade the "View Changes" button until changes since the last message are confirmed, and hide it entirely when there is nothing to show.
- Centralize plugin settings and contributions, with host-aware snapshots and atomic plugin toggles.
- Carry execution context in scheduled run reports — readable headers, schedule metadata, durations, and lifecycle error details.
### Fixed
- Preserve prompts queued during a turn when that turn is interrupted: they survive aborts, are drained after a turn aborts itself, and the stop is surfaced instead of the queue being silently dropped.
- Keep session context durable across aborts and hub restarts, so an interrupted session resumes with the state it had.
- Settle the turn phase when a mode switch aborts a running turn.
- Report queued-turn failures as `run.failed` instead of letting them complete silently.
- Keep a hung MCP server from taking down session creation, and give stdio servers that were never configured a 30-second initialize budget instead of blocking indefinitely.
- Surface OAuth authorization for SSE MCP servers on a 401 instead of failing outright.
- Route LiteLLM through Chat Completions instead of the Responses API, fixing requests against LiteLLM proxies.
- Retry network interruptions that happen mid-stream but before any model output, instead of failing the turn.
- Use the configured fetch for Vertex ADC token refreshes, so they work behind proxies and custom transports.
- Include files that were untracked when a snapshot was taken in checkpoint diffs, and pick up checkpoints when git is initialized part-way through a session.
- Fall back to the session cwd or Desktop for @-mention file search in empty windows.
- Never run a foreign compiled plugin-sandbox bootstrap for a source host.
## [4.1.6]
### Added
- Offer `meta/muse-spark-1.2-contributor` on the Cline provider, alongside a refreshed model catalog.
### Fixed
- Attribute error telemetry to the model actually in use for a run, so failures are no longer reported against the wrong model.
## [4.1.5]
### Added
- Explain when a free model promotion ends. Requests to a retired free model now show a dedicated notice with a button to pick another model, instead of a generic error with nothing but a Retry prompt.
### Changed
- Map reasoning settings onto a shared path across AI SDK providers, so effort levels and enable/disable toggles behave consistently (including on Ollama) instead of relying on per-provider overrides.
## [4.1.4]
### Added
- Recognize Chutes as a provider.
- Show skills alongside workflows in the slash command menu, and disambiguate commands that share a name instead of letting one shadow the other.
### Changed
- Remove model-initiated plan-to-act switching. Switching out of plan mode is now driven by you, not by the model deciding mid-turn.
- Hard-block file-editing shell commands in plan mode instead of relying on prompting alone. Read-only investigation still works, but file manipulation, in-place editors, redirection to files, mutating git subcommands, and package installs are refused.
### Fixed
- Stop treating a turn that completes with a plan as a failed turn when a plan-blocked command was its only tool call. The turn no longer ends in the error state with a Retry footer, and toggling to Act correctly re-runs the presented plan instead of appearing to do nothing.
- Show tool paths relative to the workspace in the chat view instead of absolute paths.
- Reset pending attachments when starting a new task, so images from the previous task no longer carry over.
- Surface a clear error when the selected provider has no API key configured, instead of a generic failure.
- Refresh MCP tool and resource lists when a server sends a `list_changed` notification, instead of only showing a toast.
- Show installed plugins under their real package names instead of all appearing as "index".
- Correct the Linux keybinding label in the Plan/Act mode tooltip.
- Recover from running out of context instead of failing with a raw provider error — the run compacts and retries once, and the cases that genuinely cannot be recovered explain why.
- Retry empty model responses on every provider rather than only Ollama, fixing hard "Model returned empty response" failures on OpenRouter, Cline, and OpenAI-compatible endpoints.
- Stop Claude 4.6+ and 5.x models being rejected with "thinking.type.enabled is not supported" when they resolve from the offline catalog or from a hand-typed model id.
- Restore Bedrock prompt caching, which reported zero cache reads and writes because the provider sent a cache format Bedrock discards, and route Bedrock foundation models through geo inference profiles.
- Send `max_completion_tokens` for reasoning models on OpenAI-compatible endpoints, and substitute image content for models without image support instead of failing the request.
- Inherit the MiniMax default model from models.dev, and refresh the bundled catalog, which adds Infomaniak and SCX.ai.
- Report the same provider failure once instead of twice in error telemetry, and rate-limit repeated failures from unattended retry loops.
## [4.1.3]
### Fixed
+113
View File
@@ -1,5 +1,118 @@
# Cline CLI Changelog
## 3.0.60
- Fixed the background hub process ballooning in memory during long sessions — session status updates were broadcasting a full copy of the conversation transcript to every connected client, which on a large task could grow the process to tens of gigabytes. Upgrading retires the running hub so the fix takes effect on the next command
- New files are now created with your platform's native line endings
- Fixed the codebase search tool crashing on files that contain a single enormous line
- Cost estimates are no longer shown for Claude Code. Its usage is typically covered by a Claude Pro/Max subscription, but its models reuse Anthropic API pricing, so Cline was showing charges you were not being billed
- Credentials embedded in git remote URLs are now redacted from the workspace information sent to the model
- Installing an MCP server no longer misreads a `--` separator in the install arguments as part of the server command
- Refreshed the model catalog. Adds seven providers (Agnes AI, Aixy, IteraCompute, LLM Tech, NeoSmith, Pendra, and Standard Compute) and updates model lists and pricing across providers. The resolved default model changes for ClinePass (now GLM 5.3), Z.ai, Hugging Face, evroc, LLM Gateway, NanoGPT, and Weights & Biases, so if you use one of those without pinning a model you will get a different default
## 3.0.58
- The first-launch "Try ClinePass" dialog no longer advertises the $4.99 first-month promo, which is ending
- The hub's event log is now capped at 64 MiB on disk. Events carrying full session snapshots could previously grow the log to tens of gigabytes on a long-running hub, since deleting rows never shrinks the file. Oldest events are dropped first and the space is returned, and pruning runs on volume as well as on a timer
- Refreshed the model catalog. Adds two providers (AgentRouter and Opper) and updates model lists and pricing across providers. The resolved default model changes for Aki.io and NanoGPT, so if you use one of those without pinning a model you will get a different default
## 3.0.57
- Added `cline hub drain`, which stops a hub from accepting new mutating work while it finishes what it is already running, and `cline hub drain --off` to lift it
- Added `cline hub upgrade`, which drains the hub, waits for it to go idle, stops it, and starts a fresh one on the current build. An aborted upgrade lifts the drain again, so the hub is never left refusing work
- Sessions now survive a hub restart. A reconnecting client replays the events it missed while disconnected, deduped by event id so nothing is delivered twice
- Fixed tool calling being silently disabled for custom OpenAI-Compatible models whose capability list was inferred from convenience flags like `supportsReasoning`. The inferred list read as an authoritative denial and stripped every tool from the request
- Langfuse traces now carry session and client identity for hub-backed and delegated-agent runs, instead of arriving without their session grouping or client version
- Refreshed the model catalog, which updates model lists and pricing across providers and changes the resolved default model for several of them (DeepSeek, Crof, CrossModel, Eden AI, Kilo, and NanoGPT)
## 3.0.56
- Models that support image generation can now produce media during a turn. The TUI saves each generated file to a temporary path and prints it so you can open it with your usual tools, HTML session exports embed images inline, and ACP clients receive generated images as image content
- Skill slash commands now load through the skills tool instead of expanding into your message. History and resume show the `/command` you typed instead of the whole skill body, and the instructions reach the model once instead of twice. Workflows still expand, as does zen mode, whose preset has no skills tool
- Image, voice, and other non-chat models are no longer offered in the onboarding and model pickers or ACP model listings, and are rejected for `--model`
- Fixed TUI dialog colors not following theme changes live
- Fixed the account dialog's selection chevron so it matches the other dialogs
- Fixed provider-executed tool activity — every tool the Claude Code provider runs inside its own session — being dropped instead of shown as a tool card
- Fixed `PreToolUse` hook `contextModification` never reaching the model, and `PostToolUse` hooks running fire-and-forget with their output and `cancel` control discarded
- Fixed `run_commands` failing with ENOENT when a structured command carried a full command line with no `args`
- PowerShell commands now fail fast on the first error instead of emitting an error record per enumerated item and still reporting success
- Fixed Gemini custom base URLs configured as a host root
- Fixed `cline schedule` commands against a remote hub, which now register a workspace client so they are authorized under the new workspace-scoped schedule rules
- Usage now displays the billed gateway cost
- Refreshed the model catalog, which adds AMD, Arcee, Echo, Jalapeno, Kosmik, LLM Gateway, RunInfra, and SCNet as providers and updates model lists, pricing, and per-provider default models across the board
## 3.0.55
- Auto-updates no longer install while a CLI is attached to the Hub. The update is recorded at startup and installed on exit, once the Hub confirms nothing else is attached, so a background update can no longer swap the package out from under a live session and kill it with `Hub connection closed (code=1006)`. `cline update` still installs immediately and now tells you the update applies on next start
- Added protections for an update landing under CLI 3.0.54 and earlier, whose updater restarts the Hub mid-session and then rejects every replacement, bricking a running session. The newly installed package defuses that path during install instead of leaving it to fire
- Fixed two Cline installations on different builds shutting each other's Hub daemon down in a loop, which killed every live session with an abnormal socket close. Build identity is now compared through a total order, so at most one side of a pair can ever decide to retire the other (from SDK v0.0.75)
- A newer build no longer replaces a Hub that is still serving sessions — it attaches to it and the swap happens on a later launch, instead of the sessions dying mid-handshake (from SDK v0.0.75)
- Removed the "outdated Hub" notice. It reported a state you cannot act on, and the toast was capped narrower than the message, so it rendered cut off before the reassuring half of the sentence at every terminal width. The prompt for a genuine build mismatch, where there is something to do, is unchanged
- Streaming assistant markdown no longer flashes back to raw text. Settled headings, links, and code stay rendered as new chunks arrive instead of the whole message being rebuilt and re-highlighted on every chunk, which also stops the transcript from jumping vertically mid-stream
- Web search calls and their results from models that run search natively now render in the transcript (from SDK v0.0.75)
- Idle plugin sandbox processes are now reclaimed instead of lingering for the life of the session (from SDK v0.0.75)
- `cline doctor fix` now reports honestly: processes that survived a kill are separated from ones that appeared while the fix ran, a live parent respawning a daemon is named, and a startup lock held by a running process is reported as held rather than leaked (from SDK v0.0.75)
- Refreshed the model catalog, which adds Crusoe as a provider and updates model lists and per-provider default models across the board (from SDK v0.0.75)
## 3.0.54
- Fixed the Claude Code provider being unusable for agentic work: the provider now runs its own native tools instead of receiving tool definitions it cannot bridge, the session is anchored on your workspace directory instead of inheriting the host's cwd, and `~/.claude` plus project settings are loaded so your permission rules apply. File edits under the workspace are auto-approved; command execution stays gated by your own Claude settings (from SDK v0.0.74)
- Fixed truncated tool-call JSON being silently "repaired" into wrong arguments — a payload with an unterminated string is now rejected rather than getting an invented terminator (from SDK v0.0.74)
- Fixed strict providers rejecting a turn with "user message must have content" when a message's content held only empty text parts (from SDK v0.0.74)
- Fixed a mid-turn crash on streamed tool calls with non-zero or non-contiguous indexes, hit through LiteLLM's Anthropic passthrough (from SDK v0.0.74)
- Managed Hub daemons now upgrade directionally: when another Cline install ships a newer Hub build, the CLI attaches to the newer daemon and prompts you to update and restart instead of the two installs repeatedly retiring each other's daemons. Yolo and sandbox sessions, which never attach to the shared Hub, are not interrupted by that prompt (from SDK v0.0.74)
- Fixed the Hub daemon logging an unhandled `hub server close failed` error and exiting non-zero whenever a client was still connected at shutdown (from SDK v0.0.74)
- Fixed per-task token totals being inflated roughly 5x on cache-heavy sessions — token telemetry now reports disjoint uncached-input, cache-read, and cache-write buckets instead of re-counting the whole cached conversation on every request (from SDK v0.0.74)
- Upgrading the CLI now retires an already-running Hub daemon and respawns it on the new code, instead of the upgraded CLI continuing to talk to a daemon executing the previous release
## 3.0.53
- Fixed the CLI reconnecting to a stale Hub daemon after an upgrade. Hub daemons now carry a runtime build fingerprint, so an upgraded CLI retires and respawns a daemon still running older code instead of attaching to it (from SDK v0.0.73)
- Fixed compaction being silently skipped on reasoning models. The summarizer no longer hardcodes a 1024-token output cap — it honors your max output tokens setting, defaults to 4096 (lowered when the model reports less), and logs a diagnostic when a summary comes back empty (from SDK v0.0.73)
- Added Fable 5 (`claude-fable-5`) to the Vertex model catalog. Pricing is intentionally omitted because Vertex bills region-dependently, so cost shows as unknown rather than wrong (from SDK v0.0.73)
- Custom Vertex model IDs are now passed through unchanged, routing Claude-style IDs to the Anthropic-on-Vertex path (from SDK v0.0.73)
## 3.0.52
- Added `cline mcp uninstall` for removing an installed MCP server
- Schedules now reuse your saved provider settings instead of needing provider configuration of their own
- Queued messages are legible on light-theme terminals — they were previously rendered in a color that washed out against a light background
- MCP tool results render as readable text in the TUI instead of escaped JSON, and binary payloads survive being expanded instead of being mangled
- Malformed tool input/output payloads no longer break rendering — the formatters degrade gracefully instead of throwing
- Prompts queued during a turn now survive being interrupted: they are preserved across aborts, drained after a turn aborts itself, and the stop is surfaced instead of leaving the queue silently dropped (from SDK v0.0.72)
- Session context stays durable across aborts and hub restarts, so an interrupted session resumes with the state it had (from SDK v0.0.72)
- A hung MCP server no longer takes down session creation, and stdio servers that were never configured get a 30-second initialize budget instead of blocking indefinitely (from SDK v0.0.72)
- Remote SSE MCP servers surface an OAuth authorization prompt on a 401 instead of failing outright, and pre-registered OAuth clients are supported for setups without dynamic client registration (from SDK v0.0.72)
- LiteLLM requests route through Chat Completions instead of the Responses API, fixing calls against LiteLLM proxies (from SDK v0.0.72)
- Network interruptions that happen mid-stream but before any model output are retried instead of failing the turn (from SDK v0.0.72)
- Vertex ADC token refreshes use the configured fetch, so they work behind proxies and custom transports (from SDK v0.0.72)
- Checkpoint diffs include files that were untracked when the snapshot was taken, and checkpoints are picked up when git is initialized part-way through a session (from SDK v0.0.72)
- Scheduled run reports carry execution context — readable headers, schedule metadata, durations, and lifecycle error details (from SDK v0.0.72)
## 3.0.51
- Reasoning effort now applies consistently across providers instead of going through per-provider thinking overrides, including Ollama, and asking for reasoning to be off is respected everywhere (from SDK v0.0.71)
- `meta/muse-spark-1.2-contributor` is now selectable on the Cline provider, alongside a refreshed model catalog (from SDK v0.0.71)
- Error telemetry now reports the model that was actually in use for the run (from SDK v0.0.71)
## 3.0.50
- Added user-selectable color themes to the interactive TUI. Pick one with `/theme`, the command palette, or the Theme row in `/settings` — the picker previews each theme live. Built-in themes are Auto (terminal-adaptive, the default), Cline Dark, Cline Light, Tokyo Night, Gruvbox Dark, Nord, Dracula, Catppuccin Mocha, One Dark, Solarized Dark, and Solarized Light. Named themes paint the background, foreground, accents, syntax highlighting, and diff colors, and `CLINE_THEME` overrides the persisted choice at startup
- The git branch shown below the prompt now updates when you switch branches from another terminal or your editor, instead of showing whatever was checked out when the TUI started
- Telegram slash commands such as `/clear` now reach the connector command host — the Telegram library was intercepting them and they were silently dropped
- Racing connector launches no longer collide: an instance is claimed before it opens socket mode, the hub supervises connector processes, and `doctor`/`connect` skip connectors that are already starting. Connector tools are also enabled by default, and the Slack greeting is no longer replayed on reconnect
- Auto-approval settings are now honored over ACP
- Plan mode now hard-blocks file-editing shell commands instead of relying on prompting alone — `run_commands` stays available for read-only investigation, but file-manipulation commands, in-place editors (`sed -i`, `perl -i`), redirection to files, mutating git subcommands, package installs, and nested command strings (`sh -c`, `eval`, `sudo`) are rejected, on Windows and PowerShell too (from SDK v0.0.70)
- A turn that ends with a completed plan is no longer rendered as a failed turn when a plan-blocked command was its only tool call
- Running out of context is now recovered from instead of failing with a raw provider error: the run force-compacts and retries once, and the cases that genuinely cannot be recovered report why (from SDK v0.0.70)
- Empty model responses are now retried on every provider, not just Ollama — OpenRouter, Cline, and OpenAI-compatible endpoints previously failed the task outright with "Model returned empty response" (from SDK v0.0.70)
- Claude 4.6+ and 5.x models are no longer rejected with "thinking.type.enabled is not supported" when they resolve from the offline catalog or from a hand-typed model id (from SDK v0.0.70)
- Bedrock prompt caching works again — the provider was sending a cache format Bedrock silently discards, so cache reads and writes were always 0 — and Bedrock foundation models are now routed through geo inference profiles (from SDK v0.0.70)
- Reasoning models on OpenAI-compatible endpoints now receive `max_completion_tokens` instead of the rejected `max_tokens`, and requests to models without image support substitute the image content instead of failing (from SDK v0.0.70)
- MiniMax now inherits its default model from models.dev, and the model catalog picked up two new providers, Infomaniak and SCX.ai (from SDK v0.0.70)
- Upgraded the model layer to AI SDK 7 and switched Ollama to the native AI SDK provider (from SDK v0.0.70)
- Error telemetry no longer reports the same provider failure twice, and repeated failures from unattended retry loops are rate-limited (from SDK v0.0.70)
## 3.0.49
- `/undo` works again once the agent has used tools — the checkpoint picker counted tool results as user turns, so restore aborted with "Could not find user message for run N"
+3
View File
@@ -270,6 +270,9 @@ The postinstall script runs in diverse environments (CI, Docker, restricted perm
### Windows
Windows binaries are `.exe` files. The build script appends `.exe` to the output filename on Windows targets. The resolver handles this. npm on Windows generates `.cmd` shims for bin entries automatically.
### Windows code signing
Windows application control (Smart App Control, WDAC, AppLocker) blocks unsigned executables at launch, regardless of how they were installed — npm distribution gets no exemption ([#12934](https://github.com/cline/cline/issues/12934)). The publish workflow Authenticode-signs `cli-windows-x64/bin/cline.exe` and `cli-windows-arm64/bin/cline.exe` with Azure Trusted Signing before publishing, via the `.github/actions/sign-windows-cli` composite action. Signing runs on the Linux publish runner using [jsign](https://ebourg.github.io/jsign/) (`--storetype TRUSTEDSIGNING`) with an OIDC-federated Entra app, then verifies the signature chain with `osslsigncode` against the Microsoft Identity Verification Root CA 2020. If all `AZURE_*` / `AZURE_TRUSTED_SIGNING_*` repository secrets are absent, the action logs a warning and the release ships unsigned rather than failing; if only some resolve (a typo'd or renamed secret), the release fails loudly instead. The certificate profile secret is suffixed `_CLI` because the desktop app will later get its own profile; the other five secrets are shared. Note that signing bun-compiled executables requires Bun >= 1.2.23 (earlier versions located the embedded bundle relative to the end of the file, which signing corrupts).
### File permissions
Compiled binaries need to be executable (`chmod 755`). The build script sets this after copying. The postinstall also sets permissions on the cached binary. Some npm packaging steps can strip permissions, so both handle this defensively.
+4 -2
View File
@@ -221,13 +221,15 @@ In chat surfaces, connector slash commands include `/help`, `/start`, `/new`, `/
Schedule agents on cron-like intervals or external events.
If `--provider` and `--model` are omitted, schedules use the last configured
provider and model. If only `--provider` is given, the schedule uses that
provider's saved model.
```sh
cline schedule create "Daily code review" \
--cron "0 9 * * MON-FRI" \
--prompt "Review PRs opened yesterday and summarize issues." \
--workspace /path/to/repo \
--provider cline \
--model openai/gpt-5.3-codex \
--timeout 3600 \
--tags automation,review
+23
View File
@@ -72,6 +72,29 @@ function run(target) {
});
if (result.error) {
console.error(result.error.message);
// Windows application control (Smart App Control, WDAC, AppLocker)
// blocks the child exe at launch, which Node surfaces only as an
// opaque "spawnSync ... UNKNOWN" error. Point users at the real cause.
const code = result.error.code;
if (
os.platform() === "win32" &&
(code === "UNKNOWN" || code === "EACCES" || code === "EPERM")
) {
console.error(
"\nWindows refused to start the Cline binary:\n " +
target +
"\n\n" +
"This usually means an application control policy (Smart App Control,\n" +
"WDAC, or AppLocker) or antivirus blocked the executable. To confirm,\n" +
"run the path above directly in a terminal and check the error Windows\n" +
"reports, or inspect its signature with:\n\n" +
' Get-AuthenticodeSignature "' +
target +
'"\n\n' +
"If it was blocked by policy, allow the file or ask your administrator\n" +
"to trust it. See https://github.com/cline/cline/issues for known issues.",
);
}
process.exit(1);
}
if (typeof result.status === "number") {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@cline/cli",
"displayName": "cline",
"version": "3.0.49",
"version": "3.0.60",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"type": "module",
"publishConfig": {
+37
View File
@@ -17,6 +17,35 @@ import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
// CLI versions <= 3.0.54 restart the hub daemon after a background
// auto-update even while it is serving live sessions, killing those sessions
// mid-turn — and their build-fingerprint check then rejects every replacement
// hub, bricking the running TUI. That restart code is the *old* version's, so
// it cannot be patched here; but it bails out harmlessly when no hub
// discovery record exists, and it runs only after this install (and this
// script) completes. Setting the record aside protects any attached clients:
// a running hub keeps serving its established connections, clients that share
// its build fingerprint rebuild the record from a port probe, and the next
// fresh launch retires stale hubs regardless of the record.
function shieldRunningHubDiscovery() {
const explicitPath = process.env.CLINE_HUB_DISCOVERY_PATH?.trim();
const dataDir =
process.env.CLINE_DATA_DIR?.trim() ||
path.join(
process.env.CLINE_DIR?.trim() || path.join(os.homedir(), ".cline"),
"data",
);
const recordPath =
explicitPath || path.join(dataDir, "locks", "hub", "production.json");
if (!fs.existsSync(recordPath)) {
return;
}
const asidePath = `${recordPath}.superseded`;
fs.rmSync(asidePath, { force: true });
fs.renameSync(recordPath, asidePath);
console.log("Set aside hub discovery record for the updated CLI");
}
function main() {
if (os.platform() === "win32") {
// On Windows, npm creates .cmd shims from the bin field.
@@ -79,6 +108,14 @@ function main() {
console.log(`Cached cline binary at ${target}`);
}
try {
shieldRunningHubDiscovery();
} catch (error) {
// Best-effort: without the shield the worst case is the pre-3.0.55
// restart-while-busy behavior, never a broken install.
console.error(`postinstall: hub discovery shield skipped: ${error.message}`);
}
try {
main();
} catch (error) {
+26 -9
View File
@@ -30,7 +30,7 @@ import {
ProviderSettingsManager,
SessionSource,
} from "@cline/core";
import { isLikelyAuthError, type Message } from "@cline/shared";
import { isLikelyAuthError, type MessageWithMetadata } from "@cline/shared";
import { getPersistedProviderApiKey } from "../commands/auth";
import { resolveSystemPrompt } from "../runtime/prompt";
import { subscribeToAgentEvents } from "../runtime/session-events";
@@ -70,6 +70,10 @@ import {
sendSessionInfoUpdate,
} from "./session-updates";
const CHAT_MODEL_QUERY_OPTIONS = {
filter: "chat",
} satisfies Llms.GetModelsForProviderOptions;
interface SessionState {
id: string;
cwd: string;
@@ -100,7 +104,7 @@ interface SessionState {
*/
fatalError?: Error;
/** Messages to inject into the next session manager for conversation continuity. */
pendingInitialMessages?: Message[];
pendingInitialMessages?: MessageWithMetadata[];
}
export class AcpAgent implements Agent {
@@ -185,7 +189,10 @@ export class AcpAgent implements Agent {
const providerId =
process.env.CLINE_PROVIDER ?? this.authResult?.providerId ?? "cline";
const providerModels = await Llms.getModelsForProvider(providerId);
const providerModels = await Llms.getModelsForProvider(
providerId,
CHAT_MODEL_QUERY_OPTIONS,
);
// Model ids are provider-scoped, so the default must come from the
// provider's own catalog: `cline-pass` uses `cline-pass/…` ids that mean
// nothing to `cline`, and vice versa.
@@ -240,7 +247,7 @@ export class AcpAgent implements Agent {
this.isSessionReady();
let session = this.sessions.get(params.sessionId);
let messages: Message[];
let messages: MessageWithMetadata[];
if (session?.sessionManager && session.activeSessionId) {
// The session is still live in this connection — replay its current
@@ -256,7 +263,10 @@ export class AcpAgent implements Agent {
// provider's own catalog just like newSession.
const providerId =
process.env.CLINE_PROVIDER ?? this.authResult?.providerId ?? "cline";
const providerModels = await Llms.getModelsForProvider(providerId);
const providerModels = await Llms.getModelsForProvider(
providerId,
CHAT_MODEL_QUERY_OPTIONS,
);
session = {
id: params.sessionId,
cwd: params.cwd,
@@ -289,6 +299,7 @@ export class AcpAgent implements Agent {
const providerModels = await Llms.getModelsForProvider(
session.currentProviderId,
CHAT_MODEL_QUERY_OPTIONS,
);
const availableModels = Object.entries(providerModels).map(
([availableModelId, info]) => ({
@@ -473,7 +484,10 @@ export class AcpAgent implements Agent {
// current one when it's offered there too, otherwise fall back to the
// provider's declared default rather than whichever model happens to
// be listed first (for cline-pass that is an unrelated free model).
const providerModels = await Llms.getModelsForProvider(value);
const providerModels = await Llms.getModelsForProvider(
value,
CHAT_MODEL_QUERY_OPTIONS,
);
session.currentModelId = await resolveDefaultModelId(
value,
session.currentModelId,
@@ -676,7 +690,7 @@ export class AcpAgent implements Agent {
session: SessionState,
acpSessionId: string,
options?: { resume?: boolean },
): Promise<Message[] | undefined> {
): Promise<MessageWithMetadata[] | undefined> {
if (session.sessionManager) {
return undefined;
}
@@ -695,7 +709,7 @@ export class AcpAgent implements Agent {
workspaceRoot: config.workspaceRoot,
});
let initialMessages: Message[] | undefined;
let initialMessages: MessageWithMetadata[] | undefined;
if (options?.resume) {
initialMessages = await sessionManager
.readMessages(acpSessionId)
@@ -907,7 +921,10 @@ async function buildAllConfigOptions(
): Promise<SessionConfigOption[]> {
const [providerOption, providerModels] = await Promise.all([
buildProviderConfigOption(session.currentProviderId),
Llms.getModelsForProvider(session.currentProviderId),
Llms.getModelsForProvider(
session.currentProviderId,
CHAT_MODEL_QUERY_OPTIONS,
),
]);
return [
providerOption,
+70
View File
@@ -225,6 +225,76 @@ describe("translateHistoricalMessage", () => {
},
]);
});
it("replays provider model tools with the ordinary ACP tool updates", () => {
expect(
translateHistoricalMessage({
role: "assistant",
content: "Found it",
metadata: {
modelToolActivities: [
{
toolCallId: "search-1",
toolName: "web_search",
execution: "provider",
input: { query: "latest Bun release" },
output: "Bun 1.3.14",
},
],
},
} as Parameters<typeof translateHistoricalMessage>[0]),
).toEqual([
{
sessionUpdate: "tool_call",
toolCallId: "search-1",
title: expect.any(String),
kind: "search",
status: "pending",
rawInput: { query: "latest Bun release" },
},
{
sessionUpdate: "tool_call_update",
toolCallId: "search-1",
status: "completed",
rawOutput: "Bun 1.3.14",
},
{
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Found it" },
},
]);
});
it("preserves structured native web-search results", () => {
const nativeResult = {
type: "web_search_result",
url: "https://bun.sh/blog/bun-v1.3.14",
title: "Bun v1.3.14",
pageAge: "2026-08-12",
encryptedContent: "encrypted",
};
const updates = translateHistoricalMessage({
role: "assistant",
content: "Found it",
metadata: {
modelToolActivities: [
{
toolCallId: "search-native",
toolName: "web_search",
execution: "provider",
input: { query: "latest Bun" },
output: [nativeResult],
},
],
},
} as Parameters<typeof translateHistoricalMessage>[0]);
expect(updates[1]).toMatchObject({
sessionUpdate: "tool_call_update",
toolCallId: "search-native",
rawOutput: JSON.stringify(nativeResult),
});
});
});
describe("replaySessionHistory", () => {
+46 -4
View File
@@ -2,10 +2,11 @@ import type {
AgentSideConnection,
SessionUpdate,
} from "@agentclientprotocol/sdk";
import { projectSessionMessagesForDisplay } from "@cline/core";
import {
type ContentBlock,
formatDisplayUserInput,
type Message,
type MessageWithMetadata,
type ToolResultContent,
} from "@cline/shared";
import { ACT_MODE_CONTINUATION_PROMPT } from "../runtime/interactive/mode";
@@ -29,7 +30,7 @@ function isSyntheticUserText(text: string): boolean {
export async function replaySessionHistory(
conn: AgentSideConnection,
sessionId: string,
messages: Message[],
messages: MessageWithMetadata[],
): Promise<void> {
for (const message of messages) {
for (const update of translateHistoricalMessage(message)) {
@@ -38,7 +39,17 @@ export async function replaySessionHistory(
}
}
export function translateHistoricalMessage(message: Message): SessionUpdate[] {
export function translateHistoricalMessage(
message: MessageWithMetadata,
): SessionUpdate[] {
return projectSessionMessagesForDisplay([message]).flatMap(({ message }) =>
translateProjectedHistoricalMessage(message),
);
}
function translateProjectedHistoricalMessage(
message: MessageWithMetadata,
): SessionUpdate[] {
const blocks: ContentBlock[] =
typeof message.content === "string"
? [{ type: "text", text: message.content }]
@@ -92,6 +103,31 @@ export function translateHistoricalMessage(message: Message): SessionUpdate[] {
);
break;
}
case "media": {
const media = block.media;
if (media.modality === "image" && media.source.type === "base64") {
updates.push({
sessionUpdate:
message.role === "user"
? "user_message_chunk"
: "agent_message_chunk",
content: {
type: "image",
data: media.source.data,
mimeType: media.mediaType,
},
});
} else {
updates.push({
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: `[Generated ${media.modality}: ${media.mediaType}]`,
},
});
}
break;
}
case "tool_use": {
updates.push({
sessionUpdate: "tool_call",
@@ -133,8 +169,14 @@ function flattenToolResultContent(
return part.text;
case "file":
return part.content;
default:
case "image":
return "[image]";
default:
try {
return JSON.stringify(part);
} catch {
return String(part);
}
}
})
.join("\n");
+34
View File
@@ -0,0 +1,34 @@
import type { AgentSideConnection } from "@agentclientprotocol/sdk";
import type { AgentEvent } from "@cline/core";
import { describe, expect, it, vi } from "vitest";
import { forwardAgentEvent } from "./session-updates";
describe("forwardAgentEvent", () => {
it("forwards generated images as ACP agent message chunks", () => {
const sessionUpdate = vi.fn().mockResolvedValue(undefined);
const connection = { sessionUpdate } as unknown as AgentSideConnection;
forwardAgentEvent(connection, "session-1", {
type: "content_end",
contentType: "media",
media: {
id: "generated-1",
modality: "image",
mediaType: "image/png",
source: { type: "base64", data: "aGVsbG8=" },
},
} as AgentEvent);
expect(sessionUpdate).toHaveBeenCalledWith({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "image",
data: "aGVsbG8=",
mimeType: "image/png",
},
},
});
});
});
+25
View File
@@ -4,6 +4,7 @@ import type {
SessionUpdate,
} from "@agentclientprotocol/sdk";
import type { AgentEvent } from "@cline/core";
import type { GeneratedMedia } from "@cline/shared";
import { getErrorMessage } from "@cline/shared";
import { buildToolTitle, mapToolKind } from "./tool-utils";
@@ -100,6 +101,7 @@ function translateContentEnd(
output?: unknown;
error?: string;
durationMs?: number;
media?: GeneratedMedia;
};
switch (e.contentType) {
@@ -109,6 +111,29 @@ function translateContentEnd(
case "reasoning":
// Reasoning was already streamed via content_start chunks; don't re-send.
return [];
case "media":
if (!e.media) return [];
if (e.media.modality !== "image" || e.media.source.type !== "base64") {
return [
{
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: `[Generated ${e.media.modality}: ${e.media.mediaType}]`,
},
},
];
}
return [
{
sessionUpdate: "agent_message_chunk",
content: {
type: "image",
data: e.media.source.data,
mimeType: e.media.mediaType,
},
},
];
case "tool": {
const toolCallId = e.toolCallId ?? "unknown";
const failed = !!e.error;
+1
View File
@@ -17,6 +17,7 @@ const TOOL_KIND_MAP: Record<string, ToolKind> = {
WebFetch: "fetch",
fetch_web_content: "fetch",
WebSearch: "search",
web_search: "search",
Agent: "think",
spawn_agent: "think",
NotebookEdit: "edit",
+65
View File
@@ -767,6 +767,71 @@ Break work into clear steps.`,
);
});
it("routes mcp uninstall and its rm alias", () => {
const tempRoot = mkdtempSync(path.join(os.tmpdir(), "cli-e2e-mcp-rm-"));
tempDirs.push(tempRoot);
const settingsPath = path.join(tempRoot, "cline_mcp_settings.json");
const writeSettings = () => {
writeFileSync(
settingsPath,
JSON.stringify(
{
mcpServers: {
docs: { transport: { type: "stdio", command: "node" } },
remote: {
transport: {
type: "streamableHttp",
url: "https://mcp.example.com",
},
},
},
customTopLevelKey: true,
},
null,
2,
),
"utf8",
);
};
const readServers = () =>
(
JSON.parse(readFileSync(settingsPath, "utf8")) as {
mcpServers?: Record<string, unknown>;
}
).mcpServers ?? {};
writeSettings();
const uninstallResult = runCli(["mcp", "uninstall", "docs"], {
env: { ...createIsolatedEnv(), CLINE_MCP_SETTINGS_PATH: settingsPath },
});
expect(uninstallResult.status).toBe(0);
expect(asText(uninstallResult.stdout)).toContain(
"Uninstalled MCP server docs.",
);
expect(Object.keys(readServers())).toEqual(["remote"]);
writeSettings();
const aliasResult = runCli(["mcp", "rm", "remote", "--json"], {
env: { ...createIsolatedEnv(), CLINE_MCP_SETTINGS_PATH: settingsPath },
});
expect(aliasResult.status).toBe(0);
expect(JSON.parse(asText(aliasResult.stdout).trim())).toEqual({
name: "remote",
status: "uninstalled",
});
expect(Object.keys(readServers())).toEqual(["docs"]);
writeSettings();
const missingResult = runCli(["mcp", "remove", "missing"], {
env: { ...createIsolatedEnv(), CLINE_MCP_SETTINGS_PATH: settingsPath },
});
expect(missingResult.status).toBe(1);
expect(asText(missingResult.stderr)).toContain(
'MCP server "missing" is not installed.',
);
expect(Object.keys(readServers())).toEqual(["docs", "remote"]);
});
it("lists available tools", () => {
const homeDir = mkdtempSync(path.join(os.tmpdir(), "cli-e2e-home-"));
const dataDir = mkdtempSync(path.join(os.tmpdir(), "cli-e2e-data-"));
+2
View File
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
stopConnectorsViaHub: vi.fn(async () => undefined as number | undefined),
disableConnectorAutostart: vi.fn(),
getPersistedConnectorConnection: vi.fn(),
getProcessStartToken: vi.fn(() => undefined),
getConnector: vi.fn(),
listActiveConnectors: vi.fn(),
listConnectors: vi.fn((): Array<{ name: string; description: string }> => []),
@@ -29,6 +30,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("@cline/core", () => ({
disableConnectorAutostart: mocks.disableConnectorAutostart,
getPersistedConnectorConnection: mocks.getPersistedConnectorConnection,
getProcessStartToken: mocks.getProcessStartToken,
listActiveConnectors: mocks.listActiveConnectors,
persistConnectorConnection: mocks.persistConnectorConnection,
removePersistedConnectorConnection: mocks.removePersistedConnectorConnection,
+101
View File
@@ -18,6 +18,7 @@ const {
mockResolveProductionHubOwnerContext,
mockResolveSharedHubOwnerContext,
mockReadHubDiscovery,
mockReadSupersededHubDiscovery,
mockProbeHubServer,
mockClearHubDiscovery,
mockStopLocalHubServerGracefully,
@@ -48,6 +49,7 @@ const {
),
})),
mockReadHubDiscovery: vi.fn(),
mockReadSupersededHubDiscovery: vi.fn(() => undefined as unknown),
mockProbeHubServer: vi.fn(),
mockClearHubDiscovery: vi.fn(),
mockStopLocalHubServerGracefully: vi.fn(async () => false),
@@ -73,6 +75,7 @@ vi.mock("@cline/core", () => ({
clearHubDiscovery: mockClearHubDiscovery,
probeHubServer: mockProbeHubServer,
readHubDiscovery: mockReadHubDiscovery,
readSupersededHubDiscovery: mockReadSupersededHubDiscovery,
stopLocalHubServerGracefully: mockStopLocalHubServerGracefully,
ensureFileExists: mockEnsureFileExists,
listActiveConnectors: mockListActiveConnectors,
@@ -186,6 +189,65 @@ describe("runDoctorCommand", () => {
);
});
it("sees the hub through the set-aside record during the shielded update window", async () => {
const cwd = "/workspace";
// The npm postinstall shield renamed the discovery record aside; the
// hub is alive and serving an old client's sessions.
mockReadHubDiscovery.mockResolvedValue(undefined);
mockReadSupersededHubDiscovery.mockReturnValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "shielded-token",
pid: 50174,
});
mockProbeHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
port: 25463,
pid: 50174,
});
mockSpawnSync.mockImplementation((command: string, args?: string[]) => {
if (command === "lsof") {
return { status: 0, stdout: "50174\n" };
}
if (
command === "pgrep" &&
Array.isArray(args) &&
args[2] === "--cline-hub-daemon"
) {
return {
status: 0,
stdout: "50174 /usr/local/bin/cline --cline-hub-daemon\n",
};
}
return { status: 1, stdout: "" };
});
const output: string[] = [];
const code = await runDoctorCommand(
{ cwd, json: true },
{
writeln: (text) => {
output.push(text ?? "");
},
writeErr: () => {},
},
);
expect(code).toBe(0);
expect(mockProbeHubServer).toHaveBeenCalledWith(
"ws://127.0.0.1:25463/hub",
{
authToken: "shielded-token",
},
);
// Without the fallback the live daemon reads as stale and doctor's
// advice (\"run doctor fix\") would kill the sessions the shield exists
// to protect.
expect(JSON.parse(output[0] || "")).toMatchObject({
hubHealthy: true,
staleHubPids: [],
});
});
it("reports CLI and running hub Core versions", async () => {
const cwd = "/workspace";
mockReadHubDiscovery.mockResolvedValue({
@@ -624,3 +686,42 @@ describe("doctor supervision reporting", () => {
);
});
});
describe("describeProcessesStartedDuringFix", () => {
const { describeProcessesStartedDuringFix } = __test__;
const liveParents = new Map([
[100, 10],
[200, 20],
]);
const resolveLiveParent = (pid: number) => liveParents.get(pid);
it("says nothing when no process started during the fix", () => {
expect(
describeProcessesStartedDuringFix([], resolveLiveParent),
).toBeUndefined();
});
it("blames the parent only when every process has a live one", () => {
expect(
describeProcessesStartedDuringFix([100, 200], resolveLiveParent),
).toBe(
"\nThese processes were respawned by a live parent. Stop the parent process listed above, then re-run.",
);
});
// A process can start on its own mid-repair - a user opening a new session,
// say - and telling them to go kill an unrelated parent would be wrong.
it("states the facts when no process has a live parent", () => {
expect(describeProcessesStartedDuringFix([777], resolveLiveParent)).toBe(
"\nThese processes started after the fix began, so they were not targeted. Re-run to see whether they persist.",
);
});
it("separates respawns from independent starts in a mixed batch", () => {
expect(
describeProcessesStartedDuringFix([100, 777], resolveLiveParent),
).toBe(
"\nSome of these were respawned by a live parent (100); stop the parent process listed above, then re-run. The rest started after the fix began and were not targeted.",
);
});
});
+149 -14
View File
@@ -7,6 +7,7 @@ import {
listActiveConnectors,
probeHubServer,
readHubDiscovery,
readSupersededHubDiscovery,
resolveClineDataDir,
resolveProductionHubOwnerContext,
resolveSharedHubOwnerContext,
@@ -384,6 +385,12 @@ async function clearHubStartupArtifacts(
await clearHubDiscovery(owner.discoveryPath);
clearedDiscovery = 1;
}
if (options?.clearDiscovery) {
// The set-aside copy the npm postinstall shield leaves behind. Once
// doctor has deliberately stopped everything, keeping it risks a much
// later launch SIGTERMing whatever process has recycled its pid.
clearPathIfExists(`${owner.discoveryPath}.superseded`);
}
return {
startupLocks: clearedStartupLocks,
discovery: clearedDiscovery,
@@ -411,7 +418,25 @@ function resolveCliHubOwnerContext() {
async function collectDoctorStatus(cwd: string): Promise<DoctorStatus> {
const owner = resolveCliHubOwnerContext();
const discovery = await readHubDiscovery(owner.discoveryPath);
// The npm postinstall shield sets the discovery record aside (see
// readSupersededHubDiscovery) while an older hub finishes serving its
// sessions. Without the fallback, doctor cannot see that hub, classifies
// the live daemon as stale, and its "run doctor fix" advice kills the
// sessions the shield exists to protect.
const recorded = await readHubDiscovery(owner.discoveryPath);
// The set-aside record carries only url/token/pid; widen so the two
// sources read uniformly below.
const discovery:
| {
url?: string;
authToken?: string;
pid?: number;
port?: number;
coreVersion?: string;
}
| undefined = recorded?.url
? recorded
: readSupersededHubDiscovery(owner.discoveryPath);
const health = discovery?.url
? await probeHubServer(discovery.url, { authToken: discovery.authToken })
: undefined;
@@ -449,6 +474,80 @@ function formatPidList(label: string, pids: number[]): string {
return `${label} ${c.dim}${pids.join(", ")}${c.reset}`;
}
function readParentPid(pid: number): number | undefined {
try {
const output = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], {
encoding: "utf8",
});
const parsed = Number(output.stdout?.trim());
return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
} catch {
return undefined;
}
}
function liveParentPid(pid: number): number | undefined {
const parent = readParentPid(pid);
return parent && isProcessRunning(parent) ? parent : undefined;
}
/**
* A daemon whose parent is still running was almost certainly just spawned by
* that parent, and killing it only invites the parent to spawn another. Naming
* the parent points at the process the user actually has to stop.
*/
function formatDaemonPidList(label: string, pids: number[]): string {
if (pids.length === 0) {
return `${label} ${c.dim}0${c.reset}`;
}
const described = pids.map((pid) => {
const parent = liveParentPid(pid);
return parent ? `${pid} (spawned by ${parent})` : String(pid);
});
return `${label} ${c.dim}${described.join(", ")}${c.reset}`;
}
/**
* Advice for processes first seen during the fix. Only a process with a live
* parent is known to have been respawned by it; anything else may have been
* started independently (a user opening a new session mid-repair), so it gets
* a statement of fact rather than an instruction to go kill something.
*/
export function describeProcessesStartedDuringFix(
pids: number[],
resolveLiveParent: (pid: number) => number | undefined,
): string | undefined {
if (pids.length === 0) {
return undefined;
}
const respawned = pids.filter((pid) => resolveLiveParent(pid) !== undefined);
if (respawned.length === 0) {
return "\nThese processes started after the fix began, so they were not targeted. Re-run to see whether they persist.";
}
if (respawned.length === pids.length) {
return "\nThese processes were respawned by a live parent. Stop the parent process listed above, then re-run.";
}
return `\nSome of these were respawned by a live parent (${respawned.join(", ")}); stop the parent process listed above, then re-run. The rest started after the fix began and were not targeted.`;
}
function formatStartupLockList(
label: string,
locks: StartupArtifact[],
): string {
const described = locks
.map((lock) => {
if (lock.pid === undefined) {
return "unreadable";
}
return lock.stale ? `${lock.pid} (stale)` : `${lock.pid} (held, live)`;
})
.filter((entry) => entry.length > 0);
if (described.length === 0) {
return `${label} ${c.dim}0${c.reset}`;
}
return `${label} ${c.dim}${described.join(", ")}${c.reset}`;
}
function formatRecentSpawnedProcess(record: SpawnedProcessRecord): string {
const pieces = [
record.timestamp ?? "unknown-time",
@@ -531,6 +630,7 @@ function killPids(pids: number[]): number {
export const __test__ = {
decideForeignContainer,
CONTAINER_CGROUP_PATTERN,
describeProcessesStartedDuringFix,
formatSupervisedConnector,
};
@@ -556,13 +656,8 @@ export async function runDoctorCommand(
);
writeln(`hub uptime ${c.dim}${before.hubUptime ?? "n/a"}${c.reset}`);
writeln(formatPidList("hub listeners", before.listeningPids));
writeln(formatPidList("stale hub daemons", before.staleHubPids));
writeln(
formatPidList(
"hub startup locks",
before.hubStartupLocks.map((a) => a.pid ?? -1).filter((pid) => pid > 0),
),
);
writeln(formatDaemonPidList("stale hub daemons", before.staleHubPids));
writeln(formatStartupLockList("hub startup locks", before.hubStartupLocks));
writeln(formatPidList("cli processes", before.staleCliPids));
writeln(formatPidList("sidecar processes", before.staleSidecarPids));
if (before.activeConnectors.length === 0) {
@@ -673,16 +768,56 @@ export async function runDoctorCommand(
`cleared hub discovery records ${c.dim}${clearedArtifacts.discovery}${c.reset}`,
);
writeln(`hub healthy after fix: ${after.hubHealthy ? "yes" : "no"}`);
writeln(formatPidList("remaining hub listeners", after.listeningPids));
writeln(formatPidList("remaining stale hub daemons", after.staleHubPids));
// "Remaining" means a process this run tried to kill and failed to. A
// re-scan alone cannot tell that apart from a process that appeared while
// the fix was running, and reporting the two together reads as a failure
// to kill something that was never targeted.
const survived = (targets: number[], remaining: number[]) =>
remaining.filter((pid) => targets.includes(pid));
const appeared = (targets: number[], remaining: number[]) =>
remaining.filter((pid) => !targets.includes(pid));
writeln(
formatPidList(
"remaining hub startup locks",
after.hubStartupLocks.map((a) => a.pid ?? -1).filter((pid) => pid > 0),
"remaining hub listeners",
survived(refreshedAfterGracefulStop.listeningPids, after.listeningPids),
),
);
writeln(formatPidList("remaining cli processes", after.staleCliPids));
writeln(formatPidList("remaining sidecar processes", after.staleSidecarPids));
writeln(
formatDaemonPidList(
"remaining stale hub daemons",
survived(staleHubTargets, after.staleHubPids),
),
);
writeln(
formatStartupLockList("remaining hub startup locks", after.hubStartupLocks),
);
writeln(
formatPidList(
"remaining cli processes",
survived(staleCliTargets, after.staleCliPids),
),
);
writeln(
formatPidList(
"remaining sidecar processes",
survived(staleSidecarTargets, after.staleSidecarPids),
),
);
const spawnedDuringFix = [
...appeared(staleHubTargets, after.staleHubPids),
...appeared(staleCliTargets, after.staleCliPids),
...appeared(staleSidecarTargets, after.staleSidecarPids),
];
if (spawnedDuringFix.length > 0) {
writeln(formatDaemonPidList("started during fix", spawnedDuringFix));
const advice = describeProcessesStartedDuringFix(
spawnedDuringFix,
liveParentPid,
);
if (advice) {
io.writeln(advice);
}
}
return 0;
}
+147
View File
@@ -3,16 +3,20 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const {
mockClearHubDiscovery,
mockEnsureDetachedHubServer,
mockLocalHubHasNoActiveSessions,
mockProbeHubServer,
mockReadHubDiscovery,
mockRequestHubDrain,
mockResolveProductionHubOwnerContext,
mockResolveSharedHubOwnerContext,
mockStopLocalHubServerGracefully,
} = vi.hoisted(() => ({
mockClearHubDiscovery: vi.fn(),
mockEnsureDetachedHubServer: vi.fn(),
mockLocalHubHasNoActiveSessions: vi.fn(),
mockProbeHubServer: vi.fn(),
mockReadHubDiscovery: vi.fn(),
mockRequestHubDrain: vi.fn(),
mockResolveProductionHubOwnerContext: vi.fn(() => ({
ownerId: "hub-production",
discoveryPath: "/tmp/cline-data/locks/hub/production.json",
@@ -27,8 +31,10 @@ const {
vi.mock("@cline/core", () => ({
clearHubDiscovery: mockClearHubDiscovery,
ensureDetachedHubServer: mockEnsureDetachedHubServer,
localHubHasNoActiveSessions: mockLocalHubHasNoActiveSessions,
probeHubServer: mockProbeHubServer,
readHubDiscovery: mockReadHubDiscovery,
requestHubDrain: mockRequestHubDrain,
resolveProductionHubOwnerContext: mockResolveProductionHubOwnerContext,
resolveSharedHubOwnerContext: mockResolveSharedHubOwnerContext,
stopLocalHubServerGracefully: mockStopLocalHubServerGracefully,
@@ -95,6 +101,147 @@ describe("createHubCommand", () => {
});
});
function createCommand() {
const output: string[] = [];
const errors: string[] = [];
let exitCode = 0;
const cmd = createHubCommand(
{
writeln: (text) => {
output.push(text ?? "");
},
writeErr: (text) => {
errors.push(text);
},
},
(code) => {
exitCode = code;
},
);
return {
cmd,
output,
errors,
exitCode: () => exitCode,
};
}
it("sends an un-drain request with drain --off", async () => {
mockReadHubDiscovery.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
mockRequestHubDrain.mockResolvedValue(true);
const { cmd, output, exitCode } = createCommand();
await cmd.parseAsync(["drain", "--off"], { from: "user" });
expect(exitCode()).toBe(0);
expect(mockRequestHubDrain).toHaveBeenCalledWith(
"ws://127.0.0.1:25463/hub",
"token",
"cline hub drain --off",
{ off: true },
);
expect(JSON.parse(output[0] || "")).toEqual({
draining: false,
url: "ws://127.0.0.1:25463/hub",
});
});
it("drains without the off flag by default", async () => {
mockReadHubDiscovery.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
mockRequestHubDrain.mockResolvedValue(true);
const { cmd, output, exitCode } = createCommand();
await cmd.parseAsync(["drain"], { from: "user" });
expect(exitCode()).toBe(0);
expect(mockRequestHubDrain).toHaveBeenCalledWith(
"ws://127.0.0.1:25463/hub",
"token",
"cline hub drain",
{ off: false },
);
expect(JSON.parse(output[0] || "")).toEqual({
draining: true,
url: "ws://127.0.0.1:25463/hub",
});
});
it("replaces an idle hub with upgrade --wait 0 instead of skipping the idle check", async () => {
mockReadHubDiscovery.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
mockRequestHubDrain.mockResolvedValue(true);
mockLocalHubHasNoActiveSessions.mockResolvedValue(true);
mockStopLocalHubServerGracefully.mockResolvedValue(true);
mockEnsureDetachedHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "new-token",
});
const { cmd, output, errors, exitCode } = createCommand();
await cmd.parseAsync(["upgrade", "--wait", "0"], { from: "user" });
expect(errors).toEqual([]);
expect(exitCode()).toBe(0);
expect(mockLocalHubHasNoActiveSessions).toHaveBeenCalled();
expect(mockStopLocalHubServerGracefully).toHaveBeenCalled();
expect(mockEnsureDetachedHubServer).toHaveBeenCalled();
// The drain was never lifted manually: the drained hub was replaced.
expect(mockRequestHubDrain).toHaveBeenCalledTimes(1);
expect(JSON.parse(output[0] || "")).toEqual({
upgraded: true,
url: "ws://127.0.0.1:25463/hub",
});
});
it("un-drains the hub when upgrade aborts because sessions are still active", async () => {
mockReadHubDiscovery.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
mockRequestHubDrain.mockResolvedValue(true);
mockLocalHubHasNoActiveSessions.mockResolvedValue(false);
const { cmd, errors, exitCode } = createCommand();
await cmd.parseAsync(["upgrade", "--wait", "0"], { from: "user" });
expect(exitCode()).toBe(1);
expect(errors[0]).toContain("still serving sessions");
expect(mockStopLocalHubServerGracefully).not.toHaveBeenCalled();
expect(mockEnsureDetachedHubServer).not.toHaveBeenCalled();
expect(mockRequestHubDrain).toHaveBeenCalledTimes(2);
expect(mockRequestHubDrain).toHaveBeenLastCalledWith(
"ws://127.0.0.1:25463/hub",
"token",
"cline hub upgrade aborted",
{ off: true },
);
});
it("rejects a non-numeric upgrade --wait instead of treating it as an expired deadline", async () => {
mockReadHubDiscovery.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
const { cmd } = createCommand();
cmd.configureOutput({ writeErr: () => {} });
for (const sub of cmd.commands) {
sub.configureOutput({ writeErr: () => {} });
}
await expect(
cmd.parseAsync(["upgrade", "--wait", "soon"], { from: "user" }),
).rejects.toThrow("--wait requires a non-negative number of seconds.");
expect(mockRequestHubDrain).not.toHaveBeenCalled();
});
it("passes the selected owner to graceful stop", async () => {
process.env.CLINE_BUILD_ENV = "development";
mockReadHubDiscovery.mockResolvedValue({
+125 -1
View File
@@ -1,14 +1,16 @@
import {
clearHubDiscovery,
ensureDetachedHubServer,
localHubHasNoActiveSessions,
probeHubServer,
readHubDiscovery,
requestHubDrain,
resolveProductionHubOwnerContext,
resolveSharedHubOwnerContext,
stopLocalHubServerGracefully,
} from "@cline/core";
import { formatUptime, resolveClineBuildEnv } from "@cline/shared";
import { Command } from "commander";
import { Command, InvalidArgumentError } from "commander";
import { version as cliVersion } from "../../package.json";
interface HubCommandIo {
@@ -54,6 +56,16 @@ function resolveCliHubOwnerContext() {
: resolveSharedHubOwnerContext();
}
function parseWaitSeconds(value: string): number {
const parsed = Number.parseInt(value, 10);
if (Number.isNaN(parsed) || parsed < 0) {
throw new InvalidArgumentError(
"--wait requires a non-negative number of seconds.",
);
}
return parsed;
}
export function createHubCommand(
io: HubCommandIo,
setExitCode: (code: number) => void,
@@ -150,5 +162,117 @@ export function createHubCommand(
}),
);
hub
.command("drain")
.description("Refuse new mutating work while accepted runs finish")
.option("--reason <text>", "Why the hub is draining")
.option("--off", "Lift the drain and accept new mutating work again")
.action(
action(async (cmdOptions: { reason?: string; off?: boolean }) => {
const owner = resolveCliHubOwnerContext();
const discovery = await readHubDiscovery(owner.discoveryPath);
if (!discovery?.url) {
io.writeErr("No hub is running.");
fail();
return;
}
const draining = cmdOptions.off !== true;
const ok = await requestHubDrain(
discovery.url,
discovery.authToken,
cmdOptions.reason ??
(draining ? "cline hub drain" : "cline hub drain --off"),
{ off: !draining },
);
if (!ok) {
io.writeErr(
draining
? "Hub drain request failed."
: "Hub un-drain request failed.",
);
fail();
return;
}
io.writeln(JSON.stringify({ draining, url: discovery.url }));
}),
);
hub
.command("upgrade")
.description(
"Drain, wait for the hub to go idle, stop it, and start a fresh one",
)
.option(
"--wait <seconds>",
"How long to wait for the hub to go idle",
parseWaitSeconds,
120,
)
.action(
action(async (cmdOptions: { wait: number }) => {
const opts = hub.opts<{
cwd: string;
host?: string;
port?: number;
pathname?: string;
}>();
const owner = resolveCliHubOwnerContext();
const discovery = await readHubDiscovery(owner.discoveryPath);
if (discovery?.url) {
const drained = await requestHubDrain(
discovery.url,
discovery.authToken,
"cline hub upgrade",
).catch(() => false);
// An aborted upgrade must hand the hub back: leaving it
// draining refuses all new mutating work until a restart.
const undrain = async (): Promise<void> => {
if (!drained) {
return;
}
await requestHubDrain(
discovery.url,
discovery.authToken,
"cline hub upgrade aborted",
{ off: true },
).catch(() => false);
};
try {
const deadline = Date.now() + cmdOptions.wait * 1_000;
let idle = false;
// Check at least once so --wait 0 still observes an idle hub.
for (;;) {
idle = await localHubHasNoActiveSessions(
discovery.url,
discovery.authToken,
).catch(() => true);
if (idle || Date.now() >= deadline) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
if (!idle) {
await undrain();
io.writeErr(
"Hub is still serving sessions after the wait window; not replacing it. Re-run with a longer --wait, or finish the sessions first.",
);
fail();
return;
}
await stopHubServer(opts.cwd);
} catch (error) {
await undrain();
throw error;
}
}
const { url } = await ensureDetachedHubServer(opts.cwd, {
host: opts.host,
port: opts.port,
pathname: opts.pathname,
});
io.writeln(JSON.stringify({ upgraded: true, url }));
}),
);
return hub;
}
+146 -1
View File
@@ -1,9 +1,13 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { installMcpServer } from "@cline/core";
import { describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
buildMcpInstallDefaults,
buildMcpInstallTransport,
runMcpInstallCommand,
runMcpUninstallCommand,
} from "./mcp";
vi.mock("@cline/core", async (importOriginal) => {
@@ -56,6 +60,19 @@ describe("mcp install command", () => {
});
});
it("shows mcp-remote marketplace entries as native remote servers", () => {
expect(
buildMcpInstallDefaults({
name: "linear",
targetArgs: ["npx", "-y", "mcp-remote", "https://mcp.linear.app/mcp"],
}),
).toEqual({
name: "linear",
type: "streamableHttp",
url: "https://mcp.linear.app/mcp",
});
});
it("normalizes streamable-http transport", () => {
expect(
buildMcpInstallDefaults({
@@ -269,3 +286,131 @@ describe("mcp install command", () => {
});
});
});
describe("mcp uninstall command", () => {
let root = "";
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "cli-mcp-uninstall-"));
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
});
function writeSettings(): string {
const settingsPath = join(root, "cline_mcp_settings.json");
writeFileSync(
settingsPath,
JSON.stringify(
{
mcpServers: {
docs: {
transport: {
type: "streamableHttp",
url: "https://example.com/mcp",
},
},
keep: {
transport: { type: "stdio", command: "node" },
disabled: true,
},
},
customTopLevelKey: true,
},
null,
2,
),
"utf8",
);
return settingsPath;
}
function readSettings(settingsPath: string): Record<string, unknown> & {
mcpServers?: Record<string, unknown>;
} {
return JSON.parse(readFileSync(settingsPath, "utf8")) as Record<
string,
unknown
> & { mcpServers?: Record<string, unknown> };
}
it("uninstalls the requested server and reports success", async () => {
const settingsPath = writeSettings();
const writeln = vi.fn();
const writeErr = vi.fn();
const code = await runMcpUninstallCommand({
name: "docs",
settingsPath,
io: { writeln, writeErr },
});
expect(code).toBe(0);
expect(writeln).toHaveBeenCalledWith("Uninstalled MCP server docs.");
expect(writeErr).not.toHaveBeenCalled();
const written = readSettings(settingsPath);
expect(Object.keys(written.mcpServers ?? {})).toEqual(["keep"]);
expect(written.mcpServers?.keep).toEqual({
transport: { type: "stdio", command: "node" },
disabled: true,
});
expect(written.customTopLevelKey).toBe(true);
});
it("prints uninstall JSON with --json", async () => {
const settingsPath = writeSettings();
const writeln = vi.fn();
const code = await runMcpUninstallCommand({
name: "docs",
settingsPath,
json: true,
io: { writeln, writeErr: vi.fn() },
});
expect(code).toBe(0);
expect(JSON.parse(writeln.mock.calls[0]?.[0])).toEqual({
name: "docs",
status: "uninstalled",
});
expect(writeln).toHaveBeenCalledTimes(1);
});
it("reports an error and leaves settings intact for an unknown server", async () => {
const settingsPath = writeSettings();
const before = readFileSync(settingsPath, "utf8");
const writeln = vi.fn();
const writeErr = vi.fn();
const code = await runMcpUninstallCommand({
name: "missing",
settingsPath,
io: { writeln, writeErr },
});
expect(code).toBe(1);
expect(writeErr).toHaveBeenCalledWith(
'MCP server "missing" is not installed.',
);
expect(writeln).not.toHaveBeenCalled();
expect(readFileSync(settingsPath, "utf8")).toBe(before);
});
it("rejects a blank name without rewriting settings", async () => {
const settingsPath = writeSettings();
const before = readFileSync(settingsPath, "utf8");
const writeErr = vi.fn();
const code = await runMcpUninstallCommand({
name: " ",
settingsPath,
io: { writeErr },
});
expect(code).toBe(1);
expect(writeErr).toHaveBeenCalledWith("MCP server name is required");
expect(readFileSync(settingsPath, "utf8")).toBe(before);
});
});
+52 -58
View File
@@ -1,12 +1,16 @@
import {
buildMcpInstallTransport as buildCoreMcpInstallTransport,
type McpInstallOptions as CoreMcpInstallOptions,
installMcpServer,
type McpInstallResult,
type McpServerTransportConfig,
type McpUninstallOptions as CoreMcpUninstallOptions,
type McpUninstallResult as CoreMcpUninstallResult,
uninstallMcpServer,
} from "@cline/core";
import type { McpAddDefaults } from "../wizards/mcp";
export { buildMcpInstallTransport } from "@cline/core";
export { buildMcpInstallTransport, uninstallMcpServer } from "@cline/core";
export interface McpCommandIo {
writeln?: (text: string) => void;
@@ -28,39 +32,6 @@ export interface McpInstallDirectResult {
warnings: string[];
}
function normalizeTransportType(
value: string | undefined,
): McpServerTransportConfig["type"] {
const normalized = (value ?? "stdio").trim();
if (normalized === "http" || normalized === "streamable-http") {
return "streamableHttp";
}
if (
normalized === "stdio" ||
normalized === "sse" ||
normalized === "streamableHttp"
) {
return normalized;
}
throw new Error(
`Unsupported MCP transport "${normalized}". Expected stdio, sse, http, streamable-http, or streamableHttp.`,
);
}
function assertValidUrl(url: string): void {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error(`Invalid MCP server URL: ${url}`);
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(
`Invalid MCP server URL: ${url} (only http and https are supported)`,
);
}
}
function quoteCommandArg(arg: string): string {
if (/^[^\s"'\\]+$/.test(arg)) {
return arg;
@@ -73,36 +44,20 @@ export function buildMcpInstallDefaults(options: {
targetArgs?: string[];
transport?: string;
}): McpAddDefaults {
const name = options.name.trim();
if (!name) {
throw new Error("MCP server name is required");
}
const type = normalizeTransportType(options.transport);
const targetArgs = options.targetArgs ?? [];
if (type === "stdio") {
if (targetArgs.length === 0) {
throw new Error(
"Stdio MCP install requires a command after the server name, for example: cline mcp install fs -- npx -y @modelcontextprotocol/server-filesystem /tmp",
);
}
const { name, transport } = buildCoreMcpInstallTransport(options);
if (transport.type === "stdio") {
return {
name,
type,
command: targetArgs.map(quoteCommandArg).join(" "),
type: transport.type,
command: [transport.command, ...(transport.args ?? [])]
.map(quoteCommandArg)
.join(" "),
};
}
if (targetArgs.length !== 1) {
throw new Error(
"Remote MCP install requires exactly one URL argument after the server name.",
);
}
const url = targetArgs[0]?.trim() ?? "";
assertValidUrl(url);
return {
name,
type,
url,
type: transport.type,
url: transport.url,
};
}
@@ -158,3 +113,42 @@ export async function runMcpInstallCommand(
return 1;
}
}
export interface McpUninstallOptions extends CoreMcpUninstallOptions {
io?: McpCommandIo;
json?: boolean;
}
export interface McpUninstallDirectResult extends CoreMcpUninstallResult {}
export function uninstallMcpServerDirect(
options: McpUninstallOptions,
): McpUninstallDirectResult {
const result: CoreMcpUninstallResult = uninstallMcpServer(options);
return {
name: result.name,
status: result.status,
};
}
export async function runMcpUninstallCommand(
options: McpUninstallOptions,
): Promise<number> {
try {
const name = options.name?.trim() ?? "";
if (!name) {
throw new Error("MCP server name is required");
}
const result = uninstallMcpServerDirect({ ...options, name });
if (options.json) {
options.io?.writeln?.(JSON.stringify(result));
} else {
options.io?.writeln?.(`Uninstalled MCP server ${result.name}.`);
}
return 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
options.io?.writeErr(message);
return 1;
}
}
+230 -55
View File
@@ -4,13 +4,42 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createScheduleCommand } from "./schedule";
const mockSendHubCommand = vi.hoisted(() => vi.fn());
const mockHubClientCommand = vi.hoisted(() => vi.fn());
const mockNodeHubClientCtor = vi.hoisted(() => vi.fn());
const mockEnsureCliHubServer = vi.hoisted(() => vi.fn());
vi.mock("@cline/core", () => ({
sendHubCommand: mockSendHubCommand,
const mockProviderSettings = vi.hoisted(() => ({
lastUsed: undefined as { provider?: string; model?: string } | undefined,
providers: {} as Record<string, { provider?: string; model?: string }>,
}));
vi.mock("@cline/core", async () => {
const actual =
await vi.importActual<typeof import("@cline/core")>("@cline/core");
return {
...actual,
NodeHubClient: class {
command = mockHubClientCommand;
constructor(options: Record<string, unknown>) {
mockNodeHubClientCtor(options);
}
async connect(): Promise<void> {}
close(): void {}
},
ProviderSettingsManager: class {
getLastUsedProviderSettings() {
return mockProviderSettings.lastUsed;
}
getProviderSettings(providerId: string) {
return mockProviderSettings.providers[providerId];
}
},
};
});
vi.mock("../utils/hub-runtime", () => ({
ensureCliHubServer: mockEnsureCliHubServer,
parseHubEndpointOverride: (rawAddress: string | undefined) => {
@@ -47,6 +76,8 @@ async function runScheduleCommand(
describe("runScheduleCommand list output", () => {
afterEach(() => {
vi.clearAllMocks();
mockProviderSettings.lastUsed = undefined;
mockProviderSettings.providers = {};
});
it('prints "No schedules found." for empty non-json list output', async () => {
@@ -54,7 +85,7 @@ describe("runScheduleCommand list output", () => {
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedules: [] },
});
@@ -76,18 +107,21 @@ describe("runScheduleCommand list output", () => {
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(output).toEqual(["No schedules found."]);
expect(mockSendHubCommand).toHaveBeenCalledWith(
{ host: "127.0.0.1", port: 25463, pathname: "/hub" },
{
clientId: "cline-schedule",
command: "schedule.list",
payload: {
limit: 100,
enabled: undefined,
tags: undefined,
},
},
// Schedule commands are workspace-scoped: the hub client must register
// with a workspace context (and the hub auth token) before commanding.
expect(mockNodeHubClientCtor).toHaveBeenCalledWith(
expect.objectContaining({
url: "ws://127.0.0.1:25463/hub",
workspaceRoot: process.cwd(),
cwd: process.cwd(),
authToken: "test-token",
}),
);
expect(mockHubClientCommand).toHaveBeenCalledWith("schedule.list", {
limit: 100,
enabled: undefined,
tags: undefined,
});
});
it("keeps JSON list output unchanged when --json is provided", async () => {
@@ -95,7 +129,7 @@ describe("runScheduleCommand list output", () => {
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedules: [] },
});
@@ -117,13 +151,163 @@ describe("runScheduleCommand list output", () => {
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(output).toEqual(["[]"]);
expect(mockSendHubCommand).toHaveBeenCalled();
expect(mockHubClientCommand).toHaveBeenCalled();
});
});
describe("runScheduleCommand create delivery metadata", () => {
describe("runScheduleCommand create", () => {
afterEach(() => {
vi.clearAllMocks();
mockProviderSettings.lastUsed = undefined;
mockProviderSettings.providers = {};
});
it("uses the last used provider and model when both flags are omitted", async () => {
mockProviderSettings.lastUsed = {
provider: "anthropic",
model: "claude-sonnet-4-6",
};
mockEnsureCliHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: { scheduleId: "sched_123" } },
});
const output: string[] = [];
const errors: string[] = [];
const code = await runScheduleCommand(
[
"create",
"Health check",
"--cron",
"0 */6 * * *",
"--prompt",
"Run tests",
"--workspace",
"/tmp/workspace",
"--address",
"127.0.0.1:25463",
],
{
writeln: (text?: string) => {
output.push(text ?? "");
},
writeErr: (text: string) => {
errors.push(text);
},
},
);
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(mockNodeHubClientCtor).toHaveBeenCalledWith(
expect.objectContaining({
url: "ws://127.0.0.1:25463/hub",
workspaceRoot: "/tmp/workspace",
cwd: "/tmp/workspace",
authToken: "test-token",
}),
);
expect(mockHubClientCommand).toHaveBeenCalledWith(
"schedule.create",
expect.objectContaining({
provider: "anthropic",
model: "claude-sonnet-4-6",
}),
);
});
it("uses an explicit provider with that provider's configured model", async () => {
mockProviderSettings.lastUsed = {
provider: "cline",
model: "openai/gpt-5.3-codex",
};
mockProviderSettings.providers.anthropic = {
provider: "anthropic",
model: "claude-sonnet-4-6",
};
mockEnsureCliHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: { scheduleId: "sched_123" } },
});
const errors: string[] = [];
const code = await runScheduleCommand(
[
"create",
"Health check",
"--cron",
"0 */6 * * *",
"--prompt",
"Run tests",
"--workspace",
"/tmp/workspace",
"--provider",
"anthropic",
"--address",
"127.0.0.1:25463",
],
{
writeln: () => {},
writeErr: (text: string) => {
errors.push(text);
},
},
);
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(mockHubClientCommand).toHaveBeenCalledWith(
"schedule.create",
expect.objectContaining({
provider: "anthropic",
model: "claude-sonnet-4-6",
}),
);
});
it("fails when an explicit provider has no configured model and no model flag", async () => {
mockEnsureCliHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
const errors: string[] = [];
const code = await runScheduleCommand(
[
"create",
"Health check",
"--cron",
"0 */6 * * *",
"--prompt",
"Run tests",
"--workspace",
"/tmp/workspace",
"--provider",
"anthropic",
"--address",
"127.0.0.1:25463",
],
{
writeln: () => {},
writeErr: (text: string) => {
errors.push(text);
},
},
);
expect(code).toBe(1);
expect(errors).toEqual([
'No model is configured for provider "anthropic". Pass --model or save a model for that provider before creating the schedule.',
]);
expect(mockHubClientCommand).not.toHaveBeenCalled();
});
it("maps --delivery-bot to delivery.userName", async () => {
@@ -131,7 +315,7 @@ describe("runScheduleCommand create delivery metadata", () => {
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: { scheduleId: "sched_delivery" } },
});
@@ -170,21 +354,17 @@ describe("runScheduleCommand create delivery metadata", () => {
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(output).toEqual(['{\n "scheduleId": "sched_delivery"\n}']);
expect(mockSendHubCommand).toHaveBeenCalledWith(
{ host: "127.0.0.1", port: 25463, pathname: "/hub" },
{
clientId: "cline-schedule",
command: "schedule.create",
payload: expect.objectContaining({
metadata: {
delivery: {
adapter: "telegram",
threadId: "telegram:123456789",
userName: "my_bot",
},
expect(mockHubClientCommand).toHaveBeenCalledWith(
"schedule.create",
expect.objectContaining({
metadata: {
delivery: {
adapter: "telegram",
threadId: "telegram:123456789",
userName: "my_bot",
},
}),
},
},
}),
);
});
});
@@ -192,6 +372,8 @@ describe("runScheduleCommand create delivery metadata", () => {
describe("runScheduleCommand import", () => {
afterEach(() => {
vi.clearAllMocks();
mockProviderSettings.lastUsed = undefined;
mockProviderSettings.providers = {};
});
it("preserves exported modelSelection providerId/modelId values", async () => {
@@ -199,7 +381,7 @@ describe("runScheduleCommand import", () => {
url: "ws://127.0.0.1:25463/hub",
authToken: "test-token",
});
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: { scheduleId: "sched_123" } },
});
@@ -240,16 +422,12 @@ describe("runScheduleCommand import", () => {
expect(code).toBe(0);
expect(errors).toEqual([]);
expect(output).toEqual(['{\n "scheduleId": "sched_123"\n}']);
expect(mockSendHubCommand).toHaveBeenCalledWith(
{ host: "127.0.0.1", port: 25463, pathname: "/hub" },
{
clientId: "cline-schedule",
command: "schedule.create",
payload: expect.objectContaining({
provider: "anthropic",
model: "claude-sonnet-4-6",
}),
},
expect(mockHubClientCommand).toHaveBeenCalledWith(
"schedule.create",
expect.objectContaining({
provider: "anthropic",
model: "claude-sonnet-4-6",
}),
);
});
});
@@ -257,6 +435,8 @@ describe("runScheduleCommand import", () => {
describe("runScheduleCommand export", () => {
afterEach(() => {
vi.clearAllMocks();
mockProviderSettings.lastUsed = undefined;
mockProviderSettings.providers = {};
});
it("writes JSON content to the --to file path", async () => {
@@ -271,7 +451,7 @@ describe("runScheduleCommand export", () => {
prompt: "review status",
workspaceRoot: "/tmp/workspace",
};
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: scheduleRecord },
});
@@ -311,14 +491,9 @@ describe("runScheduleCommand export", () => {
const written = await readFile(targetPath, "utf8");
expect(written).toBe(JSON.stringify(scheduleRecord, null, 2));
expect(mockSendHubCommand).toHaveBeenCalledWith(
{ host: "127.0.0.1", port: 25463, pathname: "/hub" },
{
clientId: "cline-schedule",
command: "schedule.get",
payload: { scheduleId: "sched_abc" },
},
);
expect(mockHubClientCommand).toHaveBeenCalledWith("schedule.get", {
scheduleId: "sched_abc",
});
} finally {
await rm(targetPath, { force: true });
}
@@ -334,7 +509,7 @@ describe("runScheduleCommand export", () => {
name: "Weekly Sync",
cronPattern: "0 9 * * 1",
};
mockSendHubCommand.mockResolvedValue({
mockHubClientCommand.mockResolvedValue({
ok: true,
payload: { schedule: scheduleRecord },
});
+62 -26
View File
@@ -2,7 +2,7 @@ import {
createLocalHubScheduleRuntimeHandlers,
HubScheduleCommandService,
HubScheduleService,
sendHubCommand,
NodeHubClient,
} from "@cline/core";
import {
ensureCliHubServer,
@@ -11,28 +11,51 @@ import {
import type { CommandIo } from "./types";
export class HubScheduleClient {
private hub: Promise<NodeHubClient> | undefined;
constructor(
private readonly endpoint: {
host?: string;
port?: number;
pathname?: string;
},
private readonly url: string,
private readonly workspaceRoot: string,
private readonly authToken?: string,
) {}
close(): void {}
close(): void {
const hub = this.hub;
this.hub = undefined;
void hub?.then((client) => client.close()).catch(() => undefined);
}
// Schedule commands are authorized against the workspace bound to the
// connection's client registration, so all commands must share one
// registered connection instead of fire-and-forget envelopes.
private connectedHub(): Promise<NodeHubClient> {
this.hub ??= (async () => {
const client = new NodeHubClient({
url: this.url,
clientType: "cli-schedule",
displayName: "Cline CLI scheduler",
workspaceRoot: this.workspaceRoot,
cwd: this.workspaceRoot,
authToken: this.authToken,
});
try {
await client.connect();
} catch (error) {
client.close();
this.hub = undefined;
throw error;
}
return client;
})();
return this.hub;
}
private async command(
command: string,
payload?: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const reply = await sendHubCommand(this.endpoint, {
clientId: "cline-schedule",
command: command as never,
payload,
});
if (!reply.ok) {
throw new Error(reply.error?.message ?? `hub command failed: ${command}`);
}
const client = await this.connectedHub();
const reply = await client.command(command as never, payload);
return (reply.payload ?? {}) as Record<string, unknown>;
}
@@ -97,6 +120,7 @@ export class LocalScheduleClient {
runtimeHandlers: createLocalHubScheduleRuntimeHandlers(),
});
private readonly commands = new HubScheduleCommandService(this.service);
constructor(private readonly workspaceRoot: string) {}
close(): void {
void this.service.dispose();
@@ -106,12 +130,21 @@ export class LocalScheduleClient {
command: string,
payload?: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const reply = await this.commands.handleCommand({
version: "v1",
clientId: "cline-schedule-local",
command: command as never,
payload,
});
const reply = await this.commands.handleCommand(
{
version: "v1",
clientId: "cline-schedule-local",
command: command as never,
payload,
},
{
clientId: "cline-schedule-local",
workspaceContext: {
workspaceRoot: this.workspaceRoot,
cwd: this.workspaceRoot,
},
},
);
if (!reply.ok) {
throw new Error(reply.error?.message ?? `hub command failed: ${command}`);
}
@@ -185,24 +218,27 @@ export async function ensureSchedulerHub(
if (!address?.trim()) {
return {
ok: true,
client: new LocalScheduleClient() as unknown as HubScheduleClient,
client: new LocalScheduleClient(
workspaceRoot,
) as unknown as HubScheduleClient,
};
}
try {
const requestedEndpoint = parseHubEndpointOverride(address);
const { url: hubUrl } = await ensureCliHubServer(
const { url: hubUrl, authToken } = await ensureCliHubServer(
workspaceRoot,
requestedEndpoint,
);
const endpoint = parseHubEndpointOverride(hubUrl);
return {
ok: true,
client: new HubScheduleClient(endpoint),
client: new HubScheduleClient(hubUrl, workspaceRoot, authToken),
};
} catch (_error) {
return {
ok: true,
client: new LocalScheduleClient() as unknown as HubScheduleClient,
client: new LocalScheduleClient(
workspaceRoot,
) as unknown as HubScheduleClient,
};
}
}
+9 -5
View File
@@ -1,4 +1,3 @@
import { CLINE_DEFAULT_MODEL_ID } from "@cline/shared";
import type { Command } from "commander";
import { ensureSchedulerHub } from "./client";
import {
@@ -19,6 +18,7 @@ import {
registerScheduleImportCommand,
registerScheduleUpdateCommand,
} from "./import-export";
import { resolveScheduleModelSelection } from "./model-selection";
import type { CommandIo, ScheduleActionWrapper } from "./types";
export function registerScheduleCommands(
@@ -66,8 +66,8 @@ export function registerScheduleCommands(
.option("--max-parallel <n>", "Max parallel executions", "1")
.option("--metadata-json <json>", "Metadata as JSON object")
.option("--mode <act|plan|yolo>", "Execution mode", "yolo")
.option("--model <model>", "Model to use", CLINE_DEFAULT_MODEL_ID)
.option("--provider <id>", "Provider ID", "cline")
.option("--model <model>", "Model to use")
.option("--provider <id>", "Provider ID")
.option("--system-prompt <text>", "System prompt override")
.option("--tags <list>", "Comma-separated tags")
.option("--timeout <seconds>", "Timeout in seconds");
@@ -92,12 +92,16 @@ export function registerScheduleCommands(
parseJsonObjectFlag(opts.metadataJson),
opts,
);
const modelSelection = resolveScheduleModelSelection({
provider: opts.provider,
model: opts.model,
});
const created = await client.createSchedule({
name,
cronPattern: opts.cron,
prompt: opts.prompt,
provider: opts.provider,
model: opts.model,
provider: modelSelection.provider,
model: modelSelection.model,
mode: parseMode(opts.mode) ?? "yolo",
workspaceRoot: opts.workspace,
cwd: opts.cwd,
+15 -14
View File
@@ -1,6 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, isAbsolute, resolve } from "node:path";
import { CLINE_DEFAULT_MODEL_ID } from "@cline/shared";
import type { Command } from "commander";
import { ensureSchedulerHub } from "./client";
import {
@@ -18,8 +17,13 @@ import {
resolveAddress,
toPositiveInt,
} from "./common";
import { resolveScheduleModelSelection } from "./model-selection";
import type { CommandIo, ScheduleActionWrapper } from "./types";
function stringValue(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function resolveImportedModelSelection(parsed: Record<string, unknown>): {
provider: string;
model: string;
@@ -30,19 +34,16 @@ function resolveImportedModelSelection(parsed: Record<string, unknown>): {
!Array.isArray(parsed.modelSelection)
? (parsed.modelSelection as Record<string, unknown>)
: undefined;
const provider = String(
modelSelection?.providerId ??
parsed.providerId ??
parsed.provider ??
"cline",
).trim();
const model = String(
modelSelection?.modelId ??
parsed.modelId ??
parsed.model ??
CLINE_DEFAULT_MODEL_ID,
).trim();
return { provider, model };
return resolveScheduleModelSelection({
provider:
stringValue(modelSelection?.providerId) ??
stringValue(parsed.providerId) ??
stringValue(parsed.provider),
model:
stringValue(modelSelection?.modelId) ??
stringValue(parsed.modelId) ??
stringValue(parsed.model),
});
}
export function registerScheduleExportCommand(
@@ -0,0 +1,52 @@
import { type ProviderSettings, ProviderSettingsManager } from "@cline/core";
import { CLINE_DEFAULT_MODEL_ID } from "@cline/shared";
export const DEFAULT_SCHEDULE_PROVIDER = "cline";
interface ProviderSettingsReader {
getLastUsedProviderSettings(): ProviderSettings | undefined;
getProviderSettings(providerId: string): ProviderSettings | undefined;
}
function trimToUndefined(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
export function resolveScheduleModelSelection(
options: {
provider?: string;
model?: string;
},
providerSettingsManager?: ProviderSettingsReader,
): { provider: string; model: string } {
const explicitProvider = trimToUndefined(options.provider);
const explicitModel = trimToUndefined(options.model);
if (explicitProvider && explicitModel) {
return { provider: explicitProvider, model: explicitModel };
}
const manager = providerSettingsManager ?? new ProviderSettingsManager();
const lastUsedSettings = manager.getLastUsedProviderSettings();
const provider =
explicitProvider ??
trimToUndefined(lastUsedSettings?.provider) ??
DEFAULT_SCHEDULE_PROVIDER;
const selectedProviderSettings = explicitProvider
? manager.getProviderSettings(provider)
: lastUsedSettings;
const model =
explicitModel ??
trimToUndefined(selectedProviderSettings?.model) ??
(provider === DEFAULT_SCHEDULE_PROVIDER
? CLINE_DEFAULT_MODEL_ID
: undefined);
if (!model) {
throw new Error(
`No model is configured for provider "${provider}". Pass --model or save a model for that provider before creating the schedule.`,
);
}
return { provider, model };
}
+86 -68
View File
@@ -1,12 +1,10 @@
import type { ChildProcess } from "node:child_process";
import { EventEmitter } from "node:events";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
const { mockEnsureCliHubServer, mockSpawn } = vi.hoisted(() => ({
mockEnsureCliHubServer: vi.fn(),
const { mockSpawn } = vi.hoisted(() => ({
mockSpawn: vi.fn(),
}));
@@ -18,14 +16,10 @@ vi.mock("node:child_process", async (importOriginal) => {
};
});
vi.mock("../utils/hub-runtime", () => ({
ensureCliHubServer: mockEnsureCliHubServer,
}));
import {
applyDeferredUpdate,
autoUpdateOnStartup,
checkForUpdates,
ensureCliHubServerAfterUpdate,
getInstallationInfo,
PackageManager,
resolveCliHubOwnerContext,
@@ -42,14 +36,6 @@ const originalIsDev = process.env.IS_DEV;
const originalNoAutoUpdate = process.env.CLINE_NO_AUTO_UPDATE;
const tempDirs: string[] = [];
function createChildProcessThatCloses(exitCode: number): ChildProcess {
const child = new EventEmitter();
queueMicrotask(() => {
child.emit("close", exitCode);
});
return child as ChildProcess;
}
function createFile(path: string): string {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, "");
@@ -265,68 +251,100 @@ describe("hub restart owner selection", () => {
});
});
describe("post-update hub launch", () => {
describe("deferred auto update", () => {
afterEach(() => {
mockEnsureCliHubServer.mockReset();
mockSpawn.mockReset();
if (originalBuildEnv === undefined) {
delete process.env.CLINE_BUILD_ENV;
} else {
process.env.CLINE_BUILD_ENV = originalBuildEnv;
}
if (originalHubDiscoveryPath === undefined) {
delete process.env.CLINE_HUB_DISCOVERY_PATH;
} else {
process.env.CLINE_HUB_DISCOVERY_PATH = originalHubDiscoveryPath;
}
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
it("uses the freshly installed wrapper instead of the current executable", async () => {
mockSpawn.mockReturnValue(createChildProcessThatCloses(0));
const env = {
CLINE_WRAPPER_PATH: "/opt/cline/lib/node_modules/cline/bin/cline",
CLINE_NO_AUTO_UPDATE: "0",
};
await ensureCliHubServerAfterUpdate("/workspace/project", env, "linux");
expect(mockSpawn).toHaveBeenCalledWith(
"/opt/cline/lib/node_modules/cline/bin/cline",
["hub", "ensure"],
{
cwd: "/workspace/project",
env: {
...env,
CLINE_NO_AUTO_UPDATE: "1",
},
stdio: "ignore",
windowsHide: true,
},
);
expect(mockEnsureCliHubServer).not.toHaveBeenCalled();
});
it("uses the in-process ensure path when no executable cache can be deleted", async () => {
mockEnsureCliHubServer.mockResolvedValue({
url: "ws://127.0.0.1:25463/hub",
authToken: "token",
});
await ensureCliHubServerAfterUpdate(
"C:\\workspace\\project",
{ CLINE_WRAPPER_PATH: "C:\\npm\\node_modules\\cline\\bin\\cline" },
"win32",
);
expect(mockEnsureCliHubServer).toHaveBeenCalledWith(
"C:\\workspace\\project",
);
it("does nothing when no update was recorded", async () => {
expect(await applyDeferredUpdate(undefined)).toBe("none");
expect(mockSpawn).not.toHaveBeenCalled();
});
it("surfaces a failure from the freshly installed CLI", async () => {
mockSpawn.mockReturnValue(createChildProcessThatCloses(1));
it("starts the detached install when no hub is discoverable", async () => {
const root = mkdtempSync(join(tmpdir(), "cline-update-test-"));
tempDirs.push(root);
process.env.CLINE_BUILD_ENV = "production";
process.env.CLINE_HUB_DISCOVERY_PATH = join(root, "production.json");
const unref = vi.fn();
mockSpawn.mockReturnValue({ unref } as unknown as ChildProcess);
await expect(
ensureCliHubServerAfterUpdate(
"/workspace/project",
{ CLINE_WRAPPER_PATH: "/opt/cline/bin/cline" },
"linux",
),
).rejects.toThrow(
"freshly installed Cline failed to start the hub (exit code 1)",
const outcome = await applyDeferredUpdate({
command: "npm update -g cline --tag latest --min-release-age=0",
});
expect(outcome).toBe("started");
expect(mockSpawn).toHaveBeenCalledWith(
"npm update -g cline --tag latest --min-release-age=0",
expect.objectContaining({
detached: true,
shell: true,
stdio: "ignore",
}),
);
expect(unref).toHaveBeenCalled();
});
it("defers while another cli client is attached to the hub", async () => {
const root = mkdtempSync(join(tmpdir(), "cline-update-test-"));
tempDirs.push(root);
const discoveryPath = join(root, "production.json");
process.env.CLINE_BUILD_ENV = "production";
process.env.CLINE_HUB_DISCOVERY_PATH = discoveryPath;
const {
createLocalHubScheduleRuntimeHandlers,
NodeHubClient,
startHubWebSocketServer,
} = await import("@cline/core");
const server = await startHubWebSocketServer({
host: "127.0.0.1",
port: 0,
owner: { ownerId: "update-test", discoveryPath },
runtimeHandlers: createLocalHubScheduleRuntimeHandlers(),
});
const cliClient = new NodeHubClient({
url: server.url,
authToken: server.authToken,
clientType: "cli",
displayName: "fake attached cli",
});
try {
await cliClient.command("client.list", {});
expect(await applyDeferredUpdate({ command: "echo update" })).toBe(
"deferred",
);
expect(mockSpawn).not.toHaveBeenCalled();
await cliClient.dispose();
const unref = vi.fn();
mockSpawn.mockReturnValue({ unref } as unknown as ChildProcess);
// The hub unregisters the client when its socket closes; poll
// briefly rather than assuming the close is processed instantly.
let outcome = "deferred";
const deadline = Date.now() + 3_000;
while (outcome === "deferred" && Date.now() < deadline) {
outcome = await applyDeferredUpdate({ command: "echo update" });
}
expect(outcome).toBe("started");
} finally {
await cliClient.dispose().catch(() => undefined);
await server.close();
}
}, 15_000);
});
describe("withMinimumReleaseAgeBypass", () => {
+137 -134
View File
@@ -1,17 +1,14 @@
import { type ChildProcess, spawn } from "node:child_process";
import { realpathSync } from "node:fs";
import {
clearHubDiscovery,
isAutoUpdateEnabledGlobally,
probeHubServer,
NodeHubClient,
readHubDiscovery,
resolveProductionHubOwnerContext,
resolveSharedHubOwnerContext,
stopLocalHubServerGracefully,
} from "@cline/core";
import { resolveClineBuildEnv } from "@cline/shared";
import { version } from "../../package.json";
import { ensureCliHubServer } from "../utils/hub-runtime";
import { c, writeErr, writeln } from "../utils/output";
import {
getInstalledKanbanVersion,
@@ -237,50 +234,6 @@ async function runKanbanUpdate(
return waitForProcessExit(updateProcess);
}
/**
* Start the hub through the freshly installed CLI after a self-update.
*
* On Unix, the npm wrapper normally starts the CLI from bin/.cline. npm 12 may
* remove that cached executable while replacing the package and then block the
* postinstall script that recreates it. The current process keeps running from
* the unlinked executable, but process.execPath is no longer spawnable. Going
* back through the wrapper makes it resolve the newly installed platform
* binary instead.
*
* Windows does not create the bin/.cline cache, and development builds do not
* have CLINE_WRAPPER_PATH, so those cases keep using the normal in-process
* ensure path.
*/
export async function ensureCliHubServerAfterUpdate(
workspaceRoot: string,
env: NodeJS.ProcessEnv = process.env,
platform: NodeJS.Platform = process.platform,
): Promise<void> {
const wrapperPath = env.CLINE_WRAPPER_PATH?.trim();
if (!wrapperPath || platform === "win32") {
await ensureCliHubServer(workspaceRoot);
return;
}
const child = spawn(wrapperPath, ["hub", "ensure"], {
cwd: workspaceRoot,
env: {
...env,
// The fresh CLI only exists to start the hub. Do not let it launch
// another background update check while this update is finishing.
CLINE_NO_AUTO_UPDATE: "1",
},
stdio: "ignore",
windowsHide: true,
});
const exitCode = await waitForProcessExit(child);
if (exitCode !== 0) {
throw new Error(
`freshly installed Cline failed to start the hub (exit code ${exitCode})`,
);
}
}
function formatUpdateSummaryTargets(targets: string[]): string {
if (targets.length === 0) {
return "";
@@ -318,86 +271,40 @@ export function getPreferredKanbanInstaller(
);
}
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
export function resolveCliHubOwnerContext() {
return resolveClineBuildEnv() === "production"
? resolveProductionHubOwnerContext()
: resolveSharedHubOwnerContext();
}
async function waitForHubToStop(
url: string,
authToken: string | undefined,
timeoutMs: number,
): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const check = await probeHubServer(url, { authToken }).catch(
() => undefined,
);
if (!check?.url) return true;
await sleep(100);
}
return false;
}
let pendingAutoUpdate: ManualUpdateCommand | undefined;
let pendingAutoUpdateCheck: Promise<void> | undefined;
/**
* Restart the hub server if one is currently running.
* Gracefully asks the running hub process to stop, falls back to process signals,
* clears stale discovery, then re-ensures a fresh instance is spawned.
*/
async function restartHubServerIfRunning(): Promise<void> {
const owner = resolveCliHubOwnerContext();
const discovery = await readHubDiscovery(owner.discoveryPath).catch(
() => undefined,
);
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
const health = discovery?.url
? await probeHubServer(discovery.url, {
authToken: discovery.authToken,
}).catch(() => undefined)
: undefined;
if (!discovery || !health?.url) return;
// How long the exit sequence will wait for a still-in-flight startup version
// check before giving up on it. Long enough for a typical registry response,
// short enough that one-shot commands do not feel it.
const UPDATE_CHECK_EXIT_GRACE_MS = 250;
const pid = discovery?.pid;
writeln(`${c.dim}[hub] restarting server…${c.reset}`);
let stopped = await stopLocalHubServerGracefully(owner).catch(() => false);
if (!stopped && pid) {
try {
process.kill(pid, "SIGTERM");
} catch {
// best-effort
}
}
stopped = await waitForHubToStop(health.url, discovery.authToken, 3_000);
if (!stopped && pid) {
try {
process.kill(pid, "SIGKILL");
} catch {
// best-effort
}
stopped = await waitForHubToStop(health.url, discovery.authToken, 2_000);
}
await clearHubDiscovery(owner.discoveryPath).catch(() => undefined);
// Re-ensure a fresh hub instance is spawned.
try {
await ensureCliHubServerAfterUpdate(process.cwd());
writeln(`${c.green}${c.reset} ${c.dim}[hub] server restarted${c.reset}`);
} catch (err) {
writeErr(
`[hub] failed to restart server: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
// Hard cap on the exit-time hub query. The hub client's default connect and
// command timeouts add up to tens of seconds against a wedged hub, and this
// runs while the user is waiting for their shell prompt back.
const CLIENT_COUNT_EXIT_TIMEOUT_MS = 3_000;
/**
* Non-blocking auto-update check for CLI startup.
* Spawns a detached install process if a newer version is available.
*
* Deliberately does NOT install right away: replacing the npm package while
* cline processes are running swaps the binary under them their respawn
* paths break on the new build fingerprint and historically also restarted
* the hub daemon out from under live sessions. The check only records that an
* update is available; the CLI entrypoint calls applyDeferredUpdate() from
* its exit sequence (an explicit process.exit() follows, so a beforeExit hook
* would never fire), and the install runs only when no other CLI is attached
* to the hub at that point nothing is running that the swap could hurt.
* The next launch picks up the new binary and a fresh hub.
*
* Skipped for npx, dev, unknown installs. Disable with CLINE_NO_AUTO_UPDATE=1.
*/
export function autoUpdateOnStartup(): void {
@@ -409,35 +316,129 @@ export function autoUpdateOnStartup(): void {
getInstallationInfo(version);
if (!updateCommand) return;
void (async () => {
pendingAutoUpdateCheck = (async () => {
try {
const latest = await getLatestVersion(packageName, version);
if (!latest || compareVersions(version, latest) >= 0) return;
const autoUpdateCommand = withMinimumReleaseAgeBypass(
pendingAutoUpdate = withMinimumReleaseAgeBypass(
updateCommand,
packageManager,
);
const child = spawn(autoUpdateCommand.command, {
shell: true,
detached: true,
stdio: "ignore",
env: autoUpdateCommand.env
? { ...process.env, ...autoUpdateCommand.env }
: process.env,
// Prevent a console window from flashing on Windows; detached
// processes otherwise allocate a new visible console.
windowsHide: true,
});
const exitCode = await waitForProcessExit(child);
if (exitCode === 0) {
await restartHubServerIfRunning();
}
} catch {
// Best-effort, silently ignore
}
})();
}
/**
* True when a hub is reachable and another cli* client is attached to it.
* Only cli* clients run the npm-installed binary desktop sidecars and
* connectors ship their own so only they make the swap unsafe. This runs
* after the entrypoint's disposeAll(), so this process's own registrations
* are closed and any cli client still listed belongs to another process. Errors count as attached:
* never install unless the hub positively confirms nothing would be hurt.
*/
async function otherCliClientsAttached(): Promise<boolean> {
const owner = resolveCliHubOwnerContext();
const discovery = await readHubDiscovery(owner.discoveryPath).catch(
() => undefined,
);
if (!discovery?.url) {
return false;
}
const client = new NodeHubClient({
url: discovery.url,
authToken: discovery.authToken,
clientType: "cli-update-check",
displayName: "cline update check",
});
try {
const reply = await client.command("client.list", {}, undefined, {
timeoutMs: CLIENT_COUNT_EXIT_TIMEOUT_MS,
});
const clients =
(reply.payload as { clients?: Array<{ clientType?: unknown }> })
.clients ?? [];
if (
clients.some(
(entry) =>
typeof entry?.clientType === "string" &&
entry.clientType.startsWith("cli") &&
entry.clientType !== "cli-update-check",
)
) {
return true;
}
// A TUI's registration can be lost in transport churn while its session
// connection survives (observed in review), so an empty client list is
// not proof of safety. Cross-check for sessions somebody is attached to.
// Participants, not session status: finished sessions can linger idle
// forever and must not pin updates, and participant-less scheduled runs
// live in the hub process, which a binary swap does not touch.
const sessions = await client.command(
"session.list",
{ limit: 500 },
undefined,
{ timeoutMs: CLIENT_COUNT_EXIT_TIMEOUT_MS },
);
const sessionRecords =
(sessions.payload as { sessions?: Array<{ participants?: unknown }> })
.sessions ?? [];
return sessionRecords.some(
(session) =>
Array.isArray(session?.participants) && session.participants.length > 0,
);
} finally {
await client.dispose().catch(() => undefined);
}
}
/**
* Spawns the recorded update install, detached, if no other CLI would be
* affected by the package swap. Fire-and-forget: the install outlives this
* process and its postinstall never blocks an exit.
*/
export async function applyDeferredUpdate(
pending?: ManualUpdateCommand,
): Promise<"none" | "deferred" | "started"> {
if (!pending) {
// Short-lived commands can reach exit before the startup version check
// resolves; give it a brief grace so one-shot-only usage still updates.
if (pendingAutoUpdateCheck) {
await Promise.race([
pendingAutoUpdateCheck,
sleep(UPDATE_CHECK_EXIT_GRACE_MS),
]);
}
pending = pendingAutoUpdate;
}
if (!pending) {
return "none";
}
// The whole query is bounded: the user is waiting on their prompt, and a
// wedged hub must not turn a finished command into a hung one. A timeout
// counts as "attached" — never install unless the hub positively confirms.
const attached = await Promise.race([
otherCliClientsAttached(),
sleep(CLIENT_COUNT_EXIT_TIMEOUT_MS).then(() => true),
]).catch(() => true);
if (attached) {
return "deferred";
}
pendingAutoUpdate = undefined;
const child = spawn(pending.command, {
shell: true,
detached: true,
stdio: "ignore",
env: pending.env ? { ...process.env, ...pending.env } : process.env,
// Prevent a console window from flashing on Windows; detached
// processes otherwise allocate a new visible console.
windowsHide: true,
});
child.unref();
return "started";
}
export interface CheckForUpdatesOptions {
verbose?: boolean;
includeKanban?: boolean;
@@ -554,7 +555,9 @@ export async function checkForUpdates(
const exitCode = await runCliUpdate(manualUpdateCommand);
if (exitCode === 0) {
installedUpdates.push(`${packageName}@${latestVersion}`);
await restartHubServerIfRunning();
writeln(
`${c.dim}The update takes effect the next time cline starts.${c.reset}`,
);
} else {
writeErr(
`Cline update failed (exit code ${exitCode}). Try running: ${manualUpdateCommand.command}`,
+6 -56
View File
@@ -1,4 +1,4 @@
import { spawn, spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import {
closeSync,
@@ -13,7 +13,11 @@ import {
} from "node:fs";
import { join } from "node:path";
import type { HubSessionClient, HubSessionRow } from "@cline/core";
import { ensureParentDir, resolveClineDataDir } from "@cline/core";
import {
ensureParentDir,
getProcessStartToken,
resolveClineDataDir,
} from "@cline/core";
import {
CLINE_RUN_AS_HUB_DAEMON_ENV,
withResolvedClineBuildEnv,
@@ -85,60 +89,6 @@ type ProcessProbe = {
getStartToken: (pid: number) => string | undefined;
};
function getProcessStartToken(pid: number): string | undefined {
if (!Number.isInteger(pid) || pid <= 0) {
return undefined;
}
try {
if (process.platform === "linux") {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
const commandEnd = stat.lastIndexOf(")");
if (commandEnd < 0) {
return undefined;
}
// Fields after the command name begin at field 3 (state), so field
// 22 (starttime) is index 19.
const startTime = stat
.slice(commandEnd + 1)
.trim()
.split(/\s+/)[19];
const bootId = readFileSync(
"/proc/sys/kernel/random/boot_id",
"utf8",
).trim();
return startTime && bootId ? `linux:${bootId}:${startTime}` : undefined;
}
const result =
process.platform === "win32"
? spawnSync(
"powershell.exe",
[
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`,
],
{
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
},
)
: spawnSync("ps", ["-p", String(pid), "-o", "lstart="], {
encoding: "utf8",
env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
const startTime = result.status === 0 ? result.stdout.trim() : "";
return startTime ? `${process.platform}:${startTime}` : undefined;
} catch {
return undefined;
}
}
const defaultProcessProbe: ProcessProbe = {
isRunning: isProcessRunning,
getStartToken: getProcessStartToken,
+74
View File
@@ -7,6 +7,7 @@ import type {
UserInstructionConfigService,
} from "@cline/core";
import { isUnusableSessionError } from "@cline/core";
import type { GeneratedMedia } from "@cline/shared";
import type { SentMessage, Thread } from "chat";
import type { CliLoggerAdapter } from "../logging/adapter";
import { buildUserInputMessage, resolveSystemPrompt } from "../runtime/prompt";
@@ -125,6 +126,7 @@ async function postConnectorRuntimeReply<TState extends ConnectorThreadState>(
stream: AsyncIterable<string>,
postFinalReply?: (text: string) => Promise<void>,
resolveFallbackText?: () => Promise<string | undefined>,
hasNonTextReply?: () => boolean,
): Promise<void> {
if (transport !== "telegram" && !postFinalReply && !resolveFallbackText) {
await thread.post(stream);
@@ -135,6 +137,9 @@ async function postConnectorRuntimeReply<TState extends ConnectorThreadState>(
for await (const chunk of stream) {
text += chunk;
}
if (!text.trim() && hasNonTextReply?.()) {
return;
}
if (!text.trim()) {
text = (await resolveFallbackText?.())?.trim() || "";
}
@@ -151,6 +156,67 @@ async function postConnectorRuntimeReply<TState extends ConnectorThreadState>(
await postConnectorText(thread, transport, text);
}
const CONNECTOR_MEDIA_EXTENSIONS: Readonly<Record<string, string>> = {
"image/png": "png",
"image/jpeg": "jpg",
"image/gif": "gif",
"image/webp": "webp",
"audio/mpeg": "mp3",
"audio/wav": "wav",
"audio/ogg": "ogg",
"video/mp4": "mp4",
"video/webm": "webm",
};
async function postConnectorGeneratedMedia<TState extends ConnectorThreadState>(
thread: Thread<TState>,
mediaItems: readonly GeneratedMedia[],
): Promise<void> {
if (mediaItems.length === 0) {
return;
}
const files: Array<{ data: Buffer; filename: string; mimeType: string }> = [];
const references: string[] = [];
for (const [index, media] of mediaItems.entries()) {
const label = media.name?.trim() || `Generated ${media.modality}`;
switch (media.source.type) {
case "base64": {
const data = Buffer.from(media.source.data, "base64");
if (data.byteLength === 0) {
references.push(
`${label} (${media.mediaType}) could not be attached.`,
);
break;
}
const extension =
CONNECTOR_MEDIA_EXTENSIONS[media.mediaType.toLowerCase()] ?? "bin";
const suppliedName = media.name ? basename(media.name) : "";
files.push({
data,
filename: suppliedName || `generated-${index + 1}.${extension}`,
mimeType: media.mediaType,
});
break;
}
case "url":
references.push(`[${label}](${media.source.url})`);
break;
case "artifact":
references.push(`${label}: artifact ${media.source.artifactId}`);
break;
}
}
if (files.length === 0 && references.length === 0) {
return;
}
await thread.post({
markdown: references.length > 0 ? references.join("\n") : "Generated media",
...(files.length > 0 ? { files } : {}),
});
}
/**
* Clears a thread's stale session mapping after the hub reported the mapped
* session no longer exists, so the next turn starts a fresh session instead of
@@ -962,6 +1028,7 @@ export async function handleConnectorUserTurn<
const { prompt, userImages, userFiles } = await buildUserInputMessage(
runtimeInput,
input.userInstructionService,
{ mode: startRequest.mode },
);
try {
await input.client.sendRuntimeSession(
@@ -1051,6 +1118,7 @@ async function runConnectorRuntimeTurnWithRecovery<
const { prompt, userImages, userFiles } = await buildUserInputMessage(
runtimeInput,
input.userInstructionService,
{ mode: startRequest.mode },
);
const request: ChatRunTurnRequest = {
config: startRequest,
@@ -1151,6 +1219,7 @@ async function runConnectorRuntimeTurn<
client: input.client,
sessionId,
});
const generatedMedia: GeneratedMedia[] = [];
const activeTurn: ActiveConnectorTurn = {
sessionId,
@@ -1200,6 +1269,9 @@ async function runConnectorRuntimeTurn<
formatConnectorApprovalPrompt(approval),
);
},
onMedia: (media) => {
generatedMedia.push(media);
},
onCompleted: async (result) => {
await input.onReplyCompleted?.({
sessionId,
@@ -1219,7 +1291,9 @@ async function runConnectorRuntimeTurn<
}),
postFinalReply,
resolveFallbackText,
() => generatedMedia.length > 0,
);
await postConnectorGeneratedMedia(input.thread, generatedMedia);
} finally {
input.pendingApprovals.delete(input.thread.id);
if (input.activeTurns?.get(turnKey) === activeTurn) {
@@ -11,6 +11,49 @@ type StreamHandlers = {
};
describe("createConnectorRuntimeTurnStream", () => {
it("forwards generated media without adding binary data to the text stream", async () => {
let handlers: StreamHandlers | undefined;
const media = {
id: "generated-1",
modality: "image" as const,
mediaType: "image/png",
source: { type: "base64" as const, data: "aGVsbG8=" },
};
const client = {
streamEvents: (_request: unknown, callbacks: StreamHandlers) => {
handlers = callbacks;
return () => {};
},
sendRuntimeSession: async () => {
handlers?.onEvent({
eventType: "runtime.chat.media",
payload: { media },
});
return { result: { text: "", finishReason: "stop", iterations: 1 } };
},
};
const receivedMedia: unknown[] = [];
const chunks: string[] = [];
for await (const chunk of createConnectorRuntimeTurnStream({
client: client as never,
sessionId: "session-1",
request: { config: {} as never, prompt: "make an image" },
clientId: "client-1",
logger: { core: {} } as unknown as CliLoggerAdapter,
transport: "slack",
conversationId: "thread-1",
onMedia: (item) => {
receivedMedia.push(item);
},
})) {
chunks.push(chunk);
}
expect(chunks).toEqual([]);
expect(receivedMedia).toEqual([media]);
});
it("delivers tool status via callbacks instead of appending it to streamed text", async () => {
let handlers: StreamHandlers | undefined;
+9
View File
@@ -1,4 +1,5 @@
import type { ChatRunTurnRequest, HubSessionClient } from "@cline/core";
import { type GeneratedMedia, isGeneratedMedia } from "@cline/shared";
import type { CliLoggerAdapter } from "../logging/adapter";
export type PendingConnectorApproval = {
@@ -141,6 +142,7 @@ export function createConnectorRuntimeTurnStream(input: {
conversationId: string;
onToolStatus?: (message: string) => Promise<void>;
onApprovalRequested?: (approval: PendingConnectorApproval) => Promise<void>;
onMedia?: (media: GeneratedMedia) => Promise<void> | void;
onCompleted?: (result: {
text: string;
finishReason?: string;
@@ -189,6 +191,13 @@ export function createConnectorRuntimeTurnStream(input: {
},
{
onEvent: (event) => {
if (event.eventType === "runtime.chat.media") {
const media = event.payload.media;
if (isGeneratedMedia(media)) {
void input.onMedia?.(media);
}
return;
}
if (event.eventType === "approval.requested") {
const approvalId =
typeof event.payload.approvalId === "string"
@@ -165,7 +165,6 @@ describe("buildConnectorStartRequest", () => {
});
});
describe("isReusableConnectorSession", () => {
it("rejects missing and terminal sessions", () => {
expect(isReusableConnectorSession(undefined)).toBe(false);
+1 -3
View File
@@ -235,9 +235,7 @@ export async function getOrCreateSessionId<
transport: input.transport,
threadId: input.thread.id,
sessionId: existing,
...(existingSession?.status
? { status: existingSession.status }
: {}),
...(existingSession?.status ? { status: existingSession.status } : {}),
},
);
}
+9
View File
@@ -97,6 +97,15 @@ if (!isMainThread) {
} finally {
await disposeAll();
}
// The explicit process.exit below means beforeExit never fires, so a
// startup-recorded auto-update must be applied here, after all runtime
// teardown. It spawns detached and only when no other CLI is attached.
try {
const { applyDeferredUpdate } = await import("./commands/update");
await applyDeferredUpdate();
} catch {
// Best-effort; never block exit on the updater.
}
process.exit(exitCode || (process.exitCode as number) || 0);
})();
}
@@ -2,7 +2,7 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useCallback, useMemo, useState } from "react";
import { palette } from "../tui/palette";
import { useDialogPalette } from "../tui/hooks/use-theme";
import {
type DialogDismissKey,
isAnyKeyDismiss,
@@ -35,6 +35,7 @@ export function MigrationNoticeContent(
},
) {
const { dialogId, notice, resolve } = props;
const palette = useDialogPalette();
const subscriptionUrl = useMemo(() => getCliSubscriptionUrl(), []);
const [status, setStatus] = useState<string | undefined>();
@@ -70,7 +71,6 @@ export function MigrationNoticeContent(
latest open-weight coding models with enough quota for day-to-day
work, at a much lower cost than paying API costs directly.
</text>
<text selectable>Try it now with a limited-time promo for $4.99.</text>
</box>
<box flexDirection="row">
<text fg={palette.act} selectable>
+22 -1
View File
@@ -17,6 +17,7 @@ import {
} from "./commands/update";
import { CLI_DEFAULT_CHECKPOINT_CONFIG } from "./runtime/defaults";
import type { TuiStartupTarget } from "./tui/types";
import { filterChatModels } from "./utils/chat-models";
import { getCliBuildInfo } from "./utils/common";
import {
buildCliCompactionConfig,
@@ -505,6 +506,24 @@ export async function runCli(): Promise<void> {
io,
});
});
const mcpUninstallCmd = mcpCmd
.command("uninstall")
.alias("remove")
.alias("rm")
.description("Uninstall an MCP server by name")
.argument("<name>", "MCP server name")
.option("--json", "Output as JSON")
.action(async (name: string) => {
const opts = mcpUninstallCmd.opts<{
json?: boolean;
}>();
const { runMcpUninstallCommand } = await import("./commands/mcp");
ctx.exitCode = await runMcpUninstallCommand({
name,
json: opts.json === true || program.opts().json === true,
io,
});
});
const createDoctorRuntimeCommand = async () => {
const { createDoctorCommand } = await import("./commands/doctor");
@@ -1011,7 +1030,9 @@ export async function runCli(): Promise<void> {
`${c.dim}[model-catalog] catalog resolution failed (${message})${c.reset}`,
);
}
const knownModelIds = knownModels ? Object.keys(knownModels) : [];
const knownModelIds = knownModels
? Object.keys(filterChatModels(knownModels))
: [];
const resolvedReasoning = resolveCliReasoning({
thinking: args.thinking,
thinkingExplicitlySet: args.thinkingExplicitlySet,
@@ -1012,7 +1012,9 @@ Review with the bundled skill.`,
const linear = data.mcp.find((item) => item.name === "linear");
const docs = data.mcp.find((item) => item.name === "docs");
expect(linear?.description).toBe("streamableHttp, oauth error, timeout 60s");
expect(linear?.description).toBe(
"streamableHttp, oauth error, timeout 60s",
);
expect(linear?.loadError).toBe("OAuth authorization failed");
expect(docs?.description).toBe("sse, oauth authorized, timeout 60s");
expect(docs?.loadError).toBeUndefined();
@@ -15,7 +15,7 @@ import {
type ToolApprovalResult,
type UserInstructionConfigService,
} from "@cline/core";
import type { Message } from "@cline/shared";
import type { MessageWithMetadata } from "@cline/shared";
import { createCliCore } from "../../session/session";
import { submitAndExitInTerminal } from "../../utils/approval";
import type {
@@ -56,11 +56,11 @@ type AskQuestionRef = {
current: ((question: string, options: string[]) => Promise<string>) | null;
};
type CurrentMessagesRead =
| { messages: Message[]; status: "read" }
| { messages: Message[]; status: "recovered" }
| { messages: Message[]; status: "stale" };
| { messages: MessageWithMetadata[]; status: "read" }
| { messages: MessageWithMetadata[]; status: "recovered" }
| { messages: MessageWithMetadata[]; status: "stale" };
type MissingSessionRecovery = {
messages: Message[];
messages: MessageWithMetadata[];
};
type ToolPolicyResolver = (
toolName: string,
@@ -210,7 +210,7 @@ export function createInteractiveSessionRuntime(input: {
};
const startFreshSession = async (
initial: Message[] = [],
initial: MessageWithMetadata[] = [],
sessionMetadata?: Record<string, unknown>,
initialCompactionState?: SessionCompactionState,
// Restarting an old session associate with this ID,
@@ -243,7 +243,7 @@ export function createInteractiveSessionRuntime(input: {
const startResumedSession = async (
resumeId: string,
initial: Message[] | undefined,
initial: MessageWithMetadata[] | undefined,
): Promise<void> => {
const generation = sessionStartGeneration;
const manager = await ensureSessionManager();
@@ -421,7 +421,7 @@ export function createInteractiveSessionRuntime(input: {
};
const restartWithMessages = async (
messages: Message[],
messages: MessageWithMetadata[],
sessionMetadata?: Record<string, unknown>,
initialCompactionState?: SessionCompactionState,
options?: { preserveSessionId?: boolean },
@@ -659,7 +659,9 @@ export function createInteractiveSessionRuntime(input: {
};
};
const resumeSession = async (sessionId: string): Promise<Message[]> => {
const resumeSession = async (
sessionId: string,
): Promise<MessageWithMetadata[]> => {
const manager = await ensureSessionManager();
const sessionRecord = await manager.get(sessionId);
if (!sessionRecord) {
@@ -754,7 +756,7 @@ export function createInteractiveSessionRuntime(input: {
const getCheckpointData = async (): Promise<
| {
messages: Message[];
messages: MessageWithMetadata[];
checkpointHistory: CheckpointEntry[];
}
| undefined
@@ -777,7 +779,9 @@ export function createInteractiveSessionRuntime(input: {
const restoreCheckpoint = async (
runCount: number,
restoreWorkspace: boolean,
): Promise<{ newSessionId: string; messages: Message[] } | undefined> => {
): Promise<
{ newSessionId: string; messages: MessageWithMetadata[] } | undefined
> => {
const manager = sessionManager;
if (!manager || !activeSessionId) {
return undefined;
+53 -4
View File
@@ -1,8 +1,17 @@
import { mkdtempSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { buildUserInputMessage } from "./prompt";
import { basename, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { buildUserInputMessage, resolveSystemPrompt } from "./prompt";
const workspaceDirectories: string[] = [];
afterEach(() => {
for (const directory of workspaceDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
describe("buildUserInputMessage", () => {
it("extracts image mentions into userImages", async () => {
@@ -43,3 +52,43 @@ describe("buildUserInputMessage", () => {
expect(result.userFiles).toEqual([filePath]);
});
});
describe("resolveSystemPrompt workspace metadata", () => {
it("includes git remotes and the latest commit for Cline requests", async () => {
const cwd = mkdtempSync(join(tmpdir(), "cline-prompt-"));
workspaceDirectories.push(cwd);
execFileSync("git", ["init"], { cwd });
execFileSync("git", ["config", "user.email", "test@cline.bot"], { cwd });
execFileSync("git", ["config", "user.name", "Cline Test"], { cwd });
writeFileSync(join(cwd, "README.md"), "test\n");
execFileSync("git", ["add", "README.md"], { cwd });
execFileSync("git", ["commit", "-m", "initial"], { cwd });
execFileSync(
"git",
["remote", "add", "origin", "https://example.com/cline/repo.git"],
{ cwd },
);
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd,
encoding: "utf8",
}).trim();
const prompt = await resolveSystemPrompt({ cwd, providerId: "cline" });
expect(prompt).toContain("origin: https://example.com/cline/repo.git");
expect(prompt).toContain(commit);
});
it("includes parseable metadata outside a project", async () => {
const cwd = mkdtempSync(join(tmpdir(), "cline-prompt-"));
workspaceDirectories.push(cwd);
const prompt = await resolveSystemPrompt({ cwd, providerId: "cline" });
expect(prompt).toContain("# Workspace Configuration");
expect(prompt).toContain(JSON.stringify(cwd));
expect(prompt).toContain(`"hint": "${basename(cwd)}"`);
expect(prompt).not.toContain("associatedRemoteUrls");
expect(prompt).not.toContain("latestGitCommitHash");
});
});
+26 -1
View File
@@ -3,7 +3,9 @@ import { homedir } from "node:os";
import { basename, resolve } from "node:path";
import {
buildWorkspaceMetadata,
isSkillsToolAvailable,
mergeRulesForSystemPrompt,
readGlobalSettings,
type UserInstructionConfigService,
} from "@cline/core";
import { type AgentMode, buildClineSystemPrompt } from "@cline/shared";
@@ -79,9 +81,30 @@ function resolveMentionPath(filePath: string): string {
return resolve(filePath);
}
/**
* Whether a typed `/skill` command must be textually expanded into the
* prompt. When the session registers the runtime's `skills` tool (its
* description requires the model to invoke it on slash-command references),
* the typed command passes through and the instructions arrive as a tool
* result keeping the persisted transcript as what the user typed. When the
* tool is unavailable (yolo preset, user toggle), expansion is the only
* delivery path.
*/
export function shouldExpandSkillSlashCommands(mode?: string): boolean {
try {
return !isSkillsToolAvailable({
mode: mode === "plan" || mode === "yolo" ? mode : "act",
disabledToolIds: new Set(readGlobalSettings().disabledTools ?? []),
});
} catch {
return true;
}
}
export async function buildUserInputMessage(
rawPrompt: string,
userInstructionService?: UserInstructionConfigService,
options?: { mode?: string },
): Promise<{
prompt: string;
userImages: string[];
@@ -90,7 +113,9 @@ export async function buildUserInputMessage(
// First, resolve slash commands if the core config service is available.
let prompt = rawPrompt;
if (userInstructionService) {
prompt = userInstructionService.resolveRuntimeSlashCommand(rawPrompt);
prompt = userInstructionService.resolveRuntimeSlashCommand(rawPrompt, {
expandSkillCommands: shouldExpandSkillSlashCommands(options?.mode),
});
}
if (!hasFileMentions(prompt)) {
+3 -1
View File
@@ -277,7 +277,9 @@ export async function runAgent(
prompt: userInput,
userImages,
userFiles,
} = await buildUserInputMessage(prompt, userInstructionService);
} = await buildUserInputMessage(prompt, userInstructionService, {
mode: config.mode,
});
const started = await sessionManager.start({
source: SessionSource.CLI,
config: {
@@ -81,6 +81,7 @@ describe("applyInteractiveModelChange", () => {
const saveProviderSettings = vi.fn(() => ({
version: 1 as const,
providers: {},
modes: {},
}));
const ensureReady = vi.fn(async () => {});
const restartWithCurrentMessages = vi.fn(async () => {});
+23 -1
View File
@@ -490,6 +490,7 @@ export async function runInteractive(
tuiApp?.destroy();
});
let startupErrorReported = false;
let updateCliAfterExit = false;
const loadDeferredInitialMessages = resumeSessionId?.trim()
? async () => {
try {
@@ -620,7 +621,9 @@ export async function runInteractive(
prompt: userInput,
userImages,
userFiles,
} = await buildUserInputMessage(input, userInstructionService);
} = await buildUserInputMessage(input, userInstructionService, {
mode,
});
const mergedUserImages = [
...(attachments?.userImages ?? []),
...userImages,
@@ -749,6 +752,10 @@ export async function runInteractive(
onExit: () => {
tuiApp?.destroy();
},
onHubUpdateRestart: () => {
updateCliAfterExit = true;
tuiApp?.destroy();
},
onRunningChange: (running) => {
isRunning = running;
if (!running) {
@@ -877,4 +884,19 @@ export async function runInteractive(
prepareTerminalForPostTuiOutput();
writeln(formatInteractiveExitSummary(exitSummary));
}
if (updateCliAfterExit) {
if (!exitSummary) {
prepareTerminalForPostTuiOutput();
}
writeln(
"The shared Cline Hub was updated by another Cline installation. Updating this CLI…",
);
const { checkForUpdates } = await import("../commands/update");
const exitCode = await checkForUpdates({ includeKanban: false });
writeln(
exitCode === 0
? "Start cline again to reconnect to the updated Hub."
: "Update did not complete. Run 'cline update' manually, then start cline again.",
);
}
}
+5 -1
View File
@@ -78,7 +78,11 @@ export async function runZen(
prompt: userInput,
userImages,
userFiles,
} = await buildUserInputMessage(prompt, userInstructionService);
} = await buildUserInputMessage(prompt, userInstructionService, {
// Zen runs in yolo mode, whose preset has no skills tool — skill
// commands must keep expanding textually.
mode: "yolo",
});
const startRequest: ChatStartSessionRequest = {
workspaceRoot,
+8
View File
@@ -2,6 +2,7 @@ import {
type BuiltinToolAvailabilityContext,
getCoreBuiltinToolCatalog,
resolveDisabledToolNames,
resolveModelToolSettings,
type ToolCatalogEntry,
} from "@cline/core";
@@ -10,8 +11,15 @@ export type { ToolCatalogEntry } from "@cline/core";
export function getToolCatalog(
availabilityContext?: BuiltinToolAvailabilityContext,
): ToolCatalogEntry[] {
const modelToolSettings = resolveModelToolSettings();
return getCoreBuiltinToolCatalog({
clientType: "cli",
disabledToolIds: resolveDisabledToolNames(),
enabledModelToolIds: new Set(
Object.entries(modelToolSettings)
.filter(([, setting]) => setting?.enabled === true)
.map(([name]) => name),
),
...availabilityContext,
});
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { generateConversationHTML } from "./export";
describe("generateConversationHTML", () => {
it("renders provider model activity with the ordinary tool HTML", () => {
const html = generateConversationHTML(
{
version: 1,
updated_at: "2026-08-13T00:00:00.000Z",
messages: [
{
id: "assistant-search",
role: "assistant",
content: "Bun 1.3.14 is current.",
metadata: {
modelToolActivities: [
{
toolCallId: "search-1",
toolName: "web_search",
execution: "provider",
input: { query: "latest Bun release" },
output: "Bun 1.3.14",
},
],
},
},
],
},
"session",
);
expect(html).toContain("web_search");
expect(html).toContain("latest Bun release");
expect(html).toContain('<span class="success">Success</span>');
expect(html).toContain("Bun 1.3.14 is current.");
});
});
+45 -2
View File
@@ -1,3 +1,4 @@
import { projectSessionMessagesForDisplay } from "@cline/core";
import {
type ContentBlock,
formatDisplayUserInput,
@@ -30,9 +31,12 @@ export function generateConversationHTML(
data: ConversationHistory,
fileName: string,
): string {
const displayMessages = projectSessionMessagesForDisplay(data.messages).map(
({ message }) => message,
);
// Build tool results map
const toolResultsMap = new Map<string, ToolResultContent>();
data.messages.forEach((msg) => {
displayMessages.forEach((msg) => {
if (!isStringContent(msg.content)) {
msg.content.forEach((block) => {
if (block.type === "tool_result") {
@@ -43,7 +47,7 @@ export function generateConversationHTML(
});
// Filter messages (same logic as viewer)
const filteredMessages = data.messages.filter((msg) => {
const filteredMessages = displayMessages.filter((msg) => {
if (msg.role === "assistant") return true;
if (isStringContent(msg.content)) {
return msg.content.trim().length > 0;
@@ -696,6 +700,14 @@ function renderContentHTML(
return renderToolUseHTML(block, toolResultsMap.get(block.id));
case "tool_result":
return ""; // Tool results are rendered with their corresponding tool_use
case "image":
return renderGeneratedMediaHTML({
modality: "image",
mediaType: block.mediaType,
source: { type: "base64", data: block.data },
});
case "media":
return renderGeneratedMediaHTML(block.media);
default:
return "";
}
@@ -703,6 +715,37 @@ function renderContentHTML(
.join("\n");
}
function renderGeneratedMediaHTML(media: {
modality: "image" | "audio" | "video" | "file";
mediaType: string;
source:
| { type: "base64"; data: string }
| { type: "url"; url: string }
| { type: "artifact"; artifactId: string };
}): string {
const source =
media.source.type === "base64"
? `data:${media.mediaType};base64,${media.source.data}`
: media.source.type === "url"
? media.source.url
: undefined;
if (!source) {
return `<p class="generated-media">Generated ${escapeHtml(media.modality)} (${escapeHtml(media.mediaType)})</p>`;
}
const escapedSource = escapeHtml(source);
const escapedType = escapeHtml(media.mediaType);
switch (media.modality) {
case "image":
return `<img class="generated-media" src="${escapedSource}" alt="Generated image" />`;
case "audio":
return `<audio class="generated-media" controls src="${escapedSource}" type="${escapedType}"></audio>`;
case "video":
return `<video class="generated-media" controls src="${escapedSource}" type="${escapedType}"></video>`;
case "file":
return `<a class="generated-media" href="${escapedSource}" download>Generated file (${escapedType})</a>`;
}
}
function renderTextHTML(text: string): string {
// Simple markdown-like rendering
let html = escapeHtml(text);
@@ -1,89 +0,0 @@
// ---------------------------------------------------------------------------
// Page-object helpers for the /settings view.
// ---------------------------------------------------------------------------
import type { Terminal } from "@microsoft/tui-test/lib/terminal/term";
import { expectVisible } from "../terminal.js";
const TAB_ORDER = [
"API",
"Auto-approve",
"Features",
"Account",
"Other",
] as const;
export type SettingsTab = (typeof TAB_ORDER)[number];
/**
* Navigate to a specific settings tab by pressing Right from the API tab (index 0).
* Waits for each tab's content to appear before pressing the next key, making
* navigation deterministic regardless of machine speed.
*/
export async function goToSettingsTab(
terminal: Terminal,
tab: SettingsTab,
): Promise<void> {
const targetIndex = TAB_ORDER.indexOf(tab);
for (let i = 0; i < targetIndex; i++) {
terminal.keyRight();
// Wait for the next tab's content to appear before pressing again
await assertTabContent(terminal, TAB_ORDER[i + 1]);
}
}
/** Assert the API tab content is visible */
export async function assertApiTab(terminal: Terminal): Promise<void> {
await expectVisible(terminal, ["Provider:", "Model ID:"]);
}
/** Assert the Auto-approve tab content is visible */
export async function assertAutoApproveTab(terminal: Terminal): Promise<void> {
await expectVisible(terminal, [
"Read project files",
"Execute safe commands",
"Edit project files",
]);
}
/** Assert the Features tab content is visible */
export async function assertFeaturesTab(terminal: Terminal): Promise<void> {
await expectVisible(terminal, [
"Subagents",
"Web tools",
"Double-check completion",
]);
}
/** Assert the Account tab content is visible */
export async function assertAccountTab(terminal: Terminal): Promise<void> {
// The account tab shows sign-in options when not authenticated to Cline
await expectVisible(terminal, /sign in|sign out/i);
}
/** Assert the Other tab content is visible */
export async function assertOtherTab(terminal: Terminal): Promise<void> {
await expectVisible(terminal, ["Preferred language:", "Cline v"]);
}
/**
* Assert the content for a given tab is visible.
* Used internally by goToSettingsTab to confirm navigation landed correctly.
*/
export async function assertTabContent(
terminal: Terminal,
tab: SettingsTab,
): Promise<void> {
switch (tab) {
case "API":
return assertApiTab(terminal);
case "Auto-approve":
return assertAutoApproveTab(terminal);
case "Features":
return assertFeaturesTab(terminal);
case "Account":
return assertAccountTab(terminal);
case "Other":
return assertOtherTab(terminal);
}
}
+2 -2
View File
@@ -2,10 +2,9 @@ import {
type ClineAccountBalance,
type ClineAccountOrganization,
type ClineAccountOrganizationBalance,
type ClineSubscriptionPlan,
type UserCurrentPlan,
ClineAccountService,
type ClineAccountUser,
type ClineSubscriptionPlan,
formatProviderOAuthApiKey,
getPersistedProviderApiKey,
getProviderOAuthCredentialsFromSettings,
@@ -13,6 +12,7 @@ import {
type ProviderSettings,
ProviderSettingsManager,
saveLocalProviderOAuthCredentials,
type UserCurrentPlan,
} from "@cline/core";
import { getClineEnvironmentConfig } from "@cline/shared";
import { formatCreditBalance, normalizeCreditBalance } from "../utils/output";
@@ -169,6 +169,39 @@ describe("slash command registry", () => {
expect(expandUserCommandPrompt("/settings", registry)).toBe("/settings");
});
it("keeps skill commands typed when skill expansion is off, but still wraps workflows", () => {
const registry = buildSlashCommandRegistry({
workflowSlashCommands: [
{
name: "review",
instructions: "Review carefully",
description: "Review files",
kind: "skill",
},
{
name: "release",
instructions: "Run the release workflow",
description: "Release",
kind: "workflow",
},
],
});
const options = { expandSkillCommands: false };
// The skills tool delivers the instructions; the transcript keeps the
// typed command.
expect(
expandUserCommandPrompt("/review this file", registry, options),
).toBe("/review this file");
expect(
expandUserCommandPrompt("please /review this file", registry, options),
).toBe("please /review this file");
// Workflows are not served by the skills tool and keep expanding.
expect(expandUserCommandPrompt("/release now", registry, options)).toBe(
'<user_command slash="release">Run the release workflow</user_command> now',
);
});
it("does not expand commands omitted from a refreshed user-command registry", () => {
const staleRegistry = buildSlashCommandRegistry({
workflowSlashCommands: [
@@ -245,19 +245,33 @@ export function formatSlashCommandAutocompleteValue(
return `/${entry.name} `;
}
export interface ExpandUserCommandPromptOptions {
/**
* Whether matched skill commands are wrapped into the prompt. Pass false
* when the session registers the runtime's skills tool: the typed
* `/skill args` then goes through as-is and the model loads the
* instructions via the tool. Workflows always expand (the tool does not
* serve them). Defaults to true.
*/
expandSkillCommands?: boolean;
}
export function expandUserCommandPrompt(
input: string,
registry: SlashCommandRegistry,
options?: ExpandUserCommandPromptOptions,
): string {
if (input.includes("<user_command")) {
return input;
}
const skipCommand = (command: SlashCommandRegistryEntry): boolean =>
command.kind === "skill" && options?.expandSkillCommands === false;
const expandedSlashCommands = input.replace(
USER_COMMAND_SLASH_PATTERN,
(match, prefix: string, name: string) => {
const command = resolveSlashCommand(registry, name);
if (command?.execution !== "user-command") {
if (command?.execution !== "user-command" || skipCommand(command)) {
return match;
}
return `${prefix}${formatUserCommandBlock(command.instructions, command.name)}`;
@@ -272,7 +286,11 @@ export function expandUserCommandPrompt(
return input;
}
const command = resolveSlashCommand(registry, match[1] ?? "");
if (!command || command.execution !== "user-command") {
if (
!command ||
command.execution !== "user-command" ||
skipCommand(command)
) {
return input;
}
const rest = (match[2] ?? "").trim();
+42 -1
View File
@@ -45,6 +45,13 @@ function trimLeading(text: string): string {
return text.replace(/^\n+/, "");
}
function formatMediaSize(byteLength: number): string {
if (byteLength <= 0) return "unknown size";
if (byteLength < 1024) return `${byteLength} B`;
if (byteLength < 1024 * 1024) return `${(byteLength / 1024).toFixed(1)} KiB`;
return `${(byteLength / (1024 * 1024)).toFixed(1)} MiB`;
}
function ReasoningBlock(props: { text: string; streaming: boolean }) {
const [expanded, setExpanded] = useState(false);
const { width } = useTerminalDimensions();
@@ -640,10 +647,30 @@ export function ChatEntryView(props: {
)}
</box>
<box flexGrow={1}>
{/*
* internalBlockMode="top-level" keeps each markdown block as its
* own renderable. The default coalesced mode merges the whole
* message into one block that is torn down and re-highlighted on
* every streamed chunk, which flashes already-rendered headings
* and links back to raw uncolored markdown while tree-sitter
* re-highlights asynchronously. Top-level blocks are reused by
* token identity, so settled content never re-renders.
* tableOptions preserves the bordered table style that coalesced
* mode used by default (top-level defaults to borderless columns).
*
* streaming stays true even after the entry settles: flipping the
* prop makes MarkdownRenderable rebuild every block from scratch
* (updateBlocks(true) skips all reuse paths), so the finished
* message flashes back to unhighlighted text while tree-sitter
* re-highlights. opencode's TUI keeps streaming={true} for the
* same reason. entry.streaming still drives the spinner glyph.
*/}
<markdown
content={content}
syntaxStyle={getSyntaxStyle(theme, mode)}
streaming={entry.streaming}
streaming={true}
internalBlockMode="top-level"
tableOptions={{ style: "grid" }}
fg={defaultFg}
/>
</box>
@@ -651,6 +678,20 @@ export function ChatEntryView(props: {
);
}
case "assistant_media":
return (
<box flexDirection="row">
<box width={2}>
<text fg={accent}>*</text>
</box>
<text fg={defaultFg} selectable>
{entry.location
? `Generated ${entry.modality} (${entry.mediaType}, ${formatMediaSize(entry.byteLength)}): ${entry.location}`
: `Generated ${entry.modality} (${entry.mediaType}) could not be saved`}
</text>
</box>
);
case "reasoning":
return <ReasoningBlock text={entry.text} streaming={entry.streaming} />;
@@ -0,0 +1,44 @@
import { useRenderer } from "@opentui/react";
import { DialogContainerRenderable } from "@opentui-ui/dialog";
import { useDialogState } from "@opentui-ui/dialog/react";
import { useEffect } from "react";
import { useTheme } from "../hooks/use-theme";
import { getDialogSurface } from "../themes";
/**
* Keeps dialog panel backgrounds in sync with the active theme.
*
* The dialog library computes a panel's style once when the dialog opens
* (from the container's dialogOptions), so theme changes made while a dialog
* is open most visibly the live preview while scrolling the theme picker
* would leave the panel on the old surface color. This component pushes the
* theme's dialog surface into the container (for dialogs opened later) and
* onto every open dialog renderable (repainting them in place).
*
* Must be mounted inside the DialogProvider. Re-runs when a dialog opens so
* the first dialog after mount is covered too (the container is only added
* to the renderer root after this component's initial effect).
*/
export function DialogThemeSync() {
const renderer = useRenderer();
const theme = useTheme();
const dialogCount = useDialogState((state: { count: number }) => state.count);
const surface = getDialogSurface(theme);
// biome-ignore lint/correctness/useExhaustiveDependencies: dialogCount re-runs the sync when a dialog opens, covering dialogs opened before the container-level option applied (see docblock).
useEffect(() => {
const container = renderer.root
.getChildren()
.find(
(child): child is DialogContainerRenderable =>
child instanceof DialogContainerRenderable,
);
if (!container) return;
container.dialogOptions = { style: { backgroundColor: surface } };
for (const [, dialogRenderable] of container.getDialogRenderables()) {
dialogRenderable.backgroundColor = surface;
}
}, [renderer, surface, dialogCount]);
return null;
}
@@ -8,7 +8,7 @@ import {
formatClineCredits,
isClineAccountAuthErrorMessage,
} from "../../cline-account";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export type AccountDialogAction =
| "change-model"
@@ -121,6 +121,7 @@ function AccountActionRow(props: {
selected: boolean;
onSelect: () => void;
}) {
const palette = useDialogPalette();
const fg = props.selected ? palette.textOnSelection : undefined;
return (
<box
@@ -138,7 +139,7 @@ function AccountActionRow(props: {
fg={props.selected ? palette.textOnSelection : "gray"}
flexShrink={0}
>
{props.selected ? ">" : " "}
{props.selected ? "" : " "}
</text>
<text fg={fg} flexShrink={0}>
{props.action.label}
@@ -161,6 +162,7 @@ function OrganizationRow(props: {
selected: boolean;
onSelect: () => void;
}) {
const palette = useDialogPalette();
return (
<box
flexDirection="row"
@@ -177,7 +179,7 @@ function OrganizationRow(props: {
fg={props.selected ? palette.textOnSelection : "gray"}
flexShrink={0}
>
{props.selected ? ">" : " "}
{props.selected ? "" : " "}
</text>
<text
fg={props.selected ? palette.textOnSelection : undefined}
@@ -234,6 +236,7 @@ export function AccountDialogContent(
switchAccount,
onAccountChange,
} = props;
const palette = useDialogPalette();
const [state, setState] = useState<AccountState>({
status: "loading",
message: "Loading account details...",
@@ -2,7 +2,7 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useRef, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export function AskQuestionContent(
props: ChoiceContext<string | null> & {
@@ -11,6 +11,7 @@ export function AskQuestionContent(
},
) {
const { resolve, dialogId, question, options } = props;
const palette = useDialogPalette();
const [selected, setSelected] = useState(0);
const [inputKey, setInputKey] = useState(0);
const customRef = useRef("");
@@ -2,7 +2,7 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useRef, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export type CheckpointRestoreMode = "chat-only" | "chat-and-workspace";
@@ -29,6 +29,7 @@ export function CheckpointConfirmContent(
},
) {
const { resolve, dismiss, dialogId, messagePreview } = props;
const palette = useDialogPalette();
const [selected, setSelected] = useState(0);
const selectedRef = useRef(0);
const selectedMode = OPTIONS[selected]?.value;
@@ -2,7 +2,7 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useMemo, useRef, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export interface CheckpointPickerItem {
runCount: number;
@@ -36,6 +36,7 @@ export function CheckpointPickerContent(
},
) {
const { resolve, dismiss, dialogId, items } = props;
const palette = useDialogPalette();
const lastIndex = Math.max(0, items.length - 1);
const [selected, setSelected] = useState(lastIndex);
const selectedRef = useRef(lastIndex);
@@ -3,7 +3,7 @@ import { useTerminalDimensions } from "@opentui/react";
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useMemo, useRef, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import {
buildCommandPaletteItems,
type CommandPaletteResult,
@@ -32,6 +32,7 @@ export function CommandPaletteContent(
},
) {
const { resolve, dismiss, dialogId, canForkSession, contentWidth } = props;
const palette = useDialogPalette();
const { height } = useTerminalDimensions();
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(0);
@@ -1,12 +1,12 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useState } from "react";
import { useDialogPalette } from "../../hooks/use-theme";
import type {
InteractiveConfigData,
InteractiveConfigItem,
LoadInteractiveConfigDataOptions,
} from "../../interactive-config";
import { palette } from "../../palette";
import {
getExtDetailFooterText,
getExtDetailRows,
@@ -23,6 +23,7 @@ export function ExtDetailContent(
) => Promise<InteractiveConfigData | undefined>;
},
) {
const palette = useDialogPalette();
const [item, setItem] = useState(props.item);
const [toggleError, setToggleError] = useState<string | undefined>();
@@ -1,7 +1,7 @@
// @jsxImportSource @opentui/react
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
type HelpRow =
| { kind: "heading"; id: string; text: string }
@@ -255,6 +255,7 @@ const KEY_WIDTH = 20;
export function HelpDialogContent(props: ChoiceContext<void>) {
const { dismiss, dialogId } = props;
const palette = useDialogPalette();
useDialogKeyboard((key) => {
if (
@@ -0,0 +1,27 @@
import type { Config } from "../../../utils/types";
import type { DialogDismissKey } from "../../utils/dialog-keys";
/**
* Enter starts the update-and-restart flow; Esc dismisses (the mismatch toast
* reminds the user to update manually). Other keys are ignored so the dialog
* is not lost to a stray keystroke mid-task.
*/
export function resolveHubUpdateRequiredKeyAction(
key: DialogDismissKey,
): "update" | "dismiss" | "ignore" {
if (key.name === "return" || key.name === "enter") return "update";
if (key.name === "escape") return "dismiss";
return "ignore";
}
/**
* Yolo and sandbox sessions force the local backend and never attach to the
* shared managed Hub (see the forceLocalBackend condition in the interactive
* session runtime), so a build mismatch on that Hub is another installation's
* concern and must not interrupt these sessions with an update dialog.
*/
export function shouldWatchManagedHubBuild(
config: Pick<Config, "mode" | "sandbox">,
): boolean {
return config.mode !== "yolo" && config.sandbox !== true;
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import {
resolveHubUpdateRequiredKeyAction,
shouldWatchManagedHubBuild,
} from "./hub-update-required-helpers";
describe("hub update required dialog", () => {
it("updates on Enter", () => {
expect(resolveHubUpdateRequiredKeyAction({ name: "return" })).toBe(
"update",
);
expect(resolveHubUpdateRequiredKeyAction({ name: "enter" })).toBe("update");
});
it("dismisses only on Esc", () => {
expect(resolveHubUpdateRequiredKeyAction({ name: "escape" })).toBe(
"dismiss",
);
});
it("ignores stray keystrokes so a mid-task keypress cannot lose the prompt", () => {
expect(resolveHubUpdateRequiredKeyAction({ name: "a" })).toBe("ignore");
expect(resolveHubUpdateRequiredKeyAction({ name: "space" })).toBe("ignore");
expect(resolveHubUpdateRequiredKeyAction({ name: "c", ctrl: true })).toBe(
"ignore",
);
});
});
describe("shouldWatchManagedHubBuild", () => {
it("watches for hub-attached modes", () => {
expect(shouldWatchManagedHubBuild({ mode: "act", sandbox: false })).toBe(
true,
);
expect(shouldWatchManagedHubBuild({ mode: "plan", sandbox: false })).toBe(
true,
);
});
it("skips yolo and sandbox sessions, which force the local backend and never attach to the managed Hub", () => {
expect(shouldWatchManagedHubBuild({ mode: "yolo", sandbox: false })).toBe(
false,
);
expect(shouldWatchManagedHubBuild({ mode: "act", sandbox: true })).toBe(
false,
);
});
});
@@ -0,0 +1,51 @@
// @jsxImportSource @opentui/react
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useDialogPalette } from "../../hooks/use-theme";
import { resolveHubUpdateRequiredKeyAction } from "./hub-update-required-helpers";
export interface HubUpdateRequiredDetails {
hubCoreVersion?: string;
}
export function HubUpdateRequiredContent(
props: ChoiceContext<boolean> & HubUpdateRequiredDetails,
) {
const { dialogId, dismiss, hubCoreVersion, resolve } = props;
const palette = useDialogPalette();
useDialogKeyboard((key) => {
const action = resolveHubUpdateRequiredKeyAction(key);
if (action === "ignore") return;
if (action === "update") {
resolve(true);
return;
}
dismiss();
}, dialogId);
return (
<box flexDirection="column" paddingX={1} gap={1}>
<text fg="yellow">Cline Hub was updated</text>
<box flexDirection="column">
<text selectable>
Another Cline installation restarted the shared Cline Hub
{hubCoreVersion ? ` (core ${hubCoreVersion})` : ""}, and it no longer
matches this CLI.
</text>
<text selectable>
Update and restart Cline so this CLI and the Hub run the same version
again.
</text>
</box>
<box flexDirection="row">
<box paddingX={1} backgroundColor={palette.act}>
<text fg={palette.textOnSelection}>Update and restart</text>
</box>
</box>
<text fg={palette.muted}>
Press Enter to update and restart, Esc to dismiss
</text>
</box>
);
}
@@ -5,7 +5,7 @@ import {
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export interface McpEntry {
name: string;
@@ -70,6 +70,7 @@ export function McpManagerContent(
servers: McpEntry[];
},
) {
const palette = useDialogPalette();
const [selected, setSelected] = useState(0);
const [servers, setServers] = useState(props.servers);
const [changed, setChanged] = useState(false);
@@ -3,7 +3,6 @@ import {
type ProviderSettingsManager,
saveLocalProviderSettings,
} from "@cline/core";
import { CLI_PROMO_CODE } from "../../../utils/cline-pass-errors";
import {
type DialogDismissKey,
isAnyKeyDismiss,
@@ -77,8 +76,5 @@ export function buildClinePassSubscriptionPageUrl(
appBaseUrl || DEFAULT_APP_BASE_URL,
);
url.searchParams.set("personal", "true");
if (CLI_PROMO_CODE) {
url.searchParams.set("code", CLI_PROMO_CODE);
}
return url.toString();
}
@@ -22,7 +22,7 @@ import {
} from "../../../utils/codex-cli";
import open from "../../../utils/open";
import { listLocalProviders } from "../../../utils/provider-catalog";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import {
getDefaultAwsRegion,
type ProviderConfigValues,
@@ -63,6 +63,7 @@ export function ProviderPickerContent(
props: ChoiceContext<string> & { currentProviderId: string },
) {
const { resolve, dismiss, dialogId, currentProviderId } = props;
const palette = useDialogPalette();
const [providers, setProviders] = useState<ProviderItem[]>([]);
const [search, setSearch] = useState("");
const [selected, setSelected] = useState(0);
@@ -272,6 +273,7 @@ export function UseExistingOrReconfigureContent(
},
) {
const { resolve, dismiss, dialogId, providerName, extraOptions } = props;
const palette = useDialogPalette();
const options: ExistingProviderOption[] = useMemo(
() => [
{ value: "use_existing", label: "Use existing configuration" },
@@ -351,6 +353,7 @@ function ClinePassBrowserPageContent(
url,
openedStatus,
} = props;
const palette = useDialogPalette();
const [status, setStatus] = useState("Opening browser...");
useEffect(() => {
@@ -489,6 +492,7 @@ export function ProviderConfigInputContent(
providerName,
providerSettingsManager,
} = props;
const palette = useDialogPalette();
const config = useMemo(
() => getProviderConfigFields(providerId),
@@ -656,6 +660,7 @@ export function CodexCliStatusContent(
},
) {
const { resolve, dismiss, dialogId, providerName } = props;
const palette = useDialogPalette();
const [status, setStatus] = useState<CodexCliStatus | undefined>();
const [checking, setChecking] = useState(false);
@@ -749,6 +754,7 @@ export function OAuthLoginContent(
providerName,
allowApiKeyFallback,
} = props;
const palette = useDialogPalette();
const [mode, setMode] = useState<"browser" | "device">(
providerId === "cline" ? "device" : "browser",
);
@@ -969,6 +975,7 @@ export function OAuthApiKeyInputContent(
providerName,
providerSettingsManager,
} = props;
const palette = useDialogPalette();
const [value, setValue] = useState("");
const submit = () => {
@@ -3,7 +3,7 @@ import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useMemo, useRef, useState } from "react";
import type { SlashCommandRegistryEntry } from "../../commands/slash-command-registry";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export const SKILLS_MARKETPLACE_ACTION = "__skills_marketplace__";
export const SKILLS_MARKETPLACE_URL = "https://skills.sh/";
@@ -26,6 +26,7 @@ function matchesFilter(
export function SkillsPickerContent(props: SkillsPickerContentProps) {
const { resolve, dismiss, dialogId, commands } = props;
const palette = useDialogPalette();
const { height, width } = useTerminalDimensions();
const [filter, setFilter] = useState("");
const [selected, setSelected] = useState(0);
@@ -2,8 +2,7 @@ import { useTerminalDimensions } from "@opentui/react";
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useEffect, useRef, useState } from "react";
import { useThemeController } from "../../hooks/use-theme";
import { palette } from "../../palette";
import { useDialogPalette, useThemeController } from "../../hooks/use-theme";
import { getThemeSwatchColors, THEMES } from "../../themes";
const SWATCH_BLOCK = "\u25a0";
@@ -12,6 +11,7 @@ export function ThemePickerContent(props: ChoiceContext<string>) {
const { resolve, dismiss, dialogId } = props;
const { height } = useTerminalDimensions();
const controller = useThemeController();
const palette = useDialogPalette();
const [selected, setSelected] = useState(() => {
const index = THEMES.findIndex(
(theme) => theme.id === controller.selectedThemeId,
@@ -2,7 +2,7 @@ import type { ToolApprovalRequest } from "@cline/shared";
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import type React from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import {
buildReadFilesKeys,
parseApplyPatchInput,
@@ -139,6 +139,7 @@ export function formatApprovalParams(
export function ToolApprovalContent(
props: ChoiceContext<boolean> & { request: ToolApprovalRequest },
) {
const palette = useDialogPalette();
useDialogKeyboard((key) => {
if (key.name === "y" || key.name === "return") {
props.resolve(true);
@@ -7,7 +7,8 @@ import {
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import "opentui-spinner/react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import type { DialogPalette } from "../../themes";
import {
CLINE_MODEL_PICKER_TIER_LABELS,
type ClineModelPickerEntry,
@@ -24,7 +25,7 @@ export {
freeTierDescriptionFor,
} from "./cline-model-entries";
function tagColor(tag: string): string {
function tagColor(tag: string, palette: DialogPalette): string {
if (tag === "FREE") return palette.success;
if (tag === "BEST") return "magenta";
return palette.act;
@@ -58,6 +59,7 @@ export function ClineModelPicker(props: {
currentModelId?: string;
}) {
const { entries, selected, loading, currentModelId } = props;
const palette = useDialogPalette();
if (loading) {
return (
@@ -119,7 +121,7 @@ export function ClineModelPicker(props: {
{tags.map((t) => (
<text
key={t}
fg={isSel ? palette.textOnSelection : tagColor(t)}
fg={isSel ? palette.textOnSelection : tagColor(t, palette)}
flexShrink={0}
>
{t}
@@ -2,7 +2,8 @@
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import type { DialogPalette } from "../../themes";
import {
CLINE_MODEL_PICKER_TIER_LABELS,
type ClineModelPickerEntry,
@@ -18,7 +19,7 @@ type ClineModelEntriesState =
| { status: "loaded"; entries: ClineModelPickerEntry[] }
| { status: "error"; message: string };
function tagColor(tag: string): string {
function tagColor(tag: string, palette: DialogPalette): string {
if (tag === "FREE") return palette.success;
if (tag === "BEST") return "magenta";
return palette.act;
@@ -39,6 +40,7 @@ export function ClineModelSelectorContent(
currentProviderName,
entries,
} = props;
const palette = useDialogPalette();
const [selected, setSelected] = useState(0);
const [onProvider, setOnProvider] = useState(false);
@@ -188,7 +190,7 @@ export function ClineModelSelectorContent(
{row.tags.map((t) => (
<text
key={t}
fg={isSel ? palette.textOnSelection : tagColor(t)}
fg={isSel ? palette.textOnSelection : tagColor(t, palette)}
flexShrink={0}
>
{t}
@@ -222,6 +224,7 @@ export function ClineModelSelectorDialogContent(
},
) {
const { dismiss, dialogId, loadEntries } = props;
const palette = useDialogPalette();
const [state, setState] = useState<ClineModelEntriesState>({
status: "loading",
message: "Loading Cline models...",
@@ -3,7 +3,7 @@ import type { Llms } from "@cline/core";
import type { ChoiceContext } from "@opentui-ui/dialog";
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
import { useMemo, useState } from "react";
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
import { ProviderRow } from "./provider-row";
export interface ModelOption {
@@ -65,6 +65,7 @@ export function ModelIdInputContent(
) {
const { resolve, dismiss, dialogId, currentModel, currentProviderName } =
props;
const palette = useDialogPalette();
const [modelId, setModelId] = useState(currentModel);
const [error, setError] = useState("");
const [onProvider, setOnProvider] = useState(false);
@@ -328,6 +329,7 @@ export function ThinkingLevelContent(
},
) {
const { resolve, dismiss, dialogId, modelName, currentLevel } = props;
const palette = useDialogPalette();
const [selected, setSelected] = useState(() => {
const initialLevel = currentLevel === "none" ? "medium" : currentLevel;
const idx = THINKING_LEVELS.findIndex((l) => l.value === initialLevel);
@@ -516,6 +518,7 @@ function CreateCustomModelRow(props: {
onSelect: () => void;
}) {
const { isSelected, dimmed, onSelect } = props;
const palette = useDialogPalette();
const active = isSelected && !dimmed;
const bg = active
? palette.selection
@@ -553,6 +556,7 @@ function ModelRow(props: {
onSelect: (key: string) => void;
}) {
const { model, isSelected, dimmed, isCurrent, onSelect } = props;
const palette = useDialogPalette();
const active = isSelected && !dimmed;
const bg = active
? palette.selection
@@ -1,5 +1,5 @@
// @jsxImportSource @opentui/react
import { palette } from "../../palette";
import { useDialogPalette } from "../../hooks/use-theme";
export function ProviderRow({
providerName,
@@ -8,6 +8,7 @@ export function ProviderRow({
providerName: string;
focused: boolean;
}) {
const palette = useDialogPalette();
return (
<box flexDirection="row" paddingX={1} gap={1}>
<text fg={focused ? palette.selection : "gray"} flexShrink={0}>
@@ -117,7 +117,10 @@ function QueuedPromptRow(props: {
flexGrow={1}
/>
) : (
<text fg={selected ? theme.textOnSelection : undefined} flexGrow={1}>
<text
fg={selected ? theme.textOnSelection : theme.defaultForeground}
flexGrow={1}
>
{truncatePrompt(item.prompt)}
</text>
)}
@@ -7,6 +7,7 @@ import type {
} from "../../runtime/session-events";
import { formatCliErrorMessage } from "../../utils/cline-pass-errors";
import { resolveNonCompactionStatusLabel } from "../../utils/events";
import { materializeGeneratedMedia } from "../../utils/generated-media";
import {
formatToolInput,
formatToolOutput,
@@ -205,6 +206,26 @@ export function useAgentEventHandlers(deps: AgentEventDeps) {
closeToolEntry(event);
break;
}
case "media": {
closeInlineStream();
const media = event.media;
if (!media) break;
const saved = materializeGeneratedMedia(media);
appendEntry({
kind: "assistant_media",
modality: media.modality,
mediaType: media.mediaType,
byteLength: saved?.byteLength ?? media.sizeBytes ?? 0,
location:
saved?.path ??
(media.source.type === "url"
? media.source.url
: media.source.type === "artifact"
? `artifact:${media.source.artifactId}`
: undefined),
});
break;
}
}
break;
}
@@ -1,4 +1,5 @@
import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { shouldExpandSkillSlashCommands } from "../../runtime/prompt";
import { formatCliErrorMessage } from "../../utils/cline-pass-errors";
import { shouldShowCliUsageCost } from "../../utils/usage-cost-display";
import type { SlashCommandRegistry } from "../commands/slash-command-registry";
@@ -308,6 +309,12 @@ export function usePromptInputController(input: {
const promptForSubmit = expandUserCommandPrompt(
expandedPrompt,
slashCommandRegistry,
// Skills load through the runtime's skills tool when it is
// available for the current mode; the typed command then goes
// through as-is so the transcript keeps what the user typed.
{
expandSkillCommands: shouldExpandSkillSlashCommands(session.uiMode),
},
);
session.setHasSubmitted(true);
@@ -1,5 +1,9 @@
import type { AgentMode } from "@cline/core";
import type { ToolApprovalRequest, ToolApprovalResult } from "@cline/shared";
import {
type ToolApprovalRequest,
type ToolApprovalResult,
USER_REJECTED_TOOL_REASON,
} from "@cline/shared";
import { useCallback, useEffect, useRef, useState } from "react";
import type { RuntimeToolInteraction, TuiProps } from "../types";
@@ -36,16 +40,16 @@ function toRuntimeToolInteraction(
};
}
function deniedToolResult(request: ToolApprovalRequest): ToolApprovalResult {
function deniedToolResult(): ToolApprovalResult {
return {
approved: false,
reason: `Tool "${request.toolName}" was denied by user`,
reason: USER_REJECTED_TOOL_REASON,
};
}
function dismissPendingInteraction(pending: PendingRuntimeToolInteraction) {
if (pending.kind === "tool_approval") {
pending.resolve(deniedToolResult(pending.request));
pending.resolve(deniedToolResult());
return;
}
pending.resolve("[User dismissed the question]");
@@ -111,9 +115,7 @@ export function useRuntimeDialogBridge(input: {
if (!pending || pending.id !== id || pending.kind !== "tool_approval") {
return;
}
pending.resolve(
approved ? { approved: true } : deniedToolResult(pending.request),
);
pending.resolve(approved ? { approved: true } : deniedToolResult());
const hasNext = finishActive(id);
if (!hasNext) {
refocusTextarea();
+19 -2
View File
@@ -1,6 +1,12 @@
import { createContext, useContext } from "react";
import { createContext, useContext, useMemo } from "react";
import type { TerminalTheme } from "../palette";
import { AUTO_THEME_ID, type ResolvedTheme, resolveTheme } from "../themes";
import {
AUTO_THEME_ID,
type DialogPalette,
getDialogPalette,
type ResolvedTheme,
resolveTheme,
} from "../themes";
export interface TerminalColors {
background: string | null;
@@ -41,6 +47,17 @@ export function useTheme(): ResolvedTheme {
return controller?.theme ?? resolveTheme(AUTO_THEME_ID, detected);
}
/**
* Theme-following colors for dialog content. Unlike the static `palette`
* constant, this re-resolves whenever the active theme changes, so open
* dialogs repaint live during theme previews (e.g. scrolling the theme
* picker).
*/
export function useDialogPalette(): DialogPalette {
const theme = useTheme();
return useMemo(() => getDialogPalette(theme), [theme]);
}
/**
* Background that adaptive colors (input field, user bubbles, rules) derive
* from: the theme's painted background when set, else the detected one.
+3 -3
View File
@@ -2,13 +2,13 @@ import { describe, expect, it } from "vitest";
import { getMcpDescription } from "./interactive-config";
describe("getMcpDescription", () => {
it("discloses the fast initialize probe for unconfigured stdio servers", () => {
it("discloses the default initialize timeout for unconfigured stdio servers", () => {
expect(
getMcpDescription({
name: "local",
transport: { type: "stdio", command: "node" },
}),
).toBe("stdio, local, request timeout 60s, initialize probe 1.5s");
).toBe("stdio, local, request timeout 60s, initialize timeout 3s");
});
it("shows one configured timeout when it also applies to initialize", () => {
@@ -40,6 +40,6 @@ describe("getMcpDescription", () => {
transport: { type: "stdio", command: "node" },
timeoutSeconds: Number.NaN,
}),
).toBe("stdio, local, request timeout 60s, initialize probe 1.5s");
).toBe("stdio, local, request timeout 60s, initialize timeout 3s");
});
});
+2 -1
View File
@@ -9,6 +9,7 @@ import {
} from "node:path";
import {
type BuiltinToolAvailabilityContext,
DEFAULT_MCP_CONNECT_TIMEOUT_MS,
discoverPluginModulePaths,
getPluginDisplayName,
hasMcpSettingsFile,
@@ -183,7 +184,7 @@ export function getMcpDescription(registration: McpServerRegistration): string {
const timeoutDescription =
registration.transport.type === "stdio" &&
!isMcpTimeoutConfigured(registration.timeoutSeconds)
? `request timeout ${timeoutSeconds}s, initialize probe 1.5s`
? `request timeout ${timeoutSeconds}s, initialize timeout ${DEFAULT_MCP_CONNECT_TIMEOUT_MS / 1000}s`
: `timeout ${timeoutSeconds}s`;
return `${registration.transport.type}, ${getMcpAuthLabel(registration)}, ${timeoutDescription}`;
}

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