Compare commits

..
Author SHA1 Message Date
Ryan Vogel 705c3ab746 feat(core): let agents create recurring and one-shot schedules
Adds schedule_create, schedule_list and schedule_cancel tools in the
opencode namespace so the agent can schedule prompts back into its own
session. schedule_create accepts `every` (30s/15m/2h/1d), `at` (ISO 8601
with offset) for a single run, or both (`at` sets the first run).

SessionSchedule now stores multiple schedules per session, keyed by a
new `sch_` ID, and persists the absolute next fire time instead of only
the interval. This replaces the one-schedule-per-session model and fixes
restarts resetting the countdown: one-shots fire at their original time
after a restart, and overdue recurring schedules fire once then resume
their cadence rather than bursting. `/schedule off` now cancels every
schedule in the session. Past `at` times, missing timing and invalid
intervals return tool errors.

Verified with an isolated managed-mode server and a scripted
OpenAI-compatible mock model driving `execute`: create every 5s fired
every 5s; `at` fired at 15:55:42.013 for a 15:55:42 target; a one-shot
created before a restart fired on time after it (15:56:23.013); list
returned both schedules with server time; cancel stopped firing; invalid
inputs returned the three expected errors. core and server typecheck.
2026-09-29 11:57:09 -04:00
Ryan Vogel e9f17d5ebe chore(core): format session schedule service
Prettier wrapped the long catchCause line; no behavior change.
2026-09-29 11:51:17 -04:00
Ryan Vogel a5ceab882e feat(core): run session schedules as global background jobs
Moves schedule timers out of the per-Location plugin into a new global
SessionSchedule service. Previously timers lived in the Location's plugin
scope, so they stopped on server restart until something reloaded the
Location, and stopped whenever the Location was evicted after 60 minutes
of inactivity. Timers now live in the global service and call
Session.prompt, which loads the Location on demand, so schedules fire
even when the session is not open.

- SessionSchedule persists entries in KV (session.schedule/<id>) and
  exposes set/remove/resume. A deleted session ends its schedule.
- The managed server calls resume at boot next to restart continuity;
  unmanaged servers sharing the database do not restore schedules.
- The opencode.schedule plugin now only registers /schedule and
  delegates to the service; the per-Location restore logic is removed.

Verified: core and server typecheck; against an isolated managed-mode
server, a 5s schedule fired every 5s, resumed after a restart with no
client touching the session, and `/schedule off` stopped the
boot-restored timer. Server tests: 3 OpenAI OAuth port tests fail
identically without this change.
2026-09-29 11:43:20 -04:00
Ryan Vogel e0709f8de0 feat(core): add /schedule command for recurring session prompts
Adds a minimal built-in plugin (opencode.schedule) that registers
`/schedule <30s|15m|2h> <prompt>` and `/schedule off`. Each schedule is
saved in plugin storage keyed by session ID and re-queues the prompt with
delivery "queue" on a fixed interval, modeled on the warming plugin loop.
When a location loads, the plugin restarts only schedules whose session
belongs to that location, so a session is never double-scheduled.

Known gaps (prototype): schedules resume after a server restart only once
something loads the session's location, and intervals longer than the
60-minute location inactivity TTL stop when the location is evicted.

