diff --git a/.gitattributes b/.gitattributes
index 149a7c2ba9a6..83f99733d550 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -7,6 +7,21 @@ packages/protocol/openapi.json linguist-generated
packages/client/src/promise/generated/** linguist-generated
packages/client/src/effect/generated/** linguist-generated
packages/client/src/effect/api/** linguist-generated
+# cli-rs: parity recordings and the files `script/gen` writes.
+packages/cli-rs/parity/fixtures/** linguist-generated
+packages/cli-rs/assets/queries/** linguist-generated
+packages/cli-rs/crates/acp/src/permission/structured_patch.json linguist-generated
+packages/cli-rs/crates/api-types/src/types.rs linguist-generated
+packages/cli-rs/crates/api/src/generated/** linguist-generated
+packages/cli-rs/crates/cli/src/run/mime.rs linguist-generated
+packages/cli-rs/crates/cli/tests/fixtures/** linguist-generated
+packages/cli-rs/crates/local/src/generated/** linguist-generated
+packages/cli-rs/crates/mermaid/src/core/entities.rs linguist-generated
+packages/cli-rs/crates/mermaid/src/core/wide.rs linguist-generated
+packages/cli-rs/crates/ui/src/fuzzy/accents.rs linguist-generated
+packages/cli-rs/crates/ui/src/keymap/generated.rs linguist-generated
+packages/cli-rs/crates/ui/src/theme/generated/** linguist-generated
+packages/cli-rs/crates/util/fixtures/time.tsv linguist-generated
packages/core/src/**/*.txt text eol=lf
packages/httpapi-codegen/test/generated/*.ts text eol=lf
# The site tests compare source text and humans.txt byte for byte, so Windows checkouts keep LF.
diff --git a/.gitleaks.toml b/.gitleaks.toml
index e487dd37baef..9f2070729f1f 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -15,8 +15,11 @@ paths = [
# api_message_id + literal REDACTED (not credentials).
'''^packages/core/test/plugin/provider/claude\-agent/fixtures/recordings/.*\.jsonl$''',
]
-# Upstream services/update verifies this public Cloudflare Access JWT audience.
-# It is an application identifier, not a token, signing key or credential.
regexes = [
+ # Upstream services/update verifies this public Cloudflare Access JWT audience.
+ # It is an application identifier, not a token, signing key or credential.
'''^d369a93ad5ce8cf96eebe30620488dd2537427c92fed439c310288832a282987$''',
+ # RFC 6455 section 1.3 sample Sec-WebSocket-Key nonce ("the sample nonce"), used by
+ # upstream v2.4.0 machine-link handshake tests (packages/server/test/machine-link.test.ts).
+ '''^dGhlIHNhbXBsZSBub25jZQ==$''',
]
diff --git a/.opencode/skills/focus-states/SKILL.md b/.opencode/skills/focus-states/SKILL.md
index fb255243cf40..a858add41923 100644
--- a/.opencode/skills/focus-states/SKILL.md
+++ b/.opencode/skills/focus-states/SKILL.md
@@ -9,7 +9,7 @@ Use one default ring when someone navigates focus to a control, not when they cl
## The ring
-- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. The only exception is a custom field that combines `:focus` with its own ring state, as the composer and Home search do (see Text fields). `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links.
+- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links.
- Offset: `2px` outward by default. `-2px` inset for full-width rows and for controls flush against an edge that clips or scrolls (segmented items, split buttons, titlebar buttons, clear buttons). No other offsets.
- Follow the control’s radius; give a square text action or link 4px where appropriate. Use a wrapper with `:has(> trigger:focus-visible)` when the wrapper owns the visible shape or the trigger’s ring would clip, as with tabs and Settings project cards.
- Outline only. Don't draw focus with `box-shadow`: Windows High Contrast removes shadows, so the ring disappears, and shadow rings looked different from every other ring.
@@ -18,15 +18,13 @@ Use one default ring when someone navigates focus to a control, not when they cl
- Inline rename inputs rely on the caret and editing state. The timeline's Jump to latest stays in the Tab order with the shared ring, since it's the only quick way back down from the keyboard; its container is `inert` while it's hidden. Loading alone doesn’t add a ring. If a busy button keeps keyboard focus, keep the ring and show the busy state separately with `aria-busy`, a disabled state, or loading text; the ring alone doesn’t say whether the button can be activated.
- These ring rules do not replace normal field borders or validation feedback. Those can respond to click focus and have their own inset treatment.
-## Text fields
+## Text fields and scroll areas
-Editable fields can match `:focus-visible` after a click, so fields with a custom frame ring (the composer and Home search) decide when focus arrives. Use `packages/ui/src/context/field-focus.tsx`, not a global input tracker.
+Chromium matches `:focus-visible` on every focused text field, and on anything that has focus once a key is pressed. A ring on a large surface then shows after a click, when the app moves focus there, and on returning to the window.
-- Ring by default. Suppress the ring for direct pointer focus and for the composer’s explicit initial autofocus when a session or draft opens, including when it was opened with the keyboard.
-- Tab, shortcuts like Find, and assistive technology moving DOM focus show the ring. Moving a screen reader’s reading cursor alone does not move DOM focus.
-- When a dialog returns focus to a custom field, `packages/ui/src/context/dialog.tsx` restores the field's own ring state; ordinary controls use the browser's `:focus-visible` state. The overlay rules below apply.
-- A `pointerdown` inside a field that already shows the ring clears it immediately; no new focus event fires. Typing never changes the decision, and blur clears it.
-- A click shows the field's normal focused border or background and the caret, with no ring.
+- A text field never draws the ring, the composer and Home search included. Focus shows as the caret and the field's focused border or background. Don't add ring state or pointer tracking to a field.
+- A scroll area (the timeline, Home's list) takes focus so the keyboard can scroll it, and draws no ring. Show focus on the items inside it instead.
+- Moving a screen reader’s reading cursor alone does not move DOM focus.
## Rows
@@ -63,7 +61,7 @@ Editable fields can match `:focus-visible` after a click, so fields with a custo
- Follow logical reading and interaction order, including in RTL. Fix DOM order rather than using positive `tabindex`. Use native buttons for actions and links for navigation; use established widget primitives or keyboard patterns for tabs, trees, sliders, and resize handles.
- Move focus in response to a user action or to recover focus when its target disappears. Background updates, streamed output, toasts, and incoming prompts must not steal focus.
- If a focused item is closed or deleted, move focus to the next place the user can continue the same task: the next or previous item in the same list, or a stable fallback such as the list heading or the control that opened it. Use the visually nearest control only when it serves that task. Don’t leave focus on `
`.
-- Chromium drops focus to `` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip.
+- Chromium drops focus to `` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. The control it moves focus to shows its ring only when Tab or an arrow key last moved focus; typing, shortcuts and a key pressed on a clicked control don't count. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip.
## Verify
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 08499c44323b..925c19480b0b 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -188,6 +188,7 @@
"**/.sst",
"**/*.d.ts",
"**/sdk.gen.ts",
+ "packages/cli-rs/**",
"packages/plugins/figma/skills/**",
".agent/**",
".agents/**",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37fb38b23598..3ca9e74f603c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,208 @@
Release notes for OpenCode V2, newest first.
+## v2.4.0-shuv.1 — 2026-11-23
+
+Syncs upstream `dev` through `d284e7ce17`: 183 commits beyond the dev pin in [#509](https://github.com/shuv1337/shuvcode/pull/509), including the v2.4.0 release commit (`d6379ff0e1`, patch-identical to the `v2.4.0` tag) and one later fix ([#65757](https://github.com/anomalyco/opencode/pull/65757)).
+
+### Highlights
+
+- **Automations** are on by default; set `"automations": false` to turn them off. Code actions can call the session's Code Mode tools, and an automation can run a fixed shell command.
+- **Machines**: `shuvcode machine add|list|remove` pairs remote machines with the background service.
+- **Session search** (`sqlite_fts`) and **session interrupt** (`full_codemode`) tools join `tools.shuvcode.session`.
+- Video generation, the desktop's built-in browser profile, MCP Events push delivery and the new TUI designs come from upstream v2.4.0 below.
+
+### Breaking changes
+
+- Automation tools move to upstream's own namespace: `tools.automation.create`, `.list`, `.pause`, `.resume` and `.delete` replace `tools.shuvcode.automation_*`, and the direct tools are `automation_create` and so on instead of `shuvcode_automation_*`. Update permission rules that name the old tools.
+- The unattended automation denylist follows upstream ([#65217](https://github.com/anomalyco/opencode/pull/65217)): it now blocks `automation.create`, `.pause`, `.resume`, `.delete` and `shuvcode.session.move`. Automation code can call `shell`, `shuvcode.session.rename` and the worktree tools after the permission prompts at creation.
+- `experimental.automations` and `experimental.mcp_events` are gone; MCP Events are always available and automations use the top-level `automations` key.
+
+### Fork changes
+
+- The new upstream session tools use the `shuvcode.session` namespace; the new `machine` and hidden `login` commands use the fork's global `--server`/`--standalone` handling.
+- Claude Agent stays hidden: the new Claude websearch provider is registered only by the unloaded Claude Agent plugin.
+- The upstream native Rust CLI (`packages/cli-rs`) is in the tree but outside the fork's build and publish.
+
+### Rollback
+
+Roll back to `v2.3.2-shuv.1`. Permission rules rewritten for the `automation.*` names would need the old `shuvcode.automation_*` names again.
+
+## v2.4.0 — 2026-11-23
+
+### Highlights
+
+- **Built-In Desktop Browser**: Import your sign-ins and browsing history from Chrome, Edge, Firefox or Safari, and add extensions from Chromium browsers or the Chrome and Edge stores. Everything stays in one persistent desktop profile: chat links open signed in, your tabs survive restarts and the agent can read and drive the same pages without you switching apps. ([#63002](https://github.com/anomalyco/opencode/pull/63002), [#65073](https://github.com/anomalyco/opencode/pull/65073))
+- **Automations**: Ask the agent to run a prompt, a script or a shell command on a timer, on a cron schedule or when an MCP server sends an event, and manage them with `/automation`. Set `"automations": false` in your config if you don't want them. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186))
+- **Generate Videos**: When a connected provider has a video model, the agent can make videos with `generate_video`. It keeps working while the video renders and saves the files into your workspace when they're ready. ([#63666](https://github.com/anomalyco/opencode/pull/63666), [#65664](https://github.com/anomalyco/opencode/pull/65664))
+- **New TUI Look**: The TUI's new designs are on by default, and the `opencode` theme is the new one. Pick `opencode-classic` in **Theme** to keep the previous colors. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
+- **Windows Taskbar Status**: On Windows, the taskbar button shows session progress, counts sessions that need you and flashes when a permission or question is waiting. ([#65317](https://github.com/anomalyco/opencode/pull/65317), [#65318](https://github.com/anomalyco/opencode/pull/65318), [#65319](https://github.com/anomalyco/opencode/pull/65319))
+
+### Upgrade notes
+
+- **Image tool renamed.** `experimental_image_generate` is now `generate_image`. Permission rules with the old name are mapped automatically, but saved "always allow" approvals are not, so it asks again once. ([#65682](https://github.com/anomalyco/opencode/pull/65682))
+- **Plugins that follow a version now update on their own.** A plugin written as `name@latest`, a version range (such as `name@^1.2.0`), a Git branch or a Git `semver:` range is checked on startup and every 24 hours, and a newer match is installed and reloaded. Ranges never leave their range, and if a new version fails to load the previous one keeps running. A bare `name`, an exact version, another tag such as `@next`, a Git tag or a commit hash doesn't update itself; `opencode plugin update` still updates those by hand. ([#64764](https://github.com/anomalyco/opencode/pull/64764), [#65052](https://github.com/anomalyco/opencode/pull/65052), [#65056](https://github.com/anomalyco/opencode/pull/65056))
+- **GitHub Copilot no longer reads `GITHUB_TOKEN`.** Set `COPILOT_GITHUB_TOKEN` or sign in with OAuth. ([#64697](https://github.com/anomalyco/opencode/pull/64697))
+- **MCP servers are tried on the newest protocol first.** A server without a `protocol` setting is probed before falling back to the legacy handshake. Set `protocol: "legacy"` on a server that misbehaves. ([#65282](https://github.com/anomalyco/opencode/pull/65282))
+- **The TUI `opencode` theme changed.** It now means the new theme; set `opencode-classic` for the previous look, and `experimental["new-designs"]: false` in your TUI config for the previous designs. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
+- **Chat links open in the browser pane.** In the desktop app, web links from the chat open beside the conversation. Modifier-click a link to open it in your system browser. A `browser` deny in your permission rules refuses every agent browser call. ([#63002](https://github.com/anomalyco/opencode/pull/63002))
+- **OpenCode Go connects through OpenCode.** The connect dialogs and `opencode auth login` list one **OpenCode** option that includes Go models. **OpenCode Go** is only listed when a Go key is already saved, and saved keys keep working. ([#65466](https://github.com/anomalyco/opencode/pull/65466))
+- **New desktop shortcut.** `Cmd+Shift+S` (`Ctrl+Shift+S` on Windows and Linux) now archives the open session. The composer's `Cmd+U` and `Escape`/`Ctrl+G` now follow the **Attach file** and **Stop session** shortcuts. ([#65428](https://github.com/anomalyco/opencode/pull/65428), [#64394](https://github.com/anomalyco/opencode/pull/64394))
+- **Code Mode session tool paths moved.** `tools.opencode.session_rename` and `session_move` are now `tools.opencode.session.rename` and `.move`. Direct tool names and permission actions are unchanged. ([#65080](https://github.com/anomalyco/opencode/pull/65080))
+- **TUI plugins need OpenTUI 0.9.4.** `@opencode/plugin` requires `@opentui/core` and `@opentui/solid` 0.9.4 or later. Renderers passed to `registerCodeBlockRenderer` now receive an OpenTUI block (`block.text`) instead of a Markdown token; `codeBlockStyle` and `escaped` are gone. ([#63989](https://github.com/anomalyco/opencode/pull/63989))
+- **SDK: plugins load in the background again.** Plugins are meant to load asynchronously, and the server never waits for them. In v2.2.7 the model, provider, `generate.*`, `voice.*` and `websearch.query` endpoints started waiting up to 5 seconds for plugins and returning 503 after that ([#63040](https://github.com/anomalyco/opencode/pull/63040)); this release removes that wait. Right after startup these endpoints answer with whatever has loaded, so a list can be empty or partial. Long-lived clients should refresh on the matching `*.updated` event, such as `model.updated`. One-shot scripts should wait on their side, for example by polling `plugin.list` until it returns plugins, or the endpoint until the entry they need appears. ([#63814](https://github.com/anomalyco/opencode/pull/63814))
+- **Desktop voice needs a matching server.** The app reads each voice model's engine, which older servers don't report, so voice shows as unavailable against a server from before this release. ([#65506](https://github.com/anomalyco/opencode/pull/65506))
+- **Storage write path.** Assistant parts are now saved as their own rows. `experimental.part_rows: false` restores the old path for this release. ([#65039](https://github.com/anomalyco/opencode/pull/65039))
+
+### Core
+
+#### Improvements
+
+- Added automations. Agents can schedule prompts, Code Mode scripts or fixed shell commands to run once, on an interval, on a cron schedule or when a connected MCP server pushes an event. Use the `/automation` command or the `automation` tools. A shell action asks for approval once, when it's created, and records each run's exit code and output. Set `"automations": false` to turn them off. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186), [#65217](https://github.com/anomalyco/opencode/pull/65217), [#65236](https://github.com/anomalyco/opencode/pull/65236), [#65001](https://github.com/anomalyco/opencode/pull/65001), [#65699](https://github.com/anomalyco/opencode/pull/65699))
+- MCP Events shipped: OpenCode follows the MCP Events beta for push delivery, with argument checks, heartbeats and automatic reconnects. An event too large for its prompt is skipped and its automation keeps running. ([#65271](https://github.com/anomalyco/opencode/pull/65271), [#65673](https://github.com/anomalyco/opencode/pull/65673))
+- MCP servers without a `protocol` setting now negotiate the newest MCP protocol and fall back to the legacy handshake. ([#65282](https://github.com/anomalyco/opencode/pull/65282))
+- Agents can generate videos with `generate_video` whenever a connected provider has a video model. The job runs in the background, survives a server restart, saves the finished videos into the workspace and wakes the agent with their paths. Set a default model with `experimental.video_generate.model`. The image tool is now called `generate_image`. ([#63666](https://github.com/anomalyco/opencode/pull/63666), [#64546](https://github.com/anomalyco/opencode/pull/64546), [#65664](https://github.com/anomalyco/opencode/pull/65664), [#65682](https://github.com/anomalyco/opencode/pull/65682))
+- Plugins that follow a version (`name@latest`, a version range, a Git branch or a Git `semver:` range) are checked on startup and every 24 hours, and a newer match is installed and reloaded without a restart. A range stays within its range, and if a new version fails to load, the previous one keeps running. Other plugins still only report updates. ([#64764](https://github.com/anomalyco/opencode/pull/64764), [#65052](https://github.com/anomalyco/opencode/pull/65052), [#65056](https://github.com/anomalyco/opencode/pull/65056))
+- The Claude Agent provider has a `configDir` setting for a Claude config folder other than the default. Given a list of folders, a chat moves to the next account when one hits its usage limit. Claude Agent sessions also show up in Claude Code as coming from `opencode`. ([#62514](https://github.com/anomalyco/opencode/pull/62514), [#65035](https://github.com/anomalyco/opencode/pull/65035), [#65016](https://github.com/anomalyco/opencode/pull/65016))
+- Removing a Sign in with ChatGPT account, with `opencode auth logout` or the remove button in the app, now also revokes it with OpenAI. ([#64947](https://github.com/anomalyco/opencode/pull/64947))
+- The ChatGPT plan model lists now come from models.dev, so new models show up without an OpenCode update. ([#65579](https://github.com/anomalyco/opencode/pull/65579))
+- Voice models are now listed from models.dev, adding newer OpenAI models such as `gpt-live-1.1`. ([#65491](https://github.com/anomalyco/opencode/pull/65491))
+- Reading far into a large file with `read`, or reading its tail, takes far fewer reads, which is much faster on remote workspaces. ([#65611](https://github.com/anomalyco/opencode/pull/65611))
+- The shell tool's result says why a command ended without an exit code, and lists its output after the smaller fields so they survive truncation. ([#65365](https://github.com/anomalyco/opencode/pull/65365), [#65513](https://github.com/anomalyco/opencode/pull/65513))
+- Code Mode scripts can define getters and setters, errors have a `stack` showing where they were thrown, and a failed import says why. ([#64908](https://github.com/anomalyco/opencode/pull/64908), [#64939](https://github.com/anomalyco/opencode/pull/64939), [#64587](https://github.com/anomalyco/opencode/pull/64587))
+- A `timeout` set on a provider now applies to every request, including image, video, speech, transcription, embedding and compaction requests, which previously could hang forever on a stalled provider. ([#64692](https://github.com/anomalyco/opencode/pull/64692))
+- Gemma 4 models on Google's Interactions API offer the `none` and `thinking` variants, and the provider's `safetySettings` are sent to Interactions. ([#65038](https://github.com/anomalyco/opencode/pull/65038), [#65036](https://github.com/anomalyco/opencode/pull/65036))
+- Added `claude-agent` as a web search provider. With Claude Agent connected, set `"websearch": { "provider": "claude-agent" }` to run `websearch` through Claude Code's WebSearch, which Claude plans include, so any model can search without a search API key. ([#65704](https://github.com/anomalyco/opencode/pull/65704))
+- With `full_codemode` on, agents can call `tools.opencode.session.interrupt` to stop another session, its background jobs and its subagents. ([#65718](https://github.com/anomalyco/opencode/pull/65718))
+- Stored blobs, such as generated videos, are deleted a week after they were written, so the data folder no longer grows without limit. Copies saved into your project are untouched; `GET /api/experimental/blob/:id` returns 404 for a deleted blob. ([#65671](https://github.com/anomalyco/opencode/pull/65671))
+- Config now reloads only when a file that feeds it changes, not on every write under `.opencode` such as editing a skill. ([#62158](https://github.com/anomalyco/opencode/pull/62158))
+- Each streamed assistant part is saved as its own row instead of rewriting the whole message on every update, so long steps with many tool calls save reliably. ([#65039](https://github.com/anomalyco/opencode/pull/65039))
+
+#### Bug fixes
+
+- Fixed GitHub Copilot picking up `GITHUB_TOKEN`, which git tooling and GitHub Actions often set without Copilot access. It now reads `COPILOT_GITHUB_TOKEN`. ([#64697](https://github.com/anomalyco/opencode/pull/64697))
+- Fixed shell commands the scanner can't analyze, such as dynamic execution, failing outright. They now ask for permission, and a matching `shell` deny rule still blocks them. ([#65269](https://github.com/anomalyco/opencode/pull/65269))
+- Fixed sessions getting stuck on provider 400 errors after a model called a tool by a dotted name such as a Code Mode path. A Code Mode tool called at the top level now runs as that tool, with a note telling the model to use `execute`. ([#65292](https://github.com/anomalyco/opencode/pull/65292), [#65193](https://github.com/anomalyco/opencode/pull/65193), [#65494](https://github.com/anomalyco/opencode/pull/65494))
+- Fixed a forced tool choice for a namespaced tool naming a tool the request never declared on every provider except native OpenAI Responses. ([#65621](https://github.com/anomalyco/opencode/pull/65621), [#65726](https://github.com/anomalyco/opencode/pull/65726))
+- Fixed the shell tool's description not saying which OS and shell commands run in when `full_codemode` is on. ([#65712](https://github.com/anomalyco/opencode/pull/65712))
+- Fixed a revoked or expired ChatGPT sign-in failing every prompt with "Request failed: 400". It now asks you to connect again. ([#65289](https://github.com/anomalyco/opencode/pull/65289))
+- Fixed `edit` and `patch` replacing every non-UTF-8 character (Latin-1, cp1252, GBK…) with `�` across the whole file. They now refuse to rewrite such files. ([#64868](https://github.com/anomalyco/opencode/pull/64868))
+- Fixed the review pane showing every line as changed in repositories with `core.autocrlf=true`, and symlinks as modified with `core.symlinks=false`. ([#64884](https://github.com/anomalyco/opencode/pull/64884))
+- Fixed file permission rules not matching other capitalizations of the same path on macOS. Thanks @knp-sap. ([#64626](https://github.com/anomalyco/opencode/pull/64626))
+- Fixed the model picker staying empty while a slow project was still loading. ([#63814](https://github.com/anomalyco/opencode/pull/63814))
+- Fixed Claude Agent processes staying alive after their session was deleted. Thanks @WTLAIB. ([#62649](https://github.com/anomalyco/opencode/pull/62649))
+- Fixed Claude Agent models becoming unavailable after Claude Code renamed them, and Claude Agent now waits up to 60 seconds for its process to start. ([#65032](https://github.com/anomalyco/opencode/pull/65032), [#65064](https://github.com/anomalyco/opencode/pull/65064))
+- Fixed shell commands failing with "failed to open output file" after OpenCode's shell output directory was removed. ([#64889](https://github.com/anomalyco/opencode/pull/64889))
+- Fixed concurrent shell commands failing on Windows with PowerShell 7 from the Microsoft Store, and stopping one such command killing the others. ([#64901](https://github.com/anomalyco/opencode/pull/64901))
+- Fixed `opencode service set password` writing the password to the CLI log. ([#64911](https://github.com/anomalyco/opencode/pull/64911))
+- Fixed `opencode run` hanging when a FIFO is passed as an attachment; it's now rejected right away. Thanks @yang0228. ([#64696](https://github.com/anomalyco/opencode/pull/64696))
+- Fixed `opencode ` crashing with a stack trace when `` is neither a command nor a directory. It now prints help and the error. ([#65262](https://github.com/anomalyco/opencode/pull/65262))
+- Fixed the background service becoming unresponsive at startup with a large database write-ahead log on a slow disk. ([#64532](https://github.com/anomalyco/opencode/pull/64532))
+- Fixed a client that opens a session during a running tool call not seeing that tool's progress, such as a running subagent's session. ([#64929](https://github.com/anomalyco/opencode/pull/64929))
+- Fixed Markdown commands dropping a separate `variant` next to `model`, and agents being skipped when frontmatter repair turned inline lists or objects into strings. ([#65118](https://github.com/anomalyco/opencode/pull/65118), [#65119](https://github.com/anomalyco/opencode/pull/65119))
+- Fixed Google Interactions responses stopping early when Google splits a response across requests. ([#65006](https://github.com/anomalyco/opencode/pull/65006))
+- Fixed GPT models over OpenAI's WebSocket transport resending the whole conversation after a freeform tool call such as `execute` or `patch`. ([#64706](https://github.com/anomalyco/opencode/pull/64706))
+- Fixed `gpt-6.2-astra` and later Astra models getting a 500k context window with ChatGPT sign-in; they stay at 272k. ([#64725](https://github.com/anomalyco/opencode/pull/64725))
+- OpenAI `cyber_policy` and Gemini "terms of use" refusals are now reported as content policy errors. Thanks @lu-zero. ([#64844](https://github.com/anomalyco/opencode/pull/64844), [#64910](https://github.com/anomalyco/opencode/pull/64910))
+- Fixed MiniMax text-to-video requests without an aspect ratio being rejected; they now default to `16:9`. ([#64822](https://github.com/anomalyco/opencode/pull/64822))
+- Fixed several Code Mode built-ins to match Bun: `localeCompare` and `Date` `toLocale*` honor their locale and options, `toBase64`/`fromBase64` honor their options, `Buffer` `map`, `filter`, `slice` and `subarray` return a Buffer, and `Uint8Array.BYTES_PER_ELEMENT` is defined. ([#64935](https://github.com/anomalyco/opencode/pull/64935), [#64938](https://github.com/anomalyco/opencode/pull/64938), [#64931](https://github.com/anomalyco/opencode/pull/64931), [#64933](https://github.com/anomalyco/opencode/pull/64933), [#64930](https://github.com/anomalyco/opencode/pull/64930), [#64965](https://github.com/anomalyco/opencode/pull/64965))
+- Fixed large file views not refreshing when only the end of the file changed. ([#65114](https://github.com/anomalyco/opencode/pull/65114))
+- Fixed the install script failing with a disk-space error when `curl` is installed through Snap. ([#65132](https://github.com/anomalyco/opencode/pull/65132))
+
+### TUI
+
+#### Improvements
+
+- The new TUI designs are on by default, and the theme named `opencode` is the new theme. The previous default is available as `opencode-classic`, and `opencode2` keeps working as an alias of `opencode`. To go back to the previous designs, turn off **New designs** in the Experiments dialog. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
+- `/login` and `/auth` open the same dialog as `/connect`, which now lists a single **OpenCode** entry that includes OpenCode Go models. ([#65265](https://github.com/anomalyco/opencode/pull/65265), [#65466](https://github.com/anomalyco/opencode/pull/65466))
+- Pressing `↓` opens the picker on the first tab with something running, the same tab that clicking the footer opens. ([#64972](https://github.com/anomalyco/opencode/pull/64972))
+- Text prompt dialogs such as rename session, `/btw`, worktree names and connect forms end with a **Submit** button, and prompt and export dialogs have tighter spacing. ([#64944](https://github.com/anomalyco/opencode/pull/64944))
+- The `opencode` theme's light mode uses lighter grays for the prompt box, selected tabs and hovered rows. ([#64962](https://github.com/anomalyco/opencode/pull/64962))
+
+#### Bug fixes
+
+- Fixed connect forms built from integration fields, such as the Azure resource name, showing an empty row between the title and the input. ([#64944](https://github.com/anomalyco/opencode/pull/64944))
+- Fixed list dialogs ending with two blank rows, and the **Manage workspaces** footer not staying at the bottom. ([#64983](https://github.com/anomalyco/opencode/pull/64983))
+- Fixed long dialog lists replacing their last visible row with a stray `…`. ([#64934](https://github.com/anomalyco/opencode/pull/64934))
+- Fixed the selection bar of a delete-confirmation row staying blue instead of red. ([#64936](https://github.com/anomalyco/opencode/pull/64936))
+- Fixed file, agent and skill mentions landing on the wrong text when you restore a prompt sent from the desktop or web app that contains tabs or wide characters. ([#63989](https://github.com/anomalyco/opencode/pull/63989))
+
+### Desktop
+
+#### Improvements
+
+- The browser pane keeps you signed in. Links from the chat open beside the conversation in one saved profile, you can import sign-ins and browsing history from Chrome, Edge, Firefox, Safari and other browsers, and you can install store extensions after reviewing what they can access. The pane gains a right-click menu, find in page, page dialogs, permission prompts, pop-up blocking and readable error pages, and the address bar completes from your history. The agent can read and drive the same signed-in tabs. ([#63002](https://github.com/anomalyco/opencode/pull/63002), [#65073](https://github.com/anomalyco/opencode/pull/65073))
+- New tabs that a page opens in the browser pane appear beside the tab they came from, and middle-clicking a link opens it in a new tab. ([#65126](https://github.com/anomalyco/opencode/pull/65126), [#65091](https://github.com/anomalyco/opencode/pull/65091))
+- Comments in the browser pane, file viewer and review diff can be sent to the session right away with `Mod+Enter`. Depending on your follow-up setting, they send, steer or queue. ([#65264](https://github.com/anomalyco/opencode/pull/65264))
+- Added **Wrap code blocks** under Settings › General › Timeline, plus a **Wrap lines** button on timeline code blocks with lines too long to fit. ([#64545](https://github.com/anomalyco/opencode/pull/64545), [#64576](https://github.com/anomalyco/opencode/pull/64576))
+- Added **Keep side panel open across sessions** in Settings › General. ([#64950](https://github.com/anomalyco/opencode/pull/64950))
+- Added an **Archive session** command, bound to `Cmd+Shift+S` (`Ctrl+Shift+S` on Windows and Linux). ([#65428](https://github.com/anomalyco/opencode/pull/65428))
+- The Home session menu has **Open** and **Open in background**, and Home shows the provider connect hint when nothing is connected. ([#65209](https://github.com/anomalyco/opencode/pull/65209), [#65212](https://github.com/anomalyco/opencode/pull/65212), [#64885](https://github.com/anomalyco/opencode/pull/64885))
+- The Inbox layout's sidebar has a **Drafts** group for unsent new-session drafts. ([#65525](https://github.com/anomalyco/opencode/pull/65525))
+- Conversation search (`Cmd+F` / `Ctrl+F`) has previous and next match buttons. ([#64865](https://github.com/anomalyco/opencode/pull/64865))
+- The connect dialog lists one **OpenCode** option that includes OpenCode Go models, Settings › Providers follows the same rule, and the free model picker has a tighter layout. ([#65466](https://github.com/anomalyco/opencode/pull/65466), [#65740](https://github.com/anomalyco/opencode/pull/65740), [#64927](https://github.com/anomalyco/opencode/pull/64927))
+- When you reach your ChatGPT Business workspace's usage limit, a dialog explains it and offers **Copy request for admin**. ([#64926](https://github.com/anomalyco/opencode/pull/64926))
+- Voice uses the newest GPT-Live model the server lists. ([#65506](https://github.com/anomalyco/opencode/pull/65506))
+- Shortcuts go through the same keymap engine as the TUI, and the new **Stop session** command can be changed in Settings › Shortcuts. ([#64394](https://github.com/anomalyco/opencode/pull/64394))
+- Shortcuts can be key chords, such as `Mod+K Mod+C` or `G I`. In Settings › Shortcuts, click **+** on a shortcut you just recorded to add another key, up to 4. While a chord is pending, a panel lists the keys that continue it. ([#64395](https://github.com/anomalyco/opencode/pull/64395))
+- The activity pill keeps a subagent listed while work it started is still running. ([#64790](https://github.com/anomalyco/opencode/pull/64790))
+- The goal pill has a new design with the labels Following goal, Goal paused and Goal reached. ([#60001](https://github.com/anomalyco/opencode/pull/60001))
+- Keyboard focus shows as one consistent ring across the app, no longer appears after a mouse click, and moves to the next item when the focused one is removed. The timeline and the composer no longer draw a ring around their whole frame. ([#64909](https://github.com/anomalyco/opencode/pull/64909), [#64976](https://github.com/anomalyco/opencode/pull/64976), [#65082](https://github.com/anomalyco/opencode/pull/65082), [#65084](https://github.com/anomalyco/opencode/pull/65084), [#65100](https://github.com/anomalyco/opencode/pull/65100), [#65690](https://github.com/anomalyco/opencode/pull/65690))
+- Only the latest response shows its Copy button all the time; older ones show it on hover or focus. ([#64640](https://github.com/anomalyco/opencode/pull/64640))
+- Added experimental tab groups for side tabs under Settings › Experimental. ([#64407](https://github.com/anomalyco/opencode/pull/64407))
+- On Windows, the taskbar button shows session status as a progress bar, a count badge for sessions that need you, and flashes when a permission or question is waiting. Notifications say what is being asked and disappear once you answer. ([#65317](https://github.com/anomalyco/opencode/pull/65317), [#65318](https://github.com/anomalyco/opencode/pull/65318), [#65319](https://github.com/anomalyco/opencode/pull/65319), [#65325](https://github.com/anomalyco/opencode/pull/65325), [#65421](https://github.com/anomalyco/opencode/pull/65421))
+- On Windows, the jump list has **New Session** and **New Window**, you can drag files from the file tree into other apps, and **Open in** includes Windows Terminal and lists only installed apps. ([#65327](https://github.com/anomalyco/opencode/pull/65327), [#65330](https://github.com/anomalyco/opencode/pull/65330), [#65320](https://github.com/anomalyco/opencode/pull/65320))
+- The web app can be built to run under a path prefix, for example behind a reverse proxy, with `bun --cwd packages/app build --base=/opencode/`. ([#64597](https://github.com/anomalyco/opencode/pull/64597))
+- The background activity menu stays smooth with many subagents, and the model picker stays responsive with catalogs of thousands of models. ([#65634](https://github.com/anomalyco/opencode/pull/65634), [#65189](https://github.com/anomalyco/opencode/pull/65189), [#65635](https://github.com/anomalyco/opencode/pull/65635))
+
+#### Bug fixes
+
+- Fixed `opencode://open-project` and `opencode://new-session` links doing nothing. ([#65332](https://github.com/anomalyco/opencode/pull/65332))
+- Fixed file links like `~/Downloads/clip.mp4` showing "File not found". `~` now opens in the server's home folder. ([#65689](https://github.com/anomalyco/opencode/pull/65689))
+- Fixed an open session's side panel tabs disappearing after you had used many other sessions. ([#65328](https://github.com/anomalyco/opencode/pull/65328), [#65322](https://github.com/anomalyco/opencode/pull/65322))
+- Fixed the app freezing when opening a session on a remote server with **Share sign-ins with remote servers** on. ([#65339](https://github.com/anomalyco/opencode/pull/65339))
+- Fixed the app freezing for several seconds when you open a group of long Code Mode scripts. An Execute row now lists its latest 10 calls, with **+N more** for the earlier ones. ([#65696](https://github.com/anomalyco/opencode/pull/65696))
+- Fixed the browser pane showing "The browser couldn't open" in a project whose server had only just started. ([#65720](https://github.com/anomalyco/opencode/pull/65720))
+- Fixed **Clear browsing data** clearing everything on the first click; it now asks first. ([#65124](https://github.com/anomalyco/opencode/pull/65124))
+- Fixed browser tabs showing a generic globe instead of the site's icon, saved tabs appearing late after the app reopens, and the page going blank while a panel is resized on Windows. ([#65094](https://github.com/anomalyco/opencode/pull/65094), [#65067](https://github.com/anomalyco/opencode/pull/65067), [#65083](https://github.com/anomalyco/opencode/pull/65083))
+- Fixed sites in the browser pane replacing the app's badge on the taskbar or Dock. ([#65646](https://github.com/anomalyco/opencode/pull/65646))
+- Fixed the mouse Back and Forward buttons doing nothing. ([#65129](https://github.com/anomalyco/opencode/pull/65129))
+- Fixed a subagent's pending permission request not reappearing after a reload or reconnect. ([#65120](https://github.com/anomalyco/opencode/pull/65120))
+- Fixed background jobs that changed while the job list was loading showing the wrong state, and rows in the activity menu jumping around. ([#64966](https://github.com/anomalyco/opencode/pull/64966), [#65312](https://github.com/anomalyco/opencode/pull/65312))
+- Fixed the session view crashing when a timeline row disappeared mid-update. ([#64565](https://github.com/anomalyco/opencode/pull/64565))
+- Fixed earlier replies being folded into the "Used N tools" group when a session was woken without a new message. ([#64917](https://github.com/anomalyco/opencode/pull/64917))
+- Fixed the Context tab showing the latest instruction update as the "System Prompt". ([#64991](https://github.com/anomalyco/opencode/pull/64991))
+- Fixed the session header briefly showing the wrong worktree while a new session starts. ([#65190](https://github.com/anomalyco/opencode/pull/65190))
+- Fixed Grep, Glob and List rows showing the parent of the folder they searched, and Windows paths not showing relative to the project. ([#65460](https://github.com/anomalyco/opencode/pull/65460), [#65639](https://github.com/anomalyco/opencode/pull/65639))
+- Fixed server event streams going stale after Windows wakes from sleep, and windows reopening in the wrong place after being snapped or minimized. ([#65321](https://github.com/anomalyco/opencode/pull/65321), [#65323](https://github.com/anomalyco/opencode/pull/65323))
+- Fixed the Windows caption buttons being hard to see with a contrast theme. ([#65324](https://github.com/anomalyco/opencode/pull/65324))
+- Fixed **Open in PowerShell** on Windows opening Windows PowerShell instead of PowerShell 7 when it's installed. ([#64873](https://github.com/anomalyco/opencode/pull/64873))
+- Fixed builds packaged without `app-update.yml`, such as AUR packages, showing update-check errors. Settings now shows **Updates unavailable**. ([#64681](https://github.com/anomalyco/opencode/pull/64681))
+- Fixed the message menu's "Today" and "Yesterday" labels, and Home's date headers staying invisible while scrolling. ([#65081](https://github.com/anomalyco/opencode/pull/65081), [#64665](https://github.com/anomalyco/opencode/pull/64665))
+- Fixed clipped or misleading focus rings, the side panel's add button being skipped by `Tab`, and the **Compacted** label only partly highlighting on hover. ([#65215](https://github.com/anomalyco/opencode/pull/65215), [#65192](https://github.com/anomalyco/opencode/pull/65192), [#65176](https://github.com/anomalyco/opencode/pull/65176), [#65177](https://github.com/anomalyco/opencode/pull/65177), [#65211](https://github.com/anomalyco/opencode/pull/65211), [#65213](https://github.com/anomalyco/opencode/pull/65213), [#65644](https://github.com/anomalyco/opencode/pull/65644))
+- Fixed the Hex voice tip showing on phones and tablets, and a fringe on project icon corners. ([#64583](https://github.com/anomalyco/opencode/pull/64583), [#64582](https://github.com/anomalyco/opencode/pull/64582))
+
+### SDK
+
+#### Improvements
+
+- Added `experimental.job.cancel` to cancel a running background job, and an `experimental.job.updated` event when a job starts, moves to the background or ends. `@opencode/client/solid`'s `createData` has a `job` slice. ([#64790](https://github.com/anomalyco/opencode/pull/64790), [#65266](https://github.com/anomalyco/opencode/pull/65266), [#64956](https://github.com/anomalyco/opencode/pull/64956))
+- The video endpoints (`experimental.generate.video.create` and `.get`) no longer need a flag. Video jobs survive a server restart, can return more than one video, and stay readable for 24 hours after they finish. ([#65664](https://github.com/anomalyco/opencode/pull/65664), [#64546](https://github.com/anomalyco/opencode/pull/64546))
+- The automation endpoints work without a flag, and an automation can run a shell command as its action. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186))
+
+### Extensions
+
+#### Improvements
+
+- A plugin tool can set `options.codemode` to an object (`{ pinned?, description?, input?, output? }`) to give its Code Mode form its own description and schemas. Top-level `options.pinned` still works but is deprecated. ([#64515](https://github.com/anomalyco/opencode/pull/64515))
+- The `execute.before` and `execute.after` tool hooks receive `info`, the tool's definition, and `codemode`, which is true when a Code Mode script made the call. ([#64515](https://github.com/anomalyco/opencode/pull/64515))
+- An integration's OAuth method can define `revoke` to sign a credential out remotely before it's removed. ([#64947](https://github.com/anomalyco/opencode/pull/64947))
+- TUI plugins can read a session's running background jobs with `api.data.job.list(sessionID)` (experimental). ([#64956](https://github.com/anomalyco/opencode/pull/64956))
+- `experimental.idle` background entries can have the kind `video`. ([#63666](https://github.com/anomalyco/opencode/pull/63666))
+- GUI plugins can declare their own SVG icons with `Plugin.define({ icons })` and use them through `ctx.icons`. The built-in `outline-pair` and `outline-steer` icons were removed. ([#64577](https://github.com/anomalyco/opencode/pull/64577))
+- The GUI composer API adds `composer.send(commentID)` and `composer.delivery()`, and the `Browser` contract adds `experimental.open` and `experimental.close`. ([#65264](https://github.com/anomalyco/opencode/pull/65264), [#63002](https://github.com/anomalyco/opencode/pull/63002))
+- GUI `System.open` only launches HTTP, HTTPS and mail URLs, and `Browser.open` refuses `file://` URLs outside the built-in preview. ([#63002](https://github.com/anomalyco/opencode/pull/63002))
+
## v2.3.2-shuv.1 — 2026-11-20
Syncs upstream `dev` through `a96327d3e8`: 104 commits beyond the dev pin in [#508](https://github.com/shuv1337/shuvcode/pull/508), or 159 dev commits plus the v2.3.2 release since v2.3.1.
diff --git a/README.zh.md b/README.zh.md
index 53568947d2c6..7aa2bc591496 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -110,4 +110,4 @@ OpenCode 内置两种 Agent,可用 `Tab` 键快速切换:
---
-**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=52ao9352-5623-4fa0-b7dd-3407c392c1af&qr_code=true) | [X.com](https://x.com/opencode)
+**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=a53kb082-3aff-41fb-b412-b3e669334f16&qr_code=true) | [X.com](https://x.com/opencode)
diff --git a/README.zht.md b/README.zht.md
index ade183eb98f9..3f78c62f563c 100644
--- a/README.zht.md
+++ b/README.zht.md
@@ -110,4 +110,4 @@ OpenCode 內建了兩種 Agent,您可以使用 `Tab` 鍵快速切換。
---
-**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=52ao9352-5623-4fa0-b7dd-3407c392c1af&qr_code=true) | [X.com](https://x.com/opencode)
+**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=a53kb082-3aff-41fb-b412-b3e669334f16&qr_code=true) | [X.com](https://x.com/opencode)
diff --git a/bun.lock b/bun.lock
index ee85d1af4bc9..b9ffe5173df0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -29,7 +29,7 @@
},
"packages/ai": {
"name": "@opencode/ai",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@aws-sdk/credential-providers": "3.1057.0",
"@opencode/schema": "workspace:*",
@@ -66,7 +66,7 @@
},
"packages/app": {
"name": "@opencode/app",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@corvu/drawer": "catalog:",
"@dnd-kit/abstract": "0.5.0",
@@ -137,7 +137,7 @@
},
"packages/cli": {
"name": "shuvcode",
- "version": "2.3.2-shuv.1",
+ "version": "2.4.0-shuv.1",
"bin": {
"shuvcode": "./bin/shuvcode.mjs",
},
@@ -199,9 +199,25 @@
"vite-plugin-solid": "catalog:",
},
},
+ "packages/cli-rs": {
+ "name": "@opencode/cli-rs",
+ "devDependencies": {
+ "@opencode/httpapi-codegen": "workspace:*",
+ "@opencode/plugin": "workspace:*",
+ "@opencode/protocol": "workspace:*",
+ "@opencode/tui": "workspace:*",
+ "@opentui/core": "catalog:",
+ "@opentui/solid": "catalog:",
+ "@tsconfig/bun": "catalog:",
+ "@types/bun": "catalog:",
+ "@typescript/native": "catalog:",
+ "effect": "catalog:",
+ "solid-js": "catalog:",
+ },
+ },
"packages/client": {
"name": "@opencode/client",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/protocol": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -227,11 +243,11 @@
},
"packages/codemode": {
"name": "@opencode/codemode",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"acorn": "8.15.0",
"effect": "catalog:",
- "psychoscript": "0.1.2",
+ "psychoscript": "0.2.1",
},
"devDependencies": {
"@tsconfig/bun": "catalog:",
@@ -241,7 +257,7 @@
},
"packages/core": {
"name": "@opencode/core",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@ai-sdk/provider": "3.0.19",
"@effect/platform-node": "catalog:",
@@ -290,6 +306,13 @@
"@ai-sdk/openai-compatible": "2.0.41",
"@anthropic-ai/claude-agent-sdk": "0.3.301",
"@hona/strobe": "catalog:",
+ "@number0/iroh-darwin-arm64": "1.2.0",
+ "@number0/iroh-linux-arm64-gnu": "1.2.0",
+ "@number0/iroh-linux-arm64-musl": "1.2.0",
+ "@number0/iroh-linux-x64-gnu": "1.2.0",
+ "@number0/iroh-linux-x64-musl": "1.2.0",
+ "@number0/iroh-win32-arm64-msvc": "1.2.0",
+ "@number0/iroh-win32-x64-msvc": "1.2.0",
"@opencode/http-recorder": "workspace:*",
"@parcel/watcher-darwin-arm64": "2.5.1",
"@parcel/watcher-darwin-x64": "2.5.1",
@@ -306,6 +329,9 @@
"drizzle-kit": "catalog:",
"fast-check": "catalog:",
},
+ "optionalDependencies": {
+ "@number0/iroh": "1.2.0",
+ },
"peerDependencies": {
"@anthropic-ai/claude-agent-sdk": "0.3.301",
},
@@ -315,7 +341,7 @@
},
"packages/data/app": {
"name": "@opencode/data-app",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@kobalte/core": "catalog:",
"@opencode/data-core": "workspace:*",
@@ -343,7 +369,7 @@
},
"packages/data/core": {
"name": "@opencode/data-core",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@planetscale/database": "1.19.0",
"drizzle-orm": "catalog:",
@@ -360,7 +386,7 @@
},
"packages/data/server": {
"name": "@opencode/data-server",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/data-core": "workspace:*",
"effect": "catalog:",
@@ -376,7 +402,7 @@
},
"packages/desktop": {
"name": "@opencode/desktop",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@zip.js/zip.js": "2.7.62",
"electron-context-menu": "5.0.0",
@@ -443,7 +469,7 @@
},
"packages/gui-plugins": {
"name": "@opencode/gui-plugins",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@betteroffice/docx": "0.4.3",
"@betteroffice/fonts": "0.4.0",
@@ -490,7 +516,7 @@
},
"packages/http-recorder": {
"name": "@opencode/http-recorder",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@effect/platform-node-shared": "catalog:",
},
@@ -509,7 +535,7 @@
},
"packages/httpapi-codegen": {
"name": "@opencode/httpapi-codegen",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"effect": "catalog:",
"prettier": "3.6.2",
@@ -522,7 +548,7 @@
},
"packages/latex": {
"name": "@opencode/latex",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -536,7 +562,7 @@
},
"packages/merman": {
"name": "@opencode/merman",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -551,7 +577,7 @@
},
"packages/nav-menus": {
"name": "@opencode/nav-menus",
- "version": "2.3.2",
+ "version": "2.4.0",
"devDependencies": {
"@happy-dom/global-registrator": "20.0.11",
"@types/bun": "catalog:",
@@ -562,7 +588,7 @@
},
"packages/patchmark": {
"name": "@opencode/patchmark",
- "version": "2.3.2",
+ "version": "2.4.0",
"devDependencies": {
"@tsconfig/bun": "catalog:",
"@types/bun": "catalog:",
@@ -575,7 +601,7 @@
},
"packages/plugin": {
"name": "@opencode/plugin",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode/ai": "workspace:*",
@@ -620,7 +646,7 @@
},
"packages/plugin-browser": {
"name": "@opencode/plugin-browser",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -636,7 +662,7 @@
},
"packages/plugins/figma": {
"name": "@opencode/plugin-figma",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"gray-matter": "4.0.3",
},
@@ -651,7 +677,7 @@
},
"packages/protocol": {
"name": "@opencode/protocol",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/schema": "workspace:*",
"effect": "catalog:",
@@ -681,7 +707,7 @@
},
"packages/schema": {
"name": "@opencode/schema",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@standard-schema/spec": "catalog:",
"effect": "catalog:",
@@ -706,7 +732,7 @@
},
"packages/sdk": {
"name": "@opencode/sdk",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -727,7 +753,7 @@
},
"packages/server": {
"name": "@opencode/server",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
@@ -750,7 +776,7 @@
},
"packages/session-ui": {
"name": "@opencode/session-ui",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@kitlangton/solid-motion": "0.2.2",
"@kobalte/core": "catalog:",
@@ -782,7 +808,7 @@
},
"packages/simulation": {
"name": "@opencode/simulation",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/ai": "workspace:*",
"@opencode/core": "workspace:*",
@@ -820,7 +846,7 @@
},
"packages/theme": {
"name": "@opencode/theme",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opentui/core": "catalog:",
"effect": "catalog:",
@@ -834,7 +860,7 @@
},
"packages/tui": {
"name": "@opencode/tui",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -870,7 +896,7 @@
},
"packages/ui": {
"name": "@opencode/ui",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@kitlangton/solid-motion": "0.2.2",
"@kobalte/core": "catalog:",
@@ -906,7 +932,7 @@
},
"packages/util": {
"name": "@opencode/util",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"@effect/opentelemetry": "catalog:",
"@effect/platform-node": "catalog:",
@@ -1045,7 +1071,7 @@
},
"services/update": {
"name": "@opencode/update",
- "version": "2.3.2",
+ "version": "2.4.0",
"dependencies": {
"jose": "6.0.11",
"semver": "catalog:",
@@ -1105,7 +1131,7 @@
"@effect/platform-node-shared": "4.1.0",
"@effect/sql-sqlite-bun": "4.1.0",
"@effect/sql-sqlite-node": "4.1.0",
- "@hona/strobe": "0.42.0",
+ "@hona/strobe": "0.44.1",
"@kobalte/core": "0.13.13",
"@lydell/node-pty": "1.2.0-beta.12",
"@npmcli/arborist": "9.4.0",
@@ -1648,19 +1674,19 @@
"@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="],
- "@hona/strobe": ["@hona/strobe@0.42.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.42.0", "@hona/strobe-darwin-x64": "0.42.0", "@hona/strobe-linux-arm64": "0.42.0", "@hona/strobe-linux-x64": "0.42.0", "@hona/strobe-win32-arm64": "0.42.0", "@hona/strobe-win32-x64": "0.42.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-9yGVLIZszb4rw91ew9MYn+K+19WiEd24pY104fz8vKF3VF21qn+bv/MdrLHqGrE3fwEZvocR9uwrRuWjyDS7YQ=="],
+ "@hona/strobe": ["@hona/strobe@0.44.1", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.44.1", "@hona/strobe-darwin-x64": "0.44.1", "@hona/strobe-linux-arm64": "0.44.1", "@hona/strobe-linux-x64": "0.44.1", "@hona/strobe-win32-arm64": "0.44.1", "@hona/strobe-win32-x64": "0.44.1" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-9HKNumRLqJm9OlAPCSNcB8HykhF5F7I4wcTwRf+CJ78xzDcMUSIekjRWz8MjpsTL5t4GdIckmMtyY7duiwo46A=="],
- "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.42.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-b3UmIH7pzDzmXSZJKzj6B0UNIO9D/zU0scI/Be9l6Lx7FOXVTMM9UyHdYlDOAUyC8ew4GIRW4Owksq8qu9Vdxw=="],
+ "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.44.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-WsTn+iyJMy0/UTSCv5ZaS8JQ984ZSA724OcyYP+znncSEVFDkJbtWSKMQOCYJ6Z7TDP9PPSXIs/YhwdfPXvPow=="],
- "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.42.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-rMcTyYJH6Dg+NRur4Id8EyM3lZJSAxCCGFVe9qc+cy1GwBdDFjRmvSxqsdCQ/ah6txlkCOIWpyAxOuCk1z4liA=="],
+ "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.44.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-lYnOotxHyBLJKrUZ+OPoMzDHqbv8MNU6rw4hy9LxIlbjJQ6szfl1WmQWDJVjGNlTH7xgd8nfQQDCSSdDNGJ1YA=="],
- "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.42.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-3QAWiuMc7kvpKvEtf0XE115PIAsQ+jXqgKrIUpcex943maskLTI1ZQIfJZTFqQm8EeeLe9nRI5X6jJt3ezsxhQ=="],
+ "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.44.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-lHtb1VIYCK64OpannKujYtmUUr58inwZYyI+D6m/FcqSYnHadMdXSIhDoVWDFQwH0kDJ1uB5Jbu+sYMQDXMujw=="],
- "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.42.0", "", { "os": "linux", "cpu": "x64" }, "sha512-LJLtYy3HrYzXAA5mKrTAZ4oWnEQHig6MwfYaqLaBoR3q/0z8qDR5u1dPcsppzI1jlS6WD3isjmXSmWYHe32CcQ=="],
+ "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.44.1", "", { "os": "linux", "cpu": "x64" }, "sha512-a0uTF+Er8qBEzcusczs4r+DTBmEWHEvvMGkEE4hRzNIWw/b3o4x9khGh0vaoyXFp3H7S0x4mI4LcFItyc2kamA=="],
- "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.42.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-upHLoBRbDsqMTmbm5QoryhUBPiQchp1MWo8FaImfPElsy25uiQKnlWfS5y4NlRLfZFZBStiSbiC0zupmXKxx0g=="],
+ "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.44.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-CpOrG4ruzC7pq01WQR01HisipFgBd3ZTLl4QHirMk9khCmOE/E32lEqaEaIZ24q9hub3ozDfbVdzHRWXkHKAXw=="],
- "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.42.0", "", { "os": "win32", "cpu": "x64" }, "sha512-cD64z5dlcNBDOgYnJlN5bcvGo1m8KUn7Ax3ttzZH33G9dVpeWdb+QhLgBq/CtPDKHf21mD+5WklCYaLMRBHk6A=="],
+ "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.44.1", "", { "os": "win32", "cpu": "x64" }, "sha512-eH1/RvKy2en7DAUFinyq1ITw9FR/S0IJVrgXcHigxSyjUQIBsvII0UenbVeBoE4/ljd/BOw4aLx/GBsznrn1Zg=="],
"@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="],
@@ -1824,6 +1850,30 @@
"@npmcli/run-script": ["@npmcli/run-script@10.0.4", "", { "dependencies": { "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "node-gyp": "^12.1.0", "proc-log": "^6.0.0" } }, "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg=="],
+ "@number0/iroh": ["@number0/iroh@1.2.0", "", { "optionalDependencies": { "@number0/iroh-android-arm-eabi": "1.2.0", "@number0/iroh-android-arm64": "1.2.0", "@number0/iroh-darwin-arm64": "1.2.0", "@number0/iroh-linux-arm-gnueabihf": "1.2.0", "@number0/iroh-linux-arm-musleabihf": "1.2.0", "@number0/iroh-linux-arm64-gnu": "1.2.0", "@number0/iroh-linux-arm64-musl": "1.2.0", "@number0/iroh-linux-x64-gnu": "1.2.0", "@number0/iroh-linux-x64-musl": "1.2.0", "@number0/iroh-win32-arm64-msvc": "1.2.0", "@number0/iroh-win32-x64-msvc": "1.2.0" } }, "sha512-pZoVnL+8nK4DQG3owF5UQ/LcIjg7m2Ue1oeEUEhLsNt9RHtEFxiASNSPopOdsRfjRimJ/e6zjQ0k3iYE6N1hZQ=="],
+
+ "@number0/iroh-android-arm-eabi": ["@number0/iroh-android-arm-eabi@1.2.0", "", { "os": "android", "cpu": "arm" }, "sha512-T8Hp4G1ewh/7AUI8DBHi596Rlr9zZZzPA3CpN58XSSQBxUEpiqxtZoYmEa3w6QgVw1o5IQrEgAUxLN7ogBtnig=="],
+
+ "@number0/iroh-android-arm64": ["@number0/iroh-android-arm64@1.2.0", "", { "os": "android", "cpu": "arm64" }, "sha512-etoVzrsoPAij+XhD+BECISJKYUG6eW+XS43I5P4SD+nqAIJ6XnMTy/Brwayuj8ERoRaFLClL8bb++v5883TcrA=="],
+
+ "@number0/iroh-darwin-arm64": ["@number0/iroh-darwin-arm64@1.2.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-91oxmPrYiCnU0APp/Ky0mgNOxaIukQDFUvxth32TDq38vJs0lDX9ppAsWrkCA+4A/kJnAt1hc7YhIKcIGD3xOA=="],
+
+ "@number0/iroh-linux-arm-gnueabihf": ["@number0/iroh-linux-arm-gnueabihf@1.2.0", "", { "os": "linux", "cpu": "arm" }, "sha512-PTi5YyxjkLluzVec5Q0NJqRUaYcVT76sZ0SaM10HFGlwlTIniYO7DYUGTLs+XcByUBcE7Ph5xkyvoLmB1mOF4A=="],
+
+ "@number0/iroh-linux-arm-musleabihf": ["@number0/iroh-linux-arm-musleabihf@1.2.0", "", { "os": "linux", "cpu": "arm" }, "sha512-IwOPvWOEyX6ZMHjctDaZyWVV2kJSXx57DRN2l5Qg/cEQjY5zWO4IMFvjw075IKrQk+VpU6RrEEI++2w2Gci1dA=="],
+
+ "@number0/iroh-linux-arm64-gnu": ["@number0/iroh-linux-arm64-gnu@1.2.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-LEenFEMMWLnlyFy8++cYq+s7/nibFgFzs1kGDk7WvFDyxT3U2z0W0+hjENzDiS1iCtH8+zesdDdFxuQtxjJHYg=="],
+
+ "@number0/iroh-linux-arm64-musl": ["@number0/iroh-linux-arm64-musl@1.2.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-YgCWpz80VOTJRtAUsTKFgLYtd7tfWwrRCD0uk3/xG4z+AjiY5c49toeDFTJJ/3SF5Q8qmjWGjpcUk6B1E55D4w=="],
+
+ "@number0/iroh-linux-x64-gnu": ["@number0/iroh-linux-x64-gnu@1.2.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-SkZUe/dqv7J1kY3Af0Cu07ldfdstEDOz6F3yIKwMw/EpabhaE3fvdDbiDQoiMxbwgIiJMspChHRMZeC88Td3QQ=="],
+
+ "@number0/iroh-linux-x64-musl": ["@number0/iroh-linux-x64-musl@1.2.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-UnZHStWdFZgylftmX2IHF+VKkrkbEhK+amkOf7A9Z3JPrqkbF5em3UW3uyDK3qfhcc9Ijc3nnYKxym+BkOLPjQ=="],
+
+ "@number0/iroh-win32-arm64-msvc": ["@number0/iroh-win32-arm64-msvc@1.2.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-2srn9OquRffLD1bQiCDRLr3T1yxmc9xc3k4oLgEMWU+lZnaMONRS2r46cTXN1b/bGsSc82TjGCO/urauXZjQcQ=="],
+
+ "@number0/iroh-win32-x64-msvc": ["@number0/iroh-win32-x64-msvc@1.2.0", "", { "os": "win32", "cpu": "x64" }, "sha512-3ltCadoaZzrRM9OmPcfwPpqwF/DBXlzhwsOIXITtpFEFfRISgvbqyhmMCaiumpyXxFeGTCfpwvUJ40i+sE0sVQ=="],
+
"@octokit/auth-app": ["@octokit/auth-app@8.0.1", "", { "dependencies": { "@octokit/auth-oauth-app": "^9.0.1", "@octokit/auth-oauth-user": "^6.0.0", "@octokit/request": "^10.0.2", "@octokit/request-error": "^7.0.0", "@octokit/types": "^14.0.0", "toad-cache": "^3.7.0", "universal-github-app-jwt": "^2.2.0", "universal-user-agent": "^7.0.0" } }, "sha512-P2J5pB3pjiGwtJX4WqJVYCtNkcZ+j5T2Wm14aJAEIC3WJOrv12jvBley3G1U/XI8q9o1A7QMG54LiFED2BiFlg=="],
"@octokit/auth-oauth-app": ["@octokit/auth-oauth-app@9.0.4", "", { "dependencies": { "@octokit/auth-oauth-device": "^8.0.4", "@octokit/auth-oauth-user": "^6.0.3", "@octokit/request": "^10.0.13", "@octokit/types": "^17.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-Pe3du5LrC6dlv10b0RbarBlJtIT1Urq8BFoQklK8WmBw8YKnGgrANn7cQmHiA1v8AVihgi7YutV8MncP57I4og=="],
@@ -1870,6 +1920,8 @@
"@opencode/app": ["@opencode/app@workspace:packages/app"],
+ "@opencode/cli-rs": ["@opencode/cli-rs@workspace:packages/cli-rs"],
+
"@opencode/client": ["@opencode/client@workspace:packages/client"],
"@opencode/codemode": ["@opencode/codemode@workspace:packages/codemode"],
@@ -3958,7 +4010,7 @@
"proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
- "psychoscript": ["psychoscript@0.1.2", "", { "dependencies": { "acorn": "8.15.0" }, "peerDependencies": { "effect": "^4.1.0" } }, "sha512-eEuVbhaQ+3MEfi+LTNatMFY0OWcrmZjiUDd/4KVmWOCBTVYY87QoIc/DPNTDu+GVKHDeAPCsIqDq6wVyLMODXA=="],
+ "psychoscript": ["psychoscript@0.2.1", "", { "dependencies": { "acorn": "8.15.0" }, "peerDependencies": { "effect": "^4.1.0" }, "optionalPeers": ["effect"] }, "sha512-kzDhlTdkk6DurnTMD95Vd98nfw5TFS6Sf4QyxEP0vclAlniB2vt2ZWjNwQ3NKXynfJL4lsbP+wjrRRdqkahUiw=="],
"pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
diff --git a/docs/sync-2026-11-23-v2.4.0.md b/docs/sync-2026-11-23-v2.4.0.md
new file mode 100644
index 000000000000..d74f02a8417f
--- /dev/null
+++ b/docs/sync-2026-11-23-v2.4.0.md
@@ -0,0 +1,127 @@
+# Upstream v2.4.0 sync and v2.4.0-shuv.1 prep — 2026-11-23 PST
+
+Requested as SM-MESH-OPENCODE-240. This PR does not merge, tag, publish or deploy anything. Do not merge without Cap's go.
+
+## Pins and ancestry
+
+| Pin | Commit |
+| --------------------------------------------------- | ------------------------------------------------------------------------ |
+| Fork base (`origin/integration-v2`, #510) | `dcbd2e8d613be915553a8ebec4299acea561a857` |
+| Previous upstream pin / merge base | `a96327d3e84d795cca231dc30b534193bbc0f47b` (#509) |
+| Merged upstream `dev` | `d284e7ce17d0a98c80d0bebd5cc6dce2dbdd5f74` |
+| `v2.4.0` tag (lightweight, content-audit reference) | `44aed4fd144611879046ae923c25541f913780ad` |
+| `v2.4.0` release commit on `dev` | `d6379ff0e1c1c09e927e63c28c58a1f2a0533462` |
+| Live `dev` at final re-pin (not taken) | `7cfd86844337705d8753b989570ed9bacb93bc92` (#65758, app focus-order fix) |
+
+- Upstream's default branch is still `dev` (`git ls-remote --symref upstream HEAD`). The frozen `v2` branch and the 2.0/alpha refs were not used.
+- The tag is not on `dev`. It points at a release commit whose parent is `609e4bb6ae`. `dev` then landed three commits (`1906056539`, `7edab789f7`, `26f4041911`) and its own `release: v2.4.0 (#65753)` commit `d6379ff0e1`. That commit has the same `git patch-id --stable` (`86f9a65dca`) as the tag commit: both apply the same version bumps, lockfile entries and CHANGELOG section. A dev merge therefore already contains everything the tag adds, so the tag commit is not merged separately.
+- `dev` has one more commit after its release commit: `d284e7ce17` (#65757, an accent-color fix in the app). It is included because the sync follows `dev`.
+- That makes 183 upstream commits past #509. Without the new native CLI in `packages/cli-rs` (2,125 files), upstream changed 808 files. No upstream commit touches `.github`.
+
+## Tag audit
+
+`git diff --name-only v2.4.0 HEAD` lists 754 paths. Each one is either:
+
+- one of the 60 paths the four post-tag `dev` commits change (`git diff v2.4.0 d284e7ce17`), or
+- one of the 712 fork-delta paths (`git diff d284e7ce17 HEAD`).
+
+No path falls outside both sets. The fork-delta set matches the set before this sync (`git diff a96327d3e8 dcbd2e8`) with three kinds of differences:
+
+- 27 workspace `package.json` files now match upstream `2.4.0`. Their only fork difference had been the version.
+- `automation.ts`, `automation.txt` and `tool-automation.test.ts` now follow upstream's `automation` namespace (see below).
+- Eight new fork-identity adaptations were added (listed under follow-ups).
+
+## Conflict resolutions (51 paths)
+
+The merge commit `354e4a0128` resolves only these paths. Review them with `git show --remerge-diff 354e4a0128`.
+
+| Path | Resolution |
+| ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 32 `package.json` files (root, workspaces, `sdks/vscode`, `services/update`) | Take upstream `2.4.0`. Only the version line conflicted. |
+| `packages/cli/package.json` | Keep fork name `shuvcode`, bin `shuvcode`. The version stays at `2.3.2-shuv.1` in the merge and moves to `2.4.0-shuv.1` in the release-prep commit. |
+| `bun.lock` | Take upstream versions. Keep the `shuvcode` CLI workspace entry. Keep the new `@opencode/cli-rs` workspace line but not upstream's `@opencode/cli` line. `bun install --frozen-lockfile` passes. |
+| `CHANGELOG.md` | Put upstream's v2.4.0 section verbatim above the fork's history. The upstream sections (v2.4.0, v2.3.2, v2.3.1) match `dev` byte for byte. |
+| `packages/cli/src/commands/commands.ts` | Keep the fork's global `--server`/`--standalone` (`ServerFlags`, `connectionFlags`) and the Shuvcode root name and description. Take upstream's `serverURLFlag`, `LoginParams`, hidden `login` alias and `machine` command, without upstream's per-command `ServerParams`/`globalFlags: ServerFlags`. |
+| `packages/cli/src/framework/spec.ts` | Use both: upstream's hidden alias (`Command.unlisted`) and the fork's `connectionFlags` on alias nodes. |
+| `packages/cli/src/commands/handlers/default.ts` | Take upstream's directory-or-help check. The requested server still comes from `ServerFlags.read()`. |
+| `packages/cli/src/commands/handlers/auth/login.ts` | Keep the `isHiddenProvider` filter and add upstream's "OpenCode Go only with a saved key" filter. |
+| `packages/tui/src/component/dialog-integration.tsx` | Same: hidden-provider filter plus upstream's Go filter. |
+| `packages/tui/src/component/dialog-model-free.tsx` | Keep the hidden-provider filter and add upstream's speed-variant filter. |
+| `packages/core/src/config.ts` | Keep fork diagnostics (`Diagnostic`, positions) and add upstream's `App` import. Upstream's `removed` diagnostic kind logs a warning; invalid entries still report positioned diagnostics. |
+| `packages/core/src/tool.ts` | Keep the fork's `executeCall` + `ToolActivity` lease + `settleFailure` split. Move upstream's new body into `executeCall`: top-level Code Mode tool calls, and background options for full Code Mode. |
+| `packages/core/src/tool/plugin/automation.ts`, `plugin/command/automation.txt` | Take upstream's own `automation` namespace (#65001). It replaced `opencode.automation_*`, the names the fork had rebranded to `shuvcode.automation_*`. The new namespace carries no brand. |
+| `packages/core/src/automation/code.ts` | Take upstream's trimmed unattended denylist (#65217), with `opencode.session.move` → `shuvcode.session.move`. |
+| `packages/core/test/automation.test.ts` | Take upstream's assertion and add the `shuvcode.session.move` denial. |
+| `packages/core/test/tool-automation.test.ts` | Take upstream's names. |
+| `packages/core/test/tool-mcp-events.test.ts` | Drop the fork's flag-off test, because upstream removed the `mcp_events` flag (#65271). Keep the fork's `opencode_list_mcp_events` deny-mapping test. |
+| `packages/core/test/tool-model-policy.test.ts` | Take upstream's expectation with the `shuvcode.session_move` path. |
+| `services/site/src/docs/content/permissions.mdx` | Keep the fork's `jev_systemOne` row and take upstream's `generate_image` rename. |
+
+## Follow-ups after the merge
+
+- `d6b171a7b3` `fix(core)`:
+ - Register upstream's new `session.search`/`read` (#65076) and `session.interrupt` (#65718) tools under `shuvcode.session`, and update their descriptions, the `sqlite_fts` flag text and the session-search tests.
+ - Switch the new `machine` handler and its tests, and the `login` alias test, to `ServerFlags.read()`. Upstream's `Server`/`Standalone` exports do not exist in the fork.
+ - Expect `shuvcode` in the new help-text tests. The machine error now says `shuvcode service unset disabled`.
+ - Update the fork identity test: automation tools are under `automation`, the forbidden list is the trimmed one, and the removed `automations`/`mcp_events` experimental flags are gone. Add `follows` to its npm mock.
+- `73b016a4a3` `chore(hygiene)`: allowlist the RFC 6455 sample `Sec-WebSocket-Key` nonce in `.gitleaks.toml`. It is used by upstream's `packages/server/test/machine-link.test.ts`.
+- `chore(release)`: `shuvcode` `2.4.0-shuv.1`, its lockfile entry, and release notes.
+
+## Behavior changes to review
+
+- **Automation tool names.** `tools.shuvcode.automation_*` / `shuvcode_automation_*` become `tools.automation.*` / `automation_*`. Permission rules that name the old tools need updating.
+- **Unattended denylist.** Upstream now lets automation code call `shell`, `session.rename` and the worktree tools. The permission prompts at creation are marked `unattended`. Only automation management and `session.move` stay blocked. This follows upstream's design and its tests. Keeping the fork's stricter list instead would break upstream's `automation-shell` capability test and is a policy decision for Cap.
+- **Automations default on.** They use the top-level `automations` key, and `experimental.automations` no longer applies.
+
+## Fork preservation
+
+- No changes in `dcbd2e8..HEAD` to:
+ - `Global.app` (`shuvcode`), service ports `0x1337`/`0x1338` or the npm-only updater
+ - `packages/cli/script/publish.ts`, `packages/script/src/version.ts` or the CLI `bin`
+ - the hidden-provider predicate, the `ProviderPlugins` Claude Agent filter, or the Antigravity, Claude, quota or gpt-live plugins
+ - `.github`
+- Claude Agent stays hidden. The same 17 files reference `isHiddenProvider`, and there are zero `claudeAgent` i18n keys. Upstream's new Claude websearch provider is registered only from the unloaded Claude Agent plugin.
+- `packages/cli-rs` (upstream's native Rust CLI) is in the tree as an upstream-owned path, outside fork build and publish. Its `typecheck` passes in the root check.
+
+## Branch inventory
+
+- No open PRs.
+- No fork branches were added or left unmerged since #509. `antigravity-no-retry`, `pwsh-hosted-probe` and `pwsh-ci-diag` keep their recorded dispositions.
+- No branch was deleted.
+
+## Validation
+
+Run on the final tree:
+
+| Gate | Result |
+| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `bun install --frozen-lockfile` | Pass (no changes) |
+| Root `bun run check` | Pass, 41/41 tasks |
+| `bun run migration --check` (`packages/core`) | Pass; no schema changes |
+| `bun run generate` (`packages/client`) | Pass; no generated diff |
+| Core | 7,823 pass / 350 skip / 0 fail. The `ConfigSkillPlugin` watcher test passed. |
+| CLI / TUI / Server / AI | 536 pass, 8 skip / 1,806 pass, 2 skip / 176 pass, 1 skip / 2,311 pass, 29 skip |
+| Schema / Protocol / Util / Plugin / Client / Codemode | 95 / 14 / 157 / 38 / 279 / 322 pass |
+| Browser plugin / Session UI / App unit | 210 / 675 (2 skip) / 2,877 pass |
+| Antigravity / Claude / quota plugins | 25 / 43 / 34 pass |
+| gitleaks 8.21.2 `dir . --config .gitleaks.toml --redact` | No leaks. The only prior hit was the RFC 6455 sample nonce. |
+| gitleaks `git` over `dcbd2e8..HEAD` | One `generic-api-key` hit in `packages/cli-rs/crates/api/tests/all/api.rs`: base64 of the test password `opencode:secret`. It is a false positive, and CI's `dir` mode does not flag it. |
+
+## Expected hygiene failure
+
+The fleet hygiene PII and shellcheck steps flag upstream files under `packages/cli-rs`:
+
+- Synthetic home paths such as `/home/ada` and `/Users/meow` in the parity oracles and three crate sources.
+- Two tree-sitter query author emails.
+- Upstream shell scripts that lack a shebang or `shell` directive (SC2148/SC2034/SC2209).
+
+None are fork data. The fix is six lines in `.github/hygiene-allowlist.txt`. This PR leaves them out because `.github` is frozen under the CI-gates hold; they need Cap's approval or a separate PR. With them, the local hygiene script reports `hygiene: clean`:
+
+```text
+pii:packages/cli-rs/parity/oracle/*
+pii:packages/cli-rs/crates/mini/src/shell.rs
+pii:packages/cli-rs/crates/tui/src/dialogs/open.rs
+pii:packages/cli-rs/crates/ui/src/prompt_input/attach.rs
+pii:packages/cli-rs/assets/queries/*
+shellcheck:packages/cli-rs/*
+```
diff --git a/install b/install
index f7914b02ec34..a54ca69727be 100755
--- a/install
+++ b/install
@@ -262,6 +262,26 @@ print_progress() {
printf "\r${ORANGE}%s%s %3d%%${NC}" "$filled" "$empty" "$percent" >&4
}
+install_tmp_dir=""
+download_curl_pid=""
+cursor_hidden=false
+
+cleanup_download() {
+ if [ -n "${download_curl_pid:-}" ]; then
+ kill "$download_curl_pid" 2>/dev/null || true
+ wait "$download_curl_pid" 2>/dev/null || true
+ download_curl_pid=""
+ fi
+ if [ "$cursor_hidden" = "true" ]; then
+ { printf '\033[?25h' >&4; exec 4>&-; } 2>/dev/null || true
+ cursor_hidden=false
+ fi
+ if [ -n "${install_tmp_dir:-}" ]; then
+ rm -rf "$install_tmp_dir"
+ install_tmp_dir=""
+ fi
+}
+
download_with_progress() {
local url="$1"
local output="$2"
@@ -272,20 +292,23 @@ download_with_progress() {
exec 4>/dev/null
fi
- local headers="${output}.headers"
-
# Hide cursor
printf "\033[?25l" >&4
+ cursor_hidden=true
- trap "trap - RETURN; rm -f \"$headers\"; printf '\033[?25h' >&4; exec 4>&-" RETURN
+ trap 'trap - RETURN; if [ "$cursor_hidden" = "true" ]; then printf "\033[?25h" >&4; exec 4>&-; cursor_hidden=false; fi' RETURN
+
+ local headers="${output}.headers"
# Poll the file size on a timer so rendering cost stays fixed no matter how many bytes arrive.
# Read the size with ls because busybox wc -c reads the whole file.
- curl -fsL -D "$headers" -o "$output" "$url" &
- local curl_pid=$!
+ # Bash opens both files so a confined curl (e.g. snap) with a private /tmp can still write them.
+ # npm's CDN omits content-length on HEAD, so read it from this request's headers.
+ curl -fsL -D /dev/stderr "$url" > "$output" 2> "$headers" &
+ download_curl_pid=$!
local length bytes
- while kill -0 "$curl_pid" 2>/dev/null; do
+ while kill -0 "$download_curl_pid" 2>/dev/null; do
if [ -f "$output" ]; then
length=$(grep -i '^content-length:' "$headers" 2>/dev/null | tail -n 1 | tr -dc '0-9' || true)
bytes=$(ls -ln "$output" | awk '{print $5}')
@@ -295,7 +318,8 @@ download_with_progress() {
done
local ret=0
- wait "$curl_pid" || ret=$?
+ wait "$download_curl_pid" || ret=$?
+ download_curl_pid=""
if [ "$ret" -eq 0 ]; then
bytes=$(ls -ln "$output" | awk '{print $5}')
print_progress "$bytes" "$bytes"
@@ -308,11 +332,16 @@ download_and_install() {
print_message info "\n${MUTED}Installing ${NC}$APP ${MUTED}version: ${NC}$specific_version"
local tmp_dir="${TMPDIR:-/tmp}/opencode_install_$$"
mkdir -p "$tmp_dir"
+ install_tmp_dir="$tmp_dir"
+ trap cleanup_download EXIT
+ trap 'exit 130' INT
+ trap 'exit 143' TERM
if [[ "$os" == "windows" ]] || ! [ -t 2 ] || ! download_with_progress "$url" "$tmp_dir/$filename"; then
# Fallback to standard curl on Windows, non-TTY environments, or if custom progress fails
local ret=0
- curl -f -# -L -o "$tmp_dir/$filename" "$url" || ret=$?
+ # Redirect in bash instead of passing -o to curl so confined builds (e.g. snap) don't need host /tmp access.
+ curl -f -# -L "$url" > "$tmp_dir/$filename" || ret=$?
# curl exits 23 when it cannot write the file, usually because the temporary directory is full.
if [ "$ret" -eq 23 ]; then
print_message error "Could not write the download to $tmp_dir. Make sure it has enough free space, or set TMPDIR to another directory, then try again." >&2
@@ -329,7 +358,7 @@ download_and_install() {
fi
mv "$tmp_dir/package/bin/$binary_name" "$INSTALL_DIR/$installed_binary"
chmod 755 "$INSTALL_DIR/$installed_binary"
- rm -rf "$tmp_dir"
+ cleanup_download
}
install_from_binary() {
diff --git a/nix/hashes.json b/nix/hashes.json
index fa493666eeef..8e41b50c180e 100644
--- a/nix/hashes.json
+++ b/nix/hashes.json
@@ -1,7 +1,7 @@
{
"nodeModules": {
- "x86_64-linux": "sha256-UOVs48Z4yO4TJv859cg89lsul54KB9StTSl/VSQJXmc=",
- "aarch64-linux": "sha256-INQvojH68t0J1Hc61N1dJvTJzl89afkQNrUcahxOs9g=",
- "aarch64-darwin": "sha256-AU2AUkdlL1g+hBkMZX93gQeQy6u8F0Gyzuk48yoN8as="
+ "x86_64-linux": "sha256-1YrR3eb2bEvJZx3q3iIpcQHk36nULYu1gs3X6nBEj8o=",
+ "aarch64-linux": "sha256-PnkwTGoX8CwvCw9+rZ10nXum4vzYY9OO2PEZfFj0yqw=",
+ "aarch64-darwin": "sha256-BLUBWz7HjYSgH4v+Y9nLy/lOsQeEcrel+KsagEE6Xro="
}
}
diff --git a/package.json b/package.json
index 16dcd00db98d..e644b492b79d 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode",
"description": "AI-powered development tool",
- "version": "2.3.2",
+ "version": "2.4.0",
"private": true,
"type": "module",
"packageManager": "bun@1.4.4",
@@ -48,7 +48,7 @@
"@effect/sql-sqlite-node": "4.1.0",
"@npmcli/arborist": "9.4.0",
"@types/bun": "1.4.3",
- "@hona/strobe": "0.42.0",
+ "@hona/strobe": "0.44.1",
"@types/cross-spawn": "6.0.6",
"@octokit/rest": "22.0.0",
"@opentui/core": "0.9.4",
diff --git a/packages/ai/package.json b/packages/ai/package.json
index d4bea63b84ec..a9af598fdcb4 100644
--- a/packages/ai/package.json
+++ b/packages/ai/package.json
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
- "version": "2.3.2",
+ "version": "2.4.0",
"name": "@opencode/ai",
"type": "module",
"license": "MIT",
diff --git a/packages/ai/src/experimental.ts b/packages/ai/src/experimental.ts
index 2e4740b8ed95..61247ac62c5a 100644
--- a/packages/ai/src/experimental.ts
+++ b/packages/ai/src/experimental.ts
@@ -72,6 +72,7 @@ export type {
export { Realtime } from "./experimental/realtime.js"
export type {
RealtimeConnectInput,
+ RealtimeEngine,
RealtimeSession,
RealtimeTransport,
RealtimeTransportInput,
diff --git a/packages/ai/src/experimental/realtime.ts b/packages/ai/src/experimental/realtime.ts
index a8ee20d0e0c9..42fa22a40c2f 100644
--- a/packages/ai/src/experimental/realtime.ts
+++ b/packages/ai/src/experimental/realtime.ts
@@ -21,6 +21,7 @@ export type RealtimeTransport =
export type RealtimeSession = Readonly>
export interface RealtimeConnectInput {
+ readonly engine: RealtimeEngine
readonly model: string
readonly apiKey: Redacted.Redacted
/** Where a GPT-Live session starts, OpenAI by default: another host of its API, such as OpenCode's. */
@@ -32,32 +33,18 @@ export interface RealtimeConnectInput {
readonly transport: RealtimeTransportInput
}
+// The voice APIs this package speaks, by provider and models.dev API. Which models they start comes from models.dev.
export const engines = [
- { family: "gpt-live", model: "gpt-live-1", id: "openai-live", provider: "openai", transports: ["webrtc"] },
- {
- family: "gpt-realtime",
- model: "gpt-realtime-2.1",
- id: "openai-realtime",
- provider: "openai",
- transports: ["webrtc", "websocket"],
- },
- { family: "grok-voice", model: "grok-voice-3.0", id: "xai-realtime", provider: "xai", transports: ["websocket"] },
- {
- family: "gemini-3.8-live",
- model: "gemini-3.8-live",
- id: "gemini-live",
- provider: "google",
- transports: ["websocket"],
- },
+ { id: "openai-live", provider: "openai", api: "live", transports: ["webrtc"] },
+ { id: "openai-realtime", provider: "openai", api: "realtime", transports: ["webrtc", "websocket"] },
+ { id: "xai-realtime", provider: "xai", api: "realtime", transports: ["websocket"] },
+ { id: "gemini-live", provider: "google", api: "bidi-generate-content", transports: ["websocket"] },
] as const
-// Matches the bare family name (`gpt-realtime`) and its versions (`gpt-realtime-2.1`, `gpt-realtime-mini`).
-export const engine = (model: string) =>
- engines.find((item) => model === item.family || model.startsWith(`${item.family}-`))
+export type RealtimeEngine = (typeof engines)[number]
export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeConnectInput) {
- const resolved = engine(input.model)
- if (!resolved) return yield* invalidRequest(`Unsupported voice model: ${input.model}`)
+ const resolved = input.engine
if (!resolved.transports.some((type) => type === input.transport.type))
return yield* invalidRequest(`${input.model} only supports ${resolved.transports.join(", ")} transport`)
const session = { ...input.session, model: input.model }
@@ -140,7 +127,6 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
export const Realtime = {
engines,
- engine,
connect,
} as const
diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts
index 1fa49264a30c..b25c942a1deb 100644
--- a/packages/ai/src/protocols/anthropic-messages.ts
+++ b/packages/ai/src/protocols/anthropic-messages.ts
@@ -29,7 +29,7 @@ import {
import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js"
import { classifyProviderFailure } from "../provider-error.js"
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js"
-import { addsTools, foldTools, toolsUpdate, withdrawnTools, type ToolUpdateEncoding } from "../tool-updates.js"
+import { addsTools, toolsUpdate, type ToolUpdateEncoding } from "../tool-updates.js"
import * as Cache from "./utils/cache.js"
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
import { Lifecycle } from "./utils/lifecycle.js"
@@ -827,7 +827,6 @@ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (
const lowerToolsUpdate = Effect.fnUntraced(function* (
message: LLMRequest["messages"][number],
update: ToolChanges,
- withdrawn: ReadonlyArray,
breakpoints: Cache.Breakpoints,
) {
const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content
@@ -838,7 +837,7 @@ const lowerToolsUpdate = Effect.fnUntraced(function* (
type: "tool_addition" as const,
tool: { type: "tool_definition" as const, definition: lowerTool(breakpoints, tool) },
})),
- ...withdrawn.map((name) => ({
+ ...update.remove.map((name) => ({
type: "tool_removal" as const,
tool: { type: "tool_reference" as const, name },
})),
@@ -860,17 +859,13 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
// user turn, the nearest spot where Anthropic accepts a native system message.
const holdUpdates = supportsNativeSystemUpdates(request)
const held: Array = []
- // The tools declared so far, so each tool update can name the flattened tools it takes away.
- let declared = request.tools
const releaseHeld = Effect.fnUntraced(function* () {
const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"))
for (const update of held.splice(0)) {
const tools = toolsUpdate(update)
if (tools !== undefined) {
if (!native) return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result")
- const next = foldTools(declared, tools.add, tools.remove)
- const lowered = yield* lowerToolsUpdate(update, tools, withdrawnTools(declared, next), breakpoints)
- declared = next
+ const lowered = yield* lowerToolsUpdate(update, tools, breakpoints)
if (lowered.content.length > 0) messages.push(lowered)
continue
}
@@ -1048,8 +1043,8 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
// messages. Tools live highest in the cache hierarchy, so when callers
// over-mark we keep their tool hints and shed the message-tail ones first.
const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)
- const flattened = ProviderShared.flattenToolRequest(updates.request)
- const tools = flattened.tools.length === 0 ? undefined : flattened.tools.map((tool) => lowerTool(breakpoints, tool))
+ const definitions = ProviderShared.flattenTools(updates.request.tools)
+ const tools = definitions.length === 0 ? undefined : definitions.map((tool) => lowerTool(breakpoints, tool))
// Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
const declared = tools !== undefined || addsTools(request)
const toolChoice = !declared || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice)
@@ -1062,7 +1057,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
text: part.text,
cache_control: cacheControl(breakpoints, part.cache),
}))
- const messages = yield* lowerMessages(flattened.request, breakpoints)
+ const messages = yield* lowerMessages(updates.request, breakpoints)
yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP)
const output_config =
updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format }
diff --git a/packages/ai/src/protocols/bedrock-converse.ts b/packages/ai/src/protocols/bedrock-converse.ts
index 5731c913e841..d3504c2feaec 100644
--- a/packages/ai/src/protocols/bedrock-converse.ts
+++ b/packages/ai/src/protocols/bedrock-converse.ts
@@ -312,8 +312,8 @@ const removeEmptyToolInputKeys = (input: unknown): unknown => {
const lowerToolCall = (part: ToolCallPart, normalizeID: (id: string) => string): BedrockToolUseBlock => ({
toolUse: {
toolUseId: normalizeID(part.id),
- // Models can emit names that Converse rejects when replayed in history.
- name: part.name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "_",
+ // Converse rejects replayed names over 64 characters; flattenRequest already fixed invalid characters.
+ name: part.name.slice(0, 64),
input: removeEmptyToolInputKeys(part.input),
},
})
@@ -594,7 +594,7 @@ const applyThinkingBindingDefault = (request: LLMRequest, thinking: Readonly {
- if (flattened.tools.length === 0) return undefined
+ if (definitions.length === 0) return undefined
return {
- tools: lowerTools(breakpoints, flattened.tools),
+ tools: lowerTools(breakpoints, definitions),
// Converse has no native "none". Keep definitions stable for prompt
// caching and omit only the unsupported choice.
toolChoice,
}
})()
const system = lowerSystem(breakpoints, request.system)
- const messages = yield* lowerMessages(flattened.request, breakpoints)
+ const messages = yield* lowerMessages(request, breakpoints)
yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP)
const inferenceConfig = (() => {
if (
diff --git a/packages/ai/src/protocols/cohere-chat.ts b/packages/ai/src/protocols/cohere-chat.ts
index c1944f9db8f4..0197bdadd771 100644
--- a/packages/ai/src/protocols/cohere-chat.ts
+++ b/packages/ai/src/protocols/cohere-chat.ts
@@ -145,7 +145,7 @@ const TOOL_CHOICE = { auto: undefined, none: "NONE", required: "REQUIRED", tool:
const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMRequest) {
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {})
- const flattened = ProviderShared.flattenToolRequest(request)
+ const definitions = ProviderShared.flattenTools(request.tools)
const messages: (typeof Message.Type)[] = request.system.length
? [
{
@@ -157,7 +157,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMR
},
]
: []
- for (const message of flattened.request.messages) {
+ for (const message of request.messages) {
if (message.role === "system") {
messages.push({ role: "user", content: (yield* ProviderShared.wrappedSystemUpdate("Cohere Chat", message)).text })
continue
@@ -211,7 +211,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMR
})
}
const selected = request.toolChoice?.type === "tool" ? request.toolChoice.name : undefined
- const tools = selected === undefined ? flattened.tools : flattened.tools.filter((tool) => tool.name === selected)
+ const tools = selected === undefined ? definitions : definitions.filter((tool) => tool.name === selected)
if (selected !== undefined && tools.length === 0)
return yield* ProviderShared.invalidRequest("Cohere Chat tool choice must name an available tool")
if (tools.some((tool) => tool.native !== undefined))
diff --git a/packages/ai/src/protocols/gemini.ts b/packages/ai/src/protocols/gemini.ts
index 730402403e21..0223649b2d89 100644
--- a/packages/ai/src/protocols/gemini.ts
+++ b/packages/ai/src/protocols/gemini.ts
@@ -429,8 +429,8 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
})
const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) {
- const flattened = ProviderShared.flattenToolRequest(request)
- const hasTools = flattened.tools.length > 0
+ const definitions = ProviderShared.flattenTools(request.tools)
+ const hasTools = definitions.length > 0
const options = yield* decodeOptions(request.providerOptions ?? {})
const generationConfig = {
maxOutputTokens: request.maxTokens,
@@ -461,7 +461,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
return {
cachedContent: options.cachedContent,
- contents: yield* lowerMessages(flattened.request),
+ contents: yield* lowerMessages(request),
safetySettings: options.safetySettings,
serviceTier: options.serviceTier,
systemInstruction:
@@ -469,7 +469,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
tools: hasTools
? [
{
- functionDeclarations: flattened.tools.map(lowerTool),
+ functionDeclarations: definitions.map(lowerTool),
},
]
: undefined,
diff --git a/packages/ai/src/protocols/google-interactions.ts b/packages/ai/src/protocols/google-interactions.ts
index 8d1665520dd2..100c03e10ef0 100644
--- a/packages/ai/src/protocols/google-interactions.ts
+++ b/packages/ai/src/protocols/google-interactions.ts
@@ -368,8 +368,8 @@ const lowerToolResult = Effect.fnUntraced(function* (part: ToolResultPart) {
const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (request: LLMRequest) {
const options = yield* decodeOptions(request.providerOptions ?? {})
- const flattened = ProviderShared.flattenToolRequest(request)
- if (flattened.tools.some((tool) => tool.native !== undefined))
+ const definitions = ProviderShared.flattenTools(request.tools)
+ if (definitions.some((tool) => tool.native !== undefined))
return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported")
if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
return yield* ProviderShared.invalidRequest(
@@ -386,7 +386,7 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
})
return {
model: request.model.id,
- input: yield* lowerMessages(flattened.request),
+ input: yield* lowerMessages(request),
stream: true as const,
// Full-history replay need not create retained provider resources. Continuation callers opt in to storage.
store: options.store ?? false,
@@ -397,8 +397,8 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
type: setting.category.replace(/^HARM_CATEGORY_/, "").toLowerCase(),
threshold: setting.threshold.toLowerCase(),
})),
- tools: flattened.tools.length
- ? flattened.tools.map((tool) => ({
+ tools: definitions.length
+ ? definitions.map((tool) => ({
type: "function" as const,
name: tool.name,
description: tool.description,
diff --git a/packages/ai/src/protocols/meta-messages.ts b/packages/ai/src/protocols/meta-messages.ts
index d5b2f5ef0eb2..7f8634980d91 100644
--- a/packages/ai/src/protocols/meta-messages.ts
+++ b/packages/ai/src/protocols/meta-messages.ts
@@ -26,8 +26,8 @@ const Body = Schema.Struct({
})
const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LLMRequest) {
- const projected = ProviderShared.flattenToolRequest(request)
- const body = yield* AnthropicMessages.protocol.body.from(projected.request)
+ const body = yield* AnthropicMessages.protocol.body.from(request)
+ const definitions = ProviderShared.flattenTools(request.tools)
return {
...body,
messages: body.messages.map((message) => {
@@ -45,7 +45,7 @@ const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LL
? undefined
: yield* Effect.forEach(body.tools, (tool, index) =>
Effect.gen(function* () {
- const native = projected.tools[index]?.native
+ const native = definitions[index]?.native
if (native === undefined) return tool
const search = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MetaResponses.WebSearch))(
native.meta,
diff --git a/packages/ai/src/protocols/mistral-chat.ts b/packages/ai/src/protocols/mistral-chat.ts
index 21b50780ed71..2f480f03d7f5 100644
--- a/packages/ai/src/protocols/mistral-chat.ts
+++ b/packages/ai/src/protocols/mistral-chat.ts
@@ -374,6 +374,7 @@ const lowerTool = (tool: ToolDefinition): MistralTool => ({
function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: false },
})
+/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (request: LLMRequest) {
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MistralOptions))(
request.providerOptions ?? {},
@@ -390,11 +391,10 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
tool: (name) => ({ type: "function" as const, function: { name } }),
})
: undefined
- const flattened = ProviderShared.flattenToolRequest(request)
return {
model: request.model.id,
- messages: yield* lowerMessages(flattened.request),
- tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined,
+ messages: yield* lowerMessages(request),
+ tools: request.tools.length > 0 ? ProviderShared.flattenTools(request.tools).map(lowerTool) : undefined,
tool_choice: toolChoice,
stream: true as const,
max_tokens: request.maxTokens,
diff --git a/packages/ai/src/protocols/open-responses.ts b/packages/ai/src/protocols/open-responses.ts
index d9589a3fcd24..79a9e4fe5f72 100644
--- a/packages/ai/src/protocols/open-responses.ts
+++ b/packages/ai/src/protocols/open-responses.ts
@@ -892,23 +892,25 @@ export const allowedToolChoice = (
}
}
+/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (
request: LLMRequest,
adapter: ProviderAdapter,
) {
- const projected = ProviderShared.flattenToolRequest(request)
+ const definitions = ProviderShared.flattenTools(request.tools)
const options = OpenResponsesOptions.resolve(request)
const custom = OpenAIFreeform.tools(request)
return {
- ...(yield* lowerConversation(projected.request, adapter)),
+ ...(yield* lowerConversation(request, adapter)),
...lowerGeneration(request, options),
- tools: projected.tools.length === 0 ? undefined : yield* lowerTools(projected.tools, adapter, custom),
+ tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
tool_choice:
allowedToolChoice(options, custom) ??
(request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
}
})
+/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
export const fromRequest = (request: LLMRequest) => fromRequestWithAdapter(request, BASE_ADAPTER)
// =============================================================================
diff --git a/packages/ai/src/protocols/openai-chat.ts b/packages/ai/src/protocols/openai-chat.ts
index dabbd096b350..5ec3370a06df 100644
--- a/packages/ai/src/protocols/openai-chat.ts
+++ b/packages/ai/src/protocols/openai-chat.ts
@@ -872,6 +872,7 @@ const lowerOptions = (request: LLMRequest, supportsStore: boolean, hasActiveTool
}
}
+/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
request: LLMRequest,
options: LoweringOptions = {},
@@ -883,7 +884,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
return yield* ProviderShared.invalidRequest(
`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,
)
- const flattened = ProviderShared.flattenToolRequest(request)
+ const definitions = ProviderShared.flattenTools(request.tools)
const provider = request.model.provider
const baseURL = request.model.route.endpoint.baseURL
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
@@ -893,18 +894,18 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
const zaiToolStream =
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
const hasHistory = hasToolHistory(request.messages)
- const hasActiveTools = flattened.tools.length > 0
+ const hasActiveTools = definitions.length > 0
const custom = OpenAIFreeform.tools(request)
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom }
return {
model: request.model.id,
- messages: yield* lowerMessages(flattened.request, lowering),
+ messages: yield* lowerMessages(request, lowering),
tools:
- flattened.tools.length === 0
+ definitions.length === 0
? hasHistory
? []
: undefined
- : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
+ : definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
stream: true as const,
...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
diff --git a/packages/ai/src/protocols/openai-responses.ts b/packages/ai/src/protocols/openai-responses.ts
index 94aa075f39a2..0076260e1fd2 100644
--- a/packages/ai/src/protocols/openai-responses.ts
+++ b/packages/ai/src/protocols/openai-responses.ts
@@ -406,6 +406,7 @@ export const protocol = Protocol.make({
}),
supportsEffortUpdates,
toolUpdates,
+ namespaces: true,
})
const endpoint = Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL })
diff --git a/packages/ai/src/protocols/shared.ts b/packages/ai/src/protocols/shared.ts
index f880d13853af..ac7725125613 100644
--- a/packages/ai/src/protocols/shared.ts
+++ b/packages/ai/src/protocols/shared.ts
@@ -10,6 +10,8 @@ import {
AssistantMessage,
type LLMRequest,
Message,
+ SystemMessage,
+ ToolChoice,
ToolDefinition,
ToolMessage,
type ContentPart,
@@ -24,6 +26,7 @@ import {
} from "../schema/index.js"
import { Json, decodeJson, encodeJson } from "../utils/json.js"
import { isRecord } from "../utils/record.js"
+import { foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js"
export { Json, decodeJson, encodeJson, isRecord }
const isJson = Schema.is(Schema.Json)
@@ -367,7 +370,8 @@ export const unsupportedOperation = (input: {
/**
* Lower namespaces to flat definitions for protocols without a native
* namespace construct. Leaf names join their namespace path with `_` because
- * `.` is not broadly accepted in provider tool names.
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
+ * it to type their tools.
*/
export const flattenTools = (tools: ReadonlyArray, path: ReadonlyArray = []) => {
const flat = tools.flatMap((tool): ReadonlyArray => {
@@ -378,28 +382,84 @@ export const flattenTools = (tools: ReadonlyArray, path: ReadonlyArra
return [...new Map(flat.map((tool) => [tool.name, tool])).values()]
}
-export const flattenToolRequest = (request: LLMRequest) => {
+/**
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
+ * requests.
+ */
+export const flattenRequest = (request: LLMRequest): LLMRequest => {
+ const all = [...request.tools, ...request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])]
+ const declared = new Set(flattenTools(all).map((tool) => tool.name))
+ const flatten = (part: Part) => flattenToolName(part, declared)
+ // A tool update that redefines a namespace drops the tools it leaves out, which only the namespace shows, so name
+ // them as explicit removals.
+ let tools = request.tools
const messages = request.messages.map((message) => {
+ if (message.role === "system" && message.tools !== undefined) {
+ const next = foldTools(tools, message.tools.add, message.tools.remove)
+ const remove = withdrawnTools(tools, next)
+ tools = next
+ return new SystemMessage({ ...message, tools: { add: flattenTools(message.tools.add), remove } })
+ }
if (message.role === "assistant") {
const content = message.content.map((part) =>
- part.type === "tool-call" || part.type === "tool-result" ? flattenToolName(part) : part,
+ part.type === "tool-call" || part.type === "tool-result" ? flatten(part) : part,
)
return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content })
}
if (message.role !== "tool") return message
- const content = message.content.map(flattenToolName)
+ const content = message.content.map(flatten)
return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content })
})
return {
+ ...request,
tools: flattenTools(request.tools),
- request: messages.every((message, index) => message === request.messages[index])
- ? request
- : { ...request, messages },
+ messages,
+ toolChoice: flattenToolChoice(request.toolChoice, all, declared),
}
}
-const flattenToolName = (part: Part): Part =>
- part.namespace === undefined ? part : { ...part, name: `${part.namespace}_${part.name}`, namespace: undefined }
+/**
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
+ * the next minor.
+ */
+export const flattenToolRequest = (request: LLMRequest) => {
+ const flat = flattenRequest(request)
+ return { tools: flattenTools(flat.tools), request: flat }
+}
+
+// A forced choice names a namespaced tool by its path (`crm.lookup`); point it at the flattened definition.
+const flattenToolChoice = (
+ choice: LLMRequest["toolChoice"],
+ tools: ReadonlyArray,
+ declared: ReadonlySet,
+) => {
+ if (choice?.type !== "tool" || choice.name === undefined || declared.has(choice.name)) return choice
+ const name = new Map(namespacedPaths(tools)).get(choice.name)
+ return name === undefined ? choice : new ToolChoice({ ...choice, name })
+}
+
+// Each namespaced tool's path and the name flattenTools gives it.
+const namespacedPaths = (
+ tools: ReadonlyArray,
+ path: ReadonlyArray = [],
+): ReadonlyArray =>
+ tools.flatMap((tool) => {
+ if (tool.type === "namespace") return namespacedPaths(tool.tools, [...path, tool.name])
+ return path.length === 0 ? [] : [[[...path, tool.name].join("."), [...path, tool.name].join("_")] as const]
+ })
+
+const flattenToolName = (
+ part: Part,
+ declared: ReadonlySet,
+): Part => {
+ const flat = part.namespace === undefined ? part.name : `${part.namespace}_${part.name}`
+ // Models sometimes call names no tool declares, such as a Code Mode path like `a.b.c`. Several providers (OpenAI
+ // Chat Completions, Bedrock Converse) reject those characters when the call is replayed, so replace them. A
+ // declared name is kept as is, so a provider that accepts it sees calls under the tool's own name.
+ const name = declared.has(flat) ? flat : flat.replace(/[^a-zA-Z0-9_-]/g, "_") || "_"
+ return name === part.name && part.namespace === undefined ? part : { ...part, name, namespace: undefined }
+}
const sameParts = (next: ReadonlyArray, previous: ReadonlyArray) =>
next.every((part, index) => part === previous[index])
diff --git a/packages/ai/src/protocols/utils/gateway-protocol.ts b/packages/ai/src/protocols/utils/gateway-protocol.ts
index f6588a9fe2f0..ea929f4880c8 100644
--- a/packages/ai/src/protocols/utils/gateway-protocol.ts
+++ b/packages/ai/src/protocols/utils/gateway-protocol.ts
@@ -65,6 +65,7 @@ export function gatewayProtocol(
},
supportsEffortUpdates: protocol.supportsEffortUpdates,
toolUpdates: protocol.toolUpdates,
+ namespaces: protocol.namespaces,
sanitizer: protocol.sanitizer,
stream: {
event: protocol.stream.event,
diff --git a/packages/ai/src/protocols/xai-responses.ts b/packages/ai/src/protocols/xai-responses.ts
index 8850ac367eea..932092e4c3fe 100644
--- a/packages/ai/src/protocols/xai-responses.ts
+++ b/packages/ai/src/protocols/xai-responses.ts
@@ -1,5 +1,6 @@
import { Effect, Schema } from "effect"
import { Protocol } from "../route/protocol.js"
+import type { CompactOperation } from "../route/client.js"
import type { LLMRequest } from "../schema/index.js"
import { OpenResponses } from "./open-responses.js"
import { JsonObject, optionalNull, ProviderShared } from "./shared.js"
@@ -93,8 +94,13 @@ export const protocol = Protocol.make({
stream: ResponsesHostedTools.stream(adapter, HOSTED_TOOLS),
})
-export const compact = ResponsesCompaction.make(adapter, (request) =>
+const compactFlat = ResponsesCompaction.make(adapter, (request) =>
OpenResponses.lowerTools(ProviderShared.flattenTools(request.tools), adapter, OpenAIFreeform.tools(request)),
)
+// /compact lowers the history itself, so flatten the whole request as `Protocol.make` does before every step's body:
+// past calls to namespaced tools then carry the same names as on those steps, and /compact reads the prefix they cached.
+export const compact: CompactOperation = (request, executor, options) =>
+ compactFlat(ProviderShared.flattenRequest(request), executor, options)
+
export * as XAIResponses from "./xai-responses.js"
diff --git a/packages/ai/src/route/protocol.ts b/packages/ai/src/route/protocol.ts
index 69a83694105d..0b15b8da97bd 100644
--- a/packages/ai/src/route/protocol.ts
+++ b/packages/ai/src/route/protocol.ts
@@ -1,5 +1,6 @@
import { Schema, type Effect } from "effect"
import type { AIError, LanguageModelSanitizerCompatibility, LLMEvent, LLMRequest, ProtocolID } from "../schema/index.js"
+import { flattenRequest } from "../protocols/shared.js"
import type { ToolUpdateEncoding } from "../tool-updates.js"
/**
@@ -46,6 +47,8 @@ export interface Protocol {
readonly supportsEffortUpdates?: (request: LLMRequest) => boolean
/** Tool changes `body.from` can send in place of `Message.tools(...)` markers; wrappers around another `body.from` must forward it. */
readonly toolUpdates?: ToolUpdateEncoding
+ /** Whether `body.from` sends tool namespaces natively; otherwise `make` hands it flattened requests. Wrappers around another `body.from` must forward it. */
+ readonly namespaces?: boolean
/** Tool schema sanitizer for every model on this protocol unless the model's compatibility sets one; wrappers around another `body.from` must forward it. */
readonly sanitizer?: LanguageModelSanitizerCompatibility
}
@@ -84,7 +87,10 @@ export interface ProtocolStream {
*/
export const make = (
input: Protocol,
-): Protocol => input
+): Protocol =>
+ input.namespaces
+ ? input
+ : { ...input, body: { ...input.body, from: (request) => input.body.from(flattenRequest(request)) } }
export const jsonEvent = (schema: S) => Schema.fromJsonString(schema)
diff --git a/packages/ai/test/compile.test.ts b/packages/ai/test/compile.test.ts
index abad911f7c80..12696006bb42 100644
--- a/packages/ai/test/compile.test.ts
+++ b/packages/ai/test/compile.test.ts
@@ -2,7 +2,17 @@ import { describe, expect, test } from "bun:test"
import { Effect, Ref, Schema } from "effect"
import { HttpClientRequest, HttpClientResponse } from "effect/http"
import { ai, Message, ToolCallPart, ToolDefinition, ToolNamespace } from "../src/effect.js"
-import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../src/protocols.js"
+import {
+ AnthropicMessages,
+ BedrockConverse,
+ CohereChat,
+ Gemini,
+ GoogleInteractions,
+ MistralChat,
+ OpenAIChat,
+ OpenAICompatibleResponses,
+ OpenAIResponses,
+} from "../src/protocols.js"
import { Auth, LLMClient } from "../src/route.js"
import { compileRequest } from "../src/route/client.js"
import { mergeProviderOptions } from "../src/schema/index.js"
@@ -168,6 +178,132 @@ describe("request option precedence", () => {
}),
)
+ it.effect("forces a namespaced tool under its flattened name on flat protocols", () =>
+ Effect.forEach(
+ [
+ AnthropicMessages,
+ BedrockConverse,
+ CohereChat,
+ Gemini,
+ GoogleInteractions,
+ MistralChat,
+ OpenAIChat,
+ OpenAICompatibleResponses,
+ ],
+ (protocol) =>
+ Effect.gen(function* () {
+ const prepared = yield* compileRequest(
+ ai.request({
+ model: protocol.route
+ .with({
+ provider: protocol.route.provider ?? "custom",
+ endpoint: { baseURL: protocol.route.endpoint.baseURL ?? "https://example.invalid/v1" },
+ auth: Auth.bearer("unused"),
+ })
+ .model({ id: "test-model" }),
+ prompt: "Look up a customer",
+ tools: [
+ ToolNamespace.make({
+ name: "crm",
+ description: "CRM tools",
+ tools: [ToolDefinition.make({ name: "lookup", description: "Look up", inputSchema: {} })],
+ }),
+ ],
+ toolChoice: "crm.lookup",
+ }),
+ )
+ const body = JSON.stringify(prepared.body)
+ expect(body).toContain("crm_lookup")
+ expect(body).not.toContain("crm.lookup")
+ }),
+ { discard: true },
+ ),
+ )
+
+ it.effect("flattens a forced choice only when it names a namespaced tool", () =>
+ Effect.gen(function* () {
+ const choose = (name: string) =>
+ compileRequest(
+ ai.request({
+ model: OpenAIChat.route.model({ id: "gpt-4o-mini" }),
+ prompt: "Hi",
+ tools: [
+ ToolDefinition.make({ name: "foo_bar", description: "Top level", inputSchema: {} }),
+ ToolNamespace.make({
+ name: "crm",
+ description: "CRM tools",
+ tools: [ToolDefinition.make({ name: "customer.lookup", description: "Look up", inputSchema: {} })],
+ }),
+ ],
+ toolChoice: name,
+ }),
+ ).pipe(Effect.map((prepared) => prepared.body.tool_choice))
+ // A dotted leaf flattens as flattenTools names it.
+ expect(yield* choose("crm.customer.lookup")).toEqual({
+ type: "function",
+ function: { name: "crm_customer.lookup" },
+ })
+ // A dotted name that isn't a namespaced tool is left for the provider to reject, not matched to foo_bar.
+ expect(yield* choose("foo.bar")).toEqual({ type: "function", function: { name: "foo.bar" } })
+ }),
+ )
+
+ it.effect("flattens a forced choice for a namespace a tool update adds", () =>
+ Effect.gen(function* () {
+ const prepared = yield* compileRequest(
+ ai.request({
+ model: AnthropicMessages.route
+ .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.bearer("unused") })
+ .model({ id: "claude-opus-5", capabilities: { tools: { updates: ["add", "remove", "replace"] } } }),
+ messages: [
+ Message.user("Hi"),
+ Message.tools({
+ add: [
+ ToolNamespace.make({
+ name: "crm",
+ description: "CRM tools",
+ tools: [ToolDefinition.make({ name: "lookup", description: "Look up", inputSchema: {} })],
+ }),
+ ],
+ }),
+ Message.user("Look up a customer"),
+ ],
+ toolChoice: "crm.lookup",
+ }),
+ )
+ expect(prepared.body.tool_choice).toMatchObject({ type: "tool", name: "crm_lookup" })
+ }),
+ )
+
+ it.effect("flattens namespaces when a flat protocol's body is built directly", () =>
+ Effect.gen(function* () {
+ const body = yield* OpenAIChat.protocol.body.from(
+ ai.request({
+ model: OpenAIChat.route.model({ id: "gpt-4o-mini" }),
+ tools: [
+ ToolNamespace.make({
+ name: "crm",
+ description: "CRM tools",
+ tools: [ToolDefinition.make({ name: "lookup", description: "Look up", inputSchema: {} })],
+ }),
+ ],
+ messages: [
+ Message.user("Look up a customer"),
+ Message.assistant(ToolCallPart.make({ id: "call_1", name: "lookup", namespace: "crm", input: {} })),
+ ],
+ toolChoice: "crm.lookup",
+ }),
+ )
+ const json = JSON.stringify(body)
+ expect(json).toContain("crm_lookup")
+ expect(json).not.toContain("crm.lookup")
+ expect(body.messages).toMatchObject([
+ { role: "user" },
+ { role: "assistant", tool_calls: [{ function: { name: "crm_lookup" } }] },
+ ])
+ }),
+ )
+
it.effect("normalizes tool history before protocol lowering", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
diff --git a/packages/ai/test/http-timeout.test.ts b/packages/ai/test/http-timeout.test.ts
index 28037655f01e..20c092a61608 100644
--- a/packages/ai/test/http-timeout.test.ts
+++ b/packages/ai/test/http-timeout.test.ts
@@ -275,6 +275,7 @@ describe("HTTP transport timeouts", () => {
for (const effect of Object.values(calls)) yield* check(effect)
yield* check(
Realtime.connect({
+ engine: Realtime.engines[1],
model: "gpt-realtime",
apiKey: Redacted.make("test"),
transport: { type: "websocket" },
diff --git a/packages/ai/test/provider/compaction.test.ts b/packages/ai/test/provider/compaction.test.ts
index 63b52138467a..4f90669b771b 100644
--- a/packages/ai/test/provider/compaction.test.ts
+++ b/packages/ai/test/provider/compaction.test.ts
@@ -1,6 +1,7 @@
import { expect } from "bun:test"
import { Effect, Schema } from "effect"
-import { ai, Message } from "../../src/effect.js"
+import { ai, Message, ToolCallPart, ToolDefinition, ToolNamespace } from "../../src/effect.js"
+import { compileRequest } from "../../src/route/client.js"
import { LLMClient } from "../../src/route/client.js"
import { OpenAI, Azure, XAI } from "../../src/providers/index.js"
import { testEffect } from "../lib/effect.js"
@@ -137,3 +138,41 @@ testEffect(
expect(part.encrypted).toBe("opaque")
}),
)
+
+// /compact must send the same history and tools as the steps before it, so it reads the prefix they cached.
+const flatRequest = ai.request({
+ model: XAI.configure({ apiKey: "test" }).responses("grok-4.6"),
+ tools: [
+ ToolNamespace.make({
+ name: "crm",
+ description: "CRM tools",
+ tools: [ToolDefinition.make({ name: "lookup", description: "Look up", inputSchema: {} })],
+ }),
+ ],
+ messages: [
+ Message.user("Look up Ada"),
+ Message.assistant(ToolCallPart.make({ id: "call_1", name: "lookup", namespace: "crm", input: {} })),
+ Message.tool({ id: "call_1", name: "lookup", namespace: "crm", result: { output: "found" } }),
+ ],
+})
+const names = (body: { input: ReadonlyArray>; tools?: ReadonlyArray> }) => ({
+ calls: body.input.flatMap((item) => (item.type === "function_call" ? [item.name] : [])),
+ tools: (body.tools ?? []).map((tool) => tool.name),
+})
+const compactBodies: Array<{ input: ReadonlyArray> }> = []
+
+testEffect(
+ dynamicResponse(({ text, respond }) =>
+ Effect.sync(() => {
+ compactBodies.push(JSON.parse(text))
+ return respond(JSON.stringify({ object: "response.compaction", output: [checkpoint] }))
+ }),
+ ),
+).effect("xAI compaction sends namespaced tools and past calls under the names every step uses", () =>
+ Effect.gen(function* () {
+ const step = names((yield* compileRequest(flatRequest)).body as Parameters[0])
+ expect(step).toEqual({ calls: ["crm_lookup"], tools: ["crm_lookup"] })
+ yield* ai.compact(flatRequest, { mechanism: "endpoint" })
+ expect(names(compactBodies[0] as Parameters[0])).toEqual(step)
+ }),
+)
diff --git a/packages/ai/test/provider/openai-chat.test.ts b/packages/ai/test/provider/openai-chat.test.ts
index a64cd89c1bff..a5152e80c485 100644
--- a/packages/ai/test/provider/openai-chat.test.ts
+++ b/packages/ai/test/provider/openai-chat.test.ts
@@ -63,6 +63,35 @@ describe("OpenAI Chat route", () => {
}),
)
+ it.effect("replaces characters providers reject in replayed names of undeclared tool calls", () =>
+ Effect.gen(function* () {
+ const invented = ToolCallPart.make({ id: "call_1", name: "opencode.session.search", input: {} })
+ const declared = ToolCallPart.make({ id: "call_2", name: "weather.get", input: {} })
+ const prepared = yield* compileRequest(
+ ai.request({
+ model,
+ tools: [
+ ToolDefinition.make({ name: "weather.get", description: "Weather", inputSchema: { type: "object" } }),
+ ],
+ messages: [
+ Message.assistant([invented, declared]),
+ Message.tool({ id: invented.id, name: invented.name, result: "unknown tool", resultType: "error" }),
+ Message.tool({ id: declared.id, name: declared.name, result: "sunny", resultType: "text" }),
+ ],
+ }),
+ )
+
+ // A declared name stays as declared, for providers that accept it.
+ expect(prepared.body.messages[0]).toMatchObject({
+ role: "assistant",
+ tool_calls: [
+ { id: "call_1", function: { name: "opencode_session_search" } },
+ { id: "call_2", function: { name: "weather.get" } },
+ ],
+ })
+ }),
+ )
+
it.effect("omits stream usage options when compatibility disables them", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
diff --git a/packages/ai/test/realtime.test.ts b/packages/ai/test/realtime.test.ts
index ac39877f260c..23d936ac9b1a 100644
--- a/packages/ai/test/realtime.test.ts
+++ b/packages/ai/test/realtime.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "bun:test"
+import { describe, expect } from "bun:test"
import { Effect, Redacted } from "effect"
import { HttpClientRequest } from "effect/http"
import { TestClock } from "effect/testing"
@@ -13,6 +13,7 @@ describe("experimental Realtime", () => {
expect(
yield* Realtime.connect({
+ engine: Realtime.engines[0],
model: "gpt-live-1",
apiKey: Redacted.make("sk-openai"),
session: { instructions: "Be concise.", voice: "marin" },
@@ -22,6 +23,7 @@ describe("experimental Realtime", () => {
expect(
yield* Realtime.connect({
+ engine: Realtime.engines[1],
model: "gpt-realtime-2.1",
apiKey: Redacted.make("sk-openai"),
session: { type: "realtime", instructions: "Brief." },
@@ -31,6 +33,7 @@ describe("experimental Realtime", () => {
expect(
yield* Realtime.connect({
+ engine: Realtime.engines[1],
model: "gpt-realtime-2.1",
apiKey: Redacted.make("sk-openai"),
session: { type: "realtime", instructions: "Brief." },
@@ -45,6 +48,7 @@ describe("experimental Realtime", () => {
expect(
yield* Realtime.connect({
+ engine: Realtime.engines[2],
model: "grok-voice-3.0",
apiKey: Redacted.make("xai-key"),
session: { voice: "ara" },
@@ -59,6 +63,7 @@ describe("experimental Realtime", () => {
expect(
yield* Realtime.connect({
+ engine: Realtime.engines[3],
model: "gemini-3.8-live",
apiKey: Redacted.make("gemini-key"),
session: {
@@ -137,38 +142,22 @@ describe("experimental Realtime", () => {
),
)
- test("routes bare and versioned model names to their engine", () => {
- expect(Realtime.engines.map((item) => Realtime.engine(item.model)?.id)).toEqual(
- Realtime.engines.map((item) => item.id),
- )
- expect(
- [
- "gpt-realtime",
- "gpt-realtime-2.1",
- "gpt-live",
- "grok-voice-latest",
- "gemini-3.8-live",
- "gemini-3.8-live-extended-thinking",
- ].map((model) => Realtime.engine(model)?.id),
- ).toEqual(["openai-realtime", "openai-realtime", "openai-live", "xai-realtime", "gemini-live", "gemini-live"])
- expect(Realtime.engine("gpt-realtimex")).toBeUndefined()
- expect(Realtime.engine("gemini-3.8-flash")).toBeUndefined()
- expect(Realtime.engine("gemini-3.5-live")).toBeUndefined()
- })
-
it.effect("rejects unsupported transports before network I/O", () =>
Effect.gen(function* () {
const liveWs = yield* Realtime.connect({
+ engine: Realtime.engines[0],
model: "gpt-live-1",
apiKey: Redacted.make("k"),
transport: { type: "websocket" },
}).pipe(Effect.flip)
const grokRtc = yield* Realtime.connect({
+ engine: Realtime.engines[2],
model: "grok-voice-3.0",
apiKey: Redacted.make("k"),
transport: { type: "webrtc", sdp: "v=0" },
}).pipe(Effect.flip)
const geminiRtc = yield* Realtime.connect({
+ engine: Realtime.engines[3],
model: "gemini-3.8-live",
apiKey: Redacted.make("k"),
transport: { type: "webrtc", sdp: "v=0" },
diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts
index a05fbae9784e..3ca885dd89c5 100644
--- a/packages/app/component-tests/browser-pane-restore.spec.ts
+++ b/packages/app/component-tests/browser-pane-restore.spec.ts
@@ -24,6 +24,8 @@ const modules = {
settings: source("../src/settings/model.tsx"),
platform: source("../src/runtime/platform/platform.tsx"),
solid: source("./plugin-host.fixture.tsx"),
+ sessionTabs: source("../src/shell/state/session-tabs.ts"),
+ layoutKeys: source("../src/shell/state/helpers.ts"),
}
story.beforeEach(async ({ mount, page }) => {
@@ -45,6 +47,8 @@ story.beforeEach(async ({ mount, page }) => {
solid,
closed,
pluginCommands,
+ sessionTabs,
+ layoutKeys,
] = await Promise.all([
import(modules.fixture),
import(modules.host),
@@ -60,6 +64,8 @@ story.beforeEach(async ({ mount, page }) => {
import(modules.solid),
import(modules.closed),
import(modules.pluginCommands),
+ import(modules.sessionTabs),
+ import(modules.layoutKeys),
// Load the pane before mounting: Vite must not reload the page to optimize its dependencies mid-fixture.
import(modules.browserPanel),
])
@@ -211,6 +217,8 @@ story.beforeEach(async ({ mount, page }) => {
return null
},
Contribution: renderer.Contribution,
+ appendTab: sessionTabs.appendSessionTab,
+ pruneKeys: layoutKeys.pruneSessionKeys,
})
}, modules)
})
@@ -262,7 +270,7 @@ story("toggles the element picker from the shortcut only inside the browser pane
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Blank page", exact: true }).click()
- // The comment tool has no button in the bar; while it waits for a pick, the pane says so in a status line.
+ // While the comment tool waits for a pick, the pane says so in a status line.
const picking = root.getByText("Click part of the page to comment on it. Press Escape to cancel.", { exact: true })
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
await address.click()
@@ -312,22 +320,19 @@ story("keeps in-page shortcuts in the editor and forwards toolbar, review and cl
await editor.press(`${mod}+k`)
await expect(editor).toHaveValue("handled:k")
- const toggle = root.getByRole("button", { name: "Toggle browser toolbar", exact: true })
+ // The toolbar's toggle is an item of the options menu, so the shortcut leaves the keyboard on that menu's button.
+ const toolbar = root.getByRole("region", { name: "Viewport", exact: true })
+ const options = root.getByRole("button", { name: "Browser options", exact: true })
await editor.press(`${mod}+Shift+m`)
- await expect(toggle).toHaveAttribute("aria-expanded", "true")
- await expect(toggle).toBeFocused()
+ await expect(toolbar).toBeVisible()
+ await expect(options).toBeFocused()
await root.getByRole("button", { name: "Device preset", exact: true }).press("ArrowDown")
await page.getByRole("menuitem", { name: "More devices", exact: true }).press("ArrowRight")
await expect(page.getByRole("menuitemradio", { name: "iPhone SE", exact: true })).toBeFocused()
await page.keyboard.press(`${mod}+Shift+m`)
- await expect(toggle).toHaveAttribute("aria-expanded", "false")
- await expect(toggle).toBeFocused()
- await expect(toggle).toHaveCSS("outline-style", "solid")
- await toggle.click()
- await expect(toggle).toBeFocused()
- await expect(toggle).toHaveCSS("outline-style", "none")
- await page.keyboard.press(`${mod}+Shift+m`)
- await expect(toggle).toHaveCSS("outline-style", "solid")
+ await expect(toolbar).toBeHidden()
+ await expect(options).toBeFocused()
+ await expect(options).toHaveCSS("outline-style", "solid")
// Shell shortcuts like ⌘⇧R and pane-scoped ⌘W are claimed before the page sees them.
await editor.press(`${mod}+Shift+r`)
@@ -341,18 +346,18 @@ story("keeps in-page shortcuts in the editor and forwards toolbar, review and cl
story("the pane's toolbar shortcut works from inside the options menu's More tools", async ({ page }) => {
const root = page.getByTestId("browser-region-fixture")
const mod = (await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform))) ? "Meta" : "Control"
- const toggle = root.getByRole("button", { name: "Toggle browser toolbar", exact: true })
+ const toolbar = root.getByRole("region", { name: "Viewport", exact: true })
await root.getByRole("button", { name: "Beta", exact: true }).click()
await root.getByRole("button", { name: "First inventory", exact: true }).click()
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
- await expect(toggle).toHaveAttribute("aria-expanded", "false")
+ await expect(toolbar).toBeHidden()
// The submenu is a portal of its own, outside the pane: it must still count as the pane for the pane's shortcuts.
await root.getByRole("button", { name: "Browser options", exact: true }).click()
await page.getByRole("menuitem", { name: "More tools", exact: true }).press("ArrowRight")
await expect(page.getByRole("menu", { name: "More tools", exact: true }).getByRole("menuitem").first()).toBeFocused()
await page.keyboard.press(`${mod}+Shift+m`)
- await expect(toggle).toHaveAttribute("aria-expanded", "true")
+ await expect(toolbar).toBeVisible()
})
story(
@@ -724,9 +729,10 @@ type MainTab = {
// The fixture reads each one through the pane Ipc's own event schema, so a shape main cannot send fails there.
type MainEvent =
- | { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string }
+ | { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string; unnamed?: string[]; placed?: { tabID: string; after: string } }
| { type: "page"; tabID: string; zoom: number; viewport: { mode: "auto" }; icon?: string }
| { type: "embed"; tabID: string; embed: string }
+ | { type: "focus"; tabID: string }
const preview = "tab_33333333-3333-3333-3333-333333333333"
@@ -851,6 +857,257 @@ story("holds every restored tab's box, label and icon from the reopen until its
expect(first.map((tab) => tab.icon)).toEqual([expect.any(String), previewIcon, docsIcon])
})
+// A tab a link opened was added at the end of the strip, after every other tab, however far from the tab it came from.
+// Now it appears at the click, beside that tab, as in Chrome. The strip sizes a tab by its label, so the tabs after it
+// move when it appears and when it takes its page's title, and at no other step: it keeps its new-tab label while its
+// page loads and has only Chromium's name for it, its address, which would move them a third time.
+type Box = Awaited>[number]
+
+// `after` is `before` with one tab added at `index`: it takes the place of the tab that stood there, every tab after it
+// moves right by its width and the strip's gap, and no other tab moves or changes width, label or icon.
+const expectInserted = (before: Box[], after: Box[], index: number) => {
+ const gap = before[1].x - before[0].x - before[0].width
+ const added = after[index]
+ expect(after.length).toBe(before.length + 1)
+ expect(after.slice(0, index)).toEqual(before.slice(0, index))
+ expect(added.x).toBeCloseTo(before[index]?.x ?? before[index - 1].x + before[index - 1].width + gap, 3)
+ after.slice(index + 1).forEach((tab, offset) => {
+ const earlier = before[index + offset]
+ expect({ ...tab, x: 0 }).toEqual({ ...earlier, x: 0 })
+ expect(tab.x).toBeCloseTo(earlier.x + added.width + gap, 3)
+ })
+}
+
+// `after` is `before` with the tab at `index` relabelled `text`: it stays where it stood with another width, every tab
+// after it moves by that difference, and no other tab moves or changes width, label or icon.
+const expectRenamed = (before: Box[], after: Box[], index: number, text: string) => {
+ const grown = after[index].width - before[index].width
+ expect(after.length).toBe(before.length)
+ expect(after.slice(0, index)).toEqual(before.slice(0, index))
+ expect(after[index]).toEqual({ ...before[index], text, width: after[index].width })
+ expect(grown).not.toBe(0)
+ after.slice(index + 1).forEach((tab, offset) => {
+ const earlier = before[index + 1 + offset]
+ expect({ ...tab, x: 0 }).toEqual({ ...earlier, x: 0 })
+ expect(tab.x).toBeCloseTo(earlier.x + grown, 3)
+ })
+}
+
+// Beta with three loaded browser tabs after its file tab, and Docs, the middle one, in front.
+const linkStrip = async (page: Page) => {
+ const root = page.getByTestId("browser-region-fixture")
+ const tabs = root.getByRole("tab")
+ const first = reported({ id: preview, url: "http://localhost:4173/", title: "Preview" })
+ const middle = reported({ id: docs, url: "https://example.com/docs", title: "Docs" })
+ const last = reported({ id: "tab_77777777-7777-7777-7777-777777777777", url: "https://example.com/guide", title: "Guide" })
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
+ await send(root, inventory(first, middle, last))
+ await root.getByRole("tab", { name: "Docs", exact: true }).click()
+ await expect(root.getByTestId("selected")).toHaveText(`browser:${docs}`)
+ await page.evaluate(() => document.fonts.ready.then(() => undefined))
+ expect((await drawn(tabs)).map((tab) => tab.text)).toEqual(["beta.ts", "Preview", "Docs", "Guide"])
+
+ // Main's inventory with `opened` between Docs and Guide, as it reports it (`publish` in pane-machine.ts).
+ const listed = (opened: MainTab[], rest: { unnamed?: string[]; placed?: { tabID: string; after: string }; focusedTabID?: string } = {}) => ({
+ type: "state" as const,
+ state: { tabs: [first, middle, ...opened, last], focusedTabID: rest.focusedTabID ?? docs },
+ ...(rest.unnamed && { unnamed: rest.unnamed }),
+ ...(rest.placed && { placed: rest.placed }),
+ })
+
+ return { root, tabs, listed, selected: root.getByTestId("selected") }
+}
+
+// What a tab a link opened reports, in order, as measured in Electron: blank, its load starts, its document commits
+// under Chromium's name for it, the document names itself, and the load ends.
+const linkPage = (id: string, path: string, title: string) => {
+ const blank = reported({ id, url: "about:blank", title: "" })
+ const committed = { ...blank, url: `https://example.com/${path}`, title: `example.com/${path}`, loading: true, generation: 1 }
+
+ return { id, blank, started: { ...blank, loading: true }, committed, named: { ...committed, title }, ended: { ...committed, title, loading: false } }
+}
+
+story("a tab a link opens behind appears at once beside the tab it came from, and its page's title is its only other change", async ({ page }) => {
+ const { root, tabs, listed, selected } = await linkStrip(page)
+ const one = linkPage("tab_88888888-8888-8888-8888-888888888888", "one", "One")
+ const two = linkPage("tab_99999999-9999-9999-9999-999999999999", "two", "Second page")
+ const three = linkPage("tab_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "three", "Three")
+ const before = await drawn(tabs)
+
+ // The person middle-clicks a link in Docs: the tab appears at once, after Docs, behind it.
+ await send(root, listed([one.blank], { placed: { tabID: one.id, after: docs }, unnamed: [one.id] }))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "New tab", "Guide"])
+ const shown = await drawn(tabs)
+ expectInserted(before, shown, 3)
+
+ // Its load starts and its document commits, with Chromium's name for it: no box moves or changes width or label.
+ for (const waiting of [one.started, one.committed]) {
+ await send(root, listed([waiting], { unnamed: [one.id] }))
+ expect(await drawn(tabs)).toEqual(shown)
+ }
+
+ // Its document names itself: the tab takes that name, where it stands.
+ await send(root, listed([one.named]))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Guide"])
+ const named = await drawn(tabs)
+ expectRenamed(shown, named, 3, "One")
+ // Its icon arrives and its load ends: no box moves or changes width.
+ await send(root, details(one.id, docsIcon))
+ await expect(root.getByRole("tab", { name: "One", exact: true }).locator("img")).toHaveAttribute("src", docsIcon)
+ await send(root, listed([one.ended]))
+ const loaded = await drawn(tabs)
+ expect(loaded).toEqual([...named.slice(0, 3), { ...named[3], icon: docsIcon }, named[4]])
+ await expect(selected).toHaveText(`browser:${docs}`)
+
+ // Two more middle-clicks in a row: each appears at its click, in the order they were opened, after One.
+ await send(root, listed([one.ended, two.blank], { placed: { tabID: two.id, after: one.id }, unnamed: [two.id] }))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "Guide"])
+ const second = await drawn(tabs)
+ expectInserted(loaded, second, 4)
+ await send(root, listed([one.ended, two.started, three.blank], { placed: { tabID: three.id, after: two.id }, unnamed: [two.id, three.id] }))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "New tab", "Guide"])
+ const third = await drawn(tabs)
+ expectInserted(second, third, 5)
+ await send(root, listed([one.ended, two.started, three.started], { unnamed: [two.id, three.id] }))
+ await send(root, listed([one.ended, two.committed, three.committed], { unnamed: [two.id, three.id] }))
+ expect(await drawn(tabs)).toEqual(third)
+ // The second one's page is named first: only it is relabelled, and only Guide moves.
+ await send(root, listed([one.ended, two.committed, three.named], { unnamed: [two.id] }))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "Three", "Guide"])
+ const reversed = await drawn(tabs)
+ expectRenamed(third, reversed, 5, "Three")
+ // Then the first one's: Three and Guide move once more, for this tab.
+ await send(root, listed([one.ended, two.named, three.named]))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Second page", "Three", "Guide"])
+ const ordered = await drawn(tabs)
+ expectRenamed(reversed, ordered, 4, "Second page")
+ await send(root, listed([one.ended, two.ended, three.ended]))
+ expect(await drawn(tabs)).toEqual(ordered)
+ await expect(selected).toHaveText(`browser:${docs}`)
+
+ // The app quits and opens again: the strip draws the same order at once, and main's restored tabs move nothing.
+ await root.getByRole("button", { name: "Quit and reopen", exact: true }).dispatchEvent("click")
+ await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible()
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Second page", "Three", "Guide"])
+ expect(await drawn(tabs)).toEqual(ordered)
+ const restored = listed([one.ended, two.ended, three.ended])
+ await send(root, { ...restored, state: { ...restored.state, tabs: restored.state.tabs.map((tab) => ({ ...tab, title: "", generation: 1 })) } })
+ await expect(root.getByRole("status", { name: "Loading", exact: true })).toHaveCount(0)
+ expect(await drawn(tabs)).toEqual(ordered)
+ await expect(selected).toHaveText(`browser:${docs}`)
+})
+
+story("a tab a link opens in front appears at once, selected, beside the tab it came from, and its page's title is its only other change", async ({ page }) => {
+ const { root, tabs, listed, selected } = await linkStrip(page)
+ const front = linkPage("tab_88888888-8888-8888-8888-888888888888", "front", "In front")
+ const address = root.getByRole("combobox", { name: "Browser address", exact: true })
+ const before = await drawn(tabs)
+
+ // The person clicks a `target="_blank"` link in Docs: main lists the tab after Docs and brings it to the front, in
+ // that order (`tab.opened`, then `tab.focused`, in pane-machine.ts).
+ await send(root, listed([front.blank], { placed: { tabID: front.id, after: docs }, unnamed: [front.id] }))
+ await send(root, listed([front.blank], { unnamed: [front.id], focusedTabID: front.id }))
+ await send(root, { type: "focus", tabID: front.id })
+ await expect(selected).toHaveText(`browser:${front.id}`)
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "New tab", "Guide"])
+ const shown = await drawn(tabs)
+ expectInserted(before, shown, 3)
+
+ // Its load starts and its document commits: the pane shows the address, and no box moves or changes width or label.
+ await send(root, listed([front.started], { unnamed: [front.id], focusedTabID: front.id }))
+ await expect(root.getByRole("button", { name: "Stop", exact: true })).toBeVisible()
+ expect(await drawn(tabs)).toEqual(shown)
+ await send(root, listed([front.committed], { unnamed: [front.id], focusedTabID: front.id }))
+ await expect(address).toHaveValue("https://example.com/front")
+ expect(await drawn(tabs)).toEqual(shown)
+
+ // Its document names itself: the tab takes that name, where it stands.
+ await send(root, listed([front.named], { focusedTabID: front.id }))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "In front", "Guide"])
+ const named = await drawn(tabs)
+ expectRenamed(shown, named, 3, "In front")
+ await send(root, details(front.id, docsIcon))
+ await expect(root.getByRole("tab", { name: "In front", exact: true }).locator("img")).toHaveAttribute("src", docsIcon)
+ await send(root, listed([front.ended], { focusedTabID: front.id }))
+ await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeVisible()
+ expect(await drawn(tabs)).toEqual([...named.slice(0, 3), { ...named[3], icon: docsIcon }, named[4]])
+ await expect(selected).toHaveText(`browser:${front.id}`)
+})
+
+// The strip is the host's, and the host can drop a session's tabs with no plugin hearing of it: its layout stores the
+// strips of the 50 sessions used last, open or not, and a session that comes back in another directory starts with
+// none. The desktop still held every tab, but the strip took only the tabs new to an inventory, so none came back. The
+// next tab the agent worked in, or the next one to open, then stood alone: every browser tab but one had gone, and
+// nobody had closed one.
+story("a strip the host forgot gets back every tab the desktop holds, so the tab the agent works in next does not stand alone", async ({ page }) => {
+ const { root, tabs, listed, selected } = await linkStrip(page)
+ const guide = "tab_77777777-7777-7777-7777-777777777777"
+ const pricing = reported({ id: "tab_88888888-8888-8888-8888-888888888888", url: "https://example.com/pricing", title: "Pricing", generation: 1 })
+ const before = await drawn(tabs)
+
+ // Each browser tab as it was drawn, wherever the strip now starts: the file tab went with the strip.
+ const same = (now: Box[]) => {
+ expect(now.map((tab) => ({ ...tab, x: 0 }))).toEqual(before.slice(1).map((tab) => ({ ...tab, x: 0 })))
+ now.slice(1).forEach((tab, index) => expect(tab.x - now[index].x).toBeCloseTo(before[index + 2].x - before[index + 1].x, 3))
+ }
+
+ // The person works in other sessions, fifty of them, and the host forgets this one's strip. Its shell tab is open.
+ const away = async () => {
+ await root.getByRole("button", { name: "Alpha", exact: true }).dispatchEvent("click")
+ await expect(tabs).toHaveText(["alpha.ts"])
+ await root.getByRole("button", { name: "Fifty other sessions used", exact: true }).dispatchEvent("click")
+ }
+
+ await away()
+ // Meanwhile the agent works in Guide, which main brings to the front.
+ await send(root, { type: "focus", tabID: guide })
+ // The person comes back: all three tabs, each once, in the desktop's order, as they were drawn, and Guide in front.
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(tabs).toHaveText(["Preview", "Docs", "Guide"])
+ await expect(selected).toHaveText(`browser:${guide}`)
+ same(await drawn(tabs))
+
+ // Again, and this time the desktop reports a tab the agent opened: it joins the three, at the end.
+ const returned = await drawn(tabs)
+ await away()
+ await send(root, { type: "state", state: { tabs: [...listed([]).state.tabs, pricing], focusedTabID: docs } })
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(tabs).toHaveText(["Preview", "Docs", "Guide", "Pricing"])
+ expect((await drawn(tabs)).slice(0, 3)).toEqual(returned)
+
+ // Once more, with nothing from the desktop, whose pages are quiet: coming back is enough.
+ const four = await drawn(tabs)
+ await away()
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(tabs).toHaveText(["Preview", "Docs", "Guide", "Pricing"])
+ expect(await drawn(tabs)).toEqual(four)
+})
+
+// A page's icon arrives after its tab is drawn: Chromium lists it once the document's head has parsed, and main loads
+// it. The tab draws the globe until then. A site's SVG is drawn as an image, never put in the window as markup.
+story("a tab draws its page's icon in the globe's place as an image, and no tab moves", async ({ page }) => {
+ const root = page.getByTestId("browser-region-fixture")
+ const tabs = root.getByRole("tab")
+ await root.getByRole("button", { name: "Beta", exact: true }).click()
+ await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
+ await send(root, inventory(reported({ id: preview, url: "http://localhost:4173/", title: "Preview" }), reported({ id: docs, url: "https://example.com/docs", title: "Docs" })))
+ await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"])
+ await page.evaluate(() => document.fonts.ready.then(() => undefined))
+ const globes = await drawn(tabs)
+ expect(globes.slice(1).map((tab) => tab.icon)).toEqual(["none", "none"])
+
+ // A site's own SVG that would run as markup: a script, and a handler on the element itself.
+ const hostile = `data:image/svg+xml;base64,${Buffer.from(``).toString("base64")}`
+ const image = root.getByRole("tab", { name: "Docs", exact: true }).locator("img")
+ await send(root, details(preview, previewIcon))
+ await send(root, details(docs, hostile))
+ await expect(image).toHaveAttribute("src", hostile)
+ await expect.poll(() => image.evaluate((node: HTMLImageElement) => node.complete && node.naturalWidth > 0)).toBe(true)
+ expect(await page.evaluate(() => "iconRan" in window)).toBe(false)
+ expect(await drawn(tabs)).toEqual([globes[0], { ...globes[1], icon: previewIcon }, { ...globes[2], icon: hostile }])
+})
+
// A server without a browser left its restored tabs on a loader with no end.
story("a restored tab on a server without a browser says that the browser could not open, and keeps its box", async ({ page }) => {
const { root, stable } = await reopen(page)
diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts
index 039cce3987ad..7f269e6421bb 100644
--- a/packages/app/component-tests/browser-pane.spec.ts
+++ b/packages/app/component-tests/browser-pane.spec.ts
@@ -837,9 +837,10 @@ story("hides the native page under a dialog even when its still never arrives",
story("comments on a picked element over a still of the page", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("zoomed")
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
await picker.click()
await expect(picker.picking).toBeAttached()
+ await expect(picker.button).toHaveAttribute("aria-pressed", "true")
await expect(root.getByText("Picker: on", { exact: true })).toBeVisible()
await expect(root.getByText("Session getter reads: 0", { exact: true })).toBeVisible()
await expect(root.getByRole("status")).toHaveText(
@@ -848,6 +849,7 @@ story("comments on a picked element over a still of the page", async ({ page })
await root.getByRole("button", { name: "Pick element", exact: true }).click()
await expect(picker.picking).toHaveCount(0)
+ await expect(picker.button).toHaveAttribute("aria-pressed", "false")
const editor = root.locator('[data-slot="browser-comment-editor"] textarea')
await expect(editor).toBeFocused()
await expect(editor).toHaveAttribute("placeholder", "Add an optional comment...")
@@ -886,7 +888,7 @@ story("comments on a picked element over a still of the page", async ({ page })
story("cancels the picker and a comment with Escape", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
await picker.click()
await expect(picker.picking).toBeAttached()
await page.keyboard.press("Escape")
@@ -905,7 +907,7 @@ story("cancels the picker and a comment with Escape", async ({ page }) => {
story("leaves the picker off and Escape to the app when main never answers", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
await root.getByRole("button", { name: "Drop picker requests", exact: true }).click()
await picker.click()
await expect(picker.picking).toHaveCount(0)
@@ -929,7 +931,7 @@ story("replaces an open page note with the comment for an element picked meanwhi
story("cleans up the originating session's picker and comment after a session switch", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
await picker.click()
await expect(root.getByText("Picker Alpha: on", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Beta", exact: true }).click()
@@ -949,7 +951,7 @@ story("cleans up the originating session's picker and comment after a session sw
story("ends the native picker and highlight when the pane unmounts", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
await picker.click()
await expect(root.getByText("Picker: on", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Unmount pane", exact: true }).click()
@@ -967,7 +969,7 @@ story("ends the native picker and highlight when the pane unmounts", async ({ pa
story("keeps a comment draft but drops its ref when the page navigates", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
- await commentTool(page, root).click()
+ await commentTool(root).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")
@@ -982,7 +984,7 @@ story("keeps a comment draft but drops its ref when the page navigates", async (
story("grows the compact comment upward without flipping and keeps its actions inside the page", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("low")
- await commentTool(page, root).click()
+ await commentTool(root).click()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
const editor = root.locator('[data-slot="browser-comment-editor"]')
const field = editor.locator("textarea")
@@ -1019,7 +1021,7 @@ story("grows the compact comment upward without flipping and keeps its actions i
// Near the surface's top, growth stops at the opening bottom rather than pushing the card down.
await field.press("Escape")
await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("default")
- await commentTool(page, root).click()
+ await commentTool(root).click()
await root.getByRole("button", { name: "Pick element", exact: true }).click()
await expect(field).toBeFocused()
const nearTop = await editor.boundingBox()
@@ -1061,7 +1063,7 @@ story(
async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
const scenario = root.getByRole("combobox", { name: "Picked element scenario" })
- const picker = commentTool(page, root)
+ const picker = commentTool(root)
const editor = root.locator('[data-slot="browser-comment-editor"]')
const overlay = root.locator('[data-component="browser-comment"]')
await scenario.selectOption("long")
@@ -1605,6 +1607,9 @@ story("keeps a page note editable beside a tiny viewport and attaches it to the
await editor.click()
await editor.fill("Check the header layout")
await addPage(page, root)
+ // The menu gives the keyboard back to its button a task after it closes, and would take it from an editor focused
+ // in that task: the Enter below would then open the menu again.
+ await expect(root.getByRole("button", { name: "Browser options", exact: true })).toBeFocused()
await expect(editor).toHaveValue("Check the header layout")
await editor.press("Enter")
await expect(root.getByTestId("fixture-comments").getByRole("listitem")).toHaveText([/: Check the header layout$/])
@@ -1617,6 +1622,8 @@ story("adds the whole page to the session and keeps the draft when the button is
await editor.click()
await editor.fill("Check the header layout")
await addPage(page, root)
+ // As above: the menu's button has the keyboard again before the editor takes it.
+ await expect(root.getByRole("button", { name: "Browser options", exact: true })).toBeFocused()
await expect(editor).toHaveValue("Check the header layout")
await editor.press("Enter")
await expect(root.getByTestId("fixture-comments").getByRole("listitem")).toHaveText([/: Check the header layout$/])
@@ -1627,9 +1634,10 @@ story("shows the page's cookies in the site information and clears them", async
await root.getByRole("button", { name: "Site information", exact: true }).click()
const site = page.getByRole("dialog")
await site.getByRole("button", { name: "Site settings", exact: true }).click()
- await expect(site).toContainText("3 cookies in use")
+ // The row is "Cookies and site data", so its count needs no more words.
+ await expect(site.getByText("3 cookies", { exact: true })).toBeVisible()
await site.getByRole("button", { name: "Clear", exact: true }).click()
- await expect(site).toContainText("0 cookies in use")
+ await expect(site.getByText("0 cookies", { exact: true })).toBeVisible()
})
story("site information opens on the site and its connection, with the rest one step away", async ({ page }) => {
@@ -1639,19 +1647,19 @@ story("site information opens on the site and its connection, with the rest one
// First: where the person is and whether the connection is private. Nothing about cookies or agents yet.
await expect(site).toContainText("alpha.example")
await expect(site).toContainText("Connection is secure")
- await expect(site).not.toContainText("cookies in use")
+ await expect(site).not.toContainText(/cookie/i)
const settings = site.getByRole("button", { name: "Site settings", exact: true })
await settings.click()
// Second: everything else, with the way back holding the keyboard.
await expect(site.getByRole("button", { name: "Back", exact: true })).toBeFocused()
- await expect(site).toContainText("3 cookies in use")
+ await expect(site.getByText("3 cookies", { exact: true })).toBeVisible()
await expect(site).toContainText("You stay signed in.")
await expect(site.getByRole("button", { name: "Clear saved files for this site", exact: true })).toBeEnabled()
await expect(site).toContainText("Agents you allow can use this page")
// Escape steps back one view, then closes.
await page.keyboard.press("Escape")
await expect(settings).toBeFocused()
- await expect(site).not.toContainText("cookies in use")
+ await expect(site).not.toContainText(/cookie/i)
await page.keyboard.press("Escape")
await expect(site).toBeHidden()
})
@@ -1662,11 +1670,11 @@ story("says a failed cookie read failed and reads again on retry", async ({ page
await root.getByRole("button", { name: "Site information", exact: true }).click()
const site = page.getByRole("dialog")
await site.getByRole("button", { name: "Site settings", exact: true }).click()
- await expect(site).toContainText("Couldn't read this site's cookies.")
+ await expect(site.getByText("Could not read site data.", { exact: true })).toBeVisible()
const retry = site.getByRole("button", { name: "Try again", exact: true })
await expect(retry).toBeEnabled()
await retry.click()
- await expect(site).toContainText("3 cookies in use")
+ await expect(site.getByText("3 cookies", { exact: true })).toBeVisible()
await expect(site.getByRole("button", { name: "Clear", exact: true })).toBeEnabled()
})
@@ -1695,11 +1703,21 @@ function viewportControls(page: Page) {
const root = page.getByTestId("browser-pane-fixture")
const controls = root.getByRole("region", { name: "Viewport", exact: true })
+ const options = root.getByRole("button", { name: "Browser options", exact: true })
return {
root,
controls,
- viewport: root.getByRole("button", { name: "Toggle browser toolbar", exact: true }),
+ // The toolbar's toggle is under Browser options > More tools. The menu gives the keyboard back to its button a
+ // task after it closes, so the click waits for that: a control focused before then would lose the keyboard.
+ viewport: {
+ click: async () => {
+ await options.click()
+ await page.getByRole("menuitem", { name: "More tools", exact: true }).click()
+ await page.getByRole("menuitem", { name: /^Toggle browser toolbar/ }).click()
+ await expect(options).toBeFocused()
+ },
+ },
preset: controls.getByRole("button", { name: "Device preset", exact: true }),
option: (name: string) => page.getByRole("menuitemradio", { name, exact: true }),
moreDevices: page.getByRole("menuitem", { name: "More devices", exact: true }),
@@ -1771,6 +1789,8 @@ story("restores the full pane when the toolbar closes and keeps the selected dev
"Laptop",
"Desktop",
])
+ // The rows show before the menu has the keyboard: until its first row is focused, a key still goes to the trigger.
+ await expect(option("Responsive")).toBeFocused()
await page.keyboard.press("End")
await expect(moreDevices).toBeFocused()
await page.keyboard.press("ArrowRight")
@@ -2286,7 +2306,7 @@ story("the options menu lists everyday actions first and the rest under More too
await expect(page.getByRole("group", { name: "Zoom", exact: true }).getByRole("menuitem")).toHaveCount(3)
await page.getByRole("menuitem", { name: "More tools", exact: true }).click()
await expect(page.getByRole("menu", { name: "More tools", exact: true }).getByRole("menuitem")).toHaveText([
- /^Comment on part of the page/,
+ /^Toggle browser toolbar/,
"Open in default browser",
/^Reload without saved files/,
"Clear history",
@@ -2295,20 +2315,19 @@ story("the options menu lists everyday actions first and the rest under More too
await page.getByRole("menuitem", { name: "Clear history", exact: true }).click()
await expect(root.getByText("Visits:", { exact: true })).toBeVisible()
await expect(root.getByText("Main history: 0", { exact: true })).toBeVisible()
- // The bar keeps only what every browser has there.
+ // Neither has a button in the bar.
await expect(root.getByRole("button", { name: "Add page to session", exact: true })).toHaveCount(0)
- await expect(root.getByRole("button", { name: "Comment on part of the page", exact: true })).toHaveCount(0)
+ await expect(root.getByRole("button", { name: "Toggle browser toolbar", exact: true })).toHaveCount(0)
})
-// The comment tool lives under Browser options > More tools. While it waits for a pick, the pane says so in a status
-// line for assistive technology, which these cases read where the old toolbar button had a pressed state.
-function commentTool(page: Page, root: Locator) {
+// The comment tool is a button in the bar. While it waits for a pick, the pane also says so in a status line for
+// assistive technology, which these cases read.
+function commentTool(root: Locator) {
+ const button = root.getByRole("button", { name: "Comment on part of the page", exact: true })
+
return {
- click: async () => {
- await root.getByRole("button", { name: "Browser options", exact: true }).click()
- await page.getByRole("menuitem", { name: "More tools", exact: true }).click()
- await page.getByRole("menuitem", { name: /^Comment on part of the page/ }).click()
- },
+ button,
+ click: () => button.click(),
picking: root.getByText("Click part of the page to comment on it. Press Escape to cancel.", { exact: true }),
}
}
diff --git a/packages/app/component-tests/browser-settings.spec.ts b/packages/app/component-tests/browser-settings.spec.ts
index 6c8707c282fb..376004ab36ff 100644
--- a/packages/app/component-tests/browser-settings.spec.ts
+++ b/packages/app/component-tests/browser-settings.spec.ts
@@ -6,21 +6,42 @@ const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("../../gui-plugins/src/browser/settings.fixture.tsx"),
ui: source("../src/runtime/plugin/ui.tsx"),
+ // The app's own confirmation dialog, which `Dialogs.confirm` shows, and the language it reads.
+ dialogs: source("../src/runtime/plugin/dialogs.tsx"),
+ language: source("../src/runtime/i18n/language.tsx"),
}
// Any story loads the app styles; the fixture mounts the real Settings > Browser page beside it. `target` is the entry
// a settings search or the command palette is revealing.
-async function open(page: Page, options?: { target?: string; extensions?: boolean; installed?: boolean; historyKept?: boolean }) {
+async function open(
+ page: Page,
+ options?: {
+ target?: string
+ extensions?: boolean
+ installed?: boolean
+ historyKept?: boolean
+ clearFails?: boolean
+ file?: { imported: number; failed: number } | "unreadable"
+ },
+) {
await page.evaluate(
async (input) => {
- const [{ mountBrowserSettings }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
+ const [{ mountBrowserSettings }, { ui }, { PluginConfirmDialog }, { LanguageProvider }] = await Promise.all([
+ import(input.modules.fixture),
+ import(input.modules.ui),
+ import(input.modules.dialogs),
+ import(input.modules.language),
+ ])
mountBrowserSettings({
ui,
+ host: { Confirm: PluginConfirmDialog, LanguageProvider },
+ clearFails: input.options?.clearFails,
target: input.options?.target,
extensions: input.options?.extensions,
installed: input.options?.installed,
historyKept: input.options?.historyKept,
+ file: input.options?.file,
})
},
{ modules, options },
@@ -32,6 +53,13 @@ async function open(page: Page, options?: { target?: string; extensions?: boolea
root,
advanced: root.getByRole("button", { name: /^Advanced/ }),
stored: root.getByTestId("browser-settings-stored"),
+ data: root.getByRole("region", { name: "Browser data", exact: true }),
+ // The red button, and the question it asks before anything is cleared.
+ clear: root.getByRole("region", { name: "Browser data", exact: true }).getByRole("button", { name: "Clear browsing data", exact: true }),
+ confirm: page.getByRole("dialog", { name: "Clear browsing data?", exact: true }),
+ // How often main was asked to clear. The dialog is modal, so this is hidden from the accessibility tree meanwhile.
+ clears: root.getByTestId("browser-settings-clears"),
+ visits: root.getByTestId("browser-settings-visits"),
}
}
@@ -72,21 +100,121 @@ story("no setting decides what an import brings: the import section has its brow
await expect(view.stored).not.toContainText("importHistory")
})
-story("a sign-out that left the history behind says so in its row, and still forgets the window's last pages", async ({ page }) => {
- const view = await open(page, { target: "settings-browser-cookies", historyKept: true })
+story("each switch is named by its row's title, and each row says what it does in one sentence", async ({ page }) => {
+ const view = await open(page, { target: "settings-browser-remote", extensions: true })
+ const row = (id: string) => view.root.locator(`[data-action="${id}"]`)
+
+ // The switch's accessible name is the row's title, so a screen reader hears what the row shows.
+ for (const [id, title, description] of [
+ ["settings-browser-links", "Open links in OpenCode", "Hold Shift and click a link to use your default browser"],
+ ["settings-browser-remote", "Share sign-ins with remote servers", "Only turn on for servers you trust, since they can access your signed\u2011in sites"],
+ ["settings-browser-agent-pages", "Open browser automatically", "Show the tab when the agent opens a page or file for you"],
+ ] as const) {
+ await expect(row(id).locator('[data-slot="settings-row-title"]')).toHaveText(title)
+ await expect(row(id).locator('[data-slot="settings-row-description"]')).toHaveText(description)
+ await expect(row(id).getByRole("switch", { name: title, exact: true })).toHaveCount(1)
+ }
+
+ await expect(row("settings-browser-extensions").locator('[data-slot="settings-row-description"]')).toHaveText(
+ "Install from the Chrome Web Store, Edge Add-ons, or your other browsers",
+ )
+ const sites = view.root.getByRole("region", { name: "Site permissions", exact: true })
+ await expect(sites.locator('[data-slot="settings-row-title"]')).toHaveText("No saved permissions")
+ await expect(sites.locator("p")).toHaveText("Agent and remote server tabs ask again. Clearing browsing data keeps saved permissions.")
+})
+
+story("the red button asks first: Cancel, Escape, Enter on Cancel and a click outside clear nothing, and the confirm clears once", async ({ page }) => {
+ const view = await open(page, { target: "settings-browser-cookies" })
+ const cancel = view.confirm.getByRole("button", { name: "Cancel", exact: true })
+ const confirm = view.confirm.getByRole("button", { name: "Clear data", exact: true })
+
+ await expect(view.data.getByText("0 cookies. Sign-ins are shared across sessions", { exact: true })).toBeVisible()
+ await view.clear.click()
+ // One title, one line, two buttons: no close button, as the app's other confirmations.
+ await expect(view.confirm.getByText("This signs you out of all sites and deletes history in OpenCode, leaving your other browsers untouched.", { exact: true })).toBeVisible()
+ await expect(view.confirm.getByRole("button")).toHaveText(["Cancel", "Clear data"])
+ // As the app's destructive confirmations do, it opens on Cancel, so Enter does not clear by accident.
+ await expect(cancel).toBeFocused()
+ await page.keyboard.press("Tab")
+ await expect(confirm).toBeFocused()
+ await page.keyboard.press("Shift+Tab")
+ await page.keyboard.press("Enter")
+ await expect(view.confirm).toHaveCount(0)
+ await expect(view.clears).toHaveText("0")
+
+ for (const dismiss of [
+ () => cancel.click(),
+ () => page.keyboard.press("Escape"),
+ // Outside the dialog: the dimmed page behind it.
+ () => page.mouse.click(8, 8),
+ ]) {
+ await view.clear.click()
+ await expect(cancel).toBeFocused()
+ await dismiss()
+ await expect(view.confirm).toHaveCount(0)
+ await expect(view.clears).toHaveText("0")
+ }
- await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("1")
- await view.root.getByRole("button", { name: "Sign out everywhere", exact: true }).click()
- // The sign-out itself worked, so the row does not call it failed; "everywhere" alone would be a false claim.
- await expect(view.root.getByText("Signed out everywhere. The history could not be cleared.", { exact: true })).toBeVisible()
- await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("0")
- await expect(view.root.getByRole("button", { name: "Sign out everywhere", exact: true })).toBeEnabled()
+ // Nothing ran: the row still shows the count, the window's last pages are there, and the button is ready again.
+ await expect(view.data.getByText("0 cookies. Sign-ins are shared across sessions", { exact: true })).toBeVisible()
+ await expect(view.visits).toHaveText("1")
+ await expect(view.clear).toBeEnabled()
+
+ // Confirmed, with a second press on its way: main is asked once, and the row says how it ended.
+ await view.clear.click()
+ await confirm.dblclick()
+ await expect(view.confirm).toHaveCount(0)
+ await expect(view.data.getByText("Cleared browsing data.", { exact: true })).toBeVisible()
+ await expect(view.clears).toHaveText("1")
+ await expect(view.visits).toHaveText("0")
+})
+
+story("a confirmed clear that left the history behind says so in its row", async ({ page }) => {
+ const kept = await open(page, { target: "settings-browser-cookies", historyKept: true })
+
+ await kept.clear.click()
+ await kept.confirm.getByRole("button", { name: "Clear data", exact: true }).click()
+ // The sign-ins and site data went, so the row does not call it failed; it says what stayed.
+ await expect(kept.data.getByText("Cleared sign-ins and site data, but history could not be cleared.", { exact: true })).toBeVisible()
+ await expect(kept.visits).toHaveText("0")
+ await expect(kept.clear).toBeEnabled()
+})
+
+story("a confirmed clear that main rejects says that it could not clear, and can be tried again", async ({ page }) => {
+ const view = await open(page, { target: "settings-browser-cookies", clearFails: true })
+
+ await view.clear.click()
+ await view.confirm.getByRole("button", { name: "Clear data", exact: true }).click()
+ await expect(view.data.getByText("Couldn't clear browsing data. Try again.", { exact: true })).toBeVisible()
+ await expect(view.clears).toHaveText("1")
+ await expect(view.visits).toHaveText("1")
+ await expect(view.clear).toBeEnabled()
})
+// A cookie file is cookies, so its row counts them: the one place an import says "cookies".
+for (const [name, file, line] of [
+ ["a cookie file that came whole", { imported: 12, failed: 0 }, "Imported 12 cookies."],
+ ["a cookie file that lost some", { imported: 12, failed: 3 }, "Imported 12 cookies, 3 skipped."],
+ ["a cookie file that brought one", { imported: 1, failed: 1 }, "Imported 1 cookie, 1 skipped."],
+ // No browser's data, and no browser to close: the line is about the file.
+ ["a cookie file that cannot be read", "unreadable", "Could not read this file."],
+] as const)
+ story(`${name} says so in its row: ${line}`, async ({ page }) => {
+ const view = await open(page, { target: "settings-browser-cookies", file })
+
+ await expect(view.root.getByText("Import cookie file", { exact: true })).toBeVisible()
+ await expect(view.root.getByText("Supports cookies.txt or JSON from browser extensions or Playwright", { exact: true })).toBeVisible()
+ await view.root.getByRole("button", { name: "Choose file", exact: true }).click()
+ await expect(view.root.getByText(line, { exact: true })).toBeVisible()
+ })
+
story("Add an extension aligns controls without top clipping and switches cleanly into a confirmation step", async ({ page }) => {
const view = await open(page, { extensions: true })
- await view.root.getByRole("button", { name: "Add extension" }).click()
+ // The row is "Add an extension", so its button is "Add", with its plus.
+ const add = view.root.locator('[data-action="settings-browser-extensions"]').getByRole("button", { name: "Add", exact: true })
+ await expect(add.locator("svg")).toHaveCount(1)
+ await add.click()
const dialog = page.getByRole("dialog", { name: "Add an extension" })
await expect(dialog).toBeVisible()
await expect(dialog.getByText("LastPass: Free Password Manager")).toBeVisible()
@@ -156,7 +284,7 @@ story("Add an extension aligns controls without top clipping and switches cleanl
// Approving installs the extension and returns to the picker with status and updated row state.
await dialog.getByRole("button", { name: "Add", exact: true }).nth(1).click()
- await confirm.getByRole("button", { name: "Add extension" }).click()
+ await confirm.getByRole("button", { name: "Add", exact: true }).click()
await expect(page.getByRole("dialog", { name: "Add an extension" })).toBeVisible()
await expect(dialog.getByRole("status")).toContainText("Added LastPass: Free Password Manager.")
await expect(dialog.getByRole("button", { name: "Added" })).toBeDisabled()
diff --git a/packages/app/component-tests/browser-site-chooser.spec.ts b/packages/app/component-tests/browser-site-chooser.spec.ts
index c5e52f8fa06f..be3f9f6d8a46 100644
--- a/packages/app/component-tests/browser-site-chooser.spec.ts
+++ b/packages/app/component-tests/browser-site-chooser.spec.ts
@@ -12,6 +12,9 @@ type SiteScenario = {
site?: { name: string; choose: boolean }
reveal?: boolean
pages?: number
+ none?: boolean
+ keychain?: boolean
+ unreadable?: boolean
}
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
@@ -300,7 +303,7 @@ story("shows what the list is doing in its place, with a way to try again", asyn
story("says why a profile has no list, and reads it again on Try again", async ({ page }) => {
const view = await open(page, { sites: "locked" })
- await expect(view.dialog.getByRole("alert")).toHaveText("Google Chrome keeps its cookies locked while it runs. Quit Google Chrome, then import again.")
+ await expect(view.dialog.getByRole("alert")).toHaveText("Quit Google Chrome and try again.")
await view.dialog.getByRole("button", { name: "Try again" }).click()
await expect(view.record).toHaveAttribute("data-reads", "Default,Default")
})
@@ -529,6 +532,42 @@ story("the bar's own dialog brings history alone when Sign-ins is unticked, and
await expect(bar.record).toHaveAttribute("data-imported", "0")
})
+story("a browser's import never counts cookies: with none brought the bar says nothing was imported, or that the browser locks them", async ({ page }) => {
+ // One sign-in could not be written and none came: no history either, so nothing was imported.
+ const bar = await offer(page, { sites: 5, none: true, partial: true })
+
+ await bar.importing.click()
+ await expect(page.getByRole("alert")).toHaveText("Nothing was imported from Google Chrome.")
+ await expect(bar.confirmation).toHaveCount(0)
+})
+
+story("the import dialog stays open to say that the browser locks its sign-ins from other apps", async ({ page }) => {
+ const view = await open(page, { sites: 5, reveal: false, none: true, protected: 12 })
+
+ await view.importButton.click()
+ await expect(view.dialog.getByRole("alert")).toHaveText("Google Chrome locks its sign-ins from other apps. Sign in here instead.")
+ await expect(view.record).toHaveAttribute("data-closed", "false")
+})
+
+story("a browser whose data cannot be read says so about the browser, with what to do", async ({ page }) => {
+ const view = await open(page, { sites: 5, reveal: false, unreadable: true })
+
+ await view.importButton.click()
+ await expect(view.dialog.getByRole("alert")).toHaveText("Could not read this browser's data. Close it and try again.")
+ await expect(view.record).toHaveAttribute("data-closed", "false")
+})
+
+story("on macOS the dialog says what the Keychain prompt asks while a Chromium import waits, and not to choose Always Allow", async ({ page }) => {
+ const view = await open(page, { sites: 5, reveal: false, keychain: true })
+
+ await view.importButton.click()
+ await expect(view.dialog.getByRole("status")).toHaveText(
+ 'macOS asks for your password (shown as "security") to import Google Chrome\'s sign-ins. Choose Allow, not Always Allow, which lets any app read them without asking.',
+ )
+ await page.getByTestId("site-chooser-release").dispatchEvent("click")
+ await expect(view.record).toHaveAttribute("data-closed", "true")
+})
+
story("the offer card has a title and no paragraph, and its Import brings both", async ({ page }) => {
const card = await offer(page, { sites: 5, pages: 4210 }, true)
const region = page.getByRole("region", { name: "Bring your sign-ins and history", exact: true })
diff --git a/packages/app/component-tests/focus-rescue.spec.ts b/packages/app/component-tests/focus-rescue.spec.ts
index 3fd89a10d985..8508f66fe0df 100644
--- a/packages/app/component-tests/focus-rescue.spec.ts
+++ b/packages/app/component-tests/focus-rescue.spec.ts
@@ -3,42 +3,81 @@ import { expect, sourceURL, story } from "../../stories/playwright/story"
const fixture = sourceURL(new URL("./focus-rescue.fixture.tsx", import.meta.url))
-story.beforeEach(async ({ mount, page }) => {
- // Any story loads the app's styles; the fixture mounts its scopes beside it.
- await mount("ui-line-comment--editor")
- await page.evaluate(async (fixture) => {
- const { mountFocusRescue } = await import(fixture)
- mountFocusRescue()
- }, fixture)
-})
+const rescue = sourceURL(new URL("../../ui/src/context/focus-rescue.tsx", import.meta.url))
-const ringed = (locator: Locator) => locator.evaluate((element) => element.matches(":focus-visible"))
+story.describe("scopes", () => {
+ story.beforeEach(async ({ mount, page }) => {
+ // Any story loads the app's styles; the fixture mounts its scopes beside it.
+ await mount("ui-line-comment--editor")
+ await page.evaluate(async (fixture) => {
+ const { mountFocusRescue } = await import(fixture)
+ mountFocusRescue()
+ }, fixture)
+ })
-story("moves focus to the next item, or to the previous one after the last", async ({ page }) => {
- const list = page.getByTestId("list")
+ const ringed = (locator: Locator) => locator.evaluate((element) => element.matches(":focus-visible"))
- await list.getByRole("button", { name: "Two" }).focus()
- await page.keyboard.press("Enter")
- await expect(list.getByRole("button", { name: "Three" })).toBeFocused()
- expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(true)
+ story("moves focus to the next item, or to the previous one after the last", async ({ page }) => {
+ const list = page.getByTestId("list")
- await page.keyboard.press("Enter")
- await expect(list.getByRole("button", { name: "One" })).toBeFocused()
-})
+ // Tab moves focus to the item, so the item that takes over shows its ring.
+ await list.getByRole("button", { name: "One" }).press("Tab")
+ await expect(list.getByRole("button", { name: "Two" })).toBeFocused()
+ await page.keyboard.press("Enter")
+ await expect(list.getByRole("button", { name: "Three" })).toBeFocused()
+ expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(true)
-story("returns focus to what had it before when a scope is left empty", async ({ page }) => {
- await page.getByTestId("opener").focus()
- await page.getByTestId("toasts").getByRole("button", { name: "Toast" }).focus()
- await page.keyboard.press("Enter")
+ await page.keyboard.press("Enter")
+ await expect(list.getByRole("button", { name: "One" })).toBeFocused()
+ })
- await expect(page.getByTestId("opener")).toBeFocused()
-})
+ story("leaves the item that takes over without a ring when no key moved focus there", async ({ page }) => {
+ const list = page.getByTestId("list")
+
+ // Typing and Enter are not navigation, and the item got focus from code.
+ await page.keyboard.press("a")
+ await list.getByRole("button", { name: "Two" }).focus()
+ await page.keyboard.press("Enter")
+ await expect(list.getByRole("button", { name: "Three" })).toBeFocused()
+ expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(false)
+ })
+
+ story("returns focus to what had it before when a scope is left empty", async ({ page }) => {
+ await page.getByTestId("opener").focus()
+ await page.getByTestId("toasts").getByRole("button", { name: "Toast" }).focus()
+ await page.keyboard.press("Enter")
+
+ await expect(page.getByTestId("opener")).toBeFocused()
+ })
-story("never moves focus into a tab list", async ({ page }) => {
- await page.getByTestId("opener").focus()
- await page.getByTestId("strip").getByRole("tab", { name: "Tab B" }).focus()
- await page.keyboard.press("Enter")
+ story("never moves focus into a tab list", async ({ page }) => {
+ await page.getByTestId("opener").focus()
+ await page.getByTestId("strip").getByRole("tab", { name: "Tab B" }).focus()
+ await page.keyboard.press("Enter")
- // Tab A and Add tab are still there, but a tab list's tabs select themselves on focus.
- await expect(page.getByTestId("opener")).toBeFocused()
+ // Tab A and Add tab are still there, but a tab list's tabs select themselves on focus.
+ await expect(page.getByTestId("opener")).toBeFocused()
+ })
})
+
+for (const action of ["Steer", "Remove"]) {
+ story(
+ `composer takes focus without a ring after a click on ${action} removes the last queued prompt`,
+ async ({ mount, page }) => {
+ const root = await mount("session-composer-docks--queue-one")
+ await page.evaluate(async (rescue) => {
+ const { installFocusRescue } = await import(rescue)
+ installFocusRescue()
+ }, rescue)
+
+ const row = root.locator('[data-component="session-queue-row"]')
+
+ await row.hover()
+ await row.getByRole("button", { name: action }).click()
+
+ const editor = root.locator('[data-component="session-composer-dock"] [contenteditable="true"]')
+
+ await expect(editor).toBeFocused()
+ },
+ )
+}
diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts
index c03249ee44ae..0169df1fbd36 100644
--- a/packages/app/e2e/regression/composer.spec.ts
+++ b/packages/app/e2e/regression/composer.spec.ts
@@ -5,7 +5,7 @@ import { mockPluginsActivating, type MockServerConfig } from "../utils/mock-serv
test.use({ permissions: ["clipboard-read", "clipboard-write"] })
-test("the composer preserves its ring on dialog return and leaves autofocus and clicks quiet", async ({ page }) => {
+test("the composer shows its caret, never a focus ring, however focus arrives", async ({ page }) => {
const view = await openSession(page, { name: "ComposerKeyboardFocus" })
const frame = page.locator('[data-component="composer"]').filter({ has: view.editor })
@@ -17,7 +17,8 @@ test("the composer preserves its ring on dialog return and leaves autofocus and
await expect(view.editor).not.toBeFocused()
await page.keyboard.press("Tab")
await expect(view.editor).toBeFocused()
- await expect(frame).toHaveCSS("outline-style", "solid")
+ await expect(frame).toHaveCSS("outline-style", "none")
+ await expect(view.editor).toHaveCSS("outline-style", "none")
const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control"))
@@ -27,7 +28,7 @@ test("the composer preserves its ring on dialog return and leaves autofocus and
await expect(dialog.getByRole("combobox")).toBeFocused()
await page.keyboard.press("Escape")
await expect(view.editor).toBeFocused()
- await expect(frame).toHaveCSS("outline-style", "solid")
+ await expect(frame).toHaveCSS("outline-style", "none")
await view.editor.click()
await expect(view.editor).toBeFocused()
@@ -218,8 +219,8 @@ test("the free usage limit opens the Go dialog once, swaps the composer for the
? [
{
id: "opencode-go",
- integrationID: "opencode-go",
- name: "OpenCode Go",
+ integrationID: "opencode",
+ name: "Anomaly / OpenCode Go",
models: {
"glm-5-go": {
id: "glm-5-go",
@@ -238,21 +239,22 @@ test("the free usage limit opens the Go dialog once, swaps the composer for the
integrations: () => [
{
id: "opencode",
- name: "OpenCode Console",
- methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
+ name: "OpenCode",
+ methods: [
+ { id: "device", type: "oauth", label: "OpenCode account" },
+ { type: "key", label: "API key (service account)" },
+ ],
connections: state.authorized
? [{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" }]
: [],
},
- {
- id: "opencode-go",
- name: "OpenCode Go",
- methods: [{ type: "key" }],
- connections: state.authorized ? [{ type: "credential", id: "cred_go", label: "Go key", method: "key" }] : [],
- },
+ { id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] },
],
- onConnectKey: (input) => {
- if (input.integrationID === "opencode-go") state.authorized = true
+ onIntegrationOAuth: () => ({ url: "https://auth.example.test/device?user_code=GOGO-1234" }),
+ onIntegrationOAuthStatus: () => {
+ state.authorized = true
+
+ return "complete"
},
pageMessages: () => ({
items: [
@@ -293,13 +295,15 @@ test("the free usage limit opens the Go dialog once, swaps the composer for the
await expect(view.editor).toHaveCount(0)
await expect(page.getByText("Free usage limit reached.")).toHaveCount(0)
- // Subscribe -> Go API key -> Continue switches the model in the current session without opening a new draft tab.
+ // Subscribe -> OpenCode sign-in -> the workspace's Go model -> Continue switches the model in the current session
+ // without opening a new draft tab.
await upsell.getByRole("button", { name: "Subscribe", exact: true }).click()
- const connect = page.getByRole("dialog", { name: "Connect OpenCode Go", exact: true })
- await connect.getByPlaceholder("API key").fill("sk-go-test")
- await connect.getByRole("button", { name: "Continue", exact: true }).click()
- const connected = page.getByRole("dialog", { name: "Connected to OpenCode Go" })
- await expect(connected.getByRole("radio", { name: "GLM-5 Go", exact: true })).toHaveAttribute("aria-checked", "true")
+ const connect = page.getByRole("dialog", { name: "Connect OpenCode", exact: true })
+ await connect.getByRole("button", { name: "OpenCode account", exact: true }).click()
+ const connected = page.getByRole("dialog", { name: "Connected to OpenCode" })
+ const go = connected.getByRole("radio", { name: "GLM-5 Go", exact: true })
+ await go.click()
+ await expect(go).toHaveAttribute("aria-checked", "true")
await connected.getByRole("button", { name: "Continue", exact: true }).click()
await expect(page.getByRole("dialog")).toHaveCount(0)
await expectPath(page, sessionHref(sessionID))
diff --git a/packages/app/e2e/regression/home.spec.ts b/packages/app/e2e/regression/home.spec.ts
index d5013068a635..b240e4e49480 100644
--- a/packages/app/e2e/regression/home.spec.ts
+++ b/packages/app/e2e/regression/home.spec.ts
@@ -64,6 +64,7 @@ test("Home projects, utility rows, search and recent sessions show keyboard focu
await page.keyboard.press("Tab")
await expect(settings).toBeFocused()
await expect(settings).toHaveCSS("outline-style", "solid")
+ await expect(settings).not.toHaveCSS("transition-property", /\b(all|outline)\b/)
await page.keyboard.press("Tab")
await expect(help).toBeFocused()
await expect(help).toHaveCSS("outline-style", "solid")
@@ -72,11 +73,9 @@ test("Home projects, utility rows, search and recent sessions show keyboard focu
const field = page.locator('[data-slot="home-session-search-field"]')
+ // A text field shows its caret and background, not a ring.
await page.keyboard.press("Tab")
await expect(search).toBeFocused()
- await expect(field).toHaveCSS("outline-style", "solid")
- await search.click()
- await expect(search).toBeFocused()
await expect(field).toHaveCSS("outline-style", "none")
const recent = page.getByRole("region", { name: "Recent sessions" })
@@ -94,8 +93,9 @@ test("Home projects, utility rows, search and recent sessions show keyboard focu
await expect(viewport).toHaveAttribute("tabindex", "0")
await viewport.press("Shift+Tab")
await page.keyboard.press("Tab")
+ // The list takes focus so the keyboard can scroll it, without a ring around the whole area.
await expect(viewport).toBeFocused()
- await expect(viewport).toHaveCSS("outline-offset", "-2px")
+ await expect(viewport).toHaveCSS("outline-style", "none")
})
test("Home keeps the session list in every interface mode", async ({ page }) => {
@@ -197,7 +197,7 @@ test("the session context menu renames, exports, and deletes a Home session", as
const box = await target.boundingBox()
await target.click({ button: "right", position: { x: 48, y: 12 } })
await expect(page).toHaveURL("/")
- await expect(page.getByRole("menuitem")).toHaveText(["Rename", "Export…", "Delete…"])
+ await expect(page.getByRole("menuitem")).toHaveText(["Open", "Open in background", "Rename", "Export…", "Delete…"])
const menu = await page.locator('[data-component="menu-v2-content"]').boundingBox()
expect(Math.abs((menu?.x ?? 0) - (box?.x ?? 0) - 48)).toBeLessThan(4)
@@ -247,6 +247,29 @@ test("the session context menu renames, exports, and deletes a Home session", as
expect(removed.requests).toHaveLength(1)
})
+test("Open in background and a middle click add a Home session's tab without leaving Home, and Open goes to it", async ({
+ page,
+}) => {
+ const background = { id: "ses_home_open_background", title: "Opened in the background" }
+ const middle = { id: "ses_home_open_middle", title: "Opened with a middle click" }
+ const open = { id: "ses_home_open", title: "Opened from the menu" }
+ await mockWorkspace(page, { name: "HomeOpen", sessions: [background, middle, open], seed: { tabs: [] } })
+ await page.goto("/")
+ const tabs = page.locator('[data-slot="titlebar-tabs"] a')
+
+ await row(page, background.title).click({ button: "right" })
+ await page.getByRole("menuitem", { name: "Open in background", exact: true }).click()
+ await expect(tabs.filter({ hasText: background.title })).toBeVisible()
+
+ await row(page, middle.title).click({ button: "middle" })
+ await expect(tabs.filter({ hasText: middle.title })).toBeVisible()
+ await expect(page).toHaveURL("/")
+
+ await row(page, open.title).click({ button: "right" })
+ await page.getByRole("menuitem", { name: "Open", exact: true }).click()
+ await expect(page).toHaveURL(new RegExp(`/session/${open.id}$`))
+})
+
test("a failed session list says so and loads again on Try again, instead of showing the empty state", async ({
page,
}) => {
@@ -309,7 +332,6 @@ test("tabbing out of session search closes its results, and tabbing back reopens
await page.keyboard.press(`${modifier}+f`)
await expect(search).toBeFocused()
- await expect(page.locator('[data-slot="home-session-search-field"]')).toHaveCSS("outline-style", "solid")
await expect(panel.getByRole("option")).toContainText(earlier.title)
})
diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts
index c4f0d001b944..c87c39ee1c7e 100644
--- a/packages/app/e2e/regression/new-session.spec.ts
+++ b/packages/app/e2e/regression/new-session.spec.ts
@@ -47,6 +47,7 @@ test("new-session project picker and provider tip show keyboard focus", async ({
await newSessionWorktree(page).press("Shift+Tab")
await expect(projectPicker).toBeFocused()
await expect(projectPicker).toHaveCSS("outline-style", "solid")
+ await expect(projectPicker).not.toHaveCSS("transition-property", /\b(all|outline)\b/)
await expect(connect).toBeVisible()
await dismiss.press("Shift+Tab")
diff --git a/packages/app/e2e/regression/panel-edges.spec.ts b/packages/app/e2e/regression/panel-edges.spec.ts
index 651d1577074f..442d18ebccfd 100644
--- a/packages/app/e2e/regression/panel-edges.spec.ts
+++ b/packages/app/e2e/regression/panel-edges.spec.ts
@@ -55,7 +55,10 @@ test("the content beside a panel follows the panel's edge on every frame of a to
.locator("visible=true")
.first()
- const review = page.locator('[data-slot="session-review-toggle"] button')
+ // The header and the open panel's strip each hold a copy; only the one showing can be clicked.
+ const review = page
+ .locator('[data-slot="session-review-toggle"] button, [data-slot="session-review-panel-toggle"] button')
+ .locator("visible=true")
const runs = [
{ toggle: sidebar, before: '[data-slot="vertical-tabs-mount"]', after: "main", gap: 0 },
diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts
index 4c4eefe5b1d7..683883fbb0ff 100644
--- a/packages/app/e2e/regression/review.spec.ts
+++ b/packages/app/e2e/regression/review.spec.ts
@@ -99,9 +99,9 @@ for (const view of ["desktop", "mobile"] as const) {
await expect(panel.getByText("Track, review, and undo changes in this project")).toBeVisible()
if (view === "desktop") {
- const toggle = panel.getByRole("button", {name:"Toggle file tree"})
+ const toggle = panel.getByRole("button", { name: "Toggle file tree" })
- if (await toggle.getAttribute("aria-expanded") === "false") await toggle.click()
+ if ((await toggle.getAttribute("aria-expanded")) === "false") await toggle.click()
await expect(panel.getByText("No changed files. Use Open file to browse the workspace.")).toBeVisible()
}
@@ -2271,6 +2271,9 @@ for (const direction of ["ltr", "rtl"] as const) {
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
const panel = page.locator("#review-panel")
+ // Once the panel settles open, its strip shows its own copy of the toggle in place of the header's. Actions wait
+ // for that copy: one that starts on the header's copy as they swap keeps waiting for it to show again.
+ const settled = panel.getByRole("button", { name: "Toggle review", exact: true })
await expect(toggle).toHaveAttribute("aria-expanded", "false")
const closed = (await toggle.boundingBox())!
const header = (await page.locator("[data-session-title]").boundingBox())!
@@ -2308,6 +2311,7 @@ for (const direction of ["ltr", "rtl"] as const) {
.toBe(closed.y + closed.height / 2)
}
+ await expect(settled).toBeVisible()
await toggle.press("Enter")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await expect(toggle).toBeFocused()
@@ -2320,7 +2324,10 @@ for (const direction of ["ltr", "rtl"] as const) {
await expect(toggle).toHaveAttribute("aria-expanded", String(opened))
await expect(panel).toHaveAttribute("aria-hidden", String(!opened))
- if (opened) await expect(() => expectHeaderClearOfToggle(page, toggle)).toPass()
+ if (opened) {
+ await expect(settled).toBeVisible()
+ await expect(() => expectHeaderClearOfToggle(page, toggle)).toPass()
+ }
}
await expect(panel).toBeHidden()
@@ -2368,8 +2375,12 @@ async function expectHeaderClearOfToggle(page: Page, toggle: Locator) {
expect(Math.abs(geometry.row - geometry.panels)).toBeLessThanOrEqual(1)
const clip = (await toggle.boundingBox())!
- // Header contents must make no difference to the pixels behind the fixed toggle.
+ // Header contents must make no difference to the pixels behind the toggle, which sits in the strip's last slot.
expect(await page.screenshot({ clip })).toEqual(
- await page.screenshot({ clip, style: ".session-review-v2-tabs-bar { visibility: hidden !important; }" }),
+ await page.screenshot({
+ clip,
+ style: `.session-review-v2-tabs-bar * { visibility: hidden !important; }
+ .session-review-v2-tabs-bar [data-slot="session-review-panel-toggle"] * { visibility: visible !important; }`,
+ }),
)
}
diff --git a/packages/app/e2e/regression/session-header.spec.ts b/packages/app/e2e/regression/session-header.spec.ts
index def9bfb004ee..ea06ef0abf1c 100644
--- a/packages/app/e2e/regression/session-header.spec.ts
+++ b/packages/app/e2e/regression/session-header.spec.ts
@@ -117,6 +117,10 @@ for (const direction of ["ltr", "rtl"] as const) {
await review.click()
await expect(review).toHaveAttribute("aria-expanded", "true")
await expect(page.locator("#review-panel")).toBeVisible()
+ // A settled panel shows its own copy of the toggle; a click that starts on the header's copy as they swap misses.
+ await expect(
+ page.locator("#review-panel").getByRole("button", { name: "Toggle review", exact: true }),
+ ).toBeVisible()
await review.click()
await expect(review).toHaveAttribute("aria-expanded", "false")
diff --git a/packages/app/e2e/regression/session-request-docks.spec.ts b/packages/app/e2e/regression/session-request-docks.spec.ts
index ae1d0277e4dd..f654614d5929 100644
--- a/packages/app/e2e/regression/session-request-docks.spec.ts
+++ b/packages/app/e2e/regression/session-request-docks.spec.ts
@@ -551,6 +551,98 @@ test("loads a running subagent's question without polling idle subagents on ever
expect(forms.toSorted()).toEqual([`/api/session/${runningID}/form`, `/api/session/${sessionID}/form`].toSorted())
})
+test("recovers a running child session's permission on load and across reconnects without polling idle subagents", async ({
+ page,
+}) => {
+ const childID = "ses_request_running_child"
+ const idleIDs = Array.from({ length: 5 }, (_, index) => `ses_request_idle_perm_${index}`)
+ const replies: { sessionID: string; permissionID: string; body: unknown }[] = []
+ const child = { idle: false }
+
+ const childPermission = (id: string, command: string) => ({
+ id,
+ sessionID: childID,
+ action: "shell",
+ resources: [command],
+ metadata: {},
+ save: [],
+ })
+
+ const childPermissions = [childPermission("perm_child_initial", "git status")]
+
+ const sessionPermissions = {
+ [sessionID]: [],
+ [childID]: childPermissions,
+ }
+
+ const transport = await installSseTransport(page, { server: SERVER, retry: 20 })
+ await mockWorkspace(page, {
+ name: "RequestDocks",
+ directory,
+ sessions: [
+ { id: sessionID, title },
+ { id: childID, title: "Running child", parentID: sessionID },
+ ...idleIDs.map((id) => ({ id, title: id, parentID: sessionID })),
+ ],
+ seed: { tabs: [sessionID] },
+ sessionStatus: () => ({ [childID]: { type: child.idle ? "idle" : "running" } }),
+ sessionPermissions,
+ onPermissionReply: (reply) => replies.push(reply),
+ })
+
+ // Idle subagents whose worktrees were deleted must not be polled for permissions.
+ await page.route(/\/api\/session\/ses_request_idle_perm_\d+\/permission$/, (route) =>
+ route.fulfill({ status: 404, json: { message: "Location not found" } }),
+ )
+
+ const permissionGets: string[] = []
+ page.on("request", (request) => {
+ const path = new URL(request.url()).pathname
+
+ if (request.method() === "GET" && path.startsWith("/api/session/") && path.endsWith("/permission"))
+ permissionGets.push(path)
+ })
+
+ await page.goto(sessionHref(sessionID))
+ const first = await transport.waitForConnection()
+ await expectSessionTitle(page, title)
+
+ const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]')
+ const composer = page.locator('[data-component="composer"]')
+ await expect(permission).toBeVisible()
+ await expect(permission.getByText("git status")).toBeVisible()
+ await expect(composer).toHaveCount(0)
+
+ // Resolved while offline and the child finished: reconnect must clear the cached request.
+ childPermissions.length = 0
+ child.idle = true
+ await transport.disconnect()
+ const second = await transport.waitForConnection({ after: first.id })
+ await expect(permission).toHaveCount(0)
+ await expect(composer).toBeVisible()
+
+ // Asked while offline with no `permission.asked` event: reconnect must recover it for the child.
+ child.idle = false
+ childPermissions.push(childPermission("perm_child_reconnect", "git diff"))
+ await transport.disconnect()
+ await transport.waitForConnection({ after: second.id })
+ await expect(permission).toBeVisible()
+ await expect(permission.getByText("git diff")).toBeVisible()
+
+ const reply = page.waitForResponse(
+ (response) =>
+ response.request().method() === "POST" &&
+ new URL(response.url()).pathname === `/api/session/${childID}/permission/perm_child_reconnect/reply`,
+ )
+
+ await permission.getByRole("button", { name: "Allow once" }).click()
+ expect((await reply).status()).toBe(204)
+ expect(replies).toEqual([{ sessionID: childID, permissionID: "perm_child_reconnect", body: { decision: "once" } }])
+ await expect(permission).toHaveCount(0)
+ await expect(composer).toBeVisible()
+ expect(permissionGets.filter((path) => path.includes("ses_request_idle_perm_"))).toEqual([])
+})
+
test("restores the draft caret before typing after a request dock closes", async ({ page }) => {
const transport = await installSseTransport(page, { server: SERVER, retry: 20 })
await mockServer(page, { forms: [] })
diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts
index 83a698d45d64..f358a4db2329 100644
--- a/packages/app/e2e/regression/settings.spec.ts
+++ b/packages/app/e2e/regression/settings.spec.ts
@@ -1805,6 +1805,8 @@ for (const row of [
// Anthropic only exists in the integration fixture, so its row proves the integration list has loaded.
await expect(settings.getByText("Anthropic", { exact: true })).toBeVisible()
await expect(settings.getByText("OpenCode Console", { exact: true })).toHaveCount(row.console ? 1 : 0)
+ // OpenCode Go connects through OpenCode, so it isn't offered without a saved Go key.
+ await expect(settings.getByText("OpenCode Go", { exact: true })).toHaveCount(0)
})
}
@@ -1814,9 +1816,9 @@ const connectDialog = (page: Page) =>
const consoleIntegrations = [
{
id: "opencode",
- name: "OpenCode Console",
+ name: "OpenCode",
methods: [
- { id: "device", type: "oauth", label: "OpenCode Console account" },
+ { id: "device", type: "oauth", label: "OpenCode account" },
{ type: "key", label: "API key (service account)" },
],
connections: [],
@@ -1831,21 +1833,22 @@ test("providers: OpenCode Console signs in from its method list", async ({ page,
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings
- .locator(".settings-provider-row", { hasText: "OpenCode Console" })
+ .locator(".settings-provider-row")
+ .filter({ has: page.locator(".settings-provider-name", { hasText: /^OpenCode$/ }) })
.getByRole("button", { name: "Connect", exact: true })
.click()
- const methods = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true })
+ const methods = page.getByRole("dialog", { name: "Connect OpenCode", exact: true })
// The methods come from the integration in the TUI's order: sign-ins first, API keys last.
await expect(methods.locator('[data-action="provider-connect-method"]')).toHaveText([
- "OpenCode Console account",
+ "OpenCode account",
"API key (service account)",
])
const popup = page.waitForEvent("popup")
- await methods.getByRole("button", { name: "OpenCode Console account", exact: true }).click()
+ await methods.getByRole("button", { name: "OpenCode account", exact: true }).click()
await expect(await popup).toHaveURL(url)
- const signIn = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true })
+ const signIn = page.getByRole("dialog", { name: "Connect OpenCode", exact: true })
await expect(signIn.getByRole("group", { name: "Device code: ABCD-EFGH", exact: true })).toBeVisible()
await expect(signIn.getByRole("button", { name: "Copy sign-in link", exact: true })).toBeVisible()
})
@@ -1854,7 +1857,16 @@ test("providers: OpenCode Go connects with its own methods, not the Console sign
const attempts: string[] = []
const { settings } = await open(page, {
- integrations: consoleIntegrations,
+ // Settings lists OpenCode Go only for people who already saved a Go key.
+ integrations: [
+ ...consoleIntegrations.filter((integration) => integration.id !== "opencode-go"),
+ {
+ id: "opencode-go",
+ name: "OpenCode Go",
+ methods: [{ type: "key" }],
+ connections: [{ type: "credential", id: "cred_go", label: "Go key", method: "key" }],
+ },
+ ],
onIntegrationOAuth: (input) => {
attempts.push(input.integrationID)
@@ -1952,7 +1964,7 @@ test("providers: Back during a pending API key request does not report the provi
await expect(dialog.getByPlaceholder("API key")).toHaveValue("")
})
-test("providers: the free tier upsell opens Go on its own, sized to its content", async ({ page }) => {
+test("providers: the free tier upsell opens OpenCode on its own, sized to its content", async ({ page }) => {
const view = await openSession(page, { name: "FreeTier", integrations: consoleIntegrations })
await view.push([
{
@@ -1973,10 +1985,14 @@ test("providers: the free tier upsell opens Go on its own, sized to its content"
.getByRole("button", { name: "Subscribe", exact: true })
.click()
- const dialog = page.getByRole("dialog", { name: "Connect OpenCode Go", exact: true })
+ // Go connects through the OpenCode connection, so the upsell opens its sign-in methods.
+ const dialog = page.getByRole("dialog", { name: "Connect OpenCode", exact: true })
const container = page.locator('[data-slot="dialog-container"]')
- await expect(dialog.getByPlaceholder("API key")).toBeVisible()
- // Nothing to go back to: the upsell opened the dialog straight on Go.
+ await expect(dialog.locator('[data-action="provider-connect-method"]')).toHaveText([
+ "OpenCode account",
+ "API key (service account)",
+ ])
+ // Nothing to go back to: the upsell opened the dialog straight on OpenCode.
await expect(dialog.getByRole("navigation").getByRole("button")).toHaveCount(0)
await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(368)
})
@@ -2196,18 +2212,19 @@ test("providers: Back from a Console connection without models returns to its si
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings
- .locator(".settings-provider-row", { hasText: "OpenCode Console" })
+ .locator(".settings-provider-row")
+ .filter({ has: page.locator(".settings-provider-name", { hasText: /^OpenCode$/ }) })
.getByRole("button", { name: "Connect", exact: true })
.click()
const dialog = connectDialog(page)
const popup = page.waitForEvent("popup")
- await dialog.getByRole("button", { name: "OpenCode Console account", exact: true }).click()
+ await dialog.getByRole("button", { name: "OpenCode account", exact: true }).click()
await popup
await expect(page.getByRole("dialog").getByText("OpenCode connected", { exact: true })).toBeVisible()
- await dialog.getByRole("navigation").getByRole("button", { name: "OpenCode Console", exact: true }).click()
+ await dialog.getByRole("navigation").getByRole("button", { name: "OpenCode", exact: true }).click()
await expect(dialog.locator('[data-action="provider-connect-method"]')).toHaveText([
- "OpenCode Console account",
+ "OpenCode account",
"API key (service account)",
])
})
@@ -2342,8 +2359,8 @@ test("providers: switching to a Zen API key does not wait for a Console workspac
integrations: () => [
{
id: "opencode",
- name: "OpenCode Console",
- methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
+ name: "OpenCode",
+ methods: [{ id: "device", type: "oauth", label: "OpenCode account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
@@ -2353,7 +2370,7 @@ test("providers: switching to a Zen API key does not wait for a Console workspac
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
- const trigger = settings.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
+ const trigger = settings.getByRole("button", { name: "Manage OpenCode accounts", exact: true })
await expect(trigger).toHaveText("Anomaly")
await trigger.click()
@@ -2364,7 +2381,7 @@ test("providers: switching to a Zen API key does not wait for a Console workspac
catalogReads.push(request.url())
})
await page.getByRole("menuitemradio", { name: "Zen key", exact: true }).click()
- await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
+ await expect(page.getByText("OpenCode account switched")).toBeVisible()
// One refresh after the switch; a Console workspace poll would keep reading the catalog.
expect(catalogReads).toHaveLength(1)
})
@@ -2399,8 +2416,8 @@ test("providers: adding a Console account keeps the Console row in place", async
integrations: () => [
{
id: "opencode",
- name: "OpenCode Console",
- methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
+ name: "OpenCode",
+ methods: [{ id: "device", type: "oauth", label: "OpenCode account" }],
connections: [
{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" },
...(state.authorized ? [{ type: "credential", id: "cred_clara", label: "Clara", method: "oauth" }] : []),
@@ -2421,10 +2438,11 @@ test("providers: adding a Console account keeps the Console row in place", async
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
- await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
+ const consoleRow = connected.locator(".settings-provider-console")
+ await expect(consoleRow.getByText("OpenCode", { exact: true })).toBeVisible()
await connected.evaluate((element) => {
new MutationObserver(() => {
- if (!element.textContent?.includes("OpenCode Console")) element.dataset.flashed = ""
+ if (!element.querySelector(".settings-provider-console")) element.dataset.flashed = ""
}).observe(element, { childList: true, subtree: true, characterData: true })
})
@@ -2434,9 +2452,11 @@ test("providers: adding a Console account keeps the Console row in place", async
const popup = page.waitForEvent("popup")
await dialog.getByRole("button", { name: "Add account", exact: true }).click()
await popup
- await expect(page.getByText("OpenCode Console connected", { exact: true })).toBeVisible()
+ await expect(
+ page.getByRole("region", { name: /^Notifications/ }).getByText("OpenCode connected", { exact: true }),
+ ).toBeVisible()
- await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
+ await expect(consoleRow.getByText("OpenCode", { exact: true })).toBeVisible()
await expect(connected).not.toHaveAttribute("data-flashed")
})
@@ -2476,8 +2496,8 @@ test("providers: switching Console accounts keeps the list until the new workspa
integrations: () => [
{
id: "opencode",
- name: "OpenCode Console",
- methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
+ name: "OpenCode",
+ methods: [{ id: "device", type: "oauth", label: "OpenCode account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
@@ -2489,7 +2509,7 @@ test("providers: switching Console accounts keeps the list until the new workspa
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
- const trigger = connected.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
+ const trigger = connected.getByRole("button", { name: "Manage OpenCode accounts", exact: true })
await expect(trigger).toHaveText("Clara")
await connected.evaluate((element) => {
new MutationObserver(() => {
@@ -2499,7 +2519,7 @@ test("providers: switching Console accounts keeps the list until the new workspa
await trigger.click()
await page.getByRole("menuitemradio", { name: "Anomaly", exact: true }).click()
- await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
+ await expect(page.getByText("OpenCode account switched")).toBeVisible()
await expect(trigger).toHaveText("Anomaly")
await expect(connected).not.toHaveAttribute("data-flashed")
})
@@ -2532,8 +2552,8 @@ test("models: a Console provider picked on Providers opens its collapsed group,
integrations: [
{
id: "opencode",
- name: "OpenCode Console",
- methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
+ name: "OpenCode",
+ methods: [{ id: "device", type: "oauth", label: "OpenCode account" }],
connections: [{ type: "credential", id: "cred_anomaly", label: "Anomaly", method: "oauth" }],
},
],
@@ -2541,7 +2561,7 @@ test("models: a Console provider picked on Providers opens its collapsed group,
const group = settings
.locator('[data-component="settings-models-console"]')
- .getByRole("button", { name: /^OpenCode Console/ })
+ .getByRole("button", { name: "OpenCode Anomaly", exact: true })
await settings.getByRole("tab", { name: "Models", exact: true }).click()
await group.click()
diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts
index b58082aa29c8..2b34c029a208 100644
--- a/packages/app/e2e/regression/side-panels.spec.ts
+++ b/packages/app/e2e/regression/side-panels.spec.ts
@@ -1,6 +1,7 @@
import { expect, test, type Page } from "@playwright/test"
-import { fileDiff, openSession } from "../utils/workspace"
-import { openReviewLauncher } from "../utils/side-panel"
+import { fileDiff, fileNode, openSession } from "../utils/workspace"
+import { openFileLauncher, openReviewLauncher, storedStrips } from "../utils/side-panel"
+import { expectSessionTitle } from "../utils/waits"
import { base64Encode } from "@opencode/util/encode"
test("review content stays aligned with the side region in both directions", async ({ page }) => {
@@ -306,6 +307,59 @@ test("a reopened side tab returns to where it closed", async ({ page }) => {
await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveAttribute("aria-selected", "true")
})
+// The layout stores the side tabs of 50 sessions. It ranked them only by when each was last on screen in this run, so
+// after a restart, or once enough other sessions were used, it forgot a session that was still open in a shell tab:
+// its file, review, terminal and browser tabs were gone when the person switched back to it.
+test("a session open in a shell tab keeps its side tabs when the layout forgets old sessions, at startup and after a scroll", async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1440, height: 900 })
+ const directory = "C:/OpenCode/KeepOpenStrip"
+ const key = (session: string) => `local\u0000${base64Encode(directory)}/${session}`
+ // Fifty-one sessions whose shell tabs are closed, oldest first, then the one open in a background shell tab.
+ const closed = Array.from({ length: 51 }, (_, index) => key(`ses_closed_${String(index).padStart(2, "0")}`))
+ const strip = { all: ["file://notes.md"], active: "file://notes.md" }
+
+ await openSession(page, {
+ name: "KeepOpenStrip",
+ sessions: [
+ { id: "ses_onscreen", title: "On screen" },
+ { id: "ses_background", title: "In the background" },
+ ],
+ fileList: () => [fileNode(directory, "long.txt")],
+ fileContent: (path) => ({ type: "text", content: path === "long.txt" ? Array.from({ length: 400 }, (_, index) => `line ${index + 1}`).join("\n") : `contents:${path}` }),
+ seed: {
+ panes: { ses_background: { review: true } },
+ storage: {
+ "opencode.global.dat:layout": {
+ sessionTabs: Object.fromEntries([...closed.map((item) => [item, strip]), [key("ses_background"), strip]]),
+ },
+ },
+ },
+ })
+
+ // Startup: 52 stored strips. The two oldest closed sessions go; the open one, stored last and not used yet, stays.
+ await expect.poll(() => storedStrips(page)).toEqual([...closed.slice(2), key("ses_background")])
+
+ // The person opens a file in the session on screen and scrolls it, which stores a 51st session and prunes again.
+ const panel = page.locator("#review-panel")
+ await page.getByRole("button", { name: "Toggle review" }).click()
+ await openFileLauncher(panel)
+ await panel.getByRole("treeitem", { name: "long.txt" }).click()
+ await expect(panel.getByRole("tab", { name: "long.txt", exact: true })).toHaveAttribute("aria-selected", "true")
+ const code = panel.locator("[data-scrollable]", { has: page.locator('[data-component="file"]') })
+ await expect.poll(() => code.evaluate((element) => element.scrollHeight - element.clientHeight)).toBeGreaterThan(0)
+ await code.hover()
+ await page.mouse.wheel(0, 2_000)
+ await expect.poll(() => storedStrips(page)).toEqual([...closed.slice(3), key("ses_background"), key("ses_onscreen")])
+
+ // Its side tab is there when the person switches to it.
+ await page.locator("[data-titlebar-tab-slot]", { hasText: "In the background" }).click()
+ await expectSessionTitle(page, "In the background")
+ await expect(panel.getByRole("tab", { name: "notes.md", exact: true })).toHaveAttribute("aria-selected", "true")
+ await expect(panel.getByText("contents:notes.md", { exact: true })).toBeVisible()
+})
+
async function expectTreeSentinel(page: Page) {
const tree = page.locator('#review-panel [data-component="file-tree-v2"]')
await expect(tree.getByRole("treeitem", { name: "action.yml" })).toBeVisible()
diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts
index 6b2134e98155..2e345aea9a3d 100644
--- a/packages/app/e2e/regression/tabs.spec.ts
+++ b/packages/app/e2e/regression/tabs.spec.ts
@@ -478,6 +478,24 @@ test("keyboard navigation and numbered shortcuts follow the visible tab order an
await expectPath(page, sessionHref(c.id))
})
+test("⌘⇧S archives the open session and moves to the next tab", async ({ page }) => {
+ await mockWorkspace(page, { name: "ArchiveShortcut", sessions: [a, b], seed: { tabs: [a.id, b.id] } })
+ await page.goto(sessionHref(a.id))
+ await expectSessionTitle(page, a.title)
+
+ const archive = page.waitForRequest(
+ (request) => request.method() === "PATCH" && new URL(request.url()).pathname === `/api/session/${a.id}`,
+ )
+
+ await page.getByRole("textbox", { name: "Prompt", exact: true }).click()
+ await page.keyboard.press("ControlOrMeta+Shift+s")
+ expect((await archive).postDataJSON()).toMatchObject({ archived: true })
+
+ await expectPath(page, sessionHref(b.id))
+ await expect(page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"])`)).toHaveCount(0)
+ await expect(page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)).toBeVisible()
+})
+
test("option arrows move to the previous or next tab, and with shift to the next unread one", async ({ page }) => {
await mockWorkspace(page, {
name: "Tabs",
@@ -2896,3 +2914,65 @@ test("tab groups reorder without color drift, collapse and auto-expand on naviga
await page.mouse.up()
await expect(manualGroup.locator("[data-titlebar-tab-slot]")).toHaveCount(2)
})
+
+test("closing the current tab in server groups selects the next visible row and keeps the group order", async ({
+ page,
+}) => {
+ const dirA = "C:/OpenCode/TabGroupsClose"
+ const dirB = "/srv/tab-groups-close"
+ const localOne = session({ id: "ses_tgc_local_1", directory: dirA, title: "Local first" })
+ const localTwo = session({ id: "ses_tgc_local_2", directory: dirA, title: "Local second" })
+ const remoteOne = session({ id: "ses_tgc_remote_1", directory: dirB, title: "Remote first" })
+
+ await mockServers(page, {
+ [SERVER]: {
+ hostname: "local",
+ directory: dirA,
+ project: project({ id: "proj_tgc_a", directory: dirA, name: "opencode" }),
+ provider: NO_PROVIDER,
+ sessions: [localOne, localTwo],
+ pageMessages: () => ({ items: [] }),
+ strictDirectory: true,
+ },
+ [REMOTE_SERVER]: {
+ hostname: "blade",
+ directory: dirB,
+ project: project({ id: "proj_tgc_b", directory: dirB, name: "blade-repo" }),
+ provider: NO_PROVIDER,
+ sessions: [remoteOne],
+ pageMessages: () => ({ items: [] }),
+ strictDirectory: true,
+ },
+ })
+
+ // The remote tab sits between the two local tabs in tab order, so it is the first local tab's neighbour there.
+ await seed(page, {
+ servers: [{ url: REMOTE_SERVER, name: "blade" }],
+ tabs: [localOne.id, { session: remoteOne.id, server: REMOTE_SERVER }, localTwo.id],
+ settings: {
+ appearance: { tabLayout: "vertical", sidebarOpen: true },
+ general: { tabGroups: true, sidebarOrganize: "list" },
+ },
+ })
+
+ await page.goto(sessionHref(localOne.id))
+ const sidebar = page.locator('[data-slot="vertical-tabs-sidebar"]')
+ const groups = sidebar.locator("[data-tab-group]")
+ const remoteHeader = sidebar.locator(`[data-tab-group-header][data-group-key="server:${REMOTE_SERVER}"]`)
+ // The collapsed header adds its tab count to the button's name.
+ const remoteToggle = remoteHeader.getByRole("button", { name: /^blade/ })
+ const slot = (href: string) => sidebar.locator(`[data-titlebar-tab-slot]:has(a[href="${href}"])`)
+
+ await expect(groups).toHaveCount(2)
+ await expect(groups.nth(0)).toHaveAttribute("data-group-key", `server:${SERVER}`)
+ await remoteToggle.click()
+ await expect(remoteToggle).toHaveAttribute("aria-expanded", "false")
+
+ await slot(sessionHref(localOne.id)).click({ button: "middle" })
+
+ await expect(slot(sessionHref(localOne.id))).toHaveCount(0)
+ await expect(page).toHaveURL(sessionHref(localTwo.id))
+ await expect(groups.nth(0)).toHaveAttribute("data-group-key", `server:${SERVER}`)
+ await expect(remoteToggle).toHaveAttribute("aria-expanded", "false")
+ await expect(slot(sessionHref(remoteOne.id, REMOTE_SERVER))).toHaveCount(0)
+})
diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts
index f1ae1869225e..8166b8bf0202 100644
--- a/packages/app/e2e/regression/timeline-geometry.spec.ts
+++ b/packages/app/e2e/regression/timeline-geometry.spec.ts
@@ -227,7 +227,7 @@ test("keeps a file diff anchored while it expands and collapses", async ({ page
const wrapper = page.locator(`[data-timeline-part-id="${id}"]`)
const diff = wrapper.locator('[data-component="apply-patch-file-diff"]')
const row = page.locator("[data-timeline-key]", { has: wrapper })
- const trigger = wrapper.getByRole("button")
+ const trigger = wrapper.locator('[data-slot="accordion-trigger"]')
const bottom = () =>
scroller.evaluate((element) => Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop))
diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts
index 89e671161c5f..6ebd8ecc31e0 100644
--- a/packages/app/e2e/regression/timeline-stream.spec.ts
+++ b/packages/app/e2e/regression/timeline-stream.spec.ts
@@ -3103,6 +3103,8 @@ test("opens an optional comment beside the quote action and skips it with Alt-cl
await chips.nth(0).hover()
await page.getByRole("button", { name: "Remove attachment" }).click()
await expect(chips).toHaveCount(0)
+ // Removing the last chip hands focus back to the editor a task later, and its caret would replace the next selection.
+ await expect(editor).toBeFocused()
// A slow tooltip names the action and its shortcut.
await select("The first sentence to quote.")
diff --git a/packages/app/e2e/utils/side-panel.ts b/packages/app/e2e/utils/side-panel.ts
index 745817e70435..77983bbef3a1 100644
--- a/packages/app/e2e/utils/side-panel.ts
+++ b/packages/app/e2e/utils/side-panel.ts
@@ -17,6 +17,15 @@ export async function openReviewLauncher(panel: Locator) {
await panel.getByRole("button", { name: /^Review/ }).click()
}
+/** The session keys whose side strips the stored layout holds, in stored order, once the app has saved them. */
+export function storedStrips(page: Page) {
+ return page.evaluate((): string[] => {
+ const layout: { sessionTabs?: Record } = JSON.parse(localStorage.getItem("opencode.global.dat:layout") ?? "{}")
+
+ return Object.keys(layout.sessionTabs ?? {})
+ })
+}
+
/** Storage that restores the Review tab, selected, in each session's side strip, as the app writes it. */
export function reviewTabs(directory: string, ...sessions: string[]) {
return {
diff --git a/packages/app/package.json b/packages/app/package.json
index cde7b14996a9..de9463a4f001 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencode/app",
- "version": "2.3.2",
+ "version": "2.4.0",
"description": "",
"type": "module",
"exports": {
diff --git a/packages/app/perf/README.md b/packages/app/perf/README.md
index 42999577788a..1ec2bbf6db2e 100644
--- a/packages/app/perf/README.md
+++ b/packages/app/perf/README.md
@@ -5,20 +5,22 @@ launches (A B, B A, …) at normal speed, decides one primary metric per case wi
cannot defend (a hidden window, a software GPU, a throttled CPU, a busy machine). The web cases run the production
build on the e2e mock server, so they need no backend.
-| File | Cases | Workload |
-| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
-| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. |
-| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · with Find open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. |
-| `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. |
-| `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home, scroll) | The stress fixture, paginated, from a fresh document every run. |
-| `home.bench.ts` | load home · update a session in the background | 500, 5,000 and 10,000 root sessions across 12 folders. |
-| `review.bench.ts` | open review · filter files · next file | 100 and 10,000 changed files of 100 lines each. |
-| `diff.bench.ts` | open a long diff · open a huge diff · return to a long diff | A 1,559-line diff, highlighted; a 15,599-line one, plain. |
-| `composer.bench.ts` | type in a large draft · move the cursor in it · recall a prompt from history | A 44,000-character saved draft; 100 prompts with screenshots. |
-| `docks.bench.ts` | open and close request docks | A permission dock and an MCP elicitation over a 20-turn session. |
-| `send.bench.ts` | send a prompt | Enter until the prompt request reaches the server, 20 turns. |
-| `question.bench.ts` | switch questions | The new question dock with its motion on: five questions. |
-| `desktop.bench.ts` | idle | The packaged desktop app, every process, doing nothing for 5 s. |
+| File | Cases | Workload |
+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
+| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · open a group of scripts · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. |
+| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · with Find open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. |
+| `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. |
+| `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home, scroll) | The stress fixture, paginated, from a fresh document every run. |
+| `home.bench.ts` | load home · update a session in the background | 500, 5,000 and 10,000 root sessions across 12 folders. |
+| `review.bench.ts` | open review · filter files · next file | 100 and 10,000 changed files of 100 lines each. |
+| `diff.bench.ts` | open a long diff · open a huge diff · return to a long diff | A 1,559-line diff, highlighted; a 15,599-line one, plain. |
+| `composer.bench.ts` | type in a large draft · move the cursor in it · recall a prompt from history | A 44,000-character saved draft; 100 prompts with screenshots. |
+| `model-picker.bench.ts` | open model picker · scroll model picker · select a model | 96 models from 19 providers in the desktop model picker. |
+| `docks.bench.ts` | open and close request docks | A permission dock and an MCP elicitation over a 20-turn session. |
+| `subagent-pill.bench.ts` | scroll pill static · scroll pill with live events | 20 long-running subagents in the background activity popover. |
+| `send.bench.ts` | send a prompt | Enter until the prompt request reaches the server, 20 turns. |
+| `question.bench.ts` | switch questions | The new question dock with its motion on: five questions. |
+| `desktop.bench.ts` | idle | The packaged desktop app, every process, doing nothing for 5 s. |
Every case decides `main.work` (renderer main-thread task time per run) unless it says otherwise: it is continuous,
while durations that end on a presented frame move in whole vsyncs. Durations, interaction latency, frames and the
diff --git a/packages/app/perf/fixtures/scripts.ts b/packages/app/perf/fixtures/scripts.ts
new file mode 100644
index 000000000000..8cd9921c1e2c
--- /dev/null
+++ b/packages/app/perf/fixtures/scripts.ts
@@ -0,0 +1,37 @@
+import type { SessionMessageAssistant } from "@opencode/client/promise"
+
+// How many calls each of 46 Code Mode scripts made in one turn of a real audit session: most made a few, six walked a
+// source tree file by file. 19,039 calls in all.
+const calls = [
+ 1, 3, 6965, 1, 1, 2, 1, 1, 3, 1, 1592, 4, 1, 377, 2, 1893, 2, 7, 2, 1, 1, 3, 3906, 3, 2004, 2, 1, 8, 1, 0, 2, 1, 1, 1,
+ 1, 2, 1, 4, 2, 86, 2, 1, 3, 2138, 3, 2,
+]
+
+/** The turn's scripts, completed, each listing the files it read through `Bun.file`. */
+export function scriptTools(): SessionMessageAssistant["content"] {
+ return calls.map((count, script) => ({
+ type: "tool",
+ id: `prt_script_${String(script).padStart(2, "0")}`,
+ name: "execute",
+ time: {
+ created: 1700000001000 + script * 1_000,
+ ran: 1700000001000 + script * 1_000,
+ completed: 1700000001500 + script * 1_000,
+ },
+ state: {
+ status: "completed",
+ input: { code: `const files = await Array.fromAsync(new Bun.Glob("**/*.ts").scan(root))\nreturn files.length` },
+ content: [{ type: "text", text: `${count} files` }],
+ metadata: {
+ toolCalls: Array.from({ length: count }, (_, call) => ({
+ tool: "Bun",
+ status: "completed",
+ input: {
+ method: "file",
+ path: `C:/OpenCode/TimelineStateRegression/packages/app/src/module-${script}-${call}.ts`,
+ },
+ })),
+ },
+ },
+ }))
+}
diff --git a/packages/app/perf/fixtures/timeline.ts b/packages/app/perf/fixtures/timeline.ts
index 55f4aa8802bf..d89362f28fb2 100644
--- a/packages/app/perf/fixtures/timeline.ts
+++ b/packages/app/perf/fixtures/timeline.ts
@@ -72,6 +72,8 @@ type TimelineOptions = {
vcsDiff?: unknown[]
/** Edits listed one per file and collapsed, each file opening on its own (by default they start open). */
collapsedEdits?: boolean
+ /** The app's default timeline detail (Compact), which folds a turn's calls into one group. */
+ compact?: boolean
/** The last assistant turn's tool parts, in place of its one small edit. */
tools?: SessionMessageAssistant["content"]
/** Events arrive from a real SSE endpoint (`source`); otherwise the mock's own stream stays idle. */
@@ -140,7 +142,9 @@ export async function mockTimelineSession(page: Page, options: TimelineOptions)
showReasoningSummaries: true,
timelineDetail: options.collapsedEdits
? { ...timelinePresets[2].value, edit: { placement: "separate", details: "collapsed" } }
- : undefined,
+ : options.compact
+ ? timelinePresets[2].value
+ : undefined,
})
return { path: `/server/${base64Encode(options.server)}/session/${sessionID}`, source }
diff --git a/packages/app/perf/model-picker.bench.ts b/packages/app/perf/model-picker.bench.ts
new file mode 100644
index 000000000000..b3a76e948043
--- /dev/null
+++ b/packages/app/perf/model-picker.bench.ts
@@ -0,0 +1,168 @@
+// Opening, scrolling and selecting in the desktop model picker with 96 models from 19 providers, at 1440×900.
+import { bench, web, type Case } from "@hona/strobe"
+import { draftHref } from "../e2e/utils/app"
+import { mockOpenCodeServer, type MockProviderCatalog } from "../e2e/utils/mock-server"
+import { fixture } from "../e2e/utils/session-fixture"
+import { installProjects } from "./fixtures/home"
+import { cached } from "./fixtures/mock"
+import { installTabs } from "./fixtures/tabs"
+
+const draftID = "draft_perf_model_picker"
+
+const composer = '[data-component="new-session"] [data-component="composer-editor"][contenteditable="true"]'
+
+const trigger = '[data-component="new-session"] [data-action="composer-model"]'
+
+const row = '[data-slot="search-list-row"]'
+
+const scroller = '[data-slot="search-list-scroll"]'
+
+// One large provider and a long tail: 96 models in all.
+const providers: ReadonlyArray<{ id: string; models: number }> = [
+ { id: "lorem", models: 47 },
+ { id: "ipsum", models: 9 },
+ { id: "dolor", models: 7 },
+ { id: "sit", models: 5 },
+ { id: "amet", models: 4 },
+ { id: "consectetur", models: 3 },
+ { id: "adipiscing", models: 3 },
+ { id: "elit", models: 3 },
+ { id: "sed", models: 2 },
+ { id: "eiusmod", models: 2 },
+ { id: "tempor", models: 2 },
+ { id: "incididunt", models: 2 },
+ { id: "labore", models: 1 },
+ { id: "dolore", models: 1 },
+ { id: "magna", models: 1 },
+ { id: "aliqua", models: 1 },
+ { id: "enim", models: 1 },
+ { id: "minim", models: 1 },
+ { id: "veniam", models: 1 },
+]
+
+const title = (id: string) => id[0].toUpperCase() + id.slice(1)
+
+// Every model has three variants, so each row's flyout lists them.
+function catalog(): MockProviderCatalog {
+ return {
+ all: providers.map((provider) => ({
+ id: provider.id,
+ name: title(provider.id),
+ models: Object.fromEntries(
+ Array.from({ length: provider.models }, (_, index) => {
+ const id = `${provider.id}-${index + 1}`
+
+ return [
+ id,
+ {
+ id,
+ name: `${title(provider.id)} ${index + 1}`,
+ cost: { input: 2, output: 10 },
+ limit: { context: 200_000, output: 32_000 },
+ variants: { low: {}, medium: {}, high: {} },
+ // A release date of 0 reads as none, so the picker lists every model, not only each family's newest.
+ time: { released: 0 },
+ },
+ ]
+ }),
+ ),
+ })),
+ connected: providers.map((provider) => provider.id),
+ default: { providerID: "lorem", modelID: "lorem-1" },
+ }
+}
+
+const metrics = ["run.duration", "interaction.p95", "main.style", "main.layout", "main.script"]
+
+type Setup = { opened: boolean }
+
+const cases = {
+ "open model picker": {
+ primary: "main.work",
+ metrics,
+ async run({ page }) {
+ await page.click(trigger, { until: [row, "frame"] })
+ await page.idle()
+ },
+ async reset({ page }) {
+ await page.press("Escape")
+ await page.idle()
+ },
+ },
+ "scroll model picker": {
+ primary: "main.work",
+ resetCheck: false,
+ metrics: ["run.duration", "main.style", "main.layout", "main.script", "frames.dropped"],
+ async run({ page }) {
+ await page.scroll(scroller, { by: 1600, speed: 2400 })
+ await page.idle()
+ },
+ async reset({ page }) {
+ await page.scroll(scroller, { by: -1600, speed: 4000 })
+ await page.idle()
+ },
+ },
+ "select a model": {
+ primary: "main.work",
+ resetCheck: false,
+ metrics,
+ async run({ page }) {
+ await page.click(`${row} index=3`, { until: "frame" })
+ await page.idle()
+ },
+ async reset({ page }) {
+ await page.click(trigger, { until: [row, "frame"] })
+ await page.idle()
+ },
+ },
+} satisfies Record>
+
+export default bench({
+ setupKey: ({ case: name }): Setup => ({
+ opened: name !== "open model picker",
+ }),
+
+ targets: {
+ web: web<{}, Setup>({
+ expect: { title: "OpenCode" },
+ viewport: { width: 1440, height: 900 },
+ async prepare(ctx) {
+ const server = new URL(ctx.url).origin
+ const page = cached(ctx)
+ await mockOpenCodeServer(page, {
+ server,
+ sessions: fixture.sessions,
+ provider: catalog(),
+ directory: fixture.directory,
+ project: fixture.project,
+ pageMessages: () => ({ items: [] }),
+ })
+ await installProjects(page, [fixture.directory])
+ await installTabs(page, {
+ server,
+ directory: fixture.directory,
+ sessions: [],
+ draft: draftID,
+ })
+
+ return { first: draftHref(draftID) }
+ },
+ url: ({ prepared }) => prepared.first,
+ }),
+ },
+
+ async setup({ setupKey, page }) {
+ await page.waitFor(composer, { timeout: 60_000 })
+ await page.waitFor(trigger, { timeout: 60_000 })
+
+ if (setupKey.opened) {
+ await page.click(trigger, { until: [row, "frame"] })
+ // Verify all 96 models actually rendered in the picker.
+ await page.waitFor(`${row} index=95`, { timeout: 10_000 })
+ }
+
+ await page.idle()
+ },
+
+ cases,
+})
diff --git a/packages/app/perf/subagent-pill.bench.ts b/packages/app/perf/subagent-pill.bench.ts
new file mode 100644
index 000000000000..b894e75a7edf
--- /dev/null
+++ b/packages/app/perf/subagent-pill.bench.ts
@@ -0,0 +1,348 @@
+// Scrolling the background activity menu with 20 long-running subagents open, both quiet and while the parent
+// session streams tool progress and child sessions update in the background.
+import { bench, web } from "@hona/strobe"
+import { base64Encode } from "@opencode/util/encode"
+import type { OpenCodeEvent, SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise"
+import { mockOpenCodeServer } from "../e2e/utils/mock-server"
+import { cached } from "./fixtures/mock"
+import { eventSource } from "./fixtures/events"
+import { composer, timeline } from "./fixtures/timeline"
+
+const directory = "C:/OpenCode/SubagentPillPerf"
+
+const projectID = "proj_subagent_pill_perf"
+
+const parentID = "ses_subagent_pill_parent"
+
+const assistantMessageID = "msg_assistant_subagents"
+
+const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
+
+const chip = '[data-slot="session-activity-chip"]'
+
+const panel = '[data-slot="session-activity-panel"]'
+
+const viewport = '[data-slot="session-activity-panel"] [data-slot="menu-scroll-viewport"]'
+
+const SUBAGENT_COUNT = 20
+
+const EXTRA_SESSIONS = 250
+
+const descriptions = [
+ "WS-3: timeline, code wrap, measurement stability and resize observers",
+ "WS-8: focus rings, rescue, tooltips and keyboard navigation",
+ "WS-1 (fresh): the browser, bridge, tab strip and pane layout",
+ "BROWSER-TOOLS (fresh): the snapshot, eval and click actions",
+ "ENGINE-DELIVERY: source.rs streaming frames and backpressure",
+ "SCREENS-B: Shift source queue ordering and inbox reconciliation",
+ "UPDATER: in-app updates 1:1 parity with desktop beta channel",
+ "GESTURES: web-default interactions and trackpad scroll inertia",
+ "AUDITOR: verify today's merges against regression benchmarks",
+ "DEV-KEEPER-b: keep dev green across windows and linux shards",
+]
+
+// Ages from 40s up to 63h 46m so rows span seconds, minutes and hours simultaneously.
+const agesMs = [
+ 63 * 3600_000 + 46 * 60_000,
+ 61 * 3600_000 + 17 * 60_000,
+ 60 * 3600_000 + 45 * 60_000,
+ 59 * 3600_000 + 8 * 60_000,
+ 45 * 3600_000 + 31 * 60_000,
+ 40_000,
+ 44 * 3600_000 + 24 * 60_000,
+ 22 * 3600_000 + 7 * 60_000,
+ 19 * 3600_000 + 47 * 60_000,
+ 22 * 60_000 + 9_000,
+ 15 * 3600_000 + 12 * 60_000,
+ 11 * 3600_000 + 3 * 60_000,
+ 9 * 3600_000 + 55 * 60_000,
+ 7 * 3600_000 + 18 * 60_000,
+ 5 * 3600_000 + 42 * 60_000,
+ 3 * 3600_000 + 11 * 60_000,
+ 2 * 3600_000 + 5 * 60_000,
+ 48 * 60_000 + 33_000,
+ 14 * 60_000 + 52_000,
+ 3 * 60_000 + 17_000,
+]
+
+let seq = 0
+
+export default bench({
+ targets: {
+ web: web({
+ expect: { title: "OpenCode" },
+ viewport: { width: 1366, height: 768 },
+ prepare: async (ctx) => {
+ const now = Date.now()
+ const server = new URL(ctx.url).origin
+ const page = cached(ctx)
+
+ const children = Array.from({ length: SUBAGENT_COUNT }, (_, i) => {
+ const started = now - agesMs[i % agesMs.length]!
+
+ return {
+ id: `ses_subagent_child_${String(i).padStart(2, "0")}`,
+ slug: `subagent-${i}`,
+ projectID,
+ parentID,
+ directory,
+ title: `${descriptions[i % descriptions.length]} (@general subagent)`,
+ agent: "general",
+ version: "dev",
+ time: { created: started, updated: now - i * 1000 },
+ }
+ })
+
+ const extra = Array.from({ length: EXTRA_SESSIONS }, (_, i) => ({
+ id: `ses_extra_${String(i).padStart(4, "0")}`,
+ slug: `extra-${i}`,
+ projectID,
+ directory,
+ title: `Historical session ${i}`,
+ version: "dev",
+ time: { created: now - (i + 100) * 60_000, updated: now - (i + 100) * 60_000 },
+ }))
+
+ const parentSession = {
+ id: parentID,
+ slug: "subagent-pill-perf",
+ projectID,
+ directory,
+ title: "Orchestrate 20 parallel subagents",
+ version: "dev",
+ time: { created: now - 70 * 3600_000, updated: now },
+ }
+
+ const tools: SessionMessageAssistantTool[] = children.map((child, i) => ({
+ type: "tool",
+ id: `prt_subagent_${i}`,
+ name: "subagent",
+ time: { created: child.time.created, ran: child.time.created, completed: child.time.created + 100 },
+ state: {
+ status: "completed",
+ input: {
+ agent: "general",
+ description: descriptions[i % descriptions.length]!,
+ prompt: descriptions[i % descriptions.length]!,
+ },
+ content: [{ type: "text", text: "Subagent started in background." }],
+ metadata: { sessionID: child.id, status: "running" },
+ },
+ }))
+
+ const history: SessionMessageInfo[] = Array.from({ length: 40 }, (_, i): SessionMessageInfo[] => [
+ {
+ id: `msg_hist_${String(i).padStart(3, "0")}_u`,
+ type: "user",
+ time: { created: now - (50 - i) * 60_000 },
+ text: `Check status of batch ${i} and launch follow-up work.`,
+ },
+ {
+ id: `msg_hist_${String(i).padStart(3, "0")}_a`,
+ type: "assistant",
+ time: { created: now - (50 - i) * 60_000 + 500, completed: now - (50 - i) * 60_000 + 2000 },
+ model: { id: model.modelID, providerID: model.providerID, variant: model.variant },
+ agent: "build",
+ cost: 0.02,
+ tokens: { input: 200, output: 400, reasoning: 0, cache: { read: 0, write: 0 } },
+ finish: "stop",
+ content: [{ type: "text", text: `Batch ${i} is underway.` }],
+ },
+ ]).flat()
+
+ const messages: SessionMessageInfo[] = [
+ ...history,
+ {
+ id: "msg_user_launch",
+ type: "user",
+ time: { created: now - 65 * 3600_000 },
+ text: "Launch all 20 workstreams in parallel.",
+ },
+ {
+ id: assistantMessageID,
+ type: "assistant",
+ time: { created: now - 64 * 3600_000 },
+ model: { id: model.modelID, providerID: model.providerID, variant: model.variant },
+ agent: "build",
+ cost: 0.5,
+ tokens: { input: 1000, output: 2000, reasoning: 500, cache: { read: 0, write: 0 } },
+ content: [
+ { type: "reasoning", text: "Coordinating 20 parallel subagents...", time: { created: now - 30_000 } },
+ ...tools,
+ ],
+ },
+ ]
+
+ const sessionStatus = Object.fromEntries([
+ [parentID, { type: "busy" }],
+ ...children.map((c) => [c.id, { type: "busy" }]),
+ ])
+
+ const source = await eventSource(page, server)
+
+ await mockOpenCodeServer(page, {
+ server,
+ directory,
+ project: {
+ id: projectID,
+ worktree: directory,
+ vcs: "git",
+ name: "subagent-pill-perf",
+ time: { created: now - 70 * 3600_000, updated: now },
+ sandboxes: [],
+ },
+ provider: {
+ all: [
+ {
+ id: "opencode",
+ name: "OpenCode",
+ models: {
+ "claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", limit: { context: 200_000 } },
+ },
+ },
+ ],
+ connected: ["opencode"],
+ default: { providerID: "opencode", modelID: "claude-opus-4-6" },
+ },
+ sessions: [parentSession, ...children, ...extra],
+ sessionStatus,
+ pageMessages: () => ({ items: messages }),
+ })
+
+ return {
+ path: `/server/${base64Encode(server)}/session/${parentID}`,
+ source,
+ childIDs: children.map((c) => c.id),
+ }
+ },
+ url: ({ prepared }) => prepared.path,
+ }),
+ },
+
+ async setup({ page }) {
+ await page.waitFor(timeline, { timeout: 60_000 })
+ await page.waitFor(composer)
+ await page.waitFor(chip, { timeout: 30_000 })
+ await page.click(chip, { until: panel })
+ await page.waitFor(viewport)
+ await page.idle()
+ },
+
+ teardown: ({ prepared }) => prepared.source.stop(),
+
+ cases: {
+ "scroll pill static": {
+ primary: "main.work",
+ metrics: [
+ "main.script",
+ "main.style",
+ "main.layout",
+ "main.paint",
+ "style.count",
+ "frames.dropped.pct",
+ "frames.interval.p95",
+ "frames.renderer.p95",
+ "frames.viz.p95",
+ ],
+ async run({ page, phase }) {
+ await phase("down1", () => page.scroll(viewport, { by: 360, speed: 300 }))
+ await phase("up1", () => page.scroll(viewport, { by: -360, speed: 300 }))
+ await phase("down2", () => page.scroll(viewport, { by: 360, speed: 300 }))
+ await phase("up2", () => page.scroll(viewport, { by: -360, speed: 300 }))
+ },
+ reset: ({ page }) => page.idle(),
+ },
+
+ "scroll pill with live events": {
+ primary: "main.work",
+ metrics: [
+ "main.script",
+ "main.style",
+ "main.layout",
+ "main.paint",
+ "style.count",
+ "frames.dropped.pct",
+ "frames.interval.p95",
+ "frames.renderer.p95",
+ "frames.viz.p95",
+ ],
+ async run({ page, phase, prepared }) {
+ // Production-shaped traffic while scrolling: the parent session runs tool calls (which refreshes history()
+ // in createSessionBackground) and background subagents tick executions (which re-sorts session.list()).
+ let tick = 0
+
+ const timer = setInterval(() => {
+ tick++
+ const toolID = `prt_live_read_${tick}`
+ const childID = prepared.childIDs[tick % prepared.childIDs.length]!
+ const created = Date.now()
+
+ const events: OpenCodeEvent[] = [
+ {
+ id: `evt_live_${++seq}`,
+ created,
+ location: { directory },
+ durable: { aggregateID: parentID, seq, version: 1 },
+ type: "session.tool.input.started",
+ data: {
+ sessionID: parentID,
+ assistantMessageID,
+ id: toolID,
+ name: "read",
+ },
+ } satisfies Extract,
+ {
+ id: `evt_live_${++seq}`,
+ created: created + 1,
+ location: { directory },
+ durable: { aggregateID: parentID, seq, version: 1 },
+ type: "session.tool.called",
+ data: {
+ sessionID: parentID,
+ assistantMessageID,
+ id: toolID,
+ input: { path: `src/check-${tick}.ts` },
+ executed: true,
+ },
+ } satisfies Extract,
+ {
+ id: `evt_live_${++seq}`,
+ created: created + 2,
+ location: { directory },
+ durable: { aggregateID: parentID, seq, version: 2 },
+ type: "session.tool.success",
+ data: {
+ sessionID: parentID,
+ assistantMessageID,
+ id: toolID,
+ content: [{ type: "text", text: "ok" }],
+ metadata: {},
+ executed: true,
+ },
+ } satisfies Extract,
+ {
+ id: `evt_live_${++seq}`,
+ created: created + 3,
+ location: { directory },
+ durable: { aggregateID: childID, seq, version: 1 },
+ type: "session.execution.started",
+ data: { sessionID: childID },
+ } satisfies Extract,
+ ]
+
+ prepared.source.send(events)
+ }, 250)
+
+ try {
+ await phase("down1", () => page.scroll(viewport, { by: 360, speed: 300 }))
+ await phase("up1", () => page.scroll(viewport, { by: -360, speed: 300 }))
+ await phase("down2", () => page.scroll(viewport, { by: 360, speed: 300 }))
+ await phase("up2", () => page.scroll(viewport, { by: -360, speed: 300 }))
+ } finally {
+ clearInterval(timer)
+ }
+ },
+ reset: ({ page }) => page.idle(),
+ },
+ },
+})
diff --git a/packages/app/perf/timeline.bench.ts b/packages/app/perf/timeline.bench.ts
index ee71ef6ca2f2..fff32f5e632d 100644
--- a/packages/app/perf/timeline.bench.ts
+++ b/packages/app/perf/timeline.bench.ts
@@ -1,9 +1,11 @@
// One long session (120 turns of markdown, code fences, tool calls and diffs) at normal speed.
import { bench, web } from "@hona/strobe"
+import { Match } from "effect"
import { editTools, reviewDiffs } from "./fixtures/diffs"
import { dragDivider, measureDivider, type Divider } from "./fixtures/drag"
import { cached } from "./fixtures/mock"
import { openReview } from "./fixtures/review"
+import { scriptTools } from "./fixtures/scripts"
import { composer, mockTimelineSession, oldestPrompt, timeline } from "./fixtures/timeline"
const find = '[data-component="timeline-search-bar"] input'
@@ -17,6 +19,14 @@ const diff = '[data-component="apply-patch-file-diff"] diffs-container >>> [data
const drag = "drag the review's edge"
+const scripts = "open a group of scripts"
+
+// The turn's one group of scripts, and the calls its scripts list once open.
+const group =
+ '[data-component="collapsed-tool-group"] > [data-component="collapsible"] > [data-slot="collapsible-trigger"]'
+
+const groupList = '[data-component="collapsed-tool-group"] [data-component="execute-tool-calls"]'
+
// The divider between the session and the side panel, read once the review is open. The session panel keeps at least
// 400px, the side panel 320px and the 8px gap.
const handle = '[data-slot="session-chat-panel"] > div > [data-component="resize-handle"]'
@@ -24,9 +34,16 @@ const handle = '[data-slot="session-chat-panel"] > div > [data-component="resize
let divider: Divider | undefined
export default bench({
- // The session a case's launch loads: the edits alone, the history beside the review, or the history. Cases with the
- // same one share a launch.
- setupKey: (ctx) => (ctx.case === "expand an edit" ? "edits" : ctx.case === drag ? "review" : "history"),
+ // The session a case's launch loads: the edits alone, the scripts alone, the history beside the review, or the history.
+ // Cases with the same one share a launch.
+ setupKey: (ctx) =>
+ ctx.case === "expand an edit"
+ ? "edits"
+ : ctx.case === scripts
+ ? "scripts"
+ : ctx.case === drag
+ ? "review"
+ : "history",
targets: {
web: web({
@@ -36,9 +53,14 @@ export default bench({
mockTimelineSession(cached(ctx), {
server: new URL(ctx.url).origin,
// The edits alone, so the case measures the diff, not the history around it.
- historyTurns: ctx.setupKey === "edits" ? 0 : 120,
+ historyTurns: ctx.setupKey === "edits" || ctx.setupKey === "scripts" ? 0 : 120,
collapsedEdits: ctx.setupKey === "edits",
- tools: ctx.setupKey === "edits" ? await editTools() : undefined,
+ compact: ctx.setupKey === "scripts",
+ tools: await Match.value(ctx.setupKey).pipe(
+ Match.when("edits", () => editTools()),
+ Match.when("scripts", async () => scriptTools()),
+ Match.orElse(async () => undefined),
+ ),
vcsDiff: ctx.setupKey === "review" ? reviewDiffs() : undefined,
}),
url: ({ prepared }) => prepared.path,
@@ -116,6 +138,21 @@ export default bench({
},
},
+ // 46 Code Mode scripts of one turn folded into one group, six of which read a source tree file by file: 19,039 calls
+ // in all. Opening the group opens each script, as the default timeline detail does.
+ [scripts]: {
+ primary: "main.work",
+ metrics: ["interaction.p50", "run.duration", "main.style", "main.layout", "main.script"],
+ async run({ page }) {
+ await page.click(group, { until: groupList })
+ await page.idle()
+ },
+ async reset({ page }) {
+ await page.click(group)
+ await page.idle()
+ },
+ },
+
// The divider beside the review (72 changed files) held for five seconds and dragged as a hand does, a pointer
// move every display frame: a slow stretch toward the session, jiggles, a fast throw toward the review and a slow
// pull back (fixtures/drag.ts). The timeline narrows and widens on every frame, so the rows in view rewrap; each
diff --git a/packages/app/src/app.tsx b/packages/app/src/app.tsx
index 369ec173acec..f3b272d7b188 100644
--- a/packages/app/src/app.tsx
+++ b/packages/app/src/app.tsx
@@ -21,6 +21,7 @@ import {
import { Dynamic } from "solid-js/web"
import { CommandProvider } from "@/shell/commands/command"
import { DesktopCommands } from "@/shell/commands/desktop"
+import { KeySequenceHint } from "@/shell/commands/key-sequence"
import { ProjectIconsProvider } from "@/shell/layout/project-icons"
import { GlobalProvider } from "@/runtime/server/runtime"
import { LanguageProvider, UiI18nBridge, type Locale } from "@/runtime/i18n/language"
@@ -117,6 +118,7 @@ export function AppInterface(props: {
{rootProps.children}
+
diff --git a/packages/app/src/components-lab/focus-visibility.stories.tsx b/packages/app/src/components-lab/focus-visibility.stories.tsx
index 099d4ee7a52c..a6545aaa8781 100644
--- a/packages/app/src/components-lab/focus-visibility.stories.tsx
+++ b/packages/app/src/components-lab/focus-visibility.stories.tsx
@@ -36,7 +36,6 @@ import { Tabs } from "@opencode/ui/tabs"
import { TextInput } from "@opencode/ui/text-input"
import { createEffect, createSignal, createUniqueId, For, onCleanup, onMount, Show, type JSX } from "solid-js"
import { createTabStripScroll } from "@/runtime/plugin/tab-strip-scroll"
-import { createFieldFocus } from "@opencode/ui/context/field-focus"
import { createOverlayFocus } from "@opencode/ui/context/overlay-focus"
import { installFocusRescue } from "@opencode/ui/context/focus-rescue"
import { useDialog } from "@opencode/ui/context/dialog"
@@ -248,16 +247,6 @@ const surfaces: Surface[] = [
),
},
- {
- name: "Composer editor: caret is the only focus cue",
- failure: "Invisible",
- target: '[data-component="composer-editor"]',
- keys: "Focus the preceding button, then press Tab into the prompt. Click inside the prompt to see the ring go away.",
- sizing: "The editor sits inside a masked scroll viewport.",
- source: "app/src/composer/editor/editor.css, ui/src/context/field-focus.tsx, context/dialog.tsx",
- fix: "Draw an inset ring on focus entry except for click-to-type and session autofocus. Returning from a dialog restores the previous ring state.",
- render: (forced) => ,
- },
],
also: [],
},
@@ -692,16 +681,6 @@ const surfaces: Surface[] = [
),
},
- {
- name: "Search sessions: Tab shows only a caret",
- failure: "Invisible",
- target: "input",
- keys: "Focus the preceding button and Tab into Search sessions. Click the field to clear the ring.",
- sizing: "The field spans the Home results column. The ring belongs on the field, not just its editable text.",
- source: "app/src/home/sessions/view.tsx, view.css, ui/src/context/field-focus.tsx",
- fix: "Tab, Find and other non-pointer focus entry draw the shared outset ring around the field. Click-to-type keeps the field background and caret without the ring.",
- render: (forced) => ,
- },
{
name: "Project row: focus looks like selection",
failure: "Inconsistent",
@@ -1658,7 +1637,7 @@ const surfaces: Surface[] = [
],
also: [
"Reviewed, left as is: the Home browse dialog's fallback focus (home/projects/browse.tsx) runs only when the opener has gone; the mobile panel drawer's Back and the location picker's Choose return follow the key or click that closed them.",
- "The workspace selector (new-session/workspace/selector.tsx) returns focus to the composer, whose field ring follows field-focus.tsx.",
+ "The workspace selector (new-session/workspace/selector.tsx) returns focus to the composer.",
],
},
{
@@ -2224,21 +2203,6 @@ function CaseCard(props: { case: Case; number: number; forced: boolean; locator:
)
}
-function createPreviewFieldFocus(forced: () => boolean) {
- const focus = createFieldFocus()
- const [entered, setEntered] = createSignal(false)
-
- return {
- visible: () => focus.visible() || (forced() && !entered()) || undefined,
- enter: (element: HTMLElement) => {
- setEntered(true)
- focus.enter(element)
- },
- pointer: focus.pointer,
- leave: focus.leave,
- }
-}
-
function SearchHighlightExample(props: { kind: "home-session-search-row" | "palette-menu-row" | "search-list-row" }) {
const [active, setActive] = createSignal(0)
@@ -2339,61 +2303,6 @@ function TreeFocusExample() {
)
}
-function HomeSearchFocusExample(props: { forced: boolean }) {
- const focus = createPreviewFieldFocus(() => props.forced)
-
- return (
-
diff --git a/packages/app/src/session/session-identity-header.tsx b/packages/app/src/session/session-identity-header.tsx
index 0a41ed6536ff..393c466d1c62 100644
--- a/packages/app/src/session/session-identity-header.tsx
+++ b/packages/app/src/session/session-identity-header.tsx
@@ -231,7 +231,7 @@ export function SessionLocation(props: {
open(props.sessionID, ancestor.id)}
>
{ancestor.title}
@@ -600,7 +600,11 @@ export function SessionIdentityHeader(props: { sessionID: string; session?: Sess
})
const directory = createMemo(
- () => props.session?.location.directory ?? pending()?.draft.directory ?? info()?.directory,
+ () =>
+ props.session?.location.directory ??
+ pending()?.view().directory ??
+ pending()?.draft.directory ??
+ info()?.directory,
)
const title = createMemo(() =>
diff --git a/packages/app/src/session/timeline/quote.stories.tsx b/packages/app/src/session/timeline/quote.stories.tsx
new file mode 100644
index 000000000000..c5df2a9b4c5c
--- /dev/null
+++ b/packages/app/src/session/timeline/quote.stories.tsx
@@ -0,0 +1,88 @@
+import { createSignal, onMount } from "solid-js"
+import { createStore } from "solid-js/store"
+import { TimelineQuote } from "./quote"
+
+const docs = `### Overview
+The toolbar over text selected in the session timeline. **Quote** attaches the selection to the composer and opens its comment editor (see Composer/QuoteComment); Alt+click attaches it without opening the editor.
+
+A selection longer than a quote can carry shows **Selection too long** and disables Quote.
+`
+
+export default {
+ title: "Session/TimelineQuote",
+ id: "session-timeline-quote",
+ parameters: { docs: { description: { component: docs } } },
+}
+
+const base = { truncated: false }
+
+function measure(passage: HTMLElement, selected: HTMLElement) {
+ const bounds = passage.getBoundingClientRect()
+
+ const extent = selected.getBoundingClientRect()
+
+ return {
+ text: selected.textContent ?? "",
+ bounds: { top: bounds.top, bottom: bounds.bottom, left: bounds.left, right: bounds.right },
+ extent: {
+ top: extent.top,
+ bottom: extent.bottom,
+ left: extent.left,
+ right: extent.right,
+ short: true,
+ backward: false,
+ },
+ }
+}
+
+export const Toolbar = {
+ args: base,
+ render: (args: typeof base) => {
+ const [view, setView] = createSignal>()
+
+ const [result, setResult] = createSignal("")
+
+ const [elements, setElements] = createStore<{ passage?: HTMLElement; selected?: HTMLElement }>({})
+
+ onMount(() => {
+ if (!elements.passage || !elements.selected) return
+ // A real selection, as the timeline shows it under the toolbar.
+ const range = document.createRange()
+
+ range.selectNodeContents(elements.selected)
+ window.getSelection()?.removeAllRanges()
+ window.getSelection()?.addRange(range)
+ setView(measure(elements.passage, elements.selected))
+ })
+
+ return (
+
+
setElements("passage", element)}
+ class="w-[480px] py-16 text-[14px] leading-[var(--line-height-base)] text-v2-text-text-base"
+ >
+ The composer clears once the prompt is in flight.{" "}
+ setElements("selected", element)}>
+ A failed send restores the draft, unless the user typed something new meanwhile.
+ {" "}
+ Queued prompts appear in the queue on admission.
+