mirror of
https://github.com/cline/cline.git
synced 2026-09-18 09:24:17 +08:00
Compare commits
117
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb1d838085 | ||
|
|
99db7582b0 | ||
|
|
15f001ad0b | ||
|
|
186ac22e29 | ||
|
|
fc68af9660 | ||
|
|
b675eb6189 | ||
|
|
82b8e1fa04 | ||
|
|
6e8bea1cba | ||
|
|
8739d4953c | ||
|
|
c17c82b79a | ||
|
|
cb0b20f791 | ||
|
|
2198414245 | ||
|
|
d718dd16f8 | ||
|
|
128ec277d5 | ||
|
|
18477898e0 | ||
|
|
9f19f047d2 | ||
|
|
e21b5903c2 | ||
|
|
17529c8cb1 | ||
|
|
36905f11cc | ||
|
|
722b640c28 | ||
|
|
067b865f97 | ||
|
|
c925a9c94c | ||
|
|
899e8f3da4 | ||
|
|
e10183f2a8 | ||
|
|
00daef8f89 | ||
|
|
94980446c9 | ||
|
|
c2ac5feecb | ||
|
|
97afeaccf0 | ||
|
|
b4b980d9a1 | ||
|
|
9de01af92d | ||
|
|
d896a0ac84 | ||
|
|
f80dd1eeff | ||
|
|
19ddebb3b9 | ||
|
|
c1c0b55ca0 | ||
|
|
ccb62e6b39 | ||
|
|
81abe4978c | ||
|
|
ea7c7f11a9 | ||
|
|
cfe9cadab9 | ||
|
|
e7d224dec6 | ||
|
|
632fce5071 | ||
|
|
e15bb0a7e5 | ||
|
|
efa9a17caf | ||
|
|
ac082be7c5 | ||
|
|
7e20bbc0e0 | ||
|
|
a7c1dfc298 | ||
|
|
23924da84f | ||
|
|
dd50b97192 | ||
|
|
5142921a54 | ||
|
|
e4f1df2c5a | ||
|
|
3f74808a43 | ||
|
|
1636215231 | ||
|
|
a0a8c060fb | ||
|
|
31b0dd9900 | ||
|
|
ea368a1fc5 | ||
|
|
f6359842a5 | ||
|
|
a35f9c7e35 | ||
|
|
05dbe644d1 | ||
|
|
7877d0e0a3 | ||
|
|
4063e1731e | ||
|
|
75ac98a3c8 | ||
|
|
258227dbe0 | ||
|
|
fc3273bbe0 | ||
|
|
ae0c86f11f | ||
|
|
46ba1d3228 | ||
|
|
35a0597471 | ||
|
|
c393958c52 | ||
|
|
be65a78b38 | ||
|
|
c8a0ace8b6 | ||
|
|
3033c394c7 | ||
|
|
2be718baba | ||
|
|
97a0d27d16 | ||
|
|
c52e87d52d | ||
|
|
35b4cd010a | ||
|
|
038102987e | ||
|
|
00fa85c164 | ||
|
|
08df88d6ec | ||
|
|
01aeb2147d | ||
|
|
1063db45d8 | ||
|
|
194214af76 | ||
|
|
2dd8f11ada | ||
|
|
bf4a364e08 | ||
|
|
fee4fb96f2 | ||
|
|
eb18ce3407 | ||
|
|
9fb1e6fc25 | ||
|
|
40f1d75bd2 | ||
|
|
b18de0904f | ||
|
|
de1d2a322c | ||
|
|
245a7d0ccb | ||
|
|
23f2197c53 | ||
|
|
9df2876c89 | ||
|
|
b63c738c22 | ||
|
|
bbacedd437 | ||
|
|
4096eca8a1 | ||
|
|
2f0f78bb8e | ||
|
|
62ba65397f | ||
|
|
79bf1e8c48 | ||
|
|
ffd65af086 | ||
|
|
119fa4ea03 | ||
|
|
40a7e6526d | ||
|
|
3d5070705c | ||
|
|
5a3b870d85 | ||
|
|
43bb575b6d | ||
|
|
50f5664683 | ||
|
|
8a520150f8 | ||
|
|
7e8063857b | ||
|
|
8ff5f22cf9 | ||
|
|
f5af82140b | ||
|
|
fc28a5fe33 | ||
|
|
5746f74ee7 | ||
|
|
d56cd10a6c | ||
|
|
6abb7cee76 | ||
|
|
afa1b01be1 | ||
|
|
c21b17255b | ||
|
|
dac3b35ba4 | ||
|
|
adbfbd97d3 | ||
|
|
952df213ee | ||
|
|
d7cb79aea5 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Warn when attached images will be ignored because the selected model does not support image input: image thumbnails get a warning badge and the composer offers to switch to an image-capable model, instead of the images being silently dropped before the API call
|
||||
@@ -1,34 +1,33 @@
|
||||
---
|
||||
name: publish-extension
|
||||
description: Use when releasing the Cline VS Code extension — stable (currently the combined legacy+next A/B VSIX via ext-vscode-ab-package), nightly (ext-vscode-publish-nightly), or a legacy-branch hotfix (ext-vscode-publish-legacy). Guides version selection, changelog, PostHog rollout-flag coordination, workflow dispatch, environment approvals, tagging, and post-publish verification, plus the eventual cutover to publishing the SDK extension standalone.
|
||||
description: Use when releasing the Cline VS Code extension — stable (standalone SDK build of main via ext-vscode-publish-stable), nightly (ext-vscode-publish-nightly, manual dispatch), or an emergency legacy-branch hotfix (ext-vscode-publish-legacy). Guides version selection, changelog, workflow dispatch, environment approvals, tagging, post-publish verification, and the remaining retirement of the finished A/B rollout machinery.
|
||||
---
|
||||
|
||||
# VS Code Extension Release
|
||||
|
||||
Use this skill when the user asks to release, publish, or ship the VS Code extension — stable, nightly, or a legacy hotfix — or to dial the rollout, or to cut over to the SDK extension permanently.
|
||||
Use this skill when the user asks to release, publish, or ship the VS Code extension — stable, nightly, or an emergency legacy hotfix — or to retire the leftover A/B rollout machinery.
|
||||
|
||||
> Working directory: repo root. All workflows are dispatched from `main` (GitHub requires the workflow file on the default branch; each workflow checks out the refs it actually builds).
|
||||
|
||||
## The current era: combined A/B rollout
|
||||
## The current era: standalone SDK extension from `main`
|
||||
|
||||
We are mid-migration from the legacy (npm, pre-SDK) extension to the next (SDK-based, bun) extension. Until the cutover is complete, **the stable and nightly listings ship a combined VSIX**: a small loader + two complete extensions (`next/` built from `main`, `legacy/` built from the `legacy-extension` branch). The loader picks one per window based on the PostHog flag `ext-sdk-bundle-rollout`. Deep-dive docs: `apps/vscode-rollout/README.md` (authoritative) and PR #12253 (design + runbook comments).
|
||||
**The legacy → SDK migration is complete.** The PostHog flag `ext-sdk-bundle-rollout` reached 100% (verified empirically 2026-09-15: 200/200 `/decide` probes returned `true`), so every user on the combined VSIX runs the `next` (SDK, bun) bundle and the `legacy/` half is dead weight. Stable releases now ship a **plain build of `main`** through `ext-vscode-publish-stable.yml`. The combined A/B path (`ext-vscode-ab-package.yml`) is no longer used for releases and is pending deletion — see "Retiring the A/B machinery" at the bottom for what is still left to clean up and the one caveat (leave the flag at 100%).
|
||||
|
||||
Endgame (see "Cutover" at the bottom): once the next bundle is trusted at 100%, stable goes back to a plain build of `main` via `ext-vscode-publish-stable.yml` and all the legacy/rollout machinery is retired.
|
||||
History, for context only: the A/B era ran `4.1.0` → `4.1.17` (Jul–Sep 2026). Design docs remain at `apps/vscode-rollout/README.md` and PR #12253 until that directory is removed.
|
||||
|
||||
### The listings and the workflows
|
||||
|
||||
| Channel | Marketplace ID | Workflow | Trigger | Version |
|
||||
|---|---|---|---|---|
|
||||
| Stable (combined) | `saoudrizwan.claude-dev` | `ext-vscode-ab-package.yml` | dispatch only; `publish` input defaults false | manual input (semver, e.g. `4.1.0`) |
|
||||
| Nightly (combined) | `saoudrizwan.cline-nightly` | `ext-vscode-publish-nightly.yml` | cron 12:00 UTC + dispatch | auto `<major>.<minor>.<unix-ts>` from main's `apps/vscode/package.json` |
|
||||
| Legacy hotfix (standalone) | `saoudrizwan.claude-dev` | `ext-vscode-publish-legacy.yml` | dispatch | from `apps/vscode/package.json` on `legacy-extension` |
|
||||
| Stable standalone (post-cutover) | `saoudrizwan.claude-dev` | `ext-vscode-publish-stable.yml` | dispatch | from `apps/vscode/package.json` on `main` |
|
||||
| **Stable** | `saoudrizwan.claude-dev` | `ext-vscode-publish-stable.yml` | dispatch, from `main` | `apps/vscode/package.json` on `main`; tag `v<version>` must match |
|
||||
| Nightly | `saoudrizwan.cline-nightly` | `ext-vscode-publish-nightly.yml` | **manual dispatch only** (cron deliberately removed) | auto `<major>.<minor>.<unix-ts>` from main's `apps/vscode/package.json` |
|
||||
| Legacy hotfix (emergency only) | `saoudrizwan.claude-dev` | `ext-vscode-publish-legacy.yml` | dispatch | `apps/vscode/package.json` on `legacy-extension` |
|
||||
|
||||
All three publish paths gate on tests before publishing: nightly and ab-package run the reusable bun suite (`ext-vscode-test.yml`, tests `main`) — ab-package additionally runs the legacy branch's npm suite — and the legacy workflow inlines the npm suite. Environment gates: stable paths use `publish` → `Publish` environment (required reviewers approve in the Actions UI); nightly uses `PublishNightly` (branch policy only, no reviewers — a reviewer requirement would block the cron).
|
||||
Stable runs the reusable bun suite (`ext-vscode-test.yml`, tests `main`) before an environment-gated publish job (`publish` environment — required reviewers approve in the Actions UI). Nightly uses `PublishNightly` (branch policy only). Nightly **still builds the combined loader VSIX** (loader + `next/` + `legacy/`) until it is converted back to a plain build — that conversion is on the retirement list below.
|
||||
|
||||
## Golden rules (read before any release)
|
||||
|
||||
1. **One listing, one version line.** `claude-dev` is published from multiple workflows/branches. Every stable publish must use a version **strictly above the highest version ever published to the listing from any branch** — marketplace versions are monotonic and cannot be unpublished (supersede, never delete). Check what's live first:
|
||||
1. **One listing, one version line.** `claude-dev` has been published from multiple workflows and branches. Every stable publish must use a version **strictly above the highest version ever published to the listing from any branch** — marketplace versions are monotonic and cannot be unpublished (supersede, never delete). Check what's live first:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery" \
|
||||
@@ -37,13 +36,123 @@ All three publish paths gate on tests before publishing: nightly and ab-package
|
||||
| python3 -c "import json,sys; v=json.load(sys.stdin)['results'][0]['extensions'][0]['versions'][0]; print(v['version'], v['lastUpdated'])"
|
||||
```
|
||||
|
||||
`ext-vscode-ab-package` also enforces this automatically for `publish=true` runs: a preflight job validates the version format (plain `X.Y.Z`) and hard-fails unless it exceeds the live Marketplace version, and the publish job re-checks right before publishing (the approval wait can last days — a legacy hotfix landing in between is caught). Still run the query yourself when *choosing* the version.
|
||||
**`ext-vscode-publish-stable` has no marketplace-monotonicity preflight** (that check only ever lived in the retired ab-package workflow), so this query is the only guard. The `legacy-extension` branch sits at `4.0.12`, so it cannot collide with the `4.1.x` line, but a legacy hotfix would have to be numbered above the live stable version (see the emergency section).
|
||||
|
||||
2. **Check the flag BEFORE any stable combined publish.** `ext-sdk-bundle-rollout` is **shared between nightly and stable** — the loader sends only a machine id to `/decide`, no channel property, so there is no per-channel targeting. If the flag is high (nightly dogfooding) and you publish stable, stable users get the next bundle at that same percentage. Verify the effective percentage empirically (no PostHog admin needed — sample `/decide` with random ids using the key inlined in any shipped loader):
|
||||
2. **Tag == package version, enforced.** The workflow reads `apps/vscode/package.json`, requires the `tag` input to equal `v<that version>`, and hard-fails otherwise. Bump the version on `main` first.
|
||||
|
||||
3. **Changelog lives at the repo ROOT** (`CHANGELOG.md`) — not `apps/vscode/CHANGELOG.md` (doesn't exist). The workflow hard-fails unless the first `## [` heading is exactly `## [<version>]`. The section body becomes the GitHub release notes and the Slack post (Slack copy is trimmed to 3000 chars with a link out; the release body stays whole).
|
||||
|
||||
4. **Ask before pushing** commits or tags. **Never approve the `publish` environment gate yourself via `gh api`** — hand the maintainer the run URL to click "Review deployments".
|
||||
|
||||
5. **Concurrency**: the workflow groups on the tag with `cancel-in-progress: false`. A publish run left `waiting` on approval blocks every later dispatch of the same tag until cancelled (`gh run cancel <id>`).
|
||||
|
||||
## Stable release — the current path
|
||||
|
||||
### Pre-flight
|
||||
|
||||
```bash
|
||||
# 1. What's live (rule 1) → pick <VERSION> strictly above it (normally patch bump).
|
||||
# 2. Confirm main's package.json is at the *previous* published version, i.e. the repo
|
||||
# reflects the live line and nothing unreleased is already bumped:
|
||||
node -p "require('./apps/vscode/package.json').version"
|
||||
# 3. What's in the release:
|
||||
git fetch origin main --tags
|
||||
git log v<PREV>..origin/main --oneline --no-merges -- apps/vscode sdk/packages
|
||||
```
|
||||
|
||||
The CLI/SDK notes are the best starting point for the extension notes — the extension bundles `@cline/*` from source, so an SDK release in the same window ships here too. Read `sdk/CHANGELOG.md` for the matching SDK version and translate what's extension-visible; skip CLI-only and desktop-only items.
|
||||
|
||||
### Release prep on `main` (PR, not direct push)
|
||||
|
||||
- Bump `apps/vscode/package.json` → `<VERSION>`.
|
||||
- Prepend `## [<VERSION>]` to root `CHANGELOG.md` with the approved notes.
|
||||
- Side effect of the bump: nightly versions become `<major>.<minor>.<unix-ts>` of the new base — harmless (separate listing, still monotonic).
|
||||
|
||||
Optional local rehearsal of the exact packaging step (the workflow has no dry-run input, and the build runs inside the gated publish job, so this is the only pre-approval check):
|
||||
|
||||
```bash
|
||||
bun install --frozen-lockfile && bun run build:sdk
|
||||
cd apps/vscode && npx @vscode/vsce package --no-dependencies --allow-package-secrets sendgrid --out /tmp/rehearsal.vsix
|
||||
# vsce runs vscode:prepublish → `bun run package` (check-types + build:webview + lint + esbuild --production),
|
||||
# i.e. the same build the workflow performs. Telemetry env is NOT set locally, so expect
|
||||
# telemetry to be dark in this artifact — that is fine for a build rehearsal, not for shipping.
|
||||
```
|
||||
|
||||
### Dispatch
|
||||
|
||||
```bash
|
||||
gh workflow run ext-vscode-publish-stable.yml --ref main \
|
||||
-f release-type=release \
|
||||
-f auto_create_tag_from_main=true \
|
||||
-f tag=v<VERSION>
|
||||
gh run list --workflow=ext-vscode-publish-stable.yml --limit 1 --json databaseId,url,status
|
||||
```
|
||||
|
||||
What the run does, in order: test gate on `main` → publish job checks out `main`, **creates and pushes `v<VERSION>` at the tested SHA** (auto-create mode; refuses if the tag already exists elsewhere) → `bun install --frozen-lockfile` → `bun run build:sdk` → asserts the `better-sqlite3` native binary → verifies tag/version/changelog/PATs → `vsce package` → `bun run publish:marketplace` (vsce publish **and** `npx ovsx publish`, both `--no-dependencies`) → GitHub release with the `.vsix` attached → Slack post. The publish job waits for `publish` environment approval before any of that. Check what a run is waiting on:
|
||||
|
||||
```bash
|
||||
gh api repos/cline/cline/actions/runs/<run-id>/pending_deployments
|
||||
```
|
||||
|
||||
`release-type=pre-release` publishes to the pre-release channel of the same listing; it is a real publish, not a rehearsal.
|
||||
|
||||
### Post-publish
|
||||
|
||||
1. Verify both registries serve the new version (expect minutes-to-an-hour of Marketplace validation lag after "Published" appears in the logs):
|
||||
|
||||
```bash
|
||||
# Marketplace: query from rule 1
|
||||
curl -s "https://open-vsx.org/api/saoudrizwan/claude-dev" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['version'], d['timestamp'])"
|
||||
```
|
||||
|
||||
2. Verify the bookkeeping landed: `git fetch --tags && git tag --list 'v<VERSION>'`, `gh release view v<VERSION>`, Slack post in the release channel. Tag creation happens **before** the build in this workflow, so a tag-push failure fails the run early (no publish) rather than leaving a published-but-untagged release. Known cause: the built commit touches `.github/workflows/**` (default token cannot create such refs). Workaround: create and push the tag yourself at `origin/main` HEAD (ask first), then re-dispatch with `auto_create_tag_from_main=false` from `main` — the workflow requires the existing tag to point at the exact SHA it tested.
|
||||
|
||||
3. Artifact check (`gh run download <run-id>` or the release asset): `package.json` inside is `saoudrizwan.claude-dev@<VERSION>`; `grep -c 'process.env.TELEMETRY_SERVICE_API_KEY' extension/dist/extension.js` must be **0** (a leftover literal means the build ran without its env and telemetry is silently dead). `CLINE_ROLLOUT_VARIANT` is defined to `""` for ordinary builds by `apps/vscode/esbuild.mjs`, so no literal is expected and telemetry carries no `extension_variant` — correct for a standalone build.
|
||||
|
||||
4. Monitor errors on `extension_version = '<VERSION>'` in `otel.otel_logs` (stable cohort is cleanly separable — nightly versions are timestamps). Metabase dashboards 17 (task error rate) and 19 (error deep dive).
|
||||
|
||||
## Nightly release
|
||||
|
||||
**Manual dispatch only.** The cron was removed on purpose: the `PublishNightly` environment made scheduled runs sit `waiting`, hold the concurrency group, and silently cancel every later scheduled run behind them. A stale nightly listing is therefore expected, not a bug.
|
||||
|
||||
```bash
|
||||
gh workflow run ext-vscode-publish-nightly.yml --ref main # real publish
|
||||
gh workflow run ext-vscode-publish-nightly.yml --ref main -f dry-run=true # artifact only
|
||||
```
|
||||
|
||||
No changelog/version prep — the version is computed. Verify with the Marketplace query against `saoudrizwan.cline-nightly`. Until converted, nightly still ships the combined loader VSIX with a `legacy/` bundle built from `legacy-extension`.
|
||||
|
||||
**Red run ≠ failed publish** on this path: its tag-push step runs *after* publishing and fails whenever main's HEAD touches `.github/workflows/**`. If "Published" appears in the logs, the release went out; push the `nightly-main-<UTC ts>-<sha12>` tag manually with user credentials.
|
||||
|
||||
## Emergency rollback
|
||||
|
||||
Preferred: **ship a fixed build of `main` at a higher version** through the stable workflow above. It is the same path, fully gated, and the only rollback that keeps users on the SDK extension.
|
||||
|
||||
Last resort — the legacy hotfix path — still exists but is degraded: `legacy-extension` is the pre-SDK npm codebase, last touched 2026-08-18 at `4.0.12`, and a publish from it would move every user back onto code that is weeks behind. If it is ever needed:
|
||||
|
||||
```bash
|
||||
# On legacy-extension: commit the fix, bump apps/vscode/package.json ABOVE the
|
||||
# live stable version (rule 1 — e.g. 4.1.18 live -> hotfix is 4.1.19, 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
|
||||
# (the branch is hardcoded to legacy-extension in the workflow)
|
||||
```
|
||||
|
||||
The npm suite runs ungated, the publish job waits on the `publish` environment, the workflow tags and creates the GitHub release itself, and it publishes to Marketplace **and** Open VSX. On that branch use `npm`, never `bun`, and expect the old monolith layout (`apps/vscode/src/core/...`).
|
||||
|
||||
## Retiring the A/B machinery (still to do)
|
||||
|
||||
The rollout is done but the scaffolding is still in the repo. Retire it in this order, each as its own PR:
|
||||
|
||||
1. **Nightly → plain build of `main`**: drop the loader/`legacy-src` stitching from `ext-vscode-publish-nightly.yml` so nightly matches stable. Preserve the `|| 'default'` fallbacks for `inputs.*` while editing.
|
||||
2. Delete `ext-vscode-ab-package.yml` and, once the emergency path above is judged unnecessary, `ext-vscode-publish-legacy.yml`; keep the `legacy-extension` branch for history.
|
||||
3. Remove `apps/vscode-rollout/` and the rollout-only code paths in `apps/vscode/src/services/telemetry/rollout-metadata.ts` (the `extension_variant` metadata and `extension.rollout.bundle_activated` event).
|
||||
4. Optionally port the marketplace-monotonicity preflight from the old ab-package workflow into `ext-vscode-publish-stable.yml` — the only automated guard for rule 1 was retired with it.
|
||||
5. **Archive the PostHog flag last, and not yet.** Machines still on a combined VSIX (`≤ 4.1.17`) consult `ext-sdk-bundle-rollout` on every window load and treat a *deleted* flag as `legacy`. Leave it at 100% until `extension.rollout.bundle_activated` for combined versions flatlines, then archive. Re-verify the percentage empirically before touching it (no PostHog admin needed — the key is inlined in any shipped combined loader; download the 4.1.17 VSIX from the Marketplace `vspackage` URL, `gunzip`, `unzip`, `grep -o 'phc_[A-Za-z0-9]*' extension/extension.js`):
|
||||
|
||||
```bash
|
||||
node -e '
|
||||
const KEY = process.argv[1]; // phc_... extracted from a shipped VSIX loader
|
||||
const KEY = process.argv[1];
|
||||
(async () => {
|
||||
let t = 0, n = 200;
|
||||
for (let i = 0; i < n; i += 20) {
|
||||
@@ -58,129 +167,15 @@ All three publish paths gate on tests before publishing: nightly and ab-package
|
||||
})()' "$KEY"
|
||||
```
|
||||
|
||||
Flag changes are made in the PostHog UI (Cline project). **0% is the kill switch** — the flag is two-way; there is no separate killswitch flag. Dialing down demotes machines back to legacy on their next window reload.
|
||||
|
||||
3. **Ask before pushing** commits or tags. Environment approvals are the maintainer's to give.
|
||||
|
||||
4. **Changelog lives at the repo ROOT** (`CHANGELOG.md`), on the branch being released — not `apps/vscode/CHANGELOG.md` (doesn't exist). The legacy and stable workflows hard-fail unless the first heading is exactly `## [<version>]`.
|
||||
|
||||
5. **Stuck concurrency groups**: `ext-vscode-ab-package` groups on the version with `cancel-in-progress: false`. Only `publish=true` runs wait on environment approval (build-only rehearsals run ungated to completion), but a publish run left `waiting` still blocks every later dispatch of the same version — cancel it (`gh run cancel <id>`) before re-dispatching.
|
||||
|
||||
## Stable release (combined A/B VSIX) — the current stable path
|
||||
|
||||
### Pre-flight
|
||||
|
||||
```bash
|
||||
# 1. What's live, and what version comes next (must exceed it — rule 1)
|
||||
# 2. Flag percentage (rule 2) — decide where it should be for this release
|
||||
# 3. Legacy tip = what the non-promoted cohort will run; confirm it's the shipped hotfix line
|
||||
git fetch origin main legacy-extension
|
||||
git log --oneline -3 origin/legacy-extension
|
||||
|
||||
# 4. Cheap local rehearsal of the most likely build failure: the union manifest
|
||||
# hard-fails if views/viewsContainers/configuration diverged between branches.
|
||||
git show origin/main:apps/vscode/package.json > /tmp/next.json
|
||||
git show origin/legacy-extension:apps/vscode/package.json > /tmp/legacy.json
|
||||
node apps/vscode-rollout/scripts/gen-manifest.mjs --next /tmp/next.json --legacy /tmp/legacy.json --version <VERSION>
|
||||
# Expected warnings only: engines union (takes newer) + walkthrough copy drift.
|
||||
```
|
||||
|
||||
Release prep on `main` (PR, not direct push):
|
||||
- Add `## [<VERSION>]` entry at the top of root `CHANGELOG.md`.
|
||||
- Bump `apps/vscode/package.json` to `<VERSION>` so the repo reflects the published line. Side effect: nightly versions become `<major>.<minor>.<unix-ts>` of the new base — harmless (separate listing, still monotonic).
|
||||
|
||||
### Dispatch
|
||||
|
||||
```bash
|
||||
gh workflow run ext-vscode-ab-package.yml --ref main \
|
||||
-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.
|
||||
gh run list --workflow=ext-vscode-ab-package.yml --limit 1
|
||||
```
|
||||
|
||||
Preflight (version format + monotonicity) and both test suites run first, then the ungated `build` job packages and uploads the VSIX; for `publish=true` the `publish` job then **waits for `Publish` environment approval** (Actions → run → "Review deployments"). Both bundles build the exact revisions their test gates ran against (branch names are resolved once — commits landing on either branch mid-run or during the approval wait are not picked up); `publish=true` is additionally refused for any `next-ref` other than `main` (the bun gate only tests main — non-main next-refs are for build-only artifact rehearsals). Check what a run is waiting on:
|
||||
|
||||
```bash
|
||||
gh api repos/cline/cline/actions/runs/<run-id>/pending_deployments
|
||||
```
|
||||
|
||||
### Post-publish
|
||||
|
||||
1. Verify the marketplace serves the new version (query from rule 1) — expect minutes-to-an-hour of validation lag after "Published" appears in the logs. Also verify Open VSX:
|
||||
|
||||
```bash
|
||||
curl -s "https://open-vsx.org/api/saoudrizwan/claude-dev" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['version'], d['timestamp'])"
|
||||
```
|
||||
2. Tag, GitHub Release (with the .vsix attached), and the Slack release-bot post happen **automatically** after a real publish (all `continue-on-error` — the publish itself already succeeded, so bookkeeping failures leave the run green). Verify they landed; the known failure is the tag push when the built commit touches `.github/workflows/**` (default token cannot create such refs — no grantable permission fixes it). Manual fallback:
|
||||
|
||||
```bash
|
||||
git tag v<VERSION> <main-sha-built> # ask before pushing
|
||||
git push origin v<VERSION>
|
||||
gh release create v<VERSION> --title "v<VERSION>" --notes "<changelog section>" <path-to.vsix>
|
||||
```
|
||||
|
||||
A real publish also **hard-fails early** if root `CHANGELOG.md` on the built main revision doesn't start with `## [<VERSION>]` — the release prep PR must be merged before dispatching.
|
||||
|
||||
3. Thorough artifact check (`gh run download <run-id>`): union `package.json` is `saoudrizwan.claude-dev@<VERSION>`, `next/package.json` and `legacy/package.json` carry the SAME version, `grep -c 'phc_' extension/extension.js` ≥ 1 (loader key inlined), no leftover `process.env.TELEMETRY_SERVICE_API_KEY` / `process.env.CLINE_ROLLOUT_VARIANT` literals in either bundle's dist (leftovers = a build ran without its env and telemetry is silently dead).
|
||||
4. Monitor: `extension.rollout.bundle_activated` in `otel.otel_logs` filtered to `extension_version = '<VERSION>'` (stable cohort is cleanly separable — nightly versions are timestamps). Watch the next/legacy ratio and the crash-fallback rate; Metabase dashboards 17 (rollout + task error rate) and 19 (error deep dive). `extension.rollout.loader_decision` (incl. `double_failure`) is PostHog-only, not in ClickHouse.
|
||||
5. Dial the flag per the rollout plan (e.g. 0% at publish → 1% → up), verifying each change with the probe from rule 2. Announce demotions ahead of time — dialing down also demotes nightly dogfooders unless they set `"cline-nightly.rollout.bundleOverride": "next"`.
|
||||
|
||||
### Known caveats of this path
|
||||
|
||||
- **`engines.vscode` unions upward** (main's floor wins, e.g. `^1.101.0` vs legacy's `^1.84.0`): users on older VS Code are never offered the combined VSIX. Fail-safe during rollout; must be resolved before 100%.
|
||||
- A red run can still mean a successful publish on paths that tag (see Gotchas).
|
||||
|
||||
## Nightly release
|
||||
|
||||
Happens automatically (cron 12:00 UTC). Manual cut:
|
||||
|
||||
```bash
|
||||
gh workflow run ext-vscode-publish-nightly.yml --ref main # real publish
|
||||
gh workflow run ext-vscode-publish-nightly.yml --ref main -f dry-run=true # artifact only
|
||||
gh run watch <run-id> --exit-status --interval 60
|
||||
```
|
||||
|
||||
No changelog/version prep — the version is computed. Verify with the marketplace query against `saoudrizwan.cline-nightly`.
|
||||
|
||||
**Red run ≠ failed publish**: the final tag-push step fails whenever main's HEAD touches `.github/workflows/**` (default token cannot create such refs). If "Published" appears in the logs, the release went out; push the `nightly-main-<UTC ts>-<sha12>` tag manually with user credentials.
|
||||
|
||||
## Legacy hotfix release (and emergency full rollback)
|
||||
|
||||
For shipping a fix on the `legacy-extension` branch — or as the **structural rollback** from a bad combined stable VSIX: a standalone legacy publish at a higher version supersedes the combined VSIX entirely (loader and all) for every user. (For "next bundle misbehaving" you don't need this — dial the flag to 0% instead.)
|
||||
|
||||
```bash
|
||||
# On legacy-extension: commit the fix, bump apps/vscode/package.json ABOVE the
|
||||
# highest version ever published to the listing (rule 1 — including combined
|
||||
# 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
|
||||
# (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/...`).
|
||||
|
||||
## Cutover: retiring the A/B machinery (the endgame)
|
||||
|
||||
When the next bundle has held at 100% long enough to trust:
|
||||
|
||||
1. **Resolve the engines floor**: decide whether stranding VS Code < main's `engines.vscode` on the last combined version is acceptable, or lower main's floor first.
|
||||
2. Bump `apps/vscode/package.json` on `main` above everything ever published; root `CHANGELOG.md` entry to match (both are enforced by the workflow).
|
||||
3. Ship standalone from main: `gh workflow run ext-vscode-publish-stable.yml --ref main` — tests main, tags `v<version>` itself, creates the GitHub release, publishes Marketplace + Open VSX.
|
||||
4. Watch the same rollout telemetry through the transition — `extension_variant` disappears from events as users leave combined builds, which is itself the adoption signal.
|
||||
5. Only after the standalone version dominates: retire `legacy-extension` (keep for history), delete `ext-vscode-publish-legacy.yml` and `ext-vscode-ab-package.yml`, convert the nightly workflow back to a plain build of main, remove `apps/vscode-rollout/`, and archive the `ext-sdk-bundle-rollout` flag in PostHog (harmless to machines still on a combined VSIX: absent flag fails safe to... nothing changing until they update, but their loader treats a deleted flag as legacy — leave the flag at 100% until combined-VSIX activations flatline, then archive).
|
||||
6. Update this skill: delete the combined-era sections and keep the standalone flow.
|
||||
6. Update this skill: delete this section and the combined-loader notes under Nightly.
|
||||
|
||||
## Gotchas index
|
||||
|
||||
- `inputs.*` are empty strings on `schedule` events — preserve `|| 'default'` fallbacks when editing the nightly workflow.
|
||||
- `bun run package` in `apps/vscode` does not build `@cline/*` workspace deps — fresh checkouts need `bun run build:sdk` first (workflows handle this).
|
||||
- `bun run package` in `apps/vscode` does not build `@cline/*` workspace deps — fresh checkouts need `bun run build:sdk` first (the workflows handle this).
|
||||
- Every ext workflow pins `bun-version: 1.3.14` while the root `packageManager` is `bun@1.3.13`. This is consistent across all of them and has shipped fine — don't "fix" it in one workflow alone.
|
||||
- The publish job pins **Node 22** on purpose: Node 24 / npm 11 can make vsce's `npm list` detection fail with `ELSPROBLEMS` during packaging. `setup-bun` provides no Node runtime, and the publish scripts and `npx ovsx` need one.
|
||||
- `gh run watch --exit-status` has returned exit 0 on a failed run. Always confirm with `gh run view <id> --json status,conclusion` before acting on a result.
|
||||
- Job-level `if:` ref checks in workflow YAML are advisory (a dispatched branch runs its own copy of the file); the enforced boundary is each environment's deployment-branch policy in repo settings.
|
||||
- Marketplace PATs (`VSCE_PAT`/`OVSX_PAT`) are only mounted into publish steps; neither publish workflow has an untrusted trigger surface.
|
||||
- Environment-approval runs left waiting don't time out quickly — they sit for days and (for ab-package publish runs) block their version's concurrency group.
|
||||
- Local forcing for manual testing: `CLINE_BUNDLE_OVERRIDE=next|legacy` env (launch VS Code fresh from a terminal) or the `<prefix>.rollout.bundleOverride` setting + reload; both report as `override` in telemetry so they don't pollute cohort data.
|
||||
- Marketplace PATs (`VSCE_PAT`/`OVSX_PAT`) are only mounted into publish steps; no publish workflow has an untrusted trigger surface.
|
||||
- Environment-approval runs left waiting don't time out quickly — they sit for days and block their tag's concurrency group.
|
||||
- Open VSX has held a first-time publish in moderation before (logs say "Published", API 404s for hours). Verify with the API query rather than the log line.
|
||||
|
||||
@@ -319,6 +319,12 @@ jobs:
|
||||
# Updater artifact signing (minisign keypair, independent of Apple)
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
# The DMG background, window size, and icon positions from
|
||||
# tauri.conf.json are applied by a Finder AppleScript in Tauri's
|
||||
# bundle_dmg.sh. When CI=true (always set on Actions) the bundler
|
||||
# passes --skip-jenkins and silently skips that script, shipping a
|
||||
# bare DMG. macOS runners have a GUI session, so opt out of the skip.
|
||||
TAURI_BUNDLER_DMG_IGNORE_CI: "true"
|
||||
|
||||
# Tauri lipos the main binary itself but sidecars are merged by our own
|
||||
# build-sidecar-bin.ts, so assert every Mach-O in the bundle really
|
||||
|
||||
@@ -6,13 +6,13 @@ on:
|
||||
- main
|
||||
paths:
|
||||
- "sdk/**"
|
||||
- "apps/examples/desktop-app/**"
|
||||
- ".github/workflows/sdk-test.yml"
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "sdk/**"
|
||||
- "apps/examples/desktop-app/**"
|
||||
- ".github/workflows/sdk-test.yml"
|
||||
workflow_call:
|
||||
|
||||
@@ -98,6 +98,14 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'windows-latest' }}
|
||||
run: bun -F './sdk/packages/**' test
|
||||
|
||||
- name: Run Desktop Sidecar Tests
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && matrix.os == 'ubuntu-latest' }}
|
||||
run: bun -F @cline/code test:sidecar
|
||||
|
||||
- name: Run Desktop Settings UI Tests
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' }}
|
||||
run: bun -F @cline/code test:settings-ui
|
||||
|
||||
- name: Smoke test SQLite under Node
|
||||
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && matrix.os != 'windows-latest' }}
|
||||
timeout-minutes: 10
|
||||
|
||||
+16
-2
@@ -61,8 +61,9 @@ Emission ownership:
|
||||
|
||||
- `user.extension_activated`: emitted **once per host process** by host-specific helpers
|
||||
(`captureCliExtensionActivated` for the CLI, `captureExtensionActivated` for VS Code).
|
||||
- `workspace.initialized` / `workspace.init_error`: emitted by a per-process de-duplicated
|
||||
emitter in `prepareLocalRuntimeBootstrap`. Hosts must NOT re-emit these.
|
||||
- `workspace.initialized` / `workspace.init_error`: emitted by a de-duplicated emitter in
|
||||
`prepareLocalRuntimeBootstrap`. A dedicated host emits once per workspace; a shared Hub emits
|
||||
once per client surface and workspace. Hosts must NOT re-emit these.
|
||||
- `workspace.path_resolved`: emitted from default tool executors **only when**
|
||||
`WorkspaceManager` exposes more than one root.
|
||||
- `task.*`: emitted by core session lifecycle code in `sdk/packages/core/src/cline-core/` and
|
||||
@@ -104,6 +105,19 @@ hub-backed session, so the daemon must own its own `ITelemetryService`. It build
|
||||
identifies from the cached cline account (re-resolved periodically, since the daemon often
|
||||
starts before login) and flushes on every shutdown path, including startup failure.
|
||||
|
||||
The Hub transport forwards the serializable `ExtensionContext.client` and
|
||||
`ExtensionContext.user` values with session create/restore requests. The daemon wraps its
|
||||
process-owned service with `createClientScopedTelemetryService()` so lifecycle events use the
|
||||
originating client's `cline_type`, platform/version, and current account/organization without
|
||||
mutating the singleton shared by concurrent clients. Keep canonical task fields named
|
||||
`provider` and `model`; do not reintroduce host-specific aliases such as `apiProvider` or
|
||||
`modelId` for `task.created`, `task.restarted`, or `task.completed`.
|
||||
|
||||
`UserContext.distinctId` may be an anonymous machine ID. Set `UserContext.accountId` to the
|
||||
authenticated account ID (or `null` for an explicitly signed-out client) whenever a client
|
||||
forwards user context; this prevents machine IDs and stale daemon identity from becoming
|
||||
`user_id` / `organization_id` on task events.
|
||||
|
||||
Flag changes that remove this wiring, construct runtime hosts inside the daemon without
|
||||
passing its telemetry handle, or add daemon exit paths that skip the flush — hub-backed
|
||||
sessions would silently drop their lifecycle telemetry (this exact bug shipped once).
|
||||
|
||||
@@ -1,5 +1,39 @@
|
||||
# Changelog
|
||||
|
||||
## [4.1.18]
|
||||
|
||||
### Added
|
||||
|
||||
- Images attached to a model that cannot read them are now flagged instead of silently discarded. Thumbnails get a warning badge and the composer explains that the images will be ignored, with a button to switch to an image-capable model. Previously the thumbnail looked normal and the image was replaced with a text placeholder just before the request, so there was no way to tell it had been dropped. Model info and the attachment picker also report image support accurately for models that declare text-only input without listing capabilities.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A model turn that fails mid-stream with a transient provider error is now retried up to three times with backoff instead of ending the task. A single rate-limit response forwarded by a gateway previously surfaced as a failed task. A turn that has already streamed output is never retried, so nothing is duplicated.
|
||||
- Terminal commands that succeed without printing anything (`git add -A` on a clean tree, for example) are now reported as empty output. They were treated as a shell-integration failure, which fed the model a snapshot of unrelated terminal scrollback prefixed with a warning that the output could not be captured, so silent commands intermittently looked like failures.
|
||||
- Checkpoints no longer re-hash every untracked file on each message. In workspaces holding large untracked directories this delayed every message by seconds to minutes; a persistent per-task index now lets git skip files it has already seen.
|
||||
- `run_commands` no longer hangs until its timeout after a command that backgrounds a child process. The command had finished, but the backgrounded process held the output pipes open.
|
||||
- `apply_patch` no longer silently overwrites an existing file when the model uses "Add File" on a path that already exists. The file's contents were replaced with no error and no record of what was lost.
|
||||
- PowerShell commands the model wrapped in another `powershell -Command "..."` are no longer parsed twice. The outer shell consumed `$_` before the inner command ran, so pipelines using it emitted an error for every item processed while still reporting success.
|
||||
- Opening your home directory as a workspace no longer drives the extension host to exhaustion. Typing an `@` mention indexed every file beneath it and re-ranked the whole index on each keystroke.
|
||||
- The "Supports Images" checkbox in OpenAI Compatible model settings now stays where you put it. The checkbox rendered the last committed value, and the re-sync that arrived during the save round-trip was re-emitted as a change event that wrote the old value back over your edit.
|
||||
- The error shown to the model when an `editor` call omits the text to replace now names the file and explains how to recover. The previous message was terse enough that some models re-sent the identical call until the task stopped.
|
||||
- Credentials are now stripped of invisible characters when saved, not only when pasted, and the cleanup covers AWS, GCP, and SAP fields and custom header values in addition to API keys.
|
||||
- Cline Pass now defaults to a model from your subscription rather than a free one. Its model list contains both tiers and the default was whichever model was published most recently, so a subscriber who never picked a model could be left on the free tier.
|
||||
- Cline Pass and free models now show no cost rather than the underlying market price, which is not what you are billed for.
|
||||
- Model pickers now fall back to the full Recommended, Free, and Subscribed lists when the models endpoint cannot be reached. The offline fallback was a short hardcoded list with no subscription tier at all.
|
||||
- Model lists for providers sharing the built-in catalog now refresh from the live catalog, so newly published models appear without an extension update, with timeouts so an unresponsive provider endpoint cannot stall the list.
|
||||
- Claude Code and OpenCode no longer ask for an API key they never read. Both authenticate from their own local CLI's credentials, but they were treated as key-based providers; the workaround was storing a dummy key. A missing CLI on `PATH` now warns rather than blocking, since a configured path or bundled binary also works.
|
||||
- The OpenAI Codex (ChatGPT subscription) model list no longer offers models the backend rejects, and Codex context limits are applied to every Codex model instead of being inherited from the OpenAI API catalog, which inflated both the context budget and the usage figures derived from it.
|
||||
- Models served by OpenCode Go are now sent over the wire protocol each one actually speaks. Every model was sent over the OpenAI chat-completions adapter, so models on that endpoint speaking other protocols failed or misbehaved.
|
||||
- Task history no longer goes blank when a task spawns many subagents. Subagent rows crowded out the tasks that created them, hiding the parent task and everything older.
|
||||
- Langfuse tracing, when configured, is now limited to the Cline and Cline Pass providers. The provider was ignored, so prompts and responses sent to third-party and bring-your-own-key providers were exported too.
|
||||
|
||||
### Changed
|
||||
|
||||
- Web search is now enabled by default on models that support it, outside YOLO mode. It can still be turned off in settings, and a settings file that cannot be read leaves it disabled rather than silently on.
|
||||
- The `run_commands` tool description now names the PowerShell edition in use — `Windows PowerShell (powershell.exe)` versus `PowerShell (pwsh.exe)` — quotes its guidance against that executable, and tells the model to run commands directly rather than wrapping them in another shell invocation. It also no longer describes the environment as Windows when `pwsh` is the configured shell on macOS or Linux.
|
||||
- Refreshed the built-in model catalog. Adds four providers (Infer by Flow7, Melious, NaN, and Wallaby) and takes the catalog from 5,788 to 6,079 models. This is a wide refresh: the resolved default model changes for 44 providers, most of them landing on DeepSeek V4.1 Flash — among them Hugging Face, Fireworks, Requesty, Nebius, Cortecs, CrossModel, DigitalOcean, Eden AI, and OpenCode Go. Gemini and Vertex now resolve to Gemini 3.8 Flash, GitHub Copilot and Vivgrid to GPT-6 Astra, and NVIDIA to GLM 5.3 Flash. If you use a provider without pinning a model, expect a different default.
|
||||
|
||||
## [4.1.17]
|
||||
|
||||
Everything here lands through the SDK bundle, so it applies to windows running that bundle.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h1 align="center">Cline</h1>
|
||||
|
||||
<p align="center">
|
||||
The open source coding agent in your IDE and terminal.
|
||||
The open source coding agent in your IDE, terminal, and desktop.
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
@@ -44,7 +44,7 @@ The open source coding agent in your IDE and terminal.
|
||||
### CLI
|
||||
|
||||
Run Cline in your terminal.
|
||||
Interactive chat or fully headless
|
||||
Interactive chat or fully headless
|
||||
for CI/CD and scripting.
|
||||
|
||||
```
|
||||
@@ -57,17 +57,13 @@ npm i -g cline
|
||||
</td>
|
||||
<td align="center" width="50%">
|
||||
|
||||
### Kanban
|
||||
### Desktop App
|
||||
|
||||
Run many agents in parallel from a
|
||||
web-based task board. Each card gets its own
|
||||
worktree, auto-commit, and dependency chains.
|
||||
Cline as a native app for macOS and Windows.
|
||||
Run agent sessions in any folder, schedule
|
||||
routines, and manage models, plugins, and MCP servers.
|
||||
|
||||
```
|
||||
npm i -g kanban
|
||||
```
|
||||
|
||||
<a href="https://github.com/cline/kanban">Learn more</a>
|
||||
<a href="https://cline.bot/desktop">Download for macOS and Windows</a>
|
||||
<br><br>
|
||||
|
||||
</td>
|
||||
@@ -108,7 +104,7 @@ the JetBrains family.
|
||||
|
||||
### SDK
|
||||
|
||||
Build your own AI agents and integrations powered by the same engine that runs the CLI, Kanban, VS Code extension, and JetBrains plugin. Custom tools, multi-agent teams, connectors, scheduled automations, and more.
|
||||
Build your own AI agents and integrations powered by the same engine that runs the CLI, desktop app, VS Code extension, and JetBrains plugin. Custom tools, multi-agent teams, connectors, scheduled automations, and more.
|
||||
|
||||
```
|
||||
npm install @cline/sdk
|
||||
@@ -131,8 +127,8 @@ npm install @cline/sdk
|
||||
| **SDK** | Node.js programmatic agent API and extension exports. | [`sdk/`](https://github.com/cline/cline/tree/main/sdk) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/sdk/CHANGELOG.md) |
|
||||
| **CLI** | Terminal UI, headless mode, shell commands, and CLI-specific flows. | [`apps/cli/`](https://github.com/cline/cline/tree/main/apps/cli) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/apps/cli/CHANGELOG.md) |
|
||||
| **VS Code Extension** | The Marketplace extension and extension host integration. | [`/`](https://github.com/cline/cline/tree/main) (WIP migrating) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/CHANGELOG.md) |
|
||||
| **Desktop App** | Native macOS and Windows app (Tauri shell, Bun sidecar, Next.js UI). | [`apps/examples/desktop-app/`](https://github.com/cline/cline/tree/main/apps/examples/desktop-app) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/apps/examples/desktop-app/CHANGELOG.md) |
|
||||
| **JetBrains Plugin** | JetBrains-hosted client that talks to the shared agent core. | Currently we are not open-sourcing JetBrains plugins | - |
|
||||
| **Kanban** | Web-based multi-agent task board. | [`cline/kanban`](https://github.com/cline/kanban) | [CHANGELOG.md](https://github.com/cline/kanban/blob/main/CHANGELOG.md) |
|
||||
| **Docs site** | Public documentation pages. | [`docs/`](https://docs.cline.bot/) | - |
|
||||
|
||||
## Edits Code Across Your Project
|
||||
@@ -186,7 +182,7 @@ const deployTool = createTool({
|
||||
|
||||
const agent = new Agent({ tools: [deployTool], /* ... */ })
|
||||
```
|
||||
...or use [MCP servers](https://github.com/modelcontextprotocol) to connect to databases, query APIs, manage cloud infrastructure, and interact with external systems. Use [community-built servers](https://github.com/modelcontextprotocol/servers) or ask Cline to create custom tools on the fly. In the CLI, manage servers with `cline mcp`.
|
||||
...or use [MCPs](https://github.com/modelcontextprotocol) to connect to databases, query APIs, manage cloud infrastructure, and interact with external systems. Use [community-built servers](https://github.com/modelcontextprotocol/servers) or ask Cline to create custom tools on the fly. In the CLI, manage servers with `cline mcp`.
|
||||
|
||||
## Multi-Agent Teams
|
||||
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
# Cline CLI Changelog
|
||||
|
||||
## 3.0.62
|
||||
|
||||
- Introducing Cline Desktop: a native app for working with open-weight models, with task import from Claude Code and Codex, scheduled runs, web search and voice input, and a marketplace for plugins, MCP servers, and skills. The CLI now shows a one-time startup notice pointing at cline.bot/desktop. At most one notice appears per launch, and `CLINE_DISABLE_CLINE_PASS_NOTICE=1` still suppresses all of them
|
||||
- Agent Plugins are now managed through the Hub. Packages under `~/.agents/plugins/*` are discovered and validated, their skills are exposed through the skills tool as `plugin-name:skill-name`, and their MCP servers start without touching `cline_mcp_settings.json`. The config screen lists them separately from Cline Plugins and Space toggles them. Workspace `.agents/plugins` directories are deliberately not scanned, so opening a repo cannot implicitly start repo-controlled MCP servers
|
||||
- A model turn that dies mid-stream with a transient provider error is now retried up to 3 times with backoff instead of failing the run — a single forwarded 429 from OpenRouter previously ended the run with exit 1. A turn that already streamed output is never retried, so nothing is duplicated
|
||||
- Streaming output is no longer throttled by the Hub. Every streamed token was proxied to client hooks as a round trip carrying a full copy of the session, with the agent loop waiting on it
|
||||
- Checkpoints no longer stall every message in workspaces with large untracked directories. Each turn re-hashed every untracked file before the model call, which on multi-GB workspaces blocked messages for seconds to minutes; a persistent per-session snapshot index now lets git skip unchanged files
|
||||
- Fixed `run_commands` hanging until timeout after a command that backgrounds a child process. The command had finished, but the backgrounded child held the output pipes open
|
||||
- Fixed `cline` being OOM-killed when run from your home directory. Typing an `@` mention indexed every file under `$HOME` and re-ranked it on each keystroke
|
||||
- Fixed `apply_patch` silently overwriting an existing file when the model used "Add File" on a path that already exists
|
||||
- Fixed PowerShell commands that the model wrapped in another `powershell -Command "..."` being parsed twice, which stripped `$_` out of pipelines and produced an error per enumerated item while still reporting success. The tool description now also names which PowerShell edition is in use and tells the model not to wrap commands
|
||||
- API keys pasted with an invisible character (BOM, zero-width space) are now cleaned before being saved. They were stored corrupted and the provider's 401 was indistinguishable from a wrong key
|
||||
- Signing in with Claude Code no longer demands an API key it never reads. It authenticates from the `claude` CLI's own credential store, but onboarding treated it as an API-key provider and dropped you into the sign-in wizard; the workaround was storing a dummy key. A missing `claude` on PATH now warns instead of blocking, since a configured path, bundled binary, or npx also works. OpenCode gets the same local-CLI treatment
|
||||
- Web search is now on by default in non-yolo sessions on models that support it
|
||||
- A running Hub on the same core version as your CLI no longer prompts you to update it. Anyone with both the desktop app and the CLI installed saw a "Cline Hub was updated" dialog on every launch that could never resolve
|
||||
- Scheduled runs no longer stall behind each other — one long turn blocked dispatch of every other schedule. Parallelism limits are now enforced at claim time, work resumed after system sleep is no longer started twice, and a schedule created without a timezone uses your local one instead of an implicit default
|
||||
- Session history no longer goes blank when a session spawns many subagents. Child rows crowded out the roots, hiding the parent session and everything older
|
||||
- Fixed TUI toasts being clipped to their first line. The Hub messages that use them are all longer than that, so the keep-Hub reminder never showed the `cline hub upgrade` command it exists to deliver
|
||||
- Cline Pass now defaults to a subscribed model instead of a free one. Its model list mixes both tiers and the default was whichever model shipped most recently, so subscribers who never picked a model were put on the free tier
|
||||
- Cline Pass and free models now show zero cost instead of the upstream market price for requests you are not billed per token for
|
||||
- Model pickers now fall back to the full Recommended, Free, and Subscribed tiers when the models endpoint is unreachable. Previously the offline fallback was six hardcoded models with no subscribed tier at all
|
||||
- The OpenAI Codex (ChatGPT subscription) model list no longer includes models the backend rejects, and Codex context limits are applied to every Codex model instead of being inherited from the OpenAI API catalog, which was inflating the context budget and the usage math
|
||||
- Model lists for all shared-catalog providers now refresh from the live catalog, so newly published models appear without a CLI update, with timeouts so a hung provider endpoint cannot stall the list
|
||||
- Cline Pass now shows as a configured provider after sign-in — it stores credentials under Cline, so one sign-in configured both but only Cline appeared
|
||||
- Fixed OpenCode Go serving several wire protocols behind one URL while every model was sent over the OpenAI chat-completions adapter
|
||||
- Collapsed a nested `undici@5.29.0` (CVE-2026-1525) onto 7.x. The earlier remediation's version-scoped override key was silently ignored by Bun, so a vulnerable copy survived
|
||||
- Refreshed the model catalog. Adds four providers (Infer by Flow7, Melious, NaN, and Wallaby) and takes the bundled catalog from 5,788 to 6,079 models. This is a wide refresh: the resolved default model changes for 44 providers, most of them landing on DeepSeek V4.1 Flash — among them Hugging Face, Fireworks, Requesty, Nebius, Cortecs, CrossModel, DigitalOcean, Eden AI, and OpenCode Go. Gemini and Vertex now resolve to Gemini 3.8 Flash, GitHub Copilot and Vivgrid to GPT-6 Astra, and NVIDIA to GLM 5.3 Flash. If you use any provider without pinning a model, expect a different default
|
||||
|
||||
## 3.0.61
|
||||
|
||||
- Cline now handles a running Hub that is older than your CLI. Instead of quietly talking to a hub executing stale code, you get a prompt showing how many active sessions a replacement would interrupt, with enter-to-replace or escape-to-keep. The replacement drains the Hub first so in-flight turns finish, and a hub too old or wedged to accept the drain is left alone rather than killed
|
||||
|
||||
+1
-7
@@ -91,12 +91,6 @@ Cline CLI runs in a few different shapes depending on what you need:
|
||||
- Yolo: `cline --yolo "..."` skips approval prompts and exits when the turn finishes
|
||||
- Zen: `cline --zen "..."` fires the task to the background hub daemon and exits immediately (see below)
|
||||
|
||||
### Computer use (experimental)
|
||||
|
||||
Start qbt before the interactive CLI and set `CLINE_COMPUTER_USE_PORT` to its agent port. The computer-user helper requires a configured direct Anthropic provider. Optionally set `CLINE_COMPUTER_USE_BACKEND_COMMAND` to a shell command that starts qbt: this adds `computer_user_restart_backend` for recovery when qbt becomes unreachable, not automatic startup. Set these variables before launching the CLI and restart it after changes.
|
||||
|
||||
See the [computer-use setup and backend recovery command](../../sdk/packages/core/src/extensions/computer-use/README.md#backend-recovery-command) for a Windows example, shell rules, ports, and process ownership.
|
||||
|
||||
## Headless mode for CI/CD
|
||||
|
||||
Run Cline with zero interaction for scripting and automation. Pipe input, get JSON output, chain commands, integrate into CI/CD pipelines.
|
||||
@@ -221,7 +215,7 @@ cline connect --stop
|
||||
cline connect --stop telegram
|
||||
```
|
||||
|
||||
In chat surfaces, connector slash commands include `/help`, `/start`, `/new`, `/clear`, `/whereami`, `/tools`, `/yolo`, `/cd <path>` (also `/cwd <path>`), `/schedule`, `/abort`, and `/exit`. Run `cline connect <adapter> --help` to see the full flag list for any adapter.
|
||||
In chat surfaces, connector slash commands include `/help`, `/start`, `/new`, `/clear`, `/whereami`, `/tools`, `/yolo`, `/cwd <path>`, `/schedule`, `/abort`, and `/exit`. Run `cline connect <adapter> --help` to see the full flag list for any adapter.
|
||||
|
||||
### Schedules
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@cline/cli",
|
||||
"displayName": "cline",
|
||||
"version": "3.0.61",
|
||||
"version": "3.0.62",
|
||||
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
|
||||
"type": "module",
|
||||
"publishConfig": {
|
||||
|
||||
@@ -32,6 +32,9 @@ const BUILD_TIME_INLINED_ENV_VARS = [
|
||||
"OTEL_TELEMETRY_ENABLED",
|
||||
"OTEL_LOGS_EXPORTER",
|
||||
"OTEL_METRICS_EXPORTER",
|
||||
"OTEL_TRACES_EXPORTER",
|
||||
"CLINE_TRACE_SAMPLE_PERCENT",
|
||||
"CLINE_TRACE_RECORD_CONTENT",
|
||||
"OTEL_EXPORTER_OTLP_PROTOCOL",
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT",
|
||||
"OTEL_EXPORTER_OTLP_HEADERS",
|
||||
|
||||
@@ -2,7 +2,8 @@ import {
|
||||
createDiscordAdapter,
|
||||
type DiscordAdapter,
|
||||
} from "@chat-adapter/discord";
|
||||
// TODO: Remove the root Undici 6 override when discord.js no longer requires Undici ^6.27.0.
|
||||
// Note: discord.js@14 declares undici ^6.27.0, but the root package.json
|
||||
// override ("undici": ">=7.29.0 <8") forces undici 7.x for CVE-2026-1525.
|
||||
import type { ChatStartSessionRequest } from "@cline/core";
|
||||
import {
|
||||
createUserInstructionConfigService,
|
||||
|
||||
@@ -57,7 +57,7 @@ The Telegram connector uses the shared connector command parser:
|
||||
- `/whereami` - show thread, cwd, tools, and yolo state
|
||||
- `/tools [on|off|toggle]` - allow or block repo/file/shell tools
|
||||
- `/yolo [on|off|toggle]` - auto-approve tool use
|
||||
- `/cd <path>` or `/cwd <path>` - change working directory
|
||||
- `/cwd <path>` - change working directory
|
||||
- `/schedule create/list/trigger/delete` - manage scheduled workflows
|
||||
- `/abort` - stop the current task
|
||||
- `/exit` - stop the connector
|
||||
|
||||
@@ -1028,7 +1028,7 @@ export async function handleConnectorUserTurn<
|
||||
const { prompt, userImages, userFiles } = await buildUserInputMessage(
|
||||
runtimeInput,
|
||||
input.userInstructionService,
|
||||
{ mode: startRequest.mode, cwd: startRequest.cwd },
|
||||
{ mode: startRequest.mode },
|
||||
);
|
||||
try {
|
||||
await input.client.sendRuntimeSession(
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
// @jsxImportSource @opentui/react
|
||||
import type { ChoiceContext } from "@opentui-ui/dialog";
|
||||
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useDialogPalette } from "../tui/hooks/use-theme";
|
||||
import {
|
||||
type DialogDismissKey,
|
||||
isAnyKeyDismiss,
|
||||
} from "../tui/utils/dialog-keys";
|
||||
import { getCliSubscriptionUrl } from "../utils/cline-pass-errors";
|
||||
import open from "../utils/open";
|
||||
import type { CliMigrationNotice } from "./notice";
|
||||
|
||||
/**
|
||||
* Enter opens the subscription page; any other (unmodified) key dismisses the
|
||||
* Enter opens the notice's page; any other (unmodified) key dismisses the
|
||||
* dialog; modifier-held keys are ignored.
|
||||
*
|
||||
* The dialog used to be dismissible only with Esc, but Esc is the least
|
||||
@@ -20,7 +19,7 @@ import type { CliMigrationNotice } from "./notice";
|
||||
* timeout disambiguation, and Windows console input layers are known to
|
||||
* swallow it), which left users stuck behind the promo with no way out.
|
||||
* Modifier-held keys are ignored so that holding Cmd/Ctrl to click the
|
||||
* subscription link never dismisses the dialog mid-click.
|
||||
* link never dismisses the dialog mid-click.
|
||||
*/
|
||||
export function resolveMigrationNoticeKeyAction(
|
||||
key: DialogDismissKey,
|
||||
@@ -36,27 +35,26 @@ export function MigrationNoticeContent(
|
||||
) {
|
||||
const { dialogId, notice, resolve } = props;
|
||||
const palette = useDialogPalette();
|
||||
const subscriptionUrl = useMemo(() => getCliSubscriptionUrl(), []);
|
||||
const [status, setStatus] = useState<string | undefined>();
|
||||
|
||||
const openSubscriptionPage = useCallback(() => {
|
||||
setStatus("Opening ClinePass in your browser...");
|
||||
void open(subscriptionUrl, { wait: false })
|
||||
const openNoticePage = useCallback(() => {
|
||||
setStatus("Opening in your browser...");
|
||||
void open(notice.url, { wait: false })
|
||||
.then(() => {
|
||||
setStatus("Opened ClinePass in your browser.");
|
||||
setStatus("Opened in your browser.");
|
||||
})
|
||||
.catch(() => {
|
||||
setStatus(
|
||||
"Could not open the browser automatically. Use the URL below.",
|
||||
);
|
||||
});
|
||||
}, [subscriptionUrl]);
|
||||
}, [notice.url]);
|
||||
|
||||
useDialogKeyboard((key) => {
|
||||
const action = resolveMigrationNoticeKeyAction(key);
|
||||
if (action === "ignore") return;
|
||||
if (action === "open") {
|
||||
openSubscriptionPage();
|
||||
openNoticePage();
|
||||
return;
|
||||
}
|
||||
resolve(true);
|
||||
@@ -66,20 +64,20 @@ export function MigrationNoticeContent(
|
||||
<box flexDirection="column" paddingX={1} gap={1}>
|
||||
<text fg={palette.act}>{notice.title}</text>
|
||||
<box flexDirection="column">
|
||||
<text selectable>
|
||||
ClinePass is a $9.99/month subscription plan to get access to the
|
||||
latest open-weight coding models with enough quota for day-to-day
|
||||
work, at a much lower cost than paying API costs directly.
|
||||
</text>
|
||||
{notice.body.split("\n").map((line) => (
|
||||
<text key={line} selectable>
|
||||
{line}
|
||||
</text>
|
||||
))}
|
||||
</box>
|
||||
<box flexDirection="row">
|
||||
<text fg={palette.act} selectable>
|
||||
<a href={subscriptionUrl}>{subscriptionUrl}</a>
|
||||
<a href={notice.url}>{notice.url}</a>
|
||||
</text>
|
||||
</box>
|
||||
<box flexDirection="row">
|
||||
<box paddingX={1} backgroundColor={palette.act}>
|
||||
<text fg={palette.textOnSelection}>Open ClinePass</text>
|
||||
<text fg={palette.textOnSelection}>{notice.openLabel}</text>
|
||||
</box>
|
||||
</box>
|
||||
{status && <text fg={palette.muted}>{status}</text>}
|
||||
|
||||
@@ -55,11 +55,42 @@ describe("migration notice", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not show after the notice is marked as shown", () => {
|
||||
it("does not show after every notice is marked as shown", () => {
|
||||
const dataDir = createTempDataDir();
|
||||
|
||||
markClineCliMigrationNoticeShown(dataDir);
|
||||
markClineCliMigrationNoticeShown(dataDir, "cline-cli-desktop-launch");
|
||||
|
||||
expect(getClineCliMigrationNotice(dataDir)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows the desktop launch notice once the ClinePass intro was shown", () => {
|
||||
const dataDir = createTempDataDir();
|
||||
|
||||
markClineCliMigrationNoticeShown(dataDir);
|
||||
|
||||
const notice = getClineCliMigrationNotice(dataDir);
|
||||
expect(notice?.id).toBe("cline-cli-desktop-launch");
|
||||
expect(notice?.url).toBe("https://cline.bot/desktop");
|
||||
});
|
||||
|
||||
it("shows only one notice per launch", () => {
|
||||
const dataDir = createTempDataDir();
|
||||
|
||||
expect(getClineCliMigrationNotice(dataDir)?.id).toBe(
|
||||
"cline-cli-cline-pass-intro",
|
||||
);
|
||||
});
|
||||
|
||||
it("marks the desktop launch notice as shown by id", () => {
|
||||
const dataDir = createTempDataDir();
|
||||
|
||||
markClineCliMigrationNoticeShown(dataDir);
|
||||
markClineCliMigrationNoticeShown(dataDir, "cline-cli-desktop-launch");
|
||||
|
||||
const rawState = readFileSync(resolveCliNoticeStatePath(dataDir), "utf8");
|
||||
expect(rawState).toContain('"cline-cli-cline-pass-intro": true');
|
||||
expect(rawState).toContain('"cline-cli-desktop-launch": true');
|
||||
expect(getClineCliMigrationNotice(dataDir)).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -85,7 +116,7 @@ describe("migration notice", () => {
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not show when ClinePass is already the active provider", () => {
|
||||
it("does not show the ClinePass intro when ClinePass is already the active provider", () => {
|
||||
const dataDir = createTempDataDir();
|
||||
|
||||
expect(
|
||||
@@ -93,8 +124,8 @@ describe("migration notice", () => {
|
||||
dataDir,
|
||||
{},
|
||||
{ activeProviderId: "cline-pass" },
|
||||
),
|
||||
).toBeUndefined();
|
||||
)?.id,
|
||||
).toBe("cline-cli-desktop-launch");
|
||||
});
|
||||
|
||||
it("suppresses the active ClinePass provider even when the provider id has surrounding whitespace", () => {
|
||||
@@ -141,6 +172,8 @@ describe("migration notice", () => {
|
||||
|
||||
const rawState = readFileSync(resolveCliNoticeStatePath(dataDir), "utf8");
|
||||
expect(rawState).toContain("cline-cli-cline-pass-intro");
|
||||
expect(getClineCliMigrationNotice(dataDir)).toBeUndefined();
|
||||
expect(getClineCliMigrationNotice(dataDir)?.id).not.toBe(
|
||||
"cline-cli-cline-pass-intro",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,20 +1,54 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { resolveClineDataDir } from "@cline/shared/storage";
|
||||
import { getCliSubscriptionUrl } from "../utils/cline-pass-errors";
|
||||
|
||||
const NOTICE_ID = "cline-cli-cline-pass-intro";
|
||||
export const CLINE_PASS_NOTICE_ID = "cline-cli-cline-pass-intro";
|
||||
const DESKTOP_NOTICE_ID = "cline-cli-desktop-launch";
|
||||
const FORCE_NOTICE_ENV = "CLINE_FORCE_CLINE_PASS_NOTICE";
|
||||
// Historically named for the ClinePass promo; disables every startup notice.
|
||||
const DISABLE_NOTICE_ENV = "CLINE_DISABLE_CLINE_PASS_NOTICE";
|
||||
const DESKTOP_APP_URL = "https://cline.bot/desktop";
|
||||
|
||||
export interface CliMigrationNotice {
|
||||
id: string;
|
||||
title: string;
|
||||
body: string;
|
||||
url: string;
|
||||
openLabel: string;
|
||||
}
|
||||
|
||||
export interface CliMigrationNoticeOptions {
|
||||
activeProviderId?: string;
|
||||
}
|
||||
|
||||
function getClinePassNotice(): CliMigrationNotice {
|
||||
return {
|
||||
id: CLINE_PASS_NOTICE_ID,
|
||||
title: "Try ClinePass",
|
||||
body: "ClinePass is a $9.99/month subscription plan to get access to the latest open-weight coding models with enough quota for day-to-day work, at a much lower cost than paying API costs directly.",
|
||||
url: getCliSubscriptionUrl(),
|
||||
openLabel: "Open ClinePass",
|
||||
};
|
||||
}
|
||||
|
||||
function getDesktopNotice(): CliMigrationNotice {
|
||||
return {
|
||||
id: DESKTOP_NOTICE_ID,
|
||||
title: "Introducing Cline Desktop",
|
||||
body: [
|
||||
"A native app for working with open weights models. Use it with ClinePass and our free models, or BYOK.",
|
||||
"- Import tasks from Claude Code and Codex",
|
||||
"- Run Cline on a regular schedule",
|
||||
"- Use web search tool and voice input",
|
||||
"- Browse Marketplace for plugins, MCPs, and skills",
|
||||
"Available for macOS and Windows.",
|
||||
].join("\n"),
|
||||
url: DESKTOP_APP_URL,
|
||||
openLabel: "Get Cline Desktop",
|
||||
};
|
||||
}
|
||||
|
||||
interface CliNoticeState {
|
||||
shown: Record<string, boolean>;
|
||||
}
|
||||
@@ -84,32 +118,33 @@ export function getClineCliMigrationNotice(
|
||||
if (disableNotice && !forceNotice) {
|
||||
return undefined;
|
||||
}
|
||||
// At most one notice per launch, oldest first, so a user who has already
|
||||
// dismissed the ClinePass intro sees the desktop launch on their next start.
|
||||
if (
|
||||
shouldSuppressClineCliMigrationNoticeForActiveProvider(
|
||||
!shouldSuppressClineCliMigrationNoticeForActiveProvider(
|
||||
options.activeProviderId,
|
||||
env,
|
||||
)
|
||||
) &&
|
||||
(forceNotice || !noticeState.shown[CLINE_PASS_NOTICE_ID])
|
||||
) {
|
||||
return undefined;
|
||||
return getClinePassNotice();
|
||||
}
|
||||
if (noticeState.shown[NOTICE_ID] && !forceNotice) {
|
||||
return undefined;
|
||||
if (!noticeState.shown[DESKTOP_NOTICE_ID]) {
|
||||
return getDesktopNotice();
|
||||
}
|
||||
return {
|
||||
id: NOTICE_ID,
|
||||
title: "Try ClinePass",
|
||||
};
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function markClineCliMigrationNoticeShown(
|
||||
dataDir = resolveClineDataDir(),
|
||||
noticeId = CLINE_PASS_NOTICE_ID,
|
||||
): void {
|
||||
const noticePath = resolveCliNoticeStatePath(dataDir);
|
||||
const noticeState = readNoticeState(noticePath);
|
||||
const nextState: CliNoticeState = {
|
||||
shown: {
|
||||
...noticeState.shown,
|
||||
[NOTICE_ID]: true,
|
||||
[noticeId]: true,
|
||||
},
|
||||
};
|
||||
mkdirSync(dirname(noticePath), { recursive: true, mode: 0o700 });
|
||||
|
||||
+14
-49
@@ -165,8 +165,14 @@ vi.mock("./runtime/run-interactive", () => {
|
||||
vi.mock("./utils/session", () => sessionMocks);
|
||||
vi.mock("./session/session", () => sessionMocks);
|
||||
vi.mock("@cline/core", async () => {
|
||||
// Keep dispatch tests independent of the full SDK runtime import graph.
|
||||
// Only persisted-settings behavior needs its real implementation here.
|
||||
const { readGlobalSettings } = await vi.importActual<
|
||||
typeof import("../../../sdk/packages/core/src/services/global-settings")
|
||||
>("../../../sdk/packages/core/src/services/global-settings");
|
||||
return {
|
||||
...(await vi.importActual("@cline/core")),
|
||||
readGlobalSettings,
|
||||
setSdkLogger: vi.fn(),
|
||||
resolveProviderConfig: llmMocks.resolveProviderConfig,
|
||||
createTeamName: vi.fn(() => "team-test"),
|
||||
createUserInstructionConfigService: vi.fn(() => ({
|
||||
@@ -576,53 +582,6 @@ describe("runCli lightweight command dispatch", () => {
|
||||
expect(mockState.runInteractiveImports).toBe(0);
|
||||
});
|
||||
|
||||
it("warns that computer use is unavailable when a prompt argument is used", async () => {
|
||||
const stdout = vi
|
||||
.spyOn(process.stdout, "write")
|
||||
.mockImplementation(() => true);
|
||||
process.env.CLINE_COMPUTER_USE_PORT = "1234";
|
||||
forcePromptModeInput();
|
||||
process.argv = ["bun", "src/index.ts", "say hello"];
|
||||
|
||||
try {
|
||||
const { runCli } = await import("./main");
|
||||
|
||||
await expect(runCli()).resolves.toBeUndefined();
|
||||
expect(stdout).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"computer use is only available in interactive mode",
|
||||
),
|
||||
);
|
||||
expect(runtimeMocks.runAgent).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
delete process.env.CLINE_COMPUTER_USE_PORT;
|
||||
stdout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not warn about computer use in interactive mode", async () => {
|
||||
const stdout = vi
|
||||
.spyOn(process.stdout, "write")
|
||||
.mockImplementation(() => true);
|
||||
process.env.CLINE_COMPUTER_USE_PORT = "1234";
|
||||
process.argv = ["bun", "src/index.ts"];
|
||||
|
||||
try {
|
||||
const { runCli } = await import("./main");
|
||||
|
||||
await expect(runCli()).resolves.toBeUndefined();
|
||||
expect(stdout).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"computer use is only available in interactive mode",
|
||||
),
|
||||
);
|
||||
expect(runtimeMocks.runInteractive).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
delete process.env.CLINE_COMPUTER_USE_PORT;
|
||||
stdout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a single bare positional prompt token", async () => {
|
||||
const consoleError = vi
|
||||
.spyOn(console, "error")
|
||||
@@ -834,6 +793,9 @@ describe("runCli lightweight command dispatch", () => {
|
||||
const notice = {
|
||||
id: "cline-cli-cline-pass-intro",
|
||||
title: "Try ClinePass",
|
||||
body: "ClinePass body",
|
||||
url: "https://app.cline.bot/dashboard/subscription?personal=true",
|
||||
openLabel: "Open ClinePass",
|
||||
};
|
||||
migrationNoticeMocks.getClineCliMigrationNotice.mockReturnValue(notice);
|
||||
process.argv = ["bun", "src/index.ts"];
|
||||
@@ -857,7 +819,7 @@ describe("runCli lightweight command dispatch", () => {
|
||||
await options?.onInitialNoticeShown?.(notice);
|
||||
expect(
|
||||
migrationNoticeMocks.markClineCliMigrationNoticeShown,
|
||||
).toHaveBeenCalledTimes(1);
|
||||
).toHaveBeenCalledWith(undefined, notice.id);
|
||||
});
|
||||
|
||||
it("passes the active ClinePass provider into the migration notice gate", async () => {
|
||||
@@ -1218,6 +1180,9 @@ describe("runCli lightweight command dispatch", () => {
|
||||
migrationNoticeMocks.getClineCliMigrationNotice.mockReturnValue({
|
||||
id: "cline-cli-cline-pass-intro",
|
||||
title: "Try ClinePass",
|
||||
body: "ClinePass body",
|
||||
url: "https://app.cline.bot/dashboard/subscription?personal=true",
|
||||
openLabel: "Open ClinePass",
|
||||
});
|
||||
process.argv = ["bun", "src/index.ts", "history"];
|
||||
|
||||
|
||||
+11
-32
@@ -32,7 +32,6 @@ import {
|
||||
normalizeAutoApproveArgs,
|
||||
resolveWorkspaceRoot,
|
||||
} from "./utils/helpers";
|
||||
import { createMutableUserInstructionConfigService } from "./utils/mutable-user-instruction-service";
|
||||
import {
|
||||
c,
|
||||
installStreamErrorGuards,
|
||||
@@ -916,22 +915,15 @@ export async function runCli(): Promise<void> {
|
||||
});
|
||||
coreServer.setSdkLogger(loggerAdapter.core);
|
||||
|
||||
const createCliUserInstructionService = (location: {
|
||||
cwd: string;
|
||||
workspaceRoot: string;
|
||||
}) =>
|
||||
createUserInstructionConfigService({
|
||||
skills: {
|
||||
workspacePath: location.workspaceRoot,
|
||||
includePluginSkills: true,
|
||||
cwd: location.cwd,
|
||||
},
|
||||
rules: { workspacePath: location.workspaceRoot },
|
||||
workflows: { workspacePath: location.workspaceRoot },
|
||||
});
|
||||
const userInstructionService = createMutableUserInstructionConfigService(
|
||||
createCliUserInstructionService({ cwd, workspaceRoot }),
|
||||
);
|
||||
const userInstructionService = createUserInstructionConfigService({
|
||||
skills: {
|
||||
workspacePath: workspaceRoot,
|
||||
includePluginSkills: true,
|
||||
cwd,
|
||||
},
|
||||
rules: { workspacePath: workspaceRoot },
|
||||
workflows: { workspacePath: workspaceRoot },
|
||||
});
|
||||
await userInstructionService.start().catch(() => {});
|
||||
let userInstructionServiceDisposed = false;
|
||||
const stopUserInstructionService = () => {
|
||||
@@ -998,16 +990,6 @@ export async function runCli(): Promise<void> {
|
||||
(!process.stdin.isTTY && !args.interactive);
|
||||
const isInteractive = (args.interactive || !args.prompt) && !isHeadless;
|
||||
|
||||
// Computer-use is wired only into the interactive runtime, so any other
|
||||
// path yields a session with no `computer` tool. The model then reports
|
||||
// having no such tool, which reads like a backend fault rather than a
|
||||
// consequence of how cline was invoked.
|
||||
if (process.env.CLINE_COMPUTER_USE_PORT?.trim() && !isInteractive) {
|
||||
writeln(
|
||||
`${c.dim}[warn] CLINE_COMPUTER_USE_PORT is set, but computer use is only available in interactive mode, so the "computer" tool will not be registered for this run. Start cline without a prompt argument (and without --yolo/--zen/--output json) to use it.${c.reset}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!apiKey && isOAuthProvider(provider) && !isHeadless && !isInteractive) {
|
||||
const oauthResult = await ensureOAuthProviderApiKey({
|
||||
providerId: provider,
|
||||
@@ -1216,17 +1198,14 @@ export async function runCli(): Promise<void> {
|
||||
activeProviderId: provider,
|
||||
});
|
||||
if (initialNotice) {
|
||||
markInitialNoticeShown = () => {
|
||||
markClineCliMigrationNoticeShown();
|
||||
markInitialNoticeShown = (notice) => {
|
||||
markClineCliMigrationNoticeShown(undefined, notice.id);
|
||||
};
|
||||
}
|
||||
}
|
||||
await runInteractive(config, userInstructionService, resumeSessionId, {
|
||||
initialPrompt: args.prompt,
|
||||
clineApiBaseUrl: initialClineProviderSettings?.baseUrl,
|
||||
explicitSystemPrompt: args.systemPrompt,
|
||||
mutableUserInstructionService: userInstructionService,
|
||||
createUserInstructionService: createCliUserInstructionService,
|
||||
clineProviderSettings: initialClineProviderSettings,
|
||||
startupTarget,
|
||||
initialNotice,
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
abortActiveRuntime,
|
||||
acquireAbortRejectionShield,
|
||||
cleanupActiveRuntime,
|
||||
clearAbortInProgress,
|
||||
isAbortInProgress,
|
||||
markAbortInProgress,
|
||||
setActiveRuntimeAbort,
|
||||
setActiveRuntimeCleanup,
|
||||
} from "./active-runtime";
|
||||
@@ -40,26 +36,4 @@ describe("active runtime hooks", () => {
|
||||
|
||||
expect(() => cleanupActiveRuntime()).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps abort rejection shielding active until overlapping aborts clear", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
markAbortInProgress();
|
||||
const releaseHelperAbort = acquireAbortRejectionShield();
|
||||
expect(isAbortInProgress()).toBe(true);
|
||||
|
||||
clearAbortInProgress();
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
expect(isAbortInProgress()).toBe(true);
|
||||
|
||||
releaseHelperAbort();
|
||||
expect(isAbortInProgress()).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
expect(isAbortInProgress()).toBe(false);
|
||||
} finally {
|
||||
clearAbortInProgress();
|
||||
await vi.runAllTimersAsync();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
let activeRuntimeAbort: (() => void) | undefined;
|
||||
let activeRuntimeCleanup: (() => void) | undefined;
|
||||
let abortGraceTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let abortScopeCount = 0;
|
||||
let abortInProgress = false;
|
||||
let savedRejectionListeners: Array<(...args: unknown[]) => void> | undefined;
|
||||
let activeRuntimeAbortRelease: (() => void) | undefined;
|
||||
|
||||
export function setActiveRuntimeAbort(abortFn: (() => void) | undefined): void {
|
||||
activeRuntimeAbort = abortFn;
|
||||
@@ -36,61 +35,35 @@ export function cleanupActiveRuntime(): void {
|
||||
// correctly (returns finishReason:"aborted"), but orphan rejections from
|
||||
// the streaming layer or hub capability teardown surface as
|
||||
// unhandledRejections and would otherwise crash the CLI.
|
||||
export function acquireAbortRejectionShield(): () => void {
|
||||
abortScopeCount += 1;
|
||||
if (abortScopeCount === 1) {
|
||||
if (abortGraceTimer) {
|
||||
clearTimeout(abortGraceTimer);
|
||||
abortGraceTimer = undefined;
|
||||
}
|
||||
if (!savedRejectionListeners) {
|
||||
// Temporarily replace all unhandledRejection listeners with a
|
||||
// suppressing handler. AbortController.abort() causes orphan promise
|
||||
// rejections in the LLM streaming layer that reach every registered
|
||||
// listener (including OpenTUI's error overlay). Swapping the listeners
|
||||
// is the only way to prevent them from surfacing to the user.
|
||||
savedRejectionListeners = process.rawListeners(
|
||||
"unhandledRejection",
|
||||
) as Array<(...args: unknown[]) => void>;
|
||||
process.removeAllListeners("unhandledRejection");
|
||||
process.on("unhandledRejection", (_reason, promise) => {
|
||||
promise.catch(() => {});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
released = true;
|
||||
releaseAbortRejectionShield();
|
||||
};
|
||||
}
|
||||
|
||||
export function markAbortInProgress(): void {
|
||||
activeRuntimeAbortRelease ??= acquireAbortRejectionShield();
|
||||
if (abortInProgress) {
|
||||
return;
|
||||
}
|
||||
abortInProgress = true;
|
||||
if (abortGraceTimer) {
|
||||
clearTimeout(abortGraceTimer);
|
||||
abortGraceTimer = undefined;
|
||||
}
|
||||
// Temporarily replace all unhandledRejection listeners with a
|
||||
// suppressing handler. AbortController.abort() causes orphan promise
|
||||
// rejections in the LLM streaming layer that reach every registered
|
||||
// listener (including OpenTUI's error overlay). Swapping the listeners
|
||||
// is the only way to prevent them from surfacing to the user.
|
||||
savedRejectionListeners = process.rawListeners("unhandledRejection") as Array<
|
||||
(...args: unknown[]) => void
|
||||
>;
|
||||
process.removeAllListeners("unhandledRejection");
|
||||
process.on("unhandledRejection", (_reason, promise) => {
|
||||
promise.catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAbortInProgress(): void {
|
||||
const release = activeRuntimeAbortRelease;
|
||||
activeRuntimeAbortRelease = undefined;
|
||||
release?.();
|
||||
}
|
||||
|
||||
function releaseAbortRejectionShield(): void {
|
||||
if (abortScopeCount === 0) {
|
||||
return;
|
||||
}
|
||||
abortScopeCount -= 1;
|
||||
if (abortScopeCount > 0) {
|
||||
return;
|
||||
}
|
||||
if (abortGraceTimer) {
|
||||
clearTimeout(abortGraceTimer);
|
||||
}
|
||||
abortGraceTimer = setTimeout(() => {
|
||||
abortInProgress = false;
|
||||
abortGraceTimer = undefined;
|
||||
if (savedRejectionListeners) {
|
||||
process.removeAllListeners("unhandledRejection");
|
||||
@@ -103,5 +76,5 @@ function releaseAbortRejectionShield(): void {
|
||||
}
|
||||
|
||||
export function isAbortInProgress(): boolean {
|
||||
return abortScopeCount > 0 || abortGraceTimer !== undefined;
|
||||
return abortInProgress;
|
||||
}
|
||||
|
||||
@@ -39,15 +39,12 @@ function makeState(config: Config): ChatCommandState {
|
||||
};
|
||||
}
|
||||
|
||||
function makeRuntime(): InteractiveChatCommandRuntime & {
|
||||
changeWorkingDirectory: (next: ChatCommandState) => Promise<void>;
|
||||
} {
|
||||
function makeRuntime(): InteractiveChatCommandRuntime {
|
||||
return {
|
||||
forkCurrentSession: vi.fn(async () => undefined),
|
||||
getActiveSessionId: vi.fn(() => "session-1"),
|
||||
resetForNewSession: vi.fn(async () => {}),
|
||||
restartEmpty: vi.fn(async () => {}),
|
||||
changeWorkingDirectory: vi.fn(async () => {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,7 +62,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
});
|
||||
|
||||
@@ -94,7 +90,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
});
|
||||
|
||||
@@ -121,7 +116,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
});
|
||||
|
||||
@@ -155,7 +149,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
autoApproveAllRef,
|
||||
setInteractiveAutoApprove,
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
});
|
||||
|
||||
@@ -171,72 +164,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
expect(setInteractiveAutoApprove).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("changes the runtime working directory before reporting /cd success", async () => {
|
||||
const config = makeConfig();
|
||||
const state = makeState(config);
|
||||
const runtime = makeRuntime();
|
||||
const target = process.cwd();
|
||||
state.cwd = "/tmp";
|
||||
state.workspaceRoot = "/tmp";
|
||||
vi.mocked(runtime.changeWorkingDirectory).mockImplementation(
|
||||
async (next) => {
|
||||
Object.assign(state, next);
|
||||
},
|
||||
);
|
||||
|
||||
const result = await runInteractiveChatCommand({
|
||||
prompt: `/cd ${target}`,
|
||||
enabled: true,
|
||||
config,
|
||||
host: chatCommandHost,
|
||||
chatCommandState: state,
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
});
|
||||
|
||||
expect(runtime.changeWorkingDirectory).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: target }),
|
||||
);
|
||||
expect(state.cwd).toBe(target);
|
||||
expect(result).toMatchObject({
|
||||
handled: true,
|
||||
turnResult: { commandOutput: expect.stringContaining(`cwd=${target}`) },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not run /cd when the submission is queued behind an active turn", async () => {
|
||||
const config = makeConfig();
|
||||
const state = makeState(config);
|
||||
const runtime = makeRuntime();
|
||||
const target = process.cwd();
|
||||
state.cwd = "/tmp";
|
||||
state.workspaceRoot = "/tmp";
|
||||
|
||||
await expect(
|
||||
runInteractiveChatCommand({
|
||||
prompt: `/cd ${target}`,
|
||||
enabled: true,
|
||||
delivery: "queue",
|
||||
config,
|
||||
host: chatCommandHost,
|
||||
chatCommandState: state,
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Cannot change working directory while a turn is running. Wait for it to finish or abort it first.",
|
||||
);
|
||||
|
||||
expect(runtime.changeWorkingDirectory).not.toHaveBeenCalled();
|
||||
expect(state).toMatchObject({ cwd: "/tmp", workspaceRoot: "/tmp" });
|
||||
});
|
||||
|
||||
it("returns plugin command submit prompts as model input", async () => {
|
||||
const config = makeConfig();
|
||||
const runtime = makeRuntime();
|
||||
@@ -258,7 +185,6 @@ describe("runInteractiveChatCommand", () => {
|
||||
autoApproveAllRef: { current: false },
|
||||
setInteractiveAutoApprove: () => {},
|
||||
sessionRuntime: runtime,
|
||||
changeWorkingDirectory: runtime.changeWorkingDirectory,
|
||||
stop: () => {},
|
||||
onCommandOutput,
|
||||
});
|
||||
|
||||
@@ -39,14 +39,12 @@ function commandTurnResult(commandOutput?: string): InteractiveTurnResult {
|
||||
export async function runInteractiveChatCommand(input: {
|
||||
prompt: string;
|
||||
enabled: boolean;
|
||||
delivery?: "queue" | "steer";
|
||||
config: Config;
|
||||
host: ChatCommandHost;
|
||||
chatCommandState: ChatCommandState;
|
||||
autoApproveAllRef: AutoApproveRef;
|
||||
setInteractiveAutoApprove: (enabled: boolean) => void;
|
||||
sessionRuntime: InteractiveChatCommandRuntime;
|
||||
changeWorkingDirectory: (next: ChatCommandState) => Promise<void>;
|
||||
stop: () => void;
|
||||
onCommandOutput?: (text: string) => void;
|
||||
}): Promise<InteractiveChatCommandResult> {
|
||||
@@ -76,22 +74,10 @@ export async function runInteractiveChatCommand(input: {
|
||||
autoApproveTools: input.autoApproveAllRef.current,
|
||||
}),
|
||||
setState: async (next) => {
|
||||
if (
|
||||
next.cwd !== input.chatCommandState.cwd ||
|
||||
next.workspaceRoot !== input.chatCommandState.workspaceRoot
|
||||
) {
|
||||
// Workspace resources and the replacement session change together at
|
||||
// an immediate submission boundary; deferred prompts cannot replay CLI
|
||||
// commands after the active turn finishes.
|
||||
if (input.delivery) {
|
||||
throw new Error(
|
||||
"Cannot change working directory while a turn is running. Wait for it to finish or abort it first.",
|
||||
);
|
||||
}
|
||||
await input.changeWorkingDirectory(next);
|
||||
} else {
|
||||
Object.assign(input.chatCommandState, next);
|
||||
}
|
||||
input.chatCommandState.enableTools = next.enableTools;
|
||||
input.chatCommandState.autoApproveTools = next.autoApproveTools;
|
||||
input.chatCommandState.cwd = next.cwd;
|
||||
input.chatCommandState.workspaceRoot = next.workspaceRoot;
|
||||
input.setInteractiveAutoApprove(next.autoApproveTools);
|
||||
},
|
||||
reply: async (text) => {
|
||||
|
||||
@@ -1,507 +0,0 @@
|
||||
import {
|
||||
type AddressInfo,
|
||||
createServer,
|
||||
type Server,
|
||||
type Socket,
|
||||
} from "node:net";
|
||||
import type { AgentHooks, AgentResult, AgentToolContext } from "@cline/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Config } from "../../utils/types";
|
||||
import {
|
||||
createInteractiveComputerUser,
|
||||
resolveHelperModelId,
|
||||
withHelperReasoningControls,
|
||||
} from "./computer-user";
|
||||
|
||||
const createCliCoreMock = vi.hoisted(() => vi.fn());
|
||||
const releaseAbortRejectionShieldMock = vi.hoisted(() => vi.fn());
|
||||
const acquireAbortRejectionShieldMock = vi.hoisted(() =>
|
||||
vi.fn(() => releaseAbortRejectionShieldMock),
|
||||
);
|
||||
|
||||
vi.mock("../../session/session", () => ({
|
||||
createCliCore: createCliCoreMock,
|
||||
}));
|
||||
|
||||
vi.mock("../active-runtime", () => ({
|
||||
acquireAbortRejectionShield: acquireAbortRejectionShieldMock,
|
||||
}));
|
||||
|
||||
const toolContext: AgentToolContext = {
|
||||
agentId: "driver-agent",
|
||||
conversationId: "driver-conversation",
|
||||
iteration: 1,
|
||||
};
|
||||
|
||||
/**
|
||||
* Stub qbt backend answering get_display_info, which tool construction
|
||||
* always performs (the backend is the sole source of truth for display
|
||||
* dimensions). Tracks sockets so teardown can force-close the tool's
|
||||
* internal client connection.
|
||||
*/
|
||||
function startStubBackend(): Promise<{
|
||||
server: Server;
|
||||
port: number;
|
||||
destroyConnections: () => void;
|
||||
}> {
|
||||
const sockets = new Set<Socket>();
|
||||
return new Promise((resolve) => {
|
||||
const server = createServer((socket: Socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => sockets.delete(socket));
|
||||
let buffer = "";
|
||||
socket.setEncoding("utf8");
|
||||
socket.on("data", (chunk: string) => {
|
||||
buffer += chunk;
|
||||
let newlineIndex = buffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = buffer.slice(0, newlineIndex);
|
||||
buffer = buffer.slice(newlineIndex + 1);
|
||||
if (line.trim().length > 0) {
|
||||
const request = JSON.parse(line) as { id: number };
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: true,
|
||||
display: { widthPx: 1920, heightPx: 1080 },
|
||||
})}\n`,
|
||||
);
|
||||
}
|
||||
newlineIndex = buffer.indexOf("\n");
|
||||
}
|
||||
});
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address() as AddressInfo;
|
||||
resolve({
|
||||
server,
|
||||
port: address.port,
|
||||
destroyConnections: () => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function makeConfig(): Config {
|
||||
return {
|
||||
cwd: "C:/work",
|
||||
workspaceRoot: "C:/work",
|
||||
} as Config;
|
||||
}
|
||||
|
||||
function makeSettings(settings: Record<string, unknown> | undefined) {
|
||||
return {
|
||||
getProviderSettings: () => settings as never,
|
||||
};
|
||||
}
|
||||
|
||||
function makeResult(overrides: Partial<AgentResult> = {}): AgentResult {
|
||||
return {
|
||||
text: "done",
|
||||
iterations: 1,
|
||||
finishReason: "completed",
|
||||
messages: [],
|
||||
toolCalls: [],
|
||||
usage: { inputTokens: 1, outputTokens: 1 },
|
||||
...overrides,
|
||||
} as AgentResult;
|
||||
}
|
||||
|
||||
describe("createInteractiveComputerUser", () => {
|
||||
let server: Server | undefined;
|
||||
let destroyConnections: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
createCliCoreMock.mockReset();
|
||||
releaseAbortRejectionShieldMock.mockReset();
|
||||
acquireAbortRejectionShieldMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
destroyConnections?.();
|
||||
destroyConnections = undefined;
|
||||
if (!server) {
|
||||
return;
|
||||
}
|
||||
await new Promise<void>((resolve) => server?.close(() => resolve()));
|
||||
server = undefined;
|
||||
});
|
||||
|
||||
it("returns undefined when computer use is not enabled by env", async () => {
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings({ apiKey: "sk-ant-x" }),
|
||||
notifyDriver: () => {},
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when the Anthropic provider has no api key", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings(undefined),
|
||||
notifyDriver: () => {},
|
||||
env: {
|
||||
CLINE_COMPUTER_USE_PORT: String(started.port),
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("exposes the driver tools when enabled and configured", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings({
|
||||
apiKey: "sk-ant-x",
|
||||
model: "claude-sonnet-4-6",
|
||||
}),
|
||||
notifyDriver: () => {},
|
||||
env: {
|
||||
CLINE_COMPUTER_USE_PORT: String(started.port),
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.driverTools.map((tool) => tool.name).sort()).toEqual([
|
||||
"computer_user_interrupt",
|
||||
"computer_user_message",
|
||||
"computer_user_restart",
|
||||
"computer_user_start",
|
||||
"computer_user_status",
|
||||
"computer_user_transcript",
|
||||
]);
|
||||
// The raw computer tool must not be among the driver's tools.
|
||||
expect(result?.driverTools.some((tool) => tool.name === "computer")).toBe(
|
||||
false,
|
||||
);
|
||||
await result?.dispose();
|
||||
});
|
||||
|
||||
it("adds the backend restart tool only when a launch command is configured", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings({
|
||||
apiKey: "sk-ant-x",
|
||||
model: "claude-sonnet-4-6",
|
||||
}),
|
||||
notifyDriver: () => {},
|
||||
env: {
|
||||
CLINE_COMPUTER_USE_PORT: String(started.port),
|
||||
CLINE_COMPUTER_USE_BACKEND_COMMAND: "echo start-the-backend",
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(result).toBeDefined();
|
||||
expect(
|
||||
result?.driverTools
|
||||
.map((tool) => tool.name)
|
||||
.includes("computer_user_restart_backend"),
|
||||
).toBe(true);
|
||||
await result?.dispose();
|
||||
});
|
||||
|
||||
it("keeps transcript session identities across helper replacement", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
const hooks: AgentHooks[] = [];
|
||||
createCliCoreMock.mockResolvedValue({
|
||||
start: vi.fn(async ({ config }: { config: { hooks: AgentHooks } }) => {
|
||||
hooks.push(config.hooks);
|
||||
return { sessionId: `helper-${hooks.length}` };
|
||||
}),
|
||||
send: vi.fn(async () => makeResult()),
|
||||
abort: vi.fn(async () => {}),
|
||||
stop: vi.fn(async () => {}),
|
||||
dispose: vi.fn(async () => {}),
|
||||
});
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings({ apiKey: "sk-ant-x" }),
|
||||
notifyDriver: () => {},
|
||||
env: { CLINE_COMPUTER_USE_PORT: String(started.port) },
|
||||
});
|
||||
expect(result).toBeDefined();
|
||||
if (!result) throw new Error("computer user was not configured");
|
||||
const tool = (name: string) => {
|
||||
const found = result.driverTools.find((tool) => tool.name === name);
|
||||
if (!found) throw new Error(`missing tool ${name}`);
|
||||
return found;
|
||||
};
|
||||
const recordMessage = (hook: AgentHooks, text: string) =>
|
||||
hook.onEvent?.({
|
||||
type: "message-added",
|
||||
snapshot: { agentId: "helper-agent" } as never,
|
||||
message: {
|
||||
id: text,
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text }],
|
||||
createdAt: 0,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await tool("computer_user_start").execute({ task: "first" }, toolContext);
|
||||
await recordMessage(hooks[0], "first");
|
||||
await tool("computer_user_restart").execute({}, toolContext);
|
||||
await tool("computer_user_start").execute(
|
||||
{ task: "second" },
|
||||
toolContext,
|
||||
);
|
||||
await recordMessage(hooks[1], "second");
|
||||
await recordMessage(hooks[0], "late first");
|
||||
const transcript = await tool("computer_user_transcript").execute(
|
||||
{},
|
||||
toolContext,
|
||||
);
|
||||
expect(transcript).toMatchObject({
|
||||
entries: [
|
||||
{ sessionId: "helper-1", text: "first" },
|
||||
{ sessionId: "helper-2", text: "second" },
|
||||
{ sessionId: "helper-1", text: "late first" },
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
await result.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("starts the helper with one moderate adaptive reasoning snapshot", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
const start = vi.fn(
|
||||
async (_input: {
|
||||
config: Record<string, unknown>;
|
||||
interactive: boolean;
|
||||
}) => ({ sessionId: "helper-session" }),
|
||||
);
|
||||
const send = vi.fn(() => new Promise(() => {}));
|
||||
createCliCoreMock.mockResolvedValue({
|
||||
start,
|
||||
send,
|
||||
abort: vi.fn(async () => {}),
|
||||
stop: vi.fn(async () => {}),
|
||||
dispose: vi.fn(async () => {}),
|
||||
});
|
||||
const driverConfig = {
|
||||
...makeConfig(),
|
||||
thinking: true,
|
||||
reasoningEffort: "high" as const,
|
||||
};
|
||||
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: driverConfig,
|
||||
providerSettingsManager: makeSettings({
|
||||
provider: "anthropic",
|
||||
apiKey: "sk-ant-x",
|
||||
model: "claude-sonnet-4-5",
|
||||
client: "openai",
|
||||
protocol: "openai-responses",
|
||||
routingProviderId: "openai-native",
|
||||
reasoning: {
|
||||
enabled: true,
|
||||
effort: "low",
|
||||
budgetTokens: 8192,
|
||||
},
|
||||
}),
|
||||
notifyDriver: () => {},
|
||||
env: {
|
||||
CLINE_COMPUTER_USE_PORT: String(started.port),
|
||||
CLINE_COMPUTER_USER_MODEL: "anthropic/claude-sonnet-5",
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
const startTool = result?.driverTools.find(
|
||||
(tool) => tool.name === "computer_user_start",
|
||||
);
|
||||
|
||||
await startTool?.execute({ task: "inspect the desktop" }, toolContext);
|
||||
|
||||
expect(start).toHaveBeenCalledWith({
|
||||
interactive: true,
|
||||
config: expect.objectContaining({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-5",
|
||||
thinking: true,
|
||||
reasoningEffort: "medium",
|
||||
providerConfig: expect.objectContaining({
|
||||
providerId: "anthropic",
|
||||
modelId: "claude-sonnet-5",
|
||||
thinking: true,
|
||||
reasoningEffort: "medium",
|
||||
clientType: undefined,
|
||||
routingProviderId: undefined,
|
||||
thinkingBudgetTokens: undefined,
|
||||
knownModels: expect.objectContaining({
|
||||
"claude-sonnet-5": expect.objectContaining({
|
||||
reasoningOptions: [
|
||||
{
|
||||
type: "effort",
|
||||
values: ["low", "medium", "high", "xhigh", "max"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
expect(start.mock.calls[0]?.[0]?.config).not.toHaveProperty(
|
||||
"thinkingBudgetTokens",
|
||||
);
|
||||
expect(driverConfig).toMatchObject({
|
||||
thinking: true,
|
||||
reasoningEffort: "high",
|
||||
});
|
||||
await result?.dispose();
|
||||
});
|
||||
|
||||
it("shields abort rejections until the helper run is quiescent", async () => {
|
||||
const started = await startStubBackend();
|
||||
server = started.server;
|
||||
destroyConnections = started.destroyConnections;
|
||||
let resolveSend: ((result: AgentResult) => void) | undefined;
|
||||
const send = vi.fn(
|
||||
() =>
|
||||
new Promise<AgentResult>((resolve) => {
|
||||
resolveSend = resolve;
|
||||
}),
|
||||
);
|
||||
const abort = vi.fn(async () => {});
|
||||
createCliCoreMock.mockResolvedValue({
|
||||
start: vi.fn(async () => ({ sessionId: "helper-session" })),
|
||||
send,
|
||||
abort,
|
||||
stop: vi.fn(async () => {}),
|
||||
dispose: vi.fn(async () => {}),
|
||||
});
|
||||
const result = await createInteractiveComputerUser({
|
||||
config: makeConfig(),
|
||||
providerSettingsManager: makeSettings({ apiKey: "sk-ant-x" }),
|
||||
notifyDriver: () => {},
|
||||
env: {
|
||||
CLINE_COMPUTER_USE_PORT: String(started.port),
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
const byName = new Map(
|
||||
result?.driverTools.map((tool) => [tool.name, tool]) ?? [],
|
||||
);
|
||||
await byName
|
||||
.get("computer_user_start")
|
||||
?.execute({ task: "inspect the desktop" }, toolContext);
|
||||
|
||||
let stopped = false;
|
||||
const interruption = byName
|
||||
.get("computer_user_interrupt")
|
||||
?.execute({ reason: "no progress" }, toolContext) as Promise<unknown>;
|
||||
const observedInterruption = interruption.then((output) => {
|
||||
stopped = true;
|
||||
return output;
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(abort).toHaveBeenCalledWith(
|
||||
"helper-session",
|
||||
expect.objectContaining({ message: "no progress" }),
|
||||
);
|
||||
});
|
||||
expect(acquireAbortRejectionShieldMock).toHaveBeenCalledTimes(1);
|
||||
expect(releaseAbortRejectionShieldMock).not.toHaveBeenCalled();
|
||||
expect(stopped).toBe(false);
|
||||
|
||||
resolveSend?.(makeResult({ finishReason: "aborted" }));
|
||||
await expect(observedInterruption).resolves.toMatchObject({
|
||||
status: "stopped",
|
||||
});
|
||||
expect(releaseAbortRejectionShieldMock).toHaveBeenCalledTimes(1);
|
||||
await result?.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withHelperReasoningControls", () => {
|
||||
it("declares adaptive effort controls for the helper model", () => {
|
||||
const result = withHelperReasoningControls(undefined, "claude-sonnet-5");
|
||||
expect(result["claude-sonnet-5"]).toEqual({
|
||||
id: "claude-sonnet-5",
|
||||
reasoningOptions: [
|
||||
{
|
||||
type: "effort",
|
||||
values: ["low", "medium", "high", "xhigh", "max"],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves other catalog entries and the helper model's own facts", () => {
|
||||
const result = withHelperReasoningControls(
|
||||
{
|
||||
"claude-sonnet-5": {
|
||||
id: "claude-sonnet-5",
|
||||
name: "Claude Sonnet 5",
|
||||
contextWindow: 1000000,
|
||||
},
|
||||
"claude-opus-4-7": { id: "claude-opus-4-7", name: "Claude Opus 4.7" },
|
||||
},
|
||||
"claude-sonnet-5",
|
||||
);
|
||||
expect(result["claude-sonnet-5"]).toMatchObject({
|
||||
name: "Claude Sonnet 5",
|
||||
contextWindow: 1000000,
|
||||
});
|
||||
expect(result["claude-opus-4-7"]).toEqual({
|
||||
id: "claude-opus-4-7",
|
||||
name: "Claude Opus 4.7",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHelperModelId", () => {
|
||||
it("prefers CLINE_COMPUTER_USER_MODEL over saved provider model", () => {
|
||||
expect(
|
||||
resolveHelperModelId({ model: "claude-sonnet-4-6" }, {
|
||||
CLINE_COMPUTER_USER_MODEL: "claude-opus-4-7",
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe("claude-opus-4-7");
|
||||
});
|
||||
|
||||
it("removes the redundant namespace for the direct Anthropic provider", () => {
|
||||
expect(
|
||||
resolveHelperModelId(undefined, {
|
||||
CLINE_COMPUTER_USER_MODEL: "anthropic/claude-sonnet-5",
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe("claude-sonnet-5");
|
||||
});
|
||||
|
||||
it("falls back to the Anthropic provider entry's saved model", () => {
|
||||
expect(
|
||||
resolveHelperModelId(
|
||||
{ model: "claude-haiku-4-5" },
|
||||
{} as NodeJS.ProcessEnv,
|
||||
),
|
||||
).toBe("claude-haiku-4-5");
|
||||
});
|
||||
|
||||
it("defaults when neither env nor settings specify a model", () => {
|
||||
expect(resolveHelperModelId(undefined, {} as NodeJS.ProcessEnv)).toBe(
|
||||
"claude-sonnet-4-6",
|
||||
);
|
||||
expect(
|
||||
resolveHelperModelId({ model: " " }, {
|
||||
CLINE_COMPUTER_USER_MODEL: " ",
|
||||
} as NodeJS.ProcessEnv),
|
||||
).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
});
|
||||
@@ -1,366 +0,0 @@
|
||||
import {
|
||||
type AgentHooks,
|
||||
type ClineCore,
|
||||
COMPUTER_USER_SYSTEM_PROMPT,
|
||||
ComputerBackendRestart,
|
||||
ComputerTaskArtifactRecorder,
|
||||
ComputerUseClient,
|
||||
ComputerUserCoordinator,
|
||||
ComputerUserTranscriptLog,
|
||||
createComputerUserCollaborationTools,
|
||||
createComputerUserDriverTools,
|
||||
createComputerUseTool,
|
||||
createJournalEventSink,
|
||||
createTranscriptRecordingHooks,
|
||||
type ProviderSettingsManager,
|
||||
resolveComputerUseBackendCommandFromEnv,
|
||||
resolveComputerUseTargetFromEnv,
|
||||
toProviderConfig,
|
||||
} from "@cline/core";
|
||||
import type { AgentTool, ModelInfo, ModelReasoningOption } from "@cline/shared";
|
||||
import { nanoid } from "nanoid";
|
||||
import { createCliCore } from "../../session/session";
|
||||
import type { Config } from "../../utils/types";
|
||||
import { acquireAbortRejectionShield } from "../active-runtime";
|
||||
|
||||
/**
|
||||
* CLI host integration for the asynchronous computer user.
|
||||
*
|
||||
* The driver session gets four `computer_user_*` tools; the helper runs as a
|
||||
* dedicated interactive ClineCore session on the Anthropic provider (the
|
||||
* computer-use beta header requires the direct provider — see qwanban's
|
||||
* README). Enabled by the same `CLINE_COMPUTER_USE_PORT` opt-in as the raw
|
||||
* `computer` tool; when the coordinator is active the driver deliberately
|
||||
* does NOT get the raw tool, so all GUI work flows through the helper.
|
||||
*
|
||||
* Helper consistency boundary: provider, credentials, reasoning, tool
|
||||
* inventory, and prompt are resolved here, once, when the runtime starts.
|
||||
* Changing them requires a new CLI session.
|
||||
*/
|
||||
|
||||
const HELPER_PROVIDER_ID = "anthropic";
|
||||
const HELPER_DEFAULT_MODEL_ID = "claude-sonnet-4-6";
|
||||
const HELPER_MODEL_ENV_VAR = "CLINE_COMPUTER_USER_MODEL";
|
||||
const HELPER_REASONING = {
|
||||
thinking: true,
|
||||
reasoningEffort: "medium" as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Reasoning controls declared for the helper's model, in the models.dev
|
||||
* shape the Anthropic provider routing reads. The bundled model catalog
|
||||
* ships without `reasoningOptions`, which the routing treats as an
|
||||
* unlisted model with manual-only thinking and encodes as
|
||||
* `thinking.type.enabled`; current Claude models reject that shape and
|
||||
* require `thinking.type.adaptive` with an effort level. Declaring the
|
||||
* controls here keeps the helper on the adaptive wire shape regardless of
|
||||
* catalog state.
|
||||
*/
|
||||
const HELPER_MODEL_REASONING_OPTIONS: ModelReasoningOption[] = [
|
||||
{ type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },
|
||||
];
|
||||
|
||||
function toDirectAnthropicModelId(modelId: string): string {
|
||||
const directProviderPrefix = `${HELPER_PROVIDER_ID}/`;
|
||||
return modelId.startsWith(directProviderPrefix)
|
||||
? modelId.slice(directProviderPrefix.length)
|
||||
: modelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the provider config's model catalog with the helper's reasoning
|
||||
* controls declared for the helper model, preserving every other entry.
|
||||
*/
|
||||
export function withHelperReasoningControls(
|
||||
knownModels: Record<string, ModelInfo> | undefined,
|
||||
modelId: string,
|
||||
): Record<string, ModelInfo> {
|
||||
return {
|
||||
...knownModels,
|
||||
[modelId]: {
|
||||
...knownModels?.[modelId],
|
||||
id: modelId,
|
||||
reasoningOptions: HELPER_MODEL_REASONING_OPTIONS,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the helper's Anthropic model id. The helper's model is chosen
|
||||
* independently of the driver's: CLINE_COMPUTER_USER_MODEL wins, then the
|
||||
* Anthropic provider entry's saved `model`, then the default. The provider
|
||||
* is always the direct `anthropic` provider — the computer-use beta header
|
||||
* is only sent on that wire target, so Anthropic models reached through
|
||||
* other providers (cline, openrouter, bedrock) would lack the extended
|
||||
* action set.
|
||||
*/
|
||||
export function resolveHelperModelId(
|
||||
helperSettings: { model?: unknown } | undefined,
|
||||
env: NodeJS.ProcessEnv,
|
||||
): string {
|
||||
const fromEnv = env[HELPER_MODEL_ENV_VAR]?.trim();
|
||||
if (fromEnv) {
|
||||
return toDirectAnthropicModelId(fromEnv);
|
||||
}
|
||||
if (
|
||||
typeof helperSettings?.model === "string" &&
|
||||
helperSettings.model.trim()
|
||||
) {
|
||||
return toDirectAnthropicModelId(helperSettings.model.trim());
|
||||
}
|
||||
return HELPER_DEFAULT_MODEL_ID;
|
||||
}
|
||||
|
||||
export interface InteractiveComputerUser {
|
||||
driverTools: AgentTool[];
|
||||
/**
|
||||
* Hooks layer to merge into the driver session's config: records the
|
||||
* driver's transcript and run status to the backend journal alongside
|
||||
* the helper's, so the observatory can flip between both timelines.
|
||||
*/
|
||||
driverRecordingHooks: AgentHooks;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
export async function createInteractiveComputerUser(input: {
|
||||
config: Config;
|
||||
providerSettingsManager: Pick<ProviderSettingsManager, "getProviderSettings">;
|
||||
/**
|
||||
* Injects a prompt into the driver's conversation. Must resolve the
|
||||
* driver session id at call time (session rebuilds change it), which
|
||||
* `sessionRuntime.sendCurrentTurn` does.
|
||||
*/
|
||||
notifyDriver: (prompt: string, delivery: "queue" | "steer") => void;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): Promise<InteractiveComputerUser | undefined> {
|
||||
// Check the local precondition (credentials) before dialing the backend:
|
||||
// tool construction queries the backend for display info and holds a
|
||||
// socket, which would be wasted if the helper cannot be configured.
|
||||
const helperSettings =
|
||||
input.providerSettingsManager.getProviderSettings(HELPER_PROVIDER_ID);
|
||||
const helperApiKey =
|
||||
typeof helperSettings?.apiKey === "string" ? helperSettings.apiKey : "";
|
||||
if (!helperApiKey) {
|
||||
// No silent fallback to the driver's credentials: the helper requires
|
||||
// the Anthropic provider's own configuration.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const target = resolveComputerUseTargetFromEnv(input.env ?? process.env);
|
||||
if (!target) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// One backend client shared by the computer tool and the observability
|
||||
// publisher. The backend serves a single agent connection at a time, so
|
||||
// splitting these across two sockets would make one of them dead.
|
||||
//
|
||||
// No client-side action observer: the backend journals every computer
|
||||
// action (with its screenshot) as it executes it, so recording actions
|
||||
// here too would give the journal two producers for one event type.
|
||||
const computerClient = new ComputerUseClient(target);
|
||||
const recorder = new ComputerTaskArtifactRecorder(
|
||||
`task_${nanoid(10)}`,
|
||||
createJournalEventSink(computerClient),
|
||||
);
|
||||
|
||||
const computerTool = await createComputerUseTool({
|
||||
...target,
|
||||
client: computerClient,
|
||||
});
|
||||
|
||||
// In-process tail of the helper's transcript. The driver's
|
||||
// computer_user_transcript tool reads it, so peeking works even while
|
||||
// the backend is down; the tee shares the recording hooks' reduction, so
|
||||
// what the tool shows is identical to what the observatory journals.
|
||||
const transcriptLog = new ComputerUserTranscriptLog();
|
||||
const backendRestart = (() => {
|
||||
const command = resolveComputerUseBackendCommandFromEnv(
|
||||
input.env ?? process.env,
|
||||
);
|
||||
return command
|
||||
? new ComputerBackendRestart({
|
||||
...target,
|
||||
command,
|
||||
client: computerClient,
|
||||
})
|
||||
: undefined;
|
||||
})();
|
||||
|
||||
const helperModelId = resolveHelperModelId(
|
||||
helperSettings,
|
||||
input.env ?? process.env,
|
||||
);
|
||||
// Helper model and reasoning settings become effective together when this
|
||||
// session is created. Keep the provider config and session config derived
|
||||
// from this snapshot so saved manual thinking budgets cannot conflict with
|
||||
// adaptive thinking on current Claude models. The model's reasoning
|
||||
// controls are declared explicitly: the bundled catalog ships without
|
||||
// them, and without them the Anthropic routing falls back to the manual
|
||||
// thinking shape those models reject.
|
||||
const baseProviderConfig = toProviderConfig({
|
||||
...helperSettings,
|
||||
provider: HELPER_PROVIDER_ID,
|
||||
model: helperModelId,
|
||||
client: undefined,
|
||||
protocol: undefined,
|
||||
routingProviderId: undefined,
|
||||
reasoning: {
|
||||
enabled: HELPER_REASONING.thinking,
|
||||
effort: HELPER_REASONING.reasoningEffort,
|
||||
},
|
||||
});
|
||||
const helperProviderConfig = {
|
||||
...baseProviderConfig,
|
||||
clientType: undefined,
|
||||
routingProviderId: undefined,
|
||||
thinkingBudgetTokens: undefined,
|
||||
knownModels: withHelperReasoningControls(
|
||||
baseProviderConfig.knownModels,
|
||||
helperModelId,
|
||||
),
|
||||
};
|
||||
|
||||
// The helper config and the coordinator reference each other (the
|
||||
// collaboration tools call back into the coordinator). Break the cycle
|
||||
// with one shared extraTools array: the coordinator captures the config
|
||||
// object now; the tools are pushed into the same array below, before any
|
||||
// session can start.
|
||||
const helperExtraTools: AgentTool[] = [computerTool];
|
||||
const helperConfig = {
|
||||
providerId: helperProviderConfig.providerId,
|
||||
modelId: helperProviderConfig.modelId,
|
||||
apiKey: helperProviderConfig.apiKey,
|
||||
baseUrl: helperProviderConfig.baseUrl,
|
||||
headers: helperProviderConfig.headers,
|
||||
knownModels: helperProviderConfig.knownModels,
|
||||
providerConfig: helperProviderConfig,
|
||||
...HELPER_REASONING,
|
||||
cwd: input.config.cwd,
|
||||
workspaceRoot: input.config.workspaceRoot?.trim() || input.config.cwd,
|
||||
mode: "act" as const,
|
||||
enableTools: true,
|
||||
enableSpawnAgent: false,
|
||||
enableAgentTeams: false,
|
||||
pluginPaths: [],
|
||||
systemPrompt: COMPUTER_USER_SYSTEM_PROMPT,
|
||||
extraTools: helperExtraTools,
|
||||
toolPolicies: {
|
||||
// Questions and completion go to the driver through the
|
||||
// collaboration tools, never to a human or generic completion.
|
||||
ask_question: { enabled: false },
|
||||
submit_and_exit: { enabled: false },
|
||||
},
|
||||
// The helper's terminal tools are ask_driver/finish_computer_task
|
||||
// (extraTools with completesRun). Require them explicitly: the
|
||||
// builder's inference only recognizes submit_and_exit, which is
|
||||
// disabled above, and a run that ends in free-form text would leave
|
||||
// the driver waiting with no report.
|
||||
completionPolicy: { requireCompletionTool: true },
|
||||
};
|
||||
|
||||
// Lazy: the helper ClineCore spawns only when the driver first delegates.
|
||||
// forceLocalBackend keeps the helper in this process, where the
|
||||
// computer-use backend's loopback socket is reachable — a hub daemon may
|
||||
// run on a different machine from the controlled display.
|
||||
let helperCorePromise: Promise<ClineCore> | undefined;
|
||||
let activeHelperSend: Promise<unknown> | undefined;
|
||||
const getHelperCore = () => {
|
||||
helperCorePromise ??= createCliCore({
|
||||
forceLocalBackend: true,
|
||||
cwd: input.config.cwd,
|
||||
workspaceRoot: input.config.workspaceRoot,
|
||||
logger: input.config.logger,
|
||||
}).catch((error) => {
|
||||
helperCorePromise = undefined;
|
||||
throw error;
|
||||
});
|
||||
return helperCorePromise;
|
||||
};
|
||||
|
||||
const coordinator = new ComputerUserCoordinator({
|
||||
host: {
|
||||
start: async (startInput) => {
|
||||
// Each session owns its recording source, so late events from a
|
||||
// stopped helper cannot be relabelled as its replacement's work.
|
||||
const source = {
|
||||
kind: "computer_user" as const,
|
||||
sessionId: undefined as string | undefined,
|
||||
};
|
||||
const started = await (await getHelperCore()).start({
|
||||
config: {
|
||||
...startInput.config,
|
||||
hooks: createTranscriptRecordingHooks(recorder, source, (event) =>
|
||||
transcriptLog.append(event),
|
||||
),
|
||||
} as never,
|
||||
interactive: startInput.interactive,
|
||||
});
|
||||
source.sessionId = started.sessionId;
|
||||
return started;
|
||||
},
|
||||
send: async (sendInput) => {
|
||||
const send = (await getHelperCore()).send(sendInput);
|
||||
if (sendInput.delivery === "steer") {
|
||||
return await send;
|
||||
}
|
||||
activeHelperSend = send;
|
||||
try {
|
||||
return await send;
|
||||
} finally {
|
||||
if (activeHelperSend === send) {
|
||||
activeHelperSend = undefined;
|
||||
}
|
||||
}
|
||||
},
|
||||
abort: async (sessionId, reason) => {
|
||||
const releaseAbortShield = acquireAbortRejectionShield();
|
||||
try {
|
||||
await (await getHelperCore()).abort(sessionId, reason);
|
||||
} catch (error) {
|
||||
releaseAbortShield();
|
||||
throw error;
|
||||
}
|
||||
const abortedSend = activeHelperSend;
|
||||
if (!abortedSend) {
|
||||
releaseAbortShield();
|
||||
return;
|
||||
}
|
||||
// The coordinator owns waiting for this run to settle. The adapter
|
||||
// only keeps expected provider cancellation rejections shielded for
|
||||
// the same interval, without making disposal wait on host teardown.
|
||||
void abortedSend.finally(releaseAbortShield).catch(() => {});
|
||||
},
|
||||
stop: async (sessionId) => (await getHelperCore()).stop(sessionId),
|
||||
},
|
||||
helperConfig,
|
||||
notifyDriver: ({ prompt, delivery }) =>
|
||||
input.notifyDriver(prompt, delivery),
|
||||
recorder,
|
||||
transcriptLog,
|
||||
});
|
||||
helperExtraTools.push(...createComputerUserCollaborationTools(coordinator));
|
||||
|
||||
return {
|
||||
driverTools: createComputerUserDriverTools(coordinator, {
|
||||
backendRestart,
|
||||
}),
|
||||
driverRecordingHooks: createTranscriptRecordingHooks(recorder, {
|
||||
kind: "driver",
|
||||
}),
|
||||
dispose: async () => {
|
||||
await coordinator.dispose().catch(() => {});
|
||||
if (helperCorePromise) {
|
||||
const core = await helperCorePromise.catch(() => undefined);
|
||||
await core?.dispose().catch(() => {});
|
||||
}
|
||||
// Push any queued journal publishes out before dropping the
|
||||
// backend connection.
|
||||
await recorder.flush().catch(() => {});
|
||||
computerClient.close();
|
||||
// Release a backend this process spawned; a backend someone else
|
||||
// owns is left running.
|
||||
await backendRestart?.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -270,37 +270,4 @@ describe("applyInteractiveModeConfig", () => {
|
||||
expect(config.extraTools).toEqual([]);
|
||||
expect(config.systemPrompt).toBe("system prompt for act");
|
||||
});
|
||||
|
||||
it("keeps persistent extra tools across plan/act switches", async () => {
|
||||
const config = makeConfig();
|
||||
const computerUserTool = {
|
||||
...switchToActModeTool,
|
||||
name: "computer_user_start",
|
||||
};
|
||||
const persistentExtraTools = [computerUserTool];
|
||||
|
||||
await applyInteractiveModeConfig({
|
||||
config,
|
||||
mode: "plan",
|
||||
switchToActModeTool,
|
||||
persistentExtraTools,
|
||||
});
|
||||
expect(config.extraTools).toEqual([switchToActModeTool, computerUserTool]);
|
||||
|
||||
await applyInteractiveModeConfig({
|
||||
config,
|
||||
mode: "act",
|
||||
switchToActModeTool,
|
||||
persistentExtraTools,
|
||||
});
|
||||
expect(config.extraTools).toEqual([computerUserTool]);
|
||||
|
||||
await applyInteractiveModeConfig({
|
||||
config,
|
||||
mode: "plan",
|
||||
switchToActModeTool,
|
||||
persistentExtraTools,
|
||||
});
|
||||
expect(config.extraTools).toEqual([switchToActModeTool, computerUserTool]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,30 +115,14 @@ export {
|
||||
type ModeSwitchNotice,
|
||||
} from "@cline/shared";
|
||||
|
||||
/**
|
||||
* Builds the extraTools list for an interactive mode. The single derivation
|
||||
* used both at startup and on every mode switch, so mode-independent tools
|
||||
* (e.g. the computer-user tools) cannot be silently dropped by a switch.
|
||||
*/
|
||||
export function buildInteractiveExtraTools(input: {
|
||||
mode: InteractiveUiMode;
|
||||
switchToActModeTool: NonNullable<Config["extraTools"]>[number];
|
||||
persistentExtraTools?: NonNullable<Config["extraTools"]>;
|
||||
}): NonNullable<Config["extraTools"]> {
|
||||
return [
|
||||
...(input.mode === "plan" ? [input.switchToActModeTool] : []),
|
||||
...(input.persistentExtraTools ?? []),
|
||||
];
|
||||
}
|
||||
|
||||
export async function applyInteractiveModeConfig(input: {
|
||||
config: Config;
|
||||
mode: InteractiveUiMode;
|
||||
switchToActModeTool: NonNullable<Config["extraTools"]>[number];
|
||||
persistentExtraTools?: NonNullable<Config["extraTools"]>;
|
||||
}): Promise<void> {
|
||||
input.config.mode = input.mode;
|
||||
input.config.extraTools = buildInteractiveExtraTools(input);
|
||||
input.config.extraTools =
|
||||
input.mode === "plan" ? [input.switchToActModeTool] : [];
|
||||
input.config.systemPrompt = await resolveSystemPrompt({
|
||||
cwd: input.config.cwd,
|
||||
providerId: input.config.providerId,
|
||||
|
||||
@@ -22,7 +22,6 @@ const subscribeToPendingPromptEventsMock = vi.hoisted(() => vi.fn());
|
||||
const markAbortInProgressMock = vi.hoisted(() => vi.fn());
|
||||
const submitAndExitInTerminalMock = vi.hoisted(() => vi.fn());
|
||||
const createInteractiveExitSummaryMock = vi.hoisted(() => vi.fn());
|
||||
const resolveSystemPromptMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../../session/session", () => ({
|
||||
createCliCore: createCliCoreMock,
|
||||
@@ -48,10 +47,6 @@ vi.mock("../active-runtime", () => ({
|
||||
markAbortInProgress: markAbortInProgressMock,
|
||||
}));
|
||||
|
||||
vi.mock("../prompt", () => ({
|
||||
resolveSystemPrompt: resolveSystemPromptMock,
|
||||
}));
|
||||
|
||||
vi.mock("../session-events", () => ({
|
||||
subscribeToAgentEvents: subscribeToAgentEventsMock,
|
||||
subscribeToPendingPromptEvents: subscribeToPendingPromptEventsMock,
|
||||
@@ -238,12 +233,10 @@ describe("createInteractiveSessionRuntime", () => {
|
||||
markAbortInProgressMock.mockReset();
|
||||
submitAndExitInTerminalMock.mockReset();
|
||||
createInteractiveExitSummaryMock.mockReset();
|
||||
resolveSystemPromptMock.mockReset();
|
||||
createRuntimeHooksMock.mockReturnValue({
|
||||
hooks: undefined,
|
||||
shutdown: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
resolveSystemPromptMock.mockResolvedValue("rebuilt system prompt");
|
||||
loadInteractiveResumeMessagesMock.mockResolvedValue([]);
|
||||
subscribeToAgentEventsMock.mockReturnValue(() => {});
|
||||
subscribeToPendingPromptEventsMock.mockReturnValue(() => {});
|
||||
@@ -594,107 +587,6 @@ describe("createInteractiveSessionRuntime", () => {
|
||||
expect(runtime.getActiveSessionId()).toBe("session-restarted");
|
||||
});
|
||||
|
||||
it("restarts the active session with one working-directory snapshot", async () => {
|
||||
const manager = makeManager();
|
||||
const config = createConfig();
|
||||
const state = createChatCommandState(config);
|
||||
createCliCoreMock.mockResolvedValue(manager);
|
||||
const { createInteractiveSessionRuntime } = await importRuntime();
|
||||
const runtime = createInteractiveSessionRuntime({
|
||||
config,
|
||||
providerSettingsManager: createProviderSettingsManager(),
|
||||
explicitSystemPrompt: "custom prompt",
|
||||
chatCommandState: state,
|
||||
requestToolApproval: vi.fn(),
|
||||
resolveToolPolicy: () => ({ autoApprove: true }),
|
||||
askQuestionRef: { current: null },
|
||||
resolveMistakeLimitDecision: undefined,
|
||||
switchToActModeTool: {} as never,
|
||||
onAgentEvent: vi.fn(),
|
||||
onTeamEvent: vi.fn(),
|
||||
onPendingPrompts: vi.fn(),
|
||||
onPendingPromptSubmitted: vi.fn(),
|
||||
});
|
||||
|
||||
await runtime.ensureReady();
|
||||
await runtime.changeWorkingDirectory({
|
||||
...state,
|
||||
cwd: "/tmp/next-project",
|
||||
workspaceRoot: "/tmp/next-project",
|
||||
});
|
||||
|
||||
expect(resolveSystemPromptMock).toHaveBeenCalledWith({
|
||||
cwd: "/tmp/next-project",
|
||||
explicitSystemPrompt: "custom prompt",
|
||||
providerId: "anthropic",
|
||||
mode: "act",
|
||||
});
|
||||
expect(config).toMatchObject({
|
||||
cwd: "/tmp/next-project",
|
||||
workspaceRoot: "/tmp/next-project",
|
||||
systemPrompt: "rebuilt system prompt",
|
||||
});
|
||||
expect(state).toMatchObject({
|
||||
cwd: "/tmp/next-project",
|
||||
workspaceRoot: "/tmp/next-project",
|
||||
});
|
||||
expect(manager.stop).toHaveBeenCalledWith("session-1");
|
||||
expect(manager.start).toHaveBeenCalledTimes(2);
|
||||
expect(manager.start.mock.calls[1]?.[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
cwd: "/tmp/next-project",
|
||||
workspaceRoot: "/tmp/next-project",
|
||||
systemPrompt: "rebuilt system prompt",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(createRuntimeHooksMock).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
cwd: "/tmp/next-project",
|
||||
workspaceRoot: "/tmp/next-project",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("restores the previous working-directory snapshot when restart fails", async () => {
|
||||
const manager = makeManager();
|
||||
const config = createConfig();
|
||||
const state = createChatCommandState(config);
|
||||
const runtime = await makeRuntime(manager, { config });
|
||||
|
||||
await runtime.ensureReady();
|
||||
manager.start.mockRejectedValueOnce(new Error("replacement failed"));
|
||||
|
||||
await expect(
|
||||
runtime.changeWorkingDirectory({
|
||||
...state,
|
||||
cwd: "/tmp/failed-project",
|
||||
workspaceRoot: "/tmp/failed-project",
|
||||
}),
|
||||
).rejects.toThrow("replacement failed");
|
||||
expect(config).toMatchObject({
|
||||
cwd: "/tmp/project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
systemPrompt: "system",
|
||||
});
|
||||
expect(state).toMatchObject({
|
||||
cwd: "/tmp/project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
});
|
||||
expect(manager.start).toHaveBeenCalledTimes(3);
|
||||
expect(manager.start.mock.calls[2]?.[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
sessionId: "session-1",
|
||||
cwd: "/tmp/project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(runtime.getActiveSessionId()).toBe("session-2");
|
||||
});
|
||||
|
||||
it("adds a live interactive approval policy hook to started sessions", async () => {
|
||||
const manager = makeManager();
|
||||
const upstreamBeforeTool = vi.fn(async () => ({
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { basename } from "node:path";
|
||||
import {
|
||||
type AgentEvent,
|
||||
type AgentHooks,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
type CoreSettingsToggleInput,
|
||||
createSessionCompactionState,
|
||||
isSessionNotFoundError,
|
||||
mergeAgentHooks,
|
||||
type PendingPromptMutationResult,
|
||||
type ProviderSettingsManager,
|
||||
projectSessionCompactionState,
|
||||
@@ -33,7 +31,6 @@ import { setActiveCliSession } from "../../utils/output";
|
||||
import { loadInteractiveResumeMessages } from "../../utils/resume";
|
||||
import type { Config } from "../../utils/types";
|
||||
import { markAbortInProgress } from "../active-runtime";
|
||||
import { resolveSystemPrompt } from "../prompt";
|
||||
import type {
|
||||
PendingPromptSnapshot,
|
||||
PendingPromptSubmittedEvent,
|
||||
@@ -100,7 +97,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
config: Config;
|
||||
providerSettingsManager: ProviderSettingsManager;
|
||||
userInstructionService?: UserInstructionConfigService;
|
||||
explicitSystemPrompt?: string;
|
||||
resumeSessionId?: string;
|
||||
chatCommandState: ChatCommandState;
|
||||
requestToolApproval: (
|
||||
@@ -110,17 +106,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
askQuestionRef: AskQuestionRef;
|
||||
resolveMistakeLimitDecision: Config["onConsecutiveMistakeLimitReached"];
|
||||
switchToActModeTool: NonNullable<Config["extraTools"]>[number];
|
||||
/**
|
||||
* Mode-independent extra tools (e.g. the computer-user tools) that must
|
||||
* survive plan/act switches. Rebuilt into config.extraTools on every
|
||||
* mode change alongside the mode-dependent switch tool.
|
||||
*/
|
||||
persistentExtraTools?: NonNullable<Config["extraTools"]>;
|
||||
/**
|
||||
* Host-supplied hooks layer (e.g. computer-use transcript recording)
|
||||
* merged after the runtime's own hooks on every session build.
|
||||
*/
|
||||
extraAgentHooks?: AgentHooks;
|
||||
onAgentEvent: (event: AgentEvent) => void;
|
||||
onTeamEvent: (event: TeamEvent) => void;
|
||||
onPendingPrompts: (event: PendingPromptSnapshot) => void;
|
||||
@@ -145,20 +130,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
|
||||
let pendingResumeSessionId = input.resumeSessionId?.trim() || undefined;
|
||||
|
||||
const createWorkspaceRuntimeHooks = (
|
||||
manager: CliCore,
|
||||
workspace: Pick<ChatCommandState, "cwd" | "workspaceRoot">,
|
||||
): RuntimeHooks =>
|
||||
createRuntimeHooks({
|
||||
verbose: input.config.verbose,
|
||||
yolo: input.config.mode === "yolo",
|
||||
cwd: workspace.cwd,
|
||||
workspaceRoot: workspace.workspaceRoot,
|
||||
dispatchHookEvent: async (payload) => {
|
||||
await manager.ingestHookEvent(payload);
|
||||
},
|
||||
});
|
||||
|
||||
const clearActiveSession = (): void => {
|
||||
activeSessionId = "";
|
||||
setActiveCliSession(undefined);
|
||||
@@ -208,7 +179,15 @@ export function createInteractiveSessionRuntime(input: {
|
||||
throw new Error("interactive runtime shutdown requested");
|
||||
}
|
||||
sessionManager = manager;
|
||||
runtimeHooks = createWorkspaceRuntimeHooks(manager, input.chatCommandState);
|
||||
runtimeHooks = createRuntimeHooks({
|
||||
verbose: input.config.verbose,
|
||||
yolo: input.config.mode === "yolo",
|
||||
cwd: input.config.cwd,
|
||||
workspaceRoot: input.config.workspaceRoot,
|
||||
dispatchHookEvent: async (payload) => {
|
||||
await manager.ingestHookEvent(payload);
|
||||
},
|
||||
});
|
||||
unsubscribeAgent = subscribeToAgentEvents(manager, input.onAgentEvent);
|
||||
unsubscribePendingPrompts = subscribeToPendingPromptEvents(manager, {
|
||||
onPendingPrompts: input.onPendingPrompts,
|
||||
@@ -222,7 +201,7 @@ export function createInteractiveSessionRuntime(input: {
|
||||
throw new Error("interactive runtime hooks are unavailable");
|
||||
}
|
||||
const hooks = withInteractiveApprovalPolicyHook(
|
||||
mergeAgentHooks([runtimeHooks.hooks, input.extraAgentHooks]),
|
||||
runtimeHooks.hooks,
|
||||
input.resolveToolPolicy,
|
||||
);
|
||||
return buildInteractiveSessionConfig({
|
||||
@@ -462,14 +441,14 @@ export function createInteractiveSessionRuntime(input: {
|
||||
messages: MessageWithMetadata[],
|
||||
sessionMetadata?: Record<string, unknown>,
|
||||
initialCompactionState?: SessionCompactionState,
|
||||
options?: { preserveSessionId?: boolean; sessionId?: string },
|
||||
options?: { preserveSessionId?: boolean },
|
||||
): Promise<void> => {
|
||||
// Config-only restarts (model/mode/account changes) continue the same
|
||||
// conversation, so they must keep the session id — otherwise each
|
||||
// restart mints a new session history entry for the same conversation.
|
||||
const reuseSessionId =
|
||||
options?.sessionId ??
|
||||
(options?.preserveSessionId ? activeSessionId || undefined : undefined);
|
||||
const reuseSessionId = options?.preserveSessionId
|
||||
? activeSessionId || undefined
|
||||
: undefined;
|
||||
sessionStartGeneration += 1;
|
||||
pendingResumeSessionId = undefined;
|
||||
startupError = undefined;
|
||||
@@ -532,99 +511,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
);
|
||||
};
|
||||
|
||||
const changeWorkingDirectory = async (
|
||||
next: ChatCommandState,
|
||||
): Promise<void> => {
|
||||
await ensureReady();
|
||||
const manager = sessionManager;
|
||||
if (!manager) {
|
||||
throw new Error("interactive session manager is unavailable");
|
||||
}
|
||||
const sourceSessionId = activeSessionId;
|
||||
|
||||
const [{ messages, status }, compactionState, systemPrompt] =
|
||||
await Promise.all([
|
||||
readCurrentMessages(),
|
||||
readCurrentCompactionState(),
|
||||
resolveSystemPrompt({
|
||||
cwd: next.cwd,
|
||||
explicitSystemPrompt: input.explicitSystemPrompt,
|
||||
providerId: input.config.providerId,
|
||||
mode: input.config.mode,
|
||||
}),
|
||||
]);
|
||||
if (status !== "read" || activeSessionId !== sourceSessionId) {
|
||||
throw new Error("Working directory changed concurrently. Try /cd again.");
|
||||
}
|
||||
|
||||
const previousState = { ...input.chatCommandState };
|
||||
const previousSessionId = activeSessionId;
|
||||
const previousConfig = {
|
||||
cwd: input.config.cwd,
|
||||
workspaceRoot: input.config.workspaceRoot,
|
||||
systemPrompt: input.config.systemPrompt,
|
||||
extensionContext: input.config.extensionContext,
|
||||
};
|
||||
const previousRuntimeHooks = runtimeHooks;
|
||||
const nextRuntimeHooks = createWorkspaceRuntimeHooks(manager, next);
|
||||
const projectedMessages = compactionState
|
||||
? projectSessionCompactionState(compactionState, messages)
|
||||
: undefined;
|
||||
const initialCompactionState = projectedMessages
|
||||
? createSessionCompactionState({
|
||||
sourceMessages: messages,
|
||||
compactedMessages: projectedMessages,
|
||||
systemPrompt: compactionState?.system_prompt,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
// The directory becomes effective as one snapshot for the replacement
|
||||
// session. A concurrent ensureReady() waits on the restart barrier.
|
||||
Object.assign(input.chatCommandState, next);
|
||||
input.config.cwd = next.cwd;
|
||||
input.config.workspaceRoot = next.workspaceRoot;
|
||||
input.config.systemPrompt = systemPrompt;
|
||||
if (input.config.extensionContext?.workspace) {
|
||||
input.config.extensionContext = {
|
||||
...input.config.extensionContext,
|
||||
workspace: {
|
||||
...input.config.extensionContext.workspace,
|
||||
rootPath: next.workspaceRoot,
|
||||
cwd: next.cwd,
|
||||
workspaceName: basename(next.cwd),
|
||||
},
|
||||
};
|
||||
}
|
||||
runtimeHooks = nextRuntimeHooks;
|
||||
|
||||
try {
|
||||
await restartWithMessages(messages, undefined, initialCompactionState, {
|
||||
preserveSessionId: true,
|
||||
});
|
||||
} catch (error) {
|
||||
Object.assign(input.chatCommandState, previousState);
|
||||
input.config.cwd = previousConfig.cwd;
|
||||
input.config.workspaceRoot = previousConfig.workspaceRoot;
|
||||
input.config.systemPrompt = previousConfig.systemPrompt;
|
||||
input.config.extensionContext = previousConfig.extensionContext;
|
||||
runtimeHooks = previousRuntimeHooks;
|
||||
await nextRuntimeHooks.shutdown().catch(() => {});
|
||||
try {
|
||||
await restartWithMessages(messages, undefined, initialCompactionState, {
|
||||
sessionId: previousSessionId || undefined,
|
||||
});
|
||||
} catch (recoveryError) {
|
||||
throw new AggregateError(
|
||||
[error, recoveryError],
|
||||
"Working directory change failed, and the previous session could not be restored.",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await previousRuntimeHooks?.shutdown().catch(() => {});
|
||||
};
|
||||
|
||||
const updateCurrentSessionConnection = async (
|
||||
update: SessionConnectionUpdate,
|
||||
): Promise<void> => {
|
||||
@@ -661,7 +547,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
config: input.config,
|
||||
mode,
|
||||
switchToActModeTool: input.switchToActModeTool,
|
||||
persistentExtraTools: input.persistentExtraTools,
|
||||
});
|
||||
await restartWithCurrentMessages();
|
||||
};
|
||||
@@ -1025,7 +910,6 @@ export function createInteractiveSessionRuntime(input: {
|
||||
resetForNewSession,
|
||||
restartWithMessages,
|
||||
restartWithCurrentMessages,
|
||||
changeWorkingDirectory,
|
||||
updateCurrentSessionConnection,
|
||||
resumeSession,
|
||||
forkCurrentSession,
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
createUserInstructionConfigService,
|
||||
type UserInstructionConfigService,
|
||||
} from "@cline/core";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createChatCommandHost } from "../../utils/chat-commands";
|
||||
import { createMutableUserInstructionConfigService } from "../../utils/mutable-user-instruction-service";
|
||||
import type { WorkspaceChatCommandHostResult } from "../../utils/plugin-chat-commands";
|
||||
import { createInteractiveWorkspaceResources } from "./workspace-resources";
|
||||
|
||||
describe("interactive workspace resources", () => {
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
tempRoots.map((dir) => rm(dir, { recursive: true, force: true })),
|
||||
);
|
||||
tempRoots.length = 0;
|
||||
});
|
||||
|
||||
async function createWorkspace(commandName: string): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), "cli-workspace-resources-"));
|
||||
tempRoots.push(root);
|
||||
const workflows = join(root, "workflows");
|
||||
await mkdir(workflows, { recursive: true });
|
||||
await writeFile(
|
||||
join(workflows, `${commandName}.md`),
|
||||
`---\nname: ${commandName}\n---\nRun ${commandName}.`,
|
||||
);
|
||||
return root;
|
||||
}
|
||||
|
||||
function createInstructionService(cwd: string): UserInstructionConfigService {
|
||||
return createUserInstructionConfigService({
|
||||
skills: { directories: [] },
|
||||
rules: { directories: [] },
|
||||
workflows: { directories: [join(cwd, "workflows")] },
|
||||
});
|
||||
}
|
||||
|
||||
function createPluginResult(
|
||||
commandName: string,
|
||||
shutdown = vi.fn(async () => {}),
|
||||
): WorkspaceChatCommandHostResult {
|
||||
return {
|
||||
host: createChatCommandHost().register("command", {
|
||||
names: [`/${commandName}`],
|
||||
run: async (_parsed, context) => {
|
||||
await context.reply(commandName);
|
||||
},
|
||||
}),
|
||||
pluginSlashCommands: [{ name: commandName }],
|
||||
shutdown,
|
||||
};
|
||||
}
|
||||
|
||||
it("commits workflow expansion and plugin commands as one workspace snapshot", async () => {
|
||||
const workspaceA = await createWorkspace("workflow-a");
|
||||
const workspaceB = await createWorkspace("workflow-b");
|
||||
const initialService = createInstructionService(workspaceA);
|
||||
await initialService.start();
|
||||
const mutableService =
|
||||
createMutableUserInstructionConfigService(initialService);
|
||||
const onCommandsChanged = vi.fn();
|
||||
const resources = createInteractiveWorkspaceResources({
|
||||
initialLocation: { cwd: workspaceA, workspaceRoot: workspaceA },
|
||||
userInstructionService: mutableService,
|
||||
createUserInstructionService: ({ cwd }) => createInstructionService(cwd),
|
||||
createPluginCommands: async ({ cwd }) =>
|
||||
createPluginResult(cwd === workspaceA ? "plugin-a" : "plugin-b"),
|
||||
onCommandsChanged,
|
||||
});
|
||||
|
||||
await resources.loadPluginSlashCommands();
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-a")).toBe(
|
||||
"Run workflow-a.",
|
||||
);
|
||||
expect(resources.getCommandSnapshot().pluginSlashCommands).toEqual([
|
||||
expect.objectContaining({ name: "plugin-a" }),
|
||||
]);
|
||||
|
||||
const applySessionChange = vi.fn(async () => {});
|
||||
await resources.changeWorkspace(
|
||||
{ cwd: workspaceB, workspaceRoot: workspaceB },
|
||||
applySessionChange,
|
||||
);
|
||||
|
||||
expect(applySessionChange).toHaveBeenCalledOnce();
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-a")).toBe(
|
||||
"/workflow-a",
|
||||
);
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-b")).toBe(
|
||||
"Run workflow-b.",
|
||||
);
|
||||
expect(onCommandsChanged).toHaveBeenLastCalledWith({
|
||||
workflowSlashCommands: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "workflow-b" }),
|
||||
]),
|
||||
pluginSlashCommands: [expect.objectContaining({ name: "plugin-b" })],
|
||||
});
|
||||
expect(
|
||||
onCommandsChanged.mock.calls
|
||||
.at(-1)?.[0]
|
||||
.workflowSlashCommands.map((command: { name: string }) => command.name),
|
||||
).not.toContain("workflow-a");
|
||||
|
||||
await resources.dispose();
|
||||
mutableService.stop();
|
||||
});
|
||||
|
||||
it("keeps the previous workspace active when the agent session transition fails", async () => {
|
||||
const workspaceA = await createWorkspace("workflow-a");
|
||||
const workspaceB = await createWorkspace("workflow-b");
|
||||
const initialService = createInstructionService(workspaceA);
|
||||
await initialService.start();
|
||||
const mutableService =
|
||||
createMutableUserInstructionConfigService(initialService);
|
||||
const nextPluginShutdown = vi.fn(async () => {});
|
||||
const resources = createInteractiveWorkspaceResources({
|
||||
initialLocation: { cwd: workspaceA, workspaceRoot: workspaceA },
|
||||
userInstructionService: mutableService,
|
||||
createUserInstructionService: ({ cwd }) => createInstructionService(cwd),
|
||||
createPluginCommands: async () =>
|
||||
createPluginResult("plugin-b", nextPluginShutdown),
|
||||
});
|
||||
|
||||
await expect(
|
||||
resources.changeWorkspace(
|
||||
{ cwd: workspaceB, workspaceRoot: workspaceB },
|
||||
async () => {
|
||||
throw new Error("session restart failed");
|
||||
},
|
||||
),
|
||||
).rejects.toThrow("session restart failed");
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-a")).toBe(
|
||||
"Run workflow-a.",
|
||||
);
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-b")).toBe(
|
||||
"/workflow-b",
|
||||
);
|
||||
expect(nextPluginShutdown).toHaveBeenCalledOnce();
|
||||
|
||||
await resources.dispose();
|
||||
mutableService.stop();
|
||||
});
|
||||
|
||||
it("rejects incompatible instruction services before changing the agent session", async () => {
|
||||
const workspaceA = await createWorkspace("workflow-a");
|
||||
const workspaceB = await createWorkspace("workflow-b");
|
||||
const initialService = createInstructionService(workspaceA);
|
||||
await initialService.start();
|
||||
const mutableService =
|
||||
createMutableUserInstructionConfigService(initialService);
|
||||
const incompatibleService = createInstructionService(workspaceB);
|
||||
incompatibleService.createSkillsExecutor = undefined;
|
||||
const applySessionChange = vi.fn(async () => {});
|
||||
const resources = createInteractiveWorkspaceResources({
|
||||
initialLocation: { cwd: workspaceA, workspaceRoot: workspaceA },
|
||||
userInstructionService: mutableService,
|
||||
createUserInstructionService: () => incompatibleService,
|
||||
createPluginCommands: async () => createPluginResult("plugin-b"),
|
||||
});
|
||||
|
||||
await expect(
|
||||
resources.changeWorkspace(
|
||||
{ cwd: workspaceB, workspaceRoot: workspaceB },
|
||||
applySessionChange,
|
||||
),
|
||||
).rejects.toThrow("incompatible skills capability");
|
||||
expect(applySessionChange).not.toHaveBeenCalled();
|
||||
expect(mutableService.resolveRuntimeSlashCommand("/workflow-a")).toBe(
|
||||
"Run workflow-a.",
|
||||
);
|
||||
|
||||
await resources.dispose();
|
||||
mutableService.stop();
|
||||
});
|
||||
|
||||
it("does not let a stale plugin load replace a newer workspace", async () => {
|
||||
const workspaceA = await createWorkspace("workflow-a");
|
||||
const workspaceB = await createWorkspace("workflow-b");
|
||||
const initialService = createInstructionService(workspaceA);
|
||||
await initialService.start();
|
||||
const mutableService =
|
||||
createMutableUserInstructionConfigService(initialService);
|
||||
let resolveStaleLoad:
|
||||
| ((value: WorkspaceChatCommandHostResult) => void)
|
||||
| undefined;
|
||||
const staleLoad = new Promise<WorkspaceChatCommandHostResult>((resolve) => {
|
||||
resolveStaleLoad = resolve;
|
||||
});
|
||||
const staleShutdown = vi.fn(async () => {});
|
||||
const resources = createInteractiveWorkspaceResources({
|
||||
initialLocation: { cwd: workspaceA, workspaceRoot: workspaceA },
|
||||
userInstructionService: mutableService,
|
||||
createUserInstructionService: ({ cwd }) => createInstructionService(cwd),
|
||||
createPluginCommands: ({ cwd }) =>
|
||||
cwd === workspaceA
|
||||
? staleLoad
|
||||
: Promise.resolve(createPluginResult("plugin-b")),
|
||||
});
|
||||
|
||||
const loadingA = resources.loadPluginSlashCommands();
|
||||
const changing = resources.changeWorkspace(
|
||||
{ cwd: workspaceB, workspaceRoot: workspaceB },
|
||||
async () => {},
|
||||
);
|
||||
resolveStaleLoad?.(createPluginResult("plugin-a", staleShutdown));
|
||||
await Promise.all([loadingA, changing]);
|
||||
|
||||
expect(resources.getCommandSnapshot().pluginSlashCommands).toEqual([
|
||||
expect.objectContaining({ name: "plugin-b" }),
|
||||
]);
|
||||
expect(staleShutdown).toHaveBeenCalledOnce();
|
||||
|
||||
await resources.dispose();
|
||||
mutableService.stop();
|
||||
});
|
||||
});
|
||||
@@ -1,200 +0,0 @@
|
||||
import type { BasicLogger, UserInstructionConfigService } from "@cline/core";
|
||||
import type { InteractiveSlashCommand } from "../../tui/interactive-welcome";
|
||||
import { listInteractiveSlashCommands } from "../../tui/interactive-welcome";
|
||||
import {
|
||||
type ChatCommandHost,
|
||||
chatCommandHost,
|
||||
} from "../../utils/chat-commands";
|
||||
import type { MutableUserInstructionConfigService } from "../../utils/mutable-user-instruction-service";
|
||||
import {
|
||||
createWorkspaceChatCommandHost,
|
||||
type WorkspaceChatCommandHostResult,
|
||||
} from "../../utils/plugin-chat-commands";
|
||||
|
||||
export interface InteractiveWorkspaceLocation {
|
||||
cwd: string;
|
||||
workspaceRoot: string;
|
||||
}
|
||||
|
||||
export interface InteractiveWorkspaceCommandSnapshot {
|
||||
workflowSlashCommands: InteractiveSlashCommand[];
|
||||
pluginSlashCommands: InteractiveSlashCommand[];
|
||||
}
|
||||
|
||||
interface WorkspacePluginCommands {
|
||||
host: ChatCommandHost;
|
||||
commands: InteractiveSlashCommand[];
|
||||
shutdown?: () => Promise<void>;
|
||||
}
|
||||
|
||||
function toPluginCommands(
|
||||
result: WorkspaceChatCommandHostResult,
|
||||
): WorkspacePluginCommands {
|
||||
return {
|
||||
host: result.host,
|
||||
commands: result.pluginSlashCommands.map((command) => ({
|
||||
name: command.name,
|
||||
instructions: "",
|
||||
description: command.description ?? "Plugin command",
|
||||
})),
|
||||
shutdown: result.shutdown,
|
||||
};
|
||||
}
|
||||
|
||||
export function createInteractiveWorkspaceResources(input: {
|
||||
initialLocation: InteractiveWorkspaceLocation;
|
||||
userInstructionService: MutableUserInstructionConfigService;
|
||||
createUserInstructionService: (
|
||||
location: InteractiveWorkspaceLocation,
|
||||
) => UserInstructionConfigService;
|
||||
logger?: BasicLogger;
|
||||
createPluginCommands?: (
|
||||
location: InteractiveWorkspaceLocation,
|
||||
) => Promise<WorkspaceChatCommandHostResult>;
|
||||
onCommandsChanged?: (snapshot: InteractiveWorkspaceCommandSnapshot) => void;
|
||||
}) {
|
||||
let location = input.initialLocation;
|
||||
let pluginCommands: WorkspacePluginCommands = {
|
||||
host: chatCommandHost,
|
||||
commands: [],
|
||||
};
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
let pluginCommandsLoaded = false;
|
||||
let pluginLoadPromise: Promise<InteractiveSlashCommand[]> | undefined;
|
||||
let workspaceChangePromise: Promise<void> | undefined;
|
||||
const createPluginCommands = async (next: InteractiveWorkspaceLocation) =>
|
||||
toPluginCommands(
|
||||
await (input.createPluginCommands
|
||||
? input.createPluginCommands(next)
|
||||
: createWorkspaceChatCommandHost({
|
||||
cwd: next.cwd,
|
||||
workspaceRoot: next.workspaceRoot,
|
||||
logger: input.logger,
|
||||
})),
|
||||
);
|
||||
const snapshot = (): InteractiveWorkspaceCommandSnapshot => ({
|
||||
workflowSlashCommands: listInteractiveSlashCommands(
|
||||
input.userInstructionService,
|
||||
),
|
||||
pluginSlashCommands: pluginCommands.commands,
|
||||
});
|
||||
|
||||
const loadPluginSlashCommands = async (): Promise<
|
||||
InteractiveSlashCommand[]
|
||||
> => {
|
||||
if (disposed) {
|
||||
return [];
|
||||
}
|
||||
if (pluginCommandsLoaded) {
|
||||
return pluginCommands.commands;
|
||||
}
|
||||
if (pluginLoadPromise) {
|
||||
return await pluginLoadPromise;
|
||||
}
|
||||
const loadGeneration = generation;
|
||||
const loadLocation = location;
|
||||
const load = (async () => {
|
||||
const loaded = await createPluginCommands(loadLocation);
|
||||
if (disposed || generation !== loadGeneration) {
|
||||
await loaded.shutdown?.().catch(() => {});
|
||||
return pluginCommands.commands;
|
||||
}
|
||||
const previous = pluginCommands;
|
||||
pluginCommands = loaded;
|
||||
pluginCommandsLoaded = true;
|
||||
await previous.shutdown?.().catch(() => {});
|
||||
return loaded.commands;
|
||||
})();
|
||||
pluginLoadPromise = load;
|
||||
try {
|
||||
return await load;
|
||||
} finally {
|
||||
if (pluginLoadPromise === load) {
|
||||
pluginLoadPromise = undefined;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const applyWorkspaceChange = async (
|
||||
next: InteractiveWorkspaceLocation,
|
||||
applySessionChange: () => Promise<void>,
|
||||
): Promise<void> => {
|
||||
if (disposed) {
|
||||
throw new Error("interactive workspace resources are disposed");
|
||||
}
|
||||
generation += 1;
|
||||
const nextService = input.createUserInstructionService(next);
|
||||
let nextPluginCommands: WorkspacePluginCommands | undefined;
|
||||
try {
|
||||
await nextService.start();
|
||||
input.userInstructionService.assertCompatible(nextService);
|
||||
nextPluginCommands = await createPluginCommands(next);
|
||||
await applySessionChange();
|
||||
} catch (error) {
|
||||
try {
|
||||
nextService.stop();
|
||||
} catch {}
|
||||
await nextPluginCommands?.shutdown?.().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
|
||||
const previousService = input.userInstructionService.replace(nextService);
|
||||
const previousPluginCommands = pluginCommands;
|
||||
location = next;
|
||||
pluginCommands = nextPluginCommands;
|
||||
pluginCommandsLoaded = true;
|
||||
// The instruction delegate, plugin host, and TUI catalog become visible as
|
||||
// one workspace snapshot after the replacement agent session is live.
|
||||
try {
|
||||
input.onCommandsChanged?.(snapshot());
|
||||
} catch (error) {
|
||||
input.logger?.log("workspace command catalog notification failed", {
|
||||
error,
|
||||
});
|
||||
}
|
||||
try {
|
||||
previousService.stop();
|
||||
} catch {}
|
||||
await previousPluginCommands.shutdown?.().catch(() => {});
|
||||
};
|
||||
|
||||
const changeWorkspace = (
|
||||
next: InteractiveWorkspaceLocation,
|
||||
applySessionChange: () => Promise<void>,
|
||||
): Promise<void> => {
|
||||
let change: Promise<void>;
|
||||
change = (async () => {
|
||||
await workspaceChangePromise?.catch(() => {});
|
||||
await applyWorkspaceChange(next, applySessionChange);
|
||||
})().finally(() => {
|
||||
if (workspaceChangePromise === change) {
|
||||
workspaceChangePromise = undefined;
|
||||
}
|
||||
});
|
||||
workspaceChangePromise = change;
|
||||
return change;
|
||||
};
|
||||
|
||||
const dispose = async (): Promise<void> => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
generation += 1;
|
||||
await workspaceChangePromise?.catch(() => {});
|
||||
await pluginLoadPromise?.catch(() => {});
|
||||
await pluginCommands.shutdown?.().catch(() => {});
|
||||
pluginCommands = { host: chatCommandHost, commands: [] };
|
||||
pluginCommandsLoaded = false;
|
||||
};
|
||||
|
||||
return {
|
||||
changeWorkspace,
|
||||
dispose,
|
||||
getChatCommandHost: () => pluginCommands.host,
|
||||
getCommandSnapshot: snapshot,
|
||||
arePluginCommandsLoaded: () => pluginCommandsLoaded,
|
||||
loadPluginSlashCommands,
|
||||
};
|
||||
}
|
||||
@@ -51,21 +51,6 @@ describe("buildUserInputMessage", () => {
|
||||
expect(result.userImages).toEqual([]);
|
||||
expect(result.userFiles).toEqual([filePath]);
|
||||
});
|
||||
|
||||
it("resolves relative file mentions from the configured working directory", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cli-prompt-cwd-"));
|
||||
const filePath = join(dir, "notes.md");
|
||||
writeFileSync(filePath, "# Notes\n");
|
||||
|
||||
const result = await buildUserInputMessage(
|
||||
"summarize @./notes.md",
|
||||
undefined,
|
||||
{ cwd: dir },
|
||||
);
|
||||
|
||||
expect(result.prompt).toBe("summarize [file: notes.md]");
|
||||
expect(result.userFiles).toEqual([filePath]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSystemPrompt workspace metadata", () => {
|
||||
|
||||
@@ -74,11 +74,11 @@ function extractFileMentions(
|
||||
return matches;
|
||||
}
|
||||
|
||||
function resolveMentionPath(filePath: string, cwd: string): string {
|
||||
function resolveMentionPath(filePath: string): string {
|
||||
if (filePath.startsWith("~/")) {
|
||||
return resolve(homedir(), filePath.slice(2));
|
||||
}
|
||||
return resolve(cwd, filePath);
|
||||
return resolve(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,7 +104,7 @@ export function shouldExpandSkillSlashCommands(mode?: string): boolean {
|
||||
export async function buildUserInputMessage(
|
||||
rawPrompt: string,
|
||||
userInstructionService?: UserInstructionConfigService,
|
||||
options?: { mode?: string; cwd?: string },
|
||||
options?: { mode?: string },
|
||||
): Promise<{
|
||||
prompt: string;
|
||||
userImages: string[];
|
||||
@@ -154,10 +154,7 @@ export async function buildUserInputMessage(
|
||||
|
||||
for (const mention of fileMentions) {
|
||||
try {
|
||||
const resolvedPath = resolveMentionPath(
|
||||
mention.path,
|
||||
options?.cwd ?? process.cwd(),
|
||||
);
|
||||
const resolvedPath = resolveMentionPath(mention.path);
|
||||
const stats = statSync(resolvedPath);
|
||||
if (!stats.isFile()) {
|
||||
throw new Error(`Path is not a file: ${resolvedPath}`);
|
||||
|
||||
@@ -279,7 +279,6 @@ export async function runAgent(
|
||||
userFiles,
|
||||
} = await buildUserInputMessage(prompt, userInstructionService, {
|
||||
mode: config.mode,
|
||||
cwd: config.cwd,
|
||||
});
|
||||
const started = await sessionManager.start({
|
||||
source: SessionSource.CLI,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
createComputerUseToolFromEnv,
|
||||
getCurrentContextSize,
|
||||
type ProviderSettings,
|
||||
ProviderSettingsManager,
|
||||
@@ -24,6 +23,7 @@ import type {
|
||||
LoadInteractiveConfigDataOptions,
|
||||
} from "../tui/interactive-config";
|
||||
import {
|
||||
type InteractiveSlashCommand,
|
||||
listInteractiveSlashCommands,
|
||||
resolveClineWelcomeLine,
|
||||
} from "../tui/interactive-welcome";
|
||||
@@ -36,12 +36,12 @@ import {
|
||||
zeroCliAgentEventCost,
|
||||
zeroCliUsageCost,
|
||||
} from "../utils/free-model-cost";
|
||||
import type { MutableUserInstructionConfigService } from "../utils/mutable-user-instruction-service";
|
||||
import {
|
||||
prepareTerminalForPostTuiOutput,
|
||||
writeErr,
|
||||
writeln,
|
||||
} from "../utils/output";
|
||||
import { createWorkspaceChatCommandHost } from "../utils/plugin-chat-commands";
|
||||
import { readRepoStatus } from "../utils/repo-status";
|
||||
import type { Config } from "../utils/types";
|
||||
import {
|
||||
@@ -52,7 +52,6 @@ import {
|
||||
} from "./active-runtime";
|
||||
import { createInteractiveApprovalController } from "./interactive/approvals";
|
||||
import { runInteractiveChatCommand } from "./interactive/chat-command-runner";
|
||||
import { createInteractiveComputerUser } from "./interactive/computer-user";
|
||||
import { createInteractiveConfigDataLoader } from "./interactive/config-data";
|
||||
import {
|
||||
formatInteractiveExitSummary,
|
||||
@@ -61,7 +60,6 @@ import {
|
||||
import { createMistakeLimitDecisionResolver } from "./interactive/mistakes";
|
||||
import {
|
||||
type AppliedModeChange,
|
||||
buildInteractiveExtraTools,
|
||||
createInteractiveModeSwitchTool,
|
||||
createModeSwitchNoticeTracker,
|
||||
type PendingModeChange,
|
||||
@@ -69,11 +67,6 @@ import {
|
||||
} from "./interactive/mode";
|
||||
import { assertInteractivePreflight } from "./interactive/preflight";
|
||||
import { createInteractiveSessionRuntime } from "./interactive/session-runtime";
|
||||
import {
|
||||
createInteractiveWorkspaceResources,
|
||||
type InteractiveWorkspaceCommandSnapshot,
|
||||
type InteractiveWorkspaceLocation,
|
||||
} from "./interactive/workspace-resources";
|
||||
import { buildUserInputMessage } from "./prompt";
|
||||
import { getUIEventEmitter } from "./session-events";
|
||||
|
||||
@@ -192,53 +185,51 @@ export async function runInteractive(
|
||||
initialPrompt?: string;
|
||||
initialNotice?: CliMigrationNotice;
|
||||
onInitialNoticeShown?: (notice: CliMigrationNotice) => void | Promise<void>;
|
||||
explicitSystemPrompt?: string;
|
||||
mutableUserInstructionService?: MutableUserInstructionConfigService;
|
||||
createUserInstructionService?: (
|
||||
location: InteractiveWorkspaceLocation,
|
||||
) => UserInstructionConfigService;
|
||||
},
|
||||
): Promise<void> {
|
||||
assertInteractivePreflight(config);
|
||||
|
||||
const initialRepoStatus = await readRepoStatus(config.cwd);
|
||||
const mutableUserInstructionService = options?.mutableUserInstructionService;
|
||||
const createUserInstructionService = options?.createUserInstructionService;
|
||||
const activeUserInstructionService =
|
||||
mutableUserInstructionService ?? userInstructionService;
|
||||
if (
|
||||
(mutableUserInstructionService === undefined) !==
|
||||
(createUserInstructionService === undefined)
|
||||
) {
|
||||
throw new Error(
|
||||
"interactive workspace resources require both the mutable instruction service and its factory",
|
||||
);
|
||||
}
|
||||
let workspaceCommandNotifier:
|
||||
| ((snapshot: InteractiveWorkspaceCommandSnapshot) => void)
|
||||
const workflowSlashCommands = listInteractiveSlashCommands(
|
||||
userInstructionService,
|
||||
);
|
||||
let interactiveChatCommandHost = chatCommandHost;
|
||||
let pluginChatCommandHostLoaded = false;
|
||||
let pluginChatSlashCommands: InteractiveSlashCommand[] = [];
|
||||
let pluginChatCommandHostShutdown: (() => Promise<void>) | undefined;
|
||||
let pluginChatCommandHostPromise:
|
||||
| Promise<InteractiveSlashCommand[]>
|
||||
| undefined;
|
||||
const workspaceResources =
|
||||
mutableUserInstructionService && createUserInstructionService
|
||||
? createInteractiveWorkspaceResources({
|
||||
initialLocation: {
|
||||
cwd: config.cwd,
|
||||
workspaceRoot: config.workspaceRoot?.trim() || config.cwd,
|
||||
},
|
||||
userInstructionService: mutableUserInstructionService,
|
||||
createUserInstructionService,
|
||||
logger: config.logger,
|
||||
onCommandsChanged: (snapshot) => workspaceCommandNotifier?.(snapshot),
|
||||
})
|
||||
: undefined;
|
||||
const initialCommandSnapshot = workspaceResources?.getCommandSnapshot() ?? {
|
||||
workflowSlashCommands: listInteractiveSlashCommands(
|
||||
activeUserInstructionService,
|
||||
),
|
||||
pluginSlashCommands: [],
|
||||
const ensurePluginChatCommandHost = async (): Promise<
|
||||
InteractiveSlashCommand[]
|
||||
> => {
|
||||
if (pluginChatCommandHostLoaded) {
|
||||
return pluginChatSlashCommands;
|
||||
}
|
||||
pluginChatCommandHostPromise ??= createWorkspaceChatCommandHost({
|
||||
cwd: config.cwd,
|
||||
workspaceRoot: config.workspaceRoot,
|
||||
logger: config.logger,
|
||||
})
|
||||
.then(({ host, pluginSlashCommands, shutdown }) => {
|
||||
interactiveChatCommandHost = host;
|
||||
pluginChatCommandHostShutdown = shutdown;
|
||||
pluginChatSlashCommands = pluginSlashCommands.map((cmd) => ({
|
||||
name: cmd.name,
|
||||
instructions: "",
|
||||
description: cmd.description ?? "Plugin command",
|
||||
}));
|
||||
return pluginChatSlashCommands;
|
||||
})
|
||||
.finally(() => {
|
||||
pluginChatCommandHostLoaded = true;
|
||||
pluginChatCommandHostPromise = undefined;
|
||||
});
|
||||
return await pluginChatCommandHostPromise;
|
||||
};
|
||||
const loadAdditionalSlashCommands = workspaceResources
|
||||
? workspaceResources.loadPluginSlashCommands
|
||||
: undefined;
|
||||
const loadAdditionalSlashCommands = async (): Promise<
|
||||
InteractiveSlashCommand[]
|
||||
> => await ensurePluginChatCommandHost();
|
||||
const shouldTryPluginChatCommands = (prompt: string): boolean => {
|
||||
return prompt.trimStart().startsWith("/");
|
||||
};
|
||||
@@ -267,47 +258,7 @@ export async function runInteractive(
|
||||
tuiModeChanged,
|
||||
});
|
||||
|
||||
const providerSettingsManager = new ProviderSettingsManager();
|
||||
|
||||
// Computer-use support, enabled when CLINE_COMPUTER_USE_PORT points at a
|
||||
// running backend. Preferred shape: the asynchronous computer user (a
|
||||
// dedicated Anthropic helper session behind computer_user_* tools). When
|
||||
// the Anthropic provider is not configured, fall back to giving the
|
||||
// driver the raw `computer` tool directly.
|
||||
//
|
||||
// notifyDriver closes over sessionRuntime (declared below) but only runs
|
||||
// after a driver turn has started, long after initialization. It resolves
|
||||
// the driver session id at call time, so session rebuilds are safe.
|
||||
const computerUser = await createInteractiveComputerUser({
|
||||
config,
|
||||
providerSettingsManager,
|
||||
notifyDriver: (prompt, delivery) => {
|
||||
void sessionRuntime
|
||||
.sendCurrentTurn({ prompt, delivery })
|
||||
.catch((error) => {
|
||||
logCliError(
|
||||
config.logger,
|
||||
"Computer-user driver notification failed",
|
||||
{
|
||||
error,
|
||||
},
|
||||
);
|
||||
});
|
||||
},
|
||||
});
|
||||
const computerUseTool = computerUser
|
||||
? undefined
|
||||
: await createComputerUseToolFromEnv();
|
||||
const persistentExtraTools = [
|
||||
...(computerUser ? computerUser.driverTools : []),
|
||||
...(computerUseTool ? [computerUseTool] : []),
|
||||
];
|
||||
|
||||
config.extraTools = buildInteractiveExtraTools({
|
||||
mode: config.mode === "plan" ? "plan" : "act",
|
||||
switchToActModeTool,
|
||||
persistentExtraTools,
|
||||
});
|
||||
config.extraTools = config.mode === "plan" ? [switchToActModeTool] : [];
|
||||
|
||||
const uiEvents = getUIEventEmitter();
|
||||
const chatCommandState: ChatCommandState = {
|
||||
@@ -320,13 +271,13 @@ export async function runInteractive(
|
||||
autoApproveAllRef,
|
||||
askQuestionRef: tuiAskQuestion,
|
||||
});
|
||||
const providerSettingsManager = new ProviderSettingsManager();
|
||||
let zeroCurrentTurnCost = false;
|
||||
|
||||
const sessionRuntime = createInteractiveSessionRuntime({
|
||||
config,
|
||||
providerSettingsManager,
|
||||
userInstructionService: activeUserInstructionService,
|
||||
explicitSystemPrompt: options?.explicitSystemPrompt,
|
||||
userInstructionService,
|
||||
resumeSessionId,
|
||||
chatCommandState,
|
||||
requestToolApproval,
|
||||
@@ -334,11 +285,6 @@ export async function runInteractive(
|
||||
askQuestionRef: tuiAskQuestion,
|
||||
resolveMistakeLimitDecision,
|
||||
switchToActModeTool,
|
||||
persistentExtraTools,
|
||||
// Record the driver's transcript to the computer-use backend's
|
||||
// journal so the observatory can show it beside the computer user's
|
||||
// transcript and screenshots.
|
||||
extraAgentHooks: computerUser?.driverRecordingHooks,
|
||||
onAgentEvent: (event) => {
|
||||
uiEvents.emit("agent", zeroCliAgentEventCost(event, zeroCurrentTurnCost));
|
||||
},
|
||||
@@ -354,24 +300,10 @@ export async function runInteractive(
|
||||
});
|
||||
const configDataLoader = createInteractiveConfigDataLoader({
|
||||
config,
|
||||
userInstructionService: activeUserInstructionService,
|
||||
userInstructionService,
|
||||
loadCoreSettings: sessionRuntime.listCoreSettings,
|
||||
toggleCoreSettings: sessionRuntime.toggleCoreSettings,
|
||||
});
|
||||
const changeInteractiveWorkingDirectory = async (
|
||||
next: ChatCommandState,
|
||||
): Promise<void> => {
|
||||
const applySessionChange = () =>
|
||||
sessionRuntime.changeWorkingDirectory(next);
|
||||
if (!workspaceResources) {
|
||||
await applySessionChange();
|
||||
return;
|
||||
}
|
||||
await workspaceResources.changeWorkspace(
|
||||
{ cwd: next.cwd, workspaceRoot: next.workspaceRoot },
|
||||
applySessionChange,
|
||||
);
|
||||
};
|
||||
let modeChangePromise: Promise<void> | undefined;
|
||||
let modeChangeTarget: "plan" | "act" | undefined;
|
||||
const modeSwitchNotice = createModeSwitchNoticeTracker();
|
||||
@@ -453,8 +385,11 @@ export async function runInteractive(
|
||||
try {
|
||||
exitSummary = await sessionRuntime.cleanup();
|
||||
} finally {
|
||||
await computerUser?.dispose().catch(() => {});
|
||||
await workspaceResources?.dispose();
|
||||
await pluginChatCommandHostPromise?.catch(() => []);
|
||||
await pluginChatCommandHostShutdown?.().catch(() => {
|
||||
// Best effort cleanup for plugin command discovery sandbox.
|
||||
});
|
||||
pluginChatCommandHostShutdown = undefined;
|
||||
setActiveRuntimeAbort(undefined);
|
||||
setActiveRuntimeCleanup(undefined);
|
||||
}
|
||||
@@ -588,7 +523,7 @@ export async function runInteractive(
|
||||
onInitialNoticeShown: options?.onInitialNoticeShown,
|
||||
loadDeferredInitialMessages,
|
||||
initialRepoStatus,
|
||||
workflowSlashCommands: initialCommandSnapshot.workflowSlashCommands,
|
||||
workflowSlashCommands,
|
||||
loadAdditionalSlashCommands,
|
||||
loadWelcomeLine: async () =>
|
||||
await resolveClineWelcomeLine({
|
||||
@@ -647,14 +582,12 @@ export async function runInteractive(
|
||||
let chatCommandResult = await runInteractiveChatCommand({
|
||||
prompt: input,
|
||||
enabled: enableChatCommands,
|
||||
delivery,
|
||||
config,
|
||||
host: workspaceResources?.getChatCommandHost() ?? chatCommandHost,
|
||||
host: interactiveChatCommandHost,
|
||||
chatCommandState,
|
||||
autoApproveAllRef,
|
||||
setInteractiveAutoApprove,
|
||||
sessionRuntime,
|
||||
changeWorkingDirectory: changeInteractiveWorkingDirectory,
|
||||
stop: () => tuiApp?.destroy(),
|
||||
onCommandOutput,
|
||||
});
|
||||
@@ -663,21 +596,18 @@ export async function runInteractive(
|
||||
}
|
||||
if (
|
||||
shouldTryPluginChatCommands(input) &&
|
||||
workspaceResources &&
|
||||
!workspaceResources.arePluginCommandsLoaded()
|
||||
!pluginChatCommandHostLoaded
|
||||
) {
|
||||
await workspaceResources.loadPluginSlashCommands();
|
||||
await ensurePluginChatCommandHost();
|
||||
chatCommandResult = await runInteractiveChatCommand({
|
||||
prompt: input,
|
||||
enabled: enableChatCommands,
|
||||
delivery,
|
||||
config,
|
||||
host: workspaceResources.getChatCommandHost(),
|
||||
host: interactiveChatCommandHost,
|
||||
chatCommandState,
|
||||
autoApproveAllRef,
|
||||
setInteractiveAutoApprove,
|
||||
sessionRuntime,
|
||||
changeWorkingDirectory: changeInteractiveWorkingDirectory,
|
||||
stop: () => tuiApp?.destroy(),
|
||||
onCommandOutput,
|
||||
});
|
||||
@@ -693,9 +623,8 @@ export async function runInteractive(
|
||||
prompt: userInput,
|
||||
userImages,
|
||||
userFiles,
|
||||
} = await buildUserInputMessage(input, activeUserInstructionService, {
|
||||
} = await buildUserInputMessage(input, userInstructionService, {
|
||||
mode,
|
||||
cwd: config.cwd,
|
||||
});
|
||||
const mergedUserImages = [
|
||||
...(attachments?.userImages ?? []),
|
||||
@@ -931,12 +860,6 @@ export async function runInteractive(
|
||||
setModeChangeNotifier: (fn) => {
|
||||
tuiModeChanged.current = fn;
|
||||
},
|
||||
setWorkspaceCommandNotifier: (fn) => {
|
||||
workspaceCommandNotifier = fn ?? undefined;
|
||||
if (fn && workspaceResources) {
|
||||
fn(workspaceResources.getCommandSnapshot());
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (!loadDeferredInitialMessages && options?.startupTarget !== "history") {
|
||||
|
||||
@@ -82,7 +82,6 @@ export async function runZen(
|
||||
// Zen runs in yolo mode, whose preset has no skills tool — skill
|
||||
// commands must keep expanding textually.
|
||||
mode: "yolo",
|
||||
cwd: config.cwd,
|
||||
});
|
||||
|
||||
const startRequest: ChatStartSessionRequest = {
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
getValidClineCredentials,
|
||||
type ProviderSettings,
|
||||
ProviderSettingsManager,
|
||||
persistClineAccountTelemetryIdentity,
|
||||
resolveClineAccountTelemetryIdentity,
|
||||
saveLocalProviderOAuthCredentials,
|
||||
type UserCurrentPlan,
|
||||
} from "@cline/core";
|
||||
@@ -158,38 +160,6 @@ export async function createClineAccountService(input: {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the active organization so headless runs and the hub daemon can
|
||||
* attach it to telemetry identity. Personal account clears stale org fields.
|
||||
*/
|
||||
function persistClineOrganizationContext(
|
||||
activeOrganization: ClineAccountOrganization | null,
|
||||
userId: string,
|
||||
): void {
|
||||
try {
|
||||
const manager = new ProviderSettingsManager();
|
||||
const persisted = manager.getProviderSettings("cline");
|
||||
if (!persisted) {
|
||||
return;
|
||||
}
|
||||
manager.saveProviderSettings(
|
||||
{
|
||||
...persisted,
|
||||
auth: {
|
||||
...persisted.auth,
|
||||
accountId: persisted.auth?.accountId ?? userId,
|
||||
organizationId: activeOrganization?.organizationId,
|
||||
organizationName: activeOrganization?.name,
|
||||
memberId: activeOrganization?.memberId,
|
||||
},
|
||||
},
|
||||
{ setLastUsed: false },
|
||||
);
|
||||
} catch {
|
||||
// Best-effort only.
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadClineAccountSnapshot(input: {
|
||||
config: ClineAccountConfig;
|
||||
clineApiBaseUrl?: string;
|
||||
@@ -213,16 +183,12 @@ export async function loadClineAccountSnapshot(input: {
|
||||
const displayedBalance = activeOrganization
|
||||
? (organizationBalance?.balance ?? balance.balance)
|
||||
: balance.balance;
|
||||
const accountContext = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
provider: "cline",
|
||||
organizationId: activeOrganization?.organizationId,
|
||||
organizationName: activeOrganization?.name,
|
||||
memberId: activeOrganization?.memberId,
|
||||
};
|
||||
const accountContext = resolveClineAccountTelemetryIdentity(user);
|
||||
identifyTelemetryAccount(accountContext, input.config.logger);
|
||||
persistClineOrganizationContext(activeOrganization, user.id);
|
||||
persistClineAccountTelemetryIdentity(
|
||||
new ProviderSettingsManager(),
|
||||
accountContext,
|
||||
);
|
||||
|
||||
return {
|
||||
user,
|
||||
|
||||
@@ -316,26 +316,4 @@ describe("slash command registry", () => {
|
||||
getVisibleSystemSlashCommands(registry).map((command) => command.name),
|
||||
).toContain("account");
|
||||
});
|
||||
|
||||
it("exposes cd as a runtime command", () => {
|
||||
const registry = buildSlashCommandRegistry({
|
||||
workflowSlashCommands: [
|
||||
{
|
||||
name: "cd",
|
||||
instructions: "/cd <directory>",
|
||||
description: "Change the working directory",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(resolveSlashCommand(registry, "cd")).toMatchObject({
|
||||
source: "runtime",
|
||||
execution: "runtime",
|
||||
visible: true,
|
||||
selectable: true,
|
||||
});
|
||||
expect(
|
||||
getVisibleSystemSlashCommands(registry).map((command) => command.name),
|
||||
).toContain("cd");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -116,7 +116,6 @@ const TUI_LOCAL_COMMANDS: Array<{
|
||||
|
||||
const SYSTEM_COMMAND_ORDER = [
|
||||
"settings",
|
||||
"cd",
|
||||
"model",
|
||||
"theme",
|
||||
"account",
|
||||
@@ -131,7 +130,7 @@ const SYSTEM_COMMAND_ORDER = [
|
||||
"history",
|
||||
"help",
|
||||
"quit",
|
||||
] satisfies ReadonlyArray<LocalSlashCommandName | "cd" | "team">;
|
||||
] satisfies ReadonlyArray<LocalSlashCommandName | "team">;
|
||||
|
||||
const SYSTEM_COMMAND_PRIORITY = new Map<string, number>(
|
||||
SYSTEM_COMMAND_ORDER.map((name, index) => [name, index]),
|
||||
|
||||
@@ -133,12 +133,6 @@ const HELP_ROWS: HelpRow[] = [
|
||||
key: "/theme",
|
||||
desc: "Change color theme",
|
||||
},
|
||||
{
|
||||
kind: "entry",
|
||||
id: "c-cd",
|
||||
key: "/cd <directory>",
|
||||
desc: "Change the working directory",
|
||||
},
|
||||
{
|
||||
kind: "entry",
|
||||
id: "c-mcp",
|
||||
|
||||
@@ -14,27 +14,6 @@ export function resolveHubUpdateRequiredKeyAction(
|
||||
return "ignore";
|
||||
}
|
||||
|
||||
/**
|
||||
* Human phrase for the live work an outdated Hub is serving, used by the
|
||||
* "Hub update required" dialog. Falls back to an unquantified phrase when the
|
||||
* Hub could not answer the activity query.
|
||||
*/
|
||||
export function describeOutdatedHubSessions(counts: {
|
||||
activeSessionCount?: number;
|
||||
participantClientCount?: number;
|
||||
}): string {
|
||||
const sessions = counts.activeSessionCount;
|
||||
if (typeof sessions !== "number" || sessions <= 0) {
|
||||
return "active sessions from other Cline clients";
|
||||
}
|
||||
const sessionsPhrase = `${sessions} active session${sessions === 1 ? "" : "s"}`;
|
||||
const clients = counts.participantClientCount;
|
||||
if (typeof clients !== "number" || clients <= 0) {
|
||||
return sessionsPhrase;
|
||||
}
|
||||
return `${sessionsPhrase} from ${clients} connected Cline client${clients === 1 ? "" : "s"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Yolo and sandbox sessions force the local backend and never attach to the
|
||||
* shared managed Hub (see the forceLocalBackend condition in the interactive
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
// @jsxImportSource @opentui/react
|
||||
import { describeOutdatedHubSessions } from "@cline/shared";
|
||||
import type { ChoiceContext } from "@opentui-ui/dialog";
|
||||
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
|
||||
import { useDialogPalette } from "../../hooks/use-theme";
|
||||
import {
|
||||
describeOutdatedHubSessions,
|
||||
resolveHubUpdateRequiredKeyAction,
|
||||
} from "./hub-update-required-helpers";
|
||||
import { resolveHubUpdateRequiredKeyAction } from "./hub-update-required-helpers";
|
||||
|
||||
export interface HubUpdateRequiredDetails {
|
||||
hubCoreVersion?: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
completeClineDeviceAuth,
|
||||
getProviderConfigFields,
|
||||
isLocalAuthProvider,
|
||||
isOAuthProvider,
|
||||
loginLocalProvider,
|
||||
type ProviderConfigFieldKey,
|
||||
@@ -15,11 +16,10 @@ import type { ChoiceContext } from "@opentui-ui/dialog";
|
||||
import { useDialogKeyboard } from "@opentui-ui/dialog/react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
CODEX_CLI_INSTALL_URL,
|
||||
type CodexCliStatus,
|
||||
checkCodexCliInstalled,
|
||||
isOpenAICodexCliProvider,
|
||||
} from "../../../utils/codex-cli";
|
||||
checkLocalCliInstalled,
|
||||
type LocalCliStatus,
|
||||
type ProviderLocalCli,
|
||||
} from "../../../utils/local-cli";
|
||||
import open from "../../../utils/open";
|
||||
import { listLocalProviders } from "../../../utils/provider-catalog";
|
||||
import { useDialogPalette } from "../../hooks/use-theme";
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
updateProviderConfigValue,
|
||||
} from "../../utils/provider-config-values";
|
||||
import { getProviderSection } from "../../utils/provider-sections";
|
||||
import { canContinueLocalCliSetup } from "../../views/onboarding/model";
|
||||
import {
|
||||
getSearchableListRowsWindow,
|
||||
type SearchableItem,
|
||||
@@ -82,7 +83,7 @@ export function ProviderPickerContent(
|
||||
// just a model id and base URL) still render as configured.
|
||||
isConfigured: p.enabled === true,
|
||||
isOAuth: isOAuthProvider(p.id),
|
||||
isLocalAuth: isOpenAICodexCliProvider(p.id),
|
||||
isLocalAuth: isLocalAuthProvider(p.id),
|
||||
capabilities: p.capabilities,
|
||||
}));
|
||||
setProviders(providerItems);
|
||||
@@ -654,29 +655,25 @@ export function ProviderConfigInputContent(
|
||||
);
|
||||
}
|
||||
|
||||
export function CodexCliStatusContent(
|
||||
export function LocalCliStatusContent(
|
||||
props: ChoiceContext<boolean> & {
|
||||
cli?: ProviderLocalCli;
|
||||
providerName: string;
|
||||
},
|
||||
) {
|
||||
const { resolve, dismiss, dialogId, providerName } = props;
|
||||
const { resolve, dismiss, dialogId, cli, providerName } = props;
|
||||
const palette = useDialogPalette();
|
||||
const [status, setStatus] = useState<CodexCliStatus | undefined>();
|
||||
const [status, setStatus] = useState<LocalCliStatus | undefined>();
|
||||
const [checking, setChecking] = useState(false);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
if (!cli) return;
|
||||
setStatus(undefined);
|
||||
setChecking(true);
|
||||
checkCodexCliInstalled()
|
||||
checkLocalCliInstalled(cli)
|
||||
.then(setStatus)
|
||||
.catch((error: unknown) => {
|
||||
setStatus({
|
||||
installed: false,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
})
|
||||
.finally(() => setChecking(false));
|
||||
}, []);
|
||||
}, [cli]);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
@@ -691,7 +688,7 @@ export function CodexCliStatusContent(
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
if (key.name === "return" && status?.installed) {
|
||||
if (key.name === "return" && canContinueLocalCliSetup(cli, status)) {
|
||||
resolve(true);
|
||||
}
|
||||
}, dialogId);
|
||||
@@ -702,31 +699,37 @@ export function CodexCliStatusContent(
|
||||
<strong>{providerName}</strong>
|
||||
</text>
|
||||
|
||||
{checking && <text fg="gray">Checking for Codex CLI...</text>}
|
||||
{checking && <text fg="gray">Checking for {providerName}...</text>}
|
||||
|
||||
{status?.installed && (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text fg={palette.success}>{"\u25cf"} Codex CLI installed</text>
|
||||
<text fg={palette.success}>
|
||||
{"\u25cf"} {providerName} installed
|
||||
</text>
|
||||
<text fg="gray">{status.version}</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{status && !status.installed && (
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text fg="yellow">Codex CLI was not found</text>
|
||||
<text fg="yellow">{providerName} was not found</text>
|
||||
<text fg="gray">{status.reason}</text>
|
||||
<text fg="gray">Install Codex CLI from:</text>
|
||||
<text fg={palette.act} selectable>
|
||||
{CODEX_CLI_INSTALL_URL}
|
||||
</text>
|
||||
{cli?.docsUrl && (
|
||||
<box flexDirection="column">
|
||||
<text fg="gray">Install {providerName} from:</text>
|
||||
<text fg={palette.act} selectable>
|
||||
{cli.docsUrl}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
)}
|
||||
|
||||
<text fg="gray">
|
||||
<em>
|
||||
{status?.installed
|
||||
{cli
|
||||
? "Enter to continue, R to recheck, Esc to go back"
|
||||
: "R to recheck, Esc to go back"}
|
||||
: "Enter to continue, Esc to go back"}
|
||||
</em>
|
||||
</text>
|
||||
</box>
|
||||
|
||||
@@ -36,7 +36,7 @@ export function QueuedPrompts(props: {
|
||||
? "Waiting. ↑/↓ navigate, Tab edit, Esc cancels turn"
|
||||
: `Steered next. ↑/↓ navigate, Tab edit, ${escapeHint}`
|
||||
: `↑/↓ navigate, Enter steer, Tab edit, ${escapeHint}`
|
||||
: "↑ steer or edit messages";
|
||||
: "Enter with empty input to steer first · ↑ select or edit";
|
||||
|
||||
return (
|
||||
<box
|
||||
|
||||
@@ -23,6 +23,9 @@ export function Toast(props: { toast: ToastState | null }) {
|
||||
};
|
||||
const availableWidth = Math.max(1, width - 4);
|
||||
const maxWidth = Math.min(44, availableWidth);
|
||||
// Border and horizontal padding take four columns. An explicit width (not
|
||||
// maxWidth) is what makes the text wrap instead of clipping at the edge.
|
||||
const boxWidth = Math.min(maxWidth, props.toast.message.length + 4);
|
||||
const right = width < 32 ? 0 : 2;
|
||||
const color = variantColor[props.toast.variant];
|
||||
|
||||
@@ -32,7 +35,7 @@ export function Toast(props: { toast: ToastState | null }) {
|
||||
zIndex={100}
|
||||
top={1}
|
||||
right={right}
|
||||
maxWidth={maxWidth}
|
||||
width={boxWidth}
|
||||
border
|
||||
borderStyle="rounded"
|
||||
borderColor={color}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { isClineProvider } from "@cline/shared";
|
||||
import type { ChoiceContext } from "@opentui-ui/dialog";
|
||||
import type { DialogActions } from "@opentui-ui/dialog/react";
|
||||
import { useCallback } from "react";
|
||||
import { isOpenAICodexCliProvider } from "../../utils/codex-cli";
|
||||
import { getLocalCliInfo } from "../../utils/local-cli";
|
||||
import {
|
||||
getPersistedProviderApiKey,
|
||||
isOAuthProvider,
|
||||
@@ -20,8 +20,8 @@ import type { Config } from "../../utils/types";
|
||||
import { withLoadingDialog } from "../components/dialogs/loading-dialog";
|
||||
import {
|
||||
ClinePassSubscriptionContent,
|
||||
CodexCliStatusContent,
|
||||
type ExistingProviderOption,
|
||||
LocalCliStatusContent,
|
||||
OAuthApiKeyInputContent,
|
||||
OAuthLoginContent,
|
||||
type OAuthLoginResult,
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
type ThinkingLevel,
|
||||
ThinkingLevelContent,
|
||||
} from "../components/model-selector/model-selector";
|
||||
import { resolveProviderSetupRoute } from "../views/onboarding/model";
|
||||
|
||||
export interface OpenModelSelectorOptions {
|
||||
onCancel?: () => Promise<void> | void;
|
||||
@@ -178,6 +179,9 @@ async function runProviderChange(
|
||||
async () => await getProviderDisplayName(newProviderId),
|
||||
);
|
||||
const existingSettings = manager.getProviderSettings(newProviderId);
|
||||
const needsLocalCliSetup =
|
||||
resolveProviderSetupRoute(newProviderId) === "local_cli";
|
||||
const localCliProvider = getLocalCliInfo(newProviderId);
|
||||
|
||||
// Manual API key entry is the escape hatch for when OAuth login isn't
|
||||
// working; only the Cline providers accept a dashboard API key.
|
||||
@@ -246,12 +250,16 @@ async function runProviderChange(
|
||||
loginResult === "use_api_key"
|
||||
? await openManualApiKeyDialog()
|
||||
: loginResult;
|
||||
} else if (isOpenAICodexCliProvider(newProviderId)) {
|
||||
} else if (needsLocalCliSetup) {
|
||||
saved = await dialog.choice<boolean>({
|
||||
style: { maxHeight: termHeight - 2 },
|
||||
closeOnEscape: false,
|
||||
content: (ctx: ChoiceContext<boolean>) => (
|
||||
<CodexCliStatusContent {...ctx} providerName={displayName} />
|
||||
<LocalCliStatusContent
|
||||
{...ctx}
|
||||
cli={localCliProvider}
|
||||
providerName={displayName}
|
||||
/>
|
||||
),
|
||||
});
|
||||
if (saved) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { KeyEvent } from "@opentui/core";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useRootKeyboard } from "./use-root-keyboard";
|
||||
import { shouldHandleInputHistory } from "./root-keyboard-routing";
|
||||
|
||||
describe("root keyboard input history routing", () => {
|
||||
@@ -29,3 +31,58 @@ describe("root keyboard input history routing", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const keyboard = vi.hoisted(() => ({ handle: (_key: KeyEvent) => {} }));
|
||||
vi.mock("@opentui/react", () => ({
|
||||
useKeyboard: (handle: (key: KeyEvent) => void) => {
|
||||
keyboard.handle = handle;
|
||||
},
|
||||
}));
|
||||
vi.mock("react", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react")>()),
|
||||
useRef: (current: unknown) => ({ current }),
|
||||
}));
|
||||
vi.mock("../contexts/session-context", () => ({
|
||||
useSession: () => ({ isRunning: true, isExitRequested: false }),
|
||||
}));
|
||||
|
||||
describe("empty-input queue steering", () => {
|
||||
it.each([
|
||||
{ text: "", shift: false, promote: true },
|
||||
{ text: " ", shift: false, promote: true },
|
||||
{ text: "new draft", shift: false, promote: false },
|
||||
{ text: "", shift: true, promote: false },
|
||||
])("routes Enter with $text and shift=$shift", ({ text, shift, promote }) => {
|
||||
const promotePrompt = vi.fn();
|
||||
useRootKeyboard({
|
||||
isDialogOpen: false,
|
||||
appView: "chat",
|
||||
autocomplete: { mode: false },
|
||||
transcriptScrollRef: { current: null },
|
||||
getCurrentInputText: () => text,
|
||||
queuedPromptSelection: {
|
||||
items: [
|
||||
{ id: "first", prompt: "first", steer: false, attachmentCount: 0 },
|
||||
{ id: "second", prompt: "second", steer: false, attachmentCount: 0 },
|
||||
],
|
||||
selectedId: null,
|
||||
editingId: null,
|
||||
promote: promotePrompt,
|
||||
},
|
||||
} as unknown as Parameters<typeof useRootKeyboard>[0]);
|
||||
const preventDefault = vi.fn();
|
||||
keyboard.handle({
|
||||
name: "return",
|
||||
ctrl: false,
|
||||
meta: false,
|
||||
shift,
|
||||
repeated: false,
|
||||
preventDefault,
|
||||
} as unknown as KeyEvent);
|
||||
expect(promotePrompt).toHaveBeenCalledTimes(promote ? 1 : 0);
|
||||
if (promote) {
|
||||
expect(promotePrompt).toHaveBeenCalledWith("first");
|
||||
expect(preventDefault).toHaveBeenCalledOnce();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -209,6 +209,22 @@ export function useRootKeyboard(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!hasInputText &&
|
||||
hasQueuedPrompts &&
|
||||
!key.shift &&
|
||||
!key.ctrl &&
|
||||
!key.meta &&
|
||||
(key.name === "enter" || key.name === "return")
|
||||
) {
|
||||
key.preventDefault();
|
||||
const firstPrompt = queuedSelection.items[0];
|
||||
if (firstPrompt && !firstPrompt.steer && !key.repeated) {
|
||||
queuedSelection.promote(firstPrompt.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.name === "up" && canHandleInputHistory) {
|
||||
if (
|
||||
input.inputHistory.navigateHistory("up", input.inputValueRef.current)
|
||||
|
||||
@@ -60,11 +60,5 @@ export function useSlashCommands(input: {
|
||||
[registry],
|
||||
);
|
||||
|
||||
return {
|
||||
registry,
|
||||
systemCommands,
|
||||
skillCommands,
|
||||
invokableSkillCommands,
|
||||
setAdditionalSlashCommands,
|
||||
};
|
||||
return { registry, systemCommands, skillCommands, invokableSkillCommands };
|
||||
}
|
||||
|
||||
@@ -123,11 +123,6 @@ export function listInteractiveSlashCommands(
|
||||
instructions: "",
|
||||
description: "Modify agent configuration",
|
||||
},
|
||||
{
|
||||
name: "cd",
|
||||
instructions: "/cd <directory>",
|
||||
description: "Change the working directory",
|
||||
},
|
||||
{
|
||||
name: "mcp",
|
||||
instructions: "",
|
||||
|
||||
@@ -15,7 +15,10 @@ import {
|
||||
useDialogState,
|
||||
} from "@opentui-ui/dialog/react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { shouldSuppressClineCliMigrationNoticeForActiveProvider } from "../kanban-migration/notice";
|
||||
import {
|
||||
CLINE_PASS_NOTICE_ID,
|
||||
shouldSuppressClineCliMigrationNoticeForActiveProvider,
|
||||
} from "../kanban-migration/notice";
|
||||
import { MigrationNoticeContent } from "../kanban-migration/notice-dialog";
|
||||
import {
|
||||
isSameRepoStatus,
|
||||
@@ -140,21 +143,12 @@ function App(props: TuiProps) {
|
||||
systemCommands,
|
||||
skillCommands,
|
||||
invokableSkillCommands,
|
||||
setAdditionalSlashCommands,
|
||||
} = useSlashCommands({
|
||||
workflowSlashCommands,
|
||||
loadAdditionalSlashCommands: props.loadAdditionalSlashCommands,
|
||||
canFork: canForkSession,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
props.setWorkspaceCommandNotifier((snapshot) => {
|
||||
setWorkflowSlashCommands(snapshot.workflowSlashCommands);
|
||||
setAdditionalSlashCommands(snapshot.pluginSlashCommands);
|
||||
});
|
||||
return () => props.setWorkspaceCommandNotifier(null);
|
||||
}, [props.setWorkspaceCommandNotifier, setAdditionalSlashCommands]);
|
||||
|
||||
const autocomplete = useAutocomplete({
|
||||
workspaceRoot,
|
||||
systemCommands,
|
||||
@@ -561,6 +555,7 @@ function App(props: TuiProps) {
|
||||
if (initialNoticeShownRef.current) return;
|
||||
if (appView !== "home") return;
|
||||
if (
|
||||
notice.id === CLINE_PASS_NOTICE_ID &&
|
||||
shouldSuppressClineCliMigrationNoticeForActiveProvider(currentProviderId)
|
||||
) {
|
||||
initialNoticeShownRef.current = true;
|
||||
|
||||
@@ -246,14 +246,6 @@ export interface TuiProps {
|
||||
handler: ((question: string, options: string[]) => Promise<string>) | null,
|
||||
) => void;
|
||||
setModeChangeNotifier: (handler: ((mode: AgentMode) => void) | null) => void;
|
||||
setWorkspaceCommandNotifier: (
|
||||
handler:
|
||||
| ((snapshot: {
|
||||
workflowSlashCommands: InteractiveSlashCommand[];
|
||||
pluginSlashCommands: InteractiveSlashCommand[];
|
||||
}) => void)
|
||||
| null,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export type InlineStream = "text" | "reasoning" | undefined;
|
||||
|
||||
@@ -17,10 +17,11 @@ import {
|
||||
getIndividualPlanFeatures,
|
||||
} from "../../../utils/cline-pass-errors";
|
||||
import {
|
||||
type CodexCliStatus,
|
||||
checkCodexCliInstalled,
|
||||
isOpenAICodexCliProvider,
|
||||
} from "../../../utils/codex-cli";
|
||||
checkLocalCliInstalled,
|
||||
getLocalCliInfo,
|
||||
type LocalCliStatus,
|
||||
type ProviderLocalCli,
|
||||
} from "../../../utils/local-cli";
|
||||
import open from "../../../utils/open";
|
||||
import { getPersistedProviderApiKey } from "../../../utils/provider-auth";
|
||||
import { listLocalProviders } from "../../../utils/provider-catalog";
|
||||
@@ -59,6 +60,7 @@ import { useOnboardingKeyboard } from "./keyboard";
|
||||
import {
|
||||
CLINE_PASS_SUBSCRIPTION_OPTIONS,
|
||||
type ClinePassSubscriptionStatus,
|
||||
canContinueLocalCliSetup,
|
||||
DEFAULT_THINKING_LEVEL_INDEX,
|
||||
getMainMenuOptions,
|
||||
type ModelEntry,
|
||||
@@ -66,6 +68,7 @@ import {
|
||||
type OnboardingStep,
|
||||
type ProviderEntry,
|
||||
type ReasoningEffort,
|
||||
resolveProviderSetupRoute,
|
||||
shouldUseFeaturedClineModelPicker,
|
||||
type ThinkingLevel,
|
||||
toModelEntriesFromKnownModels,
|
||||
@@ -103,6 +106,10 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
const [authError, setAuthError] = useState("");
|
||||
const [activeProviderId, setActiveProviderId] = useState("");
|
||||
const [activeProviderName, setActiveProviderName] = useState("");
|
||||
const localCli = useMemo(
|
||||
() => getLocalCliInfo(activeProviderId),
|
||||
[activeProviderId],
|
||||
);
|
||||
const [byoFields, setByoFields] = useState<ProviderConfigFields["fields"]>(
|
||||
{},
|
||||
);
|
||||
@@ -110,10 +117,11 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
const [byoValues, setByoValues] = useState<ProviderConfigValues>({});
|
||||
const [byoFocusedField, setByoFocusedField] =
|
||||
useState<ProviderConfigFieldKey>("apiKey");
|
||||
const [codexCliStatus, setCodexCliStatus] = useState<
|
||||
CodexCliStatus | undefined
|
||||
const [localCliStatus, setLocalCliStatus] = useState<
|
||||
LocalCliStatus | undefined
|
||||
>();
|
||||
const [codexCliChecking, setCodexCliChecking] = useState(false);
|
||||
const [localCliChecking, setLocalCliChecking] = useState(false);
|
||||
const localCliProbeRef = useRef(0);
|
||||
const authAbortRef = useRef(false);
|
||||
|
||||
// Device code flow
|
||||
@@ -486,18 +494,23 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
}
|
||||
}, [step, clinePassSubscriptionStatus, transitionToModelPicker]);
|
||||
|
||||
const refreshCodexCliStatus = useCallback(() => {
|
||||
setCodexCliStatus(undefined);
|
||||
setCodexCliChecking(true);
|
||||
checkCodexCliInstalled()
|
||||
.then(setCodexCliStatus)
|
||||
.catch((error: unknown) => {
|
||||
setCodexCliStatus({
|
||||
installed: false,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
const refreshLocalCliStatus = useCallback((provider: ProviderLocalCli) => {
|
||||
// Probing spawns the provider's CLI, so a result can land long after the
|
||||
// user moved on. Two local-CLI providers share this single status, so an
|
||||
// unlabelled result could mark the selected provider ready off a probe of
|
||||
// the previous one (or block it off a stale failure). Only the newest
|
||||
// probe may write.
|
||||
const probeId = ++localCliProbeRef.current;
|
||||
const isCurrentProbe = () => localCliProbeRef.current === probeId;
|
||||
setLocalCliStatus(undefined);
|
||||
setLocalCliChecking(true);
|
||||
checkLocalCliInstalled(provider)
|
||||
.then((status) => {
|
||||
if (isCurrentProbe()) setLocalCliStatus(status);
|
||||
})
|
||||
.finally(() => setCodexCliChecking(false));
|
||||
.finally(() => {
|
||||
if (isCurrentProbe()) setLocalCliChecking(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectProvider = useCallback(
|
||||
@@ -510,12 +523,14 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (provider.isLocalAuth || isOpenAICodexCliProvider(provider.id)) {
|
||||
if (resolveProviderSetupRoute(provider.id) === "local_cli") {
|
||||
setActiveProviderId(provider.id);
|
||||
setActiveProviderName(provider.name);
|
||||
setCodexCliStatus(undefined);
|
||||
setStep("codex_cli_setup");
|
||||
refreshCodexCliStatus();
|
||||
setStep("local_cli_setup");
|
||||
// Only providers that name a CLI have something to probe; the
|
||||
// rest reach the screen with readiness simply unknown.
|
||||
const localCliProvider = getLocalCliInfo(provider.id);
|
||||
if (localCliProvider) refreshLocalCliStatus(localCliProvider);
|
||||
return;
|
||||
}
|
||||
const config = getProviderConfigFields(provider.id);
|
||||
@@ -575,11 +590,17 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
setByoFocusedField(firstField ?? "apiKey");
|
||||
setStep("byo_apikey");
|
||||
},
|
||||
[providers, startOAuthFlow, refreshCodexCliStatus, providerSettingsManager],
|
||||
[providers, startOAuthFlow, refreshLocalCliStatus, providerSettingsManager],
|
||||
);
|
||||
|
||||
const saveCodexCliConfig = useCallback(() => {
|
||||
if (!codexCliStatus?.installed) {
|
||||
const recheckLocalCli = useCallback(() => {
|
||||
if (localCli) {
|
||||
refreshLocalCliStatus(localCli);
|
||||
}
|
||||
}, [localCli, refreshLocalCliStatus]);
|
||||
|
||||
const saveLocalCliConfig = useCallback(() => {
|
||||
if (!canContinueLocalCliSetup(localCli, localCliStatus)) {
|
||||
return;
|
||||
}
|
||||
saveLocalProviderSettings(providerSettingsManager, {
|
||||
@@ -588,7 +609,8 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
transitionToModelPicker(activeProviderId);
|
||||
}, [
|
||||
activeProviderId,
|
||||
codexCliStatus,
|
||||
localCli,
|
||||
localCliStatus,
|
||||
providerSettingsManager,
|
||||
transitionToModelPicker,
|
||||
]);
|
||||
@@ -798,13 +820,13 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
deviceAbortRef.current = true;
|
||||
},
|
||||
resetAuth,
|
||||
refreshCodexCliStatus,
|
||||
refreshLocalCliStatus: recheckLocalCli,
|
||||
startOAuthFlow,
|
||||
startDeviceCodeFlow,
|
||||
selectProvider,
|
||||
loadModelsForProvider,
|
||||
saveClineModelSelection,
|
||||
saveCodexCliConfig,
|
||||
saveLocalCliConfig,
|
||||
saveByoConfig,
|
||||
saveModelSelection,
|
||||
saveThinkingLevel,
|
||||
@@ -820,8 +842,9 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
byoFields,
|
||||
byoFocusedField,
|
||||
byoValues,
|
||||
codexCliChecking,
|
||||
codexCliStatus,
|
||||
localCli,
|
||||
localCliChecking,
|
||||
localCliStatus,
|
||||
clineEntries,
|
||||
clineModelSelected,
|
||||
clinePassCurrentPlanName,
|
||||
@@ -860,7 +883,7 @@ export function useOnboardingController(props: OnboardingControllerProps) {
|
||||
providersLoading,
|
||||
recommendedLoading: recommended.loading,
|
||||
saveByoConfig,
|
||||
saveCodexCliConfig,
|
||||
saveLocalCliConfig,
|
||||
saveCustomModelId,
|
||||
selectedModelName,
|
||||
step,
|
||||
|
||||
@@ -51,13 +51,13 @@ export function useOnboardingKeyboard(input: {
|
||||
abortOAuth: () => void;
|
||||
abortDeviceCode: () => void;
|
||||
resetAuth: () => void;
|
||||
refreshCodexCliStatus: () => void;
|
||||
refreshLocalCliStatus: () => void;
|
||||
startOAuthFlow: (providerId: OnboardingOAuthProviderId) => void;
|
||||
startDeviceCodeFlow: (providerId: OnboardingOAuthProviderId) => void;
|
||||
selectProvider: (providerId: string) => void;
|
||||
loadModelsForProvider: (providerId: string) => void;
|
||||
saveClineModelSelection: (modelId: string, modelName: string) => void;
|
||||
saveCodexCliConfig: () => void;
|
||||
saveLocalCliConfig: () => void;
|
||||
saveByoConfig: () => void;
|
||||
saveModelSelection: () => void;
|
||||
saveThinkingLevel: (level: ThinkingLevel) => void;
|
||||
@@ -98,7 +98,7 @@ export function useOnboardingKeyboard(input: {
|
||||
input.setMenuSelected(0);
|
||||
return;
|
||||
}
|
||||
if (input.step === "codex_cli_setup") {
|
||||
if (input.step === "local_cli_setup") {
|
||||
input.setStep("byo_provider");
|
||||
return;
|
||||
}
|
||||
@@ -227,13 +227,13 @@ export function useOnboardingKeyboard(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.step === "codex_cli_setup") {
|
||||
if (input.step === "local_cli_setup") {
|
||||
if (key.name === "r") {
|
||||
input.refreshCodexCliStatus();
|
||||
input.refreshLocalCliStatus();
|
||||
return;
|
||||
}
|
||||
if (key.name === "return") {
|
||||
input.saveCodexCliConfig();
|
||||
input.saveLocalCliConfig();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { getLocalCliInfo } from "../../../utils/local-cli";
|
||||
|
||||
vi.mock("../../../utils/local-cli", () => ({
|
||||
getLocalCliInfo: () => undefined,
|
||||
}));
|
||||
|
||||
import {
|
||||
canContinueLocalCliSetup,
|
||||
getMainMenuOptions,
|
||||
getOAuthProviderLabel,
|
||||
resolveProviderSetupRoute,
|
||||
shouldUseFeaturedClineModelPicker,
|
||||
toModelEntriesFromKnownModels,
|
||||
toModelEntry,
|
||||
@@ -77,6 +85,20 @@ describe("onboarding model helpers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("marks the Claude Code provider as local auth", () => {
|
||||
expect(
|
||||
toProviderEntry({
|
||||
id: "claude-code",
|
||||
name: "Claude Code",
|
||||
models: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
id: "claude-code",
|
||||
isOAuth: false,
|
||||
isLocalAuth: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps model names and reasoning support strictly", () => {
|
||||
expect(
|
||||
toModelEntry({
|
||||
@@ -166,3 +188,31 @@ describe("onboarding model helpers", () => {
|
||||
expect(shouldUseFeaturedClineModelPicker("anthropic")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("local-auth setup routing", () => {
|
||||
// A provider can declare `local-auth` without naming a CLI we can probe.
|
||||
// Routing must follow the capability; the descriptor is only for probing.
|
||||
// Otherwise it falls through to the API-key form, which renders no fields
|
||||
// for a local-auth provider.
|
||||
it("routes a local-auth provider with no CLI descriptor to local setup", () => {
|
||||
expect(getLocalCliInfo("claude-code")).toBeUndefined();
|
||||
expect(resolveProviderSetupRoute("claude-code")).toBe("local_cli");
|
||||
});
|
||||
|
||||
it("routes OAuth and API-key providers unchanged", () => {
|
||||
expect(resolveProviderSetupRoute("anthropic")).toBe("api_key");
|
||||
});
|
||||
|
||||
// The probe only looks on PATH, while the runtime also accepts an explicit
|
||||
// pathToClaudeCodeExecutable and a bundled platform binary. A PATH miss
|
||||
// therefore means "not on PATH", not "unusable", so it must not block.
|
||||
it("lets the user continue when the CLI is not found on PATH", () => {
|
||||
const cli = { command: "claude", docsUrl: "https://example.invalid" };
|
||||
expect(
|
||||
canContinueLocalCliSetup(cli, {
|
||||
installed: false,
|
||||
reason: "The claude executable was not found on PATH.",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,14 @@ import type {
|
||||
ModelOperation,
|
||||
} from "@cline/shared";
|
||||
import { isChatProviderModel } from "../../../utils/chat-models";
|
||||
import { isOpenAICodexCliProvider } from "../../../utils/codex-cli";
|
||||
import { isOAuthProvider } from "../../../utils/provider-auth";
|
||||
import type {
|
||||
LocalCliStatus,
|
||||
ProviderLocalCli,
|
||||
} from "../../../utils/local-cli";
|
||||
import {
|
||||
isLocalAuthProvider,
|
||||
isOAuthProvider,
|
||||
} from "../../../utils/provider-auth";
|
||||
|
||||
export type OnboardingStep =
|
||||
| "menu"
|
||||
@@ -13,7 +19,7 @@ export type OnboardingStep =
|
||||
| "device_code"
|
||||
| "byo_provider"
|
||||
| "byo_apikey"
|
||||
| "codex_cli_setup"
|
||||
| "local_cli_setup"
|
||||
| "cline_pass_subscription"
|
||||
| "cline_model"
|
||||
| "model_picker"
|
||||
@@ -85,6 +91,35 @@ export const MAIN_MENU: MenuOption[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Which setup flow a provider needs. Keyed off how the provider authenticates,
|
||||
* so every caller routes the same way.
|
||||
*/
|
||||
export type ProviderSetupRoute = "oauth" | "local_cli" | "api_key";
|
||||
|
||||
export function resolveProviderSetupRoute(
|
||||
providerId: string,
|
||||
): ProviderSetupRoute {
|
||||
if (isOAuthProvider(providerId)) return "oauth";
|
||||
if (isLocalAuthProvider(providerId)) return "local_cli";
|
||||
return "api_key";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the local-CLI setup screen lets the user connect.
|
||||
*/
|
||||
export function canContinueLocalCliSetup(
|
||||
_cli: ProviderLocalCli | undefined,
|
||||
_status: LocalCliStatus | undefined,
|
||||
): boolean {
|
||||
// The probe only looks on PATH, while the runtime also accepts an explicit
|
||||
// pathToClaudeCodeExecutable and a bundled platform binary, and Codex falls
|
||||
// back through `npx`. A PATH miss therefore means "not on PATH", not
|
||||
// "unusable", so the screen reports it without blocking — a provider that
|
||||
// really cannot start says so on the first turn, in its own words.
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getMainMenuOptions(options?: {
|
||||
isClinePassEnabled?: boolean;
|
||||
}): MenuOption[] {
|
||||
@@ -174,7 +209,7 @@ export function toProviderEntry(provider: ProviderCatalogItem): ProviderEntry {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
isOAuth: isOAuthProvider(provider.id),
|
||||
isLocalAuth: isOpenAICodexCliProvider(provider.id),
|
||||
isLocalAuth: isLocalAuthProvider(provider.id),
|
||||
hasAuth:
|
||||
Boolean(provider.apiKey) || provider.oauthAccessTokenPresent === true,
|
||||
...(provider.capabilities ? { capabilities: provider.capabilities } : {}),
|
||||
|
||||
@@ -2,10 +2,10 @@ import "opentui-spinner/react";
|
||||
import type { ScrollBoxRenderable } from "@opentui/core";
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import {
|
||||
CODEX_CLI_INSTALL_URL,
|
||||
type CodexCliStatus,
|
||||
} from "../../../utils/codex-cli";
|
||||
import type {
|
||||
LocalCliStatus,
|
||||
ProviderLocalCli,
|
||||
} from "../../../utils/local-cli";
|
||||
import {
|
||||
ClineModelPicker,
|
||||
type ClineModelPickerEntry,
|
||||
@@ -25,6 +25,7 @@ import { FIELD_ORDER } from "./fields";
|
||||
import {
|
||||
type ClinePassSubscriptionOption,
|
||||
type ClinePassSubscriptionStatus,
|
||||
canContinueLocalCliSetup,
|
||||
type MenuOption,
|
||||
THINKING_LEVELS,
|
||||
} from "./model";
|
||||
@@ -362,18 +363,20 @@ export function OnboardingProviderConfigScreen(props: {
|
||||
);
|
||||
}
|
||||
|
||||
export function OnboardingCodexCliScreen(props: {
|
||||
export function OnboardingLocalCliScreen(props: {
|
||||
activeProviderName: string;
|
||||
checking: boolean;
|
||||
cli?: ProviderLocalCli;
|
||||
compact: boolean;
|
||||
contentWidth: number;
|
||||
mouse: MouseTrackerState;
|
||||
status?: CodexCliStatus;
|
||||
status?: LocalCliStatus;
|
||||
}) {
|
||||
const defaultFg = useDefaultFg();
|
||||
const colors = useOnboardingColors();
|
||||
const installedStatus =
|
||||
props.status?.installed === true ? props.status : undefined;
|
||||
const canContinue = canContinueLocalCliSetup(props.cli, props.status);
|
||||
return (
|
||||
<OnboardingFrame
|
||||
compact={props.compact}
|
||||
@@ -386,31 +389,37 @@ export function OnboardingCodexCliScreen(props: {
|
||||
{props.checking && (
|
||||
<box flexDirection="row" gap={1}>
|
||||
<spinner name="dots" color="gray" />
|
||||
<text fg="gray">Checking for Codex CLI...</text>
|
||||
<text fg="gray">Checking for {props.activeProviderName}...</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{installedStatus && (
|
||||
<box flexDirection="column" gap={1} alignItems="center">
|
||||
<text fg={colors.success}>{"\u25cf"} Codex CLI installed</text>
|
||||
<text fg={colors.success}>
|
||||
{"\u25cf"} {props.activeProviderName} installed
|
||||
</text>
|
||||
<text fg="gray">{installedStatus.version}</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{props.status && !props.status.installed && (
|
||||
{props.cli && props.status && !props.status.installed && (
|
||||
<box flexDirection="column" gap={1} width={props.contentWidth}>
|
||||
<text fg="yellow">Codex CLI was not found</text>
|
||||
<text fg="yellow">{props.activeProviderName} was not found</text>
|
||||
<text fg="gray">{props.status.reason}</text>
|
||||
<text fg="gray">Install Codex CLI from:</text>
|
||||
<text fg={colors.accent} selectable>
|
||||
{CODEX_CLI_INSTALL_URL}
|
||||
</text>
|
||||
{props.cli.docsUrl && (
|
||||
<box flexDirection="column">
|
||||
<text fg="gray">Install {props.activeProviderName} from:</text>
|
||||
<text fg={colors.accent} selectable>
|
||||
{props.cli.docsUrl}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
)}
|
||||
|
||||
<text fg="gray">
|
||||
<em>
|
||||
{installedStatus
|
||||
{canContinue
|
||||
? "Enter to continue, R to recheck, Esc to go back, Ctrl+C to exit"
|
||||
: "R to recheck, Esc to go back, Ctrl+C to exit"}
|
||||
</em>
|
||||
|
||||
@@ -7,10 +7,10 @@ import { getOAuthProviderLabel, type OnboardingResult } from "./model";
|
||||
import {
|
||||
OnboardingClineModelScreen,
|
||||
OnboardingClinePassSubscriptionScreen,
|
||||
OnboardingCodexCliScreen,
|
||||
OnboardingCustomModelIdScreen,
|
||||
OnboardingDeviceCodeScreen,
|
||||
OnboardingDoneScreen,
|
||||
OnboardingLocalCliScreen,
|
||||
OnboardingMainMenuScreen,
|
||||
OnboardingModelPickerScreen,
|
||||
OnboardingOAuthPendingScreen,
|
||||
@@ -83,15 +83,16 @@ export function OnboardingView(props: OnboardingViewProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (state.step === "codex_cli_setup") {
|
||||
if (state.step === "local_cli_setup" && state.localCli) {
|
||||
return (
|
||||
<OnboardingCodexCliScreen
|
||||
<OnboardingLocalCliScreen
|
||||
activeProviderName={state.activeProviderName}
|
||||
checking={state.codexCliChecking}
|
||||
checking={state.localCliChecking}
|
||||
cli={state.localCli}
|
||||
compact={compact}
|
||||
contentWidth={contentWidth}
|
||||
mouse={mouse}
|
||||
status={state.codexCliStatus}
|
||||
status={state.localCliStatus}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createChatCommandHost,
|
||||
@@ -202,65 +199,6 @@ describe("chat commands", () => {
|
||||
expect(reply).toHaveBeenCalledWith("hello world");
|
||||
});
|
||||
|
||||
it("changes directories with both /cd and the existing /cwd spelling", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "cli-chat-cd-"));
|
||||
const target = join(root, "project with spaces");
|
||||
mkdirSync(target);
|
||||
|
||||
for (const command of [
|
||||
`/cd "project with spaces"`,
|
||||
`/cwd "project with spaces"`,
|
||||
]) {
|
||||
const state = {
|
||||
enableTools: true,
|
||||
autoApproveTools: false,
|
||||
cwd: root,
|
||||
workspaceRoot: root,
|
||||
};
|
||||
const setState = vi.fn(async (next) => Object.assign(state, next));
|
||||
const reply = vi.fn(async () => undefined);
|
||||
|
||||
expect(
|
||||
await maybeHandleChatCommand(command, {
|
||||
enabled: true,
|
||||
getState: () => state,
|
||||
setState,
|
||||
reply,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(state.cwd).toBe(target);
|
||||
expect(setState).toHaveBeenCalledOnce();
|
||||
expect(reply).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`cwd=${target}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves the working directory unchanged when /cd is not a directory", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "cli-chat-cd-invalid-"));
|
||||
writeFileSync(join(root, "file.txt"), "not a directory");
|
||||
const setState = vi.fn(async () => undefined);
|
||||
const reply = vi.fn(async () => undefined);
|
||||
|
||||
expect(
|
||||
await maybeHandleChatCommand("/cd file.txt", {
|
||||
enabled: true,
|
||||
getState: () => ({
|
||||
enableTools: true,
|
||||
autoApproveTools: false,
|
||||
cwd: root,
|
||||
workspaceRoot: root,
|
||||
}),
|
||||
setState,
|
||||
reply,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(setState).not.toHaveBeenCalled();
|
||||
expect(reply).toHaveBeenCalledWith(
|
||||
`invalid directory: ${join(root, "file.txt")}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("shows usage for /team with no arguments", async () => {
|
||||
const reply = vi.fn(async () => undefined);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { stat } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import { resolveWorkspaceRoot } from "./helpers";
|
||||
|
||||
@@ -217,22 +216,6 @@ function tokenizeArgs(input: string): string[] {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function resolveChatCommandDirectory(cwd: string, args: string[]): string {
|
||||
const rawPath = args.join(" ").trim();
|
||||
const unquotedPath =
|
||||
(rawPath.startsWith('"') && rawPath.endsWith('"')) ||
|
||||
(rawPath.startsWith("'") && rawPath.endsWith("'"))
|
||||
? rawPath.slice(1, -1)
|
||||
: rawPath;
|
||||
if (unquotedPath === "~") {
|
||||
return homedir();
|
||||
}
|
||||
if (unquotedPath.startsWith("~/")) {
|
||||
return resolve(homedir(), unquotedPath.slice(2));
|
||||
}
|
||||
return resolve(cwd, unquotedPath);
|
||||
}
|
||||
|
||||
function parseFlagValues(tokens: string[]): {
|
||||
positionals: string[];
|
||||
flags: Record<string, string>;
|
||||
@@ -299,7 +282,7 @@ function formatHelp(state: ChatCommandState): string {
|
||||
"/whereami - show thread, cwd, tools, and yolo state",
|
||||
"/tools [on|off|toggle] - allow repo/file/shell tools",
|
||||
"/yolo [on|off|toggle] - auto-approve tool use",
|
||||
"/cd <path> (or /cwd <path>) - change working directory",
|
||||
"/cwd <path> - change working directory",
|
||||
"/schedule create/list/trigger/delete - manage scheduled workflows",
|
||||
"/abort - stop the current task",
|
||||
"/mute [target] - ignore this thread or target until /unmute",
|
||||
@@ -415,7 +398,7 @@ function createDefaultChatCommandHost(): ChatCommandHost {
|
||||
},
|
||||
})
|
||||
.register("command", {
|
||||
names: ["/cd", "/cwd"],
|
||||
names: ["/cwd"],
|
||||
run: async ({ args, state }, context) => {
|
||||
const rawPath = args.join(" ").trim();
|
||||
if (!rawPath) {
|
||||
@@ -424,7 +407,7 @@ function createDefaultChatCommandHost(): ChatCommandHost {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const nextCwd = resolveChatCommandDirectory(state.cwd, args);
|
||||
const nextCwd = resolve(state.cwd, rawPath);
|
||||
const fileStat = await stat(nextCwd).catch(() => undefined);
|
||||
if (!fileStat?.isDirectory()) {
|
||||
await context.reply(`invalid directory: ${nextCwd}`);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export const OPENAI_CODEX_CLI_PROVIDER_ID = "openai-codex-cli";
|
||||
export const CODEX_CLI_INSTALL_URL = "https://developers.openai.com/codex/cli";
|
||||
|
||||
export type CodexCliStatus =
|
||||
| {
|
||||
installed: true;
|
||||
version: string;
|
||||
}
|
||||
| {
|
||||
installed: false;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export function isOpenAICodexCliProvider(providerId: string): boolean {
|
||||
return providerId.trim().toLowerCase() === OPENAI_CODEX_CLI_PROVIDER_ID;
|
||||
}
|
||||
|
||||
export async function checkCodexCliInstalled(): Promise<CodexCliStatus> {
|
||||
try {
|
||||
const result = await execFileAsync("codex", ["--version"], {
|
||||
timeout: 3000,
|
||||
windowsHide: true,
|
||||
});
|
||||
const version = (result.stdout || result.stderr).trim();
|
||||
return {
|
||||
installed: true,
|
||||
version: version || "codex",
|
||||
};
|
||||
} catch (error) {
|
||||
const details =
|
||||
error && typeof error === "object"
|
||||
? (error as { code?: unknown; message?: unknown })
|
||||
: undefined;
|
||||
const code = typeof details?.code === "string" ? details.code : "";
|
||||
if (code === "ENOENT") {
|
||||
return {
|
||||
installed: false,
|
||||
reason: "The codex executable was not found on PATH.",
|
||||
};
|
||||
}
|
||||
const message =
|
||||
typeof details?.message === "string"
|
||||
? details.message
|
||||
: "Could not run codex --version.";
|
||||
return {
|
||||
installed: false,
|
||||
reason: message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { isLocalAuthProvider } from "@cline/core";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getLocalCliInfo } from "./local-cli";
|
||||
|
||||
describe("local CLI providers", () => {
|
||||
it("reads the CLI a local-auth provider borrows credentials from", () => {
|
||||
expect(getLocalCliInfo("openai-codex-cli")).toEqual({
|
||||
command: "codex",
|
||||
docsUrl: "https://developers.openai.com/codex/cli",
|
||||
});
|
||||
expect(getLocalCliInfo("claude-code")).toEqual({
|
||||
command: "claude",
|
||||
docsUrl: "https://code.claude.com/docs/en/setup",
|
||||
});
|
||||
});
|
||||
|
||||
it("names no CLI for providers that authenticate with an API key", () => {
|
||||
expect(getLocalCliInfo("anthropic")).toBeUndefined();
|
||||
expect(getLocalCliInfo("openai-codex")).toBeUndefined();
|
||||
});
|
||||
|
||||
// Routing is keyed off the capability alone, so a local-auth provider whose
|
||||
// credentials come from somewhere unprobeable still reaches the local setup
|
||||
// screen instead of an empty API-key form.
|
||||
it("routes on the capability, not on knowing a CLI", () => {
|
||||
expect(isLocalAuthProvider("claude-code")).toBe(true);
|
||||
expect(isLocalAuthProvider("openai-codex-cli")).toBe(true);
|
||||
expect(isLocalAuthProvider("anthropic")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { Llms } from "@cline/core";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export type ProviderLocalCli = Llms.ProviderLocalCli;
|
||||
|
||||
export type LocalCliStatus =
|
||||
| {
|
||||
installed: true;
|
||||
version: string;
|
||||
}
|
||||
| {
|
||||
installed: false;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The CLI a `local-auth` provider borrows credentials from, as declared in
|
||||
* the provider catalog. `undefined` for providers that name none — those are
|
||||
* connected without a readiness check rather than probing a guessed command.
|
||||
*/
|
||||
export function getLocalCliInfo(
|
||||
providerId: string,
|
||||
): ProviderLocalCli | undefined {
|
||||
return Llms.resolveProviderLocalCli(providerId);
|
||||
}
|
||||
|
||||
export async function checkLocalCliInstalled(
|
||||
cli: ProviderLocalCli,
|
||||
): Promise<LocalCliStatus> {
|
||||
try {
|
||||
const result = await execFileAsync(cli.command, ["--version"], {
|
||||
timeout: 3000,
|
||||
windowsHide: true,
|
||||
});
|
||||
const version = (result.stdout || result.stderr).trim();
|
||||
return {
|
||||
installed: true,
|
||||
version: version || cli.command,
|
||||
};
|
||||
} catch (error) {
|
||||
const details = error as NodeJS.ErrnoException | undefined;
|
||||
if (details?.code === "ENOENT") {
|
||||
return {
|
||||
installed: false,
|
||||
reason: `The ${cli.command} executable was not found on PATH.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
installed: false,
|
||||
reason:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: `Could not run ${cli.command} --version.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { UserInstructionConfigService } from "@cline/core";
|
||||
|
||||
export interface MutableUserInstructionConfigService
|
||||
extends UserInstructionConfigService {
|
||||
assertCompatible(next: UserInstructionConfigService): void;
|
||||
replace(next: UserInstructionConfigService): UserInstructionConfigService;
|
||||
}
|
||||
|
||||
export function createMutableUserInstructionConfigService(
|
||||
initial: UserInstructionConfigService,
|
||||
): MutableUserInstructionConfigService {
|
||||
let current = initial;
|
||||
const hasSkillsExecutor = typeof initial.createSkillsExecutor === "function";
|
||||
const assertCompatible = (next: UserInstructionConfigService): void => {
|
||||
if (
|
||||
(typeof next.createSkillsExecutor === "function") !==
|
||||
hasSkillsExecutor
|
||||
) {
|
||||
throw new Error(
|
||||
"Replacement instruction service has incompatible skills capability",
|
||||
);
|
||||
}
|
||||
};
|
||||
const service: UserInstructionConfigService = {
|
||||
start: () => current.start(),
|
||||
stop: () => current.stop(),
|
||||
refreshType: (type) => current.refreshType(type),
|
||||
listRecords: (type) => current.listRecords(type),
|
||||
listRuntimeCommands: () => current.listRuntimeCommands(),
|
||||
resolveRuntimeSlashCommand: (input) =>
|
||||
current.resolveRuntimeSlashCommand(input),
|
||||
hasConfiguredSkills: (allowedSkillNames) =>
|
||||
current.hasConfiguredSkills(allowedSkillNames),
|
||||
createExtension: (options) => current.createExtension(options),
|
||||
};
|
||||
if (hasSkillsExecutor) {
|
||||
service.createSkillsExecutor = (allowedSkillNames) => {
|
||||
if (!current.createSkillsExecutor) {
|
||||
throw new Error(
|
||||
"Replacement instruction service has no skills executor",
|
||||
);
|
||||
}
|
||||
return current.createSkillsExecutor(allowedSkillNames);
|
||||
};
|
||||
}
|
||||
return {
|
||||
...service,
|
||||
assertCompatible,
|
||||
replace: (next) => {
|
||||
assertCompatible(next);
|
||||
const previous = current;
|
||||
current = next;
|
||||
return previous;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
formatProviderOAuthApiKey,
|
||||
getPersistedProviderApiKey as getCorePersistedProviderApiKey,
|
||||
isLocalAuthProvider,
|
||||
isOAuthProvider,
|
||||
Llms,
|
||||
type ProviderOAuthCredentials,
|
||||
@@ -21,7 +22,7 @@ export function normalizeAuthProviderId(providerId: string): string {
|
||||
return normalizeProviderId(normalized);
|
||||
}
|
||||
|
||||
export { isOAuthProvider };
|
||||
export { isLocalAuthProvider, isOAuthProvider };
|
||||
|
||||
export function toProviderApiKey(
|
||||
providerId: string,
|
||||
|
||||
@@ -109,7 +109,9 @@ export async function handleDesktopCommand(
|
||||
const provider = String(args?.provider ?? "").trim();
|
||||
return await getLocalProviderModels(
|
||||
provider,
|
||||
providerSettingsManager.getProviderConfig(provider),
|
||||
providerSettingsManager.getProviderConfig(provider, {
|
||||
includeKnownModels: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (command === "save_provider_settings") {
|
||||
|
||||
@@ -85,7 +85,9 @@ export async function loadModels(
|
||||
if (!provider) return;
|
||||
const payload = await getLocalProviderModels(
|
||||
provider,
|
||||
providerSettingsManager.getProviderConfig(provider),
|
||||
providerSettingsManager.getProviderConfig(provider, {
|
||||
includeKnownModels: false,
|
||||
}),
|
||||
);
|
||||
const models: WebviewProviderModel[] = payload.models
|
||||
.filter((model) =>
|
||||
|
||||
@@ -60,6 +60,7 @@ import { desktopClient } from "@/lib/desktop-client";
|
||||
import { readModelSelectionStorageFromWindow } from "@/lib/model-selection";
|
||||
import { normalizeProviderId } from "@/lib/provider-id";
|
||||
import {
|
||||
filterChatModels,
|
||||
loadProviderModelCatalog,
|
||||
loadProviderModels,
|
||||
} from "@/lib/provider-model-catalog";
|
||||
@@ -492,7 +493,9 @@ export function RoutineSchedulesContent() {
|
||||
|
||||
async function loadModelsForProvider() {
|
||||
try {
|
||||
const models = await loadProviderModels(normalizedProvider);
|
||||
const models = filterChatModels(
|
||||
await loadProviderModels(normalizedProvider),
|
||||
);
|
||||
if (cancelled || models.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -16,57 +16,48 @@ export type ProviderModelCatalog = {
|
||||
providerReasoningModels: Record<string, string[]>;
|
||||
};
|
||||
|
||||
function toModelIds(models: ProviderModel[] | undefined): string[] {
|
||||
return (models ?? [])
|
||||
.filter((model) =>
|
||||
isChatCompatibleModel({
|
||||
operation: model.operation,
|
||||
modalities: {
|
||||
input: model.inputModalities,
|
||||
output: model.outputModalities,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.map((model) => model.id);
|
||||
}
|
||||
|
||||
function toReasoningModelIds(models: ProviderModel[] | undefined): string[] {
|
||||
return (models ?? [])
|
||||
.filter(
|
||||
(model) =>
|
||||
model.supportsReasoning &&
|
||||
isChatCompatibleModel({
|
||||
operation: model.operation,
|
||||
modalities: {
|
||||
input: model.inputModalities,
|
||||
output: model.outputModalities,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.map((model) => model.id);
|
||||
export function filterChatModels(
|
||||
models: ProviderModel[] | undefined,
|
||||
): ProviderModel[] {
|
||||
return (models ?? []).filter((model) =>
|
||||
isChatCompatibleModel({
|
||||
operation: model.operation,
|
||||
modalities: {
|
||||
input: model.inputModalities,
|
||||
output: model.outputModalities,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function buildProviderModelCatalog(
|
||||
providers: Provider[],
|
||||
): ProviderModelCatalog {
|
||||
const providerEntries = providers.map((provider) => {
|
||||
const chatModels = filterChatModels(provider.modelList);
|
||||
return {
|
||||
provider,
|
||||
modelIds: chatModels.map((model) => model.id),
|
||||
reasoningModelIds: chatModels
|
||||
.filter((model) => model.supportsReasoning)
|
||||
.map((model) => model.id),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
providers,
|
||||
enabledProviderIds: providers
|
||||
enabledProviderIds: providerEntries
|
||||
.filter(
|
||||
(provider) =>
|
||||
provider.enabled && toModelIds(provider.modelList).length > 0,
|
||||
({ provider, modelIds }) => provider.enabled && modelIds.length > 0,
|
||||
)
|
||||
.map((provider) => provider.id),
|
||||
.map(({ provider }) => provider.id),
|
||||
providerModels: Object.fromEntries(
|
||||
providers.map((provider) => [
|
||||
provider.id,
|
||||
toModelIds(provider.modelList),
|
||||
]),
|
||||
providerEntries.map(({ provider, modelIds }) => [provider.id, modelIds]),
|
||||
),
|
||||
providerReasoningModels: Object.fromEntries(
|
||||
providers.map((provider) => [
|
||||
providerEntries.map(({ provider, reasoningModelIds }) => [
|
||||
provider.id,
|
||||
toReasoningModelIds(provider.modelList),
|
||||
reasoningModelIds,
|
||||
]),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -1,5 +1,103 @@
|
||||
# Cline Desktop Changelog
|
||||
|
||||
## 0.0.29
|
||||
|
||||
- Queued messages can now be sent into the running turn with Enter. While the agent is working, pressing Enter with an empty composer steers the first message in the queue, so it is picked up at the next turn boundary instead of waiting for the whole task to finish; the composer placeholder says so whenever the queue is non-empty. The queue head is claimed atomically, so a fast second Enter can't steer a message that has already left the queue, and a steer that fails now surfaces as a toast rather than silently doing nothing
|
||||
- The macOS Dock icon now has the standard margin other apps use. The bundled icon and the selectable runtime icons (Classic, Chip, Hologram, Midnight) were edge-to-edge, so Cline rendered visibly larger than its neighbours in the Dock. Windows keeps its existing artwork
|
||||
- The session sidebar's sort toggle now shows the mode a click switches to, not the one already active — a folder icon while sorted by time, a clock while grouped by project
|
||||
|
||||
## 0.0.28
|
||||
|
||||
- The app no longer gets stuck on "Desktop backend unavailable" when the backend is slow to start. The window asked for the backend's address exactly once and the shell stops waiting after about 15 seconds, so on a slower machine — where starting the hub pushed past that — you were left on the error screen until you relaunched, and the relaunch could lose the same race. Connection attempts now keep retrying and re-resolve the address each time, so a backend that has since restarted is reached at its current one
|
||||
- Confirming text with a Chinese or Japanese IME no longer sends the message. The Enter that commits an in-progress composition also reached the composer, so choosing a candidate fired off a half-typed message; Enter and the arrow keys now belong to the IME while you are composing
|
||||
- The model picker refreshes its list every time you open it, instead of staying frozen until you restart the app. The Recommended and Free groupings come from a live feed, so a newly promoted free model would otherwise not show up for the rest of the session
|
||||
- Signing in with Cline now explains what the plan includes. The sign-in card lists the regular free model promotions, ClinePass for generous usage across open-weight models like DeepSeek, Kimi, and GLM, and that no API key is needed; the last onboarding step then shows the current free models alongside a ClinePass summary. This only appears when you sign in with Cline, not when you bring your own API key
|
||||
- Cline Pass now starts you on a model from your subscription. Its model list carries both subscription and free models and the default was simply the most recently published entry, so a subscriber who never picked a model was left on a free model instead of the tier they pay for
|
||||
- A turn that fails partway through with a temporary provider error is now retried up to three times instead of failing the task. A single rate-limit response passed along by a provider gateway previously ended the turn outright. A turn that has already produced output is never retried, so nothing is duplicated
|
||||
- Long responses stream faster. Every chunk of a streaming reply was being handed to client-side hooks as a round trip carrying a full copy of the session, with the agent waiting on each one before continuing
|
||||
- The command-running tool now tells the model which PowerShell edition it is talking to — `Windows PowerShell (powershell.exe)` versus `PowerShell (pwsh.exe)` — and to write commands directly rather than wrapping them in a second shell invocation, which was corrupting pipelines that use `$_`
|
||||
- Refreshed the model catalog. Adds three providers (Infer by Flow7, Melious, and Wallaby) and takes the catalog from 5,923 to 6,079 models. The resolved default model changes for 33 providers, most of them landing on DeepSeek V4.1 Flash — among them Hugging Face, Fireworks, Requesty, Cortecs, CrossModel, DigitalOcean, Eden AI, and OpenCode Go — while NVIDIA moves to GLM 5.3 Flash and NanoGPT to GPT Astra. If you use a provider without pinning a model, expect a different default
|
||||
|
||||
## 0.0.27
|
||||
|
||||
- An expired Cline sign-in now produces one actionable error instead of two dead ends. A turn that fails before the runtime takes the prompt was reported twice — the hub's detail-less `run.failed` appended a bubble, then the send RPC resolved with the real error and overwrote the error banner underneath it — so you got a vague bubble stacked on a detailed banner. The failure now renders exactly once, upgrading in place when the detailed report arrives. Credential failures also carry a fix button: **Sign in to Cline** for the Cline provider (Settings → API Providers reads a stale token as "Signed in via browser", so there is nothing to fix there), **Open model settings** for others, and local-CLI providers keep pointing at their CLI. Sessions that fail to start over credentials get the same hint and action
|
||||
- The Account page now offers a sign-in prompt when your Cline refresh token is rejected, instead of an error card whose **Retry** failed the same way. A rejected refresh was falling back to the persisted access token, which is dead too, so the account request 401'd; a rejected refresh now reports as signed out. Transient refresh failures still fall back
|
||||
- Signing out of Cline and Cline Pass now sticks. Sign-out removes the provider entry, but the runtime re-imports missing providers from the classic extension's stored credentials on every command, so you appeared signed straight back in — the same root cause as the ChatGPT/Codex fix in 0.0.26, which only cleared Codex secrets. Cline Pass sign-out did nothing at all, because its credentials live under the Cline provider entry rather than its own
|
||||
- The settings sidebar's **Models** section is now **API Providers**, with an icon to match — it is where you configure providers and their credentials, not where you pick a model
|
||||
- A failed voice input now shows a "Speech input failed" toast in chat with the actual error, instead of dropping you into Settings → Voice. Any error that wasn't a browser exception was treated as a configuration problem, even though the microphone is already gated on a configured transcription model — so a connection or transcription failure interrupted the chat and hid the real reason. Your draft and the microphone button stay put so you can retry; microphone-permission guidance is unchanged
|
||||
- OpenCode Go models work again. Requests were missing the `x-opencode-session` header Go requires to route a conversation ("Request is missing x-opencode-session and cannot be routed efficiently"), and every model was sent to `/chat/completions` because catalog normalization discarded the per-model adapter declaration — so Muse Spark, GPT, and Grok models that expect `/responses`, and MiniMax/Qwen models that expect `/messages`, failed with internal server errors. Model-level protocol routing is now preserved end to end, retries reuse the same session identity, and Go Qwen entries that omit the declaration fall back to Messages
|
||||
- Added Crusoe as an OpenAI-compatible provider
|
||||
- Settings switches are lighter in light mode and are now a shared native control — real keyboard, label, and form behavior, a guaranteed 24px hit area, and support for reduced-motion and forced-colors
|
||||
- The welcome screen's eye color matches the dark theme, and its animation no longer triggers layout work each frame
|
||||
|
||||
## 0.0.26
|
||||
|
||||
- The composer now shows the current branch's GitHub pull request — PR number, merge status, changed-line totals, and CI checks. Click through to open it in your browser, or expand CI to inspect individual checks and their logs; status refreshes every 30 seconds while visible, on window focus, and on demand. If the branch has no PR, **Create PR** opens GitHub's comparison form. Requires the GitHub CLI (`gh`) installed and signed in, plus a GitHub.com `origin` remote; the row hides itself on the default branch, detached HEAD, and unsupported repositories. Cline does not push commits or submit the PR for you
|
||||
- The Customize view's Tools, Skills, and Rules tabs now read as one consistent list instead of three different ones, matching the pattern Plugins already used. Tools gets a search bar that filters both sections and per-section Enable all/Disable all that only touches what's visible; Skills gets an in-place enable/disable toggle — previously the desktop app had no concept of a disabled skill, so disabled ones were hidden and unreachable — and the same Copy path / Uninstall menu Plugins use. Tabs are reordered to Tools, Plugins, Skills, Rules, MCP, Hooks and open on Tools, and the sidebar's "New Task" button is now "New Session"
|
||||
- Deleting a queued prompt no longer leaves it in the transcript as a message that never ran. The sidecar inferred a queued prompt had started whenever the pending list shrank and its head changed — which is exactly what deleting the first queued prompt (or discarding the queue) looks like. It now relies only on the runtime's real start event
|
||||
- A session forked from a checkpoint restore no longer comes back stuck on "Thinking...". Sessions that materialize with seeded history never passed their status when persisting, so the row and manifest were written as "running" while the live session was idle; resuming from that manifest then showed a session that was never going to finish
|
||||
- Sending an image with no text no longer fails with "session input requires a prompt string" — the composer asks for a message instead of letting the request through to a backend that rejects it
|
||||
- Image attachments in formats the model pipeline can't read (HEIC, TIFF, SVG, BMP, ICO, and friends) are now rejected at attach time — by picker, paste, or drag-and-drop — instead of failing later in the turn. Files whose type has to be inferred from the extension are classified the same way
|
||||
- Signing out of ChatGPT (Codex) now sticks. Sign-out removes the provider entry, but the runtime re-imports any missing provider from the classic extension's stored credentials on every command, so the next action signed you straight back in. The legacy Codex credentials are now cleared too, and a failed clear reports the sign-out as failed instead of quietly succeeding
|
||||
- Auth failures on providers that log in through a local CLI — Claude Code, Codex CLI, OpenCode — now point you at that CLI instead of Settings → Models, where there is nothing to fix. "OAuth session expired", "Not logged in · Please run /login", and similar messages are also recognized as credential failures now, so they get a hint at all
|
||||
- Model lists now refresh from the live catalog for every provider that uses the shared catalog, not just Cline and Cline Pass. Providers with their own endpoint-owned model lists are unaffected, and the first providers listing is still network-free
|
||||
- Cline Pass and free models now report zero cost instead of the upstream provider's price
|
||||
- Session history rows no longer overlap their own hover metadata when a label is wider than the fixed label column
|
||||
- Scheduled sessions no longer stall out. The poller could stop advancing, and capacity waits were counted as run attempts, so a schedule could burn through its retries without ever running. Execution lifecycle and capacity claims are now fenced atomically. New recurring schedules also default to your local timezone instead of UTC; existing schedules without a timezone keep it that way when edited
|
||||
- Automation event acceptance is now atomic and retryable, so an event can't be half-accepted and lost if delivery fails mid-way
|
||||
- Nested PowerShell commands no longer flood errors and look like a hang. Commands run through an outer PowerShell bootstrap, so a nested `powershell -Command "... $_ ..."` had `$_` interpolated away by the outer parser before the inner shell saw it — a `Where-Object { $_.Name ... }` pipeline then errored once per item over a large tree while still exiting 0. Redundant nested invocations are now unwrapped and run directly, only when that provably preserves semantics (same PowerShell edition, no profile loading, fully quoted command). Cline is also told which edition it's actually on — Windows PowerShell vs. Microsoft PowerShell — and to stop wrapping commands in a shell it's already running in
|
||||
- Prompt telemetry to Cline's tracing backend is now limited to Cline and Cline Pass requests. Turns run against your own provider keys are not traced
|
||||
- Cline Pass now appears in the composer's provider picker alongside Cline. One Cline sign-in configures both — Cline Pass stores its credentials under the Cline account rather than having its own — but the picker only listed providers with their own saved settings entry, and onboarding writes just the Cline one. A new Cline Pass user therefore saw a single row
|
||||
- The composer's provider picker has a **Set up another provider** row at the bottom that opens Settings → Models. The picker only lists what you have already configured, so there was no way to reach the rest of the catalog from the composer
|
||||
- Dropped the "Configured" checkmark from the composer's provider picker (added in 0.0.25). Every row in that picker has a saved settings entry, so for anyone who set their providers up in the app every row carried the same green check and it read as decoration. Settings is still where provider readiness is shown, and it distinguishes a real credential from an entry a legacy migration left behind
|
||||
|
||||
## 0.0.25
|
||||
|
||||
- ChatGPT Subscription (Codex) now lists only the models your plan can actually use. Two separate paths filled the picker from the shared OpenAI catalog, so GPT-4o, GPT-4.1, and `chatgpt-image-latest` showed up alongside the Codex models, and the runtime lost the Codex context caps. The model rules also match what the backend now accepts: `gpt-5.4` and `gpt-5.4-mini` were retired for ChatGPT accounts on 2026-08-31 and are gone, the default moves to `gpt-5.6-terra`, and every Codex model is capped at the real 400K/272K/128K backend budget instead of inheriting the API's 1.05M limits
|
||||
- Windows updates no longer fail with "Error opening file for writing". The compiled sidecar re-executes itself as the detached Cline Hub daemon, which outlives the app by design, and Tauri's NSIS installer only kills the main binary — so the daemon still held `code-sidecar.exe` and the install stopped until you killed the process by hand. The installer now stops it first, matched on the full path so updating one channel does not take down a side-by-side Cline Beta's sessions
|
||||
- Your prompt is no longer lost when a send fails before the turn starts — switching to Codex and having the OAuth refresh throw, for instance. The runtime never took the prompt, so post-send hydration wiped the optimistic bubble and you had to retype it. The text and attachments now come back to the composer, merged with anything you attached while the send was pending, and left alone if you have already started typing something else
|
||||
- Providers that authenticate through a local CLI — Claude Code, Codex CLI — can now start sessions without an API key. They showed as Configured in Settings via their local-auth capability, but session start still refused them with "Missing API key"
|
||||
- OpenCode is now treated as a local CLI provider rather than an OAuth one, so it shows the local CLI notice instead of a browser sign-in button that could not do anything. It authenticates from the credentials the opencode CLI itself stores
|
||||
- Session import from Claude Code, Codex, and opencode has its own page in Settings instead of a row buried in General
|
||||
- The composer's provider picker now marks which providers you have already configured
|
||||
- The model picker distinguishes models that share a name, and Cline Pass subscription models are listed separately from the free fallback tier
|
||||
- Published DMGs use the intended window layout and background again. Tauri skips the Finder AppleScript that applies them whenever `CI` is set, which GitHub Actions always sets, so every DMG since the artwork landed shipped with a stock Finder window even though the artwork was generated and validated
|
||||
- Cline's recommended, free, and subscribed model lists now ship with the app, so they are correct at first launch instead of waiting on a live catalog fetch
|
||||
- Refreshed the model catalog. Adds NaN (nan.builders) and changes the resolved default model for 36 providers — including Bedrock, Vertex, OpenRouter, Kilo, GitHub Copilot, Gemini, Cerebras, Fireworks, Requesty, and Vercel AI Gateway. Several move off Claude Fable 5.1 to GPT-6 Astra, Vertex goes to Gemini 3.8 Flash, and OpenRouter/Kilo to Inception Mercury 2.5. If you use one of those without pinning a model, expect a different default
|
||||
|
||||
## 0.0.24
|
||||
|
||||
- Fixed the live chat stream doubling text and dropping messages mid-turn. The sidecar has two Hub sockets that both receive a session's events — ClineCore's own client and the observer client — and a session that streams without a local send first (a run already in flight when you open the task, a resumed run, a scheduled run) had every delta rendered twice. The observer's copy is now skipped whenever ClineCore is subscribed to the session, asked directly rather than inferred from a timer, so long commands, slow first tokens, and unanswered tool approvals cannot let a duplicate slip through ahead of the core copy. Separately, when the sidecar was replaced under a live webview (crash-respawn, Hub drain-and-replace, stale-sidecar swap) its stream counter restarted at 1 and the webview silently discarded everything until the new process counted past the old run — this dropped your own message bubbles and tool rows, not just assistant text, which is why rows appeared to vanish mid-turn and come back afterwards
|
||||
- Fixed a queued prompt's own message vanishing from the chat. When you queue a prompt behind a running turn, the runtime drains the queue just before it answers the previous send, so the previous turn's completion path replaced the whole transcript from a canonical read that predated your queued message — erasing your bubble and leaving the reply streaming in under no user message. That path now defers to the newer turn instead of treating the transcript as its own. Two symptoms rode on the same bug: the composer no longer drops out of its busy state while the queued reply is still pending, and a finished reasoning row now reads "Thought for Ns" instead of a stuck "Thinking" — live rows are stamped on the webview's clock, so a sidecar whose clock trails it (a remote Hub, the browser-dev setup) no longer produces a negative duration that gets dropped
|
||||
- Cline no longer stops silently mid-task when a model gets stuck repeating itself. The loop detector stops a run after 5 identical tool calls and the mistake tracker after 6 consecutive failures, but the desktop never registered a decision callback, so the run just ended and the composer went idle with no message. You are now asked how to continue — "Try a different approach" or "Stop this run" — and the guidance is steered into the running turn so the model knows why it was paused instead of repeating the same call
|
||||
- The `editor` tool's error message now names the file, says whether `old_text` was null or omitted, and states how to recover. Models that fill optional parameters with null (seen with kimi-k3) hit a terse "old_text is required" and re-sent the identical call until the loop detector stopped the run
|
||||
- Fixed your Cline Pass model selection being replaced when you start a new chat. Catalogs are discovery data, not validation — the bundled catalog can omit live Cline Pass models and refreshes can return partial lists, so a model missing from the catalog was treated as invalid and silently swapped for a default
|
||||
- Cline Desktop now has a custom title bar on Windows, with caption controls that follow the compact title-bar height in narrow windows and stay above overlays. The Windows taskbar icon was also updated
|
||||
- Token counts and costs now fill in for every session you can see. The sessions view only ever hydrated the four most recent rows, so every other row showed "-" and paging never asked for more; the visible page is now hydrated on demand, with reads capped and re-run when a session's status changes underneath them
|
||||
- Sessions imported from Claude Code, Codex, and opencode now say so in the chat, and their foreign history is summarized on the first resumed turn. Imported transcripts keep the source tool's own tool names and schemas, which a model continuing them may try to call — the summary runs once, the original transcript stays intact, and the "Thinking..." indicator reads "Summarizing the imported <tool> history..." while it happens
|
||||
- Fixed session history rendering empty when one session had many subagent or team-task children. Child rows always sort after the root that spawned them, so a single busy session could hide itself and every older session from the sidebar with no way to load more
|
||||
- Checkpoints no longer re-hash every untracked file before each message. Checkpoint creation rebuilt a throwaway git index each turn, so multi-GB untracked data blocked every message for seconds to minutes (~90s in one report on a cloud-synced Windows workspace). One snapshot index is now kept per session, so from the second turn the cost is roughly git process overhead. Snapshot contents are byte-identical to before
|
||||
- Commands that background a child process (`cmd &`, `nohup`, and the same from Git Bash) no longer hang until the timeout. The inherited stdio pipes stay open after the shell exits, so the completion event never arrived even though the command was done; these now settle with the real exit code and a note that background output is no longer captured
|
||||
- Typing an `@` mention from your home directory no longer indexes your entire home folder. That could take memory into the gigabytes and get the process killed; the home directory and filesystem root are now skipped entirely
|
||||
- Web search is now enabled by default outside YOLO mode, and tool settings fail closed if they cannot be loaded
|
||||
- Claude Code no longer asks for an API key it never reads. It authenticates from the local `claude` CLI's own credential store, but was reported as an API-key provider, so a keyless entry was refused and the workaround was to save a dummy key
|
||||
- Pasted credentials with invisible characters no longer persist corrupted. A BOM or zero-width character carried in from a copy-paste produced 401s indistinguishable from a wrong key; credential fields are now stripped of control and format characters on save
|
||||
- Starting a new task no longer flickers through the idle state. The Hub publishes the new session's record as "idle" while the start request is still in flight, so the composer placeholder and the request indicator switched to idle and back for a frame on every new task. A transient idle arriving during a submission is now held back; a real failure or abort still applies immediately
|
||||
- The model picker keeps section headers visible while you search. Cline Pass lists the same model in both the Subscribed and Free tiers, so flattening the sections during search produced two identical-looking rows
|
||||
- `apply_patch` "Add File" now refuses to overwrite an existing file instead of silently replacing it
|
||||
- Fixed session import paths resolving incorrectly on Windows
|
||||
- The desktop backend now starts off the command path, so startup no longer blocks the UI
|
||||
- The SDK can now connect to authenticated remote Hubs
|
||||
|
||||
## 0.0.23
|
||||
|
||||
- Agent Plugins are now discovered and run by the shared Hub. Packages under `~/.agents/plugins` are validated from their `plugin.json`, their valid Agent Skills become available to the agent, and their stdio / Streamable HTTP / SSE MCP servers start automatically. Settings → Customize lists Agent Plugins separately from Cline Plugins, with each plugin's description, badge, and contributed tools, and enable/disable is Hub-managed per plugin. Workspace `.agents/plugins` directories are intentionally ignored
|
||||
- The "Cline Hub was updated" dialog no longer appears on every launch and reconnect. The app no longer prompts about a Hub running the same core version it does — a desktop and CLI release cut from different commits bundle the same core but never share a build fingerprint, so anyone with both installed got a dialog whose "Update and restart" looped on "no app update available". The build-mismatch dialog now also waits until an app update is actually staged, and "Later" sticks across session switches, reloads, and relaunches instead of resurfacing every time. A Hub the app genuinely cannot talk to still warns every time
|
||||
- Signing in now shows the device confirmation code in the app while you wait on the browser, so you can match it against the code the browser asks you to confirm — in onboarding, Account settings, and the provider list
|
||||
- Voice input failures caused by provider setup — missing credentials, transcription config — now take you straight to voice settings instead of a toast you cannot act on. Genuine microphone permission failures still toast, with a clearer message
|
||||
- Fixed the scheduled-task report vanishing when a finished run's step collapsed
|
||||
- Fixed one wedged MCP server blocking the rest from shutting down, leaking their processes
|
||||
|
||||
## 0.0.22
|
||||
|
||||
- Import your history from Claude Code, Codex, and opencode. An Import button in the Sessions header (and a row in Settings → General) scans your local stores from all three tools and turns the conversations you pick into fully resumable Cline sessions. Sessions are grouped per tool with select-all and a search across title, folder, and first prompt; already-imported ones are shown as such so re-opening the dialog is safe. Imported sessions resume on your configured provider and model, not the source tool's. If you have history from any of these tools, onboarding now offers the import as a step
|
||||
|
||||
@@ -10,13 +10,76 @@ From `apps/examples/desktop-app/`:
|
||||
- `bun run dev:web` - Next.js UI only (approval-gated tools require `dev:headless` or the native app)
|
||||
- `bun run dev:sidecar` - sidecar backend only (approval-gated tools require `dev:headless` or the native app)
|
||||
- `bun run dev` - Tauri desktop dev
|
||||
- `bun run build` - build web assets
|
||||
- `bun run build:web` - build production web assets only (includes the shared UI build)
|
||||
- `bun run build` - build web assets and the sidecar binary
|
||||
- `bun run build:sidecar` - build the Bun sidecar bundle
|
||||
- `bun run build:sidecar:bin` - compile the Bun sidecar into a local binary
|
||||
- `bun run build:binary` - build desktop binary
|
||||
- `bun run package:desktop` - package the current OS desktop app into `dist/desktop/`
|
||||
- `bun run typecheck` - TypeScript check
|
||||
|
||||
### Checking webview changes
|
||||
|
||||
Run `bun run build:web` from this directory when changing webview imports or shared browser APIs. Type checking and Vitest do not check the production browser bundle: a valid TypeScript import can still pull Node-only modules into a client chunk. Use `@cline/shared/browser` for runtime imports in the webview; the bare `@cline/shared` source alias points to the Node entry point.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
The composer shows the current branch's GitHub pull request, merge status,
|
||||
changed-line totals, and CI checks. Click the PR number to open it in your
|
||||
browser, or expand CI to inspect individual checks and their logs. Status
|
||||
refreshes every 30 seconds while visible, when the app regains focus, and
|
||||
when you click refresh.
|
||||
|
||||
This requires GitHub CLI (`gh`) installed and authenticated with `gh auth login`,
|
||||
and a GitHub.com `origin` remote (HTTPS or SSH). The row is hidden for the
|
||||
default branch, detached HEAD, and unsupported repositories. If the branch
|
||||
has no PR, **Create PR** opens GitHub's comparison form; push your commits
|
||||
before submitting the form. The app does not push commits or submit PRs itself.
|
||||
|
||||
Missing or unauthenticated GitHub CLI also hides the row. Availability checks
|
||||
are shared across workspaces and cached for five minutes, so unavailable CLI
|
||||
installs do not spawn a failing process on every poll or window focus. After
|
||||
installing or signing into `gh`, the feature becomes available on the first
|
||||
refresh after the cache expires (or after restarting the desktop backend).
|
||||
Initial lookup failures stay hidden. Errors after a successful status load
|
||||
can be dismissed and remain dismissed through retries until a load succeeds.
|
||||
|
||||
### Pull request telemetry
|
||||
|
||||
These events use the desktop telemetry service and respect telemetry opt-out:
|
||||
|
||||
| Event | Trigger |
|
||||
| --- | --- |
|
||||
| `desktop.pull_request.shown` | First visible PR/create row per mounted workspace and branch |
|
||||
| `desktop.pull_request.open_clicked` | Click the PR link |
|
||||
| `desktop.pull_request.create_clicked` | Click Create PR (intent only, not PR submission) |
|
||||
| `desktop.pull_request.checks_expanded` | Open the CI popover |
|
||||
| `desktop.pull_request.check_clicked` | Click a check's details link |
|
||||
| `desktop.pull_request.refresh_clicked` | Click manual refresh |
|
||||
|
||||
Each event contains only `prState`, `ciState`, and `mergeTone` categories.
|
||||
The sidecar validates these values and strips extra fields. Repository/branch
|
||||
names, paths, PR numbers/titles, check names, and URLs are not included.
|
||||
Automatic polling does not emit additional impressions. Telemetry delivery
|
||||
does not block interactions, and failures do not interrupt the feature.
|
||||
|
||||
## App Icons
|
||||
|
||||
`src-tauri/app-icon.png` (1024x1024, edge-to-edge) is the source for
|
||||
`bun tauri icon`, which generates the Windows `.ico` and Linux PNGs in
|
||||
`src-tauri/icons/`. macOS is the exception: Dock icons are expected to have a
|
||||
transparent margin, with the artwork filling 824 of the 1024 canvas, so the
|
||||
committed `icons/icon.icns` is built from a padded copy of the source, and the
|
||||
selectable runtime icons in `icons/app/macos/` are padded copies of the
|
||||
Windows ones in `icons/app/`. To regenerate the macOS icon after changing the
|
||||
artwork:
|
||||
|
||||
```bash
|
||||
cd src-tauri
|
||||
magick app-icon.png -resize 824x824 -background none -gravity center -extent 1024x1024 /tmp/app-icon-macos.png
|
||||
bun tauri icon /tmp/app-icon-macos.png -o /tmp/icons-macos && cp /tmp/icons-macos/icon.icns icons/icon.icns
|
||||
```
|
||||
|
||||
## Customizing the macOS Install Window
|
||||
|
||||
The drag-to-Applications window is configured by `bundle.macOS.dmg` in
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@cline/code",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build:ui": "bun -F @cline/ui build",
|
||||
@@ -10,6 +10,8 @@
|
||||
"predev:headless": "bun run build:ui",
|
||||
"dev:headless": "bun run scripts/dev-headless.ts",
|
||||
"dev": "tauri dev --config src-tauri/tauri.dev.conf.json",
|
||||
"prebuild:web": "bun run build:ui",
|
||||
"build:web": "next build webview",
|
||||
"prebuild": "bun run build:ui",
|
||||
"build": "bun run bun.mts",
|
||||
"build:sidecar": "mkdir -p dist/sidecar && bun build ./sidecar/index.ts --outfile ./dist/sidecar/index.js --target bun",
|
||||
@@ -27,6 +29,9 @@
|
||||
"typecheck": "tsc -p tsconfig.dev.json --noEmit",
|
||||
"pretest:chat-ui": "bun run build:ui",
|
||||
"test:chat-ui": "vitest run webview/components/views/chat/chat-messages.test.tsx webview/components/views/chat/messages --config vitest.config.ts",
|
||||
"pretest:settings-ui": "bun run build:ui",
|
||||
"test:settings-ui": "vitest run webview/components/views/settings webview/components/ui/switch-integration.test.tsx --config vitest.config.ts",
|
||||
"test:sidecar": "vitest run sidecar scripts/telemetry-define-args.test.ts --config vitest.config.ts",
|
||||
"clean": "rm -rf webview/.next webview/out node_modules dist && (cd src-tauri && rm -rf target node_modules dist)"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -60,7 +65,6 @@
|
||||
"@radix-ui/react-separator": "1.1.8",
|
||||
"@radix-ui/react-slider": "1.3.6",
|
||||
"@radix-ui/react-slot": "1.2.4",
|
||||
"@radix-ui/react-switch": "1.2.6",
|
||||
"@radix-ui/react-tabs": "1.1.13",
|
||||
"@radix-ui/react-toast": "1.2.15",
|
||||
"@radix-ui/react-toggle": "1.1.10",
|
||||
|
||||
@@ -65,6 +65,18 @@ describe("telemetryDefineArgs", () => {
|
||||
expect(withKeys["process.env.ERROR_SERVICE_API_KEY"]).toBe('"ek"');
|
||||
});
|
||||
|
||||
it("inlines the cloud-agents toggle only when set at build time", () => {
|
||||
const withoutToggle = defineMap(telemetryDefineArgs({}));
|
||||
expect(withoutToggle).not.toHaveProperty(
|
||||
"process.env.CLINE_CODE_CLOUD_AGENTS",
|
||||
);
|
||||
|
||||
const withToggle = defineMap(
|
||||
telemetryDefineArgs({ CLINE_CODE_CLOUD_AGENTS: "1" }),
|
||||
);
|
||||
expect(withToggle["process.env.CLINE_CODE_CLOUD_AGENTS"]).toBe('"1"');
|
||||
});
|
||||
|
||||
it("JSON-escapes values so headers with quotes survive the define", () => {
|
||||
const defines = defineMap(
|
||||
telemetryDefineArgs({
|
||||
|
||||
@@ -15,6 +15,9 @@ const OPTIONAL_SECRET_ENV_VARS = [
|
||||
"ERROR_SERVICE_API_KEY",
|
||||
] as const;
|
||||
|
||||
/** Optional build-time overrides for packaged dogfood builds. */
|
||||
const OPTIONAL_FEATURE_ENV_VARS = ["CLINE_CODE_CLOUD_AGENTS"] as const;
|
||||
|
||||
/**
|
||||
* Every env var `getTelemetryBuildTimeConfig` reads
|
||||
* (sdk/packages/shared/src/services/telemetry-config.ts). Always inlined,
|
||||
@@ -42,7 +45,10 @@ export function telemetryDefineArgs(
|
||||
const define = (name: string, value: string) => {
|
||||
args.push("--define", `process.env.${name}=${JSON.stringify(value)}`);
|
||||
};
|
||||
for (const name of OPTIONAL_SECRET_ENV_VARS) {
|
||||
for (const name of [
|
||||
...OPTIONAL_SECRET_ENV_VARS,
|
||||
...OPTIONAL_FEATURE_ENV_VARS,
|
||||
]) {
|
||||
const value = env[name];
|
||||
if (value) {
|
||||
define(name, value);
|
||||
|
||||
@@ -16,6 +16,7 @@ sidecar/
|
||||
├── index.ts # Entry point: starts HTTP+WS server
|
||||
├── server.ts # Bun HTTP server + WebSocket handlers
|
||||
├── context.ts # SidecarContext type and factory
|
||||
├── client-context.ts # Desktop client/account identity for shared telemetry
|
||||
├── commands.ts # Command router
|
||||
├── chat-session.ts # Shared-Hub chat session adapter
|
||||
├── session-data/ # Shared discovery, messages, artifacts, search helpers
|
||||
@@ -81,6 +82,15 @@ The compiled sidecar also recognizes Core's Hub-daemon launch mode. This lets
|
||||
the desktop start the same detached Hub when no CLI process has started it yet.
|
||||
Startup discovery and locking ensure concurrent clients converge on one Hub.
|
||||
|
||||
Every create, restart, fork, and restore also attaches the serializable Desktop
|
||||
`ExtensionContext.client` and current `ExtensionContext.user`. Core forwards
|
||||
that context across the Hub transport and scopes the daemon-owned telemetry
|
||||
service to the originating surface. This keeps lifecycle events centralized in
|
||||
Core while reporting Desktop dimensions (`cline_type: "desktop"`, `platform:
|
||||
"Cline Desktop"`, and the Desktop app version) and the current account and
|
||||
organization. The shared Hub telemetry singleton is never mutated per session,
|
||||
so concurrent CLI and Desktop tasks retain their own attribution.
|
||||
|
||||
### 2. Tool Approval — Client-Owned Promise Resolution
|
||||
|
||||
The shared Hub routes approval requests back to the client that created the
|
||||
@@ -134,6 +144,17 @@ The frontend `desktop-client.ts` connects directly to the sidecar WebSocket:
|
||||
|
||||
## Command Map
|
||||
|
||||
The model picker first uses `list_provider_catalog`, which reads the bundled and
|
||||
registered models without network access. It then calls `list_provider_models`
|
||||
for the active provider, both on mount and when the provider changes. All built-in
|
||||
providers backed by the shared catalog refresh from the live feed (including
|
||||
OpenCode); concurrent requests share one fetch and reuse its ten-minute cache.
|
||||
Endpoint-owned lists such as Baseten, Hicap, Poolside, LiteLLM, Ollama, and LM Studio use their existing
|
||||
discovery endpoints instead. Catalog and public endpoint requests time out after
|
||||
five seconds, and the initial picker remains usable while a refresh is pending.
|
||||
The sidecar omits bundled `knownModels` from the discovery config so they cannot
|
||||
override live metadata; explicitly registered model overrides retain precedence.
|
||||
|
||||
Supported commands:
|
||||
|
||||
| Command | Implementation |
|
||||
|
||||
@@ -13,6 +13,8 @@ import { materializeUserFiles } from "./attachments";
|
||||
import {
|
||||
buildSessionConnectionUpdate,
|
||||
consumeWorkspaceMetadata,
|
||||
createDesktopMistakeLimitPrompt,
|
||||
createDesktopMistakeRecovery,
|
||||
handleChatSessionCommand,
|
||||
hasProviderChanged,
|
||||
mergeSessionConfig,
|
||||
@@ -22,7 +24,11 @@ import {
|
||||
shouldUpdateSessionConnection,
|
||||
WORKSPACE_METADATA_PREWARM_TTL_MS,
|
||||
} from "./chat-session";
|
||||
import { handleCoreSessionEvent } from "./context";
|
||||
import {
|
||||
handleCoreSessionEvent,
|
||||
requestSidecarAskQuestion,
|
||||
resolveSidecarAskQuestion,
|
||||
} from "./context";
|
||||
import type { SidecarContext } from "./types";
|
||||
|
||||
describe("resolveDesktopSessionMode", () => {
|
||||
@@ -195,25 +201,49 @@ describe("hasProviderChanged", () => {
|
||||
|
||||
describe("pathless session starts", () => {
|
||||
it("omits workspace paths and returns the SDK-resolved chat workspace", async () => {
|
||||
const start = vi.fn(async (input: { config: Record<string, unknown> }) => {
|
||||
expect(input.config).not.toHaveProperty("cwd");
|
||||
expect(input.config).not.toHaveProperty("workspaceRoot");
|
||||
expect(input.config).not.toHaveProperty("enableSpawnAgent");
|
||||
expect(input.config).not.toHaveProperty("enableAgentTeams");
|
||||
return {
|
||||
sessionId: "session-pathless",
|
||||
manifest: {
|
||||
cwd: "/home/host/.cline/data/workspaces/chat",
|
||||
workspace_root: "/home/host/.cline/data/workspaces/chat",
|
||||
},
|
||||
manifestPath: "/tmp/session-pathless.json",
|
||||
messagesPath: "/tmp/session-pathless.messages.json",
|
||||
};
|
||||
});
|
||||
const start = vi.fn(
|
||||
async (input: {
|
||||
config: Record<string, unknown>;
|
||||
localRuntime?: {
|
||||
extensionContext?: {
|
||||
client?: Record<string, unknown>;
|
||||
user?: Record<string, unknown>;
|
||||
};
|
||||
};
|
||||
}) => {
|
||||
expect(input.config).not.toHaveProperty("cwd");
|
||||
expect(input.config).not.toHaveProperty("workspaceRoot");
|
||||
expect(input.config).not.toHaveProperty("enableSpawnAgent");
|
||||
expect(input.config).not.toHaveProperty("enableAgentTeams");
|
||||
expect(input.localRuntime?.extensionContext?.client).toMatchObject({
|
||||
name: "cline-desktop",
|
||||
platform: "Cline Desktop",
|
||||
});
|
||||
expect(input.localRuntime?.extensionContext?.user).toEqual({
|
||||
distinctId: "account-1",
|
||||
accountId: "account-1",
|
||||
organizationId: "org-1",
|
||||
});
|
||||
return {
|
||||
sessionId: "session-pathless",
|
||||
manifest: {
|
||||
cwd: "/home/host/.cline/data/workspaces/chat",
|
||||
workspace_root: "/home/host/.cline/data/workspaces/chat",
|
||||
},
|
||||
manifestPath: "/tmp/session-pathless.json",
|
||||
messagesPath: "/tmp/session-pathless.messages.json",
|
||||
};
|
||||
},
|
||||
);
|
||||
const ctx = {
|
||||
liveSessions: new Map(),
|
||||
restoringWorkspacePaths: new Set(),
|
||||
sessionManager: { start },
|
||||
telemetryUser: {
|
||||
distinctId: "account-1",
|
||||
accountId: "account-1",
|
||||
organizationId: "org-1",
|
||||
},
|
||||
} as unknown as SidecarContext;
|
||||
|
||||
const result = (await handleChatSessionCommand(ctx, {
|
||||
@@ -545,7 +575,7 @@ describe("session forks", () => {
|
||||
expect(ctx.restoringWorkspacePaths.size).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps a full-history fork on the current workspace without restoring", async () => {
|
||||
it("keeps a full-history fork on the current workspace and cancels source questions", async () => {
|
||||
const sourceSessionId = `source-full-fork-${Date.now()}`;
|
||||
const sourceMessages = [
|
||||
{ role: "user" as const, content: "first prompt" },
|
||||
@@ -588,8 +618,19 @@ describe("session forks", () => {
|
||||
},
|
||||
streamIndices: new Map(),
|
||||
wsClients: new Set(),
|
||||
pendingQuestions: new Map(),
|
||||
} as unknown as SidecarContext;
|
||||
|
||||
const pendingDecision = createDesktopMistakeLimitPrompt(
|
||||
ctx,
|
||||
() => sourceSessionId,
|
||||
)({
|
||||
iteration: 5,
|
||||
consecutiveMistakes: 6,
|
||||
maxConsecutiveMistakes: 6,
|
||||
reason: "tool_execution_failed",
|
||||
});
|
||||
expect(ctx.pendingQuestions.size).toBe(1);
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "fork",
|
||||
sessionId: sourceSessionId,
|
||||
@@ -599,6 +640,8 @@ describe("session forks", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await expect(pendingDecision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(restore).not.toHaveBeenCalled();
|
||||
expect(start).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ initialMessages: sourceMessages }),
|
||||
@@ -1753,3 +1796,519 @@ Follow the desktop send workflow instructions.`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mistake-limit prompt", () => {
|
||||
function createPromptContext() {
|
||||
const send = vi.fn();
|
||||
const steer = vi.fn(async () => undefined);
|
||||
const ctx = {
|
||||
wsClients: new Set([{ send }]),
|
||||
streamIndices: new Map(),
|
||||
pendingQuestions: new Map(),
|
||||
liveSessions: new Map(),
|
||||
sessionManager: {
|
||||
send: steer,
|
||||
stop: vi.fn(async () => {}),
|
||||
abort: vi.fn(async () => {}),
|
||||
},
|
||||
} as unknown as SidecarContext;
|
||||
const readQuestionRequest = () => {
|
||||
const raw = send.mock.calls
|
||||
.map(
|
||||
([encoded]) =>
|
||||
JSON.parse(String(encoded)) as {
|
||||
event: { name: string; payload: Record<string, unknown> };
|
||||
},
|
||||
)
|
||||
.find((message) => message.event.name === "ask_question_requested");
|
||||
return raw?.event.payload as
|
||||
| {
|
||||
requestId: string;
|
||||
sessionId: string;
|
||||
question: string;
|
||||
options: string[];
|
||||
}
|
||||
| undefined;
|
||||
};
|
||||
return { ctx, steer, readQuestionRequest };
|
||||
}
|
||||
const limitContext = {
|
||||
iteration: 15,
|
||||
consecutiveMistakes: 6,
|
||||
maxConsecutiveMistakes: 6,
|
||||
reason: "tool_execution_failed" as const,
|
||||
details:
|
||||
"Detected 5 consecutive identical calls to `editor`; stopping to avoid a loop.",
|
||||
};
|
||||
|
||||
it("holds tool and model hooks until Continue has queued recovery guidance", async () => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
let finishSteering!: () => void;
|
||||
steer.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<undefined>((resolve) => {
|
||||
finishSteering = () => resolve(undefined);
|
||||
}),
|
||||
);
|
||||
const recovery = createDesktopMistakeRecovery(ctx, () => "session-1");
|
||||
const decision = recovery.onConsecutiveMistakeLimitReached(limitContext);
|
||||
expect(recovery.onConsecutiveMistakeLimitReached(limitContext)).toBe(
|
||||
decision,
|
||||
);
|
||||
let released = false;
|
||||
const waiting = Promise.all([
|
||||
recovery.hooks.beforeModel(),
|
||||
recovery.hooks.beforeTool(),
|
||||
recovery.hooks.afterTool(),
|
||||
]).then((results) => {
|
||||
released = true;
|
||||
return results;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(released).toBe(false);
|
||||
expect(ctx.pendingQuestions.size).toBe(1);
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
readQuestionRequest()?.requestId ?? "",
|
||||
"Try a different approach",
|
||||
);
|
||||
await Promise.resolve();
|
||||
expect(steer).toHaveBeenCalledTimes(1);
|
||||
expect(released).toBe(false);
|
||||
finishSteering();
|
||||
await expect(decision).resolves.toMatchObject({ action: "continue" });
|
||||
await expect(waiting).resolves.toEqual([undefined, undefined, undefined]);
|
||||
expect(released).toBe(true);
|
||||
await expect(recovery.hooks.beforeModel()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("leaves ordinary questions alone when cancelling a mistake prompt", async () => {
|
||||
const { ctx, readQuestionRequest } = createPromptContext();
|
||||
const decision = createDesktopMistakeLimitPrompt(
|
||||
ctx,
|
||||
() => "session-1",
|
||||
)(limitContext);
|
||||
const mistakeRequestId = readQuestionRequest()?.requestId;
|
||||
const normalQuestion = requestSidecarAskQuestion(
|
||||
ctx,
|
||||
"Which file?",
|
||||
["a", "b"],
|
||||
{ sessionId: "session-1", agentId: "desktop", iteration: 1 },
|
||||
);
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "abort",
|
||||
sessionId: "session-1",
|
||||
});
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(1);
|
||||
const remaining = [...ctx.pendingQuestions.values()][0];
|
||||
expect(remaining.item.requestId).not.toBe(mistakeRequestId);
|
||||
resolveSidecarAskQuestion(ctx, remaining.item.requestId, "a");
|
||||
await expect(normalQuestion).resolves.toBe("a");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"answer",
|
||||
"abort",
|
||||
] as const)("releases waiting hooks with Stop on %s", async (action) => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const recovery = createDesktopMistakeRecovery(ctx, () => "session-1");
|
||||
const decision = recovery.onConsecutiveMistakeLimitReached(limitContext);
|
||||
const waiting = Promise.all([
|
||||
recovery.hooks.beforeModel(),
|
||||
recovery.hooks.beforeTool(),
|
||||
recovery.hooks.afterTool(),
|
||||
]);
|
||||
if (action === "answer") {
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
readQuestionRequest()?.requestId ?? "",
|
||||
"Stop this run",
|
||||
);
|
||||
} else {
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "abort",
|
||||
sessionId: "session-1",
|
||||
});
|
||||
}
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
for (const control of await waiting)
|
||||
expect(control).toMatchObject({ stop: true });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("asks the active session's user instead of stopping silently", async () => {
|
||||
const { ctx, readQuestionRequest } = createPromptContext();
|
||||
// Session ids are only known after start() resolves; the prompt must
|
||||
// read the id at prompt time, not at construction time.
|
||||
let sessionId = "";
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => sessionId);
|
||||
sessionId = "session-late";
|
||||
|
||||
const decision = decide(limitContext);
|
||||
const request = readQuestionRequest();
|
||||
expect(request).toMatchObject({
|
||||
sessionId: "session-late",
|
||||
options: ["Try a different approach", "Stop this run"],
|
||||
});
|
||||
expect(request?.question).toContain("repeated mistakes or tool calls");
|
||||
expect(request?.question).toContain("identical calls to `editor`");
|
||||
|
||||
expect(
|
||||
resolveSidecarAskQuestion(ctx, request?.requestId ?? "", "Stop this run"),
|
||||
).toBe(true);
|
||||
await expect(decision).resolves.toEqual({
|
||||
action: "stop",
|
||||
reason: "stopped after mistake_limit_reached prompt",
|
||||
});
|
||||
});
|
||||
|
||||
it("delivers recovery guidance only through steering", async () => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
|
||||
const decision = decide(limitContext);
|
||||
const request = readQuestionRequest();
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
request?.requestId ?? "",
|
||||
"Try a different approach",
|
||||
);
|
||||
|
||||
const result = await decision;
|
||||
expect(result).toEqual({ action: "continue" });
|
||||
expect(steer).toHaveBeenCalledExactlyOnceWith({
|
||||
sessionId: "session-1",
|
||||
prompt: expect.stringContaining("Do not repeat the same call"),
|
||||
delivery: "steer",
|
||||
});
|
||||
expect(steer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
prompt: expect.stringContaining("identical calls to `editor`"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"stop",
|
||||
" STOP THIS RUN ",
|
||||
"2",
|
||||
"no",
|
||||
])("treats the free-text answer %s as Stop, like the CLI", async (answer) => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const decision = createDesktopMistakeLimitPrompt(
|
||||
ctx,
|
||||
() => "session-1",
|
||||
)(limitContext);
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
readQuestionRequest()?.requestId ?? "",
|
||||
answer,
|
||||
);
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"rejected",
|
||||
"unavailable",
|
||||
])("stops waiting hooks when steering is %s", async (failure) => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
if (failure === "rejected")
|
||||
steer.mockRejectedValueOnce(new Error("Disconnected"));
|
||||
else ctx.sessionManager = null;
|
||||
const recovery = createDesktopMistakeRecovery(ctx, () => "session-1");
|
||||
const decision = recovery.onConsecutiveMistakeLimitReached(limitContext);
|
||||
const waiting = Promise.all([
|
||||
recovery.hooks.beforeModel(),
|
||||
recovery.hooks.beforeTool(),
|
||||
recovery.hooks.afterTool(),
|
||||
]);
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
readQuestionRequest()?.requestId ?? "",
|
||||
"Try a different approach",
|
||||
);
|
||||
await expect(decision).resolves.toMatchObject({
|
||||
action: "stop",
|
||||
reason: expect.stringContaining("Could not send recovery guidance"),
|
||||
});
|
||||
for (const result of await waiting)
|
||||
expect(result).toMatchObject({ stop: true });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
});
|
||||
|
||||
it("passes free-text answers through as user guidance", async () => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
const decision = decide(limitContext);
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
readQuestionRequest()?.requestId ?? "",
|
||||
"read the file first, then edit",
|
||||
);
|
||||
await expect(decision).resolves.toEqual({ action: "continue" });
|
||||
expect(steer).toHaveBeenCalledExactlyOnceWith({
|
||||
sessionId: "session-1",
|
||||
prompt: expect.stringContaining(
|
||||
"User guidance: read the file first, then edit",
|
||||
),
|
||||
delivery: "steer",
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses Continue for already-started iterations and asks again for new mistakes", async () => {
|
||||
const { ctx, steer } = createPromptContext();
|
||||
ctx.liveSessions.set("session-1", {
|
||||
config: {},
|
||||
messages: [],
|
||||
promptsInQueue: [],
|
||||
busy: true,
|
||||
startedAt: 0,
|
||||
status: "running",
|
||||
});
|
||||
const startIteration = (iteration: number) =>
|
||||
handleCoreSessionEvent(ctx, {
|
||||
type: "agent_event",
|
||||
payload: {
|
||||
sessionId: "session-1",
|
||||
event: { type: "iteration_start", iteration },
|
||||
},
|
||||
});
|
||||
const answer = (value: string) => {
|
||||
const pending = [...ctx.pendingQuestions.values()][0];
|
||||
expect(pending).toBeDefined();
|
||||
resolveSidecarAskQuestion(ctx, pending.item.requestId, value);
|
||||
};
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
startIteration(15);
|
||||
const first = decide(limitContext);
|
||||
// The model can advance while the client decision is pending.
|
||||
startIteration(20);
|
||||
// Do not extend the covered iterations while waiting for the hub's
|
||||
// steering acknowledgement: a newer step may already have the guidance.
|
||||
steer.mockImplementationOnce(async () => {
|
||||
startIteration(21);
|
||||
return undefined;
|
||||
});
|
||||
answer("Try a different approach");
|
||||
await expect(first).resolves.toMatchObject({ action: "continue" });
|
||||
|
||||
// A batch can have many failures in one iteration, followed by more
|
||||
// failures queued before the user answered. None needs another prompt.
|
||||
for (const iteration of [
|
||||
...Array<number>(20).fill(15),
|
||||
16,
|
||||
17,
|
||||
18,
|
||||
19,
|
||||
20,
|
||||
]) {
|
||||
await expect(decide({ ...limitContext, iteration })).resolves.toEqual({
|
||||
action: "continue",
|
||||
});
|
||||
}
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(steer).toHaveBeenCalledTimes(1);
|
||||
|
||||
startIteration(21);
|
||||
const next = decide({ ...limitContext, iteration: 21 });
|
||||
answer("Try a different approach");
|
||||
await expect(next).resolves.toMatchObject({ action: "continue" });
|
||||
expect(steer).toHaveBeenCalledTimes(2);
|
||||
|
||||
// A new user run must not inherit the previous run's decision, even
|
||||
// though its iteration numbers start over.
|
||||
startIteration(1);
|
||||
startIteration(5);
|
||||
const newRun = decide({ ...limitContext, iteration: 5 });
|
||||
answer("Stop this run");
|
||||
await expect(newRun).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(steer).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("falls back to stopping when no session owns the question", async () => {
|
||||
const { ctx, steer } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "");
|
||||
await expect(decide(limitContext)).resolves.toEqual({
|
||||
action: "stop",
|
||||
reason: `mistake_limit_reached: ${limitContext.details}`,
|
||||
});
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes an aborted run's question and rejects late answers", async () => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
const decision = decide(limitContext);
|
||||
const request = readQuestionRequest();
|
||||
expect(ctx.pendingQuestions.size).toBe(1);
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "abort",
|
||||
sessionId: "session-1",
|
||||
});
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(
|
||||
resolveSidecarAskQuestion(
|
||||
ctx,
|
||||
request?.requestId ?? "",
|
||||
"Try a different approach",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"stop",
|
||||
"abort",
|
||||
"reset",
|
||||
] as const)("cancels only the owning session's questions on %s", async (action) => {
|
||||
const { ctx } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
const other = createDesktopMistakeLimitPrompt(
|
||||
ctx,
|
||||
() => "session-2",
|
||||
)(limitContext);
|
||||
const decision = decide(limitContext);
|
||||
await handleChatSessionCommand(ctx, { action, sessionId: "session-1" });
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(
|
||||
[...ctx.pendingQuestions.values()].map((p) => p.item.sessionId),
|
||||
).toEqual(["session-2"]);
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "abort",
|
||||
sessionId: "session-2",
|
||||
});
|
||||
await other;
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
});
|
||||
|
||||
it("times out an unanswered question and removes it from polling", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { ctx, steer } = createPromptContext();
|
||||
const decide = createDesktopMistakeLimitPrompt(ctx, () => "session-1");
|
||||
const decision = decide(limitContext);
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000);
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
"run",
|
||||
"session",
|
||||
])("cancels the question when the %s ends externally", async (kind) => {
|
||||
const { ctx, steer, readQuestionRequest } = createPromptContext();
|
||||
const decision = createDesktopMistakeLimitPrompt(
|
||||
ctx,
|
||||
() => "session-1",
|
||||
)(limitContext);
|
||||
const requestId = readQuestionRequest()?.requestId ?? "";
|
||||
if (kind === "session")
|
||||
handleCoreSessionEvent(ctx, {
|
||||
type: "ended",
|
||||
payload: { sessionId: "session-1", reason: "stopped", ts: Date.now() },
|
||||
});
|
||||
else
|
||||
handleCoreSessionEvent(ctx, {
|
||||
type: "agent_event",
|
||||
payload: {
|
||||
sessionId: "session-1",
|
||||
event: {
|
||||
type: "done",
|
||||
reason: "aborted",
|
||||
text: "",
|
||||
iterations: 5,
|
||||
usage: { inputTokens: 0, outputTokens: 0 },
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(decision).resolves.toMatchObject({ action: "stop" });
|
||||
expect(ctx.pendingQuestions.size).toBe(0);
|
||||
expect(
|
||||
resolveSidecarAskQuestion(ctx, requestId, "Try a different approach"),
|
||||
).toBe(false);
|
||||
expect(steer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("is wired into freshly started sessions as a local runtime option", async () => {
|
||||
const start = vi.fn(
|
||||
async (input: {
|
||||
config: Record<string, unknown>;
|
||||
localRuntime?: Record<string, unknown>;
|
||||
}) => {
|
||||
expect(input.config).not.toHaveProperty(
|
||||
"onConsecutiveMistakeLimitReached",
|
||||
);
|
||||
expect(
|
||||
typeof input.localRuntime?.onConsecutiveMistakeLimitReached,
|
||||
).toBe("function");
|
||||
expect(input.config).not.toHaveProperty("hooks");
|
||||
expect(input.localRuntime?.hooks).toMatchObject({
|
||||
beforeModel: expect.any(Function),
|
||||
beforeTool: expect.any(Function),
|
||||
afterTool: expect.any(Function),
|
||||
});
|
||||
return {
|
||||
sessionId: "session-limit",
|
||||
manifest: { cwd: "/tmp/ws", workspace_root: "/tmp/ws" },
|
||||
manifestPath: "/tmp/session-limit.json",
|
||||
messagesPath: "/tmp/session-limit.messages.json",
|
||||
};
|
||||
},
|
||||
);
|
||||
const ctx = {
|
||||
liveSessions: new Map(),
|
||||
restoringWorkspacePaths: new Set(),
|
||||
sessionManager: { start },
|
||||
} as unknown as SidecarContext;
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "start",
|
||||
config: {
|
||||
provider: "cline",
|
||||
model: "anthropic/claude-sonnet-4.6",
|
||||
cwd: "/tmp/ws",
|
||||
},
|
||||
});
|
||||
expect(start).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("queue steering routing", () => {
|
||||
it.each([
|
||||
undefined,
|
||||
"selected-prompt",
|
||||
])("routes steering with prompt ID %s", async (promptId) => {
|
||||
const result = { sessionId: "session", prompts: [], updated: false };
|
||||
const steerFirst = vi.fn(async () => result);
|
||||
const update = vi.fn(async () => result);
|
||||
const ctx = {
|
||||
liveSessions: new Map(),
|
||||
wsClients: new Set(),
|
||||
sessionManager: { pendingPrompts: { steerFirst, update } },
|
||||
} as unknown as SidecarContext;
|
||||
await handleChatSessionCommand(ctx, {
|
||||
action: "steer_prompt",
|
||||
sessionId: "session",
|
||||
promptId,
|
||||
});
|
||||
if (promptId === undefined) {
|
||||
expect(steerFirst).toHaveBeenCalledWith({ sessionId: "session" });
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
} else {
|
||||
expect(update).toHaveBeenCalledWith({
|
||||
sessionId: "session",
|
||||
promptId,
|
||||
delivery: "steer",
|
||||
});
|
||||
expect(steerFirst).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,14 +22,26 @@ import {
|
||||
trimMessagesBeforeUserRun,
|
||||
} from "@cline/core";
|
||||
import type { MessageWithMetadata } from "@cline/llms";
|
||||
import { buildClineSystemPrompt, formatUserCommandBlock } from "@cline/shared";
|
||||
import {
|
||||
buildClineSystemPrompt,
|
||||
type ConsecutiveMistakeLimitContext,
|
||||
type ConsecutiveMistakeLimitDecision,
|
||||
formatUserCommandBlock,
|
||||
} from "@cline/shared";
|
||||
import {
|
||||
deleteMaterializedAttachments,
|
||||
discardAllTrackedAttachments,
|
||||
materializeUserFiles,
|
||||
trackQueuedAttachments,
|
||||
} from "./attachments";
|
||||
import { emitChunk, nowMs, sendEvent } from "./context";
|
||||
import { createDesktopExtensionContext } from "./client-context";
|
||||
import {
|
||||
cancelSidecarMistakeQuestions,
|
||||
emitChunk,
|
||||
nowMs,
|
||||
requestSidecarAskQuestion,
|
||||
sendEvent,
|
||||
} from "./context";
|
||||
import { readSessionManifest, sharedSessionDataDir } from "./paths";
|
||||
import { persistSessionMessages } from "./session-data/messages";
|
||||
import type {
|
||||
@@ -401,7 +413,177 @@ function readPositiveInteger(value: unknown): number | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildCoreSessionConfig(config: JsonRecord): JsonRecord {
|
||||
type MistakeLimitDecider = (
|
||||
context: ConsecutiveMistakeLimitContext,
|
||||
) => Promise<ConsecutiveMistakeLimitDecision>;
|
||||
|
||||
const MISTAKE_LIMIT_CONTINUE_OPTION = "Try a different approach";
|
||||
const MISTAKE_LIMIT_STOP_OPTION = "Stop this run";
|
||||
const MISTAKE_LIMIT_DETAIL_MAX_CHARS = 600;
|
||||
|
||||
/**
|
||||
* Desktop counterpart of the CLI's mistake-limit prompt
|
||||
* (apps/cli/src/runtime/interactive/mistakes.ts).
|
||||
*
|
||||
* When the core's loop detector or mistake tracker trips, it asks the client
|
||||
* how to proceed. Without a decision callback the default is "stop", which
|
||||
* reaches the webview as a plain aborted turn: indistinguishable from the
|
||||
* user pressing Stop, with no explanation. A model stuck re-issuing the same
|
||||
* failing tool call therefore looked like Cline randomly gave up mid-task.
|
||||
* Route the decision through the existing ask-question channel instead so
|
||||
* the user sees what went wrong and can choose.
|
||||
*
|
||||
* `getSessionId` is read at prompt time: for fresh starts the session id is
|
||||
* only known after `manager.start()` resolves, and the webview matches the
|
||||
* prompt to its active session by id.
|
||||
*/
|
||||
export function createDesktopMistakeLimitPrompt(
|
||||
ctx: SidecarContext,
|
||||
getSessionId: () => string,
|
||||
): MistakeLimitDecider {
|
||||
return async (context) => {
|
||||
const sessionId = getSessionId().trim();
|
||||
const recovery = ctx.liveSessions.get(sessionId)?.mistakeRecovery;
|
||||
if (
|
||||
recovery?.continuedThroughIteration !== undefined &&
|
||||
context.iteration <= recovery.continuedThroughIteration
|
||||
) {
|
||||
// The tracker serializes decisions, so old failures can arrive after
|
||||
// Continue. The user has already answered for these in-flight steps.
|
||||
return { action: "continue" };
|
||||
}
|
||||
const detail = context.details?.trim() ?? "";
|
||||
const truncatedDetail =
|
||||
detail.length > MISTAKE_LIMIT_DETAIL_MAX_CHARS
|
||||
? `${detail.slice(0, MISTAKE_LIMIT_DETAIL_MAX_CHARS)}…`
|
||||
: detail;
|
||||
const question = [
|
||||
"Cline detected repeated mistakes or tool calls and needs your guidance.",
|
||||
truncatedDetail ? `Latest: ${truncatedDetail}` : "",
|
||||
"How should Cline continue?",
|
||||
]
|
||||
.filter((line) => line.length > 0)
|
||||
.join("\n");
|
||||
|
||||
let answer: string;
|
||||
try {
|
||||
answer = await requestSidecarAskQuestion(
|
||||
ctx,
|
||||
question,
|
||||
[MISTAKE_LIMIT_CONTINUE_OPTION, MISTAKE_LIMIT_STOP_OPTION],
|
||||
{
|
||||
sessionId,
|
||||
agentId: "desktop-mistake-limit",
|
||||
iteration: context.iteration,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
// Prompt timed out or the session was torn down: fall back to the
|
||||
// core's default decision, but keep the reason so the stop is
|
||||
// attributable.
|
||||
ctx.logger?.log("Mistake-limit prompt unanswered; stopping run", {
|
||||
sessionId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return {
|
||||
action: "stop",
|
||||
reason: `mistake_limit_reached: ${detail || context.reason}`,
|
||||
};
|
||||
}
|
||||
|
||||
const normalized = answer.trim().toLowerCase();
|
||||
if (["2", "stop this run", "stop", "n", "no"].includes(normalized)) {
|
||||
return {
|
||||
action: "stop",
|
||||
reason: "stopped after mistake_limit_reached prompt",
|
||||
};
|
||||
}
|
||||
const customGuidance =
|
||||
normalized.length > 0 &&
|
||||
normalized !== "1" &&
|
||||
normalized !== MISTAKE_LIMIT_CONTINUE_OPTION.toLowerCase()
|
||||
? answer.trim()
|
||||
: "";
|
||||
const guidance = [
|
||||
"The run reached the limit for repeated mistakes or tool calls.",
|
||||
truncatedDetail ? `Latest: ${truncatedDetail}` : "",
|
||||
"Do not repeat the same call. Re-check the tool's parameter requirements, fix the call, and try a different approach.",
|
||||
customGuidance ? `User guidance: ${customGuidance}` : "",
|
||||
]
|
||||
.filter((line) => line.length > 0)
|
||||
.join(" ");
|
||||
// Use the existing steering queue so the running model receives the
|
||||
// guidance, including any instructions entered in the desktop prompt.
|
||||
const manager = ctx.sessionManager;
|
||||
try {
|
||||
if (!manager) throw new Error("Desktop session manager is unavailable");
|
||||
const continuedThroughIteration = Math.max(
|
||||
context.iteration,
|
||||
recovery?.latestIteration ?? context.iteration,
|
||||
);
|
||||
await manager.send({ sessionId, prompt: guidance, delivery: "steer" });
|
||||
if (recovery) {
|
||||
recovery.continuedThroughIteration = continuedThroughIteration;
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
ctx.logger?.log("Failed to steer mistake-limit guidance", {
|
||||
sessionId,
|
||||
error: detail,
|
||||
});
|
||||
// Releasing the hooks without the guidance would resume the same
|
||||
// failing loop. Only Continue after the steering request succeeds.
|
||||
return {
|
||||
action: "stop",
|
||||
reason: `Could not send recovery guidance: ${detail}`,
|
||||
};
|
||||
}
|
||||
// Steering already delivers the guidance; do not also append it via
|
||||
// the mistake tracker's recovery-notice path.
|
||||
return { action: "continue" };
|
||||
};
|
||||
}
|
||||
|
||||
export function createDesktopMistakeRecovery(
|
||||
ctx: SidecarContext,
|
||||
getSessionId: () => string,
|
||||
) {
|
||||
const prompt = createDesktopMistakeLimitPrompt(ctx, getSessionId);
|
||||
let pendingDecision: Promise<ConsecutiveMistakeLimitDecision> | undefined;
|
||||
const waitForDecision = async () => {
|
||||
const decision = await pendingDecision;
|
||||
return decision?.action === "stop"
|
||||
? { stop: true, reason: decision.reason }
|
||||
: undefined;
|
||||
};
|
||||
return {
|
||||
onConsecutiveMistakeLimitReached: (
|
||||
context: ConsecutiveMistakeLimitContext,
|
||||
) => {
|
||||
if (!pendingDecision) {
|
||||
pendingDecision = prompt(context).finally(() => {
|
||||
pendingDecision = undefined;
|
||||
});
|
||||
}
|
||||
return pendingDecision;
|
||||
},
|
||||
hooks: {
|
||||
// The decision callback alone does not pause the SDK. These existing
|
||||
// awaited hooks hold desktop runs at tool/model boundaries until the
|
||||
// user answers. afterTool holds before the next iteration consumes
|
||||
// the recovery guidance queued by the prompt's Continue action.
|
||||
beforeModel: waitForDecision,
|
||||
beforeTool: waitForDecision,
|
||||
afterTool: waitForDecision,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildCoreSessionConfig(
|
||||
config: JsonRecord,
|
||||
telemetryUser?: SidecarContext["telemetryUser"],
|
||||
mistakeRecovery?: ReturnType<typeof createDesktopMistakeRecovery>,
|
||||
): JsonRecord {
|
||||
const rawWorkspaceRoot = config.workspaceRoot ?? config.workspace_root;
|
||||
const workspaceRoot =
|
||||
typeof rawWorkspaceRoot === "string" ? rawWorkspaceRoot.trim() : "";
|
||||
@@ -444,6 +626,8 @@ function buildCoreSessionConfig(config: JsonRecord): JsonRecord {
|
||||
checkpoint: { enabled: true },
|
||||
sessions: config.sessions,
|
||||
initialMessages: config.initialMessages,
|
||||
extensionContext: createDesktopExtensionContext(telemetryUser),
|
||||
...mistakeRecovery,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -674,8 +858,14 @@ async function handleStart(
|
||||
: requestedSessionId
|
||||
? (readPersistedChatMessages(requestedSessionId) ?? undefined)
|
||||
: undefined;
|
||||
// Resolved once start() returns; the mistake-limit prompt reads it lazily.
|
||||
let startedSessionId = requestedSessionId;
|
||||
const coreConfig: JsonRecord = {
|
||||
...buildCoreSessionConfig(request.config),
|
||||
...buildCoreSessionConfig(
|
||||
request.config,
|
||||
ctx.telemetryUser,
|
||||
createDesktopMistakeRecovery(ctx, () => startedSessionId),
|
||||
),
|
||||
systemPrompt,
|
||||
...(initialMessages ? { initialMessages } : {}),
|
||||
};
|
||||
@@ -697,6 +887,7 @@ async function handleStart(
|
||||
toolPolicies: resolveToolPolicies(request.config),
|
||||
});
|
||||
const sessionId = startResult.sessionId;
|
||||
startedSessionId = sessionId;
|
||||
const workspaceRoot = startResult.manifest.workspace_root;
|
||||
const cwd = startResult.manifest.cwd;
|
||||
ctx.logger?.log("Desktop chat session started", { sessionId });
|
||||
@@ -794,6 +985,7 @@ async function handleAttach(
|
||||
|
||||
async function startRebuiltSession(
|
||||
manager: ClineCore,
|
||||
ctx: SidecarContext,
|
||||
sessionId: string,
|
||||
config: JsonRecord,
|
||||
systemPrompt: string,
|
||||
@@ -805,11 +997,15 @@ async function startRebuiltSession(
|
||||
: undefined;
|
||||
const restarted = await manager.start({
|
||||
...splitCoreSessionConfig(
|
||||
buildCoreSessionConfig({
|
||||
...config,
|
||||
sessionId,
|
||||
systemPrompt,
|
||||
}) as unknown as ClineCoreStartConfig,
|
||||
buildCoreSessionConfig(
|
||||
{
|
||||
...config,
|
||||
sessionId,
|
||||
systemPrompt,
|
||||
},
|
||||
ctx.telemetryUser,
|
||||
createDesktopMistakeRecovery(ctx, () => sessionId),
|
||||
) as unknown as ClineCoreStartConfig,
|
||||
),
|
||||
source: SessionSource.DESKTOP,
|
||||
interactive: true,
|
||||
@@ -854,11 +1050,13 @@ async function rebuildSessionForProviderChange(
|
||||
resolveSystemPrompt(nextConfig),
|
||||
]);
|
||||
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Session provider changed");
|
||||
await manager.stop(sessionId);
|
||||
let replacementStarted = false;
|
||||
try {
|
||||
await startRebuiltSession(
|
||||
manager,
|
||||
ctx,
|
||||
sessionId,
|
||||
nextConfig,
|
||||
nextSystemPrompt,
|
||||
@@ -880,6 +1078,7 @@ async function rebuildSessionForProviderChange(
|
||||
}
|
||||
await startRebuiltSession(
|
||||
manager,
|
||||
ctx,
|
||||
sessionId,
|
||||
previousConfig,
|
||||
previousSystemPrompt,
|
||||
@@ -996,9 +1195,9 @@ async function handleSend(
|
||||
request.attachments?.userFiles,
|
||||
);
|
||||
if (session?.attachedViaHub) {
|
||||
// Once ClineCore sends a turn, its HubRuntimeHost owns the session
|
||||
// subscription. Stop projecting the observer stream as well or every
|
||||
// assistant/tool update (including command chunks) is emitted twice.
|
||||
// Once ClineCore sends a turn it owns the session: the attach-time
|
||||
// connection refresh above has happened and the observer projection is
|
||||
// muted by its subscription, so the session is no longer attach-only.
|
||||
session.attachedViaHub = false;
|
||||
}
|
||||
if (delivery === "queue") {
|
||||
@@ -1133,6 +1332,7 @@ async function handleStop(
|
||||
): Promise<unknown> {
|
||||
const sessionId = request.sessionId?.trim();
|
||||
if (!sessionId) throw new Error("sessionId is required");
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Session stopped");
|
||||
await getSessionManager(ctx).stop(sessionId);
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (session) {
|
||||
@@ -1148,6 +1348,7 @@ async function handleAbort(
|
||||
): Promise<unknown> {
|
||||
const sessionId = request.sessionId?.trim();
|
||||
if (!sessionId) throw new Error("sessionId is required");
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Run aborted");
|
||||
await getSessionManager(ctx).abort(sessionId, "user_abort");
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (session) {
|
||||
@@ -1289,12 +1490,18 @@ async function handleForkUnlocked(
|
||||
},
|
||||
};
|
||||
const systemPrompt = await resolveSystemPrompt(forkConfig);
|
||||
// Assigned below once the forked session exists; read lazily by the prompt.
|
||||
let newSessionId = "";
|
||||
const startInput = {
|
||||
...splitCoreSessionConfig(
|
||||
buildCoreSessionConfig({
|
||||
...forkConfig,
|
||||
systemPrompt,
|
||||
}) as unknown as ClineCoreStartConfig,
|
||||
buildCoreSessionConfig(
|
||||
{
|
||||
...forkConfig,
|
||||
systemPrompt,
|
||||
},
|
||||
ctx.telemetryUser,
|
||||
createDesktopMistakeRecovery(ctx, () => newSessionId),
|
||||
) as unknown as ClineCoreStartConfig,
|
||||
),
|
||||
source: SessionSource.DESKTOP,
|
||||
interactive: true,
|
||||
@@ -1311,7 +1518,6 @@ async function handleForkUnlocked(
|
||||
readSessionCheckpointHistory({ metadata: sourceMetadata }),
|
||||
forkBeforeRunCount,
|
||||
) !== undefined;
|
||||
let newSessionId: string;
|
||||
if (forkBeforeRunCount !== undefined && canRestoreWorkspace) {
|
||||
const cwd =
|
||||
restoreWorkspacePath ||
|
||||
@@ -1354,6 +1560,11 @@ async function handleForkUnlocked(
|
||||
sourceSessionId,
|
||||
ctx.liveSessions.get(sourceSessionId),
|
||||
);
|
||||
cancelSidecarMistakeQuestions(
|
||||
ctx,
|
||||
sourceSessionId,
|
||||
"Session replaced by fork",
|
||||
);
|
||||
ctx.liveSessions.delete(sourceSessionId);
|
||||
ctx.liveSessions.set(
|
||||
newSessionId,
|
||||
@@ -1378,6 +1589,7 @@ async function handleReset(
|
||||
): Promise<unknown> {
|
||||
const sessionId = request.sessionId?.trim();
|
||||
if (sessionId) {
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Session reset");
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (
|
||||
session?.busy ||
|
||||
@@ -1416,6 +1628,8 @@ async function handleRestoreCheckpoint(
|
||||
if (!cwd) throw new Error("config.cwd or config.workspaceRoot is required");
|
||||
const manager = getSessionManager(ctx);
|
||||
return withWorkspaceRestoreLock(ctx, cwd, async () => {
|
||||
// Updated once restore() returns; read lazily by the mistake-limit prompt.
|
||||
let restoredSessionId = sourceSessionId;
|
||||
const restored = await manager.restore({
|
||||
sessionId: sourceSessionId,
|
||||
checkpointRunCount: runCount,
|
||||
@@ -1423,10 +1637,14 @@ async function handleRestoreCheckpoint(
|
||||
restore: { messages: true, workspace: true },
|
||||
start: {
|
||||
...splitCoreSessionConfig(
|
||||
buildCoreSessionConfig({
|
||||
...config,
|
||||
systemPrompt: await resolveSystemPrompt(config),
|
||||
}) as unknown as ClineCoreStartConfig,
|
||||
buildCoreSessionConfig(
|
||||
{
|
||||
...config,
|
||||
systemPrompt: await resolveSystemPrompt(config),
|
||||
},
|
||||
ctx.telemetryUser,
|
||||
createDesktopMistakeRecovery(ctx, () => restoredSessionId),
|
||||
) as unknown as ClineCoreStartConfig,
|
||||
),
|
||||
source: SessionSource.DESKTOP,
|
||||
interactive: true,
|
||||
@@ -1438,10 +1656,16 @@ async function handleRestoreCheckpoint(
|
||||
if (!sessionId || !restoredMessages) {
|
||||
throw new Error("Checkpoint restore did not return a new session");
|
||||
}
|
||||
restoredSessionId = sessionId;
|
||||
discardAllTrackedAttachments(
|
||||
sourceSessionId,
|
||||
ctx.liveSessions.get(sourceSessionId),
|
||||
);
|
||||
cancelSidecarMistakeQuestions(
|
||||
ctx,
|
||||
sourceSessionId,
|
||||
"Session checkpoint restored",
|
||||
);
|
||||
ctx.liveSessions.delete(sourceSessionId);
|
||||
ctx.liveSessions.set(
|
||||
sessionId,
|
||||
@@ -1487,14 +1711,17 @@ async function handleSteerPrompt(
|
||||
): Promise<unknown> {
|
||||
const sessionId = request.sessionId?.trim();
|
||||
const promptId = request.promptId?.trim();
|
||||
if (!sessionId || !promptId)
|
||||
throw new Error("sessionId and promptId are required");
|
||||
if (!sessionId) throw new Error("sessionId is required");
|
||||
if (request.promptId !== undefined && !promptId)
|
||||
throw new Error("promptId cannot be empty");
|
||||
const manager = getSessionManager(ctx);
|
||||
const result = await manager.pendingPrompts.update({
|
||||
sessionId,
|
||||
promptId,
|
||||
delivery: "steer",
|
||||
});
|
||||
const result = promptId
|
||||
? await manager.pendingPrompts.update({
|
||||
sessionId,
|
||||
promptId,
|
||||
delivery: "steer",
|
||||
})
|
||||
: await manager.pendingPrompts.steerFirst({ sessionId });
|
||||
return {
|
||||
sessionId,
|
||||
updated: result.updated === true,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import * as os from "node:os";
|
||||
import { resolveCoreDistinctId } from "@cline/core";
|
||||
import type {
|
||||
ClientContext,
|
||||
ExtensionContext,
|
||||
TelemetryMetadata,
|
||||
UserContext,
|
||||
} from "@cline/shared";
|
||||
import { version } from "../package.json";
|
||||
|
||||
/** Shared identity for request headers, Hub attribution, and telemetry. */
|
||||
export const DESKTOP_CLIENT_CONTEXT = {
|
||||
name: "cline-desktop",
|
||||
version,
|
||||
platform: "Cline Desktop",
|
||||
platformVersion: version,
|
||||
isMultiRoot: false,
|
||||
} as const satisfies ClientContext;
|
||||
|
||||
export const DESKTOP_TELEMETRY_METADATA = {
|
||||
extension_version: version,
|
||||
cline_type: "desktop",
|
||||
platform: DESKTOP_CLIENT_CONTEXT.platform,
|
||||
platform_version: DESKTOP_CLIENT_CONTEXT.platformVersion,
|
||||
os_type: os.platform(),
|
||||
os_version: os.version(),
|
||||
} satisfies TelemetryMetadata;
|
||||
|
||||
export function resolveDesktopTelemetryUser(input?: {
|
||||
accountId?: string;
|
||||
email?: string;
|
||||
organizationId?: string;
|
||||
}): UserContext {
|
||||
const accountId = input?.accountId?.trim();
|
||||
return accountId
|
||||
? {
|
||||
distinctId: accountId,
|
||||
accountId,
|
||||
email: input?.email,
|
||||
organizationId: input?.organizationId,
|
||||
}
|
||||
: {
|
||||
distinctId: resolveCoreDistinctId(),
|
||||
accountId: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Serializable context attached to every Desktop session sent to the Hub. */
|
||||
export function createDesktopExtensionContext(
|
||||
user?: UserContext,
|
||||
): ExtensionContext {
|
||||
return {
|
||||
client: DESKTOP_CLIENT_CONTEXT,
|
||||
...(user ? { user: { ...user } } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
captureAuthRefreshSoftFailure,
|
||||
getProviderAuthHandler,
|
||||
OAuthReauthRequiredError,
|
||||
type ProviderSettingsManager,
|
||||
RuntimeOAuthTokenManager,
|
||||
} from "@cline/core";
|
||||
import type { SidecarContext } from "./types";
|
||||
|
||||
// Share the refresh-aware manager so single-use refresh tokens stay single-flight.
|
||||
let clineOAuthTokenManager: RuntimeOAuthTokenManager | undefined;
|
||||
|
||||
export async function resolveFreshClineAuthToken(
|
||||
manager: ProviderSettingsManager,
|
||||
ctx?: SidecarContext,
|
||||
): Promise<string | undefined> {
|
||||
let refreshError: Error | undefined;
|
||||
try {
|
||||
clineOAuthTokenManager ??= new RuntimeOAuthTokenManager();
|
||||
const resolution = await clineOAuthTokenManager.resolveProviderApiKey({
|
||||
providerId: "cline",
|
||||
});
|
||||
if (resolution?.apiKey) {
|
||||
return resolution.apiKey;
|
||||
}
|
||||
} catch (error) {
|
||||
// A persisted token may still let the account request surface the failure.
|
||||
refreshError = error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
// Apply canonical OAuth-token formatting while preserving raw API keys.
|
||||
const persisted = getProviderAuthHandler("cline")?.getApiKey(
|
||||
manager.getProviderSettings("cline"),
|
||||
);
|
||||
if (!persisted && refreshError && ctx) {
|
||||
ctx.logger?.error?.("Cline auth token refresh failed with no fallback", {
|
||||
error: refreshError,
|
||||
});
|
||||
captureAuthRefreshSoftFailure(ctx.telemetry, "cline", {
|
||||
errorName: refreshError.name,
|
||||
errorCode: "desktop_refresh_failed_no_fallback_token",
|
||||
});
|
||||
}
|
||||
// A rejected refresh token means the persisted access token is dead too.
|
||||
// Handing it out would turn the signed-out state into an opaque request
|
||||
// failure (an error card whose Retry fails the same way) instead of the
|
||||
// sign-in prompt. Transient refresh failures still fall back to it.
|
||||
if (refreshError instanceof OAuthReauthRequiredError) {
|
||||
return undefined;
|
||||
}
|
||||
return persisted;
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
CloudSessionApi,
|
||||
CloudSessionError,
|
||||
type CloudSessionRecord,
|
||||
} from "./cloud-sessions";
|
||||
|
||||
const REMOTE_SESSION: CloudSessionRecord = {
|
||||
id: "ses-outer",
|
||||
status: "ready",
|
||||
sandboxUrl: "https://pod.example/hub",
|
||||
repoContext: { repoUrl: "https://github.com/cline/test" },
|
||||
metadata: { modelId: "anthropic/claude-sonnet-5" },
|
||||
createdAt: "2026-08-05T10:00:00.000Z",
|
||||
updatedAt: "2026-08-05T10:01:00.000Z",
|
||||
};
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
function jwtFor(subject: string, nonce: string): string {
|
||||
const encode = (value: unknown) =>
|
||||
Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
return (
|
||||
"workos:" +
|
||||
encode({ alg: "none" }) +
|
||||
"." +
|
||||
encode({ sub: subject, nonce }) +
|
||||
".sig"
|
||||
);
|
||||
}
|
||||
|
||||
describe("CloudSessionApi", () => {
|
||||
it("resolves a fresh bearer token for every REST request", async () => {
|
||||
const tokens = ["workos:first", "workos:second"];
|
||||
const authorizations: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example/",
|
||||
appBaseUrl: "https://app.example/",
|
||||
getAuthToken: async () => tokens.shift(),
|
||||
fetch: async (_input, init) => {
|
||||
authorizations.push(
|
||||
new Headers(init?.headers).get("Authorization") ?? "",
|
||||
);
|
||||
return jsonResponse({ success: true, data: [] });
|
||||
},
|
||||
});
|
||||
|
||||
await api.list();
|
||||
await api.list();
|
||||
|
||||
expect(authorizations).toEqual([
|
||||
"Bearer workos:first",
|
||||
"Bearer workos:second",
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the dashboard create body and includes branch only when requested", async () => {
|
||||
const bodies: Array<Record<string, unknown>> = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async (_input, init) => {
|
||||
bodies.push(JSON.parse(String(init?.body)));
|
||||
return jsonResponse(
|
||||
{ success: true, data: { sessionId: "ses-1", sandboxUrl: "pod" } },
|
||||
201,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
await api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
branch: "feature/login-fix",
|
||||
});
|
||||
await api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
});
|
||||
|
||||
expect(bodies[0]).toMatchObject({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
branch: "feature/login-fix",
|
||||
title: expect.stringMatching(/^__cline_create_request__:/),
|
||||
});
|
||||
expect(bodies[1]).toMatchObject({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
title: expect.stringMatching(/^__cline_create_request__:/),
|
||||
});
|
||||
expect(bodies[1]).not.toHaveProperty("branch");
|
||||
});
|
||||
|
||||
it("treats a missing history snapshot (404) as null, not an empty archive", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async () => new Response("not found", { status: 404 }),
|
||||
});
|
||||
|
||||
expect(await api.history("ses-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts v1 history and rejects malformed snapshots instead of returning empty history", async () => {
|
||||
const messages = [{ role: "user", content: "Hello" }];
|
||||
let snapshot: unknown = { version: 1, messages };
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async () => jsonResponse(snapshot),
|
||||
});
|
||||
|
||||
expect(await api.history("ses-1")).toEqual(messages);
|
||||
snapshot = { version: 1, messages: [] };
|
||||
expect(await api.history("ses-1")).toEqual([]);
|
||||
for (const invalid of [
|
||||
null,
|
||||
{ version: 1 },
|
||||
{ version: 2, messages: [] },
|
||||
]) {
|
||||
snapshot = invalid;
|
||||
await expect(api.history("ses-1")).rejects.toMatchObject({
|
||||
code: "request_failed",
|
||||
detail: "Invalid archived session history",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the real id before polling readiness and reports provisioning phases", async () => {
|
||||
vi.useFakeTimers();
|
||||
const tokens = ["workos:create", "workos:create", "workos:new-account"];
|
||||
const authorizations: string[] = [];
|
||||
let statusCalls = 0;
|
||||
const phases: Array<string | undefined> = [];
|
||||
try {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => tokens.shift(),
|
||||
fetch: async (input, init) => {
|
||||
authorizations.push(
|
||||
new Headers(init?.headers).get("Authorization") ?? "",
|
||||
);
|
||||
const url = new URL(String(input));
|
||||
if (init?.method === "POST") {
|
||||
return jsonResponse(
|
||||
{
|
||||
success: true,
|
||||
data: { sessionId: "ses-1", status: "provisioning" },
|
||||
},
|
||||
201,
|
||||
);
|
||||
}
|
||||
expect(url.pathname).toBe("/api/v1/session/ses-1/status");
|
||||
statusCalls += 1;
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: {
|
||||
sessionId: "ses-1",
|
||||
status: statusCalls === 1 ? "provisioning" : "ready",
|
||||
phase: statusCalls === 1 ? "cloning_repo" : "ready",
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const created = await api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
});
|
||||
expect(created).toMatchObject({
|
||||
sessionId: "ses-1",
|
||||
status: "provisioning",
|
||||
});
|
||||
expect(statusCalls).toBe(0);
|
||||
const ready = api.waitUntilReady(
|
||||
created.sessionId,
|
||||
new AbortController().signal,
|
||||
({ phase }) => phases.push(phase),
|
||||
);
|
||||
await vi.waitFor(() => expect(statusCalls).toBe(1));
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
await expect(ready).resolves.toBeUndefined();
|
||||
expect(statusCalls).toBe(2);
|
||||
expect(phases).toEqual(["cloning_repo", "ready"]);
|
||||
expect(authorizations).toEqual([
|
||||
"Bearer workos:create",
|
||||
"Bearer workos:create",
|
||||
"Bearer workos:create",
|
||||
]);
|
||||
expect(tokens).toEqual(["workos:new-account"]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("refreshes an expired provisioning token without switching accounts", async () => {
|
||||
const original = jwtFor("user-1", "original");
|
||||
const refreshed = jwtFor("user-1", "refreshed");
|
||||
const tokens = [original, refreshed];
|
||||
const authorizations: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => tokens.shift(),
|
||||
fetch: async (_input, init) => {
|
||||
const authorization =
|
||||
new Headers(init?.headers).get("Authorization") ?? "";
|
||||
authorizations.push(authorization);
|
||||
if (authorization === `Bearer ${original}`) {
|
||||
return jsonResponse(
|
||||
{ success: false, error: "authentication required" },
|
||||
401,
|
||||
);
|
||||
}
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: { sessionId: "ses-1", status: "ready" },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.waitUntilReady("ses-1", new AbortController().signal),
|
||||
).resolves.toBeUndefined();
|
||||
expect(authorizations).toEqual([
|
||||
`Bearer ${original}`,
|
||||
`Bearer ${refreshed}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not switch accounts while refreshing provisioning auth", async () => {
|
||||
const original = jwtFor("user-1", "original");
|
||||
const otherAccount = jwtFor("user-2", "refreshed");
|
||||
const tokens = [original, otherAccount];
|
||||
let statusCalls = 0;
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => tokens.shift(),
|
||||
fetch: async () => {
|
||||
statusCalls += 1;
|
||||
return jsonResponse(
|
||||
{ success: false, error: "authentication required" },
|
||||
401,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.waitUntilReady("ses-1", new AbortController().signal),
|
||||
).rejects.toMatchObject({ code: "authentication_required" });
|
||||
expect(statusCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("returns a recovered real id without waiting for provisioning", async () => {
|
||||
const requests: string[] = [];
|
||||
let recoveryTitle = "";
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:fresh",
|
||||
fetch: async (input, init) => {
|
||||
requests.push(
|
||||
`${init?.method ?? "GET"} ${new URL(String(input)).pathname}`,
|
||||
);
|
||||
if (init?.method === "POST") {
|
||||
recoveryTitle = String(JSON.parse(String(init.body)).title);
|
||||
return jsonResponse({ success: false, error: "gateway" }, 500);
|
||||
}
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
id: "ses-recovered",
|
||||
title: recoveryTitle,
|
||||
status: "provisioning",
|
||||
sandboxUrl: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
sessionId: "ses-recovered",
|
||||
status: "provisioning",
|
||||
});
|
||||
expect(requests).toEqual(["POST /api/v1/session", "GET /api/v1/session"]);
|
||||
});
|
||||
|
||||
it("recovers the real id after the create request times out", async () => {
|
||||
vi.useFakeTimers();
|
||||
const requests: string[] = [];
|
||||
let recoveryTitle = "";
|
||||
try {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
createTimeoutMs: 100,
|
||||
getAuthToken: async () => "workos:fresh",
|
||||
fetch: async (input, init) => {
|
||||
requests.push(
|
||||
`${init?.method ?? "GET"} ${new URL(String(input)).pathname}`,
|
||||
);
|
||||
if (init?.method === "POST") {
|
||||
recoveryTitle = String(JSON.parse(String(init.body)).title);
|
||||
return await new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener(
|
||||
"abort",
|
||||
() => reject(init.signal?.reason),
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
id: "ses-recovered",
|
||||
title: recoveryTitle,
|
||||
status: "provisioning",
|
||||
sandboxUrl: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const creating = api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
await expect(creating).resolves.toMatchObject({
|
||||
sessionId: "ses-recovered",
|
||||
});
|
||||
expect(requests).toEqual(["POST /api/v1/session", "GET /api/v1/session"]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a failed recovered session without hiding its real id", async () => {
|
||||
let recoveryTitle = "";
|
||||
const requests: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:fresh",
|
||||
fetch: async (input, init) => {
|
||||
requests.push(
|
||||
`${init?.method ?? "GET"} ${new URL(String(input)).pathname}`,
|
||||
);
|
||||
if (init?.method === "POST") {
|
||||
recoveryTitle = String(JSON.parse(String(init.body)).title);
|
||||
return jsonResponse({ success: false, error: "gateway" }, 500);
|
||||
}
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
title: recoveryTitle,
|
||||
status: "failed",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.create({
|
||||
modelId: REMOTE_SESSION.metadata.modelId ?? "",
|
||||
repoUrl: REMOTE_SESSION.repoContext.repoUrl ?? "",
|
||||
}),
|
||||
).resolves.toMatchObject({ sessionId: "ses-outer", status: "failed" });
|
||||
expect(requests).toEqual(["POST /api/v1/session", "GET /api/v1/session"]);
|
||||
});
|
||||
|
||||
it("recovers a create accepted before a raw network failure", async () => {
|
||||
let recoveryTitle = "";
|
||||
let listCalls = 0;
|
||||
const now = new Date().toISOString();
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async (_input, init) => {
|
||||
if (init?.method === "POST") {
|
||||
recoveryTitle = String(JSON.parse(String(init.body)).title);
|
||||
throw new TypeError("fetch failed");
|
||||
}
|
||||
listCalls += 1;
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
id: "ses-recovered",
|
||||
title: recoveryTitle,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.create({
|
||||
requestId: "request-a",
|
||||
modelId: REMOTE_SESSION.metadata.modelId ?? "",
|
||||
repoUrl: REMOTE_SESSION.repoContext.repoUrl ?? "",
|
||||
}),
|
||||
).resolves.toMatchObject({ sessionId: "ses-recovered" });
|
||||
expect(listCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not recover another process's identical session", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async (_input, init) =>
|
||||
init?.method === "POST"
|
||||
? jsonResponse({ success: false, error: "gateway timeout" }, 500)
|
||||
: jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
id: "ses-other-process",
|
||||
title: "__cline_create_request__:other-request",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.create({
|
||||
requestId: "this-request",
|
||||
modelId: REMOTE_SESSION.metadata.modelId ?? "",
|
||||
repoUrl: REMOTE_SESSION.repoContext.repoUrl ?? "",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "request_failed" });
|
||||
});
|
||||
|
||||
it("hides temporary create request titles from session lists", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async () =>
|
||||
jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
...REMOTE_SESSION,
|
||||
title: "__cline_create_request__:request-a",
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
await expect(api.list()).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
id: "ses-outer",
|
||||
title: undefined,
|
||||
metadata: expect.objectContaining({
|
||||
createRequestTitle: "__cline_create_request__:request-a",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns a stable, environment-aware GitHub connection error", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://staging-app.example/",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({ success: false, error: "GitHub is not connected" }, 412),
|
||||
});
|
||||
|
||||
const error = await api
|
||||
.create({ modelId: "model", repoUrl: "https://github.com/cline/test" })
|
||||
.catch((caught) => caught);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudSessionError);
|
||||
expect(error.code).toBe("github_not_connected");
|
||||
expect(error.message).toBe(
|
||||
'CLOUD_SESSION_ERROR:{"code":"github_not_connected","message":"GitHub is not connected","connectUrl":"https://staging-app.example/dashboard/integrations"}',
|
||||
);
|
||||
});
|
||||
|
||||
it("routes organization GitHub setup to organization integrations", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://staging-app.example/",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({ success: false, error: "GitHub is not connected" }, 412),
|
||||
});
|
||||
|
||||
const error = await api
|
||||
.create({
|
||||
modelId: "model",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
organizationId: "org-cline-bot",
|
||||
})
|
||||
.catch((caught) => caught);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudSessionError);
|
||||
expect(error.connectUrl).toBe(
|
||||
"https://staging-app.example/dashboard/organization/integrations",
|
||||
);
|
||||
});
|
||||
|
||||
it("lists connected GitHub repositories and their branches", async () => {
|
||||
const requestedPaths: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async (input) => {
|
||||
const path = new URL(String(input)).pathname;
|
||||
requestedPaths.push(path);
|
||||
if (path.endsWith("/branches")) {
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [{ name: "main" }, { name: "feature/cloud" }],
|
||||
});
|
||||
}
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
id: 42,
|
||||
name: "cline",
|
||||
full_name: "cline/cline",
|
||||
html_url: "https://github.com/cline/cline",
|
||||
clone_url: "https://github.com/cline/cline.git",
|
||||
default_branch: "main",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
expect(await api.listRepositories()).toEqual({
|
||||
connected: true,
|
||||
connectUrl: "https://app.example/dashboard/integrations",
|
||||
repositories: [
|
||||
{
|
||||
id: 42,
|
||||
name: "cline",
|
||||
fullName: "cline/cline",
|
||||
url: "https://github.com/cline/cline",
|
||||
defaultBranch: "main",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(await api.listBranches(42)).toEqual({
|
||||
available: true,
|
||||
branches: ["main", "feature/cloud"],
|
||||
nextToken: "",
|
||||
});
|
||||
expect(requestedPaths).toEqual([
|
||||
"/api/v1/integrations/github/repositories",
|
||||
"/api/v1/integrations/github/repositories/42/branches",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads paginated branch responses and forwards search cursors", async () => {
|
||||
let requestedUrl = "";
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async (input) => {
|
||||
requestedUrl = String(input);
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: {
|
||||
items: [{ name: "feature/cloud" }],
|
||||
nextToken: "next/page",
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await api.listBranches(42, undefined, {
|
||||
cursor: "search cursor",
|
||||
query: "feature/cloud",
|
||||
}),
|
||||
).toEqual({
|
||||
available: true,
|
||||
branches: ["feature/cloud"],
|
||||
nextToken: "next/page",
|
||||
});
|
||||
const url = new URL(requestedUrl);
|
||||
expect(url.pathname).toBe(
|
||||
"/api/v1/integrations/github/repositories/42/branches",
|
||||
);
|
||||
expect(url.searchParams.get("query")).toBe("feature/cloud");
|
||||
expect(url.searchParams.get("cursor")).toBe("search cursor");
|
||||
});
|
||||
|
||||
it("filters legacy branch responses while backends roll out", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({
|
||||
success: true,
|
||||
data: [{ name: "main" }, { name: "feature/cloud" }],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(await api.listBranches(42, undefined, { query: "FEATURE" })).toEqual(
|
||||
{
|
||||
available: true,
|
||||
branches: ["feature/cloud"],
|
||||
nextToken: "",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the repository default when the branch API is unavailable", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({ success: false, error: "route not found" }, 404),
|
||||
});
|
||||
|
||||
expect(await api.listBranches(42)).toEqual({
|
||||
available: false,
|
||||
branches: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses organization-scoped repository and branch endpoints", async () => {
|
||||
const requestedPaths: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async (input) => {
|
||||
const path = new URL(String(input)).pathname;
|
||||
requestedPaths.push(path);
|
||||
return jsonResponse({ success: true, data: [] });
|
||||
},
|
||||
});
|
||||
|
||||
expect(await api.listRepositories("org-cline-bot")).toMatchObject({
|
||||
connected: true,
|
||||
connectUrl: "https://app.example/dashboard/organization/integrations",
|
||||
});
|
||||
await api.listBranches(42, "org-cline-bot");
|
||||
expect(requestedPaths).toEqual([
|
||||
"/api/v1/organizations/org-cline-bot/integrations/github/repositories",
|
||||
"/api/v1/organizations/org-cline-bot/integrations/github/repositories/42/branches",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses ambiguous recovery for overlapping identical create requests", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const record = (id: string, createdAt: string) => ({
|
||||
id,
|
||||
title: "__cline_create_request__:same-request",
|
||||
status: "running",
|
||||
sandboxUrl: `pod-${id}`,
|
||||
repoContext: { repoUrl: "https://github.com/cline/test" },
|
||||
metadata: { modelId: "anthropic/claude-sonnet-5" },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async (_input, init) =>
|
||||
init?.method === "POST"
|
||||
? jsonResponse({ success: false, error: "gateway timeout" }, 500)
|
||||
: jsonResponse({
|
||||
success: true,
|
||||
data: [
|
||||
record("ses-newer", now),
|
||||
record("ses-older", new Date(Date.now() - 1_000).toISOString()),
|
||||
],
|
||||
}),
|
||||
});
|
||||
const input = {
|
||||
requestId: "same-request",
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
};
|
||||
|
||||
const error = await api.create(input).catch((caught) => caught);
|
||||
expect(error).toMatchObject({ code: "request_failed" });
|
||||
expect(String(error)).toContain("ambiguous result");
|
||||
});
|
||||
|
||||
it("reports provisioning failure without deleting the known session", async () => {
|
||||
const authorizations: string[] = [];
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:create",
|
||||
fetch: async (input, init) => {
|
||||
authorizations.push(
|
||||
new Headers(init?.headers).get("Authorization") ?? "",
|
||||
);
|
||||
expect(new URL(String(input)).pathname).toBe(
|
||||
"/api/v1/session/ses-failed/status",
|
||||
);
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
data: {
|
||||
sessionId: "ses-failed",
|
||||
status: "failed",
|
||||
statusReason: "clone failed",
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.waitUntilReady("ses-failed", new AbortController().signal),
|
||||
).rejects.toMatchObject({ code: "session_failed", detail: "clone failed" });
|
||||
expect(authorizations).toEqual(["Bearer workos:create"]);
|
||||
});
|
||||
|
||||
it("turns a generic forbidden response into actionable account guidance", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({ success: false, error: "forbidden" }, 403),
|
||||
});
|
||||
|
||||
const error = await api
|
||||
.create({ modelId: "model", repoUrl: "https://github.com/cline/test" })
|
||||
.catch((caught) => caught);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudSessionError);
|
||||
expect(error.code).toBe("request_failed");
|
||||
expect(error.status).toBe(403);
|
||||
expect(error.message).toContain(
|
||||
"Switch to Personal or another organization in Settings → Account",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not run list recovery after a fast client-side rejection", async () => {
|
||||
let listRequests = 0;
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example",
|
||||
getAuthToken: async () => "sk_test",
|
||||
fetch: async (_input, init) => {
|
||||
if (init?.method === "POST") {
|
||||
return jsonResponse({ success: false, error: "invalid branch" }, 422);
|
||||
}
|
||||
listRequests += 1;
|
||||
return jsonResponse({ success: true, data: [] });
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
api.create({
|
||||
modelId: "anthropic/claude-sonnet-5",
|
||||
repoUrl: "https://github.com/cline/test",
|
||||
}),
|
||||
).rejects.toThrow(/invalid branch/);
|
||||
expect(listRequests).toBe(0);
|
||||
});
|
||||
|
||||
it("returns the GitHub connection action when no integration exists", async () => {
|
||||
const api = new CloudSessionApi({
|
||||
apiBaseUrl: "https://api.example",
|
||||
appBaseUrl: "https://app.example/",
|
||||
getAuthToken: async () => "workos:test",
|
||||
fetch: async () =>
|
||||
jsonResponse({ success: false, error: "not connected" }, 404),
|
||||
});
|
||||
|
||||
expect(await api.listRepositories()).toEqual({
|
||||
connected: false,
|
||||
connectUrl: "https://app.example/dashboard/integrations",
|
||||
repositories: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,712 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { decodeJwtPayload } from "@cline/shared";
|
||||
import type {
|
||||
CloudBranchListOptions,
|
||||
CloudBranchListResult,
|
||||
CloudRepositoryListResult,
|
||||
} from "../webview/lib/cloud-repositories";
|
||||
|
||||
const CREATE_TIMEOUT_MS = 610_000;
|
||||
const PROVISIONING_POLL_MS = 3_000;
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const CLOUD_ERROR_PREFIX = "CLOUD_SESSION_ERROR:";
|
||||
const CREATE_REQUEST_TITLE_PREFIX = "__cline_create_request__:";
|
||||
|
||||
type FetchLike = (
|
||||
input: string | URL | Request,
|
||||
init?: RequestInit,
|
||||
) => Promise<Response>;
|
||||
|
||||
export type CloudSessionRecord = {
|
||||
id: string;
|
||||
status: string;
|
||||
title?: string;
|
||||
sandboxUrl: string;
|
||||
repoContext: { repoUrl?: string; branch?: string };
|
||||
metadata: {
|
||||
modelId?: string;
|
||||
statusReason?: string;
|
||||
createRequestTitle?: string;
|
||||
};
|
||||
expiredAt?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type CloudProvisioningOutcome =
|
||||
| { status: "provisioning" }
|
||||
| { status: "ready"; sessionId: string }
|
||||
| { status: "failed"; message: string };
|
||||
|
||||
export function deriveCloudSessionTitle(prompt: string): string {
|
||||
return (prompt.trim().split("\n")[0] ?? "").trim().slice(0, 72);
|
||||
}
|
||||
|
||||
export type CreateCloudSessionInput = {
|
||||
/** Stable client-planned id for single-flighting one chat's start request. */
|
||||
requestId?: string;
|
||||
modelId: string;
|
||||
repoUrl: string;
|
||||
initialPrompt?: string;
|
||||
branch?: string;
|
||||
autoApproveTools?: boolean;
|
||||
thinking?: boolean;
|
||||
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
||||
/** Omit for a personal session; otherwise scopes billing to this org. */
|
||||
organizationId?: string;
|
||||
};
|
||||
|
||||
export type {
|
||||
CloudBranchListOptions,
|
||||
CloudBranchListResult,
|
||||
CloudRepositoryListResult,
|
||||
CloudRepositoryOption,
|
||||
} from "../webview/lib/cloud-repositories";
|
||||
|
||||
type CloudSessionApiOptions = {
|
||||
apiBaseUrl: string;
|
||||
appBaseUrl: string;
|
||||
getAuthToken: () => Promise<string | undefined>;
|
||||
fetch?: FetchLike;
|
||||
createTimeoutMs?: number;
|
||||
};
|
||||
|
||||
type CloudErrorCode =
|
||||
| "authentication_required"
|
||||
| "github_not_connected"
|
||||
| "session_not_found"
|
||||
| "session_expired"
|
||||
| "session_failed"
|
||||
| "request_failed";
|
||||
|
||||
export class CloudSessionError extends Error {
|
||||
constructor(
|
||||
readonly code: CloudErrorCode,
|
||||
readonly detail: string,
|
||||
readonly connectUrl?: string,
|
||||
/** HTTP status of the failed request, when one was received. */
|
||||
readonly status?: number,
|
||||
) {
|
||||
super(
|
||||
`${CLOUD_ERROR_PREFIX}${JSON.stringify({ code, message: detail, connectUrl })}`,
|
||||
);
|
||||
this.name = "CloudSessionError";
|
||||
}
|
||||
}
|
||||
|
||||
type ApiResponse<T> = {
|
||||
success?: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function trimTrailingSlash(value: string): string {
|
||||
return value.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function createRequestTitle(requestId: string): string {
|
||||
return `${CREATE_REQUEST_TITLE_PREFIX}${requestId}`.slice(0, 255);
|
||||
}
|
||||
|
||||
function isCreateRequestTitle(title: string | undefined): boolean {
|
||||
return title?.startsWith(CREATE_REQUEST_TITLE_PREFIX) === true;
|
||||
}
|
||||
|
||||
type CreationAuth = {
|
||||
token: string;
|
||||
subject?: string;
|
||||
};
|
||||
|
||||
type RequestAuth = string | CreationAuth;
|
||||
|
||||
function authSubject(token: string): string | undefined {
|
||||
const payload = decodeJwtPayload(token.replace(/^workos:/, ""));
|
||||
return typeof payload?.sub === "string" && payload.sub.trim()
|
||||
? payload.sub.trim()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function waitForProvisioningPoll(signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason);
|
||||
return;
|
||||
}
|
||||
const onAbort = () => {
|
||||
clearTimeout(timeout);
|
||||
reject(signal.reason);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, PROVISIONING_POLL_MS);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function readApiError(payload: unknown, fallback: string): string {
|
||||
if (payload && typeof payload === "object") {
|
||||
const error = (payload as { error?: unknown }).error;
|
||||
if (typeof error === "string" && error.trim()) {
|
||||
return error.trim();
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function cloudErrorForResponse(
|
||||
status: number,
|
||||
payload: unknown,
|
||||
appBaseUrl: string,
|
||||
githubConnectUrl?: string,
|
||||
): CloudSessionError {
|
||||
const message = readApiError(
|
||||
payload,
|
||||
`Cloud session request failed (${status})`,
|
||||
);
|
||||
if (status === 401) {
|
||||
return new CloudSessionError("authentication_required", message);
|
||||
}
|
||||
if (status === 404) {
|
||||
return new CloudSessionError("session_not_found", message);
|
||||
}
|
||||
if (status === 410) {
|
||||
return new CloudSessionError("session_expired", message);
|
||||
}
|
||||
if (status === 412) {
|
||||
return new CloudSessionError(
|
||||
"github_not_connected",
|
||||
message,
|
||||
githubConnectUrl ??
|
||||
`${trimTrailingSlash(appBaseUrl)}/dashboard/integrations`,
|
||||
);
|
||||
}
|
||||
if (status === 403 && message.trim().toLowerCase() === "forbidden") {
|
||||
return new CloudSessionError(
|
||||
"request_failed",
|
||||
"Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",
|
||||
undefined,
|
||||
status,
|
||||
);
|
||||
}
|
||||
return new CloudSessionError("request_failed", message, undefined, status);
|
||||
}
|
||||
|
||||
export type CloudProvisioningPhase =
|
||||
| "provisioning"
|
||||
| "cloning_repo"
|
||||
| "agent_starting"
|
||||
| "ready"
|
||||
| "failed";
|
||||
|
||||
function parseCloudProvisioningPhase(
|
||||
value: unknown,
|
||||
): CloudProvisioningPhase | undefined {
|
||||
switch (value) {
|
||||
case "provisioning":
|
||||
case "cloning_repo":
|
||||
case "agent_starting":
|
||||
case "ready":
|
||||
case "failed":
|
||||
return value;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudSessionApi {
|
||||
private readonly apiBaseUrl: string;
|
||||
private readonly appBaseUrl: string;
|
||||
private readonly fetchImpl: FetchLike;
|
||||
private readonly createTimeoutMs: number;
|
||||
constructor(private readonly options: CloudSessionApiOptions) {
|
||||
this.apiBaseUrl = trimTrailingSlash(options.apiBaseUrl);
|
||||
this.appBaseUrl = trimTrailingSlash(options.appBaseUrl);
|
||||
this.fetchImpl = options.fetch ?? fetch;
|
||||
this.createTimeoutMs = options.createTimeoutMs ?? CREATE_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
githubConnectUrl?: string,
|
||||
auth?: RequestAuth,
|
||||
): Promise<T> {
|
||||
let refreshed = false;
|
||||
while (true) {
|
||||
const token =
|
||||
typeof auth === "string"
|
||||
? auth
|
||||
: (auth?.token ?? (await this.options.getAuthToken()));
|
||||
if (!token?.trim()) {
|
||||
throw new CloudSessionError(
|
||||
"authentication_required",
|
||||
"Sign in to Cline before starting a cloud session.",
|
||||
);
|
||||
}
|
||||
const response = await this.fetchImpl(`${this.apiBaseUrl}${path}`, {
|
||||
...init,
|
||||
signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${token.trim()}`,
|
||||
...(init.body ? { "Content-Type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
const payload =
|
||||
response.status === 204
|
||||
? undefined
|
||||
: await response.json().catch(() => undefined);
|
||||
if (!response.ok) {
|
||||
if (
|
||||
response.status === 401 &&
|
||||
typeof auth === "object" &&
|
||||
!refreshed &&
|
||||
(await this.refreshCreationAuth(auth))
|
||||
) {
|
||||
refreshed = true;
|
||||
continue;
|
||||
}
|
||||
throw cloudErrorForResponse(
|
||||
response.status,
|
||||
payload,
|
||||
this.appBaseUrl,
|
||||
githubConnectUrl,
|
||||
);
|
||||
}
|
||||
return (payload as ApiResponse<T> | undefined)?.data as T;
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshCreationAuth(auth: CreationAuth): Promise<boolean> {
|
||||
if (!auth.subject) return false;
|
||||
const freshToken = (await this.options.getAuthToken())?.trim();
|
||||
if (
|
||||
!freshToken ||
|
||||
freshToken === auth.token ||
|
||||
authSubject(freshToken) !== auth.subject
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
auth.token = freshToken;
|
||||
return true;
|
||||
}
|
||||
|
||||
async list(organizationId?: string): Promise<CloudSessionRecord[]> {
|
||||
return await this.listWithToken(organizationId);
|
||||
}
|
||||
|
||||
private async listWithToken(
|
||||
organizationId?: string,
|
||||
auth?: RequestAuth,
|
||||
preserveCreateRequestTitle = false,
|
||||
): Promise<CloudSessionRecord[]> {
|
||||
const query = organizationId?.trim()
|
||||
? `?organizationId=${encodeURIComponent(organizationId.trim())}`
|
||||
: "";
|
||||
const rows =
|
||||
(await this.request<CloudSessionRecord[]>(
|
||||
`/api/v1/session${query}`,
|
||||
{},
|
||||
undefined,
|
||||
auth,
|
||||
)) ?? [];
|
||||
// Keep malformed account records from breaking discovery or recovery.
|
||||
return rows.flatMap((row) => {
|
||||
if (!row || typeof row !== "object" || typeof row.id !== "string") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
...row,
|
||||
title:
|
||||
!preserveCreateRequestTitle && isCreateRequestTitle(row.title)
|
||||
? undefined
|
||||
: row.title,
|
||||
repoContext:
|
||||
row.repoContext && typeof row.repoContext === "object"
|
||||
? row.repoContext
|
||||
: {},
|
||||
metadata: {
|
||||
...(row.metadata && typeof row.metadata === "object"
|
||||
? row.metadata
|
||||
: {}),
|
||||
...(!preserveCreateRequestTitle && isCreateRequestTitle(row.title)
|
||||
? { createRequestTitle: row.title }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
async listRepositories(
|
||||
organizationId?: string,
|
||||
): Promise<CloudRepositoryListResult> {
|
||||
const normalizedOrganizationId = organizationId?.trim();
|
||||
const connectUrl = normalizedOrganizationId
|
||||
? `${this.appBaseUrl}/dashboard/organization/integrations`
|
||||
: `${this.appBaseUrl}/dashboard/integrations`;
|
||||
const path = normalizedOrganizationId
|
||||
? `/api/v1/organizations/${encodeURIComponent(normalizedOrganizationId)}/integrations/github/repositories`
|
||||
: "/api/v1/integrations/github/repositories";
|
||||
try {
|
||||
const repositories =
|
||||
(await this.request<
|
||||
Array<{
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
full_name?: unknown;
|
||||
html_url?: unknown;
|
||||
clone_url?: unknown;
|
||||
default_branch?: unknown;
|
||||
}>
|
||||
>(path)) ?? [];
|
||||
return {
|
||||
connected: true,
|
||||
connectUrl,
|
||||
repositories: repositories.flatMap((repository) => {
|
||||
const id = Number(repository.id);
|
||||
const url = String(
|
||||
repository.html_url ?? repository.clone_url ?? "",
|
||||
).trim();
|
||||
if (!Number.isSafeInteger(id) || id <= 0 || !url) return [];
|
||||
const name = String(repository.name ?? "").trim();
|
||||
return [
|
||||
{
|
||||
id,
|
||||
name,
|
||||
fullName: String(repository.full_name ?? (name || url)).trim(),
|
||||
url,
|
||||
defaultBranch: String(repository.default_branch ?? "").trim(),
|
||||
},
|
||||
];
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof CloudSessionError &&
|
||||
error.code === "session_not_found"
|
||||
) {
|
||||
return { connected: false, connectUrl, repositories: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async listBranches(
|
||||
repositoryId: number,
|
||||
organizationId?: string,
|
||||
options: CloudBranchListOptions = {},
|
||||
): Promise<CloudBranchListResult> {
|
||||
if (!Number.isSafeInteger(repositoryId) || repositoryId <= 0) {
|
||||
throw new CloudSessionError(
|
||||
"request_failed",
|
||||
"Select a GitHub repository before loading branches.",
|
||||
);
|
||||
}
|
||||
const normalizedOrganizationId = organizationId?.trim();
|
||||
const path = normalizedOrganizationId
|
||||
? `/api/v1/organizations/${encodeURIComponent(normalizedOrganizationId)}/integrations/github/repositories/${repositoryId}/branches`
|
||||
: `/api/v1/integrations/github/repositories/${repositoryId}/branches`;
|
||||
const search = new URLSearchParams();
|
||||
const query = options.query?.trim();
|
||||
const cursor = options.cursor?.trim();
|
||||
if (query) search.set("query", query);
|
||||
if (cursor) search.set("cursor", cursor);
|
||||
const requestPath = search.size > 0 ? `${path}?${search}` : path;
|
||||
try {
|
||||
const payload = await this.request<
|
||||
| Array<{ name?: unknown }>
|
||||
| {
|
||||
items?: Array<{ name?: unknown }>;
|
||||
nextToken?: unknown;
|
||||
}
|
||||
>(requestPath);
|
||||
const branches = Array.isArray(payload)
|
||||
? payload
|
||||
: Array.isArray(payload?.items)
|
||||
? payload.items
|
||||
: [];
|
||||
const normalizedQuery = query?.toLowerCase();
|
||||
return {
|
||||
available: true,
|
||||
branches: branches.flatMap((branch) => {
|
||||
const name = String(branch.name ?? "").trim();
|
||||
return name &&
|
||||
(!Array.isArray(payload) ||
|
||||
!normalizedQuery ||
|
||||
name.toLowerCase().includes(normalizedQuery))
|
||||
? [name]
|
||||
: [];
|
||||
}),
|
||||
nextToken: Array.isArray(payload)
|
||||
? ""
|
||||
: String(payload?.nextToken ?? "").trim(),
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof CloudSessionError &&
|
||||
error.code === "session_not_found"
|
||||
) {
|
||||
return { available: false, branches: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async status(
|
||||
sessionId: string,
|
||||
options: { authToken?: string; signal?: AbortSignal } = {},
|
||||
): Promise<{
|
||||
sessionId?: string;
|
||||
status?: string;
|
||||
phase?: CloudProvisioningPhase;
|
||||
statusReason?: string;
|
||||
}> {
|
||||
return await this.request(
|
||||
`/api/v1/session/${encodeURIComponent(sessionId)}/status`,
|
||||
{ signal: options.signal },
|
||||
undefined,
|
||||
options.authToken,
|
||||
);
|
||||
}
|
||||
|
||||
async create(input: CreateCloudSessionInput): Promise<{
|
||||
sessionId: string;
|
||||
status: string;
|
||||
sandboxUrl: string;
|
||||
cleanupAuthToken: string;
|
||||
}> {
|
||||
const initialAuthToken = (await this.options.getAuthToken())?.trim();
|
||||
if (!initialAuthToken) {
|
||||
throw new CloudSessionError(
|
||||
"authentication_required",
|
||||
"Sign in to Cline before starting a cloud session.",
|
||||
);
|
||||
}
|
||||
const creationAuth: CreationAuth = {
|
||||
token: initialAuthToken,
|
||||
subject: authSubject(initialAuthToken),
|
||||
};
|
||||
const recoveryTitle = createRequestTitle(
|
||||
input.requestId?.trim() || randomUUID(),
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.createTimeoutMs);
|
||||
try {
|
||||
const created = await this.request<{
|
||||
sessionId: string;
|
||||
sandboxUrl?: string;
|
||||
status?: string;
|
||||
}>(
|
||||
"/api/v1/session",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
modelId: input.modelId,
|
||||
repoUrl: input.repoUrl,
|
||||
title: recoveryTitle,
|
||||
...(input.branch?.trim() ? { branch: input.branch.trim() } : {}),
|
||||
...(input.organizationId?.trim()
|
||||
? { organizationId: input.organizationId.trim() }
|
||||
: {}),
|
||||
}),
|
||||
signal: controller.signal,
|
||||
},
|
||||
input.organizationId?.trim()
|
||||
? `${this.appBaseUrl}/dashboard/organization/integrations`
|
||||
: undefined,
|
||||
creationAuth,
|
||||
);
|
||||
const sessionId = created?.sessionId?.trim();
|
||||
if (!sessionId) {
|
||||
throw new CloudSessionError(
|
||||
"request_failed",
|
||||
"The cloud session service returned no session id.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
sessionId,
|
||||
status: created.status?.trim() || "provisioning",
|
||||
sandboxUrl: created.sandboxUrl?.trim() ?? "",
|
||||
cleanupAuthToken: creationAuth.token,
|
||||
};
|
||||
} catch (error) {
|
||||
// Recover only failures that may have followed an accepted POST.
|
||||
const mayStillBeProvisioning =
|
||||
controller.signal.aborted ||
|
||||
!(error instanceof CloudSessionError) ||
|
||||
(error instanceof CloudSessionError &&
|
||||
error.code === "request_failed" &&
|
||||
(error.status === undefined || error.status >= 500));
|
||||
if (mayStillBeProvisioning) {
|
||||
const requestedBranch = input.branch?.trim();
|
||||
// The title carries the request identity because the API lacks idempotency.
|
||||
const candidates = (
|
||||
await this.listWithToken(
|
||||
input.organizationId,
|
||||
creationAuth,
|
||||
true,
|
||||
).catch(() => [])
|
||||
).filter(
|
||||
(session) =>
|
||||
session.title === recoveryTitle &&
|
||||
session.repoContext.repoUrl === input.repoUrl &&
|
||||
session.metadata.modelId === input.modelId &&
|
||||
(!requestedBranch ||
|
||||
session.repoContext.branch === requestedBranch),
|
||||
);
|
||||
if (candidates.length > 1) {
|
||||
throw new CloudSessionError(
|
||||
"request_failed",
|
||||
"Cloud session creation had an ambiguous result. Check your cloud session list before trying again.",
|
||||
);
|
||||
}
|
||||
const recovered = candidates[0];
|
||||
if (recovered) {
|
||||
return {
|
||||
sessionId: recovered.id,
|
||||
status: recovered.status,
|
||||
sandboxUrl: recovered.sandboxUrl,
|
||||
cleanupAuthToken: creationAuth.token,
|
||||
};
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
async waitUntilReady(
|
||||
sessionId: string,
|
||||
signal: AbortSignal,
|
||||
onStatus?: (status: { phase?: CloudProvisioningPhase }) => void,
|
||||
): Promise<void> {
|
||||
signal = AbortSignal.any([
|
||||
signal,
|
||||
AbortSignal.timeout(this.createTimeoutMs),
|
||||
]);
|
||||
const token = await this.options.getAuthToken();
|
||||
const authToken = token
|
||||
? { token, subject: authSubject(token) }
|
||||
: undefined;
|
||||
while (!signal.aborted) {
|
||||
let result:
|
||||
| {
|
||||
sessionId?: string;
|
||||
status?: string;
|
||||
phase?: CloudProvisioningPhase;
|
||||
statusReason?: string;
|
||||
}
|
||||
| undefined;
|
||||
try {
|
||||
result = await this.request(
|
||||
`/api/v1/session/${encodeURIComponent(sessionId)}/status`,
|
||||
{
|
||||
signal: AbortSignal.any([
|
||||
signal,
|
||||
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
]),
|
||||
},
|
||||
undefined,
|
||||
authToken,
|
||||
);
|
||||
} catch (error) {
|
||||
if (signal.aborted) throw error;
|
||||
if (
|
||||
error instanceof CloudSessionError &&
|
||||
error.code !== "request_failed"
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
await waitForProvisioningPoll(signal);
|
||||
continue;
|
||||
}
|
||||
const status = result?.status?.trim().toLowerCase();
|
||||
onStatus?.({ phase: parseCloudProvisioningPhase(result?.phase) });
|
||||
if (status === "ready" || status === "active") return;
|
||||
if (status === "failed") {
|
||||
throw new CloudSessionError(
|
||||
"session_failed",
|
||||
result?.statusReason?.trim() ||
|
||||
"The cloud sandbox could not be prepared.",
|
||||
);
|
||||
}
|
||||
if (status !== "provisioning") {
|
||||
throw new CloudSessionError(
|
||||
"request_failed",
|
||||
"The cloud session service returned an unexpected provisioning status.",
|
||||
);
|
||||
}
|
||||
await waitForProvisioningPoll(signal);
|
||||
}
|
||||
throw signal.reason;
|
||||
}
|
||||
|
||||
async delete(sessionId: string, authToken?: string): Promise<void> {
|
||||
await this.deleteWithAuth(sessionId, authToken);
|
||||
}
|
||||
|
||||
private async deleteWithAuth(
|
||||
sessionId: string,
|
||||
auth?: RequestAuth,
|
||||
): Promise<void> {
|
||||
await this.request(
|
||||
`/api/v1/session/${encodeURIComponent(sessionId)}`,
|
||||
{ method: "DELETE" },
|
||||
undefined,
|
||||
auth,
|
||||
);
|
||||
}
|
||||
|
||||
async updateTitle(
|
||||
sessionId: string,
|
||||
title: string,
|
||||
): Promise<CloudSessionRecord> {
|
||||
return await this.request<CloudSessionRecord>(
|
||||
`/api/v1/session/${encodeURIComponent(sessionId)}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ title }),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Raw archived snapshot; null distinguishes a missing archive from []. */
|
||||
async history(sessionId: string): Promise<unknown[] | null> {
|
||||
const token = await this.options.getAuthToken();
|
||||
if (!token?.trim()) {
|
||||
throw new CloudSessionError(
|
||||
"authentication_required",
|
||||
"Sign in to Cline to load this session's history.",
|
||||
);
|
||||
}
|
||||
const response = await this.fetchImpl(
|
||||
`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(sessionId)}/history`,
|
||||
{
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${token.trim()}`,
|
||||
},
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
},
|
||||
);
|
||||
if (response.status === 404) {
|
||||
return null;
|
||||
}
|
||||
const payload = await response.json().catch(() => undefined);
|
||||
if (!response.ok) {
|
||||
throw cloudErrorForResponse(response.status, payload, this.appBaseUrl);
|
||||
}
|
||||
if (payload?.version !== 1 || !Array.isArray(payload.messages)) {
|
||||
throw new CloudSessionError(
|
||||
"request_failed",
|
||||
"Invalid archived session history",
|
||||
);
|
||||
}
|
||||
return payload.messages;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,13 @@ const clineAccountServiceCtorMock = vi.hoisted(() => vi.fn());
|
||||
const executeClineAccountActionMock = vi.hoisted(() => vi.fn());
|
||||
const getProviderSettingsMock = vi.hoisted(() => vi.fn());
|
||||
const saveProviderSettingsMock = vi.hoisted(() => vi.fn());
|
||||
const persistProviderSettingsMock = vi.hoisted(() => vi.fn());
|
||||
const resolveProviderApiKeyMock = vi.hoisted(() => vi.fn());
|
||||
const clearLegacyProviderCredentialsMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("./legacy-provider-credentials", () => ({
|
||||
clearLegacyProviderCredentials: clearLegacyProviderCredentialsMock,
|
||||
}));
|
||||
|
||||
vi.mock("@cline/core", async () => {
|
||||
const actual =
|
||||
@@ -21,6 +27,7 @@ vi.mock("@cline/core", async () => {
|
||||
executeClineAccountAction: executeClineAccountActionMock,
|
||||
ProviderSettingsManager: class {
|
||||
getProviderSettings = getProviderSettingsMock;
|
||||
saveProviderSettings = persistProviderSettingsMock;
|
||||
},
|
||||
saveLocalProviderSettings: saveProviderSettingsMock,
|
||||
RuntimeOAuthTokenManager: class {
|
||||
@@ -31,11 +38,13 @@ vi.mock("@cline/core", async () => {
|
||||
|
||||
function createContext() {
|
||||
const capture = vi.fn();
|
||||
const setDistinctId = vi.fn();
|
||||
const updateCommonProperties = vi.fn();
|
||||
const ctx = {
|
||||
telemetry: { capture },
|
||||
telemetry: { capture, setDistinctId, updateCommonProperties },
|
||||
logger: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as unknown as SidecarContext;
|
||||
return { ctx, capture };
|
||||
return { ctx, capture, setDistinctId, updateCommonProperties };
|
||||
}
|
||||
|
||||
const FETCH_ME_ARGS = {
|
||||
@@ -53,12 +62,15 @@ beforeEach(() => {
|
||||
executeClineAccountActionMock.mockReset();
|
||||
getProviderSettingsMock.mockReset();
|
||||
saveProviderSettingsMock.mockReset();
|
||||
persistProviderSettingsMock.mockReset();
|
||||
resolveProviderApiKeyMock.mockReset();
|
||||
clearLegacyProviderCredentialsMock.mockReset();
|
||||
});
|
||||
|
||||
describe("cline_account command auth states", () => {
|
||||
it("returns a typed not-authenticated result when signed out, without telemetry or a thrown error", async () => {
|
||||
const { ctx, capture } = createContext();
|
||||
it("returns a typed not-authenticated result and restores anonymous telemetry when signed out", async () => {
|
||||
const { ctx, capture, setDistinctId, updateCommonProperties } =
|
||||
createContext();
|
||||
resolveProviderApiKeyMock.mockResolvedValue(null);
|
||||
getProviderSettingsMock.mockReturnValue(undefined);
|
||||
|
||||
@@ -72,6 +84,14 @@ describe("cline_account command auth states", () => {
|
||||
expect(executeClineAccountActionMock).not.toHaveBeenCalled();
|
||||
expect(clineAccountServiceCtorMock).not.toHaveBeenCalled();
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
expect(setDistinctId).toHaveBeenCalledWith(expect.any(String));
|
||||
expect(updateCommonProperties).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
user_id: undefined,
|
||||
account_id: undefined,
|
||||
organization_id: undefined,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("runs the account action unchanged when a fresh token resolves", async () => {
|
||||
@@ -114,11 +134,30 @@ describe("cline_account command auth states", () => {
|
||||
getAuthToken: () => Promise<string | undefined>;
|
||||
};
|
||||
await expect(serviceOptions.getAuthToken()).resolves.toBe(
|
||||
"persisted-token",
|
||||
"workos:persisted-token",
|
||||
);
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports signed out when the refresh token is rejected even though a stale access token is persisted", async () => {
|
||||
// The stale token would only fail the account request with a 401,
|
||||
// which rendered an error card whose Retry failed the same way.
|
||||
const { ctx } = createContext();
|
||||
const { OAuthReauthRequiredError } =
|
||||
await vi.importActual<typeof import("@cline/core")>("@cline/core");
|
||||
resolveProviderApiKeyMock.mockRejectedValue(
|
||||
new OAuthReauthRequiredError("cline"),
|
||||
);
|
||||
getProviderSettingsMock.mockReturnValue({
|
||||
auth: { accessToken: "persisted-token" },
|
||||
});
|
||||
|
||||
const result = await runClineAccountCommand(ctx);
|
||||
|
||||
expect(isClineAccountNotAuthenticatedResult(result)).toBe(true);
|
||||
expect(executeClineAccountActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports one auth refresh soft-failure event when the refresh fails and no fallback token exists", async () => {
|
||||
const { ctx, capture } = createContext();
|
||||
const refreshError = new Error(
|
||||
@@ -171,7 +210,7 @@ describe("cline_account keeps feature-flag identity in sync", () => {
|
||||
});
|
||||
|
||||
it("adopts the account identity on login", async () => {
|
||||
const { ctx } = createContext();
|
||||
const { ctx, setDistinctId, updateCommonProperties } = createContext();
|
||||
resolveProviderApiKeyMock.mockResolvedValue({ apiKey: "token" });
|
||||
getProviderSettingsMock.mockReturnValue({});
|
||||
executeClineAccountActionMock.mockResolvedValue({
|
||||
@@ -182,6 +221,62 @@ describe("cline_account keeps feature-flag identity in sync", () => {
|
||||
await runOperation(ctx, "fetchMe");
|
||||
|
||||
expect(await currentFlagsUserId()).toBe("acct-1");
|
||||
expect(setDistinctId).toHaveBeenCalledWith("acct-1");
|
||||
expect(updateCommonProperties).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ user_id: "acct-1", account_id: "acct-1" }),
|
||||
);
|
||||
expect(ctx.telemetryUser).toEqual({
|
||||
distinctId: "acct-1",
|
||||
accountId: "acct-1",
|
||||
email: "dev@example.com",
|
||||
organizationId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies and persists the active organization for task telemetry", async () => {
|
||||
const { ctx, updateCommonProperties } = createContext();
|
||||
resolveProviderApiKeyMock.mockResolvedValue({ apiKey: "token" });
|
||||
getProviderSettingsMock.mockReturnValue({
|
||||
provider: "cline",
|
||||
auth: { accountId: "acct-1", accessToken: "token" },
|
||||
});
|
||||
executeClineAccountActionMock.mockResolvedValue({
|
||||
id: "acct-1",
|
||||
email: "dev@example.com",
|
||||
organizations: [
|
||||
{
|
||||
active: true,
|
||||
memberId: "member-1",
|
||||
name: "Acme",
|
||||
organizationId: "org-1",
|
||||
roles: ["member"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await runOperation(ctx, "fetchMe");
|
||||
|
||||
expect(updateCommonProperties).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
user_id: "acct-1",
|
||||
organization_id: "org-1",
|
||||
}),
|
||||
);
|
||||
expect(persistProviderSettingsMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
auth: expect.objectContaining({
|
||||
organizationId: "org-1",
|
||||
memberId: "member-1",
|
||||
}),
|
||||
}),
|
||||
{ setLastUsed: false },
|
||||
);
|
||||
expect(ctx.telemetryUser).toEqual({
|
||||
distinctId: "acct-1",
|
||||
accountId: "acct-1",
|
||||
email: "dev@example.com",
|
||||
organizationId: "org-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the signed-in identity intact across an organization switch", async () => {
|
||||
@@ -219,7 +314,7 @@ describe("cline_account keeps feature-flag identity in sync", () => {
|
||||
});
|
||||
|
||||
it("clears the account identity on logout", async () => {
|
||||
const { ctx } = createContext();
|
||||
const { ctx, setDistinctId, updateCommonProperties } = createContext();
|
||||
resolveProviderApiKeyMock.mockResolvedValue({ apiKey: "token" });
|
||||
getProviderSettingsMock.mockReturnValue({});
|
||||
executeClineAccountActionMock.mockResolvedValue({ id: "acct-1" });
|
||||
@@ -233,10 +328,28 @@ describe("cline_account keeps feature-flag identity in sync", () => {
|
||||
await runOperation(ctx, "fetchMe");
|
||||
|
||||
expect(await currentFlagsUserId()).toBeUndefined();
|
||||
expect(ctx.telemetryUser).toEqual(
|
||||
expect.objectContaining({
|
||||
accountId: null,
|
||||
distinctId: expect.any(String),
|
||||
}),
|
||||
);
|
||||
expect(setDistinctId).toHaveBeenLastCalledWith(
|
||||
ctx.telemetryUser?.distinctId,
|
||||
);
|
||||
expect(ctx.telemetryUser?.distinctId).not.toBe("acct-1");
|
||||
expect(updateCommonProperties).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
user_id: undefined,
|
||||
account_id: undefined,
|
||||
account_email: undefined,
|
||||
organization_id: undefined,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the identity when sign-out blanks the cline auth settings", async () => {
|
||||
const { ctx } = createContext();
|
||||
const { ctx, setDistinctId, updateCommonProperties } = createContext();
|
||||
resolveProviderApiKeyMock.mockResolvedValue({ apiKey: "token" });
|
||||
getProviderSettingsMock.mockReturnValue({});
|
||||
executeClineAccountActionMock.mockResolvedValue({ id: "acct-1" });
|
||||
@@ -259,6 +372,47 @@ describe("cline_account keeps feature-flag identity in sync", () => {
|
||||
});
|
||||
|
||||
expect(await currentFlagsUserId()).toBeUndefined();
|
||||
expect(ctx.telemetryUser).toEqual(
|
||||
expect.objectContaining({
|
||||
accountId: null,
|
||||
distinctId: expect.any(String),
|
||||
}),
|
||||
);
|
||||
expect(setDistinctId).toHaveBeenLastCalledWith(
|
||||
ctx.telemetryUser?.distinctId,
|
||||
);
|
||||
expect(updateCommonProperties).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
user_id: undefined,
|
||||
account_id: undefined,
|
||||
organization_id: undefined,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("signs out of the shared cline entry and legacy secrets when cline-pass is disabled", async () => {
|
||||
const { ctx } = createContext();
|
||||
getProviderSettingsMock.mockReturnValue(undefined);
|
||||
saveProviderSettingsMock.mockImplementation(
|
||||
(_manager: unknown, request: { providerId: string }) => ({
|
||||
providerId: request.providerId,
|
||||
enabled: false,
|
||||
settingsPath: "/tmp/settings.json",
|
||||
}),
|
||||
);
|
||||
const { handleCommand } = await import("./commands");
|
||||
await handleCommand(ctx, "save_provider_settings", {
|
||||
provider: "cline-pass",
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
// Cline Pass stores its credentials under "cline", so both entries go,
|
||||
// and the legacy secrets are cleared for the storage provider.
|
||||
expect(saveProviderSettingsMock.mock.calls.map(([, r]) => r)).toEqual([
|
||||
expect.objectContaining({ providerId: "cline-pass", enabled: false }),
|
||||
{ providerId: "cline", enabled: false },
|
||||
]);
|
||||
expect(clearLegacyProviderCredentialsMock).toHaveBeenCalledWith("cline");
|
||||
});
|
||||
|
||||
it("ignores settings writes for other providers", async () => {
|
||||
|
||||
@@ -15,7 +15,8 @@ import type {
|
||||
import {
|
||||
addLocalProvider,
|
||||
ClineAccountService,
|
||||
captureAuthRefreshSoftFailure,
|
||||
type ClineAccountUser,
|
||||
clearAccountTelemetryIdentity,
|
||||
createConfiguredStreamingTranscriptionSession,
|
||||
createUserInstructionConfigService,
|
||||
ensureCustomProvidersLoaded,
|
||||
@@ -23,15 +24,17 @@ import {
|
||||
fetchClineRecommendedModels,
|
||||
getCoreBuiltinToolCatalog,
|
||||
getLocalProviderModels,
|
||||
getProviderAuthHandler,
|
||||
identifyAccount,
|
||||
listHookConfigFiles,
|
||||
listLocalProviders,
|
||||
normalizeOAuthProvider,
|
||||
ProviderSettingsManager,
|
||||
parseMcpServerRegistration,
|
||||
persistClineAccountTelemetryIdentity,
|
||||
probeMcpServerConnection,
|
||||
RuntimeOAuthTokenManager,
|
||||
readGlobalSettings,
|
||||
resolveLocalClineAuthToken,
|
||||
resolveClineAccountTelemetryIdentity,
|
||||
resolveMcpServerRegistration,
|
||||
resolveSessionBackend,
|
||||
resolveAgentConfigSearchPaths as resolveSharedAgentConfigSearchPaths,
|
||||
@@ -66,6 +69,8 @@ import { readFileSyncStrippingUtf8Bom } from "@cline/shared/node";
|
||||
import packageJson from "../package.json";
|
||||
import { CLINE_ACCOUNT_NOT_AUTHENTICATED_RESULT } from "../webview/lib/cline-account-state";
|
||||
import { MAX_RECORDED_AUDIO_BYTES } from "../webview/lib/voice-input-limits";
|
||||
import { resolveDesktopTelemetryUser } from "./client-context";
|
||||
import { resolveFreshClineAuthToken } from "./cline-auth";
|
||||
import {
|
||||
listClineGitHubRepositories,
|
||||
listClineIntegrations,
|
||||
@@ -86,6 +91,7 @@ import {
|
||||
identifyDesktopFeatureFlagsAccount,
|
||||
refreshDesktopFeatureFlags,
|
||||
} from "./feature-flags";
|
||||
import { clearLegacyProviderCredentials } from "./legacy-provider-credentials";
|
||||
import {
|
||||
installMarketplaceEntryForDesktopCommand,
|
||||
listMarketplaceInstalledEntries,
|
||||
@@ -115,6 +121,8 @@ import {
|
||||
sessionLogPath,
|
||||
sharedSessionDataDir,
|
||||
} from "./paths";
|
||||
import { getPullRequestStatus } from "./pull-request";
|
||||
import { capturePullRequestEvent } from "./pull-request-telemetry";
|
||||
import { listSessionAgents } from "./session-data/agents";
|
||||
import { readSessionHooks } from "./session-data/artifacts";
|
||||
import { normalizeSessionTitle } from "./session-data/common";
|
||||
@@ -303,21 +311,23 @@ function removePathIfExists(
|
||||
return true;
|
||||
}
|
||||
|
||||
// Cline access tokens expire between app launches, so account requests must
|
||||
// resolve through the refresh-aware OAuth manager instead of reading the
|
||||
// persisted token directly. A single shared instance keeps concurrent account
|
||||
// requests single-flight; the refresh token is single-use, so parallel
|
||||
// refreshes would invalidate each other.
|
||||
let clineOAuthTokenManager: RuntimeOAuthTokenManager | undefined;
|
||||
|
||||
function syncFeatureFlagsAccountFromResult(
|
||||
function syncAccountContextFromResult(
|
||||
ctx: SidecarContext,
|
||||
manager: ProviderSettingsManager,
|
||||
operation: string,
|
||||
result: unknown,
|
||||
): void {
|
||||
if (operation === "fetchMe") {
|
||||
const user = result as { id?: string; email?: string } | undefined;
|
||||
const user = result as ClineAccountUser | undefined;
|
||||
if (user?.id) {
|
||||
const identity = resolveClineAccountTelemetryIdentity(user);
|
||||
ctx.telemetryUser = resolveDesktopTelemetryUser({
|
||||
accountId: identity.id,
|
||||
email: identity.email,
|
||||
organizationId: identity.organizationId,
|
||||
});
|
||||
identifyAccount(ctx.telemetry, identity);
|
||||
persistClineAccountTelemetryIdentity(manager, identity);
|
||||
void identifyDesktopFeatureFlagsAccount(
|
||||
{ id: user.id, email: user.email },
|
||||
{ logger: ctx.logger, telemetry: ctx.telemetry },
|
||||
@@ -327,51 +337,41 @@ function syncFeatureFlagsAccountFromResult(
|
||||
}
|
||||
}
|
||||
|
||||
function syncFeatureFlagsAccountFromSettings(
|
||||
function syncAccountContextFromSettings(
|
||||
ctx: SidecarContext,
|
||||
manager: ProviderSettingsManager,
|
||||
): void {
|
||||
const auth = manager.getProviderSettings("cline")?.auth;
|
||||
const accountId = auth?.accountId?.trim();
|
||||
if (!auth || !accountId) {
|
||||
syncSignedOutAccountContext(ctx);
|
||||
return;
|
||||
}
|
||||
ctx.telemetryUser = resolveDesktopTelemetryUser({
|
||||
accountId,
|
||||
organizationId: auth.organizationId,
|
||||
});
|
||||
identifyAccount(ctx.telemetry, {
|
||||
id: accountId,
|
||||
provider: "cline",
|
||||
organizationId: auth.organizationId,
|
||||
organizationName: auth.organizationName,
|
||||
memberId: auth.memberId,
|
||||
});
|
||||
void identifyDesktopFeatureFlagsAccount(
|
||||
{ id: manager.getProviderSettings("cline")?.auth?.accountId },
|
||||
{ id: accountId },
|
||||
{ logger: ctx.logger, telemetry: ctx.telemetry },
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveFreshClineAuthToken(
|
||||
ctx: SidecarContext,
|
||||
manager: ProviderSettingsManager,
|
||||
): Promise<string | undefined> {
|
||||
let refreshError: Error | undefined;
|
||||
try {
|
||||
clineOAuthTokenManager ??= new RuntimeOAuthTokenManager();
|
||||
const resolution = await clineOAuthTokenManager.resolveProviderApiKey({
|
||||
providerId: "cline",
|
||||
});
|
||||
if (resolution?.apiKey) {
|
||||
return resolution.apiKey;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fall back to the persisted token; when one exists the account request
|
||||
// surfaces the auth failure to the caller.
|
||||
refreshError = error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
const persisted = resolveLocalClineAuthToken(
|
||||
manager.getProviderSettings("cline"),
|
||||
function syncSignedOutAccountContext(ctx: SidecarContext): void {
|
||||
const telemetryUser = resolveDesktopTelemetryUser();
|
||||
ctx.telemetryUser = telemetryUser;
|
||||
clearAccountTelemetryIdentity(ctx.telemetry, telemetryUser.distinctId);
|
||||
void identifyDesktopFeatureFlagsAccount(
|
||||
{},
|
||||
{ logger: ctx.logger, telemetry: ctx.telemetry },
|
||||
);
|
||||
// Never-signed-in resolves to undefined without a refresh attempt and is
|
||||
// silent. A refresh failure with no persisted fallback means credentials
|
||||
// existed but yielded nothing — that is the signal a real auth regression
|
||||
// would show up as, so report exactly one event for it.
|
||||
if (!persisted && refreshError) {
|
||||
ctx.logger?.error?.("Cline auth token refresh failed with no fallback", {
|
||||
error: refreshError,
|
||||
});
|
||||
captureAuthRefreshSoftFailure(ctx.telemetry, "cline", {
|
||||
errorName: refreshError.name,
|
||||
errorCode: "desktop_refresh_failed_no_fallback_token",
|
||||
});
|
||||
}
|
||||
return persisted;
|
||||
}
|
||||
|
||||
function mergePersistedSessionRecord(
|
||||
@@ -648,9 +648,13 @@ function toPositiveInt(value: unknown): number | undefined {
|
||||
return rounded > 0 ? rounded : undefined;
|
||||
}
|
||||
|
||||
function routineScheduleTiming(
|
||||
args?: Record<string, unknown>,
|
||||
): { cronPattern: string; metadata?: Record<string, number> } | undefined {
|
||||
function routineScheduleTiming(args?: Record<string, unknown>):
|
||||
| {
|
||||
cronPattern: string;
|
||||
timezone?: string;
|
||||
metadata?: Record<string, number>;
|
||||
}
|
||||
| undefined {
|
||||
if (args?.schedule_type === "once") {
|
||||
const runAt =
|
||||
typeof args.run_at === "number" ? args.run_at : Number(args?.run_at);
|
||||
@@ -662,7 +666,9 @@ function routineScheduleTiming(
|
||||
: undefined;
|
||||
}
|
||||
const cronPattern = asTrimmedString(args?.cron_pattern);
|
||||
return cronPattern ? { cronPattern } : undefined;
|
||||
return cronPattern
|
||||
? { cronPattern, timezone: asTrimmedString(args?.timezone) }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown): string | undefined {
|
||||
@@ -920,7 +926,7 @@ async function listHubSettings(
|
||||
async function toggleHubSetting(
|
||||
ctx: SidecarContext,
|
||||
input: {
|
||||
type: "plugins" | "tools";
|
||||
type: "plugins" | "tools" | "skills";
|
||||
path?: string;
|
||||
name?: string;
|
||||
enabled?: boolean;
|
||||
@@ -959,13 +965,18 @@ async function listUserInstructionConfigs(
|
||||
const items: unknown[] = [];
|
||||
for (const record of userInstructionService.listRecords(type)) {
|
||||
const item = record.item as unknown as JsonRecord;
|
||||
if (item.disabled === true) continue;
|
||||
const disabled = item.disabled === true;
|
||||
// Rules and workflows have no toggle UI, so keep hiding disabled
|
||||
// ones; skills need to stay visible (disabled) so they can be
|
||||
// re-enabled from the Skills tab.
|
||||
if (disabled && type !== "skill") continue;
|
||||
items.push({
|
||||
id: record.id,
|
||||
name: item.name ?? record.id,
|
||||
description: item.description,
|
||||
instructions: item.instructions,
|
||||
path: record.filePath,
|
||||
...(type === "skill" ? { enabled: !disabled } : {}),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
@@ -1825,16 +1836,13 @@ export async function handleCommand(
|
||||
// token up front and return a typed result the webview can act on
|
||||
// instead of letting the account service throw a generic error that
|
||||
// would be captured as error telemetry and shown raw to the user.
|
||||
const authToken = await resolveFreshClineAuthToken(ctx, manager);
|
||||
const authToken = await resolveFreshClineAuthToken(manager, ctx);
|
||||
if (!authToken) {
|
||||
// Backstop for credentials that go away without a settings write —
|
||||
// an expired or server-revoked token. Explicit sign-out is handled
|
||||
// at its source in `save_provider_settings`; this catches the rest
|
||||
// so a stale account never keeps serving its rollout cohort.
|
||||
void identifyDesktopFeatureFlagsAccount(
|
||||
{},
|
||||
{ logger: ctx.logger, telemetry: ctx.telemetry },
|
||||
);
|
||||
syncSignedOutAccountContext(ctx);
|
||||
return CLINE_ACCOUNT_NOT_AUTHENTICATED_RESULT;
|
||||
}
|
||||
const settings = manager.getProviderSettings("cline");
|
||||
@@ -1847,7 +1855,7 @@ export async function handleCommand(
|
||||
args as ClineAccountActionRequest,
|
||||
accountService,
|
||||
);
|
||||
syncFeatureFlagsAccountFromResult(ctx, operation, result);
|
||||
syncAccountContextFromResult(ctx, manager, operation, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1857,7 +1865,7 @@ export async function handleCommand(
|
||||
if (!operation) throw new Error("operation is required");
|
||||
const manager = new ProviderSettingsManager();
|
||||
|
||||
const authToken = await resolveFreshClineAuthToken(ctx, manager);
|
||||
const authToken = await resolveFreshClineAuthToken(manager, ctx);
|
||||
if (!authToken) {
|
||||
return CLINE_ACCOUNT_NOT_AUTHENTICATED_RESULT;
|
||||
}
|
||||
@@ -1890,9 +1898,13 @@ export async function handleCommand(
|
||||
}
|
||||
if (command === "list_provider_models") {
|
||||
const manager = new ProviderSettingsManager();
|
||||
const provider = String(args?.provider ?? "").trim();
|
||||
// Known models are merged in unfiltered after the provider's own model
|
||||
// rules run, so including them here would leak e.g. the full OpenAI
|
||||
// catalog into the ChatGPT Subscription (codex) picker.
|
||||
return await getLocalProviderModels(
|
||||
String(args?.provider ?? ""),
|
||||
manager.getProviderConfig(String(args?.provider ?? "").trim()),
|
||||
provider,
|
||||
manager.getProviderConfig(provider, { includeKnownModels: false }),
|
||||
);
|
||||
}
|
||||
if (command === "list_cline_recommended_models") {
|
||||
@@ -2045,12 +2057,30 @@ export async function handleCommand(
|
||||
apiKey: typeof args?.api_key === "string" ? args.api_key : undefined,
|
||||
baseUrl: typeof args?.base_url === "string" ? args.base_url : undefined,
|
||||
});
|
||||
if (!saved.enabled) {
|
||||
// Cline Pass keeps its credentials under "cline", so removing only
|
||||
// its own entry would leave the account signed in.
|
||||
const storageProviderId =
|
||||
getProviderAuthHandler(saved.providerId)?.storageProviderId ??
|
||||
saved.providerId;
|
||||
if (storageProviderId !== saved.providerId) {
|
||||
saveLocalProviderSettings(manager, {
|
||||
providerId: storageProviderId,
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
// Removing a providers.json entry lets the legacy import restore it
|
||||
// from the extension's secrets.json on the next command unless those
|
||||
// credentials go too. A failed write throws so the webview reports
|
||||
// the sign-out as failed and resyncs.
|
||||
clearLegacyProviderCredentials(storageProviderId);
|
||||
}
|
||||
// Sign-out is a `save_provider_settings` that blanks the cline auth block
|
||||
// (see signOut in webview settings/account-view.tsx), so this is the
|
||||
// authoritative signal — it fires the moment credentials are cleared
|
||||
// rather than waiting for the next account fetch.
|
||||
if (saved.providerId === "cline" || saved.providerId === "cline-pass") {
|
||||
syncFeatureFlagsAccountFromSettings(ctx, manager);
|
||||
syncAccountContextFromSettings(ctx, manager);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
@@ -2388,6 +2418,17 @@ export async function handleCommand(
|
||||
}
|
||||
|
||||
// ── Git operations ─────────────────────────────────────────────────
|
||||
if (command === "capture_pull_request_event") {
|
||||
capturePullRequestEvent(ctx.telemetry, args);
|
||||
return null;
|
||||
}
|
||||
if (command === "get_pull_request_status") {
|
||||
return await getPullRequestStatus(
|
||||
typeof args?.cwd === "string" && args.cwd.trim()
|
||||
? args.cwd.trim()
|
||||
: ctx.workspaceRoot,
|
||||
);
|
||||
}
|
||||
if (command === "get_git_branch") {
|
||||
const cwd =
|
||||
typeof args?.cwd === "string" && args.cwd.trim()
|
||||
@@ -2507,6 +2548,18 @@ export async function handleCommand(
|
||||
});
|
||||
return await listUserInstructionConfigs(ctx, snapshot);
|
||||
}
|
||||
if (command === "set_skill_disabled") {
|
||||
const skillPath = String(args?.path ?? "").trim();
|
||||
if (!skillPath) {
|
||||
throw new Error("skill path is required");
|
||||
}
|
||||
const snapshot = await toggleHubSetting(ctx, {
|
||||
type: "skills",
|
||||
path: skillPath,
|
||||
enabled: args?.disabled !== true,
|
||||
});
|
||||
return await listUserInstructionConfigs(ctx, snapshot);
|
||||
}
|
||||
|
||||
// ── Native OS commands ────────────────────────────────────────────
|
||||
if (command === "validate_workspace_directory") {
|
||||
|
||||
@@ -531,6 +531,65 @@ describe("Code sidecar runtime capabilities", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("does not announce a queued prompt start when the head is deleted from the queue", async () => {
|
||||
const { createSidecarContext, initializeSessionManager } = await import(
|
||||
"./context"
|
||||
);
|
||||
let onEvent: ((event: unknown) => void) | undefined;
|
||||
createCoreMock.mockResolvedValue({
|
||||
runtimeAddress: "ws://127.0.0.1:25463/hub",
|
||||
subscribe: vi.fn((handler: (event: unknown) => void) => {
|
||||
onEvent = handler;
|
||||
return () => {};
|
||||
}),
|
||||
dispose: vi.fn(),
|
||||
});
|
||||
|
||||
const ctx = createSidecarContext("/workspace/project");
|
||||
ctx.wsClients.add({ send: vi.fn() });
|
||||
await initializeSessionManager(ctx);
|
||||
ctx.liveSessions.set("session-1", {
|
||||
config: {},
|
||||
messages: [],
|
||||
promptsInQueue: [
|
||||
{ id: "prompt-1", prompt: "first", steer: false, attachmentCount: 0 },
|
||||
{ id: "prompt-2", prompt: "second", steer: false, attachmentCount: 0 },
|
||||
],
|
||||
busy: true,
|
||||
startedAt: Date.now(),
|
||||
status: "running",
|
||||
});
|
||||
|
||||
// Removing the head only produces a shrunken snapshot — no
|
||||
// pending_prompt_submitted — so nothing must reach the transcript.
|
||||
onEvent?.({
|
||||
type: "pending_prompts",
|
||||
payload: {
|
||||
sessionId: "session-1",
|
||||
prompts: [{ id: "prompt-2", prompt: "second", delivery: "queue" }],
|
||||
},
|
||||
});
|
||||
|
||||
const events = readEvents(ctx);
|
||||
expect(
|
||||
events.filter(
|
||||
(message) =>
|
||||
message.event.name === "chat_event" &&
|
||||
(message.event.payload as { stream?: string }).stream ===
|
||||
"chat_queued_prompt_start",
|
||||
),
|
||||
).toHaveLength(0);
|
||||
expect(
|
||||
events.find((message) => message.event.name === "prompts_in_queue_state")
|
||||
?.event.payload,
|
||||
).toEqual({
|
||||
sessionId: "session-1",
|
||||
items: [
|
||||
{ id: "prompt-2", prompt: "second", steer: false, attachmentCount: 0 },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("relays generated media for attach-only Hub sessions", async () => {
|
||||
const { createSidecarContext, handleHubLiveEvent } = await import(
|
||||
"./context"
|
||||
@@ -1271,3 +1330,215 @@ describe("disposeSidecarContext attachment cleanup", () => {
|
||||
expect(ctx.liveSessions.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Chat chunk pipe selection", () => {
|
||||
async function createStreamingContext(
|
||||
sessionId: string,
|
||||
coreSubscriptions: Set<string> = new Set(),
|
||||
) {
|
||||
const { createSidecarContext } = await import("./context");
|
||||
const ctx = createSidecarContext("/workspace/project");
|
||||
ctx.wsClients.add({ send: vi.fn() });
|
||||
ctx.liveSessions.set(sessionId, {
|
||||
config: {},
|
||||
messages: [],
|
||||
promptsInQueue: [],
|
||||
busy: true,
|
||||
startedAt: Date.now(),
|
||||
status: "running",
|
||||
attachedViaHub: true,
|
||||
});
|
||||
ctx.sessionManager = {
|
||||
hasSessionSubscription: (id: string) => coreSubscriptions.has(id),
|
||||
} as never;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function coreTextEvent(sessionId: string, text: string) {
|
||||
return {
|
||||
type: "agent_event",
|
||||
payload: {
|
||||
sessionId,
|
||||
event: { type: "content_start", contentType: "text", text },
|
||||
},
|
||||
} as never;
|
||||
}
|
||||
|
||||
function eventsFor(ctx: SidecarContext, name: string) {
|
||||
return readEvents(ctx)
|
||||
.filter((message) => message.event.name === name)
|
||||
.map((message) => message.event.payload);
|
||||
}
|
||||
|
||||
function chunksFor(ctx: SidecarContext, stream: string): string[] {
|
||||
return eventsFor(ctx, "chat_event")
|
||||
.filter((payload) => (payload as { stream?: string }).stream === stream)
|
||||
.map((payload) => String((payload as { chunk?: string }).chunk));
|
||||
}
|
||||
|
||||
it("emits one copy when both pipes carry the same delta", async () => {
|
||||
const { handleCoreSessionEvent, handleHubLiveEvent } = await import(
|
||||
"./context"
|
||||
);
|
||||
// Opening a session arms both pipes: ClineCore subscribes to the session
|
||||
// and `attach` enables the observer projection, so the hub publishes each
|
||||
// delta to both sockets.
|
||||
const ctx = await createStreamingContext(
|
||||
"session-1",
|
||||
new Set(["session-1"]),
|
||||
);
|
||||
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "Pack " },
|
||||
});
|
||||
handleCoreSessionEvent(ctx, coreTextEvent("session-1", "Pack "));
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "my box" },
|
||||
});
|
||||
handleCoreSessionEvent(ctx, coreTextEvent("session-1", "my box"));
|
||||
|
||||
expect(chunksFor(ctx, "chat_text")).toEqual(["Pack ", "my box"]);
|
||||
});
|
||||
|
||||
it("still streams sessions only the observer delivers", async () => {
|
||||
const { handleHubLiveEvent } = await import("./context");
|
||||
const ctx = await createStreamingContext("session-1");
|
||||
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "remote " },
|
||||
});
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "run" },
|
||||
});
|
||||
|
||||
expect(chunksFor(ctx, "chat_text")).toEqual(["remote ", "run"]);
|
||||
});
|
||||
|
||||
it("mutes the whole observer projection, not just text", async () => {
|
||||
const { handleHubLiveEvent } = await import("./context");
|
||||
const ctx = await createStreamingContext(
|
||||
"session-1",
|
||||
new Set(["session-1"]),
|
||||
);
|
||||
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "tool.started",
|
||||
sessionId: "session-1",
|
||||
payload: { toolCallId: "call-1", toolName: "run_commands" },
|
||||
});
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "run.completed",
|
||||
sessionId: "session-1",
|
||||
payload: {},
|
||||
});
|
||||
|
||||
expect(chunksFor(ctx, "chat_tool_call_start")).toEqual([]);
|
||||
expect(eventsFor(ctx, "chat_session_ended")).toEqual([]);
|
||||
expect(ctx.liveSessions.get("session-1")?.busy).toBe(true);
|
||||
});
|
||||
|
||||
it("follows the subscription as it comes and goes", async () => {
|
||||
const { handleHubLiveEvent } = await import("./context");
|
||||
const coreSubscriptions = new Set<string>();
|
||||
const ctx = await createStreamingContext("session-1", coreSubscriptions);
|
||||
const delta = (text: string) =>
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text },
|
||||
});
|
||||
|
||||
delta("observer first");
|
||||
// A send (or pending-prompt list) subscribes ClineCore.
|
||||
coreSubscriptions.add("session-1");
|
||||
delta("muted");
|
||||
// `stop` drops the subscription; a run another client starts on the
|
||||
// same session is the observer's to render again.
|
||||
coreSubscriptions.delete("session-1");
|
||||
delta("observer again");
|
||||
|
||||
expect(chunksFor(ctx, "chat_text")).toEqual([
|
||||
"observer first",
|
||||
"observer again",
|
||||
]);
|
||||
});
|
||||
|
||||
it("decides per session", async () => {
|
||||
const { handleHubLiveEvent } = await import("./context");
|
||||
const ctx = await createStreamingContext(
|
||||
"session-1",
|
||||
new Set(["session-1"]),
|
||||
);
|
||||
ctx.liveSessions.set("session-2", {
|
||||
config: {},
|
||||
messages: [],
|
||||
promptsInQueue: [],
|
||||
busy: true,
|
||||
startedAt: Date.now(),
|
||||
status: "running",
|
||||
attachedViaHub: true,
|
||||
});
|
||||
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "one" },
|
||||
});
|
||||
handleHubLiveEvent(ctx, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-2",
|
||||
payload: { text: "two" },
|
||||
});
|
||||
|
||||
expect(chunksFor(ctx, "chat_text")).toEqual(["two"]);
|
||||
});
|
||||
|
||||
it("never drops chunks the sidecar produces itself", async () => {
|
||||
const { broadcastChunk } = await import("./context");
|
||||
const ctx = await createStreamingContext(
|
||||
"session-1",
|
||||
new Set(["session-1"]),
|
||||
);
|
||||
|
||||
broadcastChunk(ctx, "session-1", "chat_queued_prompt_start", "{}");
|
||||
|
||||
expect(chunksFor(ctx, "chat_queued_prompt_start")).toEqual(["{}"]);
|
||||
});
|
||||
|
||||
it("stamps chunks with a stable per-process boot id", async () => {
|
||||
const { createSidecarContext, handleHubLiveEvent } = await import(
|
||||
"./context"
|
||||
);
|
||||
const first = await createStreamingContext("session-1");
|
||||
handleHubLiveEvent(first, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "a" },
|
||||
});
|
||||
handleHubLiveEvent(first, {
|
||||
event: "assistant.delta",
|
||||
sessionId: "session-1",
|
||||
payload: { text: "b" },
|
||||
});
|
||||
|
||||
const boots = readEvents(first)
|
||||
.filter((message) => message.event.name === "chat_event")
|
||||
.map((message) => (message.event.payload as { boot?: string }).boot);
|
||||
expect(boots).toHaveLength(2);
|
||||
expect(boots[0]).toBeTruthy();
|
||||
expect(boots[1]).toBe(boots[0]);
|
||||
|
||||
// A replacement sidecar restarts `index` at 1, so it must be
|
||||
// distinguishable by boot id.
|
||||
const second = createSidecarContext("/workspace/project");
|
||||
expect(second.bootId).not.toBe(first.bootId);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -187,6 +187,7 @@ function emitChunk(
|
||||
chunk,
|
||||
ts,
|
||||
index: nextIndex,
|
||||
boot: ctx.bootId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -344,6 +345,7 @@ function handleAgentEvent(
|
||||
message: event.message,
|
||||
noticeType: event.noticeType,
|
||||
reason: event.reason,
|
||||
metadata: event.metadata,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
@@ -367,6 +369,7 @@ function handleAgentEvent(
|
||||
break;
|
||||
}
|
||||
case "done": {
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Run ended");
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (session) {
|
||||
session.busy = false;
|
||||
@@ -401,7 +404,19 @@ function handleAgentEvent(
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "iteration_start":
|
||||
case "iteration_start": {
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (session) {
|
||||
// Iterations restart at one for each user run. Keep the previous
|
||||
// answer only within the run in which it was supplied.
|
||||
if (event.iteration === 1 || !session.mistakeRecovery) {
|
||||
session.mistakeRecovery = { latestIteration: event.iteration };
|
||||
} else {
|
||||
session.mistakeRecovery.latestIteration = event.iteration;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "iteration_end":
|
||||
break;
|
||||
}
|
||||
@@ -411,10 +426,8 @@ function handleAgentEvent(
|
||||
// CoreSessionEvent routing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The runtime's queue drain emits a pending_prompts snapshot (head removed)
|
||||
// and a pending_prompt_submitted event for the same prompt back-to-back, and
|
||||
// both are translated here into chat_queued_prompt_start — dedupe by prompt
|
||||
// id or the UI renders the user message twice.
|
||||
// Dedupe by prompt id so a repeated pending_prompt_submitted for the same
|
||||
// prompt cannot render the user message twice.
|
||||
function emitQueuedPromptStart(
|
||||
ctx: SidecarContext,
|
||||
sessionId: string,
|
||||
@@ -475,20 +488,10 @@ export function handleCoreSessionEvent(
|
||||
session,
|
||||
mapped.map((item) => item.id),
|
||||
);
|
||||
const previous = session.promptsInQueue;
|
||||
// A shrinking snapshot is not evidence that the head started
|
||||
// running: the user may have deleted it or the queue may have been
|
||||
// discarded. Only pending_prompt_submitted announces a start.
|
||||
session.promptsInQueue = mapped;
|
||||
if (
|
||||
previous.length > mapped.length &&
|
||||
previous[0] &&
|
||||
previous[0].id !== mapped[0]?.id
|
||||
) {
|
||||
emitQueuedPromptStart(ctx, sessionId, session, {
|
||||
promptId: previous[0].id,
|
||||
prompt: previous[0].prompt,
|
||||
attachmentCount: previous[0].attachmentCount ?? 0,
|
||||
userImages: previous[0].userImages,
|
||||
});
|
||||
}
|
||||
}
|
||||
sendPromptsInQueueSnapshot(ctx, sessionId);
|
||||
break;
|
||||
@@ -520,6 +523,7 @@ export function handleCoreSessionEvent(
|
||||
}
|
||||
case "ended": {
|
||||
const { sessionId, reason } = event.payload;
|
||||
cancelSidecarMistakeQuestions(ctx, sessionId, "Session ended");
|
||||
const session = ctx.liveSessions.get(sessionId);
|
||||
if (session) {
|
||||
session.busy = false;
|
||||
@@ -570,12 +574,14 @@ export function createSidecarContext(
|
||||
observability: {
|
||||
logger?: BasicLogger;
|
||||
telemetry?: ITelemetryService;
|
||||
telemetryUser?: SidecarContext["telemetryUser"];
|
||||
} = {},
|
||||
): SidecarContext {
|
||||
return {
|
||||
liveSessions: new Map(),
|
||||
restoringWorkspacePaths: new Set(),
|
||||
streamIndices: new Map(),
|
||||
bootId: randomUUID(),
|
||||
wsClients: new Set(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingQuestions: new Map(),
|
||||
@@ -584,6 +590,7 @@ export function createSidecarContext(
|
||||
workspaceRoot,
|
||||
logger: observability.logger,
|
||||
telemetry: observability.telemetry,
|
||||
telemetryUser: observability.telemetryUser,
|
||||
unsubscribeSessionEvents: null,
|
||||
hubBuildMismatch: null,
|
||||
};
|
||||
@@ -724,6 +731,28 @@ export function resolveSidecarAskQuestion(
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Remove prompts before their session is stopped or replaced in the UI. */
|
||||
export function cancelSidecarMistakeQuestions(
|
||||
ctx: SidecarContext,
|
||||
sessionId: string,
|
||||
reason: string,
|
||||
): void {
|
||||
for (const pending of ctx.pendingQuestions?.values() ?? []) {
|
||||
if (
|
||||
pending.item.sessionId !== sessionId ||
|
||||
pending.item.context?.agentId !== "desktop-mistake-limit"
|
||||
)
|
||||
continue;
|
||||
ctx.pendingQuestions.delete(pending.item.requestId);
|
||||
if (pending.timeoutId) clearTimeout(pending.timeoutId);
|
||||
pending.reject(new Error(reason));
|
||||
sendEvent(ctx, "ask_question_cancelled", {
|
||||
requestId: pending.item.requestId,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function createSidecarRuntimeCapabilities(
|
||||
ctx: SidecarContext,
|
||||
): RuntimeCapabilities {
|
||||
@@ -824,6 +853,15 @@ export function handleHubLiveEvent(
|
||||
if (!session?.attachedViaHub) {
|
||||
return;
|
||||
}
|
||||
// The observer client and ClineCore's own hub client are separate sockets
|
||||
// that both receive this session's events. This projection only exists for
|
||||
// sessions ClineCore is not subscribed to (it subscribes as a side effect
|
||||
// of start/send/pending_prompts and unsubscribes on stop); once it is,
|
||||
// `handleCoreSessionEvent` carries everything below and a second copy here
|
||||
// would double every delta, tool row, and status change.
|
||||
if (ctx.sessionManager?.hasSessionSubscription(sessionId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.event) {
|
||||
case "assistant.delta": {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
readDesktopSettings,
|
||||
resolveDesktopSettingsPath,
|
||||
setCloudSessionsEnabled,
|
||||
} from "./desktop-settings";
|
||||
|
||||
let dataDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dataDir = mkdtempSync(join(tmpdir(), "cline-desktop-settings-"));
|
||||
process.env.CLINE_DATA_DIR = dataDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.CLINE_DATA_DIR;
|
||||
rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("desktop settings", () => {
|
||||
it("defaults cloud sessions to off when no settings file exists", () => {
|
||||
expect(readDesktopSettings()).toEqual({ cloudSessionsEnabled: false });
|
||||
});
|
||||
|
||||
it("persists the cloud sessions opt-in and reads it back", () => {
|
||||
expect(setCloudSessionsEnabled(true)).toEqual({
|
||||
cloudSessionsEnabled: true,
|
||||
});
|
||||
expect(readDesktopSettings()).toEqual({ cloudSessionsEnabled: true });
|
||||
expect(resolveDesktopSettingsPath().endsWith("code-settings.json")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
JSON.parse(readFileSync(resolveDesktopSettingsPath(), "utf8")),
|
||||
).toMatchObject({ cloudSessionsEnabled: true });
|
||||
expect(setCloudSessionsEnabled(false)).toEqual({
|
||||
cloudSessionsEnabled: false,
|
||||
});
|
||||
expect(readDesktopSettings()).toEqual({ cloudSessionsEnabled: false });
|
||||
});
|
||||
|
||||
it("treats malformed files and non-boolean values as off", () => {
|
||||
mkdirSync(dirname(resolveDesktopSettingsPath()), { recursive: true });
|
||||
writeFileSync(resolveDesktopSettingsPath(), "{not json", "utf8");
|
||||
expect(readDesktopSettings()).toEqual({ cloudSessionsEnabled: false });
|
||||
writeFileSync(
|
||||
resolveDesktopSettingsPath(),
|
||||
JSON.stringify({ cloudSessionsEnabled: "yes" }),
|
||||
"utf8",
|
||||
);
|
||||
expect(readDesktopSettings()).toEqual({ cloudSessionsEnabled: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { resolveClineDataDir } from "@cline/shared/storage";
|
||||
|
||||
/** Desktop-only preferences kept separate from strict shared global settings. */
|
||||
export type DesktopSettings = {
|
||||
/** Opt-in gate for cloud sessions while the feature is in preview. */
|
||||
cloudSessionsEnabled: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_SETTINGS: DesktopSettings = {
|
||||
cloudSessionsEnabled: false,
|
||||
};
|
||||
|
||||
export function resolveDesktopSettingsPath(): string {
|
||||
return join(resolveClineDataDir(), "settings", "code-settings.json");
|
||||
}
|
||||
|
||||
export function readDesktopSettings(): DesktopSettings {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(resolveDesktopSettingsPath(), "utf8");
|
||||
} catch {
|
||||
return { ...DEFAULT_SETTINGS };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
||||
return {
|
||||
cloudSessionsEnabled: parsed.cloudSessionsEnabled === true,
|
||||
};
|
||||
} catch {
|
||||
return { ...DEFAULT_SETTINGS };
|
||||
}
|
||||
}
|
||||
|
||||
export function writeDesktopSettings(settings: DesktopSettings): void {
|
||||
const filePath = resolveDesktopSettingsPath();
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
// Avoid leaving torn settings if the process exits mid-write.
|
||||
const tempPath = `${filePath}.${process.pid}.tmp`;
|
||||
writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
||||
renameSync(tempPath, filePath);
|
||||
}
|
||||
|
||||
export function setCloudSessionsEnabled(enabled: boolean): DesktopSettings {
|
||||
const next = { ...readDesktopSettings(), cloudSessionsEnabled: enabled };
|
||||
writeDesktopSettings(next);
|
||||
return next;
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -18,6 +21,7 @@ const mocks = vi.hoisted(() => ({
|
||||
poll: vi.fn(async () => {}),
|
||||
dispose: vi.fn(async () => {}),
|
||||
setContext: vi.fn(),
|
||||
getBooleanFlagEnabled: vi.fn((_flag: unknown): boolean => false),
|
||||
getFlagPayload: vi.fn((_flag: unknown): unknown => undefined),
|
||||
}));
|
||||
|
||||
@@ -39,6 +43,7 @@ vi.mock("@cline/core", async () => {
|
||||
poll = mocks.poll;
|
||||
dispose = mocks.dispose;
|
||||
setContext = mocks.setContext;
|
||||
getBooleanFlagEnabled = mocks.getBooleanFlagEnabled;
|
||||
getFlagPayload = mocks.getFlagPayload;
|
||||
},
|
||||
};
|
||||
@@ -61,15 +66,26 @@ import {
|
||||
|
||||
const originalApiKey = process.env.TELEMETRY_SERVICE_API_KEY;
|
||||
const originalIsTest = process.env.IS_TEST;
|
||||
const originalDataDir = process.env.CLINE_DATA_DIR;
|
||||
let dataDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dataDir = mkdtempSync(join(tmpdir(), "cline-feature-flags-"));
|
||||
process.env.CLINE_DATA_DIR = dataDir;
|
||||
vi.clearAllMocks();
|
||||
mocks.getBooleanFlagEnabled.mockReset().mockReturnValue(false);
|
||||
resetDesktopFeatureFlagsForTesting();
|
||||
delete process.env.IS_TEST;
|
||||
delete process.env.E2E_TEST;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dataDir, { recursive: true, force: true });
|
||||
if (originalDataDir === undefined) {
|
||||
delete process.env.CLINE_DATA_DIR;
|
||||
} else {
|
||||
process.env.CLINE_DATA_DIR = originalDataDir;
|
||||
}
|
||||
if (originalApiKey === undefined) {
|
||||
delete process.env.TELEMETRY_SERVICE_API_KEY;
|
||||
} else {
|
||||
@@ -239,3 +255,53 @@ describe("disposeDesktopFeatureFlagsService", () => {
|
||||
expect(mocks.dispose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cloud agents gate", () => {
|
||||
beforeEach(() => {
|
||||
delete process.env.CLINE_CODE_CLOUD_AGENTS;
|
||||
});
|
||||
|
||||
it("is unavailable and disabled while the rollout flag is off", async () => {
|
||||
const { isCloudAgentsAvailable, isCloudAgentsEnabled } = await import(
|
||||
"./feature-flags"
|
||||
);
|
||||
expect(isCloudAgentsAvailable()).toBe(false);
|
||||
expect(isCloudAgentsEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it("does not enable a boolean rollout from a truthy variant payload", async () => {
|
||||
const { isCloudAgentsAvailable } = await import("./feature-flags");
|
||||
mocks.getFlagPayload.mockReturnValue("control");
|
||||
expect(isCloudAgentsAvailable()).toBe(false);
|
||||
expect(mocks.getBooleanFlagEnabled).toHaveBeenCalledWith(
|
||||
"code-cloud-agents",
|
||||
);
|
||||
});
|
||||
|
||||
it("needs both the rollout flag and the user's opt-in to enable", async () => {
|
||||
const { isCloudAgentsEnabled, isCloudAgentsAvailable } = await import(
|
||||
"./feature-flags"
|
||||
);
|
||||
const { setCloudSessionsEnabled } = await import("./desktop-settings");
|
||||
mocks.getBooleanFlagEnabled.mockImplementation(
|
||||
(flag: unknown) => flag === "code-cloud-agents",
|
||||
);
|
||||
expect(isCloudAgentsAvailable()).toBe(true);
|
||||
setCloudSessionsEnabled(false);
|
||||
expect(isCloudAgentsEnabled()).toBe(false);
|
||||
setCloudSessionsEnabled(true);
|
||||
expect(isCloudAgentsEnabled()).toBe(true);
|
||||
});
|
||||
|
||||
it("lets the env override force the gate in both directions", async () => {
|
||||
const { isCloudAgentsEnabled, isCloudAgentsAvailable } = await import(
|
||||
"./feature-flags"
|
||||
);
|
||||
mocks.getFlagPayload.mockReturnValue(undefined);
|
||||
process.env.CLINE_CODE_CLOUD_AGENTS = "1";
|
||||
expect(isCloudAgentsAvailable()).toBe(true);
|
||||
expect(isCloudAgentsEnabled()).toBe(true);
|
||||
process.env.CLINE_CODE_CLOUD_AGENTS = "0";
|
||||
expect(isCloudAgentsEnabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
buildClinePostHogClient,
|
||||
PostHogFeatureFlagsProvider,
|
||||
} from "@cline/core/services/feature-flags/posthog";
|
||||
import { FeatureFlag as SharedFeatureFlag } from "@cline/shared";
|
||||
import { resolveClineDataDir } from "@cline/shared/storage";
|
||||
import { readDesktopSettings } from "./desktop-settings";
|
||||
|
||||
const FEATURE_FLAG_CODE_CLOUD_AGENTS = SharedFeatureFlag.CODE_CLOUD_AGENTS;
|
||||
|
||||
const DESKTOP_FEATURE_FLAGS_CACHE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -169,3 +173,33 @@ export function resetDesktopFeatureFlagsForTesting(): void {
|
||||
desktopFeatureFlagsService = undefined;
|
||||
desktopFeatureFlagsContext = { clientName: "cline-code" };
|
||||
}
|
||||
|
||||
export function readCloudAgentsEnvOverride(): boolean | undefined {
|
||||
const override = process.env.CLINE_CODE_CLOUD_AGENTS?.trim().toLowerCase();
|
||||
if (override === "1" || override === "true") return true;
|
||||
if (override === "0" || override === "false") return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Whether the rollout makes cloud sessions available to this install. */
|
||||
export function isCloudAgentsAvailable(options?: {
|
||||
logger?: BasicLogger;
|
||||
telemetry?: ITelemetryService;
|
||||
}): boolean {
|
||||
const override = readCloudAgentsEnvOverride();
|
||||
if (override !== undefined) return override;
|
||||
return getDesktopFeatureFlagsService(options).getBooleanFlagEnabled(
|
||||
FEATURE_FLAG_CODE_CLOUD_AGENTS,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether cloud sessions are both available and enabled by the user. */
|
||||
export function isCloudAgentsEnabled(options?: {
|
||||
logger?: BasicLogger;
|
||||
telemetry?: ITelemetryService;
|
||||
}): boolean {
|
||||
const override = readCloudAgentsEnvOverride();
|
||||
if (override !== undefined) return override;
|
||||
if (!isCloudAgentsAvailable(options)) return false;
|
||||
return readDesktopSettings().cloudSessionsEnabled;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { clearLegacyProviderCredentials } from "./legacy-provider-credentials";
|
||||
|
||||
describe("clearLegacyProviderCredentials", () => {
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("removes only the Codex credentials from the legacy secrets file", () => {
|
||||
const dataDir = mkdtempSync(path.join(os.tmpdir(), "desktop-legacy-"));
|
||||
tempDirs.push(dataDir);
|
||||
const secretsPath = path.join(dataDir, "secrets.json");
|
||||
writeFileSync(
|
||||
secretsPath,
|
||||
JSON.stringify({
|
||||
"openai-codex-oauth-credentials": JSON.stringify({
|
||||
access_token: "a",
|
||||
refresh_token: "r",
|
||||
}),
|
||||
openRouterApiKey: "sk-or-keep",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(clearLegacyProviderCredentials("openai-codex", dataDir)).toBe(true);
|
||||
expect(JSON.parse(readFileSync(secretsPath, "utf8"))).toEqual({
|
||||
openRouterApiKey: "sk-or-keep",
|
||||
});
|
||||
});
|
||||
|
||||
it("removes both Cline account secrets from the legacy secrets file", () => {
|
||||
const dataDir = mkdtempSync(path.join(os.tmpdir(), "desktop-legacy-"));
|
||||
tempDirs.push(dataDir);
|
||||
const secretsPath = path.join(dataDir, "secrets.json");
|
||||
writeFileSync(
|
||||
secretsPath,
|
||||
JSON.stringify({
|
||||
"cline:clineAccountId": JSON.stringify({ idToken: "t" }),
|
||||
clineApiKey: "cline-key",
|
||||
openRouterApiKey: "sk-or-keep",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(clearLegacyProviderCredentials("cline", dataDir)).toBe(true);
|
||||
expect(JSON.parse(readFileSync(secretsPath, "utf8"))).toEqual({
|
||||
openRouterApiKey: "sk-or-keep",
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when the file is missing, has no matching credentials, or the provider is unknown", () => {
|
||||
const dataDir = mkdtempSync(path.join(os.tmpdir(), "desktop-legacy-"));
|
||||
tempDirs.push(dataDir);
|
||||
expect(clearLegacyProviderCredentials("openai-codex", dataDir)).toBe(false);
|
||||
|
||||
const secretsPath = path.join(dataDir, "secrets.json");
|
||||
writeFileSync(secretsPath, JSON.stringify({ apiKey: "keep" }));
|
||||
expect(clearLegacyProviderCredentials("cline", dataDir)).toBe(false);
|
||||
expect(clearLegacyProviderCredentials("anthropic", dataDir)).toBe(false);
|
||||
expect(readFileSync(secretsPath, "utf8")).toBe(
|
||||
JSON.stringify({ apiKey: "keep" }),
|
||||
);
|
||||
|
||||
writeFileSync(secretsPath, "{not json");
|
||||
expect(clearLegacyProviderCredentials("openai-codex", dataDir)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { resolveClineDataDir } from "@cline/shared/storage";
|
||||
|
||||
/**
|
||||
* Legacy VS Code extension secrets.json keys that the legacy import in
|
||||
* ProviderSettingsManager turns back into a providers.json entry.
|
||||
*/
|
||||
const LEGACY_SECRET_KEYS_BY_PROVIDER: Record<string, string[]> = {
|
||||
"openai-codex": ["openai-codex-oauth-credentials"],
|
||||
cline: ["cline:clineAccountId", "clineApiKey"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes a provider's credentials from the legacy VS Code extension's
|
||||
* secrets.json. The legacy import in ProviderSettingsManager runs on
|
||||
* construction and re-adds any provider missing from providers.json, so
|
||||
* leaving these credentials on disk would sign the user straight back in
|
||||
* after they sign out in the desktop app. Temporary until the legacy import
|
||||
* is retired.
|
||||
*
|
||||
* A missing or unparseable file is a no-op (the import ignores those too).
|
||||
* A failed write throws so the sign-out is reported as failed instead of
|
||||
* succeeding and then being undone by the next import.
|
||||
*/
|
||||
export function clearLegacyProviderCredentials(
|
||||
providerId: string,
|
||||
dataDir: string = resolveClineDataDir(),
|
||||
): boolean {
|
||||
const keys = LEGACY_SECRET_KEYS_BY_PROVIDER[providerId];
|
||||
const secretsPath = join(dataDir, "secrets.json");
|
||||
if (!keys || !existsSync(secretsPath)) {
|
||||
return false;
|
||||
}
|
||||
let secrets: unknown;
|
||||
try {
|
||||
secrets = JSON.parse(readFileSync(secretsPath, "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (!secrets || typeof secrets !== "object" || Array.isArray(secrets)) {
|
||||
return false;
|
||||
}
|
||||
const present = keys.filter((key) => key in secrets);
|
||||
if (present.length === 0) {
|
||||
return false;
|
||||
}
|
||||
for (const key of present) {
|
||||
delete (secrets as Record<string, unknown>)[key];
|
||||
}
|
||||
writeFileSync(secretsPath, `${JSON.stringify(secrets, null, 2)}\n`, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ function createContext(workspaceRoot: string): SidecarContext {
|
||||
liveSessions: new Map(),
|
||||
restoringWorkspacePaths: new Set(),
|
||||
streamIndices: new Map(),
|
||||
bootId: "test-boot",
|
||||
wsClients: new Set(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingQuestions: new Map(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { version } from "../package.json";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
captureExtensionActivated: vi.fn(),
|
||||
@@ -28,7 +29,14 @@ vi.mock("@cline/core", async () => {
|
||||
identifyAccount: mocks.identifyAccount,
|
||||
ProviderSettingsManager: class {
|
||||
getProviderSettings() {
|
||||
return { auth: { accountId: "account-1" } };
|
||||
return {
|
||||
auth: {
|
||||
accountId: "account-1",
|
||||
organizationId: "org-1",
|
||||
organizationName: "Acme",
|
||||
memberId: "member-1",
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
setSdkLogger: mocks.setSdkLogger,
|
||||
@@ -57,8 +65,10 @@ describe("desktop observability", () => {
|
||||
|
||||
expect(mocks.createClineTelemetryServiceConfig).toHaveBeenCalledWith({
|
||||
metadata: expect.objectContaining({
|
||||
extension_version: version,
|
||||
cline_type: "desktop",
|
||||
platform: "Cline",
|
||||
platform: "Cline Desktop",
|
||||
platform_version: version,
|
||||
}),
|
||||
});
|
||||
expect(mocks.createConfiguredTelemetryHandle).toHaveBeenCalledWith(
|
||||
@@ -67,9 +77,18 @@ describe("desktop observability", () => {
|
||||
expect(mocks.identifyAccount).toHaveBeenCalledWith(telemetry, {
|
||||
id: "account-1",
|
||||
provider: "cline",
|
||||
organizationId: "org-1",
|
||||
organizationName: "Acme",
|
||||
memberId: "member-1",
|
||||
});
|
||||
expect(mocks.captureExtensionActivated).toHaveBeenCalledWith(telemetry);
|
||||
expect(mocks.setSdkLogger).toHaveBeenCalledWith(logger);
|
||||
expect(observability.telemetryUser).toEqual({
|
||||
distinctId: "account-1",
|
||||
accountId: "account-1",
|
||||
email: undefined,
|
||||
organizationId: "org-1",
|
||||
});
|
||||
|
||||
await observability.dispose();
|
||||
await observability.dispose();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as os from "node:os";
|
||||
import {
|
||||
captureExtensionActivated,
|
||||
createClineTelemetryServiceConfig,
|
||||
@@ -8,7 +7,11 @@ import {
|
||||
ProviderSettingsManager,
|
||||
setSdkLogger,
|
||||
} from "@cline/core";
|
||||
import { version } from "../package.json";
|
||||
import type { UserContext } from "@cline/shared";
|
||||
import {
|
||||
DESKTOP_TELEMETRY_METADATA,
|
||||
resolveDesktopTelemetryUser,
|
||||
} from "./client-context";
|
||||
import { setDesktopFeatureFlagsAccountContext } from "./feature-flags";
|
||||
import {
|
||||
createDesktopLoggerAdapter,
|
||||
@@ -18,6 +21,7 @@ import {
|
||||
export interface DesktopObservability {
|
||||
readonly logger: DesktopLoggerAdapter["core"];
|
||||
readonly telemetry: ITelemetryService;
|
||||
readonly telemetryUser?: UserContext;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -28,23 +32,23 @@ export function createDesktopObservability(): DesktopObservability {
|
||||
|
||||
const telemetryHandle = createConfiguredTelemetryHandle({
|
||||
...createClineTelemetryServiceConfig({
|
||||
metadata: {
|
||||
extension_version: version,
|
||||
cline_type: "desktop",
|
||||
platform: "Cline",
|
||||
platform_version: process.version,
|
||||
os_type: os.platform(),
|
||||
os_version: os.version(),
|
||||
},
|
||||
metadata: DESKTOP_TELEMETRY_METADATA,
|
||||
}),
|
||||
logger,
|
||||
});
|
||||
const telemetry = telemetryHandle.telemetry;
|
||||
const auth = new ProviderSettingsManager().getProviderSettings("cline")?.auth;
|
||||
const telemetryUser = resolveDesktopTelemetryUser({
|
||||
accountId: auth?.accountId,
|
||||
organizationId: auth?.organizationId,
|
||||
});
|
||||
if (auth?.accountId) {
|
||||
identifyAccount(telemetry, {
|
||||
id: auth.accountId,
|
||||
provider: "cline",
|
||||
organizationId: auth.organizationId,
|
||||
organizationName: auth.organizationName,
|
||||
memberId: auth.memberId,
|
||||
});
|
||||
setDesktopFeatureFlagsAccountContext({ id: auth.accountId });
|
||||
}
|
||||
@@ -54,6 +58,7 @@ export function createDesktopObservability(): DesktopObservability {
|
||||
return {
|
||||
logger,
|
||||
telemetry,
|
||||
telemetryUser,
|
||||
async dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ITelemetryService } from "@cline/shared";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { capturePullRequestEvent } from "./pull-request-telemetry";
|
||||
|
||||
const event = {
|
||||
action: "open_clicked",
|
||||
prState: "open",
|
||||
ciState: "success",
|
||||
mergeTone: "success",
|
||||
};
|
||||
function service(enabled = true) {
|
||||
const capture = vi.fn();
|
||||
return {
|
||||
capture,
|
||||
telemetry: {
|
||||
capture,
|
||||
isEnabled: () => enabled,
|
||||
} as unknown as ITelemetryService,
|
||||
};
|
||||
}
|
||||
|
||||
it("captures only allowlisted status categories and strips identifiers", () => {
|
||||
const { capture, telemetry } = service();
|
||||
capturePullRequestEvent(telemetry, {
|
||||
...event,
|
||||
repository: "private/repo",
|
||||
cwd: "/private/path",
|
||||
url: "https://github.com/private/repo",
|
||||
title: "Secret",
|
||||
number: 42,
|
||||
});
|
||||
expect(capture).toHaveBeenCalledExactlyOnceWith({
|
||||
event: "desktop.pull_request.open_clicked",
|
||||
properties: {
|
||||
prState: "open",
|
||||
ciState: "success",
|
||||
mergeTone: "success",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...event, action: "arbitrary.event" },
|
||||
{ ...event, prState: "private/repo" },
|
||||
{ ...event, ciState: "test name" },
|
||||
{ ...event, mergeTone: "secret" },
|
||||
{},
|
||||
null,
|
||||
])("drops invalid payloads", (input) => {
|
||||
const { capture, telemetry } = service();
|
||||
capturePullRequestEvent(telemetry, input);
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("respects telemetry opt-out", () => {
|
||||
const { capture, telemetry } = service(false);
|
||||
capturePullRequestEvent(telemetry, event);
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
expect(() => capturePullRequestEvent(undefined, event)).not.toThrow();
|
||||
});
|
||||
|
||||
it("does not fail the command when the provider throws", () => {
|
||||
const { capture, telemetry } = service();
|
||||
capture.mockImplementation(() => {
|
||||
throw new Error("Telemetry unavailable");
|
||||
});
|
||||
expect(() => capturePullRequestEvent(telemetry, event)).not.toThrow();
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ITelemetryService } from "@cline/shared";
|
||||
import { pullRequestTelemetrySchema } from "../webview/lib/pull-request-telemetry-schema";
|
||||
|
||||
export function capturePullRequestEvent(
|
||||
telemetry: ITelemetryService | undefined,
|
||||
input: unknown,
|
||||
): void {
|
||||
const parsed = pullRequestTelemetrySchema.safeParse(input);
|
||||
if (!parsed.success) return;
|
||||
try {
|
||||
if (!telemetry?.isEnabled()) return;
|
||||
const { action, ...properties } = parsed.data;
|
||||
telemetry.capture({ event: `desktop.pull_request.${action}`, properties });
|
||||
} catch {
|
||||
// Product interactions must continue if the telemetry provider fails.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { getMergeStatus, summarizeChecks } from "../webview/lib/pull-request";
|
||||
import {
|
||||
createPullRequestStatusReader,
|
||||
GITHUB_AVAILABILITY_CACHE_MS,
|
||||
githubRepository,
|
||||
normalizeCheck,
|
||||
} from "./pull-request";
|
||||
|
||||
const pr = {
|
||||
number: 42,
|
||||
title: "Feature",
|
||||
url: "https://github.com/cline/cline/pull/42",
|
||||
state: "OPEN",
|
||||
isDraft: false,
|
||||
mergeable: "MERGEABLE",
|
||||
mergeStateStatus: "CLEAN",
|
||||
additions: 12,
|
||||
deletions: 3,
|
||||
headRepositoryOwner: { login: "cline" },
|
||||
headRepository: { name: "cline" },
|
||||
statusCheckRollup: [
|
||||
{
|
||||
__typename: "CheckRun",
|
||||
name: "Test",
|
||||
status: "COMPLETED",
|
||||
conclusion: "SUCCESS",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function runner(prs: unknown[] = [pr], branch = "feature/pr-ui") {
|
||||
return vi.fn(async (file: string, args: string[], _cwd: string) => {
|
||||
if (file === "git")
|
||||
return args[0] === "branch" ? branch : "git@github.com:cline/cline.git";
|
||||
if (args[0] === "pr" && args[1] === "view")
|
||||
return JSON.stringify(
|
||||
prs.find((item) => (item as typeof pr).number === Number(args[2])),
|
||||
);
|
||||
return JSON.stringify(
|
||||
args[0] === "repo" ? { defaultBranchRef: { name: "main" } } : prs,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
describe("pull request status", () => {
|
||||
it("reads the active workspace, filters same-named fork branches and prefers an open PR", async () => {
|
||||
const run = runner([
|
||||
{ ...pr, number: 99, headRepositoryOwner: { login: "someone" } },
|
||||
{ ...pr, number: 41, state: "MERGED" },
|
||||
pr,
|
||||
]);
|
||||
const result = await createPullRequestStatusReader({ run })("/worktree");
|
||||
expect(result?.pullRequest?.number).toBe(42);
|
||||
expect(result?.pullRequest?.checks[0].state).toBe("success");
|
||||
expect(result?.createUrl).toBe(
|
||||
"https://github.com/cline/cline/compare/main...feature%2Fpr-ui?expand=1",
|
||||
);
|
||||
expect(run.mock.calls.every((call) => call[2] === "/worktree")).toBe(true);
|
||||
expect(run.mock.calls.find((call) => call[1][0] === "pr")?.[1]).toContain(
|
||||
"feature/pr-ui",
|
||||
);
|
||||
});
|
||||
it("offers creation for a feature branch and hides it for the default branch", async () => {
|
||||
expect(
|
||||
(await createPullRequestStatusReader({ run: runner([]) })("/repo"))
|
||||
?.pullRequest,
|
||||
).toBeNull();
|
||||
expect(
|
||||
await createPullRequestStatusReader({ run: runner([], "main") })("/repo"),
|
||||
).toBeNull();
|
||||
});
|
||||
it("keeps merged and closed PR states", async () => {
|
||||
for (const state of ["MERGED", "CLOSED"] as const) {
|
||||
const result = await createPullRequestStatusReader({
|
||||
run: runner([{ ...pr, state }]),
|
||||
})("/repo");
|
||||
expect(result?.pullRequest?.state).toBe(state);
|
||||
}
|
||||
});
|
||||
it("does not invoke GitHub for detached HEAD or unsupported remotes", async () => {
|
||||
const detached = runner([], "");
|
||||
expect(
|
||||
await createPullRequestStatusReader({ run: detached })("/repo"),
|
||||
).toBeNull();
|
||||
expect(detached).toHaveBeenCalledTimes(1);
|
||||
const local = vi.fn(async () => "local");
|
||||
expect(
|
||||
await createPullRequestStatusReader({ run: local })("/repo"),
|
||||
).toBeNull();
|
||||
expect(local).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it.each([
|
||||
"ENOENT",
|
||||
1,
|
||||
4,
|
||||
])("hides unavailable GitHub CLI (%s), shares the cooldown, and recovers after login", async (code) => {
|
||||
let time = 0;
|
||||
let authenticated = false;
|
||||
const base = runner();
|
||||
const run = vi.fn(async (file: string, args: string[], cwd: string) => {
|
||||
if (file === "gh" && args[0] === "auth" && !authenticated)
|
||||
throw Object.assign(new Error("private stderr"), { code });
|
||||
return base(file, args, cwd);
|
||||
});
|
||||
const read = createPullRequestStatusReader({ run, now: () => time });
|
||||
expect(await read("/repo")).toBeNull();
|
||||
const attempts = run.mock.calls.length;
|
||||
authenticated = true;
|
||||
time = GITHUB_AVAILABILITY_CACHE_MS - 1;
|
||||
expect(await read("/other-workspace")).toBeNull();
|
||||
expect(run).toHaveBeenCalledTimes(attempts);
|
||||
time++;
|
||||
expect((await read("/repo"))?.pullRequest?.number).toBe(42);
|
||||
expect(run.mock.calls.filter((call) => call[1][0] === "auth")).toHaveLength(
|
||||
2,
|
||||
);
|
||||
});
|
||||
|
||||
it("shares an in-flight availability check across concurrent workspaces", async () => {
|
||||
let finish!: () => void;
|
||||
const waiting = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const base = runner();
|
||||
const run = vi.fn(async (file: string, args: string[], cwd: string) => {
|
||||
if (args[0] === "auth") await waiting;
|
||||
return base(file, args, cwd);
|
||||
});
|
||||
const read = createPullRequestStatusReader({ run });
|
||||
const first = read("/first");
|
||||
const second = read("/second");
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
run.mock.calls.filter((call) => call[1][0] === "auth"),
|
||||
).toHaveLength(1),
|
||||
);
|
||||
finish();
|
||||
await Promise.all([first, second]);
|
||||
expect(run.mock.calls.filter((call) => call[1][0] === "auth")).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("hides default-branch authentication failures before any repository query", async () => {
|
||||
const base = runner([], "main");
|
||||
const run = vi.fn(async (file: string, args: string[], cwd: string) => {
|
||||
if (file === "gh")
|
||||
throw Object.assign(new Error("Not logged in"), { code: 1 });
|
||||
return base(file, args, cwd);
|
||||
});
|
||||
expect(await createPullRequestStatusReader({ run })("/repo")).toBeNull();
|
||||
expect(
|
||||
run.mock.calls.filter((call) => call[0] === "gh").map((call) => call[1]),
|
||||
).toEqual([["auth", "status", "--active", "--hostname", "github.com"]]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ code: 4 },
|
||||
{ code: 1, stderr: "HTTP 401: Bad credentials" },
|
||||
])("invalidates cached availability if authentication expires during a lookup", async (failure) => {
|
||||
let expired = false;
|
||||
const base = runner();
|
||||
const run = vi.fn(async (file: string, args: string[], cwd: string) => {
|
||||
if (args[0] === "repo" && expired)
|
||||
throw Object.assign(new Error("Failed"), failure);
|
||||
return base(file, args, cwd);
|
||||
});
|
||||
const read = createPullRequestStatusReader({ run });
|
||||
expect((await read("/repo"))?.pullRequest?.number).toBe(42);
|
||||
expired = true;
|
||||
expect(await read("/repo")).toBeNull();
|
||||
const attempts = run.mock.calls.length;
|
||||
expect(await read("/other")).toBeNull();
|
||||
expect(run).toHaveBeenCalledTimes(attempts);
|
||||
});
|
||||
|
||||
it("preserves transient lookup errors after successful authentication", async () => {
|
||||
const base = runner();
|
||||
const run = async (file: string, args: string[], cwd: string) => {
|
||||
if (args[0] === "repo")
|
||||
throw Object.assign(new Error("private stderr"), {
|
||||
code: 1,
|
||||
stderr: "error connecting to api.github.com",
|
||||
});
|
||||
return base(file, args, cwd);
|
||||
};
|
||||
await expect(
|
||||
createPullRequestStatusReader({ run })("/repo"),
|
||||
).rejects.toThrow(
|
||||
"Could not load pull request status. Check your connection and try again.",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts GitHub SSH/HTTPS remotes only", () => {
|
||||
for (const remote of [
|
||||
"git@github.com:cline/cline.git",
|
||||
"https://github.com/cline/cline.git",
|
||||
"ssh://git@github.com/cline/cline",
|
||||
])
|
||||
expect(githubRepository(remote)).toBe("cline/cline");
|
||||
expect(
|
||||
githubRepository("https://github.com.evil.test/cline/cline"),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("check and merge states", () => {
|
||||
it("handles check runs, legacy statuses, skipped checks and unsafe links", () => {
|
||||
const pending = normalizeCheck({
|
||||
__typename: "CheckRun",
|
||||
status: "IN_PROGRESS",
|
||||
conclusion: "SUCCESS",
|
||||
});
|
||||
const failed = normalizeCheck({
|
||||
__typename: "StatusContext",
|
||||
state: "ERROR",
|
||||
context: "Build",
|
||||
targetUrl: "javascript:alert(1)",
|
||||
});
|
||||
const skipped = normalizeCheck({
|
||||
__typename: "CheckRun",
|
||||
status: "COMPLETED",
|
||||
conclusion: "SKIPPED",
|
||||
});
|
||||
expect(pending.state).toBe("pending");
|
||||
expect(failed).toEqual({ name: "Build", state: "failure", url: undefined });
|
||||
expect(summarizeChecks([pending, failed])).toBe("failure");
|
||||
expect(summarizeChecks([skipped])).toBe("skipped");
|
||||
expect(summarizeChecks([])).toBe("none");
|
||||
});
|
||||
it("never calls an unknown, draft or blocked PR ready to merge", async () => {
|
||||
const result = await createPullRequestStatusReader({ run: runner() })(
|
||||
"/repo",
|
||||
);
|
||||
const value = result!.pullRequest!;
|
||||
expect(
|
||||
getMergeStatus({ ...value, mergeStateStatus: "BLOCKED" }).label,
|
||||
).toBe("Blocked");
|
||||
expect(getMergeStatus({ ...value, isDraft: true }).label).toBe("Draft");
|
||||
expect(
|
||||
getMergeStatus({
|
||||
...value,
|
||||
mergeable: "UNKNOWN",
|
||||
mergeStateStatus: "UNKNOWN",
|
||||
}).label,
|
||||
).toBe("Merge status pending");
|
||||
expect(getMergeStatus({ ...value, mergeable: "CONFLICTING" }).label).toBe(
|
||||
"Conflicts",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import type {
|
||||
PullRequestCheck,
|
||||
PullRequestStatus,
|
||||
} from "../webview/lib/pull-request";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
type RunCommand = (
|
||||
file: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
) => Promise<string>;
|
||||
const runCommand: RunCommand = async (file, args, cwd) => {
|
||||
const { stdout } = await execFileAsync(file, args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
timeout: 15_000,
|
||||
maxBuffer: 2 * 1024 * 1024,
|
||||
env: { ...process.env, GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0" },
|
||||
});
|
||||
return stdout.trim();
|
||||
};
|
||||
|
||||
type GitHubCheck = {
|
||||
__typename: string;
|
||||
name?: string;
|
||||
context?: string;
|
||||
status?: string;
|
||||
conclusion?: string;
|
||||
state?: string;
|
||||
detailsUrl?: string;
|
||||
targetUrl?: string;
|
||||
};
|
||||
|
||||
export function normalizeCheck(check: GitHubCheck): PullRequestCheck {
|
||||
const result =
|
||||
check.__typename === "CheckRun"
|
||||
? check.status === "COMPLETED"
|
||||
? check.conclusion
|
||||
: "PENDING"
|
||||
: check.state;
|
||||
return {
|
||||
name: check.name || check.context || "Check",
|
||||
state:
|
||||
result === "SUCCESS"
|
||||
? "success"
|
||||
: result === "NEUTRAL" || result === "SKIPPED"
|
||||
? "skipped"
|
||||
: [
|
||||
"FAILURE",
|
||||
"ERROR",
|
||||
"CANCELLED",
|
||||
"TIMED_OUT",
|
||||
"ACTION_REQUIRED",
|
||||
"STALE",
|
||||
"STARTUP_FAILURE",
|
||||
].includes(result ?? "")
|
||||
? "failure"
|
||||
: "pending",
|
||||
url: safeHttpUrl(check.detailsUrl || check.targetUrl),
|
||||
};
|
||||
}
|
||||
|
||||
function safeHttpUrl(value?: string): string | undefined {
|
||||
if (!value) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return ["https:", "http:"].includes(url.protocol) ? url.href : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function githubRepository(remote: string): string | null {
|
||||
const match = remote.match(
|
||||
/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+?)\/?$/,
|
||||
);
|
||||
return match ? `${match[1]}/${match[2].replace(/\.git$/, "")}` : null;
|
||||
}
|
||||
|
||||
type GitHubPullRequest = Omit<
|
||||
NonNullable<PullRequestStatus["pullRequest"]>,
|
||||
"checks"
|
||||
> & {
|
||||
headRepositoryOwner: { login: string } | null;
|
||||
headRepository: { name: string } | null;
|
||||
statusCheckRollup: GitHubCheck[] | null;
|
||||
};
|
||||
|
||||
// Shared across workspaces: missing credentials are a machine-level capability,
|
||||
// not a repository failure. Retry after installation/login without polling gh.
|
||||
export const GITHUB_AVAILABILITY_CACHE_MS = 5 * 60_000;
|
||||
|
||||
function commandErrorCode(error: unknown): unknown {
|
||||
return error && typeof error === "object" && "code" in error
|
||||
? error.code
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function isAuthenticationFailure(error: unknown): boolean {
|
||||
if (commandErrorCode(error) === 4) return true;
|
||||
const stderr =
|
||||
error && typeof error === "object" && "stderr" in error
|
||||
? String(error.stderr)
|
||||
: "";
|
||||
return /HTTP 401|Bad credentials/i.test(stderr);
|
||||
}
|
||||
|
||||
export function createPullRequestStatusReader({
|
||||
run = runCommand,
|
||||
now = Date.now,
|
||||
}: {
|
||||
run?: RunCommand;
|
||||
now?: () => number;
|
||||
} = {}) {
|
||||
let available: boolean | undefined;
|
||||
let expiresAt = 0;
|
||||
let probe: Promise<boolean> | undefined;
|
||||
|
||||
function markUnavailable() {
|
||||
available = false;
|
||||
expiresAt = now() + GITHUB_AVAILABILITY_CACHE_MS;
|
||||
}
|
||||
|
||||
async function isAvailable(cwd: string): Promise<boolean> {
|
||||
if (available !== undefined && now() < expiresAt) return available;
|
||||
if (probe) return probe;
|
||||
probe = (async () => {
|
||||
try {
|
||||
await run(
|
||||
"gh",
|
||||
["auth", "status", "--active", "--hostname", "github.com"],
|
||||
cwd,
|
||||
);
|
||||
available = true;
|
||||
expiresAt = now() + GITHUB_AVAILABILITY_CACHE_MS;
|
||||
return true;
|
||||
} catch (error) {
|
||||
// gh auth status documents exit 1 for missing/invalid authentication.
|
||||
const code = commandErrorCode(error);
|
||||
if (code === "ENOENT" || code === 1 || code === 4) {
|
||||
markUnavailable();
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
try {
|
||||
return await probe;
|
||||
} finally {
|
||||
probe = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read-only: creation is reviewed and submitted in GitHub's compare form. */
|
||||
return async function readPullRequestStatus(
|
||||
cwd: string,
|
||||
): Promise<PullRequestStatus | null> {
|
||||
if (available === false && now() < expiresAt) return null;
|
||||
const branch = await run("git", ["branch", "--show-current"], cwd).catch(
|
||||
() => "",
|
||||
);
|
||||
if (!branch) return null;
|
||||
const remote = await run("git", ["remote", "get-url", "origin"], cwd).catch(
|
||||
() => "",
|
||||
);
|
||||
const repository = githubRepository(remote);
|
||||
if (!repository) return null;
|
||||
try {
|
||||
if (!(await isAvailable(cwd))) return null;
|
||||
const repo = JSON.parse(
|
||||
await run(
|
||||
"gh",
|
||||
["repo", "view", repository, "--json", "defaultBranchRef"],
|
||||
cwd,
|
||||
),
|
||||
) as { defaultBranchRef: { name: string } | null };
|
||||
const base = repo.defaultBranchRef?.name;
|
||||
// The default branch can have years-old PRs from earlier branch workflows.
|
||||
// Those do not describe the current work, and it is not a PR source branch.
|
||||
if (branch === base) return null;
|
||||
const prsJson = await run(
|
||||
"gh",
|
||||
[
|
||||
"pr",
|
||||
"list",
|
||||
"--repo",
|
||||
repository,
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"100",
|
||||
"--json",
|
||||
"number,state,headRepositoryOwner,headRepository",
|
||||
],
|
||||
cwd,
|
||||
);
|
||||
const [owner, name] = repository.split("/");
|
||||
const candidates = (
|
||||
JSON.parse(prsJson) as Pick<
|
||||
GitHubPullRequest,
|
||||
"number" | "state" | "headRepositoryOwner" | "headRepository"
|
||||
>[]
|
||||
).filter(
|
||||
(pr) =>
|
||||
pr.headRepositoryOwner?.login.toLowerCase() === owner.toLowerCase() &&
|
||||
pr.headRepository?.name.toLowerCase() === name.toLowerCase(),
|
||||
);
|
||||
const candidate =
|
||||
candidates.find((pr) => pr.state === "OPEN") ?? candidates[0];
|
||||
const pr = candidate
|
||||
? (JSON.parse(
|
||||
await run(
|
||||
"gh",
|
||||
[
|
||||
"pr",
|
||||
"view",
|
||||
String(candidate.number),
|
||||
"--repo",
|
||||
repository,
|
||||
"--json",
|
||||
"number,title,url,state,isDraft,mergeable,mergeStateStatus,additions,deletions,statusCheckRollup",
|
||||
],
|
||||
cwd,
|
||||
),
|
||||
) as GitHubPullRequest)
|
||||
: null;
|
||||
return {
|
||||
repository,
|
||||
branch,
|
||||
createUrl:
|
||||
base && branch !== base
|
||||
? `https://github.com/${repository}/compare/${encodeURIComponent(base)}...${encodeURIComponent(branch)}?expand=1`
|
||||
: null,
|
||||
pullRequest: pr
|
||||
? {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
state: pr.state,
|
||||
isDraft: pr.isDraft,
|
||||
mergeable: pr.mergeable,
|
||||
mergeStateStatus: pr.mergeStateStatus,
|
||||
additions: pr.additions,
|
||||
deletions: pr.deletions,
|
||||
checks: (pr.statusCheckRollup ?? []).map(normalizeCheck),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
} catch (error) {
|
||||
// Authentication can expire while a positive availability result is cached.
|
||||
if (
|
||||
commandErrorCode(error) === "ENOENT" ||
|
||||
isAuthenticationFailure(error)
|
||||
) {
|
||||
markUnavailable();
|
||||
return null;
|
||||
}
|
||||
throw new Error(
|
||||
"Could not load pull request status. Check your connection and try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const getPullRequestStatus = createPullRequestStatusReader();
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
ToolApprovalResult,
|
||||
} from "@cline/core";
|
||||
import type { MessageWithMetadata } from "@cline/llms";
|
||||
import type { UserContext } from "@cline/shared";
|
||||
|
||||
export type JsonRecord = Record<string, unknown>;
|
||||
|
||||
@@ -60,6 +61,11 @@ export type LiveSession = {
|
||||
prompt?: string;
|
||||
title?: string;
|
||||
attachedViaHub?: boolean;
|
||||
/** Iterations already in flight when the user supplied recovery guidance. */
|
||||
mistakeRecovery?: {
|
||||
latestIteration: number;
|
||||
continuedThroughIteration?: number;
|
||||
};
|
||||
/** Materialized attachment files for prompts still waiting in the queue. */
|
||||
queuedAttachmentFiles?: Map<string, string[]>;
|
||||
/** Last prompt id announced via chat_queued_prompt_start, to dedupe emits. */
|
||||
@@ -115,6 +121,12 @@ export type SidecarContext = {
|
||||
liveSessions: Map<string, LiveSession>;
|
||||
restoringWorkspacePaths: Set<string>;
|
||||
streamIndices: Map<string, number>;
|
||||
/**
|
||||
* Identifies this sidecar process. `streamIndices` restarts whenever the
|
||||
* sidecar does, so the webview needs to tell "index 1 of a new process"
|
||||
* apart from a replay of the run it already rendered.
|
||||
*/
|
||||
bootId: string;
|
||||
wsClients: Set<SidecarWebSocketClient>;
|
||||
pendingApprovals: Map<string, PendingToolApproval>;
|
||||
pendingQuestions: Map<string, PendingAskQuestion>;
|
||||
@@ -123,6 +135,8 @@ export type SidecarContext = {
|
||||
workspaceRoot: string;
|
||||
logger?: BasicLogger;
|
||||
telemetry?: ITelemetryService;
|
||||
/** Analytics identity and explicit account state forwarded with each session. */
|
||||
telemetryUser?: UserContext;
|
||||
unsubscribeSessionEvents: (() => void) | null;
|
||||
/**
|
||||
* Latest managed Hub build mismatch, broadcast as `hub_build_mismatch` and
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"notification:default"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user