Verified: core typecheck passes; against an isolated `serve` instance, a
5s schedule admitted prompts every 5s, stopped across a restart, and
resumed after the session's location was reloaded by a manual prompt.
2026-09-29 11:35:53 -04:00
188 changed files with 1008 additions and 6616 deletions
+1 -1
View File
@@ -662,7 +662,7 @@ jobs:
needs:
- version
- publish
if: ${{ !cancelled() && github.repository == 'anomalyco/opencode' && github.ref_name == 'v2' && needs.version.outputs.release && needs.publish.result == 'success' }}
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'v2' && needs.version.outputs.release && needs.publish.result == 'success'
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
# Unlike dev, V2 publishes a tag rather than a GitHub Release event.
+52 -51
View File
@@ -32,7 +32,7 @@
},
"packages/ai": {
"name": "@opencode/ai",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@aws-sdk/credential-providers": "3.1057.0",
"@opencode/schema": "workspace:*",
@@ -54,7 +54,7 @@
},
"packages/app": {
"name": "@opencode/app",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@corvu/drawer": "catalog:",
"@dnd-kit/abstract": "0.5.0",
@@ -112,7 +112,7 @@
},
"packages/cli": {
"name": "@opencode/cli",
"version": "2.0.20",
"version": "2.0.19",
"bin": {
"opencode": "./bin/opencode.cjs",
"opencode2": "./bin/opencode2.cjs",
@@ -178,7 +178,7 @@
},
"packages/client": {
"name": "@opencode/client",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/protocol": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -204,7 +204,7 @@
},
"packages/codemode": {
"name": "@opencode/codemode",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"acorn": "8.15.0",
"effect": "catalog:",
@@ -217,7 +217,7 @@
},
"packages/console/app": {
"name": "@opencode/console-app",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@cloudflare/vite-plugin": "1.15.2",
"@ibm/plex": "6.4.1",
@@ -253,7 +253,7 @@
},
"packages/console/core": {
"name": "@opencode/console-core",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@aws-sdk/client-sts": "3.782.0",
"@jsx-email/render": "1.1.1",
@@ -280,7 +280,7 @@
},
"packages/console/function": {
"name": "@opencode/console-function",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@openauthjs/openauth": "0.0.0-20250322224806",
"@opencode/console-core": "workspace:*",
@@ -297,7 +297,7 @@
},
"packages/console/mail": {
"name": "@opencode/console-mail",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@jsx-email/all": "2.2.3",
"@jsx-email/cli": "1.4.3",
@@ -321,7 +321,7 @@
},
"packages/console/support": {
"name": "@opencode/console-support",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@cloudflare/vite-plugin": "1.15.2",
"@opencode/console-core": "workspace:*",
@@ -341,7 +341,7 @@
},
"packages/core": {
"name": "@opencode/core",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@ai-sdk/cohere": "3.0.27",
"@ai-sdk/gateway": "3.0.104",
@@ -377,7 +377,6 @@
"https-proxy-agent": "7.0.6",
"ignore": "7.0.5",
"immer": "11.1.4",
"jose": "6.0.11",
"jsonc-parser": "3.3.1",
"mime-types": "3.0.2",
"tree-sitter-bash": "0.25.0",
@@ -410,7 +409,7 @@
},
"packages/desktop": {
"name": "@opencode/desktop",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@zip.js/zip.js": "2.7.62",
"electron-context-menu": "5.0.0",
@@ -459,7 +458,7 @@
},
"packages/enterprise": {
"name": "@opencode/enterprise",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@hono/standard-validator": "catalog:",
"@opencode-ai/sdk": "1.18.21",
@@ -496,7 +495,7 @@
},
"packages/function": {
"name": "@opencode/function",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@octokit/auth-app": "8.0.1",
"@octokit/rest": "catalog:",
@@ -512,7 +511,7 @@
},
"packages/http-recorder": {
"name": "@opencode/http-recorder",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@effect/platform-node-shared": "4.0.0-rc.112",
},
@@ -531,7 +530,7 @@
},
"packages/httpapi-codegen": {
"name": "@opencode/httpapi-codegen",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"effect": "catalog:",
"prettier": "3.6.2",
@@ -544,7 +543,7 @@
},
"packages/latex": {
"name": "@opencode/latex",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -558,7 +557,7 @@
},
"packages/merman": {
"name": "@opencode/merman",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -573,7 +572,7 @@
},
"packages/plugin": {
"name": "@opencode/plugin",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode/ai": "workspace:*",
@@ -599,8 +598,8 @@
},
"peerDependencies": {
"@opencode/theme": "workspace:*",
"@opentui/core": ">=0.5.13",
"@opentui/solid": ">=0.5.13",
"@opentui/core": ">=0.5.12",
"@opentui/solid": ">=0.5.12",
"solid-js": ">=1.9.0",
},
"optionalPeers": [
@@ -612,7 +611,7 @@
},
"packages/plugin-browser": {
"name": "@opencode/plugin-browser",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -642,7 +641,7 @@
},
"packages/protocol": {
"name": "@opencode/protocol",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/schema": "workspace:*",
"effect": "catalog:",
@@ -657,7 +656,7 @@
},
"packages/schema": {
"name": "@opencode/schema",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@standard-schema/spec": "catalog:",
"effect": "catalog:",
@@ -681,7 +680,7 @@
},
"packages/sdk": {
"name": "@opencode/sdk",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -702,7 +701,7 @@
},
"packages/server": {
"name": "@opencode/server",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
@@ -724,7 +723,7 @@
},
"packages/session-ui": {
"name": "@opencode/session-ui",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
@@ -759,7 +758,7 @@
},
"packages/simulation": {
"name": "@opencode/simulation",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/ai": "workspace:*",
"@opencode/core": "workspace:*",
@@ -779,7 +778,7 @@
},
"packages/stats/app": {
"name": "@opencode/stats-app",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@ibm/plex": "6.4.1",
"@kobalte/core": "catalog:",
@@ -813,7 +812,7 @@
},
"packages/stats/core": {
"name": "@opencode/stats-core",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@aws-sdk/client-athena": "3.933.0",
"@planetscale/database": "1.19.0",
@@ -832,7 +831,7 @@
},
"packages/stats/server": {
"name": "@opencode/stats-server",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@aws-sdk/client-firehose": "3.933.0",
"@effect/platform-node": "catalog:",
@@ -878,7 +877,7 @@
},
"packages/theme": {
"name": "@opencode/theme",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opentui/core": "catalog:",
"effect": "catalog:",
@@ -892,7 +891,7 @@
},
"packages/tui": {
"name": "@opencode/tui",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -926,7 +925,7 @@
},
"packages/ui": {
"name": "@opencode/ui",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@kobalte/core": "catalog:",
"@pierre/diffs": "catalog:",
@@ -961,7 +960,7 @@
},
"packages/util": {
"name": "@opencode/util",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@effect/opentelemetry": "catalog:",
"@effect/platform-node": "catalog:",
@@ -999,7 +998,7 @@
},
"packages/web": {
"name": "@opencode/web",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@astrojs/cloudflare": "12.6.3",
"@astrojs/markdown-remark": "6.3.1",
@@ -1040,7 +1039,7 @@
},
"services/update": {
"name": "@opencode/update",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"jose": "6.0.11",
"semver": "catalog:",
@@ -1117,9 +1116,9 @@
"@npmcli/arborist": "9.4.0",
"@octokit/rest": "22.0.0",
"@openauthjs/openauth": "0.0.0-20250322224806",
"@opentui/core": "0.5.13",
"@opentui/keymap": "0.5.13",
"@opentui/solid": "0.5.13",
"@opentui/core": "0.5.12",
"@opentui/keymap": "0.5.12",
"@opentui/solid": "0.5.12",
"@pierre/diffs": "1.5.1",
"@playwright/test": "1.59.1",
"@sentry/solid": "10.71.0",
@@ -2255,25 +2254,27 @@
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
"@opentui/core": ["@opentui/core@0.5.13", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.13", "@opentui/core-darwin-x64": "0.5.13", "@opentui/core-linux-arm64": "0.5.13", "@opentui/core-linux-arm64-musl": "0.5.13", "@opentui/core-linux-x64": "0.5.13", "@opentui/core-linux-x64-musl": "0.5.13", "@opentui/core-win32-arm64": "0.5.13", "@opentui/core-win32-x64": "0.5.13" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-3XNXJx3J9I+Ce170oh7GJ3leBZZA7QYv4OAhwiMCPQtKMkhy3Wra99NM26HXcEGme0zjkkJLownwLLnxuc0U/Q=="],
"@opentui/core": ["@opentui/core@0.5.12", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.12", "@opentui/core-darwin-x64": "0.5.12", "@opentui/core-linux-arm64": "0.5.12", "@opentui/core-linux-arm64-musl": "0.5.12", "@opentui/core-linux-x64": "0.5.12", "@opentui/core-linux-x64-musl": "0.5.12", "@opentui/core-win32-arm64": "0.5.12", "@opentui/core-win32-x64": "0.5.12" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-ZXBE5gmvdovmV8zJQrOQf6E44v1tJRDEgrM2MYhEglzgXZ+smIUp95O8zeRYGsuIzQIiMPMgQqKtTJuzvAb7BQ=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5X9U2v5qn4+vKj31zpn0RMoBV3Q9ttdM4t5KN41NPg6XgtIOZgKwox5yOsvBaiQ1KGbuk5wMvXCxfWJ30Mj/nw=="],
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-YdVnP0tAyerBNl0mIcmQEOotPeZzW1VnSXKBl5cyZ5e6nDd2Y+ui/8eRPpn1oqcamf1NCnzS4ohMgejOvna8Zg=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-9IgQHLKSn3quVsU0gibkRjOPegv1QH4573KWYXQNDmSxBXw84Nd1mDNsbK9f72SblAILhOCYK685pmk3X/z0Ig=="],
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-uRrQJdHmLUSj3PV23QPi3WSimYTTxcXnVouxF6U4xMXlOv4N3SxnHfVwMRQkPqbGOfvVWHeLE6FdK4C+ubU0sQ=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-jMXGEpB/2Ch/IR0QzYBM5eCr1tUzicxoTP1AbMCbOduJXcGRCHTWqIdQIgRErwPF92gBcDIs4JugSn/Jd0Ki7g=="],
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-XeKhuIaEtgipvuPHbl4qPOBj+Ut+2zObmsxMVM1jDcjz/FatG9PGeGQPx1G1SnvH2AgpT4K+eCu7DUF0+yIqoQ=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.13", "", { "os": "linux", "cpu": "x64" }, "sha512-7ytcKy7pQxvQer3PADGYNK+HRhSDyhZvp475GRBEhlBJIdhdL8PNU6hjd2R1dnieifiW7Mpc4EiC1kGKe69gYg=="],
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.5.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-VZ2sNMw1d/r1SLPjUbOP9LKscKz1CQjID8adTL6gG8Lrrq+mYcIUxutyB+P/eG0J/7oRZLPR6OMt7dUOap6RTg=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.13", "", { "os": "linux", "cpu": "x64" }, "sha512-C2ZC7WA7YH/GS+rJnbeVGe6Kxeor0aTD2qcS6l32KmN4XuY7TXm192XJMfxxnKaTA6oKp3mW27ezolJKUcGtMw=="],
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.12", "", { "os": "linux", "cpu": "x64" }, "sha512-eZiCjEzwbb6qClPPfk32Nha9xmr9obt69Xj0+9SKsXxWLBKkjQEGOMRoh/R9ObaQF4aq8If1xV3VEY0sD9W9vg=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-IB6eLh6I/gYXrJ0AYxZpD+Dr+yfZJck0ZfLnIapbD+fykaT0umOtvc/BL+CtlC/aSc7jpe0q4eXdn6XIA8HtLw=="],
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.12", "", { "os": "linux", "cpu": "x64" }, "sha512-WWW0hVBoSYZ3D6AgZ4u2Y5/u/IyIq2pDb+4yI3WgJ70Wyt6ofHy+6kRGRgbXFn1p+rPInAHjCXD2v6C7iEKSrA=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.13", "", { "os": "win32", "cpu": "x64" }, "sha512-FCucDN8A4iFDPdwqLK99ISs42pcbcObkxhN1jtsnmcYM9/Ptron7Hhapx2ObQWYjSrJNnntmfZQd2ewpE8YqTQ=="],
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-aLbm6870Ybls6CYL4zMOCImTBPLZHZMUXJFGqMI44lIWxitkAtT6zg5lYA4oRqFRzzryDclxr29+hDgT3p3Blw=="],
"@opentui/keymap": ["@opentui/keymap@0.5.13", "", { "dependencies": { "@opentui/core": "0.5.13" }, "peerDependencies": { "@opentui/react": "0.5.13", "@opentui/solid": "0.5.13", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-bbpQ5N8000CuvVDhptGuHxUE92sivChjUjLkvYT1VnLlDTiGbQ4mPsHfnqsaEokc7O7jBcoJXJQsLxw7rO/qkg=="],
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.12", "", { "os": "win32", "cpu": "x64" }, "sha512-KTwtwpfd2zF9opVh3SyRJYDd1o3Xv4XL8OZb8Zi+CqWUel6Y2IDCiVivCv8fGJt3J7wOIXXtuZI9ZUkLyKJCiQ=="],
"@opentui/solid": ["@opentui/solid@0.5.13", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.13", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-MGMYQYeoZNn9uq3zsLPqq/G+nBQXgGwpylsrYux0nJ+C+6oflDEE6t8huSTZaAUizC/3WG8sVSVFutczeRbnPg=="],
"@opentui/keymap": ["@opentui/keymap@0.5.12", "", { "dependencies": { "@opentui/core": "0.5.12" }, "peerDependencies": { "@opentui/react": "0.5.12", "@opentui/solid": "0.5.12", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-yWPvJjRhJTRoRSUucQq9Ua8ZW7n/2YQ/j6JxWq5Qekm4WuFiTplEkebR/Aj2/xA8tX68NOE5qv1LrY0Jk3NLNQ=="],
"@opentui/solid": ["@opentui/solid@0.5.12", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.12", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-hAiVlVMtT7AkHGblKwcW1YAuXtxkSy1XSf/RRc4j3IlG3mTNX0bhJdnGOo3Xw14EqeZMp41Mcp5WzHAzMm/DzA=="],
"@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="],
+4 -4
View File
@@ -2,7 +2,7 @@
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode",
"description": "AI-powered development tool",
"version": "2.0.20",
"version": "2.0.19",
"private": true,
"type": "module",
"packageManager": "bun@1.4.2",
@@ -52,9 +52,9 @@
"@octokit/rest": "22.0.0",
"@hono/standard-validator": "0.2.0",
"@hono/zod-validator": "0.4.2",
"@opentui/core": "0.5.13",
"@opentui/keymap": "0.5.13",
"@opentui/solid": "0.5.13",
"@opentui/core": "0.5.12",
"@opentui/keymap": "0.5.12",
"@opentui/solid": "0.5.12",
"@tanstack/solid-virtual": "3.13.37",
"@shikijs/stream": "4.4.3",
"@standard-schema/spec": "1.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.0.20",
"version": "2.0.19",
"name": "@opencode/ai",
"type": "module",
"license": "MIT",
+3 -15
View File
@@ -51,17 +51,6 @@ const RESPECTS_INLINE_HINTS = new Set([
"openrouter",
])
// OpenRouter upstreams other than Anthropic and Alibaba Qwen cache without breakpoints. Gemini uses only the last
// breakpoint, so a conversation-tail breakpoint writes a new cache every step and costs more than none. Qwen ignores
// breakpoints on tool definitions and caches tools with the system prompt.
const openRouterPolicy = (modelID: string): CachePolicyObject => {
// `~anthropic/claude-sonnet-latest` style IDs are OpenRouter aliases for the latest model in a family.
const id = modelID.replace(/^~/, "")
if (id.startsWith("anthropic/")) return AUTO
if (id.startsWith("qwen/")) return { system: true, messages: { tail: 1 } }
return NONE
}
const makeHint = (ttlSeconds: number | undefined): CacheHint =>
ttlSeconds !== undefined ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" })
@@ -167,10 +156,9 @@ const countHints = (request: LLMRequest) =>
export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
if (!RESPECTS_INLINE_HINTS.has(request.model.route.id)) return request
const policy =
request.model.route.id === "openrouter" && (request.cache === undefined || request.cache === "auto")
? openRouterPolicy(request.model.id)
: resolve(request.cache)
if (request.model.route.id === "openrouter" && (request.cache === undefined || request.cache === "auto"))
return request
const policy = resolve(request.cache)
if (!policy.tools && !policy.system && !policy.messages) return request
const hint = makeHint(policy.ttlSeconds)
+6 -10
View File
@@ -426,7 +426,6 @@ interface ActiveContent {
readonly type: "text" | "reasoning"
readonly id: string
readonly thinking?: MistralThinkingContent
readonly thinkingUnits?: MistralThinkingUnit[]
}
export interface ParserState {
@@ -503,8 +502,8 @@ const closeActive = (state: ParserState, events: LLMEvent[]) => {
state.lifecycle,
events,
state.active.id,
thinkingMetadata({ ...state.active.thinking, type: "thinking", thinking: state.active.thinkingUnits ?? [] }),
thinkingText(state.active.thinkingUnits ?? []),
thinkingMetadata(state.active.thinking ?? { type: "thinking", thinking: [] }),
thinkingText(state.active.thinking?.thinking ?? []),
)
return { ...state, lifecycle, active: undefined }
}
@@ -525,23 +524,20 @@ const appendThinking = (state: ParserState, events: LLMEvent[], part: MistralOut
const current = state.active?.type === "reasoning" ? state : closeActive(state, events)
const units = thinkingUnits(part.thinking)
const active = current.active ?? { type: "reasoning" as const, id: `reasoning-${current.nextContent}` }
// Keep native units out of streamed events until the block is complete.
const accumulated = active.thinkingUnits ?? []
accumulated.push(...units)
const thinking = {
...active.thinking,
...part,
type: "thinking" as const,
thinking: [],
thinking: [...(active.thinking?.thinking ?? []), ...units],
}
const text = thinkingText(units)
return {
...current,
lifecycle:
text.length > 0
? Lifecycle.reasoningDelta(current.lifecycle, events, active.id, text)
: Lifecycle.reasoningStart(current.lifecycle, events, active.id),
active: { ...active, thinking, thinkingUnits: accumulated },
? Lifecycle.reasoningDelta(current.lifecycle, events, active.id, text, thinkingMetadata(thinking))
: Lifecycle.reasoningStart(current.lifecycle, events, active.id, thinkingMetadata(thinking)),
active: { ...active, thinking },
nextContent: current.active ? current.nextContent : current.nextContent + 1,
}
}
+40 -47
View File
@@ -20,6 +20,7 @@ import {
type LLMRequest,
type MediaPart,
type ReasoningPart,
type TextPart,
type ToolCallPart,
type ToolDefinition,
} from "../schema/index.js"
@@ -44,7 +45,6 @@ const OpenAIChatCacheControl = Schema.Struct({
type: Schema.Literal("ephemeral"),
ttl: Schema.optional(Schema.String),
})
type OpenAIChatCacheControl = Schema.Schema.Type<typeof OpenAIChatCacheControl>
const OpenAIChatFunction = Schema.Struct({
name: Schema.String,
@@ -121,15 +121,12 @@ const decodeReasoningDetail = Schema.decodeUnknownOption(ReasoningDetail)
const knownReasoningDetails = (details: ReadonlyArray<unknown>) =>
details.flatMap((detail) => Option.toArray(decodeReasoningDetail(detail)))
const OpenAIChatTextContent = Schema.Struct({
type: Schema.Literal("text"),
text: Schema.String,
cache_control: Schema.optional(OpenAIChatCacheControl),
})
type OpenAIChatTextContent = Schema.Schema.Type<typeof OpenAIChatTextContent>
const OpenAIChatUserContent = Schema.Union([
OpenAIChatTextContent,
Schema.Struct({
type: Schema.Literal("text"),
text: Schema.String,
cache_control: Schema.optional(OpenAIChatCacheControl),
}),
Schema.Struct({
type: Schema.Literal("image_url"),
image_url: Schema.Struct({ url: Schema.String }),
@@ -139,7 +136,6 @@ const OpenAIChatUserContent = Schema.Union([
file: Schema.Struct({ filename: Schema.String, file_data: Schema.String }),
}),
])
type OpenAIChatUserContent = Schema.Schema.Type<typeof OpenAIChatUserContent>
const OpenAIChatMessage = Schema.Union([
Schema.Struct({
@@ -153,19 +149,21 @@ const OpenAIChatMessage = Schema.Union([
Schema.StructWithRest(
Schema.Struct({
role: Schema.Literal("assistant"),
content: Schema.NullOr(Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)])),
content: Schema.NullOr(Schema.String),
tool_calls: optionalArray(OpenAIChatAssistantToolCall),
reasoning_content: Schema.optional(Schema.String),
reasoning: Schema.optional(Schema.String),
reasoning_text: Schema.optional(Schema.String),
reasoning_details: Schema.optional(Schema.Unknown),
cache_control: Schema.optional(OpenAIChatCacheControl),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
),
Schema.Struct({
role: Schema.Literal("tool"),
tool_call_id: Schema.String,
content: Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)]),
content: Schema.String,
cache_control: Schema.optional(OpenAIChatCacheControl),
}),
]).pipe(Schema.toTaggedUnion("role"))
type OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>
@@ -329,7 +327,9 @@ export interface ParserState {
// OpenAI Chat wire format. Keep provider quirks here instead of leaking native
// fields into `LLMRequest`.
interface LoweringOptions {
readonly cacheControl?: (cache: CacheHint | undefined) => OpenAIChatCacheControl | undefined
readonly cacheControl?: (
cache: CacheHint | undefined,
) => Schema.Schema.Type<typeof OpenAIChatCacheControl> | undefined
readonly toolCallID?: (id: string) => string
}
@@ -415,7 +415,7 @@ const lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (
message: OpenAIChatRequestMessage,
options: LoweringOptions,
) {
const content: OpenAIChatUserContent[] = []
const content: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []
for (const part of message.content) {
if (part.type === "text") {
content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) })
@@ -441,14 +441,14 @@ const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(func
requireReasoning: boolean,
options: LoweringOptions & { readonly providerMetadataKey: string },
) {
const content: OpenAIChatTextContent[] = []
const content: TextPart[] = []
const reasoning: ReasoningPart[] = []
const toolCalls: OpenAIChatAssistantToolCall[] = []
for (const part of message.content) {
if (!ProviderShared.supportsContent(part, ["text", "reasoning", "tool-call"]))
return yield* ProviderShared.unsupportedContent("OpenAI Chat", "assistant", ["text", "reasoning", "tool-call"])
if (part.type === "text") {
content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) })
content.push(part)
continue
}
if (part.type === "reasoning") {
@@ -486,15 +486,14 @@ const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(func
if (reasoning.length === 0) return nativeReasoning ?? (requireReasoning ? "" : undefined)
return text
})()
const cached = message.content.findLast((part) => "cache" in part && part.cache !== undefined)
const cacheControl = options.cacheControl?.(cached && "cache" in cached ? cached.cache : undefined)
const result = {
role: "assistant" as const,
content: (() => {
if (content.some((part) => part.cache_control !== undefined)) return content
if (content.length === 0 && toolCalls.length > 0) return null
return content.map((part) => part.text).join("")
})(),
content: content.length > 0 ? content.map((part) => part.text).join("") : toolCalls.length > 0 ? null : "",
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
...(details !== undefined ? { reasoning_details: details } : {}),
...(cacheControl !== undefined ? { cache_control: cacheControl } : {}),
}
if (field === undefined || reasoningText === undefined) return result
return { ...result, [field]: reasoningText }
@@ -505,38 +504,33 @@ const lowerToolMessages = Effect.fn("OpenAIChat.lowerToolMessages")(function* (
options: LoweringOptions,
) {
const messages: OpenAIChatMessage[] = []
const attachments: OpenAIChatUserContent[] = []
const attachments: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []
for (const part of message.content) {
if (!ProviderShared.supportsContent(part, ["tool-result"]))
return yield* ProviderShared.unsupportedContent("OpenAI Chat", "tool", ["tool-result"])
if (part.result.type !== "content") {
messages.push(
toolMessage(
options.toolCallID?.(part.id) ?? part.id,
ProviderShared.toolResultText(part),
options.cacheControl?.(part.cache),
),
)
messages.push({
role: "tool",
tool_call_id: options.toolCallID?.(part.id) ?? part.id,
content: ProviderShared.toolResultText(part),
cache_control: options.cacheControl?.(part.cache),
})
continue
}
const content: ReadonlyArray<Tool.Content> = part.result.value
const text = content.filter((item) => item.type === "text").map((item) => item.text)
messages.push(
toolMessage(options.toolCallID?.(part.id) ?? part.id, text.join("\n"), options.cacheControl?.(part.cache)),
)
messages.push({
role: "tool",
tool_call_id: options.toolCallID?.(part.id) ?? part.id,
content: text.join("\n"),
cache_control: options.cacheControl?.(part.cache),
})
const files = content.filter((item) => item.type === "file")
attachments.push(...(yield* Effect.forEach(files, (item) => lowerMedia(ProviderShared.toolFileMedia(item)))))
}
return { messages, attachments }
})
// Chat cache breakpoints belong on text content parts, not on the message itself.
const toolMessage = (toolCallID: string, text: string, cacheControl: OpenAIChatCacheControl | undefined) => ({
role: "tool" as const,
tool_call_id: toolCallID,
content: cacheControl === undefined ? text : [{ type: "text" as const, text, cache_control: cacheControl }],
})
const lowerMessage = Effect.fn("OpenAIChat.lowerMessage")(function* (
message: OpenAIChatRequestMessage,
reasoningField: string | undefined,
@@ -595,7 +589,7 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
if (requireAssistantAfterTool && messages.at(-1)?.role === "tool")
messages.push({ role: "assistant", content: "Done." })
}
const pendingAttachments: OpenAIChatUserContent[] = []
const pendingAttachments: Array<Schema.Schema.Type<typeof OpenAIChatUserContent>> = []
const flushAttachments = () => {
if (pendingAttachments.length === 0) return
bridgeTools()
@@ -605,25 +599,24 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
if (message.role === "user") bridgeTools()
if (message.role === "system") {
const part = yield* ProviderShared.wrappedSystemUpdate("OpenAI Chat", message)
const cacheControl = options.cacheControl?.(part.cache)
if (pendingAttachments.length > 0) {
messages.push({
role: "user",
content: [
...pendingAttachments.splice(0),
{ type: "text", text: part.text, cache_control: cacheControl },
{ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) },
],
})
continue
}
const previous = messages.at(-1)
if (previous?.role === "user" && typeof previous.content === "string")
messages[messages.length - 1] = cacheControl
messages[messages.length - 1] = options.cacheControl?.(part.cache)
? {
role: "user",
content: [
{ type: "text", text: previous.content },
{ type: "text", text: part.text, cache_control: cacheControl },
{ type: "text", text: part.text, cache_control: options.cacheControl(part.cache) },
],
}
: { role: "user", content: `${previous.content}\n${part.text}` }
@@ -632,15 +625,15 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
role: "user",
content: [
...previous.content,
{ type: "text", text: part.text, cache_control: cacheControl },
{ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) },
],
}
else
messages.push(
cacheControl
options.cacheControl?.(part.cache)
? {
role: "user",
content: [{ type: "text", text: part.text, cache_control: cacheControl }],
content: [{ type: "text", text: part.text, cache_control: options.cacheControl(part.cache) }],
}
: { role: "user", content: part.text },
)
-2
View File
@@ -16,8 +16,6 @@ import {
const patterns = [
/prompt is too long/i,
/input is too long for requested model/i,
// Cloudflare Workers AI reports this as HTTP 413.
/exceeded this model context window limit/i,
/exceeds the context window/i,
/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,
/input token count.*exceeds the maximum/i,
@@ -4,7 +4,7 @@
"model": "anthropic/claude-sonnet-4.6",
"tags": ["prefix:openai-compatible-chat", "provider:openrouter", "protocol:openai-chat", "reasoning"],
"name": "openrouter-reasoning",
"recordedAt": "2026-09-29T16:19:02.835Z"
"recordedAt": "2026-07-18T11:28:39.267Z"
},
"interactions": [
{
@@ -15,14 +15,14 @@
"headers": {
"content-type": "application/json"
},
"body": "{\"model\":\"anthropic/claude-sonnet-4.6\",\"messages\":[{\"role\":\"system\",\"content\":[{\"type\":\"text\",\"text\":\"Think through the arithmetic, then reply with only the final integer.\",\"cache_control\":{\"type\":\"ephemeral\"}}]},{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"What is 173 multiplied by 219?\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"store\":false,\"max_completion_tokens\":1536,\"temperature\":0,\"usage\":{\"include\":true},\"reasoning\":{\"max_tokens\":1024}}"
"body": "{\"model\":\"anthropic/claude-sonnet-4.6\",\"messages\":[{\"role\":\"system\",\"content\":\"Think through the arithmetic, then reply with only the final integer.\"},{\"role\":\"user\",\"content\":\"What is 173 multiplied by 219?\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"temperature\":0,\"reasoning\":{\"max_tokens\":1024},\"max_completion_tokens\":1536,\"store\":false,\"usage\":{\"include\":true}}"
},
"response": {
"status": 200,
"headers": {
"content-type": "text/event-stream"
},
"body": "data: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":\"173\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\"173\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\n: OPENROUTER PROCESSING\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":\" × 219\\n\\n173 × 200 = 34,600\\n173 × 19 = 173 × 20 - 173 = 3,460 - 173 = 3,287\\n\\n34,600 + 3,287 = 37,887\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\" × 219\\n\\n173 × 200 = 34,600\\n173 × 19 = 173 × 20 - 173 = 3,460 - 173 = 3,287\\n\\n34,600 + 3,287 = 37,887\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"signature\":\"Ev8CCrIBCBIYAipA0W4viH3kgBs43Cl5ewwVBPXTQElvzfbA2TLF4iSbKy9ZZDCSDjjAlF3Bs4ELEnP3vrrTuTioC6OB380lXQdyIDIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJDRjMGYwNDZmLTI1ZmQtNDVmYi1iZmIzLWEwOGE4ZTI0OWNhN3oedXByb2ZfMDExQ2VkSE1TN0tEcTM4Z2JkUkp0bXN3qAH2ye/VBhIMhjcPOnE2wLhs0P05GgwA3z9luwbhnSyRMSQiMDYeIIThirdkJb/n2s2TxUk5EOMrSc1xejAb0RN7BIl66P5KhtwXvcZTiyCkBS8+7Cp6MOinWi+I8U7DhWskSA0pHZqaAncbV7qCIHkoZ5aT8jiPWplAOnlciDo2tLkGsLnzXrnfhI11GTF0kcfyhbrt3tjEDSiPstBbT2u19LJ5IqwV2VKl0pWVdl4PTsDwC09ClbnJj1y0A3AM9gEh4B9mEo4BvT0XVEncux4YAQ==.eyJlbmRwb2ludF9zbHVnIjoiYW50aHJvcGljL2NsYXVkZS00LjYtc29ubmV0LTIwMjYwMjE3fGNsYXVkZS1vbi1hd3MifQ\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"37\",\"role\":\"assistant\"},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"887\",\"role\":\"assistant\"},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":null},\"finish_reason\":\"stop\",\"native_finish_reason\":\"end_turn\"}]}\n\ndata: {\"id\":\"gen-1790698739-Acm5E9n2uVTO14sqrick\",\"object\":\"chat.completion.chunk\",\"created\":1790698739,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Claude Platform on AWS\",\"service_tier\":\"default\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"native_finish_reason\":\"end_turn\"}],\"usage\":{\"prompt_tokens\":61,\"completion_tokens\":80,\"total_tokens\":141,\"cost\":0.001383,\"is_byok\":false,\"prompt_tokens_details\":{\"cached_tokens\":0,\"cache_write_tokens\":0,\"audio_tokens\":0,\"video_tokens\":0},\"cost_details\":{\"upstream_inference_cost\":0.001383,\"upstream_inference_prompt_cost\":0.000183,\"upstream_inference_completions_cost\":0.0012},\"completion_tokens_details\":{\"reasoning_tokens\":73,\"image_tokens\":0,\"audio_tokens\":0}}}\n\ndata: [DONE]\n\n"
"body": ": OPENROUTER PROCESSING\n\n: OPENROUTER PROCESSING\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":\"173\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\"173\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\n: OPENROUTER PROCESSING\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":\" × 219\\n\\n173 × 200 = 34,600\\n173 × 19 = 173 × 20 - 173 = 3,460 - 173 = 3,287\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\" × 219\\n\\n173 × 200 = 34,600\\n173 × 19 = 173 × 20 - 173 = 3,460 - 173 = 3,287\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":\"\\n\\n34,600 + 3,287 = 37,887\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"text\":\"\\n\\n34,600 + 3,287 = 37,887\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning_details\":[{\"type\":\"reasoning.text\",\"signature\":\"EtgCCosBCA8YAipA0W4viH3kgBs43Cl5ewwVBPXTQElvzfbA2TLF4iSbKy9ZZDCSDjjAlF3Bs4ELEnP3vrrTuTioC6OB380lXQdyIDIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJDRjMGYwNDZmLTI1ZmQtNDVmYi1iZmIzLWEwOGE4ZTI0OWNhNxIMMiUlJC3x/5p5PuTwGgwlc8eipZyoM94BHwMiMO45uQx/ymeOjbugi7RDVPZ4jZXSIiEbVi2CD7zPjAK5fFQoVGP1HD55v9CER823JCp6Dg5Xb7Lrk6NUd1XN2KTKrttK7mATE+IBrDTFmor/1cNeg+9gjIbxM/jn/6L5HPmh3/esEVu24Q0IGLZVoE7cTgGgxsrceKMD71Jp2XQgIWD8ltsPfWw3gSc4p+z18UuPN6LuR0mHHENTnClHrAPnOrxbDIl4ZwZgMX8YAQ==\",\"format\":\"anthropic-claude-v1\",\"index\":0}]},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"37887\",\"role\":\"assistant\"},\"finish_reason\":null,\"native_finish_reason\":null}]}\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\",\"reasoning\":null},\"finish_reason\":\"stop\",\"native_finish_reason\":\"end_turn\"}]}\n\ndata: {\"id\":\"gen-1784374117-AXXPsQRoclZeQGx2uHeK\",\"object\":\"chat.completion.chunk\",\"created\":1784374117,\"model\":\"anthropic/claude-sonnet-4.6\",\"provider\":\"Anthropic\",\"service_tier\":\"default\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\",\"native_finish_reason\":\"end_turn\"}],\"usage\":{\"prompt_tokens\":61,\"completion_tokens\":80,\"total_tokens\":141,\"cost\":0.001383,\"is_byok\":false,\"prompt_tokens_details\":{\"cached_tokens\":0,\"cache_write_tokens\":0,\"audio_tokens\":0,\"video_tokens\":0},\"cache_creation\":{\"ephemeral_5m_input_tokens\":0,\"ephemeral_1h_input_tokens\":0},\"cost_details\":{\"upstream_inference_cost\":0.001383,\"upstream_inference_prompt_cost\":0.000183,\"upstream_inference_completions_cost\":0.0012},\"completion_tokens_details\":{\"reasoning_tokens\":29,\"image_tokens\":0,\"audio_tokens\":0}}}\n\ndata: [DONE]\n\n"
}
}
]
-11
View File
@@ -355,17 +355,6 @@ describe("provider error rawBody classification", () => {
}
})
test("classifies Workers AI context window rejections as context overflow despite HTTP 413", () => {
const message =
"AiError: Ai: The estimated number of input and maximum output tokens (900047) exceeded this model context window limit (32000). (17851589-f2e6-405d-b67c-5550e52ee1c1)"
const reason = classifyProviderFailure({
message,
status: 413,
rawBody: JSON.stringify({ errors: [{ message, code: 5021 }], success: false, result: {}, messages: [] }),
})
expect(reason._tag === "InvalidRequest" ? reason.classification : reason._tag).toBe("context-overflow")
})
test("classifies Google invalid API keys as authentication failures", () => {
const rawBody = JSON.stringify({
error: {
+3 -19
View File
@@ -303,8 +303,7 @@ describe("Mistral Chat", () => {
fixedResponse(
sseEvents(
chunk({ content: [{ type: "thinking", thinking: [], marker: "empty" }] }),
chunk({ content: [{ type: "thinking", thinking: [{ type: "text", text: "Con" }] }] }),
chunk({ content: [{ type: "thinking", thinking: [{ type: "text", text: "sider" }], closed: true }] }),
chunk({ content: [{ type: "thinking", thinking: [{ type: "text", text: "Consider" }] }] }),
chunk({ content: [{ type: "text", text: "Answer" }] }),
chunk({}, "stop"),
),
@@ -314,11 +313,6 @@ describe("Mistral Chat", () => {
expect(response.reasoning).toBe("Consider")
expect(response.text).toBe("Answer")
expect(response.events.find(LLMEvent.is.reasoningStart)?.providerMetadata).toBeUndefined()
expect(response.events.filter(LLMEvent.is.reasoningDelta).map((event) => [event.text, event.providerMetadata])).toEqual([
["Con", undefined],
["sider", undefined],
])
expect(response.message.content).toEqual([
{
type: "reasoning",
@@ -327,12 +321,8 @@ describe("Mistral Chat", () => {
mistral: {
thinking: {
type: "thinking",
thinking: [
{ type: "text", text: "Con" },
{ type: "text", text: "sider" },
],
thinking: [{ type: "text", text: "Consider" }],
marker: "empty",
closed: true,
},
},
},
@@ -347,12 +337,8 @@ describe("Mistral Chat", () => {
content: [
{
type: "thinking",
thinking: [
{ type: "text", text: "Con" },
{ type: "text", text: "sider" },
],
thinking: [{ type: "text", text: "Consider" }],
marker: "empty",
closed: true,
},
{ type: "text", text: "Answer" },
],
@@ -371,8 +357,6 @@ describe("Mistral Chat", () => {
),
),
)
expect(response.events.find(LLMEvent.is.reasoningStart)?.providerMetadata).toBeUndefined()
expect(response.events.filter(LLMEvent.is.reasoningDelta)).toEqual([])
expect(response.message.content).toEqual([
{
type: "reasoning",
@@ -89,14 +89,7 @@ for (const item of cases) {
const replay = yield* compileRequest(LLM.request({ model: item.model, messages: [response.message] }))
expect(replay.body.messages).toMatchObject([
{
role: "assistant",
content:
item.model.route.id === "openrouter"
? [{ type: "text", text: response.text, cache_control: { type: "ephemeral" } }]
: response.text,
reasoning: response.reasoning,
},
{ role: "assistant", content: response.text, reasoning: response.reasoning },
])
const replayDetails =
replay.body.messages[0]?.role === "assistant" ? replay.body.messages[0].reasoning_details : undefined
@@ -4996,42 +4996,6 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("retains the token-sharing HTTP 429 body for retry hooks", () =>
Effect.gen(function* () {
const body = JSON.stringify({ error: { code: "subscription_sharing_usage_limit_exceeded", message: "Rate limit exceeded" } })
const error = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(body, { status: 429, headers: { "content-type": "application/json" } }),
),
Effect.flip,
)
expect(error).toMatchObject({ reason: { _tag: "RateLimit", http: { status: 429 }, body } })
}),
)
it.effect("retains the token-sharing response.failed event for retry hooks", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents({
type: "response.failed",
response: {
id: "resp_usage_limit",
error: { code: "subscription_sharing_usage_limit_exceeded", message: "Rate limit exceeded" },
},
}),
),
),
Effect.flip,
)
expect(error).toMatchObject({ reason: { _tag: "RateLimit" } })
expect(error.reason.body).toContain("subscription_sharing_usage_limit_exceeded")
}),
)
it.effect("surfaces response.failed code when no nested message is present", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(request).pipe(
+4 -164
View File
@@ -32,125 +32,6 @@ describe("OpenRouter", () => {
}),
)
it.effect("places default cache breakpoints on tools, system boundaries, and the conversation tail", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
system: [
{ type: "text", text: "Base agent" },
{ type: "text", text: "Model details" },
{ type: "text", text: "Project instructions" },
],
tools: [
{ name: "read", description: "Read", inputSchema: { type: "object", properties: {} } },
{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } },
],
prompt: "Hello",
}),
)
expect(prepared.body.tools?.map((tool) => tool.cache_control)).toEqual([undefined, { type: "ephemeral" }])
expect(prepared.body.messages).toMatchObject([
{
role: "system",
content: [
{ text: "Base agent", cache_control: { type: "ephemeral" } },
{ text: "Model details" },
{ text: "Project instructions", cache_control: { type: "ephemeral" } },
],
},
{ role: "user", content: [{ text: "Hello", cache_control: { type: "ephemeral" } }] },
])
expect(prepared.body.messages[0]?.content).not.toContainEqual(
expect.objectContaining({ text: "Model details", cache_control: expect.anything() }),
)
}),
)
it.effect("places default cache breakpoints on OpenRouter latest-model aliases", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: OpenRouter.configure({ apiKey: "test-key" }).model("~anthropic/claude-sonnet-latest"),
system: "Base agent",
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
prompt: "Hello",
}),
)
expect(prepared.body.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" })
expect(prepared.body.messages).toMatchObject([
{ role: "system", content: [{ text: "Base agent", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ text: "Hello", cache_control: { type: "ephemeral" } }] },
])
}),
)
it.effect("skips the tool breakpoint for Qwen, which caches tools with the system prompt", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: OpenRouter.configure({ apiKey: "test-key" }).model("qwen/qwen3-coder-plus"),
system: "Base agent",
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
prompt: "Hello",
}),
)
expect(prepared.body.tools?.[0]?.cache_control).toBeUndefined()
expect(prepared.body.messages).toMatchObject([
{ role: "system", content: [{ text: "Base agent", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ text: "Hello", cache_control: { type: "ephemeral" } }] },
])
}),
)
it.effect("places the default Qwen conversation-tail breakpoint inside tool-result text", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: OpenRouter.configure({ apiKey: "test-key" }).model("qwen/qwen3-coder-plus"),
messages: [
Message.user("Call the tool"),
Message.assistant([{ type: "tool-call", id: "call_1", name: "lookup", input: {} }]),
Message.tool({ id: "call_1", name: "lookup", result: "Done" }),
],
}),
)
expect(prepared.body.messages.at(-1)).toMatchObject({
role: "tool",
tool_call_id: "call_1",
content: [{ type: "text", text: '"Done"', cache_control: { type: "ephemeral" } }],
})
}),
)
it.effect("sends no default breakpoints to upstreams that cache without them", () =>
Effect.gen(function* () {
const openrouter = OpenRouter.configure({ apiKey: "test-key" })
const bodies = yield* Effect.forEach(["google/gemini-2.5-flash", "openai/gpt-5-mini"], (id) =>
compileRequest(
LLM.request({
model: openrouter.model(id),
system: "Base agent",
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
prompt: "Hello",
}),
).pipe(Effect.map((prepared) => prepared.body)),
)
bodies.forEach((body) => {
expect(body.tools?.[0]?.cache_control).toBeUndefined()
expect(body.messages).toMatchObject([
{ role: "system", content: "Base agent" },
{ role: "user", content: "Hello" },
])
})
}),
)
it.effect("lowers the native cache policy to OpenRouter cache controls", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
@@ -193,8 +74,6 @@ describe("OpenRouter", () => {
cache: "none",
messages: [
Message.user("Call the tool"),
Message.assistant("Unmarked reply"),
Message.user("Call again"),
Message.assistant([
{ type: "text", text: "Calling", cache: new CacheHint({ type: "ephemeral" }) },
{ type: "tool-call", id: "call_1", name: "lookup", input: {} },
@@ -211,17 +90,8 @@ describe("OpenRouter", () => {
expect(prepared.body.messages).toMatchObject([
{ role: "user", content: "Call the tool" },
{ role: "assistant", content: "Unmarked reply" },
{ role: "user", content: "Call again" },
{
role: "assistant",
content: [{ type: "text", text: "Calling", cache_control: { type: "ephemeral" } }],
tool_calls: [{ id: "call_1", type: "function", function: { name: "lookup", arguments: "{}" } }],
},
{
role: "tool",
content: [{ type: "text", text: '"Done"', cache_control: { type: "ephemeral", ttl: "1h" } }],
},
{ role: "assistant", content: "Calling", cache_control: { type: "ephemeral" } },
{ role: "tool", content: '"Done"', cache_control: { type: "ephemeral", ttl: "1h" } },
])
}),
)
@@ -248,7 +118,7 @@ describe("OpenRouter", () => {
}),
)
it.effect("does not emit text cache markers on reasoning-only assistant messages", () =>
it.effect("preserves cache policy hints on reasoning-only assistant messages", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
@@ -260,38 +130,8 @@ describe("OpenRouter", () => {
expect(prepared.body.messages).toMatchObject([
{ role: "user", content: "Think" },
{ role: "assistant", content: "" },
{ role: "assistant", cache_control: { type: "ephemeral" } },
])
expect(prepared.body.messages[1]).not.toHaveProperty("cache_control")
}),
)
it.effect("counts wrapped system-update markers once so all four default breakpoints survive", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: OpenRouter.configure({ apiKey: "test-key" }).model("anthropic/claude-sonnet-4.6"),
system: [
{ type: "text", text: "Base agent" },
{ type: "text", text: "Project instructions" },
],
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
messages: [Message.user("Start"), Message.system("Updated instructions")],
}),
)
expect(prepared.body.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" })
expect(prepared.body.messages.at(-1)).toMatchObject({
role: "user",
content: [
{ type: "text", text: "Start" },
{
type: "text",
text: "<system-update>\nUpdated instructions\n</system-update>",
cache_control: { type: "ephemeral" },
},
],
})
}),
)
@@ -4,9 +4,9 @@ import { For, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { Portal, render } from "solid-js/web"
import { LanguageProvider, UiI18nBridge } from "../src/runtime/i18n/language"
import type { BrowserPaneEvent, BrowserPaneLayout, BrowserPaneRegistration } from "../src/runtime/platform/browser-pane"
import type { BrowserPaneLayout, BrowserPaneRegistration } from "../src/runtime/platform/browser-pane"
import type { createSessionBrowser } from "../src/session/browser/model"
import { SessionBrowserPane, type SessionBrowserComment } from "../src/session/browser/pane"
import { SessionBrowserPane } from "../src/session/browser/pane"
export function mountBrowserPane() {
const host = document.createElement("main")
@@ -30,15 +30,9 @@ export function mountBrowserPane() {
covered: false,
captures: 0,
holdCapture: false,
picker: {} as Record<string, boolean | undefined>,
highlights: [] as string[],
comments: [] as SessionBrowserComment[],
})
// Each capture waits until the fixture releases it, so a spec can observe the pending state.
const held: (() => void)[] = []
const inspectors = new Set<(event: Extract<BrowserPaneEvent, { type: "inspect" }>) => void>()
const emitInspect = (event: Extract<BrowserPaneEvent, { type: "inspect" }>) =>
inspectors.forEach((listener) => listener(event))
const tabs = ["Alpha", "Beta"].map((name) => ({
id: Browser.TabID.make(`tab_${name === "Alpha" ? "11111111" : "22222222"}-1111-1111-1111-111111111111`),
title: name,
@@ -66,12 +60,6 @@ export function mountBrowserPane() {
}
return canvas.convertToBlob()
},
// The desktop confirms each picker change, as the page does once inspect mode is armed.
inspect: (tabID, enabled) => {
setStore("picker", tab.title, enabled)
emitInspect({ type: "inspect", tabID, active: enabled })
},
highlight: (_tabID, ref) => setStore("highlights", (items) => [...items, ref ?? "clear"]),
close: () => undefined,
},
]),
@@ -109,26 +97,7 @@ export function mountBrowserPane() {
}
if (command.type === "stop") setStore("loading", false)
},
onInspect: (listener) => {
inspectors.add(listener)
return () => inspectors.delete(listener)
},
reveal: () => undefined,
}
const pick = () =>
emitInspect({
type: "inspect",
tabID: browser.active().id,
active: false,
element: {
ref: Browser.Ref.make("e7"),
selector: "main > button.primary",
label: "button.primary",
role: "button",
name: "Save changes",
rect: { x: 48, y: 40, width: 160, height: 36 },
},
})
return (
<>
<h1 style={{ "font-size": "24px", "margin-bottom": "16px" }}>Browser pane lifecycle</h1>
@@ -168,30 +137,13 @@ export function mountBrowserPane() {
<button onClick={() => setStore("holdCapture", true)}>Hold capture</button>
<button onClick={() => held.splice(0).forEach((resolve) => resolve())}>Release capture</button>
<button onClick={() => setStore("covered", (covered) => !covered)}>Toggle popover</button>
<button onClick={pick}>Pick element</button>
</nav>
<p>Captures: {store.captures}</p>
<p>Picker: {store.picker[store.session] ? "on" : "off"}</p>
<p>Highlights: {store.highlights.join(",")}</p>
<div style={{ position: "relative", width: "640px", height: "360px", border: "1px solid #555" }}>
<Show when={store.mounted}>
<SessionBrowserPane
browser={browser}
visible={store.visible}
onComment={(comment) => setStore("comments", (items) => [...items, comment])}
/>
<SessionBrowserPane browser={browser} visible={store.visible} />
</Show>
</div>
<ul data-testid="fixture-comments">
<For each={store.comments}>
{(comment) => (
<li>
{comment.element.label} {comment.element.ref ? `@${comment.element.ref}` : "(no ref)"}:{" "}
{comment.comment}
</li>
)}
</For>
</ul>
<Show when={store.covered}>
{/* Floating content portals into <body> like a menu or hover card over the page. */}
<Portal mount={document.body}>
@@ -79,81 +79,6 @@ story("keeps a still of the page under floating content that covers it", async (
await expect(root.getByText("Captures: 1", { exact: true })).toBeVisible()
})
story("comments on a picked element over a still of the page", async ({ page }, testInfo) => {
const root = page.getByTestId("browser-pane-fixture")
const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true })
await picker.click()
await expect(picker).toHaveAttribute("aria-pressed", "true")
await expect(root.getByText("Picker: on", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
await expect(picker).toHaveAttribute("aria-pressed", "false")
const editor = root.locator('[data-slot="browser-comment-editor"] textarea')
await expect(editor).toBeFocused()
await expect(root.locator('[data-slot="browser-comment-editor"]')).toContainText("button.primary")
// The native page hides behind its still so the editor can float over it.
await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "false")
await expect(root.locator("#browser-panel img")).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("comment.png") })
await editor.fill("Make this the primary colour")
await editor.press("Enter")
await expect(root.getByTestId("fixture-comments")).toHaveText("button.primary @e7: Make this the primary colour")
await expect(root.locator('[data-component="browser-comment"]')).toHaveCount(0)
await expect(root.getByText("Highlights: clear", { exact: true })).toBeVisible()
await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true")
})
story("cancels the picker and a comment with Escape", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true })
await picker.click()
await expect(picker).toHaveAttribute("aria-pressed", "true")
await page.keyboard.press("Escape")
await expect(picker).toHaveAttribute("aria-pressed", "false")
await expect(root.getByText("Picker: off", { exact: true })).toBeVisible()
await picker.click()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
const editor = root.locator('[data-slot="browser-comment-editor"] textarea')
await expect(editor).toBeFocused()
await editor.press("Escape")
await expect(root.locator('[data-component="browser-comment"]')).toHaveCount(0)
await expect(root.getByTestId("fixture-comments")).toHaveText("")
await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true")
})
story("keeps a comment draft but drops its ref when the page navigates", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Select an element to comment on", exact: true }).click()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
const editor = root.locator('[data-slot="browser-comment-editor"] textarea')
await editor.fill("Still misaligned after the reload")
await root.getByRole("button", { name: "Load current page", exact: true }).click()
await expect(editor).toHaveValue("Still misaligned after the reload")
await editor.press("Enter")
await expect(root.getByTestId("fixture-comments")).toHaveText(
"button.primary (no ref): Still misaligned after the reload",
)
})
story("keeps the comment editor and its actions inside the page", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Select an element to comment on", exact: true }).click()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
const editor = root.locator('[data-slot="browser-comment-editor"]')
// As if the user dragged the textarea's resize handle far past the page.
await editor.locator("textarea").evaluate((element) => {
element.style.height = "900px"
})
const surface = await root.locator('[data-component="browser-comment"]').boundingBox()
const box = await editor.boundingBox()
expect(surface && box && box.y + box.height <= surface.y + surface.height).toBe(true)
const submit = editor.getByRole("button", { name: "Comment", exact: true })
await submit.scrollIntoViewIfNeeded()
await expect(submit).toBeInViewport()
})
story("shows the empty state over a blank native page and restores navigation", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Blank page", exact: true }).click()
@@ -186,17 +186,11 @@ for (const scenario of scenarios) {
const toolTitle = element
.closest('[data-component="edit-tool"]')
?.querySelector('[data-slot="collapsible-trigger"][data-locked]')
// Grouped file headers stack below the stuck Used header.
const group = element
.closest('[data-component="collapsed-tool-group"]')
?.querySelector(':scope > [data-component="collapsible"] > [data-slot="collapsible-trigger"]')
const sessionTop = viewport.getBoundingClientRect().top + (title?.getBoundingClientRect().height ?? 0)
const top = sessionTop + (group?.getBoundingClientRect().height ?? 0)
const top = viewport.getBoundingClientRect().top + (title?.getBoundingClientRect().height ?? 0)
const rect = element.getBoundingClientRect()
const trigger = element.querySelector("button")!
return {
gap: Math.abs(rect.top - top - (toolTitle?.getBoundingClientRect().height ?? 0)),
groupGap: group ? Math.abs(group.getBoundingClientRect().top - sessionTop) : 0,
titleGap: toolTitle ? Math.abs(toolTitle.getBoundingClientRect().top - top) : 0,
clickable: trigger.contains(
document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2),
@@ -204,7 +198,7 @@ for (const scenario of scenarios) {
}
}),
)
.toEqual({ gap: 0, groupGap: 0, titleGap: 0, clickable: true })
.toEqual({ gap: 0, titleGap: 0, clickable: true })
await page.screenshot({ path: info.outputPath(`${file}.png`) })
}
@@ -1,43 +0,0 @@
import { expect, test } from "@playwright/test"
import { base64Encode } from "@opencode/util/encode"
import {
assistantMessage,
session,
setupTimeline,
textPart,
userMessage,
} from "../performance/timeline-stability/fixture"
const target = "ses_0123456789abcdefghijklmnop"
const missing = "ses_abcdefghijklmnopqrstuvwxyz"
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
test("opens a verified session from agent prose or inline code with the keyboard", async ({ page }) => {
await setupTimeline(page, {
sessions: [session(), session({ id: target, title: "Linked session" })],
messages: [
userMessage(),
assistantMessage([textPart("prt_session_links", `Visit ${target} or \`${target}\` to see the result.`)]),
],
})
const markdown = page.locator('[data-component="markdown"]').filter({ hasText: `Visit ${target}` })
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
await expect(markdown.getByRole("button", { name: target })).toHaveCount(2)
await markdown
.getByRole("button", { name: target })
.filter({ has: page.locator("code") })
.press("Enter")
await expect(page).toHaveURL(`/server/${base64Encode(server)}/session/${target}`)
await expect(page.locator(`[data-titlebar-tab-link][href$="/session/${target}"]`)).toContainText("Linked session")
})
test("does not navigate to an ID that is absent from the current server", async ({ page }) => {
await setupTimeline(page, {
messages: [userMessage(), assistantMessage([textPart("prt_session_missing", `See ${missing}.`)])],
})
const markdown = page.locator('[data-component="markdown"]').filter({ hasText: `See ${missing}.` })
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
await markdown.getByRole("button", { name: missing }).click()
await expect(page.getByText("This session cannot be found")).toBeVisible()
await expect(page).toHaveURL(/\/session\/ses_timeline_stability$/)
})
@@ -37,7 +37,7 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
return (
url.pathname === endpoint &&
url.searchParams.get("location[directory]") === directory &&
(recover ? response.ok() : requests >= 3 && response.status() === 500)
(recover ? response.ok() : requests === 3 && response.status() === 500)
)
})
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
@@ -50,7 +50,7 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
await settled
await expect(prompt).toBeEditable()
await expect(prompt).toHaveText("Continue after reconnecting")
expect(requests).toBeGreaterThanOrEqual(recover ? 2 : 3)
expect(requests).toBe(recover ? 2 : 3)
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toHaveCount(0)
expect(recovery).toEqual([])
@@ -59,53 +59,6 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
}
}
for (const error of [
{ _tag: "FileNotFoundError", path: "/projects/current", message: "Unrelated file" },
{ _tag: "LocationNotFoundError", directory: "/projects/other", message: "Other location" },
undefined,
]) {
test(`does not recover from an unrelated 404 (${error?._tag ?? "no typed error"})`, async ({ page }) => {
const recovery = recoveryRequests(page)
const directory = "/projects/current"
const sessionID = "ses_location_unrelated_404"
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
provider: fixture.provider,
sessions: [{ id: sessionID, projectID: fixture.project.id, directory, title: "Unrelated error" }],
fileList: () => [],
pageMessages: () => ({
items: [{ id: "msg_saved", type: "user", text: "Continue in the current worktree", time: { created: 1 } }],
}),
})
await page.route("**/api/location?**", (route) => {
if (new URL(route.request().url()).searchParams.get("location[directory]") !== directory) return route.fallback()
return route.fulfill({
status: 404,
...(error ? { json: error } : { body: "" }),
headers: { "access-control-allow-origin": "*" },
})
})
const failure = page.waitForResponse((response) => {
const url = new URL(response.url())
return (
url.pathname === "/api/location" &&
url.searchParams.get("location[directory]") === directory &&
response.status() === 404
)
})
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
await failure
await expect(page.getByText("Continue in the current worktree", { exact: true })).toBeVisible()
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(prompt).toBeEditable()
await prompt.fill("Keep this draft")
await expect(prompt).toHaveText("Keep this draft")
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
expect(recovery).toEqual([])
})
}
test("follows a live session move while the agent catalog is still loading", async ({ page }) => {
const recovery = recoveryRequests(page)
const directory = "/projects/old-tree"
@@ -264,7 +217,7 @@ test("ignores an old failed location read after reconnecting", async ({ page })
await expect(prompt).toHaveText("Keep typing here")
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toHaveCount(0)
expect(requests).toBeGreaterThanOrEqual(2)
expect(requests).toBe(2)
expect(recovery).toEqual([])
})
@@ -1,330 +0,0 @@
import { expect, test } from "@playwright/test"
import { base64Encode } from "@opencode/util/encode"
import { fixture } from "../smoke/session-timeline.fixture"
import { mockOpenCodeServer } from "../utils/mock-server"
import { installSseTransport } from "../utils/sse-transport"
test("keeps a session in a removed worktree readable and movable", async ({ page }) => {
const missing = "/projects/removed-worktree"
const sessionDirectory = `${missing}/src`
const destination = fixture.directory
const sessionID = "ses_removed_worktree"
const session = {
id: sessionID,
projectID: fixture.project.id,
directory: sessionDirectory,
title: "Removed worktree",
}
const transport = await installSseTransport(page, { server: fixture.serverKey })
await mockOpenCodeServer(page, {
directory: destination,
project: fixture.project,
provider: fixture.provider,
sessions: [session],
fileList: () => [],
pageMessages: () => ({
items: [{ id: "msg_saved", type: "user", text: "Saved conversation in removed worktree", time: { created: 1 } }],
}),
})
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url())
if (url.searchParams.get("location[directory]") !== sessionDirectory) return route.fallback()
if (url.pathname === "/api/location")
return route.fulfill({
status: 404,
json: {
_tag: "LocationNotFoundError",
directory: sessionDirectory,
message: `Location not found: ${sessionDirectory}`,
},
headers: { "access-control-allow-origin": "*" },
})
if (!["/api/agent", "/api/provider", "/api/model", "/api/model/default"].includes(url.pathname))
return route.fallback()
return route.fulfill({
status: 500,
json: { _tag: "ServiceUnavailableError", message: "Unable to boot removed location" },
headers: { "access-control-allow-origin": "*" },
})
})
await page.route(`**/api/session/${sessionID}/move`, (route) => route.fulfill({ status: 204, body: "" }))
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`, { waitUntil: "domcontentloaded" })
await expect(page.getByText("Saved conversation in removed worktree", { exact: true })).toBeVisible()
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(page.getByRole("status")).toContainText("Session location unavailable")
await expect(page.getByRole("status")).toContainText(sessionDirectory)
await expect(prompt).toHaveCount(0)
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toBeEnabled()
await transport.waitForConnection()
await page.getByRole("button", { name: "Choose worktree", exact: true }).click()
const create = page.waitForRequest(
(request) => new URL(request.url()).pathname === "/api/worktree" && request.method() === "POST",
{ timeout: 10_000 },
)
const move = page.waitForRequest(
(request) => new URL(request.url()).pathname === `/api/session/${sessionID}/move` && request.method() === "POST",
)
await page.getByRole("menuitem", { name: "New worktree" }).click()
expect((await create).postDataJSON()).toMatchObject({ projectID: fixture.project.id, from: fixture.project.worktree })
const created = `${destination}/copy`
expect((await move).postDataJSON()).toMatchObject({ directory: created })
session.directory = created
await transport.send({
id: "evt_removed_worktree_moved",
type: "session.moved",
created: 2,
durable: { aggregateID: sessionID, seq: 1, version: 1 },
data: { sessionID, location: { directory: created }, projectID: fixture.project.id },
})
await expect(prompt).toBeEditable()
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
await expect(page.locator('[data-action="composer-model"]')).toContainText("Claude Opus 4.6")
await expect(page.getByText("Saved conversation in removed worktree", { exact: true })).toBeVisible()
})
test("preserves a draft when a worktree disappears and resumes after choosing a directory", async ({ page }) => {
const source = "/projects/draft-worktree"
const destination = "/projects/restored"
const sessionID = "ses_draft_recovery"
const session = { id: sessionID, projectID: fixture.project.id, directory: source, title: "Draft recovery" }
const transport = await installSseTransport(page, { server: fixture.serverKey })
let missing = false
await mockOpenCodeServer(page, {
directory: destination,
project: { ...fixture.project, worktree: destination },
provider: fixture.provider,
sessions: [session],
fileList: () => [],
pageMessages: () => ({
items: [{ id: "msg_draft", type: "user", text: "Saved draft history", time: { created: 1 } }],
}),
})
await page.route("**/api/location?**", (route) => {
const url = new URL(route.request().url())
if (url.searchParams.get("location[directory]") !== source || !missing) return route.fallback()
return route.fulfill({
status: 404,
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
headers: { "access-control-allow-origin": "*" },
})
})
let moves = 0
await page.route(`**/api/session/${sessionID}/move`, (route) => {
moves++
if (moves === 1)
return route.fulfill({
status: 400,
json: { _tag: "InvalidRequestError", message: "Destination is unavailable" },
headers: { "access-control-allow-origin": "*" },
})
return route.fulfill({ status: 204, body: "" })
})
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(prompt).toBeEditable()
await prompt.fill("A draft to keep after moving")
const connection = await transport.waitForConnection()
const missingResponse = page.waitForResponse((response) => {
const url = new URL(response.url())
return (
url.pathname === "/api/location" &&
url.searchParams.get("location[directory]") === source &&
response.status() === 404
)
})
missing = true
await transport.close()
await transport.waitForConnection({ after: connection.id })
await missingResponse
await expect(page.getByRole("status")).toContainText("Session location unavailable")
await expect(prompt).toHaveCount(0)
await expect(page.getByText("Saved draft history", { exact: true })).toBeVisible()
await page.getByRole("button", { name: "Choose directory", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Choose directory", exact: true })
await expect(dialog.getByRole("combobox")).toBeFocused()
await dialog.getByRole("combobox").fill(destination)
await dialog.getByRole("combobox").press("Enter")
await expect(dialog.locator(".directory-picker-selection")).toHaveText(destination)
const move = page.waitForRequest(
(request) => new URL(request.url()).pathname === `/api/session/${sessionID}/move` && request.method() === "POST",
)
await dialog.getByRole("button", { name: "Select folder", exact: true }).click()
expect((await move).postDataJSON()).toEqual({ directory: destination })
await expect(page.getByText("Failed to move session", { exact: true })).toBeVisible()
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toBeEnabled()
await expect(prompt).toHaveCount(0)
expect(moves).toBe(1)
await page.getByRole("button", { name: "Choose directory", exact: true }).click()
await expect(dialog.getByRole("combobox")).toBeFocused()
await dialog.getByRole("combobox").fill(destination)
await dialog.getByRole("combobox").press("Enter")
await expect(dialog.locator(".directory-picker-selection")).toHaveText(destination)
const secondMove = page.waitForRequest(
(request) => new URL(request.url()).pathname === `/api/session/${sessionID}/move` && request.method() === "POST",
)
await dialog.getByRole("button", { name: "Select folder", exact: true }).click()
expect((await secondMove).postDataJSON()).toEqual({ directory: destination })
expect(moves).toBe(2)
session.directory = destination
missing = false
await transport.send({
id: "evt_draft_recovery_moved",
type: "session.moved",
created: 2,
durable: { aggregateID: sessionID, seq: 1, version: 1 },
data: { sessionID, location: { directory: destination }, projectID: fixture.project.id },
})
await expect(prompt).toBeEditable()
await expect(prompt).toHaveText("A draft to keep after moving")
await expect(page.getByText("Saved draft history", { exact: true })).toBeVisible()
})
test("ignores a stale missing result after the session moves", async ({ page }) => {
const source = "/projects/old-worktree"
const destination = "/projects/new-worktree"
const sessionID = "ses_stale_location_read"
const session = { id: sessionID, projectID: fixture.project.id, directory: source, title: "Moving session" }
const requested = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
const transport = await installSseTransport(page, { server: fixture.serverKey })
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
provider: fixture.provider,
sessions: [session],
pageMessages: () => ({ items: [] }),
})
await page.route("**/api/location?**", async (route) => {
if (new URL(route.request().url()).searchParams.get("location[directory]") !== source) return route.fallback()
requested.resolve()
await release.promise
return route.fulfill({
status: 404,
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
headers: { "access-control-allow-origin": "*" },
})
})
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
await requested.promise
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(prompt).toBeEditable()
await prompt.fill("Draft in new worktree")
await transport.waitForConnection()
const next = page.waitForResponse((response) => {
const url = new URL(response.url())
return (
url.pathname === "/api/location" && url.searchParams.get("location[directory]") === destination && response.ok()
)
})
session.directory = destination
await transport.send({
id: "evt_stale_probe_moved",
type: "session.moved",
created: 2,
durable: { aggregateID: sessionID, seq: 1, version: 1 },
data: { sessionID, location: { directory: destination }, projectID: fixture.project.id },
})
await next
const old = page.waitForResponse((response) => {
const url = new URL(response.url())
return (
url.pathname === "/api/location" &&
url.searchParams.get("location[directory]") === source &&
response.status() === 404
)
})
release.resolve()
await old
await expect(prompt).toBeEditable()
await expect(prompt).toHaveText("Draft in new worktree")
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
})
test("moves a removed-worktree session into an existing worktree", async ({ page }) => {
const source = "/projects/deleted-worktree"
const destination = "/projects/existing-worktree"
const sessionID = "ses_existing_worktree"
const session = { id: sessionID, projectID: fixture.project.id, directory: source, title: "Existing worktree" }
const transport = await installSseTransport(page, { server: fixture.serverKey })
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: { ...fixture.project, sandboxes: [destination] },
provider: fixture.provider,
sessions: [session],
pageMessages: () => ({ items: [] }),
})
await page.route("**/api/location?**", (route) => {
if (new URL(route.request().url()).searchParams.get("location[directory]") !== source) return route.fallback()
return route.fulfill({
status: 404,
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
headers: { "access-control-allow-origin": "*" },
})
})
await page.route(`**/api/session/${sessionID}/move`, (route) => route.fulfill({ status: 204, body: "" }))
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
await expect(page.getByRole("status")).toContainText("Session location unavailable")
await transport.waitForConnection()
await page.getByRole("button", { name: "Choose worktree", exact: true }).click()
const option = page.getByRole("menuitem", { name: "existing-worktree", exact: true })
await expect(option).toBeVisible()
const move = page.waitForRequest(
(request) => new URL(request.url()).pathname === `/api/session/${sessionID}/move` && request.method() === "POST",
)
await option.click()
expect((await move).postDataJSON()).toEqual({ directory: destination })
session.directory = destination
await transport.send({
id: "evt_existing_worktree_moved",
type: "session.moved",
created: 2,
durable: { aggregateID: sessionID, seq: 1, version: 1 },
data: { sessionID, location: { directory: destination }, projectID: fixture.project.id },
})
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeEditable()
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
})
test("recovers a missing session directory without consulting the worktree inventory", async ({ page }) => {
const source = "/projects/unregistered-worktree"
const sessionID = "ses_unregistered_worktree"
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
provider: fixture.provider,
sessions: [{ id: sessionID, projectID: fixture.project.id, directory: source }],
pageMessages: () => ({
items: [{ id: "msg_saved", type: "user", text: "Keep this session", time: { created: 1 } }],
}),
})
const inventory: string[] = []
page.on("request", (request) => {
if (new URL(request.url()).pathname.startsWith("/api/worktree")) inventory.push(request.url())
})
await page.route("**/api/location?**", (route) => {
if (new URL(route.request().url()).searchParams.get("location[directory]") !== source) return route.fallback()
return route.fulfill({
status: 404,
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
headers: { "access-control-allow-origin": "*" },
})
})
const missing = page.waitForResponse((response) => {
const url = new URL(response.url())
return (
url.pathname === "/api/location" &&
url.searchParams.get("location[directory]") === source &&
response.status() === 404
)
})
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
await missing
await expect(page.getByText("Keep this session", { exact: true })).toBeVisible()
await expect(page.getByRole("status")).toContainText("Session location unavailable")
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toHaveCount(0)
expect(inventory).toEqual([])
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/app",
"version": "2.0.20",
"version": "2.0.19",
"description": "",
"type": "module",
"exports": {
-4
View File
@@ -30,10 +30,6 @@ export type ComposerControls = {
opened: () => boolean
open: () => void
}
/** Present in sessions with a desktop browser pane. */
browser?: {
reveal: (tabID: string, ref?: string) => void
}
}
}
@@ -1,41 +0,0 @@
import { describe, expect, test } from "bun:test"
import { commentContextItem, formatBrowserCommentNote, readPromptPresentation } from "./comment-note"
const browser = {
type: "browser" as const,
tabID: "tab_00000000-0000-4000-8000-000000000000",
url: "http://localhost:5173/",
element: { ref: "e42", selector: "#save", label: "button#save" },
comment: "Rename this",
}
describe("browser element comments", () => {
test("read from message metadata beside file comments and skip malformed entries", () => {
const value = readPromptPresentation({
displayText: "hi",
comments: [browser, { ...browser, element: { label: "button" } }, { path: "src/app.ts", comment: "Keep" }],
})
expect(value?.comments).toEqual([browser, { path: "src/app.ts", comment: "Keep" }])
})
test("explain a selector that crosses into a shadow root", () => {
expect(
formatBrowserCommentNote({ ...browser, element: { ...browser.element, selector: "#card >>> div > button" } }),
).toContain('selector "#card >>> div > button" (">>>" enters a shadow root)')
expect(formatBrowserCommentNote(browser)).not.toContain("shadow root")
})
test("leave out a selector that was too long to keep", () => {
expect(formatBrowserCommentNote({ ...browser, element: { ...browser.element, selector: "" } })).toBe(
'The user made the following comment regarding the "button#save" element in browser tab tab_00000000-0000-4000-8000-000000000000 at http://localhost:5173/ (browser ref @e42, usable as ref in any browser tool including browser.evaluate until the page navigates): Rename this',
)
})
test("return to the composer without their element ref", () => {
expect(commentContextItem(browser)).toEqual({
...browser,
element: { selector: "#save", label: "button#save" },
commentID: expect.any(String),
})
})
})
+2 -42
View File
@@ -1,18 +1,12 @@
import { Option, Schema } from "effect"
import type { FileSelection } from "@/workspaces/files/model"
import { BrowserComment, durableBrowserElement, type ContextItem } from "./schema"
export type PromptFileComment = {
type?: "file"
export type PromptComment = {
path: string
selection?: FileSelection
comment: string
preview?: string
origin?: "review" | "file"
}
export type PromptComment = PromptFileComment | BrowserComment
const decodeBrowserComment = Schema.decodeUnknownOption(BrowserComment)
/** An attachment the model receives as a path on the server rather than inline bytes. */
export type PromptAttachmentReference = {
@@ -36,7 +30,7 @@ function selection(selection: unknown) {
} satisfies FileSelection
}
export function createCommentMetadata(input: PromptFileComment) {
export function createCommentMetadata(input: PromptComment) {
return {
opencodeComment: {
path: input.path,
@@ -84,7 +78,6 @@ export function readPromptPresentation(value: unknown) {
}),
comments: comments.flatMap((item): PromptComment[] => {
if (!item || typeof item !== "object") return []
if ((item as { type?: unknown }).type === "browser") return Option.toArray(decodeBrowserComment(item))
const path = (item as { path?: unknown }).path
const comment = (item as { comment?: unknown }).comment
if (typeof path !== "string" || typeof comment !== "string") return []
@@ -107,39 +100,6 @@ export function formatAttachmentReference(input: PromptAttachmentReference) {
return `Attached file: \`${input.path}\``
}
export function formatBrowserCommentNote(input: BrowserComment) {
const element = input.element
// Page-provided strings are quoted so they read as data, not as part of the user's request.
const details = [
element.role ? `role ${element.role}` : undefined,
element.name ? `accessible name ${JSON.stringify(element.name)}` : undefined,
element.text && element.text !== element.name ? `text ${JSON.stringify(element.text.slice(0, 80))}` : undefined,
// A selector too long to keep is empty rather than cut into invalid syntax.
element.selector
? `selector ${JSON.stringify(element.selector)}${element.selector.includes(" >>> ") ? ' (">>>" enters a shadow root)' : ""}`
: undefined,
element.ref
? `browser ref @${element.ref}, usable as ref in any browser tool including browser.evaluate until the page navigates`
: undefined,
].filter((detail) => detail !== undefined)
return `The user made the following comment regarding the ${JSON.stringify(element.label)} element in browser tab ${input.tabID} at ${input.url}${details.length ? ` (${details.join("; ")})` : ""}: ${input.comment}`
}
/** Restores a sent comment to the composer, for example after a revert or fork. */
export function commentContextItem(comment: PromptComment): ContextItem {
// The message may predate the desktop process, so its element ref can no longer be trusted.
if (comment.type === "browser")
return { ...comment, element: durableBrowserElement(comment.element), commentID: crypto.randomUUID() }
return {
type: "file",
path: comment.path,
selection: comment.selection,
comment: comment.comment,
preview: comment.preview,
commentOrigin: comment.origin,
}
}
export function formatCommentNote(input: { path: string; selection?: FileSelection; comment: string }) {
const start = input.selection ? Math.min(input.selection.startLine, input.selection.endLine) : undefined
const end = input.selection ? Math.max(input.selection.startLine, input.selection.endLine) : undefined
@@ -279,39 +279,6 @@ export const MixedAttachments = {
),
}
export const BrowserElementComment = {
render: () => (
<ComposerStory
prompt={text("Tidy up the settings page")}
comments={[
{
type: "browser",
key: "browser:tab_story:c=save",
tabID: "tab_00000000-0000-4000-8000-000000000000",
url: "http://localhost:5173/settings",
title: "Settings",
element: {
ref: "e42",
selector: "#settings > form > button.btn.primary",
label: "button.btn.primary",
role: "button",
name: "Save changes",
},
comment: "Match the secondary button height",
commentID: "save",
},
{
type: "file",
key: "comment:src/app.tsx",
path: "src/app.tsx",
selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 },
comment: "Keep the normal flow flat",
},
]}
/>
),
}
export const ModelAndVariant = { render: () => <ComposerStory prompt={text("Compare both variants")} /> }
export const SlashSuggestions = { render: () => <ComposerStory suggestions="command" /> }
+2 -5
View File
@@ -533,11 +533,8 @@ export function ComposerAttachments(props: {
>
<CommentCard
comment={comment.comment ?? ""}
target={
comment.type === "browser"
? { type: "browser", element: comment.element.label }
: { type: "file", path: comment.path, selection: comment.selection }
}
path={comment.path}
selection={comment.selection}
active={comment.key === props.activeCommentID}
onClick={() => props.onCommentClick?.(comment)}
/>
+6 -12
View File
@@ -98,7 +98,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const byID = new Map(comments.all().map((item) => [`${item.file}\n${item.id}`, item] as const))
return prompt.context.items().flatMap((item) => {
const comment = item.comment?.trim()
if (!comment || item.type !== "file") return []
if (!comment) return []
const selection = item.commentID ? byID.get(`${item.path}\n${item.commentID}`)?.selection : undefined
const nextSelection =
selection ??
@@ -129,11 +129,9 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
time: item.time,
})),
)
// History records file comments only; browser comments stay with the draft while it is browsed.
prompt.context.replaceComments([
...prompt.context.items().filter((item) => item.type === "browser"),
...items.map((item) => ({
type: "file" as const,
prompt.context.replaceComments(
items.map((item) => ({
type: "file",
path: item.path,
selection: selectionFromLines(item.selection),
comment: item.comment,
@@ -141,7 +139,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
commentOrigin: item.origin,
preview: item.preview,
})),
])
)
}
const referenceDescription = (reference: ReferenceInfo) =>
@@ -300,7 +298,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
mention: { type: "file", path, content: `@${path}`, start: 0, end: 0 },
})),
onContextRemove(item) {
if (item.type === "file" && item.commentID) comments.remove(item.path, item.commentID)
if (item?.commentID) comments.remove(item.path, item.commentID)
},
openAttachment: (attachment) => {
if (attachment.type !== "image") return
@@ -310,10 +308,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
},
openContext(key) {
const item = controller.contextItem(key)
if (item?.type === "browser") {
adapter.controls().session.browser?.reveal(item.tabID, item.element.ref)
return
}
if (item) openComment(item, adapter.controls(), layout, files, comments)
},
onEditor(element) {
+1 -2
View File
@@ -28,7 +28,6 @@ export {
} from "./state"
export type {
AgentPart,
BrowserContextItem,
ContentPart,
ContextItem,
FileAttachmentPart,
@@ -161,7 +160,7 @@ export const { use: useComposerState, provider: ComposerPersistenceProvider } =
removeComment: (path: string, commentID: string) => session().context.removeComment(path, commentID),
updateComment: (path: string, commentID: string, next: Partial<FileContextItem> & { comment?: string }) =>
session().context.updateComment(path, commentID, next),
replaceComments: (items: ContextItem[]) => session().context.replaceComments(items),
replaceComments: (items: FileContextItem[]) => session().context.replaceComments(items),
},
set: (prompt: Prompt, cursorPosition?: number, scope?: PromptScope) => pick(scope).set(prompt, cursorPosition),
reset: (scope?: PromptScope) => pick(scope).reset(),
-51
View File
@@ -144,57 +144,6 @@ describe("buildPromptRequest", () => {
expect(result.files.some((file) => file.uri === "file:///repo/src/shared.ts")).toBe(true)
})
test("sends a browser element comment as a note the browser tools can act on", () => {
const result = buildPromptRequest({
prompt: [{ type: "text", content: "tidy up", start: 0, end: 7 }],
context: [
{
key: "browser:tab:c=1",
type: "browser",
tabID: "tab_00000000-0000-4000-8000-000000000000",
url: "http://localhost:5173/settings",
title: "Settings",
element: {
ref: "e42",
selector: "#settings > button.primary",
label: "button.primary",
role: "button",
name: "Save",
text: "Save",
},
comment: "Match @src/button.css",
commentID: "1",
},
],
images: [],
text: "tidy up",
sessionDirectory: "/repo",
})
expect(result.text).toBe(
'tidy up\nThe user made the following comment regarding the "button.primary" element in browser tab tab_00000000-0000-4000-8000-000000000000 at http://localhost:5173/settings (role button; accessible name "Save"; selector "#settings > button.primary"; browser ref @e42, usable as ref in any browser tool including browser.evaluate until the page navigates): Match @src/button.css',
)
expect(result.comments).toEqual([
{
type: "browser",
tabID: "tab_00000000-0000-4000-8000-000000000000",
url: "http://localhost:5173/settings",
title: "Settings",
element: {
ref: "e42",
selector: "#settings > button.primary",
label: "button.primary",
role: "button",
name: "Save",
text: "Save",
},
comment: "Match @src/button.css",
},
])
// A browser comment has no file of its own; only files it mentions are attached.
expect(result.files).toEqual([{ uri: "file:///repo/src/button.css", mime: "text/plain", name: "button.css" }])
})
test("handles Windows paths correctly (simulated on macOS)", () => {
const prompt: Prompt = [{ type: "file", path: "src\\foo.ts", content: "@src\\foo.ts", start: 0, end: 11 }]
+21 -35
View File
@@ -1,18 +1,9 @@
import { getFilename } from "@opencode/util/path"
import type { FileSelection } from "@/workspaces/files/model"
import { encodeFilePath } from "@/workspaces/files/path"
import type {
AgentPart,
ContextItem,
FileAttachmentPart,
ImageAttachmentPart,
PathAttachmentPart,
Prompt,
SkillPart,
} from "@/composer/state"
import type { AgentPart, FileAttachmentPart, ImageAttachmentPart, PathAttachmentPart, Prompt, SkillPart } from "@/composer/state"
import {
formatAttachmentReference,
formatBrowserCommentNote,
formatCommentNote,
type PromptAttachmentReference,
type PromptComment,
@@ -29,9 +20,20 @@ type PromptRequest = {
attachments: PromptAttachmentReference[]
}
type ContextFile = {
key: string
type: "file"
path: string
selection?: FileSelection
comment?: string
commentID?: string
commentOrigin?: "review" | "file"
preview?: string
}
type BuildPromptRequestInput = {
prompt: Prompt
context: (ContextItem & { key: string })[]
context: ContextFile[]
images: (Omit<ImageAttachmentPart, "blob"> & { dataUrl: string })[]
text: string
sessionDirectory: string
@@ -85,27 +87,7 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques
const used = new Set(files.map((file) => file.uri))
const comments: PromptComment[] = []
const mentioned = (comment: string) =>
parseCommentMentions(comment).flatMap((path) => {
const uri = `file://${encodeFilePath(absolute(input.sessionDirectory, path))}`
if (used.has(uri)) return []
used.add(uri)
return [{ uri, mime: "text/plain", name: getFilename(path) }]
})
const context = input.context.flatMap((item) => {
if (item.type === "browser") {
const comment = item.comment.trim()
if (!comment) return []
comments.push({
type: "browser",
tabID: item.tabID,
url: item.url,
...(item.title ? { title: item.title } : {}),
element: { ...item.element },
comment,
})
return mentioned(comment)
}
const path = absolute(input.sessionDirectory, item.path)
const uri = `file://${encodeFilePath(path)}${fileQuery(item.selection)}`
const comment = item.comment?.trim()
@@ -122,7 +104,13 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques
preview: item.preview,
origin: item.commentOrigin,
})
return [file, ...mentioned(comment)]
const mentions = parseCommentMentions(comment).flatMap((path) => {
const uri = `file://${encodeFilePath(absolute(input.sessionDirectory, path))}`
if (used.has(uri)) return []
used.add(uri)
return [{ uri, mime: "text/plain", name: getFilename(path) }]
})
return [file, ...mentions]
})
const inline = input.images.map((attachment) => ({
@@ -139,9 +127,7 @@ export function buildPromptRequest(input: BuildPromptRequestInput): PromptReques
text: [
...(input.text.trim() ? [input.text] : []),
...attachments.map(formatAttachmentReference),
...comments.map((comment) =>
comment.type === "browser" ? formatBrowserCommentNote(comment) : formatCommentNote(comment),
),
...comments.map(formatCommentNote),
].join("\n"),
displayText: input.text,
files: [...files, ...context, ...inline],
-22
View File
@@ -53,28 +53,6 @@ describe("composer persistence schemas", () => {
expect(decode({}).prompt).toEqual(DEFAULT_PROMPT)
})
test("restores browser element comments without the process-bound element ref", () => {
const decode = Schema.decodeUnknownSync(
Persistence.withInitial(ComposerStore, { prompt: DEFAULT_PROMPT, context: { items: [] } }),
)
const browser = {
type: "browser" as const,
tabID: "tab_00000000-0000-4000-8000-000000000000",
url: "http://localhost:5173/",
element: { ref: "e42", selector: "#save", label: "button#save", role: 42 },
comment: "Rename this",
commentID: "note",
}
const value = decode({ context: { items: [browser, { ...browser, url: null }] } })
expect(value.context.items).toEqual([
{
...browser,
element: { selector: "#save", label: "button#save" },
key: "browser:tab_00000000-0000-4000-8000-000000000000:c=note",
},
])
})
test("drops invalid parts without losing valid mentions or optional field recovery", () => {
const value = Schema.decodeUnknownSync(
Persistence.withInitial(ComposerStore, { prompt: DEFAULT_PROMPT, context: { items: [] } }),
+2 -57
View File
@@ -134,49 +134,9 @@ export const FileContextItem = Persistence.struct({
preview: Persistence.optional(Schema.String),
})
export type FileContextItem = typeof FileContextItem.Type
/** An element the user picked in a desktop browser tab. The ref is valid until the page navigates. */
export const BrowserElement = Persistence.struct({
ref: Persistence.optional(Schema.String),
selector: Schema.String,
label: Schema.String,
role: Persistence.optional(Schema.String),
name: Persistence.optional(Schema.String),
text: Persistence.optional(Schema.String),
})
export type BrowserElement = typeof BrowserElement.Type
/**
* A ref names an element only inside the desktop process that picked it; a later process can hand
* the same ref to another element. Anything that may outlive the pick keeps the description only.
*/
export function durableBrowserElement(element: BrowserElement): BrowserElement {
return {
selector: element.selector,
label: element.label,
...(element.role ? { role: element.role } : {}),
...(element.name ? { name: element.name } : {}),
...(element.text ? { text: element.text } : {}),
}
}
const BrowserCommentFields = {
type: Schema.Literal("browser"),
tabID: Schema.String,
url: Schema.String,
title: Persistence.optional(Schema.String),
element: BrowserElement,
comment: Schema.String,
}
/** A comment on a browser element as sent in message metadata. */
export const BrowserComment = Persistence.struct(BrowserCommentFields)
export type BrowserComment = typeof BrowserComment.Type
export const BrowserContextItem = Persistence.struct({ ...BrowserCommentFields, commentID: Schema.String })
export type BrowserContextItem = typeof BrowserContextItem.Type
export type ContextItem = FileContextItem | BrowserContextItem
export type ContextItem = FileContextItem
export function contextItemKey(item: ContextItem) {
if (item.type === "browser") return `browser:${item.tabID}:c=${item.commentID}`
const key = `${item.type}:${item.path}:${item.selection?.startLine}:${item.selection?.endLine}`
if (item.commentID) return `${key}:c=${item.commentID}`
const comment = item.comment?.trim()
@@ -185,27 +145,12 @@ export function contextItemKey(item: ContextItem) {
return `${key}:c=${digest.slice(0, 8)}`
}
const FileContextEntry = Schema.Struct({ ...FileContextItem.fields, key: Persistence.optional(Schema.String) }).pipe(
const ContextEntry = Schema.Struct({ ...FileContextItem.fields, key: Persistence.optional(Schema.String) }).pipe(
Schema.decodeTo(Persistence.struct({ ...FileContextItem.fields, key: Schema.String }).pipe(Schema.toType), {
decode: SchemaGetter.transform((item) => ({ ...item, key: contextItemKey(item) })),
encode: SchemaGetter.transform((item) => item),
}),
)
const BrowserContextEntry = Schema.Struct({
...BrowserContextItem.fields,
key: Persistence.optional(Schema.String),
}).pipe(
Schema.decodeTo(Persistence.struct({ ...BrowserContextItem.fields, key: Schema.String }).pipe(Schema.toType), {
// A stored draft can outlive the desktop process that picked the element.
decode: SchemaGetter.transform((item) => ({
...item,
element: durableBrowserElement(item.element),
key: contextItemKey(item),
})),
encode: SchemaGetter.transform((item) => item),
}),
)
const ContextEntry = Schema.Union([FileContextEntry, BrowserContextEntry])
export const DEFAULT_PROMPT: Prompt = [{ type: "text", content: "", start: 0, end: 0 }]
+1 -6
View File
@@ -12,11 +12,7 @@ import { cycleModelVariant, getConfiguredAgentVariant, resolveModelVariant } fro
import { useComposerState } from "./persistence"
import { useConfiguredModel } from "@/providers/models/configured"
export function createComposerControls(input: {
sessionKey: Accessor<string>
model?: ModelSelection
browser?: ComposerControls["session"]["browser"]
}) {
export function createComposerControls(input: { sessionKey: Accessor<string>; model?: ModelSelection }) {
const layout = useLayout()
const local = useLocal()
const sdk = useWorkspaceLocation()
@@ -44,7 +40,6 @@ export function createComposerControls(input: {
session: {
tabs: layout.tabs(input.sessionKey),
reviewPanel: view.reviewPanel,
browser: input.browser,
},
}
})
+2 -5
View File
@@ -17,9 +17,6 @@ import {
export { DEFAULT_PROMPT } from "./schema"
export type {
AgentPart,
BrowserComment,
BrowserContextItem,
BrowserElement,
ComposerStore,
ContentPart,
ContextItem,
@@ -41,7 +38,7 @@ type InitialPrompt = {
}
export function isCommentItem(item: ContextItem | (ContextItem & { key: string })) {
return !!item.comment?.trim()
return item.type === "file" && !!item.comment?.trim()
}
function createComposerActions(setStore: SetStoreFunction<ComposerStore>) {
@@ -140,7 +137,7 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti
)
clearRetry()
},
replaceComments(items: ContextItem[]) {
replaceComments(items: FileContextItem[]) {
setStore("context", "items", (current) => [
...current.filter((item) => !isCommentItem(item)),
...items.map((item) => ({ ...item, key: contextItemKey(item) })),
+26 -53
View File
@@ -1,7 +1,6 @@
import { SessionMessage } from "@opencode/schema/session-message"
import type { SessionMessageUser } from "@opencode/client/promise"
import type { Accessor } from "solid-js"
import type { PromptComment } from "./comment-note"
import type { PromptHistoryComment } from "./history/entry"
import type { ImageAttachmentPart, Prompt } from "./state"
import { clonePrompt, promptLength } from "./prompt-parts"
@@ -74,13 +73,10 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
const submission = createComposerSubmission({
target: input.adapter.state,
prompt,
context: input.adapter.state.context
.items()
.map((item) =>
item.type === "browser"
? { ...item, element: { ...item.element } }
: { ...item, selection: item.selection ? { ...item.selection } : undefined },
),
context: input.adapter.state.context.items().map((item) => ({
...item,
selection: item.selection ? { ...item.selection } : undefined,
})),
})
const read = readSubmission(input, submission.prompt, submission.context, text, options?.alternate ?? false)
if (!read) {
@@ -199,30 +195,19 @@ function handoffMessage(value: ComposerSubmission): SessionMessageUser {
attachments: value.prompt.flatMap((part) =>
part.type === "path" ? [{ name: part.filename, mime: part.mime, path: part.path }] : [],
),
comments: value.context.flatMap((item): PromptComment[] => {
const comment = item.comment?.trim()
if (!comment) return []
if (item.type === "browser")
return [
{
type: "browser",
tabID: item.tabID,
url: item.url,
...(item.title ? { title: item.title } : {}),
element: { ...item.element },
comment,
},
]
return [
{
path: item.path,
comment,
...(item.selection ? { selection: { ...item.selection } } : {}),
...(item.preview !== undefined ? { preview: item.preview } : {}),
...(item.commentOrigin ? { origin: item.commentOrigin } : {}),
},
]
}),
comments: value.context.flatMap((item) =>
item.comment?.trim()
? [
{
path: item.path,
comment: item.comment.trim(),
...(item.selection ? { selection: { ...item.selection } } : {}),
...(item.preview !== undefined ? { preview: item.preview } : {}),
...(item.commentOrigin ? { origin: item.commentOrigin } : {}),
},
]
: [],
),
agent: value.selection.agent,
model: {
...value.selection.model,
@@ -302,27 +287,15 @@ function restoreSubmission(
restored.target.context.replaceComments(
restored.context
.filter((item) => !!item.comment?.trim())
.map((item) =>
item.type === "browser"
? {
type: "browser",
tabID: item.tabID,
url: item.url,
title: item.title,
element: item.element,
comment: item.comment,
commentID: item.commentID,
}
: {
type: "file",
path: item.path,
selection: item.selection,
comment: item.comment,
commentID: item.commentID,
commentOrigin: item.commentOrigin,
preview: item.preview,
},
),
.map((item) => ({
type: "file",
path: item.path,
selection: item.selection,
comment: item.comment,
commentID: item.commentID,
commentOrigin: item.commentOrigin,
preview: item.preview,
})),
)
// A recovered follow-up changes the payload, so it must use a new admission ID.
if (value.mode === "normal" && restored.prompt === submission.prompt) {
-1
View File
@@ -5,7 +5,6 @@ export { loadLocaleDict, normalizeLocale, type Locale, useLanguage } from "./run
export { type FatalRendererErrorLog, type Platform, PlatformProvider } from "./runtime/platform/platform"
export type {
BrowserPaneCommand,
BrowserPaneElement,
BrowserPaneEndpoint,
BrowserPaneEvent,
BrowserPaneLayout,
-36
View File
@@ -445,42 +445,6 @@
}
}
@keyframes browser-comment-enter {
from {
opacity: 0;
}
}
@keyframes browser-comment-editor-enter {
from {
opacity: 0;
transform: translateY(4px) scale(0.98);
}
}
[data-component="browser-comment"] {
animation: browser-comment-enter 160ms cubic-bezier(0.215, 0.61, 0.355, 1);
}
/* Dim the frozen page around the picked element, whose DevTools highlight stays in the still. */
[data-component="browser-comment"] [data-slot="browser-comment-spotlight"] {
box-shadow:
0 0 0 1px var(--v2-border-border-focus),
0 0 0 100vmax color-mix(in srgb, var(--v2-overlay-simple-overlay-scrim) 50%, transparent);
}
[data-component="browser-comment"] [data-slot="browser-comment-editor"] {
animation: browser-comment-editor-enter 200ms cubic-bezier(0.215, 0.61, 0.355, 1);
transform-origin: top left;
}
@media (prefers-reduced-motion: reduce) {
[data-component="browser-comment"],
[data-component="browser-comment"] [data-slot="browser-comment-editor"] {
animation: none;
}
}
[data-slot="home-projects-scroll"] {
timeline-scope: --home-projects-scroll;
}
@@ -62,7 +62,6 @@ export function createComposerProjectControls(props: { draftId: string; worktree
return createMemo<PromptProjectControls>(() => ({
available: projects(),
directory: location().directory,
projectID: location().current?.project.id,
server: servers.list.length > 1 ? ServerConnection.key(projectServer()) : undefined,
select: selectProject,
add: addProject,
@@ -1,51 +0,0 @@
import { describe, expect, mock, test } from "bun:test"
import { createRoot } from "solid-js"
import type { PromptProjectControls } from "./selector"
mock.module("@/runtime/i18n/language", () => ({ useLanguage: () => ({ t: (key: string) => key }) }))
const { createPromptProjectController } = await import("./selector")
describe("new session project selection", () => {
test("shows the current project's appearance before its worktree inventory loads", () => {
const generic = { id: "other", worktree: "/other" }
const current = {
id: "current",
worktree: "/repo",
name: "My custom name",
icon: { override: "data:image/png;base64,AAAA" },
}
const controls: PromptProjectControls = {
available: [generic, current],
directory: "/repo/.opencode/worktree/feature",
projectID: "current",
select() {},
add() {},
}
createRoot((dispose) => {
const controller = createPromptProjectController({ controls: () => controls, onDone() {} })
expect(controller.selected()).toEqual(current)
dispose()
})
})
test("does not select a matching project ID from another server", () => {
const remote = { id: "shared", worktree: "/remote", server: { key: "remote", name: "Remote" } }
const local = { id: "shared", worktree: "/local", server: { key: "local", name: "Local" } }
const controls: PromptProjectControls = {
available: [remote, local],
directory: "/local/feature",
projectID: "shared",
server: "local",
select() {},
add() {},
}
createRoot((dispose) => {
const controller = createPromptProjectController({ controls: () => controls, onDone() {} })
expect(controller.selected()).toEqual(local)
dispose()
})
})
})
@@ -31,7 +31,6 @@ export type PromptProject = {
export type PromptProjectControls = {
available: PromptProject[]
directory: string
projectID?: string
server?: string
select: (worktree: string, server?: string) => void
add: (title: string, server?: string) => void
@@ -57,15 +56,14 @@ export function createPromptProjectController(input: {
let searchRef: HTMLInputElement | undefined
const current = () => {
const controls = input.controls()
const key = pathKey(controls.directory)
const projects = controls.available.filter((project) => !project.server || project.server.key === controls.server)
return (
projects.find(
const key = pathKey(input.controls().directory)
return input
.controls()
.available.find(
(project) =>
pathKey(project.worktree) === key || project.sandboxes?.some((sandbox) => pathKey(sandbox) === key),
) ?? projects.find((project) => controls.projectID && project.id === controls.projectID)
)
(!project.server || project.server.key === input.controls().server) &&
(pathKey(project.worktree) === key || project.sandboxes?.some((sandbox) => pathKey(sandbox) === key)),
)
}
const selected = () => current() ?? input.controls().available[0]
const projects = () => {
@@ -1,23 +0,0 @@
import { Button } from "@opencode/ui/button"
import { useDialog } from "@opencode/ui/context/dialog"
import { onMount } from "solid-js"
import { DialogChatGPTUsageLimit } from "./chatgpt-usage-limit"
function UsageLimitStory() {
const dialog = useDialog()
const open = () => dialog.show(() => <DialogChatGPTUsageLimit />)
onMount(open)
return (
<Button variant="neutral" onClick={open}>
Open ChatGPT usage limit
</Button>
)
}
export default {
title: "App/Dialogs/Connect Provider",
id: "app-dialog-chatgpt-usage-limit",
}
export const ChatGPTUsageLimit = { render: () => <UsageLimitStory /> }
@@ -1,48 +0,0 @@
import { Button } from "@opencode/ui/button"
import { useDialog } from "@opencode/ui/context/dialog"
import { Dialog, DialogTitle } from "@opencode/ui/dialog"
import { ProviderIcon } from "@opencode/ui/provider-icon"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
export function DialogChatGPTUsageLimit() {
const dialog = useDialog()
const language = useLanguage()
const platform = usePlatform()
return (
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),390px)] !rounded-xl">
<div class="flex w-full flex-col items-center px-8 pb-8 pt-9 text-center [font-family:var(--v2-font-family-sans)]">
<ProviderIcon id="openai" class="!size-12 text-v2-icon-icon-base" aria-hidden="true" />
<div class="mt-6 max-w-[270px] text-[20px] font-[530] leading-7 tracking-[-0.3px] text-v2-text-text-base">
<DialogTitle>
<bdi dir="auto">{language.t("provider.connect.chatgptUsageLimit.title")}</bdi>
</DialogTitle>
</div>
<p class="mt-3 text-[13px] leading-5 text-v2-text-text-muted">
<bdi dir="auto">{language.t("provider.connect.chatgptUsageLimit.description")}</bdi>
</p>
<Button
variant="contrast"
size="large"
class="mt-8 w-full"
autofocus
onClick={() => {
platform.openExternal("https://chatgpt.com/settings/usage")
dialog.close()
}}
>
{language.t("provider.connect.chatgptUsageLimit.manage")}
</Button>
<Button
variant="ghost"
size="large"
class="mt-2 w-full"
onClick={() => dialog.close()}
>
{language.t("provider.connect.chatgptUsageLimit.close")}
</Button>
</div>
</Dialog>
)
}
@@ -1,23 +0,0 @@
import { Button } from "@opencode/ui/button"
import { useDialog } from "@opencode/ui/context/dialog"
import { onMount } from "solid-js"
import { DialogChatGPTPlanWelcome } from "./chatgpt-welcome"
function WelcomeStory() {
const dialog = useDialog()
const open = () => dialog.show(() => <DialogChatGPTPlanWelcome />)
onMount(open)
return (
<Button variant="neutral" onClick={open}>
Open ChatGPT plan welcome
</Button>
)
}
export default {
title: "App/Dialogs/Connect Provider",
id: "app-dialog-chatgpt-welcome",
}
export const ChatGPTPlanWelcome = { render: () => <WelcomeStory /> }
@@ -1,37 +0,0 @@
import { Button } from "@opencode/ui/button"
import { useDialog } from "@opencode/ui/context/dialog"
import { Dialog, DialogTitle } from "@opencode/ui/dialog"
import { ProviderIcon } from "@opencode/ui/provider-icon"
import { useLanguage } from "@/runtime/i18n/language"
import { ExternalLink } from "@/runtime/platform/external-link"
export function DialogChatGPTPlanWelcome() {
const dialog = useDialog()
const language = useLanguage()
return (
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),390px)] !rounded-xl">
<div class="flex w-full flex-col items-center px-8 pb-8 pt-9 text-center [font-family:var(--v2-font-family-sans)]">
<ProviderIcon id="openai" class="!size-12 text-v2-icon-icon-base" aria-hidden="true" />
<div class="mt-6 max-w-[270px] text-[20px] font-[530] leading-7 tracking-[-0.3px] text-v2-text-text-base">
<DialogTitle>
<bdi dir="auto">{language.t("provider.connect.chatgptWelcome.title")}</bdi>
</DialogTitle>
</div>
<p class="mt-3 text-[13px] leading-5 text-v2-text-text-muted">
<bdi dir="auto">{language.t("provider.connect.chatgptWelcome.description")}</bdi>
</p>
<ExternalLink
href="https://chatgpt.com/settings/usage"
dir="auto"
class="mt-1 rounded-sm text-[13px] leading-5 text-v2-text-text-muted underline-offset-2 hover:text-v2-text-text-base focus-visible:outline focus-visible:outline-2"
>
{language.t("provider.connect.chatgptWelcome.usage")}
</ExternalLink>
<Button variant="contrast" size="large" class="mt-8 w-full" autofocus onClick={() => dialog.close()}>
{language.t("provider.connect.chatgptWelcome.confirm")}
</Button>
</div>
</Dialog>
)
}
+6 -29
View File
@@ -39,9 +39,6 @@ import { OpenCodeLogo } from "@/providers/opencode-logo"
import { decode64 } from "@/runtime/persistence/base64"
import { SettingsList } from "@/settings/list"
import { useTabs } from "@/shell/tabs/tabs"
import { Persist, persisted } from "@/runtime/persistence/storage"
import { Persistence } from "@/runtime/persistence/schema"
import { Schema } from "effect"
import {
CONSOLE_INTEGRATION,
CONSOLE_PROVIDERS,
@@ -51,7 +48,6 @@ import {
type ProviderConnectMethod,
} from "./controller"
import { ConsoleAuthorization } from "./console"
import { DialogChatGPTPlanWelcome } from "./chatgpt-welcome"
import { authServerName, RemoteAuthNotice } from "./remote"
import "./models.css"
@@ -85,15 +81,8 @@ export const DialogConnectProvider: Component<{
completed: false,
modelProvider: undefined as { id: string; name: string } | undefined,
authorization: false,
chatgptWelcome: false,
})
const language = useLanguage()
const dialog = useDialog()
const [welcome, setWelcome, , welcomeReady] = persisted(
Persist.global("chatgpt-plan-welcome.v1"),
Persistence.struct({ seen: Schema.Boolean }),
{ seen: false },
)
const reset = controller.reset
const back = { current: reset }
const consoleSelected = () => CONSOLE_PROVIDERS.has(controller.selected() ?? "")
@@ -123,11 +112,7 @@ export const DialogConnectProvider: Component<{
setBack={(handler) => (back.current = handler)}
selection={props.selection}
onDone={props.onDone ? () => setState("completed", true) : undefined}
onConnected={(methodID) => {
props.onConnected?.(provider)
if (provider === "openai" && methodID === "chatgpt-token-sharing")
setState("chatgptWelcome", true)
}}
onConnected={() => props.onConnected?.(provider)}
onFirstConnection={(provider) => setState("modelProvider", provider)}
onAuthorization={(authorization) => setState("authorization", authorization)}
/>
@@ -151,16 +136,9 @@ export const DialogConnectProvider: Component<{
: "!h-[min(calc(100vh_-_16px),512px)] !w-[min(calc(100vw_-_16px),640px)]"
}
onCloseAutoFocus={(event) => {
if (state.completed && props.onDone) {
event.preventDefault()
props.onDone()
}
if (!state.chatgptWelcome) return
void Promise.resolve(welcomeReady.promise).then(() => {
if (welcome.seen) return
setWelcome("seen", true)
void dialog.show(() => <DialogChatGPTPlanWelcome />)
})
if (!state.completed || !props.onDone) return
event.preventDefault()
props.onDone()
}}
class="[font-family:var(--v2-font-family-sans)] [&_[data-slot=dialog-header]]:!px-5 [&_[data-slot=dialog-header-title]]:!text-[15px] [&_[data-slot=dialog-header-title]]:!tracking-[-0.13px]"
classList={{
@@ -376,7 +354,7 @@ function ProviderConnection(props: {
setBack: (handler: () => void) => void
selection?: ModelSelection
onDone?: () => void
onConnected?: (methodID?: string) => void
onConnected?: () => void
onFirstConnection: (provider: { id: string; name: string }) => void
onAuthorization: (authorization: boolean) => void
}) {
@@ -423,8 +401,7 @@ function ProviderConnection(props: {
prepare: isConsole ? prepareConsoleCatalog : undefined,
pollInterval: isConsole ? 500 : undefined,
onComplete: () => {
const method = controller.currentMethod()
props.onConnected?.(method?.type === "oauth" ? method.id : undefined)
props.onConnected?.()
// The picker only lists the newest model per family by default, which hides most of
// what a new connection just unlocked. Show everything the connected integration offers.
global.models.show(
@@ -1,78 +0,0 @@
import { Button } from "@opencode/ui/button"
import { createSignal } from "solid-js"
import type { ModelSelection } from "./selection"
import { ModelSelectorPopoverView } from "./select-dialog"
const chatgpt = {
id: "gpt-5.6-sol",
providerID: "openai",
api: { id: "gpt-5.6-sol", url: "https://api.openai.com/v1", npm: "@opencode/ai/providers/openai" },
name: "GPT-5.6 Sol",
family: "gpt",
capabilities: {
temperature: true,
reasoning: true,
attachment: true,
toolcall: true,
input: { text: true, audio: false, image: true, video: false, pdf: false },
output: { text: true, audio: false, image: false, video: false, pdf: false },
interleaved: true,
},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: 400_000, output: 64_000 },
status: "active",
options: {},
headers: {},
release_date: "2026-09-01",
variants: {},
provider: {
id: "openai",
name: "OpenAI",
source: "custom",
env: [],
options: {},
models: {},
},
latest: true,
} satisfies NonNullable<ReturnType<ModelSelection["current"]>>
const models = [
chatgpt,
{
...chatgpt,
id: "gpt-5.6-terra",
api: { ...chatgpt.api, id: "gpt-5.6-terra" },
name: "GPT-5.6 Terra",
latest: false,
},
]
function SelectorStory(props: { plan: boolean }) {
const [current, setCurrent] = createSignal(models[0].id)
return (
<div class="flex min-h-[280px] items-end justify-center">
<ModelSelectorPopoverView
trigger={(trigger) => (
<Button {...trigger} variant="ghost-muted">
{models.find((model) => model.id === current())?.name}
</Button>
)}
models={(search) => models.filter((model) => model.name.toLowerCase().includes(search.toLowerCase()))}
groups={(items) => [{ category: "openai", items }]}
current={`openai:${current()}`}
chatgptPlan={props.plan}
select={(item) => setCurrent(item.id)}
onManage={() => undefined}
onClose={() => undefined}
/>
</div>
)
}
export default {
title: "App/Dialogs/Model Selector",
id: "app-dialog-model-selector",
}
export const ChatGPTPlan = { render: () => <SelectorStory plan /> }
export const ApiKey = { render: () => <SelectorStory plan={false} /> }
@@ -15,16 +15,13 @@ import { Menu } from "@opencode/ui/menu"
import { TextInput } from "@opencode/ui/text-input"
import { ModelTooltip } from "./tooltip"
import { useLanguage } from "@/runtime/i18n/language"
import { ExternalLink } from "@/runtime/platform/external-link"
import { useData } from "@/runtime/server/current"
import { useWorkspaceLocation } from "@/workspaces/location"
import { decode64 } from "@/runtime/persistence/base64"
import { handleDocumentSearchKeydown } from "@/shell/commands/search-keydown"
import { createMenuDismissController } from "@/shell/commands/menu-dismiss"
import { createEventListener } from "@solid-primitives/event-listener"
import { matchesModelSearch } from "./search"
import { SettingsList } from "@/settings/list"
import { CONSOLE_GROUP_KEY, consoleModelGroup, ProviderModelIcon, ProviderModelSections } from "@/providers/models/provider-group"
import { CONSOLE_GROUP_KEY, consoleModelGroup, ProviderModelSections } from "@/providers/models/provider-group"
import "@/settings/settings.css"
const isFree = (provider: string, cost: { input: number } | undefined) =>
@@ -221,21 +218,11 @@ export function ModelSelectorPopover(props: {
onClose?: () => void
}) {
const dialog = useDialog()
const data = useData()
const location = useWorkspaceLocation()
const controller = createModelSelectorController({
model: props.model,
provider: () => props.provider,
onSelect: () => props.onClose?.(),
})
const chatgptPlan = () => {
if (!controller.current()?.startsWith("openai:")) return false
const connection = data.location.integration
.list(location().ref)
?.find((integration) => integration.id === "openai")
?.connections[0]
return connection?.type === "credential" && connection.method === "oauth"
}
return (
<ModelSelectorPopoverView
@@ -243,7 +230,6 @@ export function ModelSelectorPopover(props: {
models={controller.models}
groups={controller.groups}
current={controller.current()}
chatgptPlan={chatgptPlan()}
select={controller.select}
onManage={() => {
void import("./manage").then((module) => {
@@ -295,12 +281,11 @@ function createModelSelectorController(input: {
}
}
export function ModelSelectorPopoverView(props: {
function ModelSelectorPopoverView(props: {
trigger: ModelSelectorTrigger
models: (search: string) => ModelItem[]
groups: (models: ModelItem[]) => { category: string; items: ModelItem[] }[]
current: string | undefined
chatgptPlan?: boolean
select: (item: ModelItem) => void
onManage: () => void
onClose: () => void
@@ -383,8 +368,7 @@ export function ModelSelectorPopoverView(props: {
<Menu.Portal>
<Menu.Content
ref={(element: HTMLDivElement) => (contentRef = element)}
class="w-[284px] max-w-[calc(100vw-16px)] overflow-hidden rounded-md border-0 bg-v2-background-bg-layer-01 !p-0 shadow-[var(--v2-elevation-floating)] focus:outline-none"
classList={{ "!w-[320px]": props.chatgptPlan }}
class="w-[284px] overflow-hidden rounded-md border-0 bg-v2-background-bg-layer-01 !p-0 shadow-[var(--v2-elevation-floating)] focus:outline-none"
onPointerDownOutside={dismiss.preventTriggerRestore}
onFocusOutside={dismiss.preventTriggerRestore}
onCloseAutoFocus={dismiss.onCloseAutoFocus}
@@ -521,20 +505,6 @@ export function ModelSelectorPopoverView(props: {
<span class="min-w-0 flex-1 truncate leading-5">{language.t("dialog.model.manage")}</span>
</Menu.Item>
</div>
<Show when={props.chatgptPlan}>
<div class="h-px bg-v2-border-border-muted" />
<div class="flex min-h-10 items-center gap-2 px-3 py-2 text-[13px] leading-5 text-v2-text-text-base">
<ProviderModelIcon provider={{ id: "openai", name: "OpenAI" }} class="shrink-0" />
<span class="min-w-0 flex-1 truncate">{language.t("dialog.model.chatgptPlan")}</span>
<ExternalLink
href="https://chatgpt.com/settings/usage"
class="flex shrink-0 items-center gap-1 rounded-sm text-v2-text-text-muted no-underline hover:text-v2-text-text-base focus-visible:outline focus-visible:outline-2"
>
{language.t("dialog.model.chatgptManageUsage")}
<Icon name="arrow-up-right" size="small" />
</ExternalLink>
</div>
</Show>
</Menu.Content>
</Menu.Portal>
</Menu>
-14
View File
@@ -111,7 +111,6 @@ export const dict = {
"command.file.open": "Open file",
"command.browser.open": "Open browser",
"command.browser.reload": "Reload browser page",
"command.browser.inspect": "Select an element in the browser page",
"command.tab.close": "Close tab",
"command.tab.reopenClosed": "Reopen closed tab",
"command.context.addSelection": "Add selection to context",
@@ -187,8 +186,6 @@ export const dict = {
"dialog.model.empty": "No model results",
"dialog.model.manage": "Manage models",
"dialog.model.manage.description": "Customize which models appear in the model selector.",
"dialog.model.chatgptPlan": "Using ChatGPT plan",
"dialog.model.chatgptManageUsage": "Manage usage",
"dialog.model.manage.provider.toggle": "Toggle all {{provider}} models",
"dialog.model.unpaid.freeModels.title": "Free models provided by OpenCode",
@@ -220,15 +217,7 @@ export const dict = {
"provider.connect.models.title": "Connected to {{provider}}",
"provider.connect.models.description": "Choose a model to start with. You can switch models anytime.",
"provider.connect.models.available": "Available models",
"provider.connect.chatgptWelcome.title": "ChatGPT connected",
"provider.connect.chatgptWelcome.description": "Eligible requests in OpenCode can use your ChatGPT plan.",
"provider.connect.chatgptWelcome.usage": "Manage usage in ChatGPT settings",
"provider.connect.chatgptWelcome.confirm": "Got it",
"provider.connect.models.list": "Models available from {{provider}}",
"provider.connect.chatgptUsageLimit.title": "ChatGPT usage limit reached",
"provider.connect.chatgptUsageLimit.description": "Check your usage and limits in ChatGPT settings.",
"provider.connect.chatgptUsageLimit.manage": "Manage usage",
"provider.connect.chatgptUsageLimit.close": "Close",
"provider.connect.console.refreshFailed":
"Your account is connected, but we couldn't load your models. Try again to refresh them.",
"provider.connect.console.connected": "OpenCode connected",
@@ -1023,9 +1012,6 @@ export const dict = {
"session.browser.unsupported": "This desktop app does not support the browser pane.",
"session.browser.suspended": "Browser suspended. Interact with this session to reconnect.",
"session.browser.address.placeholder": "Enter URL",
"session.browser.inspect": "Select an element to comment on",
"session.browser.inspect.active": "Click an element in the page to comment on it. Press Escape to cancel.",
"session.browser.inspect.pageShortcut": "While the page has focus",
"session.browser.empty.title": "Enter URL",
"session.browser.empty.description": 'Or prompt "Open in the app browser"',
"session.browser.failed.title": "URL can't be reached",
@@ -17,32 +17,16 @@ export type BrowserPaneLayout = {
export type BrowserPaneCommand = Browser.Action
export type BrowserPaneState = Browser.State | null
/** An element the user picked in the page. The ref stays valid for browser tools until the page navigates. */
export type BrowserPaneElement = {
ref: Browser.Ref
selector: string
label: string
role?: string
name?: string
text?: string
/** Border box in the native view's DIPs. */
rect: { x: number; y: number; width: number; height: number }
}
export type BrowserPaneEvent =
| { type: "focus"; tabID: Browser.TabID }
| { type: "preview"; path: string }
| { type: "state"; state: BrowserPaneState; error?: string }
| { type: "inspect"; tabID: Browser.TabID; active: boolean; element?: BrowserPaneElement }
export type BrowserPaneRegistration = {
setLayout(layout?: BrowserPaneLayout): void
command(command: BrowserPaneCommand): Promise<void>
/** Captures the shown page, or resolves null when nothing is on screen. */
capture(tabID: Browser.TabID): Promise<Blob | null>
/** Starts or stops the page's element picker; the page reports picks and exits as inspect events. */
inspect(tabID: Browser.TabID, enabled: boolean): void
/** Highlights a picked element briefly, or clears any highlight when ref is omitted. */
highlight(tabID: Browser.TabID, ref?: Browser.Ref): void
close(): void
}
@@ -2,8 +2,7 @@ import { batch, createEffect, createMemo, createRoot, getOwner, on, onCleanup, r
import { createStore, reconcile } from "solid-js/store"
import { createSimpleContext } from "@opencode/ui/context"
import { useLanguage } from "@/runtime/i18n/language"
import type { Browser } from "@opencode/plugin-browser/rpc"
import type { BrowserPaneCommand, BrowserPaneEvent } from "@/runtime/platform/browser-pane"
import type { BrowserPaneCommand } from "@/runtime/platform/browser-pane"
import { usePlatform } from "@/runtime/platform/platform"
import type { useServer } from "@/runtime/server/current"
import type { SessionStateKey } from "@/runtime/server/scope"
@@ -14,7 +13,6 @@ import { createEventListener } from "@solid-primitives/event-listener"
import { createBrowserConnection, type BrowserConnectionState } from "./connection"
type Server = ReturnType<typeof useServer>
type InspectEvent = Extract<BrowserPaneEvent, { type: "inspect" }>
export type BrowserAttachment = BrowserConnectionState
@@ -44,7 +42,6 @@ export const { use: useBrowserAttachments, provider: BrowserAttachmentsProvider
const [unsupported, setUnsupported] = createStore<Record<string, true | undefined>>({})
const live = new Map<string, Live>()
const preview = new Map<string, Set<(path: string) => void>>()
const inspect = new Map<string, Set<(event: InspectEvent) => void>>()
const key = (server: Server, sessionID: string) => `${server.key}\n${sessionID}`
const enabled = createMemo(() => !!platform.browserPane)
const close = (id: string) => {
@@ -113,7 +110,6 @@ export const { use: useBrowserAttachments, provider: BrowserAttachmentsProvider
})
},
preview: (path) => preview.get(id)?.forEach((listener) => listener(path)),
inspect: (event) => inspect.get(id)?.forEach((listener) => listener(event)),
change: (state) => {
if (state.error === "browser.pane.unsupported") {
setUnsupported(server.key, true)
@@ -156,34 +152,20 @@ export const { use: useBrowserAttachments, provider: BrowserAttachmentsProvider
},
/** Agent requests to show a file in this session's Review pane. */
onPreview(server: Server, sessionID: string, listener: (path: string) => void) {
return subscribe(preview, key(server, sessionID), listener)
},
/** The page's element picker starting, stopping, or picking an element. */
onInspect(server: Server, sessionID: string, listener: (event: InspectEvent) => void) {
return subscribe(inspect, key(server, sessionID), listener)
const id = key(server, sessionID)
const listeners = preview.get(id) ?? new Set()
listeners.add(listener)
preview.set(id, listeners)
return () => {
listeners.delete(listener)
if (!listeners.size) preview.delete(id)
}
},
command(server: Server, sessionID: string, command: BrowserPaneCommand) {
const connection = live.get(key(server, sessionID))?.connection
if (!connection) return Promise.reject(new Error("browser.pane.unavailable"))
return connection.command(command)
},
highlight(server: Server, sessionID: string, tabID: Browser.TabID, ref?: Browser.Ref) {
live.get(key(server, sessionID))?.connection.highlight(tabID, ref)
},
}
},
})
function subscribe<Value>(
listeners: Map<string, Set<(value: Value) => void>>,
id: string,
listener: (value: Value) => void,
) {
const set = listeners.get(id) ?? new Set()
set.add(listener)
listeners.set(id, set)
return () => {
set.delete(listener)
if (!set.size) listeners.delete(id)
}
}
@@ -29,14 +29,11 @@ function fixture() {
}[] = []
const endpoint = { url: "http://localhost:4096" }
const previews: string[] = []
const inspections: Extract<BrowserPaneEvent, { type: "inspect" }>[] = []
const highlights: (Browser.Ref | undefined)[] = []
const connection = createBrowserConnection({
target: () => ({ serverKey: "browser-test", sessionID: "ses_browser", endpoint: { ...endpoint } }),
change: (state) => states.push(state),
focus: () => {},
preview: (path) => previews.push(path),
inspect: (event) => inspections.push(event),
pane: {
register(target, emit) {
const call = { target, emit, closed: false, commands: [] as Browser.Action[] }
@@ -49,10 +46,6 @@ function fixture() {
async capture() {
return null
},
inspect() {},
highlight(_tabID, ref) {
highlights.push(ref)
},
close() {
call.closed = true
},
@@ -62,30 +55,9 @@ function fixture() {
})
connection.wake()
calls[0].emit({ type: "state", state: browser })
return { connection, calls, states, endpoint, previews, inspections, highlights }
return { connection, calls, states, endpoint, previews }
}
test("picked elements reach the session and highlights reach the page without touching connection state", () => {
const app = fixture()
try {
const before = app.states.length
const element = {
ref: Browser.Ref.make("e4"),
selector: "#save",
label: "button#save",
rect: { x: 1, y: 2, width: 3, height: 4 },
}
app.calls[0].emit({ type: "inspect", tabID, active: false, element })
expect(app.inspections).toEqual([{ type: "inspect", tabID, active: false, element }])
app.connection.highlight(tabID, element.ref)
app.connection.highlight(tabID)
expect(app.highlights).toEqual([element.ref, undefined])
expect(app.states).toHaveLength(before)
} finally {
app.connection.dispose()
}
})
test("preview requests reach the session without touching connection state", () => {
const app = fixture()
try {
@@ -1,5 +1,4 @@
import type {
BrowserPaneEvent,
BrowserPanePlatform,
BrowserPaneRegistration,
BrowserPaneState,
@@ -21,7 +20,6 @@ export function createBrowserConnection(input: {
change: (state: BrowserConnectionState) => void
focus: (tabID: Browser.TabID) => void
preview: (path: string) => void
inspect: (event: Extract<BrowserPaneEvent, { type: "inspect" }>) => void
}) {
const state: BrowserConnectionState = { browser: null, suspended: false }
let disposed = false
@@ -37,7 +35,6 @@ export function createBrowserConnection(input: {
if (disposed || state.registration !== registration) return
if (event.type === "focus") return input.focus(event.tabID)
if (event.type === "preview") return input.preview(event.path)
if (event.type === "inspect") return input.inspect(event)
if (event.error === "browser.pane.unsupported" || event.error === "browser.pane.replaced") {
blocked = true
registration.close()
@@ -75,9 +72,6 @@ export function createBrowserConnection(input: {
register()
return state.registration?.command(command) ?? Promise.reject(new Error("browser.pane.unavailable"))
},
highlight(tabID: Browser.TabID, ref?: Browser.Ref) {
state.registration?.highlight(tabID, ref)
},
dispose() {
disposed = true
clearTimeout(retry)
+1 -20
View File
@@ -2,7 +2,7 @@ import { batch, createEffect, createMemo, on } from "solid-js"
import type { Browser } from "@opencode/plugin-browser/rpc"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import type { BrowserPaneCommand, BrowserPaneEvent } from "@/runtime/platform/browser-pane"
import type { BrowserPaneCommand } from "@/runtime/platform/browser-pane"
import { useServer } from "@/runtime/server/current"
import { useCommand } from "@/shell/commands/command"
import type { SessionModel } from "../model"
@@ -120,24 +120,5 @@ export function createSessionBrowser(session: SessionModel) {
close: (tabID: Browser.TabID) => session.layout.tabs().close(sessionBrowserTab(tabID)),
open,
command,
onInspect(listener: (event: Extract<BrowserPaneEvent, { type: "inspect" }>) => void) {
const sessionID = session.identity.sessionID()
return sessionID ? attachments.onInspect(server, sessionID, listener) : () => undefined
},
/** Shows the browser tab that owns a picked element and flashes the element. */
reveal(tabID: string, ref?: string) {
const sessionID = session.identity.sessionID()
const tab = browserTabs().find((tab) => tab.id === tabID)
if (!sessionID || !tab) return
const view = session.layout.view()
if (!view.reviewPanel.opened()) view.reviewPanel.open()
session.layout.tabs().setActive(sessionBrowserTab(tab.id))
if (ref && isRef(ref)) attachments.highlight(server, sessionID, tab.id, ref)
},
}
}
// Stored comments keep refs as plain strings; this matches the desktop's ref format.
function isRef(value: string): value is Browser.Ref {
return /^e[1-9][0-9]*$/.test(value)
}
+5 -263
View File
@@ -1,36 +1,20 @@
import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { LineCommentEditor, type LineCommentEditorMention } from "@opencode/ui/line-comment"
import { Loader } from "@opencode/ui/loader"
import { Keybind } from "@opencode/ui/keybind"
import { Tooltip } from "@opencode/ui/tooltip"
import { useDialog } from "@opencode/ui/context/dialog"
import { createEventListener } from "@solid-primitives/event-listener"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { createEffect, For, on, onCleanup, Show, untrack } from "solid-js"
import { createEffect, For, on, onCleanup, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import type { BrowserPaneElement } from "@/runtime/platform/browser-pane"
import { usePlatform } from "@/runtime/platform/platform"
import { formatKeybindParts, useCommand } from "@/shell/commands/command"
import { useCommand } from "@/shell/commands/command"
import type { Browser } from "@opencode/plugin-browser/rpc"
import type { createSessionBrowser } from "./model"
/** A comment on an element the user picked in the page. The ref is absent once the page navigated. */
export type SessionBrowserComment = {
tabID: Browser.TabID
url: string
title: string
element: Omit<BrowserPaneElement, "rect" | "ref"> & { ref?: Browser.Ref }
comment: string
}
export function SessionBrowserPane(props: {
browser: ReturnType<typeof createSessionBrowser>
visible: boolean
onComment?: (comment: SessionBrowserComment) => void
mention?: LineCommentEditorMention
}) {
export function SessionBrowserPane(props: { browser: ReturnType<typeof createSessionBrowser>; visible: boolean }) {
const platform = usePlatform()
const language = useLanguage()
const dialog = useDialog()
@@ -49,91 +33,8 @@ export function SessionBrowserPane(props: {
visible: typeof document === "undefined" || document.visibilityState === "visible",
// A still of the page shown in the DOM while floating content covers the hidden native view.
snapshot: undefined as { tabID: Browser.TabID; url: string } | undefined,
// The tab whose element picker is on.
picking: undefined as Browser.TabID | undefined,
// A picked element awaiting its comment. The page stays frozen as a still until it closes.
comment: undefined as
| {
tabID: Browser.TabID
url: string
title: string
// The tab's navigation count at the pick; the element's ref dies when it changes.
generation: number
element: BrowserPaneElement
draft: string
}
| undefined,
size: { width: 0, height: 0 },
editorHeight: 0,
})
const empty = () => !address() && !state()?.loading && !store.navigating
const inspectable = () => !!props.onComment && !!address() && !failed() && !props.browser.suspended()
const picking = () => !!state() && store.picking === state()?.id
const setPicking = (tabID: Browser.TabID, enabled: boolean) => {
registration()?.inspect(tabID, enabled)
setStore("picking", enabled ? tabID : undefined)
}
const toggleInspect = () => {
const tab = state()
if (!tab || !inspectable()) return
if (store.comment) closeComment()
setPicking(tab.id, !picking())
}
const closeComment = () => {
const current = store.comment
if (!current) return
registration()?.highlight(current.tabID)
setStore("comment", undefined)
}
const submitComment = (value: string) => {
const current = store.comment
if (!current) return
const tab = state()
// The draft outlives a reload or agent navigation, but the ref no longer names anything.
const live = tab?.id === current.tabID && tab.generation === current.generation
props.onComment?.({
tabID: current.tabID,
url: current.url,
title: current.title,
element: {
...(live ? { ref: current.element.ref } : {}),
selector: current.element.selector,
label: current.element.label,
...(current.element.role ? { role: current.element.role } : {}),
...(current.element.name ? { name: current.element.name } : {}),
...(current.element.text ? { text: current.element.text } : {}),
},
comment: value,
})
closeComment()
}
// The picked element in surface pixels, and the editor anchored below it, above it, or over it.
const spotlight = () => {
const rect = store.comment?.element.rect
if (!rect) return
const zoom = platform.webviewZoom?.() ?? 1
return { x: rect.x / zoom, y: rect.y / zoom, width: rect.width / zoom, height: rect.height / zoom }
}
const placement = () => {
const rect = spotlight()
if (!rect) return
const gap = 8
const width = Math.max(0, Math.min(400, store.size.width - gap * 2))
// The editor scrolls rather than growing past the surface, so its actions stay reachable.
const maxHeight = Math.max(0, store.size.height - gap * 2)
// Until the editor has been measured once, assume its default three-row height.
const height = Math.min(store.editorHeight || 176, maxHeight)
const left = Math.min(Math.max(gap, rect.x), Math.max(gap, store.size.width - width - gap))
const below = rect.y + rect.height + gap
const above = rect.y - gap - height
const top =
below + height <= store.size.height - gap
? below
: above >= gap
? above
: Math.max(gap, store.size.height - height - gap)
return { left, top, width, maxHeight }
}
let surface: HTMLDivElement | undefined
let addressDisplay: HTMLDivElement | undefined
let frame: number | undefined
@@ -164,62 +65,8 @@ export function SessionBrowserPane(props: {
if (tab) props.browser.command({ type: "reload", tabID: tab.id })
},
},
// Ctrl+Shift+C copies in the terminal, so only the focused page claims it, as in Chromium.
{
id: "browser.inspect",
title: language.t("command.browser.inspect"),
category: language.t("command.category.view"),
disabled: !props.visible || !inspectable(),
onSelect: toggleInspect,
},
])
createEffect(() => {
onCleanup(
props.browser.onInspect((event) => {
if (event.active) {
setStore("picking", event.tabID)
return
}
if (store.picking === event.tabID) setStore("picking", undefined)
if (!event.element) return
const tab = state()
if (!props.onComment || tab?.id !== event.tabID || !props.visible || !store.visible) {
registration()?.highlight(event.tabID)
return
}
setStore("comment", {
tabID: tab.id,
url: tab.url,
title: tab.title,
generation: tab.generation,
element: event.element,
draft: "",
})
}),
)
})
// A picker or comment belongs to the page on screen; switching tabs or hiding the pane ends it.
createEffect(
on([() => state()?.id, () => props.visible && store.visible], ([id, shown]) => {
const tabID = untrack(() => store.picking)
if (tabID && (tabID !== id || !shown)) setPicking(tabID, false)
if (untrack(() => store.comment)?.tabID !== id) closeComment()
}),
)
// The page does not have focus while the picker waits for a hover, so Escape reaches the app.
createEventListener(
window,
"keydown",
(event) => {
if (event.key !== "Escape" || !store.picking) return
event.preventDefault()
event.stopPropagation()
setPicking(store.picking, false)
},
{ capture: true },
)
// The native page always paints above the DOM, so hide it while a floating
// menu, select, or popover overlaps it. Tooltips are excluded.
const covered = (rect: DOMRect) =>
@@ -282,8 +129,7 @@ export function SessionBrowserPane(props: {
// The desktop page hides blank and loading documents itself; only hide here
// while the pane shows its own empty or failed state over the surface.
const shown = props.visible && store.visible && !empty() && !failed() && !dialog.active
// A comment on a picked element freezes the page so its editor can float above it.
const cover = store.comment?.tabID === tab.id || covered(rect)
const cover = covered(rect)
if (shown && cover) freeze(tab.id)
if (!cover) thaw()
const visible = shown && !(cover && store.snapshot?.tabID === tab.id)
@@ -356,7 +202,6 @@ export function SessionBrowserPane(props: {
() => store.visible,
() => props.visible,
() => state()?.id,
() => store.comment?.tabID,
empty,
failed,
registration,
@@ -375,13 +220,7 @@ export function SessionBrowserPane(props: {
)
// ResizeObserver runs after layout in the same frame; measuring here instead of on the next
// animation frame keeps the native view in step with a pane drag.
createResizeObserver(
() => surface,
(rect) => {
measure()
setStore("size", { width: rect.width, height: rect.height })
},
)
createResizeObserver(() => surface, measure)
createEventListener(window, "resize", () => schedule(300))
// Floating content portals directly into <body>; keep measuring briefly so
// the positioner has settled before the overlap check runs.
@@ -451,39 +290,6 @@ export function SessionBrowserPane(props: {
}
/>
</Tooltip>
<Show when={props.onComment}>
<Tooltip
placement="top"
value={
<div class="flex flex-col gap-1">
<div class="flex items-center gap-2">
<span>{language.t("session.browser.inspect")}</span>
<Show when={command.keybindParts("browser.inspect").length > 0}>
<Keybind keys={command.keybindParts("browser.inspect")} variant="neutral" />
</Show>
</div>
{/* The page claims Chromium's picker chord itself; the app leaves it to the terminal. */}
<div class="flex items-center gap-2">
<span>{language.t("session.browser.inspect.pageShortcut")}</span>
<Keybind keys={formatKeybindParts("mod+shift+c", language.t)} variant="neutral" />
</div>
</div>
}
>
{/* The ghost variant sets the button color, so the active accent needs precedence over it. */}
<IconButton
{...button}
data-action="browser-inspect"
disabled={!inspectable()}
state={picking() ? "pressed" : undefined}
classList={{ "!text-v2-icon-icon-accent": picking() || !!store.comment }}
aria-pressed={picking()}
aria-label={language.t("session.browser.inspect")}
onClick={toggleInspect}
icon={<Icon name="select-element" size="small" />}
/>
</Tooltip>
</Show>
<form
dir="ltr"
class="relative min-w-0 flex-1 h-7 rounded-md hover:bg-v2-overlay-simple-overlay-hover focus-within:bg-v2-overlay-simple-overlay-hover text-12-regular"
@@ -572,71 +378,7 @@ export function SessionBrowserPane(props: {
{language.t("session.browser.suspended")}
</p>
</Show>
<Show when={store.comment?.tabID === state()?.id && store.comment}>
{(current) => (
<div
data-component="browser-comment"
class="absolute inset-0 z-10"
onPointerDown={(event) => {
// A click beside the editor dismisses it unless it would discard a draft.
if (event.target === event.currentTarget && !current().draft.trim()) closeComment()
}}
>
<Show when={spotlight()}>
{(rect) => (
<div
data-slot="browser-comment-spotlight"
class="pointer-events-none absolute rounded-[2px]"
style={{
left: `${rect().x}px`,
top: `${rect().y}px`,
width: `${rect().width}px`,
height: `${rect().height}px`,
}}
/>
)}
</Show>
<Show when={placement()}>
{(position) => (
<div
ref={(element) =>
createResizeObserver(element, (rect) => setStore("editorHeight", Math.ceil(rect.height)))
}
data-slot="browser-comment-editor"
data-prevent-autofocus
class="absolute overflow-y-auto rounded-[6px] shadow-[var(--v2-elevation-raised)]"
style={{
left: `${position().left}px`,
top: `${position().top}px`,
width: `${position().width}px`,
"max-height": `${position().maxHeight}px`,
}}
>
<LineCommentEditor
value={current().draft}
onInput={(value) => setStore("comment", "draft", value)}
onCancel={closeComment}
onSubmit={submitComment}
mention={props.mention}
selection={
<span class="flex min-w-0 items-center gap-1" dir="ltr">
<Icon name="select-element" size="small" class="shrink-0" />
<span class="min-w-0 truncate leading-[var(--line-height-tight)]">
{current().element.label}
</span>
</span>
}
/>
</div>
)}
</Show>
</div>
)}
</Show>
</div>
<p class="sr-only" role="status" aria-live="polite">
{picking() ? language.t("session.browser.inspect.active") : ""}
</p>
</aside>
)
}
@@ -9,7 +9,6 @@ import { showToast } from "@/shell/notifications/toast"
import { useLanguage } from "@/runtime/i18n/language"
import { useServerSDK } from "@/runtime/server/client"
import { base64Encode } from "@opencode/util/encode"
import { commentContextItem } from "@/composer/comment-note"
import { extractPromptComments, extractPromptFromMessage } from "@/composer/prompt"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useServer } from "@/runtime/server/current"
@@ -76,7 +75,16 @@ export const DialogFork: Component = () => {
dialog.close()
const target = prompt.capture({ dir, id: forked.id })
target.set(restored)
target.context.replaceComments(extractPromptComments(message).map(commentContextItem))
target.context.replaceComments(
extractPromptComments(message).map((comment) => ({
type: "file",
path: comment.path,
selection: comment.selection,
comment: comment.comment,
preview: comment.preview,
commentOrigin: comment.origin,
})),
)
navigate(sessionHref(server.key, forked.id))
})
.catch((err: unknown) => {
@@ -1,135 +0,0 @@
import { Button } from "@opencode/ui/button"
import { useDialog } from "@opencode/ui/context/dialog"
import { DockShell, DockTray } from "@opencode/ui/dock-surface"
import { Icon } from "@opencode/ui/icon"
import { Menu } from "@opencode/ui/menu"
import { getFilename } from "@opencode/util/path"
import { useMutation } from "@tanstack/solid-query"
import { createEffect, createResource, For, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import { useServerSDK } from "@/runtime/server/client"
import { useData } from "@/runtime/server/current"
import { showToast } from "@/shell/notifications/toast"
import { useDirectoryPicker } from "@/workspaces/selection/picker"
import { createWorktree } from "@/workspaces/create"
export type MissingLocation = { sessionID: string; projectID: string; directory: string }
export function SessionLocationMissing(props: MissingLocation) {
const language = useLanguage()
const sdk = useServerSDK()
const data = useData()
const dialog = useDialog()
const pickDirectory = useDirectoryPicker()
const [state, setState] = createStore({ restoreFocus: false, worktreesOpen: false })
const project = () => data.project.get(props.projectID)
const [worktrees] = createResource(
() => (state.worktreesOpen ? props.projectID : undefined),
async (projectID) => {
try {
await sdk.api.worktree.refresh({ projectID })
return await sdk.api.worktree.list({ projectID })
} catch {
showToast({ variant: "error", title: language.t("session.location.worktreesFailed") })
return []
}
},
{ initialValue: [] },
)
let button: HTMLButtonElement | undefined
const move = useMutation(() => ({
mutationFn: async (input: { sessionID: string; directory?: string }) => {
const current = project()
if (!current) throw new Error(language.t("workspace.move.failed"))
const destination =
input.directory ??
(await createWorktree({
api: sdk.api,
data,
directory: current.canonical,
project: { id: current.id, canonical: current.canonical, directory: current.canonical },
}))
await sdk.api.session.move({ sessionID: input.sessionID, directory: destination })
},
onError: (error) => {
setState("restoreFocus", true)
showToast({
variant: "error",
title: language.t("workspace.move.failed"),
description: error instanceof Error ? error.message : language.t("common.requestFailed"),
})
},
}))
createEffect(() => {
if (!state.restoreFocus || move.isPending || dialog.active) return
setState("restoreFocus", false)
button?.focus()
})
const choose = () => {
if (move.isPending) return
const sessionID = props.sessionID
pickDirectory({
server: sdk.server,
title: language.t("session.location.choose"),
onSelect: (result) => {
const directory = Array.isArray(result) ? result[0] : result
if (directory) move.mutate({ sessionID, directory })
if (!directory) setState("restoreFocus", true)
},
})
}
return (
<div data-component="session-location-missing">
<DockShell class="flex flex-col gap-2 p-3">
<div role="status" class="flex items-start gap-2 text-13-regular leading-[var(--line-height-base)]">
<Icon name="warning" class="shrink-0 text-icon-warning-base" />
<div class="min-w-0 flex flex-col gap-1">
<div class="font-medium text-text-strong">{language.t("session.location.unavailable")}</div>
<div class="break-all font-mono text-12-regular text-text-weak">{props.directory}</div>
<div class="text-text-base">{language.t("session.location.description")}</div>
</div>
</div>
</DockShell>
<DockTray class="flex flex-wrap justify-end gap-2 p-2">
<Show when={project()?.vcs === "git"}>
<Menu placement="top-end" onOpenChange={(open) => setState("worktreesOpen", open)}>
<Menu.Trigger as={Button} variant="neutral" disabled={move.isPending}>
{language.t("session.location.worktree")}
</Menu.Trigger>
<Menu.Portal>
<Menu.Content class="max-h-80 max-w-[calc(100vw-32px)] overflow-y-auto">
<Menu.Item onSelect={() => move.mutate({ sessionID: props.sessionID })} disabled={move.isPending}>
<Icon name="workspace-new" />
{language.t("workspace.new")}
</Menu.Item>
<Show when={worktrees.loading}>
<Menu.Item disabled>{language.t("common.loading")}</Menu.Item>
</Show>
<For each={worktrees.latest.filter((item) => item.strategy && item.directory !== props.directory)}>
{(worktree) => (
<Menu.Item
title={worktree.directory}
onSelect={() => move.mutate({ sessionID: props.sessionID, directory: worktree.directory })}
disabled={move.isPending}
>
<Icon name="workspace-isolated" />
<span class="truncate">{getFilename(worktree.directory)}</span>
</Menu.Item>
)}
</For>
</Menu.Content>
</Menu.Portal>
</Menu>
</Show>
<Button ref={button} variant="contrast" onClick={choose} disabled={move.isPending}>
{language.t(move.isPending ? "session.location.moving" : "session.location.choose")}
</Button>
</DockTray>
</div>
)
}
+13 -28
View File
@@ -4,7 +4,7 @@ import { useDialog } from "@opencode/ui/context/dialog"
import { isScrollKeyTarget, scrollKey, scrollKeyOwner } from "@opencode/ui/scroll-view"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useNavigate } from "@solidjs/router"
import { createEffect, createMemo, on, onMount, Show, type Accessor } from "solid-js"
import { createEffect, createMemo, on, onMount, type Accessor } from "solid-js"
import { Composer } from "@/composer/composer"
import { useComposerState } from "@/composer/persistence"
import { createComposerControls } from "@/composer/selection"
@@ -18,7 +18,6 @@ import { useWorkspaceLocation } from "@/workspaces/location"
import { requireServerKey, sessionHref } from "@/shell/routes/session"
import { useComposerCommands } from "@/composer/commands"
import { useSessionCommands } from "../commands/use-session-commands"
import type { createSessionBrowser } from "../browser/model"
import type { SessionModel } from "../model"
import type { SessionScreenLayout } from "../screen-layout"
import { syncPromptModel, syncSessionModel } from "../session-model-helpers"
@@ -29,14 +28,12 @@ import { createSessionComposerController, type SessionComposerController } from
import { SessionQueuePanel } from "./queue-panel"
import { resolveSessionComposerSelection } from "./selection"
import { createSessionRequestModel } from "../requests/model"
import { SessionLocationMissing, type MissingLocation } from "./location-missing"
export function createActiveSessionRegion(input: {
session: SessionModel
screen: SessionScreenLayout
timeline: SessionTimelineInteraction
visible: Accessor<boolean>
browser: Pick<ReturnType<typeof createSessionBrowser>, "reveal">
}) {
const command = useCommand()
const dialog = useDialog()
@@ -49,7 +46,6 @@ export function createActiveSessionRegion(input: {
const state = createSessionRequestModel()
const controls = createComposerControls({
sessionKey: input.session.identity.sessionKey,
browser: { reveal: input.browser.reveal },
})
let promptRef: HTMLDivElement | undefined
@@ -220,33 +216,22 @@ export type ActiveSessionRegionModel = ReturnType<typeof createActiveSessionRegi
export function ActiveSessionComposerRegion(props: {
model: SessionComposerController
suggestionBoundary: () => HTMLElement | undefined
missing?: Accessor<MissingLocation | undefined>
}) {
return (
<SessionComposerRegion
controller={{
...props.model.region,
showComposer: () => props.model.region.showComposer() || !!props.missing?.(),
}}
controller={props.model.region}
composer={
<Show
when={props.missing?.()}
fallback={
<div class="relative">
<SessionQueuePanel queue={props.model.queue} />
<div class="relative z-10">
<Composer
model={props.model.composer}
borderUnderlay
readOnly={props.model.queue.undoing()}
suggestionBoundary={props.suggestionBoundary}
/>
</div>
</div>
}
>
{(missing) => <SessionLocationMissing {...missing()} />}
</Show>
<div class="relative">
<SessionQueuePanel queue={props.model.queue} />
<div class="relative z-10">
<Composer
model={props.model.composer}
borderUnderlay
readOnly={props.model.queue.undoing()}
suggestionBoundary={props.suggestionBoundary}
/>
</div>
</div>
}
/>
)
@@ -29,7 +29,6 @@ import { SessionContextTab } from "@/session/files/session-context-tab"
import { SortableTab } from "@/session/files/tab"
import { OpenInAppButton } from "@/session/files/open-in-app-button"
import { useCommand } from "@/shell/commands/command"
import { useComposerState } from "@/composer/persistence"
import { useFile, type SelectedLineRange } from "@/workspaces/files/model"
import { useLanguage } from "@/runtime/i18n/language"
import { useLayout } from "@/shell/state/layout"
@@ -81,7 +80,6 @@ export function SessionSidePanel(props: {
const layout = useLayout()
const settings = useSettings()
const file = useFile()
const prompt = useComposerState()
const language = useLanguage()
const command = useCommand()
const sdk = useWorkspaceLocation()
@@ -616,10 +614,6 @@ export function SessionSidePanel(props: {
<SessionBrowserPane
browser={props.browser}
visible={reviewOpen() && isSessionBrowserTab(activeTab())}
mention={{ items: file.searchFilesAndDirectories }}
onComment={(comment) =>
prompt.context.add({ type: "browser", ...comment, commentID: crypto.randomUUID() })
}
/>
</div>
</Show>
+10 -2
View File
@@ -4,7 +4,6 @@ import { useData } from "@/runtime/server/current"
import { useServerSDK } from "@/runtime/server/client"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useLanguage } from "@/runtime/i18n/language"
import { commentContextItem } from "@/composer/comment-note"
import { extractPromptComments, extractPromptFromMessage } from "@/composer/prompt"
import { showToast } from "@/shell/notifications/toast"
import type { SessionModel } from "./model"
@@ -35,7 +34,16 @@ export function createSessionRevert(input: {
directory: location().directory,
}),
)
target.context.replaceComments(extractPromptComments(message).map(commentContextItem))
target.context.replaceComments(
extractPromptComments(message).map((comment) => ({
type: "file",
path: comment.path,
selection: comment.selection,
comment: comment.comment,
preview: comment.preview,
commentOrigin: comment.origin,
})),
)
}
const stage = async (message: SessionMessageUser, previous: SessionMessageUser | undefined) => {
+8 -46
View File
@@ -1,9 +1,7 @@
import { ErrorBoundary, createEffect, createMemo, onCleanup, Show, type ParentProps } from "solid-js"
import { createStore } from "solid-js/store"
import { ErrorBoundary, createEffect, createMemo, Show, type ParentProps } from "solid-js"
import { useParams } from "@solidjs/router"
import { DataProvider } from "@opencode/session-ui/context"
import { SessionUserMessage } from "@opencode/session-ui/message"
import { isLocationNotFoundError } from "@opencode/client/promise"
import { TextShimmer } from "@opencode/ui/text-shimmer"
import { CommentsProvider } from "@/composer/comments"
import { readPromptPresentation } from "@/composer/comment-note"
@@ -29,46 +27,13 @@ import { SessionErrorFallback } from "./route-error"
import { createSessionResolution } from "./session-resolution"
import { SessionScreen } from "./screen"
import { PreparingComposer } from "./preparing-composer"
import type { MissingLocation } from "./composer/location-missing"
export function TargetSessionRouteContent() {
const params = useParams<{ serverKey: string; id: string }>()
const data = useData()
const server = useServer()
const tabs = useTabs()
const [locationState, setLocationState] = createStore<{ missing?: MissingLocation }>({})
const directory = createMemo(() => data.session.get(params.id)?.location.directory)
createEffect(() => {
const session = data.session.get(params.id)
const directory = session?.location.directory
const project = session && data.project.get(session.projectID)
const connected = server.ctx.sdk.connection.status() === "connected"
setLocationState("missing", undefined)
if (!session || !directory || !project || !connected || directory === project.canonical) return
let stale = false
onCleanup(() => {
stale = true
})
void server.ctx.sdk.api.location.get({ location: { directory } }).then(
() => undefined,
(error) => {
if (
!stale &&
server.ctx.sdk.connection.status() === "connected" &&
isLocationNotFoundError(error) &&
error.directory === directory
)
setLocationState("missing", { sessionID: session.id, projectID: project.id, directory })
},
)
})
const missing = createMemo(() => {
const session = data.session.get(params.id)
const state = locationState.missing
if (!state || !session || session.id !== state.sessionID || session.location.directory !== state.directory) return
if (server.ctx.sdk.connection.status() !== "connected") return
return state
})
return (
<>
@@ -76,10 +41,7 @@ export function TargetSessionRouteContent() {
<ModelsProvider directory={directory}>
<TargetSessionSettingsCommand />
<SessionRouteErrorBoundary sessionID={params.id} serverKey={requireServerKey(params.serverKey)}>
<Show
when={tabs.pendingSession(server.key, params.id)}
fallback={<ResolvedTargetSessionRoute missing={missing} />}
>
<Show when={tabs.pendingSession(server.key, params.id)} fallback={<ResolvedTargetSessionRoute />}>
{(pending) => <PreparingSession sessionID={params.id} pending={pending()} />}
</Show>
</SessionRouteErrorBoundary>
@@ -149,7 +111,7 @@ function SessionRouteErrorBoundary(props: ParentProps<{ sessionID?: string; serv
)
}
function ResolvedTargetSessionRoute(props: { missing: () => MissingLocation | undefined }) {
function ResolvedTargetSessionRoute() {
const params = useParams<{ id: string }>()
const server = useServer()
const tabs = useTabs()
@@ -176,7 +138,7 @@ function ResolvedTargetSessionRoute(props: { missing: () => MissingLocation | un
{(value) => (
<LocationProvider directory={value}>
<SessionUIProvider directory={value()} server={server.key}>
<TargetSessionPage missing={props.missing} />
<TargetSessionPage />
</SessionUIProvider>
</LocationProvider>
)}
@@ -201,7 +163,7 @@ function SessionStatePanel(props: ParentProps) {
)
}
function TargetSessionPage(props: { missing: () => MissingLocation | undefined }) {
function TargetSessionPage() {
return (
// These providers select their scoped state reactively and retain bounded caches,
// so keep their owners alive while navigating between workspaces on this server.
@@ -209,7 +171,7 @@ function TargetSessionPage(props: { missing: () => MissingLocation | undefined }
<FileProvider>
<ComposerPersistenceProvider>
<CommentsProvider>
<SessionPage missing={props.missing} />
<SessionPage />
</CommentsProvider>
</ComposerPersistenceProvider>
</FileProvider>
@@ -217,9 +179,9 @@ function TargetSessionPage(props: { missing: () => MissingLocation | undefined }
)
}
function SessionPage(props: { missing: () => MissingLocation | undefined }) {
function SessionPage() {
const session = useSessionModel()
return <SessionScreen session={session} missing={props.missing} />
return <SessionScreen session={session} />
}
function MarkSessionNotificationsViewed(props: { sessionID: () => string | undefined }) {
+4 -13
View File
@@ -9,7 +9,6 @@ import {
createEffect,
createComputed,
on,
type Accessor,
} from "solid-js"
import { createStore } from "solid-js/store"
import { ResizeHandle } from "@opencode/ui/resize-handle"
@@ -37,7 +36,6 @@ import { createSessionBrowser } from "./browser/model"
import { createTimelineCache } from "./timeline/cache"
import { ArtifactMarkdownProvider, ArtifactOpenerProvider } from "./files/open-artifact"
import { createSessionBtw } from "./btw/model"
import type { MissingLocation } from "./composer/location-missing"
const SessionMobileFiles = lazy(async () => {
const { SessionMobileFiles } = await import("./files/session-mobile-files")
@@ -49,23 +47,19 @@ const SessionSummaryPanel = lazy(async () => {
return { default: SessionSummaryPanel }
})
export function SessionScreen(props: { session: SessionModel; missing?: Accessor<MissingLocation | undefined> }) {
export function SessionScreen(props: { session: SessionModel }) {
// The timeline cache captures its owner when created, so link handling must be provided above it.
const browser = createSessionBrowser(props.session)
return (
<ArtifactOpenerProvider session={props.session} browser={browser}>
<ArtifactMarkdownProvider>
<SessionScreenContent session={props.session} browser={browser} missing={props.missing} />
<SessionScreenContent session={props.session} browser={browser} />
</ArtifactMarkdownProvider>
</ArtifactOpenerProvider>
)
}
function SessionScreenContent(props: {
session: SessionModel
browser: ReturnType<typeof createSessionBrowser>
missing?: Accessor<MissingLocation | undefined>
}) {
function SessionScreenContent(props: { session: SessionModel; browser: ReturnType<typeof createSessionBrowser> }) {
const session = props.session
const browser = props.browser
const server = useServer()
@@ -184,7 +178,6 @@ function SessionScreenContent(props: {
screen,
timeline,
visible: conversationVisible,
browser,
})
useUsageExceededDialogs()
@@ -330,9 +323,7 @@ function SessionScreenContent(props: {
</div>
<Show when={composer.active()} keyed>
{(model) => (
<ActiveSessionComposerRegion model={model} suggestionBoundary={timeline.scroller} missing={props.missing} />
)}
{(model) => <ActiveSessionComposerRegion model={model} suggestionBoundary={timeline.scroller} />}
</Show>
</>
)
@@ -69,7 +69,7 @@ export function SessionWorkspaceMenu(props: {
api: sdk.api,
data,
directory: props.directory,
project: { id: props.project.id, canonical: props.project.worktree, directory: props.project.worktree },
project: data.location.info({ directory: props.directory })?.project,
})
: selection
if (!destination) return
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import { GoUpsellState, isChatGPTUsageLimit } from "./usage-exceeded-dialogs"
import { GoUpsellState } from "./usage-exceeded-dialogs"
import { Persistence } from "@/runtime/persistence/schema"
const decode = Schema.decodeUnknownSync(
@@ -38,31 +38,3 @@ describe("usage exceeded preferences", () => {
})
})
})
describe("ChatGPT usage limit", () => {
const message =
"ChatGPT usage limit reached. Try again after your allowance resets; check ChatGPT Settings → Usage for details."
test("detects the mapped message regardless of failure type", () => {
expect(
isChatGPTUsageLimit({
type: "provider.rate-limit",
message,
status: 429,
}),
).toBe(true)
expect(isChatGPTUsageLimit({ type: "provider.unknown", message })).toBe(true)
})
test("ignores other rate limits and similar messages", () => {
expect(isChatGPTUsageLimit({ type: "provider.rate-limit", message: "Rate limit exceeded", status: 429 })).toBe(
false,
)
expect(
isChatGPTUsageLimit({
type: "provider.rate-limit",
message: "ChatGPT usage limit reached",
}),
).toBe(false)
})
})
@@ -1,6 +1,6 @@
import { useWorkspaceLocation } from "@/workspaces/location"
import { Persist, persisted } from "@/runtime/persistence/storage"
import type { SessionStatus, SessionStepFailed } from "@opencode/client/promise"
import type { SessionStatus } from "@opencode/client/promise"
import { onCleanup } from "solid-js"
import { Schema } from "effect"
import { Persistence } from "@/runtime/persistence/schema"
@@ -14,14 +14,6 @@ const GO_UPSELL_ACCOUNT_RATE_LIMIT_LAST_SEEN_AT = "go_upsell_account_rate_limit_
const GO_UPSELL_ACCOUNT_RATE_LIMIT_DONT_SHOW = "go_upsell_account_rate_limit_dont_show"
const GO_UPSELL_WINDOW = 86_400_000 // 24 hrs
const GO_UPSELL_PROVIDERS = new Set(["opencode", "opencode-go"])
const CHATGPT_USAGE_LIMIT_WINDOW = 86_400_000 // 24 hrs
export function isChatGPTUsageLimit(error: SessionStepFailed["data"]["error"]) {
return (
error.message ===
"ChatGPT usage limit reached. Try again after your allowance resets; check ChatGPT Settings → Usage for details."
)
}
export const GoUpsellState = Persistence.struct({
[GO_UPSELL_FREE_TIER_LAST_SEEN_AT]: Schema.NullOr(Schema.Finite),
@@ -60,25 +52,6 @@ export function useUsageExceededDialogs() {
[GO_UPSELL_ACCOUNT_RATE_LIMIT_LAST_SEEN_AT]: null,
[GO_UPSELL_ACCOUNT_RATE_LIMIT_DONT_SHOW]: null,
})
const [chatgptUsageLimit, setChatGPTUsageLimit] = persisted(
Persist.global("chatgpt-usage-limit"),
Persistence.struct({ lastSeenAt: Schema.NullOr(Schema.Finite) }),
{ lastSeenAt: null },
)
onCleanup(
sdk().event.on("session.step.failed", (evt) => {
if (evt.data.sessionID !== params.id) return
if (!isChatGPTUsageLimit(evt.data.error) || dialog.active) return
if (chatgptUsageLimit.lastSeenAt && Date.now() - chatgptUsageLimit.lastSeenAt < CHATGPT_USAGE_LIMIT_WINDOW) return
void import("@/providers/connect/chatgpt-usage-limit").then((usage) => {
if (dialog.active) return
setChatGPTUsageLimit("lastSeenAt", Date.now())
dialog.show(() => <usage.DialogChatGPTUsageLimit />)
})
}),
)
onCleanup(
sdk().event.on("session.status", (evt) => {
@@ -1,94 +0,0 @@
import { afterAll, beforeAll, expect, mock, test } from "bun:test"
import { createRoot } from "solid-js"
import { createStore } from "solid-js/store"
import type { ServerSDK } from "@/runtime/server/client"
import type { Data } from "@opencode/client/solid"
import type { ServerConnection } from "@/runtime/server/registry"
import { ServerScope } from "@/runtime/server/scope"
import type { Tab } from "@/shell/tabs/tabs"
const server = "local\nhttp://localhost:4096" as ServerConnection.Key
const session = { id: "session-1", title: "Test session", location: { directory: "/project" } }
const alerts: string[] = []
const tabs: { store: Tab[] } = { store: [] }
let createServerNotificationState: typeof import("./notification").createServerNotificationState
let storage: typeof import("@/runtime/persistence/storage")
beforeAll(async () => {
storage = await import("@/runtime/persistence/storage")
const { sessionIDHasOpenTab } = await import("@/shell/tabs/tabs")
mock.module("@/runtime/platform/platform", () => ({
usePlatform: () => ({
platform: "web",
notify: async (title: string) => {
alerts.push(title)
},
}),
}))
mock.module("@/settings/model", () => ({
useSettings: () => ({
sounds: { agentEnabled: () => false, errorsEnabled: () => false },
notifications: { agent: () => true, errors: () => true },
}),
}))
mock.module("@/runtime/i18n/language", () => ({ useLanguage: () => ({ t: (key: string) => key }) }))
mock.module("@/shell/tabs/tabs", () => ({
useTabs: () => tabs,
sessionIDHasOpenTab,
}))
mock.module("@/runtime/persistence/storage", () => ({
...storage,
persisted: () => {
const [store, setStore] = createStore({ list: [] })
return [store, setStore, undefined, () => false]
},
}))
createServerNotificationState = (await import("./notification")).createServerNotificationState
})
afterAll(() => mock.module("@/runtime/persistence/storage", () => storage))
test.each([
["session.execution.succeeded", "notification.session.responseReady.title"],
["session.execution.failed", "notification.session.error.title"],
] as const)("system alert for %s requires an open session tab", async (type, title) => {
alerts.length = 0
tabs.store = [{ type: "session", server, sessionId: "another-session" }]
let listener: ((event: unknown) => void) | undefined
const dispose = createRoot((dispose) => {
const state = createServerNotificationState({
key: server,
sdk: {
scope: ServerScope.local,
event: {
listen: (fn: typeof listener) => {
listener = fn
return () => {}
},
},
} as unknown as ServerSDK,
data: { session: { get: () => session } } as unknown as Data,
coordinator: { system: async (_id: string, fn: () => Promise<void>) => fn() },
} as Parameters<typeof createServerNotificationState>[0])
return { dispose, state }
})
listener?.({
type,
id: "event-1",
data: { sessionID: session.id, error: { type: "api", message: "failed", status: 500 } },
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(dispose.state.session.all(session.id)).toHaveLength(1)
expect(alerts).toEqual([])
tabs.store = [{ type: "session", server, sessionId: session.id }]
listener?.({
type,
id: "event-2",
data: { sessionID: session.id, error: { type: "api", message: "failed", status: 500 } },
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(alerts).toEqual([title])
dispose.dispose()
})
@@ -228,8 +228,7 @@ export function createServerNotificationState(input: {
if (!session) return
if (session.parentID) return
const hasOpenTab = sessionIDHasOpenTab(tabs.store, input.key, sessionID)
if (hasOpenTab && settings.sounds.agentEnabled()) {
if (sessionIDHasOpenTab(tabs.store, input.key, sessionID) && settings.sounds.agentEnabled()) {
void input.coordinator.sound(`${input.key}\0${eventID}`, () => playSoundById(settings.sounds.agent()))
}
@@ -241,7 +240,7 @@ export function createServerNotificationState(input: {
session: sessionID,
})
if (hasOpenTab && settings.notifications.agent()) {
if (settings.notifications.agent()) {
void input.coordinator.system(`${input.key}\0${eventID}`, () =>
platform.notify(language.t("notification.session.responseReady.title"), session.title ?? sessionID, () =>
openNotificationSession(tabs, input.key, sessionID),
@@ -256,8 +255,7 @@ export function createServerNotificationState(input: {
if (meta.disposed) return
if (session?.parentID) return
const hasOpenTab = sessionIDHasOpenTab(tabs.store, input.key, sessionID)
if (hasOpenTab && settings.sounds.errorsEnabled()) {
if (sessionIDHasOpenTab(tabs.store, input.key, sessionID) && settings.sounds.errorsEnabled()) {
void input.coordinator.sound(`${input.key}\0${eventID}`, () => playSoundById(settings.sounds.errors()))
}
@@ -272,7 +270,7 @@ export function createServerNotificationState(input: {
const description =
session?.title ??
(typeof error === "string" ? error : language.t("notification.session.error.fallbackDescription"))
if (hasOpenTab && settings.notifications.errors()) {
if (settings.notifications.errors()) {
void input.coordinator.system(`${input.key}\0${eventID}`, () =>
platform.notify(language.t("notification.session.error.title"), description, () =>
openNotificationSession(tabs, input.key, sessionID),
@@ -10,8 +10,6 @@ import { useData } from "@/runtime/server/current"
import { useServerSDK } from "@/runtime/server/client"
import { useTabs } from "@/shell/tabs/tabs"
import { readLocalImage } from "@/runtime/server/image"
import { useLanguage } from "@/runtime/i18n/language"
import { showToast } from "@/shell/notifications/toast"
export function SessionUIProvider(
props: ParentProps<{
@@ -24,7 +22,6 @@ export function SessionUIProvider(
const data = useData()
const serverSDK = useServerSDK()
const tabs = useTabs()
const language = useLanguage()
const directory = () => props.directory
const readImage = createMemo<ReadMarkdownImage>(() => {
const dir = directory()
@@ -42,17 +39,6 @@ export function SessionUIProvider(
await data.session.sync(sessionID).catch(() => undefined)
navigate(href(sessionID))
}
const openReferencedSession = async (sessionID: string) => {
// The transcript may mention a session from another server (or one that was deleted).
// Resolve it on this server before touching tabs or the current route.
const session = await serverSDK.api.session.get({ sessionID }).catch(() => undefined)
if (!session || session.time.archived) {
showToast({ title: language.t("session.error.notFound") })
return
}
data.session.remember(session)
tabs.select(tabs.addSessionTab({ server: props.server, sessionId: session.id }))
}
const providers = useProviders(directory)
const sessionUIData = createMemo(() => ({
provider: providers.ready()
@@ -80,7 +66,7 @@ export function SessionUIProvider(
onNavigateToSession={navigateToSession}
onSessionHref={href}
>
<MarkdownProvider readImage={readImage()} openSession={openReferencedSession}>
<MarkdownProvider readImage={readImage()}>
<LocalProvider>{props.children}</LocalProvider>
</MarkdownProvider>
</DataProvider>
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/cli",
"version": "2.0.20",
"version": "2.0.19",
"type": "module",
"license": "MIT",
"bin": {
-20
View File
@@ -183,26 +183,6 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
),
},
}),
Spec.make("export", {
description: "print stored credentials, including secrets, as JSON",
params: {
...ServerParams,
target: Argument.string("target").pipe(
Argument.withDescription("Integration ID or name (exports every integration when omitted)"),
Argument.optional,
),
},
}),
Spec.make("import", {
description: "import credentials exported by auth export",
params: {
...ServerParams,
file: Argument.string("file").pipe(
Argument.withDescription("JSON file to import (reads stdin when omitted)"),
Argument.optional,
),
},
}),
Spec.make("switch", {
description: "switch the active account for an integration",
params: {
@@ -1,31 +0,0 @@
import { EOL } from "node:os"
import { Effect, Option } from "effect"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { createClient, loadIntegrations, request, resolveIntegration } from "./shared"
import { errorMessage } from "../../../util/error"
export default Runtime.handler(
Commands.commands.auth.commands.export,
Effect.fn("cli.auth.export")(
function* (input) {
const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })
const target = Option.getOrUndefined(input.target)
const integrationID = target ? (yield* resolveIntegration(yield* loadIntegrations(client), target)).id : undefined
const credentials = (yield* request((signal) => client.credential.list({ signal }))).filter(
(credential) => !integrationID || credential.integrationID === integrationID,
)
if (process.stdout.isTTY)
process.stderr.write(
"Warning: the output contains secrets; redirect it to a file or pipe it to auth import" + EOL,
)
process.stdout.write(JSON.stringify(credentials, null, 2) + EOL)
},
Effect.catch((error) =>
Effect.sync(() => {
process.stderr.write(errorMessage(error) + EOL)
process.exitCode = 1
}),
),
),
)
@@ -1,58 +0,0 @@
import { EOL } from "node:os"
import { isConflictError, type CredentialCreateInput } from "@opencode/client"
import { Credential } from "@opencode/schema/credential"
import { Effect, Option, Schema } from "effect"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { createClient, request } from "./shared"
import { errorMessage } from "../../../util/error"
import { readStdin } from "../../../util/io"
export default Runtime.handler(
Commands.commands.auth.commands.import,
Effect.fn("cli.auth.import")(
function* (input) {
const file = Option.getOrUndefined(input.file)
if (!file && process.stdin.isTTY)
return yield* Effect.fail(new Error("Pipe auth export output into stdin or pass a file to import"))
const text = yield* request(() => (file ? Bun.file(file).text() : readStdin()))
const credentials = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Credential.Entry)))(text)
const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })
const existing = yield* request((signal) => client.credential.list({ signal }))
const ids = new Set(existing.map((credential) => credential.id))
const integrations = new Set(existing.map((credential) => credential.integrationID))
const results = yield* Effect.forEach(credentials, (credential) => {
if (ids.has(credential.id)) return Effect.succeed(false)
return request((signal) =>
client.credential.create(
{
id: credential.id,
integrationID: credential.integrationID,
label: credential.label,
// Stored metadata is JSON, but the credential schema types it as unknown while the generated client expects JSON.
value: credential.value as CredentialCreateInput["value"],
// Keep the destination's current selections; only integrations new to it adopt the exported selection.
activate: credential.active && !integrations.has(credential.integrationID),
},
{ signal },
),
).pipe(
Effect.as(true),
Effect.catchIf(isConflictError, () => Effect.succeed(false)),
)
})
const imported = results.filter(Boolean).length
process.stderr.write(
`Imported ${imported} ${imported === 1 ? "credential" : "credentials"}` +
(results.length > imported ? `, skipped ${results.length - imported} already present` : "") +
EOL,
)
},
Effect.catch((error) =>
Effect.sync(() => {
process.stderr.write(errorMessage(error) + EOL)
process.exitCode = 1
}),
),
),
)
@@ -4,12 +4,12 @@ import { OpenCode } from "@opencode/client"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { Service } from "@opencode/client/effect/service"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
export default Runtime.handler(
Commands.commands.debug.commands.agents,
Effect.fn("cli.debug.agents")(function* () {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const response = yield* Effect.promise(() => client.agent.list({ location: { directory: process.cwd() } }))
process.stdout.write(
@@ -4,13 +4,13 @@ import { OpenCode } from "@opencode/client"
import { Service } from "@opencode/client/effect/service"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
import { redactConfig } from "./redact"
export default Runtime.handler(
Commands.commands.debug.commands.config,
Effect.fn("cli.debug.config")(function* () {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const entries = yield* Effect.promise(() => client.config.get({ location: { directory: process.cwd() } }))
process.stdout.write(JSON.stringify(redactConfig(entries), null, 2) + EOL)
@@ -4,7 +4,7 @@ import { OpenCode, type IntegrationInfo, type IntegrationOAuthMethod, type McpSe
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { Service } from "@opencode/client/effect/service"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
import { selectIntegration, type IntegrationChoice } from "../../../ui/integration-picker"
import { handlePromptErrors, prompt, requireInteractive } from "../../../ui/prompt"
import { answerForm } from "../auth/form"
@@ -21,7 +21,7 @@ export default Runtime.handler(
const authenticate = Effect.fn("cli.mcp.auth.run")(function* (name?: string) {
if (!name) yield* requireInteractive("Pass an MCP server name when running without an interactive terminal")
intro("Authenticate an MCP server")
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const integrations = yield* loadIntegrations(client)
const servers = yield* request((signal) => client.mcp.list({ location }, { signal }))
@@ -4,12 +4,12 @@ import { OpenCode, type McpServer } from "@opencode/client"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { Service } from "@opencode/client/effect/service"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
export default Runtime.handler(
Commands.commands.mcp.commands.list,
Effect.fn("cli.mcp.list")(function* () {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const response = yield* Effect.promise(() => client.mcp.list({ location: { directory: process.cwd() } }))
const servers = response.data.toSorted((a, b) => a.name.localeCompare(b.name))
@@ -4,7 +4,7 @@ import { OpenCode } from "@opencode/client"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { Service } from "@opencode/client/effect/service"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
import { resolveIntegration } from "./resolve"
const location = { directory: process.cwd() }
@@ -12,7 +12,7 @@ const location = { directory: process.cwd() }
export default Runtime.handler(
Commands.commands.mcp.commands.logout,
Effect.fn("cli.mcp.logout")(function* (input) {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const integration = yield* resolveIntegration(client, input.name, location)
@@ -10,10 +10,6 @@ import { ServiceConfig } from "../../services/service-config"
export default Runtime.handler(
Commands.commands.pair,
Effect.fn("cli.pair")(function* (input: Runtime.Input<typeof Commands.commands.pair>) {
if ((yield* ServiceConfig.read()).disabled === true)
return yield* Effect.fail(
new Error("Pairing requires the background service; run `opencode service unset disabled` first"),
)
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const urls = Option.isSome(input.url)
@@ -4,7 +4,7 @@ import { OpenCode, type PluginInfo } from "@opencode/client"
import { Service } from "@opencode/client/effect/service"
import { Npm } from "@opencode/util/npm"
import { Config } from "../../../config"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
export interface Item {
readonly runtime: "Server" | "TUI"
@@ -16,7 +16,7 @@ export interface Item {
}
export const inspect = Effect.fn("cli.plugin.inspect")(function* (selected?: string) {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const location = { directory: process.cwd() }
const listed = yield* Effect.promise(() => client.plugin.list({ location }))
@@ -5,7 +5,7 @@ import { OpenCode, type PluginInfo } from "@opencode/client"
import { Service } from "@opencode/client/effect/service"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
import { Config } from "../../../config"
import { Global } from "@opencode/util/global"
import { Npm } from "@opencode/util/npm"
@@ -16,7 +16,7 @@ import { discoverPluginTargets, localPluginDirectories, localSource } from "@ope
export default Runtime.handler(
Commands.commands.plugin.commands.list,
Effect.fn("cli.plugin.list")(function* (input) {
const { endpoint } = yield* ServerConnection.resolve()
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const response = yield* Effect.promise(() => client.plugin.list({ location: { directory: process.cwd() } }))
const config = yield* Config.Service
-2
View File
@@ -31,8 +31,6 @@ const Handlers = Runtime.handlers(Commands, {
list: () => import("./commands/handlers/auth/list"),
login: () => import("./commands/handlers/auth/login"),
logout: () => import("./commands/handlers/auth/logout"),
export: () => import("./commands/handlers/auth/export"),
import: () => import("./commands/handlers/auth/import"),
switch: () => import("./commands/handlers/auth/switch"),
},
debug: {
+7 -35
View File
@@ -67,9 +67,6 @@ type FormRequest = Extract<V2Event, { type: "form.created" }>["data"]["form"]
// attached client must not cancel input that may belong to another session.
const GLOBAL_FORM_SESSION_ID = "global"
const PERMISSION_REJECTED_FEEDBACK =
"This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action."
export async function runNonInteractivePrompt(input: Input) {
const controller = new AbortController()
const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
@@ -135,34 +132,10 @@ export async function runNonInteractivePrompt(input: Input) {
}
}
// Subagents run in child sessions; their asks and questions belong to this run too. Other
// sessions on a shared server (e.g. the TUI's) must be left alone.
const owned = new Map<string, Promise<boolean>>([[input.sessionID, Promise.resolve(true)]])
const ownsSession = (sessionID: string): Promise<boolean> => {
const known = owned.get(sessionID)
if (known) return known
const result =
sessionID === GLOBAL_FORM_SESSION_ID
? Promise.resolve(false)
: input.client.session
.get({ sessionID })
.then((session) => (session.parentID ? ownsSession(session.parentID) : false))
.catch(() => false)
owned.set(sessionID, result)
return result
}
const replyPermission = async (request: {
id: string
sessionID: string
action: string
resources: ReadonlyArray<string>
}) => {
// Nobody can approve here. Outside V1 compatibility, reject with feedback so the tool fails
// as ordinary model-visible output and the model continues without the action.
const continuing = !input.auto && input.compatibility !== "v1"
const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {
if (!input.auto) {
if (!continuing) permissionRejected = true
permissionRejected = true
if (input.compatibility !== "v1") process.exitCode = 1
UI.println(
UI.Style.TEXT_WARNING_BOLD + "!",
UI.Style.TEXT_NORMAL +
@@ -171,13 +144,12 @@ export async function runNonInteractivePrompt(input: Input) {
}
await input.client.permission
.reply({
sessionID: request.sessionID,
sessionID: input.sessionID,
requestID: request.id,
decision: input.auto ? "once" : "reject",
...(continuing ? { message: PERMISSION_REJECTED_FEEDBACK } : {}),
})
.catch(() => {})
if (!input.auto && !continuing) {
if (!input.auto) {
await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})
}
}
@@ -207,14 +179,14 @@ export async function runNonInteractivePrompt(input: Input) {
}
const event = next.value
if (event.type === "permission.asked" && submitted && (await ownsSession(event.data.sessionID))) {
if (event.type === "permission.asked" && submitted && event.data.sessionID === input.sessionID) {
await replyPermission(event.data)
continue
}
if (
event.type === "form.created" &&
submitted &&
((await ownsSession(event.data.form.sessionID)) ||
(event.data.form.sessionID === input.sessionID ||
(!input.attached &&
event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&
sameLocation(event.location, input.location)))
@@ -18,7 +18,7 @@ export type Resolved = {
readonly service?: ReturnType<typeof managedService>
}
export const resolve = Effect.fn("cli.server-connection.resolve")(function* (args: Args = {}) {
export const resolve = Effect.fn("cli.server-connection.resolve")(function* (args: Args) {
if (args.server !== undefined && args.standalone)
return yield* Effect.fail(new Error("--server and --standalone cannot be combined"))
if (args.server !== undefined) {
@@ -38,7 +38,7 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
)
return { endpoint } satisfies Resolved
}
if (args.standalone || (yield* ServiceConfig.read()).disabled === true) {
if (args.standalone) {
return { endpoint: yield* Standalone.start() } satisfies Resolved
}
+2 -25
View File
@@ -12,7 +12,6 @@ import { selfCommand } from "../util/process"
// registration file (by channel), which version, and how to spawn opencode.
export const Info = Schema.Struct({
disabled: Schema.optional(Schema.Boolean),
hostname: Schema.optional(Schema.String),
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),
password: Schema.optional(Schema.String),
@@ -21,7 +20,7 @@ export const Info = Schema.Struct({
})
export type Info = typeof Info.Type
const keys = ["disabled", "hostname", "port", "password", "cors", "env"] as const
const keys = ["hostname", "port", "password", "cors", "env"] as const
type Key = (typeof keys)[number]
const decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
@@ -79,15 +78,7 @@ export const migrateConfig = Effect.fnUntraced(function* (legacy: string, file:
})
function configKey(key: string): Key {
if (
key === "disabled" ||
key === "hostname" ||
key === "port" ||
key === "password" ||
key === "cors" ||
key === "env"
)
return key
if (key === "hostname" || key === "port" || key === "password" || key === "cors" || key === "env") return key
throw new Error(`Unknown service config key: ${key}`)
}
@@ -160,9 +151,6 @@ export const get = Effect.fn("cli.service-config.get")(function* (key?: string,
const selected = configKey(key)
if (selected !== "env" && name !== undefined) throw new Error(`Usage: opencode service get ${selected}`)
switch (selected) {
case "disabled": {
return String((yield* read()).disabled ?? false)
}
case "hostname": {
return (yield* read()).hostname ?? ""
}
@@ -189,12 +177,6 @@ export const set = Effect.fn("cli.service-config.set")(function* (key: string, v
if (selected !== "env" && nestedValue !== undefined)
throw new Error(`Usage: opencode service set ${selected} <value>`)
switch (selected) {
case "disabled": {
if (value !== "true" && value !== "false") throw new Error("Disabled must be true or false")
if (value === "true") yield* Service.stop(yield* options())
yield* write({ ...(yield* read()), disabled: value === "true" })
return
}
case "hostname": {
yield* Service.stop(yield* options())
yield* write({ ...(yield* read()), hostname: value })
@@ -239,11 +221,6 @@ export const unset = Effect.fn("cli.service-config.unset")(function* (key: strin
const selected = configKey(key)
if (selected !== "env" && name !== undefined) throw new Error(`Usage: opencode service unset ${selected}`)
switch (selected) {
case "disabled": {
const { disabled: _disabled, ...next } = yield* read()
yield* write(next)
return
}
case "hostname": {
yield* Service.stop(yield* options())
const { hostname: _hostname, ...next } = yield* read()
+1 -1
View File
@@ -38,7 +38,7 @@ test("resolution groups Effect-native lifecycle operations only for the managed
pid: process.pid,
}),
)
const resolved = await runPromise(ServerConnection.resolve())
const resolved = await runPromise(ServerConnection.resolve({}))
expect(resolved.endpoint.url).toBe(server.url.toString())
expect(resolved.service).toBeDefined()
+1 -19
View File
@@ -3,7 +3,7 @@ import { Service, type Info } from "@opencode/client/effect/service"
import { Global } from "@opencode/util/global"
import { OPENCODE_VERSION } from "../src/version"
import { expect, test } from "bun:test"
import { Effect, FileSystem, Schema } from "effect"
import { Effect, Schema } from "effect"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
@@ -21,24 +21,6 @@ test("managed service ports are stable per installation channel", () => {
expect(ServiceConfig.defaultPort("preview-a")).not.toBe(ServiceConfig.defaultPort("preview-b"))
})
test("service disabled accepts only booleans without changing configuration on invalid input", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-disabled-config-"))
const layer = Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })
const run = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem>) =>
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer)))
try {
expect(await run(ServiceConfig.get("disabled"))).toBe("false")
await expect(run(ServiceConfig.set("disabled", "yes"))).rejects.toThrow("Disabled must be true or false")
expect(await run(ServiceConfig.read())).toEqual({})
await run(ServiceConfig.set("disabled", "true"))
expect(await run(ServiceConfig.read())).toEqual({ disabled: true })
await run(ServiceConfig.unset("disabled"))
expect(await run(ServiceConfig.read())).toEqual({})
} finally {
await fs.rm(root, { recursive: true, force: true })
}
})
test("local channel stores service config with the local service filename", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-"))
try {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/client",
"version": "2.0.20",
"version": "2.0.19",
"type": "module",
"license": "MIT",
"repository": {
+5 -47
View File
@@ -710,12 +710,7 @@ export type SessionLogOutput =
| undefined
readonly data: {
readonly sessionID: Session.ID
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly response?: { readonly body: string } | undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
}
}
| {
@@ -907,12 +902,7 @@ export type SessionLogOutput =
readonly data: {
readonly sessionID: Session.ID
readonly assistantMessageID: SessionMessage.ID
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly response?: { readonly body: string } | undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly finish?: "content-filter" | undefined
readonly rawFinish?: string | undefined
readonly providerState?: SessionMessage.ProviderState | undefined
@@ -1122,12 +1112,7 @@ export type SessionLogOutput =
readonly sessionID: Session.ID
readonly assistantMessageID: SessionMessage.ID
readonly id: string
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly response?: { readonly body: string } | undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly content?:
| readonly [
(
@@ -1172,12 +1157,7 @@ export type SessionLogOutput =
readonly assistantMessageID: SessionMessage.ID
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly response?: { readonly body: string } | undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
}
}
| {
@@ -1258,12 +1238,7 @@ export type SessionLogOutput =
readonly data: {
readonly sessionID: Session.ID
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number | undefined
readonly response?: { readonly body: string } | undefined
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
readonly inputID?: SessionMessage.ID | undefined
readonly cost?: (number & Brand.Brand<"Money.USD">) | undefined
readonly tokens?:
@@ -1743,21 +1718,6 @@ export interface McpApi<E = never> {
readonly resource: { readonly catalog: McpResourceCatalogOperation<E> }
}
export type CredentialListOutput = ReadonlyArray<Credential.Entry>
export type CredentialListOperation<E = never> = () => Effect.Effect<CredentialListOutput, E>
export type CredentialCreateInput = {
readonly id?: Credential.ID | undefined
readonly integrationID: Integration.ID
readonly label?: string | undefined
readonly value: Credential.Value
readonly activate?: boolean | undefined
}
export type CredentialCreateOutput = Credential.Entry
export type CredentialCreateOperation<E = never> = (
input: CredentialCreateInput,
) => Effect.Effect<CredentialCreateOutput, E>
export type CredentialUpdateInput = { readonly credentialID: Credential.ID; readonly label: string }
export type CredentialUpdateOutput = void
export type CredentialUpdateOperation<E = never> = (
@@ -1777,8 +1737,6 @@ export type CredentialRemoveOperation<E = never> = (
) => Effect.Effect<CredentialRemoveOutput, E>
export interface CredentialApi<E = never> {
readonly list: CredentialListOperation<E>
readonly create: CredentialCreateOperation<E>
readonly update: CredentialUpdateOperation<E>
readonly activate: CredentialActivateOperation<E>
readonly remove: CredentialRemoveOperation<E>
@@ -153,9 +153,6 @@ import type {
McpDisconnectOutput,
McpResourceCatalogInput,
McpResourceCatalogOutput,
CredentialListOutput,
CredentialCreateInput,
CredentialCreateOutput,
CredentialUpdateInput,
CredentialUpdateOutput,
CredentialActivateInput,
@@ -1024,30 +1021,6 @@ const adaptGroupMcp = (raw: RawClient["server.mcp"]) => ({
resource: { catalog: EndpointMcpResourceCatalog(raw) },
})
const EndpointCredentialList = (raw: RawClient["server.credential"]) => () =>
preserveEffect<CredentialListOutput>()(
raw["credential.list"]({}).pipe(
Effect.mapError(mapClientError),
Effect.map((value) => value.data),
),
)
const EndpointCredentialCreate = (raw: RawClient["server.credential"]) => (input: CredentialCreateInput) =>
preserveEffect<CredentialCreateOutput>()(
raw["credential.create"]({
payload: {
id: input["id"],
integrationID: input["integrationID"],
label: input["label"],
value: input["value"],
activate: input["activate"],
},
}).pipe(
Effect.mapError(mapClientError),
Effect.map((value) => value.data),
),
)
const EndpointCredentialUpdate = (raw: RawClient["server.credential"]) => (input: CredentialUpdateInput) =>
preserveEffect<CredentialUpdateOutput>()(
raw["credential.update"]({
@@ -1069,8 +1042,6 @@ const EndpointCredentialRemove = (raw: RawClient["server.credential"]) => (input
)
const adaptGroupCredential = (raw: RawClient["server.credential"]) => ({
list: EndpointCredentialList(raw),
create: EndpointCredentialCreate(raw),
update: EndpointCredentialUpdate(raw),
activate: EndpointCredentialActivate(raw),
remove: EndpointCredentialRemove(raw),
@@ -147,9 +147,6 @@ import type {
McpDisconnectOutput,
McpResourceCatalogInput,
McpResourceCatalogOutput,
CredentialListOutput,
CredentialCreateInput,
CredentialCreateOutput,
CredentialUpdateInput,
CredentialUpdateOutput,
CredentialActivateInput,
@@ -447,7 +444,7 @@ export function make(options: ClientOptions) {
path: `/api/location`,
query: { location: input?.["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 404],
declaredStatuses: [400, 401],
empty: false,
},
requestOptions,
@@ -1395,29 +1392,6 @@ export function make(options: ClientOptions) {
},
},
credential: {
list: (requestOptions?: RequestOptions) =>
request<{ readonly data: CredentialListOutput }>(
{ method: "GET", path: `/api/credential`, successStatus: 200, declaredStatuses: [400, 401], empty: false },
requestOptions,
).then((value) => value.data),
create: (input: CredentialCreateInput, requestOptions?: RequestOptions) =>
request<{ readonly data: CredentialCreateOutput }>(
{
method: "POST",
path: `/api/credential`,
body: {
id: input["id"],
integrationID: input["integrationID"],
label: input["label"],
value: input["value"],
activate: input["activate"],
},
successStatus: 200,
declaredStatuses: [400, 401, 409],
empty: false,
},
requestOptions,
).then((value) => value.data),
update: (input: CredentialUpdateInput, requestOptions?: RequestOptions) =>
request<CredentialUpdateOutput>(
{
+15 -231
View File
@@ -133,7 +133,7 @@ export type ToolTextContent = { type: "text"; text: string }
export type ToolFileContent = { type: "file"; uri: string; mime: string; name?: string | null }
export type SessionStructuredError = { type: string; message: string; status?: number; response?: { body: string } }
export type SessionStructuredError = { type: string; message: string; status?: number }
export type SessionMessageCompactionRunning = {
type: "compaction"
@@ -293,15 +293,6 @@ export type McpResourceTemplate = {
mimeType?: string
}
export type CredentialOAuth = {
type: "oauth"
methodID: string
refresh: string
access: string
expires: number
metadata?: { [x: string]: JsonValue }
}
export type ProjectVcs = string
export type ProjectIcon = { url?: string; override?: string; color?: string }
@@ -1665,7 +1656,7 @@ export type FormMultiselectField1 = {
default?: Array<string>
}
export type FormAnswer2 = { [x: string]: FormValue1 }
export type FormAnswer1 = { [x: string]: FormValue1 }
export type SessionStatusUpdated = {
id: string
@@ -1899,13 +1890,6 @@ export type FormField =
export type FormState = { status: "pending" } | { status: "answered"; answer: FormAnswer } | { status: "cancelled" }
export type CredentialKey = {
type: "key"
key: string
metadata?: { [x: string]: JsonValue }
configuration?: FormAnswer
}
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type FormField1 =
@@ -1922,7 +1906,7 @@ export type FormReplied = {
metadata?: { [x: string]: any }
type: "form.replied"
location?: LocationRef
data: { id: string; sessionID: string; answer: FormAnswer2 }
data: { id: string; sessionID: string; answer: FormAnswer1 }
}
export type ReferenceInfo = {
@@ -2241,8 +2225,6 @@ export type SessionMessageAssistantTool1 = {
export type FormFields = [FormField, ...Array<FormField>]
export type CredentialValue = CredentialOAuth | CredentialKey
export type FormFields2 = [FormField1, ...Array<FormField1>]
export type SessionsResponse = { data: Array<SessionInfo>; cursor: { previous?: string | null; next?: string | null } }
@@ -2297,14 +2279,6 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
export type CredentialEntry = {
id: string
integrationID: string
label: string
active: boolean
value: CredentialValue
}
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields2 }
export type SessionMessageInfo =
@@ -2518,14 +2492,6 @@ export type UnauthorizedError = { readonly _tag: "UnauthorizedError"; readonly m
export const isUnauthorizedError = (value: unknown): value is UnauthorizedError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "UnauthorizedError"
export type LocationNotFoundError = {
readonly _tag: "LocationNotFoundError"
readonly directory: string
readonly message: string
}
export const isLocationNotFoundError = (value: unknown): value is LocationNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "LocationNotFoundError"
export type ServiceUnavailableError = {
readonly _tag: "ServiceUnavailableError"
readonly message: string
@@ -3217,12 +3183,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -3259,21 +3220,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -3325,12 +3276,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly cost?: number
readonly tokens?: {
readonly input: number
@@ -3554,12 +3500,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -3596,21 +3537,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -3662,12 +3593,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly cost?: number
readonly tokens?: {
readonly input: number
@@ -3891,12 +3817,7 @@ export type SessionImportInput = {
| {
readonly status: "error"
readonly input: { readonly [x: string]: JsonValue }
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly content?: readonly [
(
| { readonly type: "text"; readonly text: string }
@@ -3933,21 +3854,11 @@ export type SessionImportInput = {
readonly reasoning: number
readonly cache: { readonly read: number; readonly write: number }
}
readonly error?: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
readonly retry?: {
readonly attempt: number
readonly at: number
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
}
}
| (
@@ -3999,12 +3910,7 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly status: "failed"
readonly reason: "auto" | "manual"
readonly error: {
readonly type: string
readonly message: string
readonly status?: number
readonly response?: { readonly body: string }
}
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
readonly cost?: number
readonly tokens?: {
readonly input: number
@@ -5784,128 +5690,6 @@ export type McpResourceCatalogInput = {
export type McpResourceCatalogOutput = { location: LocationPublicRef; data: McpResourceCatalog }
export type CredentialListOutput = { data: Array<CredentialEntry> }["data"]
export type CredentialCreateInput = {
readonly id?: {
readonly id?: string
readonly integrationID: string
readonly label?: string
readonly value:
| {
readonly type: "oauth"
readonly methodID: string
readonly refresh: string
readonly access: string
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
readonly activate?: boolean
}["id"]
readonly integrationID: {
readonly id?: string
readonly integrationID: string
readonly label?: string
readonly value:
| {
readonly type: "oauth"
readonly methodID: string
readonly refresh: string
readonly access: string
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
readonly activate?: boolean
}["integrationID"]
readonly label?: {
readonly id?: string
readonly integrationID: string
readonly label?: string
readonly value:
| {
readonly type: "oauth"
readonly methodID: string
readonly refresh: string
readonly access: string
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
readonly activate?: boolean
}["label"]
readonly value: {
readonly id?: string
readonly integrationID: string
readonly label?: string
readonly value:
| {
readonly type: "oauth"
readonly methodID: string
readonly refresh: string
readonly access: string
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
readonly activate?: boolean
}["value"]
readonly activate?: {
readonly id?: string
readonly integrationID: string
readonly label?: string
readonly value:
| {
readonly type: "oauth"
readonly methodID: string
readonly refresh: string
readonly access: string
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
readonly activate?: boolean
}["activate"]
}
export type CredentialCreateOutput = { data: CredentialEntry }["data"]
export type CredentialUpdateInput = {
readonly credentialID: { readonly credentialID: string }["credentialID"]
readonly label: { readonly label: string }["label"]
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/codemode",
"version": "2.0.20",
"version": "2.0.19",
"description": "Effect-native confined code execution over schema-described tools",
"type": "module",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-app",
"version": "2.0.20",
"version": "2.0.19",
"type": "module",
"license": "MIT",
"scripts": {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/console-core",
"version": "2.0.20",
"version": "2.0.19",
"private": true,
"type": "module",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-function",
"version": "2.0.20",
"version": "2.0.19",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-mail",
"version": "2.0.20",
"version": "2.0.19",
"dependencies": {
"@jsx-email/all": "2.2.3",
"@jsx-email/cli": "1.4.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-support",
"version": "2.0.20",
"version": "2.0.19",
"type": "module",
"license": "MIT",
"scripts": {
+1 -2
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.0.20",
"version": "2.0.19",
"name": "@opencode/core",
"type": "module",
"license": "MIT",
@@ -129,7 +129,6 @@
"https-proxy-agent": "7.0.6",
"ignore": "7.0.5",
"immer": "11.1.4",
"jose": "6.0.11",
"jsonc-parser": "3.3.1",
"mime-types": "3.0.2",
"tree-sitter-bash": "0.25.0",
+13 -32
View File
@@ -38,16 +38,11 @@ export interface Interface {
readonly list: (integrationID: Integration.ID) => Effect.Effect<Info[]>
/** Returns one stored credential by ID. */
readonly get: (id: ID) => Effect.Effect<Info | undefined>
/**
* Creates a credential for an integration and returns the new record. The new credential becomes the
* integration's selection unless `activate` is false and the integration already has a credential.
*/
/** Creates a credential for an integration and returns the new record. */
readonly create: (input: {
readonly id?: ID
readonly integrationID: Integration.ID
readonly value: Value
readonly label?: string
readonly activate?: boolean
}) => Effect.Effect<Info>
/** Selects a stored credential for its integration. */
readonly activate: (id: ID) => Effect.Effect<void>
@@ -104,30 +99,19 @@ const layer = Layer.effect(
}),
create: Effect.fn("Credential.create")(function* (input) {
const credential = new Info({
id: input.id ?? ID.create(),
id: ID.create(),
integrationID: input.integrationID,
label: input.label ?? "default",
value: input.value,
})
const activated = yield* db
yield* db
.transaction((tx) =>
Effect.gen(function* () {
const current = yield* tx
.select({ id: CredentialTable.id, active: CredentialTable.active })
.from(CredentialTable)
yield* tx
.update(CredentialTable)
.set({ active: false })
.where(eq(CredentialTable.integration_id, credential.integrationID))
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
.get()
const activate = input.activate !== false || !current
if (activate)
yield* tx
.update(CredentialTable)
.set({ active: false })
.where(eq(CredentialTable.integration_id, credential.integrationID))
.run()
// Legacy rows have no active flag and the newest one is selected, so pin it before inserting a newer row.
if (!activate && current && !current.active)
yield* tx.update(CredentialTable).set({ active: true }).where(eq(CredentialTable.id, current.id)).run()
.run()
yield* tx
.insert(CredentialTable)
.values({
@@ -135,10 +119,9 @@ const layer = Layer.effect(
integration_id: credential.integrationID,
label: credential.label,
value: credential.value,
active: activate,
active: true,
})
.run()
return activate
}),
)
.pipe(
@@ -155,15 +138,13 @@ const layer = Layer.effect(
credentialID: credential.id,
integrationID: credential.integrationID,
type: credential.value.type,
active: activated,
})
yield* bus.publish(Event.Updated, {}, { global: true })
if (activated)
yield* bus.publish(
Event.Switched,
{ integrationID: credential.integrationID, credentialID: credential.id },
{ global: true },
)
yield* bus.publish(
Event.Switched,
{ integrationID: credential.integrationID, credentialID: credential.id },
{ global: true },
)
return credential
}),
activate: Effect.fn("Credential.activate")(function* (id) {
+3 -23
View File
@@ -5,8 +5,6 @@ import { sqliteLayer, supportsForeignKeyToggle, supportsTuningPragmas } from "#s
import { Context, Effect, Layer, Schema, Semaphore } from "effect"
import type { SqlClient } from "effect/unstable/sql"
import { Global } from "@opencode/util/global"
import { closeSync, existsSync, openSync } from "node:fs"
import { chmod } from "node:fs/promises"
import { isAbsolute, join } from "path"
import { DatabaseMigration } from "./migration.js"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
@@ -72,31 +70,13 @@ export function layer(options: Options = { path: ":memory:" }) {
Layer.provide(sqliteLayer({ filename })),
)
const filename = options.path ?? ":memory:"
if (filename === ":memory:") return provide(filename)
const file = isAbsolute(filename) ? filename : join((yield* Global.Service).data, filename)
yield* Effect.promise(() => restrictToOwner(file))
return provide(file)
if (filename === ":memory:" || isAbsolute(filename)) return provide(filename)
const global = yield* Global.Service
return provide(join(global.data, filename))
}),
)
}
// SQLite creates new sidecars with the database's mode, but does not tighten existing sidecars.
// Windows relies on the user profile directory's inherited ACLs instead of POSIX modes.
async function restrictToOwner(filename: string) {
if (process.platform === "win32") return
// Opening and closing an existing database can release another connection's POSIX locks.
// Create missing files synchronously so another fiber cannot open one before it is restricted.
if (!existsSync(filename)) closeSync(openSync(filename, "a", 0o600))
await chmod(filename, 0o600)
await Promise.all(
[`${filename}-wal`, `${filename}-shm`].map((file) =>
chmod(file, 0o600).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error
}),
),
)
}
// The database service over an injected SqlClient, for runtimes that receive
// database storage instead of opening a filesystem path. Any client provided
// here still goes through the pragma guards and migrations; Global is required
@@ -149,6 +149,7 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
responseFormat,
}: LanguageModelV3CallOptions) {
const warnings: SharedV3Warning[] = []
const modelConfig = getResponsesModelConfig(this.modelId)
if (topK != null) {
warnings.push({ type: "unsupported", feature: "topK" })
@@ -185,7 +186,7 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
prompt,
systemMessageMode: "system",
systemMessageMode: modelConfig.systemMessageMode,
fileIdPrefixes: this.config.fileIdPrefixes,
store,
})
@@ -285,18 +286,84 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
safety_identifier: openaiOptions?.safetyIdentifier,
top_logprobs: topLogprobs,
...((openaiOptions?.reasoningEffort != null || openaiOptions?.reasoningSummary != null) && {
reasoning: {
...(openaiOptions?.reasoningEffort != null && {
effort: openaiOptions.reasoningEffort,
}),
...(openaiOptions?.reasoningSummary != null && {
summary: openaiOptions.reasoningSummary,
}),
},
// model-specific settings:
...(modelConfig.isReasoningModel &&
(openaiOptions?.reasoningEffort != null || openaiOptions?.reasoningSummary != null) && {
reasoning: {
...(openaiOptions?.reasoningEffort != null && {
effort: openaiOptions.reasoningEffort,
}),
...(openaiOptions?.reasoningSummary != null && {
summary: openaiOptions.reasoningSummary,
}),
},
}),
...(modelConfig.requiredAutoTruncation && {
truncation: "auto",
}),
}
if (modelConfig.isReasoningModel) {
// remove unsupported settings for reasoning models
// see https://platform.openai.com/docs/guides/reasoning#limitations
if (baseArgs.temperature != null) {
baseArgs.temperature = undefined
warnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature is not supported for reasoning models",
})
}
if (baseArgs.top_p != null) {
baseArgs.top_p = undefined
warnings.push({
type: "unsupported",
feature: "topP",
details: "topP is not supported for reasoning models",
})
}
} else {
if (openaiOptions?.reasoningEffort != null) {
warnings.push({
type: "unsupported",
feature: "reasoningEffort",
details: "reasoningEffort is not supported for non-reasoning models",
})
}
if (openaiOptions?.reasoningSummary != null) {
warnings.push({
type: "unsupported",
feature: "reasoningSummary",
details: "reasoningSummary is not supported for non-reasoning models",
})
}
}
// Validate flex processing support
if (openaiOptions?.serviceTier === "flex" && !modelConfig.supportsFlexProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details: "flex processing is only available for o3, o4-mini, and gpt-5 models",
})
// Remove from args if not supported
baseArgs.service_tier = undefined
}
// Validate priority processing support
if (openaiOptions?.serviceTier === "priority" && !modelConfig.supportsPriorityProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details:
"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported",
})
// Remove from args if not supported
baseArgs.service_tier = undefined
}
return {
getHostedToolName,
args: {
@@ -1591,6 +1658,69 @@ function isErrorChunk(chunk: z.infer<typeof openaiResponsesChunkSchema>): chunk
return chunk.type === "error"
}
type ResponsesModelConfig = {
isReasoningModel: boolean
systemMessageMode: "remove" | "system" | "developer"
requiredAutoTruncation: boolean
supportsFlexProcessing: boolean
supportsPriorityProcessing: boolean
}
function getResponsesModelConfig(modelId: string): ResponsesModelConfig {
const supportsFlexProcessing =
modelId.startsWith("o3") ||
modelId.startsWith("o4-mini") ||
(modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
const supportsPriorityProcessing =
modelId.startsWith("gpt-4") ||
modelId.startsWith("gpt-5-mini") ||
(modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat")) ||
modelId.startsWith("o3") ||
modelId.startsWith("o4-mini")
const defaults = {
requiredAutoTruncation: false,
systemMessageMode: "system" as const,
supportsFlexProcessing,
supportsPriorityProcessing,
}
// gpt-5-chat models are non-reasoning
if (modelId.startsWith("gpt-5-chat")) {
return {
...defaults,
isReasoningModel: false,
}
}
// o series reasoning models:
if (
modelId.startsWith("o") ||
modelId.startsWith("gpt-5") ||
modelId.startsWith("codex-") ||
modelId.startsWith("computer-use")
) {
if (modelId.startsWith("o1-mini") || modelId.startsWith("o1-preview")) {
return {
...defaults,
isReasoningModel: true,
systemMessageMode: "remove",
}
}
return {
...defaults,
isReasoningModel: true,
systemMessageMode: "developer",
}
}
// gpt models:
return {
...defaults,
isReasoningModel: false,
}
}
// TODO AI SDK 6: use optional here instead of nullish
const openaiResponsesProviderOptionsSchema = z.object({
include: z

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