diff --git a/.github/actions/prefetch-ghostty/action.yml b/.github/actions/prefetch-ghostty/action.yml new file mode 100644 index 000000000000..cfa1419a7914 --- /dev/null +++ b/.github/actions/prefetch-ghostty/action.yml @@ -0,0 +1,40 @@ +name: Prefetch Ghostty dependencies +description: Prepare the pinned source and Zig packages for process-daemon's native build +runs: + using: composite + steps: + - name: Check out pinned Ghostty source + id: pins + shell: bash + env: + GHOSTTY_SOURCE_DIR: ${{ runner.temp }}/ghostty + ZIG_GLOBAL_CACHE_DIR: ${{ github.workspace }}/.zig-cache + run: | + revision=$(git show HEAD:packages/process-daemon/ghostty-revision) + git init --quiet "$GHOSTTY_SOURCE_DIR" + git -C "$GHOSTTY_SOURCE_DIR" fetch --depth=1 https://github.com/ghostty-org/ghostty.git "$revision" + git -C "$GHOSTTY_SOURCE_DIR" -c core.longpaths=true checkout --detach "$revision" + echo "revision=$revision" >> "$GITHUB_OUTPUT" + echo "zig=$(zig version)" >> "$GITHUB_OUTPUT" + echo "GHOSTTY_SOURCE_DIR=$GHOSTTY_SOURCE_DIR" >> "$GITHUB_ENV" + echo "ZIG_GLOBAL_CACHE_DIR=$ZIG_GLOBAL_CACHE_DIR" >> "$GITHUB_ENV" + + # Zig 0.16 stores portable, content-addressed source tarballs in p/. + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: .zig-cache/p + key: ghostty-packages-${{ steps.pins.outputs.zig }}-${{ steps.pins.outputs.revision }} + enableCrossOsArchive: true + + - name: Fetch Zig packages + shell: bash + working-directory: ${{ env.GHOSTTY_SOURCE_DIR }} + run: | + for attempt in 1 2 3 4; do + echo "zig build --fetch=all (attempt $attempt/4)" + if zig build --fetch=all; then exit 0; fi + if [[ $attempt == 4 ]]; then exit 1; fi + delay=$((5 * 2 ** (attempt - 1))) + echo "Retrying in ${delay}s" + sleep "$delay" + done diff --git a/.oxlintrc.json b/.oxlintrc.json index 9a5df86606e5..0ad3ae0a5cc8 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -23,6 +23,40 @@ ] }, "overrides": [ + { + "files": ["packages/ai/src/**"], + "rules": { + "no-restricted-globals": [ + "error", + { + "name": "Reflect", + "message": "Use typed property access or direct invocation. Suppress this rule only for genuine reflection." + }, + { + "name": "fetch", + "message": "Send HTTP through RequestExecutor, which applies executor-wide and scoped middleware (HTTP hooks). A request sent any other way skips them." + } + ], + "no-restricted-imports": [ + "error", + { + "paths": [ + { + "name": "effect/http", + "importNames": ["HttpClient", "FetchHttpClient"], + "message": "Send HTTP through RequestExecutor, which applies executor-wide and scoped middleware (HTTP hooks). Only route/executor.ts holds the HTTP client." + } + ] + } + ] + } + }, + { + "files": ["packages/ai/src/route/executor.ts"], + "rules": { + "no-restricted-imports": "off" + } + }, { "files": [ "packages/app/**", diff --git a/AGENTS.md b/AGENTS.md index 472527f04b54..9a68154d205e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -239,8 +239,8 @@ const table = sqliteTable("session", { - When you open a PR, decide whether the change needs a flag: new user-visible behavior, risky core changes, and anything not ready to release get one; fixes, refactors, docs and tests do not. - Gate risky behavior, or behavior that lands over several PRs, with a key and a description in `packages/schema/src/config/flag.ts`, and read it with `Flag.enabled("")` from `@opencode/core/flag`. -- Flags are on in local and dev builds and off in releases; `experimental.` in config and `OPENCODE_FLAGS="key,-other"` override that. -- Say in the PR body which flag guards the change. To try every flag at once, use `OPENCODE_FLAGS=all` or `experimental.all_flags: true`; a `-` opt-out or `experimental.: false` still wins, and neither `all` nor `all_flags` is a flag key. +- Flags default to on in local and dev builds and off in releases, except `optInOnly` flags (such as `full_codemode`), which require an explicit `OPENCODE_FLAGS=` or `experimental.: true` in every build. +- Say in the PR body which flag guards the change. The reserved switches `OPENCODE_FLAGS=all` and `experimental.all_flags: true` skip opt-in-only flags; use `all,-` or `experimental.: false` to opt out within the respective source. - Ship a feature by deleting its flag and the checks that read it. ## Testing diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b1bb811f3ff..8ee89cfef99b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,149 @@ Release notes for OpenCode V2, newest first. +## v2.3.1-shuv.1 — 2026-11-17 + +Sync upstream v2.3.1 (`c769de8300`), 127 commits after the #497 pin `0fad04b3d5`. + +### Google AI Pro / Antigravity + +- Adds Gemini 4 Carbon (High, Medium, Low) and Gemini 4 Hydrogen (XHigh, High, Medium, Low) to the bundled Antigravity plugin, alongside Gemini 4 Argon ([#501](https://github.com/shuv1337/shuvcode/pull/501)). Accounts whose plan does not include a model keep it hidden. + +### Fork notes on upstream changes + +- Permission prompts from subagents still collect on the root session, and a subagent session shows "Parent is waiting for you" until they are answered ([#429](https://github.com/shuv1337/shuvcode/pull/429)). Upstream's change to show them in the subagent's own session is not adopted. Rejecting a request now also rejects only the other pending requests from the same step, as upstream does. +- Upstream's string `search("…")` shorthand in Code Mode replaces the fork's equivalent patch. +- Upstream's new Claude Agent translations are dropped with the rest of that hidden provider's strings. +- Retains Shuvcode identity, npm-only updates and guarded publishing, the hidden Claude Agent SDK provider, durable subagent recovery, tool-activity leases and rich failures. +- Upstream release notes for v2.3.1 follow verbatim; earlier fork notes remain intact. + +## v2.3.1 — 2026-11-17 + +### Highlights + +- **Timed-Out Shell Commands Keep Running**: A shell command still running when its timeout expires now moves to the background instead of being killed, so long builds and test runs finish and report back. A foreground `timeout: 0` now means the default 120 seconds. ([#63699](https://github.com/anomalyco/opencode/pull/63699)) +- **Compaction Without the Wait**: As a session nears automatic compaction, the summary is now written in the background, so your next prompt doesn't pause for it. Set `compaction.background: false` to turn it off; a background summary that ends up unused still costs tokens. ([#64290](https://github.com/anomalyco/opencode/pull/64290)) +- **GPT 6.2 with ChatGPT Sign-In**: GPT 6.2 Sol and GPT 6.2 Astra, plus their fast variants, now show up in the model picker when you sign in with ChatGPT. ([#64508](https://github.com/anomalyco/opencode/pull/64508)) +- **Update Plugins from Settings**: Open **Settings › Extensions**, click **Check for updates**, then **Update** on any plugin with a new version. ([#64511](https://github.com/anomalyco/opencode/pull/64511)) +- **Comment on Selected Code**: Selecting code in diff and file viewers now just selects it, so you can copy it, and an **Add comment** toolbar appears beside the selection. ([#64410](https://github.com/anomalyco/opencode/pull/64410)) + +### Core + +#### Improvements + +- Shell commands still running when their timeout expires now move to the background instead of being killed, in every build. The `shell_timeout_background` flag is gone; configs that still set it keep loading. A foreground `timeout: 0` now uses the default 120 second timeout instead of waiting until the command exits. ([#63699](https://github.com/anomalyco/opencode/pull/63699)) +- Background compaction is now on by default: as a session nears automatic compaction, the summary is written in the background so the next prompt doesn't wait for it. Turn it off with `compaction.background: false`; a background summary that is never used still costs tokens. The `experimental.background_compaction` setting is removed. ([#64290](https://github.com/anomalyco/opencode/pull/64290)) +- OpenCode again reads `CLAUDE.md` in any directory that has no `AGENTS.md`, and falls back to `~/.claude/CLAUDE.md` when the global `AGENTS.md` is missing. This also applies to instructions found when the agent reads nested files. Set `OPENCODE_DISABLE_CLAUDE_CODE` or `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` to skip every `CLAUDE.md`. ([#64474](https://github.com/anomalyco/opencode/pull/64474), [#64533](https://github.com/anomalyco/opencode/pull/64533)) +- Added GPT 6.2 Sol and GPT 6.2 Astra, plus their fast variants, to the ChatGPT model list. ([#64508](https://github.com/anomalyco/opencode/pull/64508)) +- `websearch` now returns a flat list of results, each with its `url`, `title`, `content` and `published` date. ([#64471](https://github.com/anomalyco/opencode/pull/64471)) +- Code Mode and plugins get a simpler structured result from `read`: `text` (with `offset`, `lineCount` and `next`), `directory` (entry names) or `media` (a URI instead of base64). What the model sees is unchanged. ([#64361](https://github.com/anomalyco/opencode/pull/64361)) +- Code Mode programs can use Node's `Buffer` for encoding and decoding bytes. ([#64365](https://github.com/anomalyco/opencode/pull/64365)) +- In Code Mode, `search("issues")` now works as shorthand for `search({ query: "issues" })`. ([#64347](https://github.com/anomalyco/opencode/pull/64347)) +- Code Mode tool summaries in the catalog can now be up to 500 characters instead of 120, so the model sees more of each tool's description. ([#64341](https://github.com/anomalyco/opencode/pull/64341)) +- The `glob` and `grep` tools now report a malformed filename glob (for example `[`) as an error that names the parameter to fix, instead of returning no results. ([#63960](https://github.com/anomalyco/opencode/pull/63960)) +- Server requests that crash now return a 500 with a readable JSON `UnknownError` body instead of an empty one. Storage problems name the cause (for example "Storage is full" or "Storage is read-only"); other crashes include a `ref` you can find in the server log. ([#64022](https://github.com/anomalyco/opencode/pull/64022)) +- The shell tool description now tells the model that its session ID is in the `OPENCODE_SESSION_ID` environment variable. ([#63718](https://github.com/anomalyco/opencode/pull/63718)) +- Experimental schedules are now automations, behind the `automations` flag (the old `schedules` flag still works). An automation runs on a time, an interval, a cron or a pushed MCP event, and either sends a prompt (to the creating session, another session or a new subagent) or runs a Code Mode program that decides whether to send one. Use `/automation` or the `automation_*` tools. Active or paused plain prompt schedules carry over; schedules with a condition or run limit, and finished ones, are dropped. ([#64160](https://github.com/anomalyco/opencode/pull/64160)) + +#### Bug fixes + +- Fixed finished shell commands leaving zombie processes under `opencode-pty`. The process daemon now cleans each command up when it exits. Background processes started by a successful command (`cmd &`) keep running, and a failed command's leftovers are stopped. ([#64266](https://github.com/anomalyco/opencode/pull/64266), [#64251](https://github.com/anomalyco/opencode/pull/64251)) +- Fixed ChatGPT and OpenAI subscription logins losing their sharing-limit safeguards and context caps when a token refresh failed. ([#64470](https://github.com/anomalyco/opencode/pull/64470)) +- Fixed Claude Agent models falling back to a 200K context window when Claude Code adds or renames a model. Thanks @Tarquinen. ([#64107](https://github.com/anomalyco/opencode/pull/64107)) +- Fixed requests being rejected after switching models mid-session on OpenAI-compatible providers. Models that declare a different reasoning field (such as `reasoning_content`) no longer receive `reasoning_details` from earlier turns. ([#64243](https://github.com/anomalyco/opencode/pull/64243)) +- Rejecting a permission request now rejects only the other pending requests from the same step, not every pending request in the session. ([#64343](https://github.com/anomalyco/opencode/pull/64343)) +- Fixed a finished subagent being reported to its parent as still running when its answer quoted the "Background work still running" heading. ([#64026](https://github.com/anomalyco/opencode/pull/64026)) +- Fixed ACP clients missing turns that a background shell woke after the original turn ended. ([#64262](https://github.com/anomalyco/opencode/pull/64262)) +- Reading a small text file now applies the default line and byte limits, so a short file with very many lines is paged instead of returned whole. ([#63810](https://github.com/anomalyco/opencode/pull/63810)) +- Paged reads that select a single blank line now return that line instead of an empty result. ([#63809](https://github.com/anomalyco/opencode/pull/63809)) +- `read` now rejects `limit: 0` with "Limit must be a positive integer". ([#63808](https://github.com/anomalyco/opencode/pull/63808)) +- Text files that start with `BM` are no longer mistaken for BMP images, and only real `GIF87a`/`GIF89a` headers count as GIFs, so these files read as text again. ([#63822](https://github.com/anomalyco/opencode/pull/63822), [#63811](https://github.com/anomalyco/opencode/pull/63811)) +- Fixed shell output pages, grep previews, generated titles, read lines and shell output tails splitting emoji and other multi-byte characters, which showed up as `�`. ([#63984](https://github.com/anomalyco/opencode/pull/63984), [#63967](https://github.com/anomalyco/opencode/pull/63967)) +- Shell commands using unknown ANSI-C escapes such as `$'\q'` are now read the same way Bash and Zsh read them, so permission rules can match them. ([#64263](https://github.com/anomalyco/opencode/pull/64263)) +- Session title search is now case-insensitive for non-ASCII letters, such as Cyrillic and accented text. ([#64259](https://github.com/anomalyco/opencode/pull/64259)) +- Fixed `grep` results being dropped when a matching line or path is not valid UTF-8. Thanks @Tarquinen. ([#62249](https://github.com/anomalyco/opencode/pull/62249)) +- The `@` file picker now finds files in hidden folders such as `.github/` and dotfiles such as `.env.example` when file search uses ripgrep (the default on Windows and outside git repos). `.git` and gitignored files stay excluded. Thanks @Tarquinen. ([#62577](https://github.com/anomalyco/opencode/pull/62577)) +- An unreachable well-known integration source is now skipped instead of dropping every well-known source. Thanks @Tarquinen. ([#62578](https://github.com/anomalyco/opencode/pull/62578)) +- A corrupt cached project ID is now ignored instead of being used. Thanks @Tarquinen. ([#62576](https://github.com/anomalyco/opencode/pull/62576)) +- Plugin tool renames from `tool.execute.before` now apply to calls inside Code Mode programs, and a renamed call returns the new tool's structured result. ([#63633](https://github.com/anomalyco/opencode/pull/63633), [#64333](https://github.com/anomalyco/opencode/pull/64333)) +- In Code Mode, calling a tool that doesn't exist now returns a rejected promise, so `.catch` and `Promise.allSettled` can handle it instead of the whole script failing. ([#64510](https://github.com/anomalyco/opencode/pull/64510)) +- A Code Mode program that only logs no longer shows a stray `null` line before its logs. ([#64344](https://github.com/anomalyco/opencode/pull/64344)) + +### TUI + +#### Improvements + +- Permission prompts from a subagent, and from that subagent's own subagents, now appear while you view the subagent's session. Prompts also show in front of an open composer. ([#64343](https://github.com/anomalyco/opencode/pull/64343)) +- The export dialog under the new designs can save to the system temp directory as well as the project folder. Thanks @Tarquinen. ([#62490](https://github.com/anomalyco/opencode/pull/62490)) +- Removed time to first token (ttft) from the assistant message footer. Tokens per second still shows when `session.tps` is on. ([#63759](https://github.com/anomalyco/opencode/pull/63759)) + +#### Bug fixes + +- When another TUI sharing your tabs closes the session you're viewing, closing it here now moves to the neighbouring tab. ([#64261](https://github.com/anomalyco/opencode/pull/64261)) +- Fixed broken characters at the edges of the shell output viewer and the inline shell display when output is long. ([#63967](https://github.com/anomalyco/opencode/pull/63967), [#63984](https://github.com/anomalyco/opencode/pull/63984)) + +### Desktop + +#### Improvements + +- You can check for and install plugin package updates from **Settings › Extensions**. Use **Check for updates** to look for new versions, then click **Update** on any plugin that has one. ([#64511](https://github.com/anomalyco/opencode/pull/64511), [#64525](https://github.com/anomalyco/opencode/pull/64525)) +- Selecting code in diff and file viewers now just selects text, so you can copy it. An **Add comment** toolbar appears next to the selection to comment on those lines; line numbers and the gutter `+` still start a comment directly. ([#64410](https://github.com/anomalyco/opencode/pull/64410)) +- Cmd+F (Ctrl+F) now finds text in Markdown, Mermaid, CSV and HTML previews in the side panel, using the same find bar as the code view. ([#63663](https://github.com/anomalyco/opencode/pull/63663)) +- Disconnecting a provider or removing an account in **Settings → Providers** now asks for confirmation first. Disconnecting OpenCode Console says how many providers will stop working. ([#64212](https://github.com/anomalyco/opencode/pull/64212)) +- The model picker's variant flyout now follows the keyboard: it opens beside the highlighted row, `→` enters it to pick a variant or toggle Favorite, and `←` or `Escape` goes back. A model's Console budget and reset time now show in the flyout. ([#64409](https://github.com/anomalyco/opencode/pull/64409), [#64423](https://github.com/anomalyco/opencode/pull/64423)) +- When **New worktree** is selected for a new session, the composer shows the base branch (`from dev ▾`). Click it to pick another base; the choice applies immediately, and **Use main checkout** switches back. ([#64228](https://github.com/anomalyco/opencode/pull/64228)) +- Redesigned the folder picker for remote servers, with a path bar, up to three recent-project pills plus a **More projects** menu, and a search box that shows the selected folder. ([#64241](https://github.com/anomalyco/opencode/pull/64241)) +- ` ```latex ` and ` ```math ` code fences now render as display math once complete. ([#64380](https://github.com/anomalyco/opencode/pull/64380)) +- The new icon set is now the default, and the **New icons** experiment has been removed. ([#64466](https://github.com/anomalyco/opencode/pull/64466), [#64451](https://github.com/anomalyco/opencode/pull/64451)) +- The copy button under assistant messages is now always visible. Message metadata still appears on hover. ([#64478](https://github.com/anomalyco/opencode/pull/64478)) +- Text files opened in side-panel tabs now have the same copy and download actions as other files. ([#64463](https://github.com/anomalyco/opencode/pull/64463)) +- **Manage models** now shows every provider as a card with a `⋯` menu, whether or not you're signed in to OpenCode Console. ([#64235](https://github.com/anomalyco/opencode/pull/64235)) +- The connect provider dialog has a cleaner layout for every sign-in step: breadcrumbs, method icons, full-width device codes, and a "Signing in from another device?" row for pasting a redirect URL. ([#63829](https://github.com/anomalyco/opencode/pull/63829)) +- **Collapse long messages** is no longer experimental. It is now a setting under **Timeline** preferences. ([#64441](https://github.com/anomalyco/opencode/pull/64441)) +- Settings now opens on your client preferences, which are listed first, pairing is grouped with Servers, and there's a **Help & feedback** link. ([#64440](https://github.com/anomalyco/opencode/pull/64440), [#64220](https://github.com/anomalyco/opencode/pull/64220)) +- Automatic compactions now always show as a single quiet divider; manual and failed compactions still show the full record. ([#64290](https://github.com/anomalyco/opencode/pull/64290)) +- Pairing QR codes can carry a server name, which becomes the paired server's default name. ([#64139](https://github.com/anomalyco/opencode/pull/64139)) +- Image attachment thumbnails are larger, with a 3:2 crop, and a failed image no longer moves the message below it when retried. ([#64215](https://github.com/anomalyco/opencode/pull/64215)) +- The Hex voice tip no longer appears when Hex is already installed, its copy now says what Hex is, and tips wait an hour after first launch before the first one shows. ([#64130](https://github.com/anomalyco/opencode/pull/64130), [#64131](https://github.com/anomalyco/opencode/pull/64131), [#63974](https://github.com/anomalyco/opencode/pull/63974), [#63760](https://github.com/anomalyco/opencode/pull/63760)) +- Added missing translations for every non-English language, about 920 strings each. ([#64205](https://github.com/anomalyco/opencode/pull/64205)) + +#### Bug fixes + +- Fixed the desktop app failing to start when `drafts.sqlite` was a symlink to or copy of the CLI's `opencode.db`. The desktop now moves that file aside and creates its own, leaving the CLI database untouched. ([#64203](https://github.com/anomalyco/opencode/pull/64203)) +- Switching session tabs with a keyboard shortcut now focuses the composer. ([#64418](https://github.com/anomalyco/opencode/pull/64418)) +- Long prompts now stay folded while a new session is being created. ([#64452](https://github.com/anomalyco/opencode/pull/64452)) +- On macOS, the browser pane stays live while you resize panels instead of showing a still image. ([#64443](https://github.com/anomalyco/opencode/pull/64443)) +- Submenus now open one at a time and swap without blinking, and stay open while you move the pointer across other items to reach them. ([#63739](https://github.com/anomalyco/opencode/pull/63739)) +- Pressing a button now dismisses its tooltip until you hover it again, and copy buttons show "Copied" for two seconds, including in the `/btw` panel. ([#63834](https://github.com/anomalyco/opencode/pull/63834)) +- Dialogs now use consistent sizes, corner radius and row styles across the command palette, session search, model picker, location picker and other lists. ([#63432](https://github.com/anomalyco/opencode/pull/63432), [#64216](https://github.com/anomalyco/opencode/pull/64216), [#64206](https://github.com/anomalyco/opencode/pull/64206)) +- Sessions on OpenCode Go no longer show a $0.00 cost. ([#63744](https://github.com/anomalyco/opencode/pull/63744)) +- **Use main checkout** now stays on one line in the branch picker, and wrapped question descriptions have better spacing. ([#64450](https://github.com/anomalyco/opencode/pull/64450), [#64446](https://github.com/anomalyco/opencode/pull/64446)) +- Restyled the **Timeline detail** slider and visibility buttons in settings so they read as clickable. ([#64186](https://github.com/anomalyco/opencode/pull/64186)) +- Polished small details: animated counts no longer look faded at rest, the sidebar resize pill is hidden, the sidebar peek insets match, subagent breadcrumbs show a hover background, and screen readers name the redirect URL field after its label only. ([#64155](https://github.com/anomalyco/opencode/pull/64155), [#64219](https://github.com/anomalyco/opencode/pull/64219), [#64192](https://github.com/anomalyco/opencode/pull/64192), [#63742](https://github.com/anomalyco/opencode/pull/63742), [#63885](https://github.com/anomalyco/opencode/pull/63885)) + +### SDK + +#### Improvements + +- Unhandled server errors now return a JSON `UnknownError` body (`message` and `ref`) with status 500 instead of an empty body. ([#64022](https://github.com/anomalyco/opencode/pull/64022)) +- Experimental automation endpoints replace the schedule endpoints: `/api/experimental/automation` and `client.experimental.automation.*` (`create`, `list`, `get`, `pause`, `resume`, `delete`). `/api/experimental/schedule` and `client.experimental.schedule.*` are removed. ([#64160](https://github.com/anomalyco/opencode/pull/64160)) +- Config adds `compaction.background`; `experimental.background_compaction` and the `shell_timeout_background` flag are removed. ([#64290](https://github.com/anomalyco/opencode/pull/64290), [#63699](https://github.com/anomalyco/opencode/pull/63699)) + +#### Bug fixes + +- Apps embedding the SDK with an in-memory database no longer import the user's legacy `auth.json` credentials. Only a database file opened by path imports them. ([#63716](https://github.com/anomalyco/opencode/pull/63716)) + +### Extensions + +#### Improvements + +- Each tool call inside a Code Mode program now has its own call ID in plugin hooks and traces. Its permission requests still show on the `execute` call's row. ([#64324](https://github.com/anomalyco/opencode/pull/64324)) +- Plugin `SessionIdleBackground` items can now be `{ kind: "codemode", sessionID, jobID }`, and GUI plugin `BridgeLayout` accepts an optional `clip` rectangle. ([#64343](https://github.com/anomalyco/opencode/pull/64343), [#63819](https://github.com/anomalyco/opencode/pull/63819)) + +#### Bug fixes + +- The browser extension's URL bar action buttons are now spaced 6px apart. ([#64214](https://github.com/anomalyco/opencode/pull/64214)) + ## v2.3.0-shuv.3 — 2026-11-15 Maintenance release on upstream v2.3.0, syncing `dev` from `cbe71595e1` through `0fad04b3d5` (22 commits) as [#497](https://github.com/shuv1337/shuvcode/pull/497), plus the updater fix from [#496](https://github.com/shuv1337/shuvcode/pull/496). The latest upstream release remains v2.3.0. diff --git a/bun.lock b/bun.lock index 4c73d47cae34..eb5eb5f734d1 100644 --- a/bun.lock +++ b/bun.lock @@ -13,7 +13,7 @@ "@ast-grep/cli": "0.44.0", "@hona/strobe": "catalog:", "@opencode/client": "workspace:*", - "@oxlint/plugins": "1.60.0", + "@oxlint/plugins": "1.93.0", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@types/mime-types": "3.0.1", @@ -21,7 +21,7 @@ "@typescript/native": "catalog:", "glob": "13.0.5", "husky": "9.1.7", - "oxlint": "1.60.0", + "oxlint": "1.93.0", "prettier": "3.6.2", "semver": "^7.6.0", "turbo": "2.10.2", @@ -29,7 +29,7 @@ }, "packages/ai": { "name": "@opencode/ai", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@aws-sdk/credential-providers": "3.1057.0", "@opencode/schema": "workspace:*", @@ -66,7 +66,7 @@ }, "packages/app": { "name": "@opencode/app", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@corvu/drawer": "catalog:", "@dnd-kit/abstract": "0.5.0", @@ -136,7 +136,7 @@ }, "packages/cli": { "name": "shuvcode", - "version": "2.3.0-shuv.3", + "version": "2.3.1-shuv.1", "bin": { "shuvcode": "./bin/shuvcode.mjs", }, @@ -147,7 +147,7 @@ "@effect/platform-node": "catalog:", "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", - "@opencode/pty": "0.5.2", + "@opencode/pty": "0.6.0", "@opencode/schema": "workspace:*", "@opencode/server": "workspace:*", "@opencode/tui": "workspace:*", @@ -200,7 +200,7 @@ }, "packages/client": { "name": "@opencode/client", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/protocol": "workspace:*", "@opencode/schema": "workspace:*", @@ -226,7 +226,7 @@ }, "packages/codemode": { "name": "@opencode/codemode", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "acorn": "8.15.0", "effect": "catalog:", @@ -239,7 +239,7 @@ }, "packages/core": { "name": "@opencode/core", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@ai-sdk/provider": "3.0.19", "@effect/platform-node": "catalog:", @@ -256,7 +256,7 @@ "@opencode/codemode": "workspace:*", "@opencode/plugin": "workspace:*", "@opencode/plugin-browser": "workspace:*", - "@opencode/pty": "0.5.2", + "@opencode/pty": "0.6.0", "@opencode/schema": "workspace:*", "@opencode/util": "workspace:*", "@parcel/watcher": "2.5.1", @@ -313,7 +313,7 @@ }, "packages/data/app": { "name": "@opencode/data-app", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@kobalte/core": "catalog:", "@opencode/data-core": "workspace:*", @@ -341,7 +341,7 @@ }, "packages/data/core": { "name": "@opencode/data-core", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@planetscale/database": "1.19.0", "drizzle-orm": "catalog:", @@ -358,7 +358,7 @@ }, "packages/data/server": { "name": "@opencode/data-server", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/data-core": "workspace:*", "effect": "catalog:", @@ -374,7 +374,7 @@ }, "packages/desktop": { "name": "@opencode/desktop", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@zip.js/zip.js": "2.7.62", "electron-context-menu": "5.0.0", @@ -440,7 +440,7 @@ }, "packages/gui-plugins": { "name": "@opencode/gui-plugins", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@betteroffice/docx": "0.4.3", "@betteroffice/fonts": "0.4.0", @@ -485,7 +485,7 @@ }, "packages/http-recorder": { "name": "@opencode/http-recorder", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@effect/platform-node-shared": "catalog:", }, @@ -504,7 +504,7 @@ }, "packages/httpapi-codegen": { "name": "@opencode/httpapi-codegen", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "effect": "catalog:", "prettier": "3.6.2", @@ -517,7 +517,7 @@ }, "packages/latex": { "name": "@opencode/latex", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/plugin": "workspace:*", "@opentui/core": "catalog:", @@ -531,7 +531,7 @@ }, "packages/merman": { "name": "@opencode/merman", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/plugin": "workspace:*", "@opentui/core": "catalog:", @@ -546,7 +546,7 @@ }, "packages/nav-menus": { "name": "@opencode/nav-menus", - "version": "2.3.0", + "version": "2.3.1", "devDependencies": { "@happy-dom/global-registrator": "20.0.11", "@types/bun": "catalog:", @@ -557,7 +557,7 @@ }, "packages/patchmark": { "name": "@opencode/patchmark", - "version": "2.3.0", + "version": "2.3.1", "devDependencies": { "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", @@ -570,7 +570,7 @@ }, "packages/plugin": { "name": "@opencode/plugin", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode/ai": "workspace:*", @@ -615,7 +615,7 @@ }, "packages/plugin-browser": { "name": "@opencode/plugin-browser", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/plugin": "workspace:*", "@opencode/schema": "workspace:*", @@ -630,7 +630,7 @@ }, "packages/plugins/figma": { "name": "@opencode/plugin-figma", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "gray-matter": "4.0.3", }, @@ -645,7 +645,7 @@ }, "packages/protocol": { "name": "@opencode/protocol", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/schema": "workspace:*", "effect": "catalog:", @@ -675,7 +675,7 @@ }, "packages/schema": { "name": "@opencode/schema", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@standard-schema/spec": "catalog:", "effect": "catalog:", @@ -700,7 +700,7 @@ }, "packages/sdk": { "name": "@opencode/sdk", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/client": "workspace:*", "@opencode/core": "workspace:*", @@ -721,7 +721,7 @@ }, "packages/server": { "name": "@opencode/server", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", @@ -735,7 +735,7 @@ "devDependencies": { "@opencode/client": "workspace:*", "@opencode/plugin": "workspace:*", - "@opencode/pty": "0.5.2", + "@opencode/pty": "0.6.0", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@typescript/native": "catalog:", @@ -744,7 +744,7 @@ }, "packages/session-ui": { "name": "@opencode/session-ui", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@kitlangton/solid-motion": "0.2.2", "@kobalte/core": "catalog:", @@ -776,7 +776,7 @@ }, "packages/simulation": { "name": "@opencode/simulation", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/ai": "workspace:*", "@opencode/core": "workspace:*", @@ -814,7 +814,7 @@ }, "packages/theme": { "name": "@opencode/theme", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opentui/core": "catalog:", "effect": "catalog:", @@ -828,7 +828,7 @@ }, "packages/tui": { "name": "@opencode/tui", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@opencode/client": "workspace:*", "@opencode/core": "workspace:*", @@ -864,7 +864,7 @@ }, "packages/ui": { "name": "@opencode/ui", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@kitlangton/solid-motion": "0.2.2", "@kobalte/core": "catalog:", @@ -900,7 +900,7 @@ }, "packages/util": { "name": "@opencode/util", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "@effect/opentelemetry": "catalog:", "@effect/platform-node": "catalog:", @@ -1039,7 +1039,7 @@ }, "services/update": { "name": "@opencode/update", - "version": "2.3.0", + "version": "2.3.1", "dependencies": { "jose": "6.0.11", "semver": "catalog:", @@ -1906,23 +1906,23 @@ "@opencode/protocol": ["@opencode/protocol@workspace:packages/protocol"], - "@opencode/pty": ["@opencode/pty@0.5.2", "", { "optionalDependencies": { "@opencode/pty-darwin-arm64": "0.5.2", "@opencode/pty-darwin-x64": "0.5.2", "@opencode/pty-linux-arm64-gnu": "0.5.2", "@opencode/pty-linux-arm64-musl": "0.5.2", "@opencode/pty-linux-x64-gnu": "0.5.2", "@opencode/pty-linux-x64-musl": "0.5.2", "@opencode/pty-win32-arm64": "0.5.2", "@opencode/pty-win32-x64": "0.5.2" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-SZrzOFZDQHvPndC+ZfDYB52qY/RFxeW0OmKeosSlm4I7tmdDxtvUYN/vy8yynh8678bL+1efbQGxhKa1nz0DCA=="], + "@opencode/pty": ["@opencode/pty@0.6.0", "", { "optionalDependencies": { "@opencode/pty-darwin-arm64": "0.6.0", "@opencode/pty-darwin-x64": "0.6.0", "@opencode/pty-linux-arm64-gnu": "0.6.0", "@opencode/pty-linux-arm64-musl": "0.6.0", "@opencode/pty-linux-x64-gnu": "0.6.0", "@opencode/pty-linux-x64-musl": "0.6.0", "@opencode/pty-win32-arm64": "0.6.0", "@opencode/pty-win32-x64": "0.6.0" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-H4sID90Vuj0AxRN+WFILS65xUZCrltFfRQF7kL8VG6DGyg7bUsNE9LZHgvoWecTWxSZ4HT5ZFd/wUx2eCLTL6w=="], - "@opencode/pty-darwin-arm64": ["@opencode/pty-darwin-arm64@0.5.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CxlLA/+ruVwt+QGOQEnBxiIImgpYU9EdW7bjvA0m+qSDOrFc0hAHOD13Suq3B2JJQxSsj7IM3XicQqmJfqe32Q=="], + "@opencode/pty-darwin-arm64": ["@opencode/pty-darwin-arm64@0.6.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-KDDVvVVcJJlb5vqtzqs/os1DxNwviKV1iwfjODww9y6qAl/Dx/IFZnqlDjp7sTwrAmX2HnJgqIqhwSii+QFRIw=="], - "@opencode/pty-darwin-x64": ["@opencode/pty-darwin-x64@0.5.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-xn4W7y8D+93WM+5+VAwTsPJjw/U9TTEZJQdtIQqFwcCgPCQUylMGu4/xhFbyMllzSycZyysJuhV6CHq/J798zw=="], + "@opencode/pty-darwin-x64": ["@opencode/pty-darwin-x64@0.6.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-A97X8lI7EvEcLhIEPHi79hKZDlBpjO2hopL0ehphjzzQpoS8iCivY+6lo2+9Lf+B/sAHVQYWE4jqpymdM4l6nw=="], - "@opencode/pty-linux-arm64-gnu": ["@opencode/pty-linux-arm64-gnu@0.5.2", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-0Kg1477t9VYHLkaOStiDuoC8S3qHH92ZY/QEgNSOavgkCAAbSEU0NrkIBhEi3Gnw5+ElvfgVcLzEwcM5cfiYAA=="], + "@opencode/pty-linux-arm64-gnu": ["@opencode/pty-linux-arm64-gnu@0.6.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-XMLczimkpuY1fYxn1UmybhbRt7bvDL33qY3NcJq0xE3mNhFTT75SEneduG+3i56+WmIa2QXLrbvubvOWk/u9CQ=="], - "@opencode/pty-linux-arm64-musl": ["@opencode/pty-linux-arm64-musl@0.5.2", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-ZNk4nBooiVCvkB8cCfwn2nDV5OQHdFk/MfRQzBfwk28LakM1YC4lSwZPzY0McvFVjUILie9UEKntHRzgPaDBcA=="], + "@opencode/pty-linux-arm64-musl": ["@opencode/pty-linux-arm64-musl@0.6.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-JjC0D3xhdr0ArDydPg1j0ubo0qypeGPM7fLYbjpvAn3HVgFwdHvhX8DmUqjZHsCtiBVZLGsu5o51vluLLN47/g=="], - "@opencode/pty-linux-x64-gnu": ["@opencode/pty-linux-x64-gnu@0.5.2", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-iLEq9nWOKfm9iWqDGlhqcx+SSLFqBz3toX83n/W+MSlxWg5048HzlGd/3RxY04sxmI6dlg/Ygz3KqP3bCgfusg=="], + "@opencode/pty-linux-x64-gnu": ["@opencode/pty-linux-x64-gnu@0.6.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-OdeuIfAzBM78DNTBoqcwoDanmlokHg+/wPIIB38QbvTms1mNlbUZhILBOw7ra9EwUfSOy6jfcUlrBFLMKj1aOA=="], - "@opencode/pty-linux-x64-musl": ["@opencode/pty-linux-x64-musl@0.5.2", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-jBIw7oimeoTXoHH4yvtVFoPZGU1Rx+kdTVU8HVFGwCDNmeP4hI+R7QhF/pEsKZxzykTskR5x9u5ciiVJ5WEnMg=="], + "@opencode/pty-linux-x64-musl": ["@opencode/pty-linux-x64-musl@0.6.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-8Vm4xBxMQZK212ccHdhVtkAgumueVODYJuazsXzw0yOp5jZhuGCNdxSHeTCItM/SuvoVgVV7c0yySrwszTXwTg=="], - "@opencode/pty-win32-arm64": ["@opencode/pty-win32-arm64@0.5.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-giPMQUcSyoe2z6wQN6MKhRgu4rVv/xqscX8qOVt2lu7yfRNfviPFVY0qFPGOcu1L3e+DT5VrIo2QZeRBeV1Bdw=="], + "@opencode/pty-win32-arm64": ["@opencode/pty-win32-arm64@0.6.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-lYPHn9pqM/0dpuDw+aqAx4k88oHEGM4lNvleQf0Pw+LF+aWTQjHtnx3LoUJEKAlYFOuCbNvLUr4SfAKwhPLsGQ=="], - "@opencode/pty-win32-x64": ["@opencode/pty-win32-x64@0.5.2", "", { "os": "win32", "cpu": "x64" }, "sha512-hXdQWx+gHhQMRovDS3Fm0n4LuvSgLxRqEdicpVQzjjCTPYBMSBysWYRheQ2ydZlP0GCQ2Ymoi0dixgAHTYHO8A=="], + "@opencode/pty-win32-x64": ["@opencode/pty-win32-x64@0.6.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Qb0dqKJyRqe8Q2olfiEc47UybtIUEH12SWag0PkVqDqXabWA3urvcO4+hhD4g/WDkm9F6lPzafiSddtjb2HMtA=="], "@opencode/schema": ["@opencode/schema@workspace:packages/schema"], @@ -2048,45 +2048,45 @@ "@oxc-project/types": ["@oxc-project/types@0.146.0", "", {}, "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA=="], - "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.60.0", "", { "os": "android", "cpu": "arm" }, "sha512-YdeJKaZckDQL1qa62a1aKq/goyq48aX3yOxaaWqWb4sau4Ee4IiLbamftNLU3zbePky6QsDj6thnSSzHRBjDfA=="], + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.93.0", "", { "os": "android", "cpu": "arm" }, "sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg=="], - "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.60.0", "", { "os": "android", "cpu": "arm64" }, "sha512-7ANS7PpXCfq84xZQ8E5WPs14gwcuPcl+/8TFNXfpSu0CQBXz3cUo2fDpHT8v8HJN+Ut02eacvMAzTnc9s6X4tw=="], + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.93.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A=="], - "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.60.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-pJsgd9AfplLGBm1fIr25V6V14vMrayhx4uIQvlfH7jWs2SZwSrvi3TfgfJySB8T+hvyEH8K2zXljQiUnkgUnfQ=="], + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.93.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw=="], - "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.60.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ue1aXHX49ivwflKqGJc7zcd/LeLgbhaTcDCQStgx5x06AXgjEAZmvrlMuIkWd4AL4FHQe6QJ9f33z04Cg448VQ=="], + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.93.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g=="], - "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.60.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-YCyQzsQtusQw+gNRW9rRTifSO+Dt/+dtCl2NHoDMZqJlRTEZ/Oht9YnuporI9yiTx7+cB+eqzX3MtHHVHGIWhg=="], + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.93.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA=="], - "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.60.0", "", { "os": "linux", "cpu": "arm" }, "sha512-c7dxM2Zksa45Qw16i2iGY3Fti2NirJ38FrsBsKw+qcJ0OtqTsBgKJLF0xV+yLG56UH01Z8WRPgsw31e0MoRoGQ=="], + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ=="], - "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.60.0", "", { "os": "linux", "cpu": "arm" }, "sha512-ZWALoA42UYqBEP1Tbw9OWURgFGS1nWj2AAvLdY6ZcGx/Gj93qVCBKjcvwXMupZibYwFbi9s/rzqkZseb/6gVtQ=="], + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA=="], - "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.60.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-tpy+1w4p9hN5CicMCxqNy6ymfRtV5ayE573vFNjp1k1TN/qhLFgflveZoE/0++RlkHikBz2vY545NWm/hp7big=="], + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.93.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw=="], - "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.60.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-eDYDXZGhQAXyn6GwtwiX/qcLS0HlOLPJ/+iiIY8RYr+3P8oKBmgKxADLlniL6FtWfE7pPk7IGN9/xvDEvDvFeg=="], + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.93.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg=="], - "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.60.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-nxehly5XYBHUWI9VJX1bqCf9j/B43DaK/aS/T1fcxCpX3PA4Rm9BB54nPD1CKayT8xg6REN1ao+01hSRNgy8OA=="], + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.93.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA=="], - "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.60.0", "", { "os": "linux", "cpu": "none" }, "sha512-j1qf/NaUfOWQutjeoooNG1Q0zsK0XGmSu1uDLq3cctquRF3j7t9Hxqf/76ehCc5GEUAanth2W4Fa+XT1RFg/nw=="], + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.93.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg=="], - "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.60.0", "", { "os": "linux", "cpu": "none" }, "sha512-YELKPRefQ/q/h3RUmeRfPCUhh2wBvgV1RyZ/F9M9u8cDyXsQW2ojv1DeWQTt466yczDITjZnIOg/s05pk7Ve2A=="], + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.93.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g=="], - "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.60.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-JkO3C6Gki7Y6h/MiIkFKvHFOz98/YWvQ4WYbK9DLXACMP2rjULzkeGyAzorJE5S1dzLQGFgeqvN779kSFwoV1g=="], + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.93.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw=="], - "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.60.0", "", { "os": "linux", "cpu": "x64" }, "sha512-XjKHdFVCpZZZSWBCKyyqCq65s2AKXykMXkjLoKYODrD+f5toLhlwsMESscu8FbgnJQ4Y/dpR/zdazsahmgBJIA=="], + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.93.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A=="], - "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.60.0", "", { "os": "linux", "cpu": "x64" }, "sha512-js29ZWIuPhNWzY8NC7KoffEMEeWG105vbmm+8EOJsC+T/jHBiKIJEUF78+F/IrgEWMMP9N0kRND4Pp75+xAhKg=="], + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.93.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw=="], - "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.60.0", "", { "os": "none", "cpu": "arm64" }, "sha512-H+PUITKHk04stFpWj3x3Kg08Afp/bcXSBi0EhasR5a0Vw7StXHTzdl655PUI0fB4qdh2Wsu6Dsi+3ACxPoyQnA=="], + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.93.0", "", { "os": "none", "cpu": "arm64" }, "sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw=="], - "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.60.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-WA/yc7f7ZfCefBXVzNHn1Ztulb1EFwNBb4jMZ6pjML0zz6pHujlF3Q3jySluz3XHl/GNeMTntG1seUBWVMlMag=="], + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.93.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA=="], - "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.60.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-33YxL1sqwYNZXtn3MD/4dno6s0xeedXOJlT1WohkVD565WvohClZUr7vwKdAk954n4xiEWJkewiCr+zLeq7AeA=="], + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.93.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg=="], - "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.60.0", "", { "os": "win32", "cpu": "x64" }, "sha512-JOro4ZcfBLamJCyfURQmOQByoorgOdx3ZjAkSqnb/CyG/i+lN3KoV5LAgk5ZAW6DPq7/Cx7n23f8DuTWXTWgyQ=="], + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.93.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q=="], - "@oxlint/plugins": ["@oxlint/plugins@1.60.0", "", {}, "sha512-wxEoVVAS5FQAXiA8jPY+NWTOTKTzbSViMfW7yU5OQ7+f34W0KYfy2iuSLC9o1fiYn5xt3LQLxZBREFJtDlQLRw=="], + "@oxlint/plugins": ["@oxlint/plugins@1.93.0", "", {}, "sha512-bKWQI1g9jn8bWUZsvhbOLfgva576Fbp1KwoTNSUCMdT9tlTAvQS2JkifX1UrhPPdyN4GHvM20HhvIMqqU1yotQ=="], "@pagefind/darwin-arm64": ["@pagefind/darwin-arm64@1.5.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-MXpI+7HsAdPkvJ0gk9xj9g541BCqBZOBbdwj9g6lB5LCj6kSV6nqDSjzcAJwvOsfu0fjwvC8hQU+ecfhp+MpiQ=="], @@ -3844,7 +3844,7 @@ "oxc-parser": ["oxc-parser@0.141.0", "", { "dependencies": { "@oxc-project/types": "^0.141.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.141.0", "@oxc-parser/binding-android-arm64": "0.141.0", "@oxc-parser/binding-darwin-arm64": "0.141.0", "@oxc-parser/binding-darwin-x64": "0.141.0", "@oxc-parser/binding-freebsd-x64": "0.141.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.141.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.141.0", "@oxc-parser/binding-linux-arm64-gnu": "0.141.0", "@oxc-parser/binding-linux-arm64-musl": "0.141.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.141.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.141.0", "@oxc-parser/binding-linux-riscv64-musl": "0.141.0", "@oxc-parser/binding-linux-s390x-gnu": "0.141.0", "@oxc-parser/binding-linux-x64-gnu": "0.141.0", "@oxc-parser/binding-linux-x64-musl": "0.141.0", "@oxc-parser/binding-openharmony-arm64": "0.141.0", "@oxc-parser/binding-wasm32-wasi": "0.141.0", "@oxc-parser/binding-win32-arm64-msvc": "0.141.0", "@oxc-parser/binding-win32-ia32-msvc": "0.141.0", "@oxc-parser/binding-win32-x64-msvc": "0.141.0" } }, "sha512-uFkGGr1KMWd6aWv9UAqooYrN78trw8MWWmoPvgWokfBEUq1+eiIQ+qfj3wokhy0fxtZWZk+0dHoS7/yRTJtd6w=="], - "oxlint": ["oxlint@1.60.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.60.0", "@oxlint/binding-android-arm64": "1.60.0", "@oxlint/binding-darwin-arm64": "1.60.0", "@oxlint/binding-darwin-x64": "1.60.0", "@oxlint/binding-freebsd-x64": "1.60.0", "@oxlint/binding-linux-arm-gnueabihf": "1.60.0", "@oxlint/binding-linux-arm-musleabihf": "1.60.0", "@oxlint/binding-linux-arm64-gnu": "1.60.0", "@oxlint/binding-linux-arm64-musl": "1.60.0", "@oxlint/binding-linux-ppc64-gnu": "1.60.0", "@oxlint/binding-linux-riscv64-gnu": "1.60.0", "@oxlint/binding-linux-riscv64-musl": "1.60.0", "@oxlint/binding-linux-s390x-gnu": "1.60.0", "@oxlint/binding-linux-x64-gnu": "1.60.0", "@oxlint/binding-linux-x64-musl": "1.60.0", "@oxlint/binding-openharmony-arm64": "1.60.0", "@oxlint/binding-win32-arm64-msvc": "1.60.0", "@oxlint/binding-win32-ia32-msvc": "1.60.0", "@oxlint/binding-win32-x64-msvc": "1.60.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.18.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-tnRzTWiWJ9pg3ftRWnD0+Oqh78L6ZSwcEudvCZaER0PIqiAnNyXj5N1dPwjmNpDalkKS9m/WMLN1CTPUBPmsgw=="], + "oxlint": ["oxlint@1.93.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.93.0", "@oxlint/binding-android-arm64": "1.93.0", "@oxlint/binding-darwin-arm64": "1.93.0", "@oxlint/binding-darwin-x64": "1.93.0", "@oxlint/binding-freebsd-x64": "1.93.0", "@oxlint/binding-linux-arm-gnueabihf": "1.93.0", "@oxlint/binding-linux-arm-musleabihf": "1.93.0", "@oxlint/binding-linux-arm64-gnu": "1.93.0", "@oxlint/binding-linux-arm64-musl": "1.93.0", "@oxlint/binding-linux-ppc64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-musl": "1.93.0", "@oxlint/binding-linux-s390x-gnu": "1.93.0", "@oxlint/binding-linux-x64-gnu": "1.93.0", "@oxlint/binding-linux-x64-musl": "1.93.0", "@oxlint/binding-openharmony-arm64": "1.93.0", "@oxlint/binding-win32-arm64-msvc": "1.93.0", "@oxlint/binding-win32-ia32-msvc": "1.93.0", "@oxlint/binding-win32-x64-msvc": "1.93.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2005", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA=="], "p-cancelable": ["p-cancelable@2.1.1", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="], diff --git a/docs/sync-2026-11-17-v2.3.1.md b/docs/sync-2026-11-17-v2.3.1.md new file mode 100644 index 000000000000..c96a5eee5939 --- /dev/null +++ b/docs/sync-2026-11-17-v2.3.1.md @@ -0,0 +1,65 @@ +# Upstream v2.3.1 sync — 2026-11-17 PST + +## Summary and ancestry + +- Fork base: `72b398734b5b0ddbab3335f23aa374a38154030c` (`origin/integration-v2`, #501), freshly fetched; local `integration-v2` was fast-forwarded to it before branching. +- Previous upstream pin: `0fad04b3d5a8d5f40e6147573192a7e076787522` (#497). +- Upstream target: tag `v2.3.1` → `c769de83007e3584b5b395176c9fcde2d3231e88` (`release: v2.3.1`), **127 commits** past the previous pin. The release commit is not on `dev` (its parent `bd115fdac8` is; `upstream/dev` has since moved to `9cfff5f24d`); as with v2.3.0 (#489) the tag is the sync source. +- Normal two-parent merge `e38dd71500762bdf84fc58f88392707c3e0b05d0` on `sync-upstream-231`. No rebase or force push. +- 1,504 files changed against the base, mostly upstream's `packages/codemode` reorganisation (`src/codemode/*`, `src/language/*`) and translation updates. The 15 deleted files are all upstream deletions (schedules → automations, `codemode/src/host.ts`, the old icon set, a servers fixture). +- Release prep is folded in, as in #489: CLI manifest and lockfile move to **`2.3.1-shuv.1`**; root and workspace manifests take upstream `2.3.1`. + +## Conflict resolutions + +| Path | Resolution | +| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `.github/workflows/check-process-daemon.yml`, `release-process-daemon.yml` | Kept deleted (fork CI does not run them). | +| `CHANGELOG.md` | Upstream `v2.3.1` notes verbatim above the fork's `v2.3.0-shuv.*` notes; new `v2.3.1-shuv.1` entry on top. | +| `bun.lock`, `packages/cli/package.json` | Kept `shuvcode` name; version `2.3.1-shuv.1`. | +| `packages/core/src/database/migration.gen.ts` | Fork registry (with the fork-only `20261005094821_subagent-operation` migration) plus upstream's three automation migrations as `m60`–`m62`. `bun run migration --check` reports no schema drift. | +| `packages/core/src/permission.ts` | Upstream's same-step scoping (`source.messageID`) plus the fork's claim-before-yield `pending.delete(id)`. Upstream's `nested` call parents are kept. | +| `packages/core/src/tool.ts` | Kept the fork's `executeCall` + `ToolActivity` lease + `settleFailure`; moved upstream's `CodeModeJob.Current` background handling for `execute` into `executeCall`. | +| `packages/core/src/tool/plugin/subagent.ts` | Kept fork durable-subagent recovery checks (#437); replaced the inline depth walk with upstream's `SubagentDepth.reached`. | +| `packages/core/test/codemode/catalog.test.ts` | Upstream expectation (`search(query: string \| {`). | +| `packages/core/test/tool-registry.test.ts` | Kept both sides' new tests (fork rich-failure image tests, upstream Code Mode rename/ID tests). | +| `packages/tui/src/routes/session/index.tsx` | Kept the fork's root-family permission routing and "Parent is waiting for you" banner (#429). Upstream's per-subagent prompt display is not adopted; upstream's `composerVisible` memo and temp-dir export auto-merged. | + +Semantic follow-ups beyond textual conflicts: + +- `packages/codemode/src/codemode/tool-runtime.ts` and `packages/codemode/test/codemode.test.ts`: taken from upstream. Upstream #64347 implements `search("…")` in the runtime; the fork's earlier schema-union patch was redundant and changed the rendered signature. +- `packages/app/src/runtime/i18n/*.ts`: removed the `dialog.provider.claudeAgent.note` and `provider.connect.claudeAgent.*` keys upstream re-added in 62 locales (#64205). The fork removed them from `en.ts` with the hidden Claude Agent provider. + +## Fork preservation + +- Identity: package/bin `shuvcode`, `Global.app = "shuvcode"`, ports `0x1337`/`0x1338`, npm-only updates and the publish guard are unchanged. +- Claude Agent SDK hiding: `ProviderPlugins` still filters `opencode.provider.claude-agent`, the config provider plugin still calls `isHiddenProvider`, and the 17 files calling the predicate are unchanged (17 before, 17 after). Upstream's new app provider surfaces (Manage models cards, Settings › Providers confirmations, plugin updates) read the app catalog, which `omitHiddenProviderCatalog` already filters. +- No public Protocol or Server `HttpApi` drift beyond upstream's own: `bun run generate` in `packages/client` leaves the tree clean. +- Bundled Antigravity (now with Gemini 4 Carbon/Hydrogen from #501), Claude and Quota plugins pass their suites. + +## Branch inventory + +No new fork branches since #497's inventory except `gemini-4-models` (#501, merged into the base). `pwsh-hosted-probe` and `pwsh-ci-diag` remain parked diagnostics for #493 (do not merge, nothing included). All older unmerged local and `origin/*` branches keep the dispositions recorded in `docs/sync-2026-11-15-dev.md` and earlier audits. No open PRs. + +## Validation + +Bun 1.4.4. Package suites ran from their package directories under `env -i` with a private `HOME`, XDG roots and `TMPDIR`. + +| Gate | Result | +| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Root `bun run check` (lint + typecheck) | Pass, 40/40 tasks | +| `bun run generate` (`packages/client`) | Pass, no drift | +| `bun install --frozen-lockfile` | Pass, no changes | +| `bun run migration --check` (`packages/core`) | Pass | +| `git diff --check` | Pass | +| Core | 7,745 pass / 16 skip / 11 fail — all 11 are the GitLab OAuth callback-port tests (port occupied on this host), same as #497 | +| TUI | 1,755 pass / 2 skip / 2 fail — both `dialog-shell-output.test.tsx` "survives exit" cases time out identically on the unmodified base `72b398734b` on this host | +| CLI | 489 pass / 7 skip / 0 fail | +| Server | 143 pass / 1 skip / 0 fail | +| AI | 2,289 pass / 29 skip / 0 fail | +| App unit + browser | 2,746 pass and 361 pass, 0 fail | +| Session-ui | 617 pass / 0 fail | +| Codemode | 1,690 pass / 0 fail | +| Antigravity / Claude / Quota plugins | 80 / 43 / 37 pass, 0 fail | +| Util / Schema / Protocol | 156 / 95 / 14 pass, 0 fail | + +CI's `unit` and `e2e` jobs (enabled by the `chore(sync)` title) are the release gate. diff --git a/package.json b/package.json index 3a3f4cd2a78e..69ece8b01574 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.0", + "version": "2.3.1", "private": true, "type": "module", "packageManager": "bun@1.4.4", @@ -111,7 +111,7 @@ "@ast-grep/cli": "0.44.0", "@hona/strobe": "catalog:", "@opencode/client": "workspace:*", - "@oxlint/plugins": "1.60.0", + "@oxlint/plugins": "1.93.0", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@types/mime-types": "3.0.1", @@ -119,7 +119,7 @@ "@typescript/native": "catalog:", "glob": "13.0.5", "husky": "9.1.7", - "oxlint": "1.60.0", + "oxlint": "1.93.0", "prettier": "3.6.2", "semver": "^7.6.0", "turbo": "2.10.2" diff --git a/packages/ai/AGENTS.md b/packages/ai/AGENTS.md index c79efda7fe26..f01770a9ca2e 100644 --- a/packages/ai/AGENTS.md +++ b/packages/ai/AGENTS.md @@ -7,7 +7,8 @@ - **One canonical model.** The Schema classes in `src/schema/` are the data model. Do not add a parallel shape or a second construction path. - **Independent of Session.** Auth, permissions, plugins, and orchestration belong in Core. `ai.stream`/`ai.generate` run exactly one model call. - **Reuse protocols.** Providers compose existing protocols with `Route.make(...)` instead of cloning them. -- **One API, two runtimes.** `ai` from `@opencode/ai` and `ai` from `@opencode/ai/effect` have the same namespaces and operations, with the same names, overloads, input and options (plus `signal` on the Promise side); keep `test/promise-parity.types.ts` passing. +- **One API, two runtimes.** `ai` from `@opencode/ai` and `ai` from `@opencode/ai/effect` have the same namespaces and operations, with the same names, overloads, input and options (plus `RunOptions`, `signal` and `http`, on the Promise side); keep `test/promise-parity.types.ts` passing. +- **One way to hook HTTP.** Every request goes through `RequestExecutor`, which applies executor-wide middleware (`RequestExecutor.middleware`) and the caller's scoped middleware (`RequestExecutor.withMiddleware`, Promise `{ http }`). Don't add a per-method hook option or send HTTP any other way. A `url` asset downloads with its own `middleware`, which a route sets only for URLs on the provider's origin. Types already require every route to send through the executor it is given, and lint rejects `fetch` and the `HttpClient` import outside `route/executor.ts`. Keep `test/http-hooks.test.ts` passing; it lists every Promise method. ## Code style diff --git a/packages/ai/README.md b/packages/ai/README.md index 0ac9f6f9aa4d..4aecba45b411 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -249,6 +249,29 @@ const logged = RequestExecutor.middleware((request, next) => const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged }) ``` +To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request +they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it. + +```ts +const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1")) + +// Effect: an Effect or a Stream +const video = + yield * + Effect.gen(function* () { + const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" }) + return yield* ai.video.result(model, job.id) + }).pipe(RequestExecutor.withMiddleware(signed)) + +// Promise: `http` on any call's options; a handle it returns keeps it +await AI.ai.video.start({ model, prompt: "A red balloon floats up" }, { http: signed }) +``` + +Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another +host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the +call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with +`Media.url(url, { middleware })`. + ## Venice AI `Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat` diff --git a/packages/ai/package.json b/packages/ai/package.json index 776cc31ec4b8..7214d2c3d1ba 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.0", + "version": "2.3.1", "name": "@opencode/ai", "type": "module", "license": "MIT", diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index b50992c47a27..21e4627dd6e5 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -23,6 +23,7 @@ import { type ToolEntry, } from "./schema/messages.js" import { effortUpdate } from "./effort-updates.js" +import { toolsUpdate } from "./tool-updates.js" const AUTO: CachePolicyObject = { tools: true, @@ -191,14 +192,15 @@ const markMessages = ( let remaining = strategy.tail while (remaining > 0 && start > 0) { start -= 1 - if (effortUpdate(messages[start]!) === undefined) remaining -= 1 + if (!isMarker(messages[start]!)) remaining -= 1 } let next = messages - for (let i = start; i < messages.length; i++) - if (effortUpdate(messages[i]!) === undefined) next = markMessageAt(next, i, hint, budget) + for (let i = start; i < messages.length; i++) if (!isMarker(messages[i]!)) next = markMessageAt(next, i, hint, budget) return next } +const isMarker = (message: Message) => effortUpdate(message) !== undefined || toolsUpdate(message) !== undefined + const countHints = (request: LLMRequest) => countToolHints(request.tools) + request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) + diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index 8495891924da..59599444db88 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -13,7 +13,7 @@ import { type StreamOptions, type TriggerCompactOptions, } from "./route/client.js" -import { RequestExecutor } from "./route/executor.js" +import { RequestExecutor, type HttpMiddleware } from "./route/executor.js" import { AIError, InvalidRequestError, @@ -56,8 +56,16 @@ export interface Options { export interface RunOptions { readonly signal?: AbortSignal + /** + * Runs on every provider request the call makes, like `RequestExecutor.withMiddleware`: submits, polls, results and + * cancels included. A handle the call returns keeps it for its own calls. + */ + readonly http?: HttpMiddleware } +/** Options for reading or writing an asset. Downloads use the asset's own `middleware`, never a caller's `http`. */ +export type AssetRunOptions = Omit + export type Services = AIClient.Services /** @@ -97,7 +105,7 @@ export const make = (options: Options = {}) => { /** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */ const run = (effect: Effect.Effect, options?: RunOptions) => - runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal))) + runtime.runPromise(Effect.raceFirst(scoped(effect, options?.http), abortEffect(options?.signal))) const iterate = (stream: Stream.Stream, options?: RunOptions): AsyncIterable => Stream.toAsyncIterable( @@ -105,7 +113,10 @@ export const make = (options: Options = {}) => { runtime.contextEffect.pipe( Effect.map( (context): Stream.Stream => - stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context)), + scoped(stream, options?.http).pipe( + Stream.interruptWhen(abortEffect(options?.signal)), + Stream.provideContext(context), + ), ), ), ), @@ -119,8 +130,9 @@ export const make = (options: Options = {}) => { input: LLMRequestInput, options?: StreamOptions & RunOptions, ): Promise + // `run` and `iterate` apply `http` around the whole call, so the LLM call gets none of its own. function generate(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) { - return run(LLM.generate(input, options), options) + return run(LLM.generate(input, { ...options, http: undefined }), options) } function stream( @@ -132,7 +144,7 @@ export const make = (options: Options = {}) => { options?: StreamOptions & RunOptions, ): AsyncIterable function stream(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) { - return iterate(LLM.stream(input, options), options) + return iterate(LLM.stream(input, { ...options, http: undefined }), options) } function loop( @@ -144,7 +156,7 @@ export const make = (options: Options = {}) => { options?: StreamOptions & RunOptions, ): AsyncIterable function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) { - return iterate(LLM.loop(input, options), options) + return iterate(LLM.loop(input, { ...options, http: undefined }), options) } /** Read `events` from `stream` or `loop` to the end and fold them into the final result. */ @@ -165,31 +177,33 @@ export const make = (options: Options = {}) => { options?: (TriggerCompactOptions | EndpointCompactOptions) & RunOptions, ) { return options?.mechanism === "trigger" - ? run(LLM.compact(request as CheckpointRequest, options), options) - : run(LLM.compact(request as CompactionRequest, options), options) + ? run(LLM.compact(request as CheckpointRequest, { ...options, http: undefined }), options) + : run(LLM.compact(request as CompactionRequest, { ...options, http: undefined }), options) } - const handle = (generation: Generation): GenerationHandle => ({ - ...generation.snapshot, - snapshot: generation.snapshot, - terminal: generation.terminal, - token: generation.token, - await: (options) => run(generation.await(options), options), - events: (options) => iterate(generation.events(options), options), - result: (options) => run(generation.result(), options), - refresh: (options) => run(generation.refresh(), options).then(handle), - cancel: (options) => run(generation.cancel(), options), - }) + const handle = + (http: HttpMiddleware | undefined) => + (generation: Generation): GenerationHandle => ({ + ...generation.snapshot, + snapshot: generation.snapshot, + terminal: generation.terminal, + token: generation.token, + await: (options) => run(generation.await(options), { http, ...options }), + events: (options) => iterate(generation.events(options), { http, ...options }), + result: (options) => run(generation.result(), { http, ...options }), + refresh: (options) => run(generation.refresh(), { http, ...options }).then(handle(options?.http ?? http)), + cancel: (options) => run(generation.cancel(), { http, ...options }), + }) return { run, /** Decoded asset bytes, downloading `url` sources through the executor. */ - bytes: (asset: Media.Asset, options?: RunOptions) => run(asset.bytes(), options), - base64: (asset: Media.Asset, options?: RunOptions) => run(asset.base64(), options), + bytes: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.bytes(), options), + base64: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.base64(), options), /** Pull a `url` asset into owned bytes before the provider URL expires. */ - materialize: (asset: Media.Asset, options?: RunOptions) => run(asset.materialize(), options), + materialize: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.materialize(), options), /** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */ - file: async (path: string, options?: Media.AssetOptions & RunOptions) => { + file: async (path: string, options?: Media.AssetOptions & AssetRunOptions) => { const { readFile } = await import("node:fs/promises") return run( Effect.tryPromise({ @@ -205,7 +219,7 @@ export const make = (options: Options = {}) => { ) }, /** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */ - write: async (asset: Media.Asset, path: string, options?: RunOptions) => { + write: async (asset: Media.Asset, path: string, options?: AssetRunOptions) => { const { open, rename, rm } = await import("node:fs/promises") const temporary = `${path}.${crypto.randomUUID()}.tmp` try { @@ -299,9 +313,9 @@ export const make = (options: Options = {}) => { start: ( input: TranscriptionRequestInput | TranscriptionRequest, options?: RunOptions, - ) => run(Transcription.start(input), options).then(handle), + ) => run(Transcription.start(input), options).then(handle(options?.http)), resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => - run(Transcription.resume(model, token), options).then(handle), + run(Transcription.resume(model, token), options).then(handle(options?.http)), }, }, dispose: () => runtime.dispose(), @@ -310,6 +324,11 @@ export const make = (options: Options = {}) => { export type Client = ReturnType +const scoped = | Stream.Stream>( + self: Self, + http: HttpMiddleware | undefined, +) => (http === undefined ? self : RequestExecutor.withMiddleware(http)(self)) + const fileError = (message: string, cause: unknown) => new AIError({ reason: new InvalidRequestError({ message, cause }) }) diff --git a/packages/ai/src/llm.ts b/packages/ai/src/llm.ts index bf35b69f87bf..22d69f48ba21 100644 --- a/packages/ai/src/llm.ts +++ b/packages/ai/src/llm.ts @@ -39,6 +39,7 @@ import { import { tool, type ExecutableTool, type Tool, type ToolSchema } from "./tool.js" import { runTools } from "./tool-runtime.js" import { addUsage, nextRequest, pendingCalls } from "./loop.js" +import { foldTools } from "./tool-updates.js" /** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */ export type LLMRequestInput = TextRequestFields & PromptOrMessages @@ -53,7 +54,10 @@ interface TextRequestFields GenerationOptionsFields { readonly id?: string readonly system?: string | SystemPart | ReadonlyArray - /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */ + /** + * Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. The same as a + * `Message.tools({ add: tools })` leading the history. + */ readonly tools?: ReadonlyArray readonly toolChoice?: ToolChoice.Input readonly cache?: CachePolicy @@ -149,11 +153,35 @@ export function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, o const { tools, until, ...rest } = input return Stream.unwrap( prepare({ ...rest, tools }).pipe( - Effect.map(({ request, output }) => driveLoop({ tools, until, output, options }, request, [], undefined)), + // Untyped callers may omit `tools`. + Effect.map(({ request, output }) => + driveLoop( + { tools: runnableTools(tools ?? [], input.messages ?? []), until, output, options }, + request, + [], + undefined, + ), + ), ), ) } +// Tools that `Message.tools(...)` adds run like top-level ones; a later change with the same name replaces or removes them. +const runnableTools = (tools: ReadonlyArray, messages: ReadonlyArray) => + messages + .reduce>( + (current, message) => + message.role === "system" && message.tools !== undefined + ? foldTools( + current, + message.tools.add ?? [], + (message.tools.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)), + ) + : current, + tools, + ) + .filter((item): item is Tool => "_definition" in item) + export { collect, type Collected, type CollectResult } from "./loop.js" interface Step { @@ -209,7 +237,7 @@ const finishStep = ( } interface LoopContext { - readonly tools: ReadonlyArray + readonly tools: ReadonlyArray readonly until: LLMLoopInput["until"] readonly output: Tool | undefined readonly options: StreamOptions | undefined diff --git a/packages/ai/src/media.ts b/packages/ai/src/media.ts index 9ac2ca44c291..0a675c368ad8 100644 --- a/packages/ai/src/media.ts +++ b/packages/ai/src/media.ts @@ -6,7 +6,7 @@ import { HttpClientRequest } from "effect/http" import { ProviderID } from "./schema/ids.js" import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js" import { ProviderMetadata } from "./schema/options.js" -import { responseHttp, Service } from "./route/executor-service.js" +import { CurrentMiddleware, type HttpMiddleware, responseHttp, Service } from "./route/executor-service.js" import { detectMediaType, fileMediaType } from "./utils/media-type.js" export { detectMediaType } from "./utils/media-type.js" @@ -109,6 +109,8 @@ export class Asset { readonly providerMetadata?: ProviderMetadata /** Transient download credentials for `url` sources; see `Asset.Input.headers`. */ readonly headers?: Record + /** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */ + readonly middleware?: HttpMiddleware // Derived payload forms are cached on the instance because every protocol lowering re-reads the same payload. The // cache is check-then-set (concurrent first reads of a `url` source may both download) and is never observable @@ -127,6 +129,7 @@ export class Asset { this.expiresAt = input.source.type === "url" ? input.source.expiresAt : undefined this.providerMetadata = input.providerMetadata this.headers = input.source.type === "url" ? input.headers : undefined + this.middleware = input.source.type === "url" ? input.middleware : undefined } /** Inline payload without effects, for protocols that embed base64 or data URLs directly. */ @@ -151,7 +154,7 @@ export class Asset { ? Effect.fromResult(Base64.decode(source.data)).pipe( Effect.mapError((cause) => invalid(`Media asset contains invalid base64 data`, cause)), ) - : download(source, this.headers) + : download(source, this.headers, this.middleware) return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data)))) }) } @@ -160,7 +163,7 @@ export class Asset { stream(): Stream.Stream { const source = this.source if (source.type !== "url" || this.#bytes !== undefined) return Stream.fromEffect(this.bytes()) - return Stream.unwrap(downloadStream(source, this.headers)) + return Stream.unwrap(downloadStream(source, this.headers, this.middleware)) } base64(): Effect.Effect { @@ -211,6 +214,12 @@ export namespace Asset { * credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting. */ readonly headers?: Record + /** + * Middleware for downloading a `url` source, runtime-only like `headers`. A download never uses the caller's + * scoped middleware (`RequestExecutor.withMiddleware`), so hooks that add provider credentials can't reach another + * host. Routes set this to that middleware only for result URLs on the provider's origin. + */ + readonly middleware?: HttpMiddleware } } @@ -256,11 +265,12 @@ export type ImageAsset = typeof ImageAssetSchema.Type const download = Effect.fn("Media.download")(function* ( source: Extract, headers: Record | undefined, + middleware: HttpMiddleware | undefined, ) { const executor = yield* Service - const response = yield* executor.execute( - HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})), - ) + const response = yield* executor + .execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {}))) + .pipe(Effect.provideService(CurrentMiddleware, middleware)) const buffer = yield* response.arrayBuffer.pipe( Effect.mapError( (cause) => @@ -279,11 +289,12 @@ const download = Effect.fn("Media.download")(function* ( const downloadStream = Effect.fn("Media.downloadStream")(function* ( source: Extract, headers: Record | undefined, + middleware: HttpMiddleware | undefined, ) { const executor = yield* Service - const response = yield* executor.execute( - HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})), - ) + const response = yield* executor + .execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {}))) + .pipe(Effect.provideService(CurrentMiddleware, middleware)) return response.stream.pipe( Stream.mapError( (cause) => diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index 370da402cf0f..1fa49264a30c 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -23,11 +23,13 @@ import { type ProviderOptions, type ToolCallPart, type ToolDefinition, + type ToolChanges, type ToolResultPart, } from "../schema/index.js" 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 * as Cache from "./utils/cache.js" import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js" import { Lifecycle } from "./utils/lifecycle.js" @@ -253,25 +255,34 @@ const AnthropicAssistantBlock = Schema.Union([ type AnthropicAssistantBlock = Schema.Schema.Type type AnthropicToolResultBlock = Schema.Schema.Type +const AnthropicTool = Schema.Struct({ + name: Schema.String, + description: Schema.String, + input_schema: JsonObject, + cache_control: Schema.optional(AnthropicCacheControl), +}) +type AnthropicTool = Schema.Schema.Type + +const AnthropicToolAdditionBlock = Schema.Struct({ + type: Schema.tag("tool_addition"), + tool: Schema.Struct({ type: Schema.tag("tool_definition"), definition: AnthropicTool }), +}) +const AnthropicToolRemovalBlock = Schema.Struct({ + type: Schema.tag("tool_removal"), + tool: Schema.Struct({ type: Schema.tag("tool_reference"), name: Schema.String }), +}) + const AnthropicMessage = Schema.Union([ Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }), Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }), Schema.Struct({ role: Schema.Literal("system"), - content: Schema.Array(AnthropicTextBlock), + content: Schema.Array(Schema.Union([AnthropicTextBlock, AnthropicToolAdditionBlock, AnthropicToolRemovalBlock])), output_config: Schema.optional(Schema.Struct({ effort: Schema.String })), }), ]).pipe(Schema.toTaggedUnion("role")) type AnthropicMessage = Schema.Schema.Type -const AnthropicTool = Schema.Struct({ - name: Schema.String, - description: Schema.String, - input_schema: JsonObject, - cache_control: Schema.optional(AnthropicCacheControl), -}) -type AnthropicTool = Schema.Schema.Type - const AnthropicToolChoice = Schema.Union([ Schema.Struct({ type: Schema.Literals(["auto", "any", "none"]), @@ -813,6 +824,29 @@ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* ( return { type: "text" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) } }) +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 + return { + role: "system" as const, + content: [ + ...ProviderShared.flattenTools(update.add).map((tool) => ({ + type: "tool_addition" as const, + tool: { type: "tool_definition" as const, definition: lowerTool(breakpoints, tool) }, + })), + ...withdrawn.map((name) => ({ + type: "tool_removal" as const, + tool: { type: "tool_reference" as const, name }, + })), + ...text, + ], + } +}) + const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBlock) => { const last = messages.at(-1) if (last?.role === "user") messages[messages.length - 1] = { role: "user", content: [...last.content, block] } @@ -826,9 +860,20 @@ 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 + if (lowered.content.length > 0) messages.push(lowered) + continue + } if (native) messages.push(yield* lowerNativeSystemUpdate(update, breakpoints)) else appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(update, breakpoints)) } @@ -842,6 +887,12 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } }) continue } + // Held like text updates, so one between a tool call and its result lands after the result. Planning keeps a + // marker in place only on models that take native system messages. + if (toolsUpdate(message) !== undefined) { + held.push(message) + continue + } if (splitsLocalToolResults(request.messages, index)) return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result") if (holdUpdates) held.push(message) @@ -951,6 +1002,21 @@ const supportsEffortUpdates = (request: LLMRequest) => { return version.major > 5 || (version.major === 5 && version.minor >= 1) } +// `tool_addition` adds a tool, or redefines one with the same name; `tool_removal` removes one. A held marker is +// released just before the next assistant message, where Anthropic only accepts a native system message after a +// user message or tool result; a marker that would land elsewhere folds. +const toolUpdates = { + kinds: ["add", "remove", "replace"], + placeable: (request, index) => { + if (!supportsNativeSystemUpdates(request)) return false + const end = request.messages.findIndex((next, at) => at > index && next.role === "assistant") + const role = request.messages + .slice(0, end === -1 ? undefined : end) + .findLast((next) => next.role !== "system")?.role + return role === "user" || role === "tool" + }, +} satisfies ToolUpdateEncoding + const applyThinkingBindingDefault = (model: LLMRequest["model"], thinking: AnthropicThinking | undefined) => { if (isThinkingOff(thinking)) return thinking if (!supportsThinkingBlockBinding(model)) return thinking @@ -984,8 +1050,9 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques 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)) - // Anthropic rejects tool_choice when tools are absent; "none" is only meaningful with tools present. - const toolChoice = tools === undefined || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice) + // 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) const systemParts = request.system.filter((part) => part.text.length > 0) const system = systemParts.length === 0 @@ -1549,6 +1616,7 @@ export const protocol = Protocol.make({ step, }, supportsEffortUpdates, + toolUpdates, }) export const transport = < @@ -1589,6 +1657,14 @@ function requiredBetaHeaders( if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined)) betas.push("mid-conversation-output-config-2026-07-01") + if ( + body.messages.some( + (message) => + message.role === "system" && + message.content.some((block) => block.type === "tool_addition" || block.type === "tool_removal"), + ) + ) + betas.push("inline-tools-2026-09-15") // Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it. if (body.speed !== undefined) betas.push("fast-mode-2026-02-01") diff --git a/packages/ai/src/protocols/open-responses.ts b/packages/ai/src/protocols/open-responses.ts index 24c6ffd032e8..9606df4d7231 100644 --- a/packages/ai/src/protocols/open-responses.ts +++ b/packages/ai/src/protocols/open-responses.ts @@ -14,6 +14,7 @@ import { type ReasoningPart, type TextPart, type ToolCallPart, + type ToolChanges, type ToolDefinition, type ToolResultPart, type UserMessage, @@ -30,6 +31,7 @@ import { } from "./shared.js" import { classifyProviderFailure } from "../provider-error.js" import { effortUpdate } from "../effort-updates.js" +import { toolsUpdate } from "../tool-updates.js" import { OpenResponsesOptions } from "./utils/open-responses-options.js" import { Lifecycle } from "./utils/lifecycle.js" import { ToolStream } from "./utils/tool-stream.js" @@ -189,9 +191,49 @@ export const HostedToolReplay = Schema.StructWithRest( ) export type HostedToolReplayItem = Schema.Schema.Type +export const Tool = Schema.Struct({ + type: Schema.tag("function"), + name: Schema.String, + description: Schema.String, + parameters: JsonObject, + strict: Schema.optional(Schema.Boolean), +}) + +export const CustomTool = Schema.Struct({ + type: Schema.tag("custom"), + name: Schema.String, + description: Schema.String, + format: Schema.Union([ + Schema.Struct({ type: Schema.tag("text") }), + Schema.Struct({ + type: Schema.tag("grammar"), + syntax: Schema.Literals(["lark", "regex"]), + definition: Schema.String, + }), + ]), +}) + +export const HostedTool = Schema.StructWithRest( + Schema.Struct({ + type: Schema.String, + }), + [JsonObject], +) +export type HostedTool = Schema.Schema.Type + +const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String }) + +// Tools added mid-conversation. Only the OpenAI extension lowers it; other hosts fold tool updates. +export const AdditionalTools = Schema.Struct({ + type: Schema.Literal("additional_tools"), + role: Schema.Literal("developer"), + tools: Schema.Array(Schema.Union([Tool, CustomTool, HostedTool])), +}) + export const InputItem = Schema.Union([ CompactionItem, ConfigurationUpdate, + AdditionalTools, Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("system"), content: Schema.String }), Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("developer"), content: Schema.String }), Schema.Struct({ @@ -243,38 +285,6 @@ type OpenResponsesReasoningInput = { summary: Array<{ type: "summary_text"; text: string }> encrypted_content?: string | null } -export const Tool = Schema.Struct({ - type: Schema.tag("function"), - name: Schema.String, - description: Schema.String, - parameters: JsonObject, - strict: Schema.optional(Schema.Boolean), -}) - -export const CustomTool = Schema.Struct({ - type: Schema.tag("custom"), - name: Schema.String, - description: Schema.String, - format: Schema.Union([ - Schema.Struct({ type: Schema.tag("text") }), - Schema.Struct({ - type: Schema.tag("grammar"), - syntax: Schema.Literals(["lark", "regex"]), - definition: Schema.String, - }), - ]), -}) - -export const HostedTool = Schema.StructWithRest( - Schema.Struct({ - type: Schema.String, - }), - [JsonObject], -) -export type HostedTool = Schema.Schema.Type - -const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String }) - export const ToolChoice = Schema.Union([ Schema.Literals(["auto", "none", "required"]), NamedTool, @@ -434,6 +444,8 @@ export interface ProviderAdapter { readonly request: LLMRequest }) => MediaInput | undefined readonly restoreHostedToolItem?: (item: unknown) => HostedToolReplayItem | undefined + /** Lowers a `Message.tools(...)` marker sent in place; routes without it must fold tool updates. */ + readonly lowerToolChanges?: (changes: ToolChanges) => Effect.Effect, AIError> } const BASE_ADAPTER: ProviderAdapter = { id: ADAPTER, name: NAME } @@ -666,6 +678,13 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter: input.push({ type: "configuration_update", reasoning: { effort: update.effort ?? DEFAULT_EFFORT } }) continue } + // Planning folds every marker on routes whose protocol has no `toolUpdates`, so only adapters with + // `lowerToolChanges` see one. + const tools = toolsUpdate(message) + if (tools && adapter.lowerToolChanges) { + input.push(...(yield* adapter.lowerToolChanges(tools))) + if (message.content.length === 0) continue + } input.push({ type: "message", role: "developer", diff --git a/packages/ai/src/protocols/openai-chat.ts b/packages/ai/src/protocols/openai-chat.ts index 20a94bb4ed63..dabbd096b350 100644 --- a/packages/ai/src/protocols/openai-chat.ts +++ b/packages/ai/src/protocols/openai-chat.ts @@ -577,6 +577,9 @@ const lowerAssistantMessage = Effect.fnUntraced(function* ( const opaque = reasoningOpaque(reasoning, options.providerMetadataKey) const reasoningText = reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text + // A model that declares a different reasoning field reads reasoning there, so structured details and opaque values + // from earlier turns (including another model served under the same provider metadata key) must not be replayed. + const replaysStructured = configuredField === undefined || configuredField === "reasoning_details" const result = { role: "assistant" as const, content: (() => { @@ -585,10 +588,11 @@ const lowerAssistantMessage = Effect.fnUntraced(function* ( return content.map((part) => part.text).join("") })(), ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}), - ...(details !== undefined ? { reasoning_details: details } : {}), - ...(opaque !== undefined ? { reasoning_opaque: opaque } : {}), + ...(details !== undefined && replaysStructured ? { reasoning_details: details } : {}), + ...(opaque !== undefined && replaysStructured ? { reasoning_opaque: opaque } : {}), } - if (field === undefined || reasoningText === undefined) return result + // `reasoning_details` is the structured list itself, so scalar text must not be written over it. + if (field === undefined || reasoningText === undefined || field === "reasoning_details") return result return { ...result, [field]: reasoningText } }) diff --git a/packages/ai/src/protocols/openai-freeform.ts b/packages/ai/src/protocols/openai-freeform.ts index 272827f7c934..5bd810787337 100644 --- a/packages/ai/src/protocols/openai-freeform.ts +++ b/packages/ai/src/protocols/openai-freeform.ts @@ -8,6 +8,7 @@ import { } from "../schema/index.js" import { encodeJson, flattenTools, isRecord } from "./shared.js" import { ToolStream } from "./utils/tool-stream.js" +import { toolsUpdate } from "../tool-updates.js" // Freeform tools as OpenAI custom tools, shared by Responses and Chat Completions: // https://platform.openai.com/docs/guides/function-calling#custom-tools @@ -26,14 +27,16 @@ export const resolve = (tool: ToolDefinition): Custom | undefined => { return { field, format: tool.freeform } } -/** Custom tools in this request, by flattened tool name. */ -export const tools = (request: LLMRequest): ReadonlyMap => - new Map( - flattenTools(request.tools).flatMap((tool) => { +/** Custom tools in this request, including ones added mid-conversation, by flattened tool name. */ +export const tools = (request: LLMRequest): ReadonlyMap => { + const added = request.messages.flatMap((message) => toolsUpdate(message)?.add ?? []) + return new Map( + flattenTools([...request.tools, ...added]).flatMap((tool) => { const custom = resolve(tool) return custom ? [[tool.name, custom] as const] : [] }), ) +} /** The format's grammar, or `undefined` for unconstrained text. */ export const grammar = (format: Freeform) => diff --git a/packages/ai/src/protocols/openai-responses.ts b/packages/ai/src/protocols/openai-responses.ts index d50c44a3a56d..00a0dbfcd834 100644 --- a/packages/ai/src/protocols/openai-responses.ts +++ b/packages/ai/src/protocols/openai-responses.ts @@ -6,9 +6,10 @@ import { Auth } from "../route/auth.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" import { HttpTransport } from "../route/transport/index.js" -import type { LLMRequest, ToolDefinition, ToolEntry } from "../schema/index.js" +import type { LLMRequest, ToolChanges, ToolDefinition, ToolEntry } from "../schema/index.js" import { requestTTL } from "../cache-policy.js" import { resolveEffortUpdates } from "../effort-updates.js" +import { addsTools, toolUpdateKinds, type ToolUpdateEncoding } from "../tool-updates.js" import { OpenResponses } from "./open-responses.js" import { OpenResponsesOptions } from "./utils/open-responses-options.js" import { JsonObject, lenient, optionalArray, optionalNull, ProviderShared } from "./shared.js" @@ -173,6 +174,22 @@ const supportsEffortUpdates = (request: LLMRequest) => { return match !== null && Number(match[1]) >= 6 } +// `additional_tools` adds tools, and redefines one by name only when that one was declared through `additional_tools` +// too. So a model whose `tools.updates` includes "add" gets every tool the request declares in a leading +// `additional_tools` item instead of top-level `tools`; without "add" nothing goes in place. Later additions and +// redefinitions ("replace") are later items. The API can't withdraw a tool, so a removal ("remove") is announced in +// a developer message and the tool stays declared. Hosted tools stay in `tools`, since the model doesn't use one +// declared in `additional_tools`, and changing one folds. +const toolUpdates = { + kinds: ["add", "remove", "replace"], + placeable: (request) => declaresInPlace(request), + declarable: (tool) => !isHostedTool(tool), +} satisfies ToolUpdateEncoding + +const isHostedTool = (tool: ToolEntry) => tool.type === "tool" && tool.native !== undefined + +const declaresInPlace = (request: LLMRequest) => toolUpdateKinds(request).includes("add") + const nativeImageToolInput = (tool: ToolDefinition) => { const native = tool.native?.openai return ProviderShared.isRecord(native) && native.type === "image_generation" ? native : undefined @@ -216,11 +233,59 @@ const lowerToolEntry = Effect.fnUntraced(function* ( } }) -const lowerTools = (request: LLMRequest) => { - const custom = OpenAIFreeform.tools(request) - return Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, custom)) +// Lowers one request's tool updates, in message order. Every `additional_tools` item after the first is preceded by +// a hint that it adds to the tools declared before it, naming tools removed and not declared again since. Without +// it, models can read the latest item as the whole set. +const toolChangeLowering = (declaredInPlace: boolean, custom: ReadonlyMap) => { + let declared = declaredInPlace + const unavailable = new Set() + return Effect.fnUntraced(function* (changes: ToolChanges) { + changes.add.forEach((tool) => unavailable.delete(tool.name)) + const hint = declared && changes.add.length > 0 ? [developer(incrementalNotice([...unavailable]))] : [] + const additions = + changes.add.length === 0 + ? [] + : [ + { + type: "additional_tools" as const, + role: "developer" as const, + tools: yield* Effect.forEach(changes.add, (tool) => lowerToolEntry(tool, custom)), + }, + ] + declared = declared || changes.add.length > 0 + changes.remove.forEach((name) => unavailable.add(name)) + return [...hint, ...additions, ...(changes.remove.length === 0 ? [] : [developer(removalNotice(changes.remove))])] + }) } +const developer = (content: string) => ({ type: "message" as const, role: "developer" as const, content }) + +const incrementalNotice = (unavailable: ReadonlyArray) => + [ + "Tool update: the tools below are added to the ones you already have. Earlier tools stay available unless marked unavailable, and a tool declared again replaces its earlier definition.", + ...(unavailable.length === 0 ? [] : [`Still unavailable: ${unavailable.join(", ")}.`]), + ].join("\n") + +const removalNotice = (names: ReadonlyArray) => + `These tools are no longer available. Do not call them: ${names.join(", ")}.` + +// The leading declaration: top-level `tools`, or a leading `additional_tools` item on models that add tools in place. +const lowerToolLayout = Effect.fnUntraced(function* ( + request: LLMRequest, + custom: ReadonlyMap, +) { + const lower = (tools: ReadonlyArray) => Effect.forEach(tools, (tool) => lowerToolEntry(tool, custom)) + const declared = declaresInPlace(request) ? request.tools.filter((tool) => !isHostedTool(tool)) : [] + const top = declared.length === 0 ? request.tools : request.tools.filter(isHostedTool) + return { + head: + declared.length === 0 + ? [] + : [{ type: "additional_tools" as const, role: "developer" as const, tools: yield* lower(declared) }], + tools: top.length === 0 ? undefined : yield* lower(top), + } +}) + const lowerToolChoice = ( toolChoice: NonNullable, tools: ReadonlyArray, @@ -245,8 +310,14 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request: const updates = resolveEffortUpdates(request, options.reasoningEffort) const generation = OpenResponses.lowerGeneration(request, { ...options, reasoningEffort: updates.effort }) const custom = OpenAIFreeform.tools(request) + const layout = yield* lowerToolLayout(request, custom) + const conversation = yield* OpenResponses.lowerConversation(updates.request, { + ...adapter, + lowerToolChanges: toolChangeLowering(layout.head.length > 0, custom), + }) return { - ...(yield* OpenResponses.lowerConversation(updates.request, adapter)), + ...conversation, + input: [...layout.head, ...conversation.input], ...generation, ...Cache.openAIRequestTTL(requestTTL(request)), ...(generation.reasoning || reasoning.reasoningMode || reasoning.reasoningContext @@ -259,9 +330,9 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request: } : {}), context_management: management?.map((edit) => ({ type: edit.type, compact_threshold: edit.compactThreshold })), - tools: request.tools.length === 0 ? undefined : yield* lowerTools(request), + tools: layout.tools, tool_choice: - request.tools.length === 0 + request.tools.length === 0 && !addsTools(request) ? undefined : (OpenResponses.allowedToolChoice(options, custom) ?? (request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools, custom) : undefined)), @@ -334,6 +405,7 @@ export const protocol = Protocol.make({ : ProviderShared.eventError(ADAPTER, `${event.type} is missing item_id`) }), supportsEffortUpdates, + toolUpdates, }) const endpoint = Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }) @@ -350,7 +422,10 @@ export const transport = channelTransport({ export const route = Route.make({ compact: { - endpoint: ResponsesCompaction.make(adapter, lowerTools), + endpoint: ResponsesCompaction.make(adapter, (request) => { + const custom = OpenAIFreeform.tools(request) + return Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, custom)) + }), trigger: ResponsesCheckpoint.make(checkpointBody), }, id: ADAPTER, diff --git a/packages/ai/src/protocols/openrouter-video.ts b/packages/ai/src/protocols/openrouter-video.ts index 7843d03344dd..79d3faa8c59d 100644 --- a/packages/ai/src/protocols/openrouter-video.ts +++ b/packages/ai/src/protocols/openrouter-video.ts @@ -169,12 +169,12 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( if (urls.length === 0) return yield* output.invalid(`${route.name} completed without a video URL`) // The content URLs are OpenRouter's own and only download with the API key. const videos = yield* Effect.forEach(urls, (url) => - context.headers(url).pipe( - Effect.map((headers) => + context.credentials(url).pipe( + Effect.map((credentials) => Media.url(url, { mediaType: "video/mp4", expiresAt: job.expires_at === undefined || job.expires_at === null ? undefined : job.expires_at * 1000, - headers, + ...credentials, }), ), ), diff --git a/packages/ai/src/protocols/utils/gateway-protocol.ts b/packages/ai/src/protocols/utils/gateway-protocol.ts index 8fe8651dd54c..f6588a9fe2f0 100644 --- a/packages/ai/src/protocols/utils/gateway-protocol.ts +++ b/packages/ai/src/protocols/utils/gateway-protocol.ts @@ -64,6 +64,7 @@ export function gatewayProtocol( }), }, supportsEffortUpdates: protocol.supportsEffortUpdates, + toolUpdates: protocol.toolUpdates, sanitizer: protocol.sanitizer, stream: { event: protocol.stream.event, diff --git a/packages/ai/src/protocols/utils/responses-compaction.ts b/packages/ai/src/protocols/utils/responses-compaction.ts index 3500019b7b02..b096f3145471 100644 --- a/packages/ai/src/protocols/utils/responses-compaction.ts +++ b/packages/ai/src/protocols/utils/responses-compaction.ts @@ -12,6 +12,7 @@ import { } from "../../schema/index.js" import type { CompactOperation } from "../../route/client.js" import { stripEffortUpdates } from "../../effort-updates.js" +import { foldToolUpdates } from "../../tool-updates.js" import { Endpoint } from "../../route/endpoint.js" import { RequestExecutor } from "../../route/executor.js" import { HttpTransport } from "../../route/transport/index.js" @@ -86,10 +87,13 @@ export const make = ( ): CompactOperation => Effect.fn("ResponsesCompaction.execute")(function* (request, executor, options) { const route = request.model.route - // The standalone compaction endpoint rejects histories containing configuration updates. - const native = yield* OpenResponses.lowerConversation(stripEffortUpdates(request), adapter) + // The standalone compaction endpoint rejects effort updates (`configuration_update`). Every tool goes in + // top-level `tools`: after compacting a history whose tools were only in `additional_tools`, small models lost + // track of them more often. + const folded = foldToolUpdates(stripEffortUpdates(request)) + const native = yield* OpenResponses.lowerConversation(folded, adapter) const generation = OpenResponses.lowerGeneration(request) - const tools = request.tools.length === 0 ? undefined : yield* lowerTools(request) + const tools = folded.tools.length === 0 ? undefined : yield* lowerTools(folded) const body = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Body))( mergeJsonRecords( { diff --git a/packages/ai/src/providers/google-vertex-messages.ts b/packages/ai/src/providers/google-vertex-messages.ts index 97bb8e66d060..170b309ea45d 100644 --- a/packages/ai/src/providers/google-vertex-messages.ts +++ b/packages/ai/src/providers/google-vertex-messages.ts @@ -55,6 +55,7 @@ const route = Route.make({ }, stream: AnthropicMessages.protocol.stream, supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates, + toolUpdates: AnthropicMessages.protocol.toolUpdates, }), endpoint: Endpoint.path(({ request }) => `/${request.model.id}:streamRawPredict`), auth: Auth.none, diff --git a/packages/ai/src/public.ts b/packages/ai/src/public.ts index c319679a3d62..4254886d96cb 100644 --- a/packages/ai/src/public.ts +++ b/packages/ai/src/public.ts @@ -34,6 +34,7 @@ export { CompactionPart, EffortPart, ContentPart, + ToolChanges, Message, SystemMessage, UserMessage, @@ -188,6 +189,7 @@ export type { export type { ExecutableTool, Tool, + ToolChangesInput, ToolExecute, ToolExecuteContext, ToolInput, @@ -199,3 +201,4 @@ export type { } from "./tool.js" export type { LLM } from "./llm.js" export type { LLMLoopInput, LLMRequestInput } from "./llm.js" +export type { HttpHandler, HttpMiddleware } from "./route/executor-service.js" diff --git a/packages/ai/src/route/client.ts b/packages/ai/src/route/client.ts index 9781477d8f48..e4966fbf4ea2 100644 --- a/packages/ai/src/route/client.ts +++ b/packages/ai/src/route/client.ts @@ -8,6 +8,7 @@ import type { HttpMiddleware, Transport, TransportRuntime, WebSocketChannelExecu import type { Protocol } from "./protocol.js" import { applyCachePolicy } from "../cache-policy.js" import { applyEffortUpdates } from "../effort-updates.js" +import { mapToolUpdates, planToolUpdates, type ToolUpdateEncoding } from "../tool-updates.js" import { normalizeToolHistory } from "../tool-history.js" import { sanitizeSurrogates } from "../utils/sanitize.js" import * as ProviderShared from "../protocols/shared.js" @@ -65,6 +66,7 @@ export interface Route< readonly options?: RequestOptions readonly body: RouteBody readonly supportsEffortUpdates?: (request: LLMRequest) => boolean + readonly toolUpdates?: ToolUpdateEncoding readonly sanitizer?: LanguageModelSanitizerCompatibility readonly with: { ( @@ -376,6 +378,7 @@ function makeFromTransport( options: routeInput.options, body: protocol.body, supportsEffortUpdates: protocol.supportsEffortUpdates, + toolUpdates: protocol.toolUpdates, sanitizer: protocol.sanitizer, with: (patch: RoutePatch) => { const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...options } = patch @@ -547,8 +550,10 @@ const prepareRequest = (request: LLMRequest): LLMRequest => { [...new Map(tools.map((tool) => [`${tool.type}:${tool.name}`, tool])).values()].map((tool) => tool.type === "tool" ? tool : { ...tool, tools: dedupe(tool.tools) }, ) + const project = (tools: LLMRequest["tools"]) => ToolSchemaProjection.tools(dedupe(tools), sanitized.model) + const updated = planToolUpdates(sanitized) const resolved = applyCachePolicy( - applyEffortUpdates({ ...sanitized, tools: ToolSchemaProjection.tools(dedupe(sanitized.tools), sanitized.model) }), + applyEffortUpdates(mapToolUpdates({ ...updated, tools: project(updated.tools) }, project)), ) const headers = resolved.model.route.headers?.({ request: resolved }) return headers === undefined ? resolved : { ...resolved, headers: { ...headers, ...resolved.headers } } diff --git a/packages/ai/src/route/executor-service.ts b/packages/ai/src/route/executor-service.ts index 4eb33784d6eb..977c7dfa274d 100644 --- a/packages/ai/src/route/executor-service.ts +++ b/packages/ai/src/route/executor-service.ts @@ -1,4 +1,4 @@ -import { Context, type Effect } from "effect" +import { Context, Effect, Stream } from "effect" import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http" import { HttpContext, type AIError } from "../schema/errors.js" import type { ClientTls } from "../schema/options.js" @@ -34,6 +34,46 @@ export const CurrentTls = Context.Reference("@opencode/AI }) export type Service = RequestExecutorService +/** + * Middleware for every provider request made while it is set: model calls, media submits, polls, results and cancels, + * whatever the modality. Set it with {@link withMiddleware}. Downloads of a `url` asset don't use it; they use the + * asset's own `middleware`, which a route sets only for URLs on the provider's origin. + */ +export const CurrentMiddleware = Context.Reference( + "@opencode/AI/RequestExecutor/CurrentMiddleware", + { defaultValue: () => undefined }, +) + +/** `outer` wraps `inner`: it sees the request first and the response last. */ +export const composeMiddleware = ( + outer: HttpMiddleware | undefined, + inner: HttpMiddleware | undefined, +): HttpMiddleware | undefined => { + if (outer === undefined) return inner + if (inner === undefined) return outer + return (request, handler) => outer(request, (forwarded) => inner(forwarded, handler)) +} + +/** + * Runs `fn` on every provider request `self` makes, an Effect or a Stream. Inside an outer `withMiddleware`, the outer + * one wraps this one. Executor-wide middleware (`RequestExecutor.middleware`) wraps both. + */ +export const withMiddleware = + (fn: HttpMiddleware) => + | Stream.Stream>( + self: Self, + ): Self => { + const merged = Effect.gen(function* () { + return composeMiddleware(yield* CurrentMiddleware, fn) + }) + // One signature for both, so it infers inside `pipe`; each branch returns the same kind it was given. + return ( + Stream.isStream(self) + ? Stream.provideServiceEffect(self, CurrentMiddleware, merged) + : Effect.provideServiceEffect(self, CurrentMiddleware, merged) + ) as Self + } + export const headerDetails = (headers: Headers.Headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value])) diff --git a/packages/ai/src/route/executor.ts b/packages/ai/src/route/executor.ts index 51c789a8d146..f9b97c257f03 100644 --- a/packages/ai/src/route/executor.ts +++ b/packages/ai/src/route/executor.ts @@ -10,6 +10,8 @@ import { import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js" import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js" import { + composeMiddleware, + CurrentMiddleware, CurrentTls, headerDetails, responseHttp, @@ -19,7 +21,14 @@ import { } from "./executor-service.js" import type { ClientTls } from "../schema/options.js" -export { CurrentTls, responseHttp, Service } from "./executor-service.js" +export { + composeMiddleware, + CurrentMiddleware, + CurrentTls, + responseHttp, + Service, + withMiddleware, +} from "./executor-service.js" export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js" const normalizedHeaders = (headers: Headers.Headers) => @@ -254,7 +263,13 @@ export const layer: Layer.Layer = Layer.e return yield* statusError(response) }) return Service.of({ - execute: executeOnce, + // Scoped middleware runs outside per-call middleware. It is cleared while the request runs, so a request a + // middleware makes itself isn't wrapped again. + execute: (request, next) => + Effect.gen(function* () { + const middleware = composeMiddleware(yield* CurrentMiddleware, next) + return yield* executeOnce(request, middleware).pipe(Effect.provideService(CurrentMiddleware, undefined)) + }), }) }), ) @@ -285,18 +300,25 @@ export const withFetch = ( return middleware === undefined ? send : (request) => middleware(request, send) } -/** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */ +/** + * Run `fn` on every request: it sees the raw response before status classification, inside middleware already on + * `executor`, and outside per-call and scoped ({@link withMiddleware}) middleware. + */ export const middleware = (fn: HttpMiddleware, executor: Layer.Layer = fetchLayer): Layer.Layer => Layer.effect( Service, Effect.gen(function* () { const inner = yield* Service return Service.of({ + // Scoped middleware sits where per-call middleware does, inside `fn`; it is read here and cleared so the + // executors below don't apply it again. execute: (request, next) => - inner.execute( - request, - next === undefined ? fn : (input, handler) => fn(input, (forwarded) => next(forwarded, handler)), - ), + Effect.gen(function* () { + const scoped = composeMiddleware(yield* CurrentMiddleware, next) + return yield* inner + .execute(request, composeMiddleware(fn, scoped)) + .pipe(Effect.provideService(CurrentMiddleware, undefined)) + }), }) }), ).pipe(Layer.provide(executor)) diff --git a/packages/ai/src/route/media-protocol.ts b/packages/ai/src/route/media-protocol.ts index 5ca8f4bccb71..3abcb69cea20 100644 --- a/packages/ai/src/route/media-protocol.ts +++ b/packages/ai/src/route/media-protocol.ts @@ -93,10 +93,11 @@ export interface Started { export interface PollContext { readonly token: Token /** - * The headers an authenticated GET of `url` would send (deployment headers plus auth), for result URLs that need - * the API key to download. URLs on another origin than the route's base URL get no headers. + * What an authenticated download of `url` needs, for result URLs that only download with the API key: the headers a + * GET would send (deployment headers plus auth) and the caller's scoped middleware. Spread it into `Media.url`. URLs + * on another origin than the route's base URL get neither, so credentials and hooks never leave the provider's host. */ - readonly headers: (url: string) => Effect.Effect, AIError> + readonly credentials: (url: string) => Effect.Effect, AIError> /** * A further GET with the same auth and headers, retried like the poll itself, for providers whose result needs a * second lookup (MiniMax v1 answers with a file id that resolves to a download URL). diff --git a/packages/ai/src/route/media.ts b/packages/ai/src/route/media.ts index 37228f119882..c68aa219aa6c 100644 --- a/packages/ai/src/route/media.ts +++ b/packages/ai/src/route/media.ts @@ -205,7 +205,16 @@ export const queued = ( }) => get(operation.path(token)).pipe( Effect.flatMap((response) => - operation.decode(response, { token, get, headers: (url) => transport.headers(url, exchange) }), + operation.decode(response, { + token, + get, + credentials: (url) => + Effect.gen(function* () { + const headers = yield* transport.headers(url, exchange) + if (headers === undefined) return {} + return { headers, middleware: yield* RequestExecutor.CurrentMiddleware } + }), + }), ), ) const status = poll(protocol.status) @@ -399,7 +408,7 @@ const makeTransport = ( }), /** * The headers a follow-up GET of `url` sends, for result URLs that only download with the same credentials. A URL - * on another origin than the route's base URL gets none, so credentials never leave the provider's host. + * on another origin than the route's base URL gets undefined, so credentials never leave the provider's host. */ headers: (url: string, exchange: Exchange) => URL.canParse(url) && new URL(url).origin === baseURL("").origin @@ -409,8 +418,8 @@ const makeTransport = ( url, body: "", headers: Headers.fromInput(exchange.headers), - }).pipe(Effect.map((headers): Record => ({ ...headers }))) - : Effect.succeed({}), + }).pipe(Effect.map((headers): Record | undefined => ({ ...headers }))) + : Effect.succeed(undefined), /** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */ call: (method: AuthInput["method"], path: string, exchange: Exchange, execute: Execute) => { // Provider-issued absolute URLs are used as-is; everything else resolves against the base. diff --git a/packages/ai/src/route/protocol.ts b/packages/ai/src/route/protocol.ts index 89c8d536108f..69a83694105d 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 type { ToolUpdateEncoding } from "../tool-updates.js" /** * The semantic API contract of one model server family. @@ -43,6 +44,8 @@ export interface Protocol { readonly stream: ProtocolStream /** Whether `body.from` lowers `Message.effort(...)` markers; wrappers around another `body.from` must forward it. */ 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 /** 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 } diff --git a/packages/ai/src/schema/messages.ts b/packages/ai/src/schema/messages.ts index 78e9fd930901..d735f4003b1a 100644 --- a/packages/ai/src/schema/messages.ts +++ b/packages/ai/src/schema/messages.ts @@ -15,6 +15,7 @@ import { import { ProviderID } from "./ids.js" import { Media } from "../media.js" import { Json } from "../utils/json.js" +import type { ToolChangesInput } from "../tool.js" export const MessageRole = Schema.Literals(["system", "user", "assistant", "tool"]) export type MessageRole = Schema.Schema.Type @@ -241,10 +242,18 @@ export const ContentPart = Schema.Union([ ]).pipe(Schema.toTaggedUnion("type")) export type ContentPart = Schema.Schema.Type +/** Tools changed here: `add` appends or redefines tools by name, `remove` drops them by name. */ +export const ToolChanges = Schema.Struct({ + add: Schema.Array(Schema.suspend((): Schema.Codec => ToolEntry)), + remove: Schema.Array(Schema.String), +}).annotate({ identifier: "LLM.ToolChanges" }) +export type ToolChanges = Schema.Schema.Type + export class SystemMessage extends Schema.Class("LLM.SystemMessage")({ id: Schema.optional(Schema.String), role: Schema.Literal("system"), content: Schema.Array(Schema.Union([TextPart, EffortPart]).pipe(Schema.toTaggedUnion("type"))), + tools: Schema.optional(ToolChanges), }) {} export class UserMessage extends Schema.Class("LLM.UserMessage")({ @@ -287,9 +296,9 @@ export namespace Message { > type RoleInput = Omit & { readonly content: Content } export type SystemInput = RoleInput< - ConstructorParameters[0], + Omit[0], "tools">, ContentInput - > + > & { readonly tools?: ToolChangesInput } export type UserInput = RoleInput[0], UserContentInput> export type AssistantInput = RoleInput[0], AssistantContentInput> export type ToolInput = RoleInput< @@ -328,8 +337,15 @@ function make(input: ToolMessage | Message.ToolInput): ToolMessage function make(input: Message | Message.Input): Message function make(input: Message | Message.Input): Message { switch (input.role) { - case "system": - return input instanceof SystemMessage ? input : new SystemMessage({ ...input, content: content(input.content) }) + case "system": { + if (input instanceof SystemMessage) return input + const { tools, ...rest } = input + return new SystemMessage({ + ...rest, + content: content(input.content), + ...(tools === undefined ? {} : { tools: toolChanges(tools) }), + }) + } case "user": return input instanceof UserMessage ? input @@ -365,10 +381,21 @@ export const Message = withStatics(messageSchema, { system: (input: Message.SystemContentInput) => make({ role: "system", content: input }), effort: (input: { readonly effort?: ReasoningEffort; readonly previous?: ReasoningEffort }) => make({ role: "system", content: [{ type: "effort", effort: input.effort, previous: input.previous }] }), + /** + * Change the available tools at this point. A route sends the change in place when the model's `tools.updates` + * allows it, and otherwise folds it into the top-level `tools`. Returns message input that keeps the tool objects, + * so `ai.loop` can run an executable tool added here. + */ + tools: (input: ToolChangesInput) => ({ role: "system" as const, content: [], tools: input }), tool: (result: ToolResultPart | Parameters[0]) => make({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] }), }) +const toolChanges = (input: ToolChangesInput): ToolChanges => ({ + add: (input.add ?? []).map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))), + remove: (input.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)), +}) + /** * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input. diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index 48bb876901c6..bfe88ad7a8ef 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -249,8 +249,16 @@ export interface Capabilities { readonly search?: boolean /** Input formats accepted by custom (free-form) tools. */ readonly freeform?: ReadonlyArray<"text" | "lark" | "regex"> - /** Accepts a changed tool list mid-conversation. */ - readonly updates?: boolean + /** + * Tool changes the model takes mid-conversation without changing the leading tool declaration, so the prompt + * cache holds. `add`: declares a tool not declared before. `remove`: withdraws a declared tool. `replace`: + * declares a tool under a name declared before (a redefinition, or re-adding a removed tool). Unset or empty: + * every change folds into the top-level tools. Anthropic Messages sends all three as native blocks. OpenAI + * Responses needs `add` for any of them: it declares every tool in `additional_tools` items with a short + * incremental-update hint before each later item, and announces a removal as developer text while the tool + * stays declared, so list `remove` only for models that follow that announcement. + */ + readonly updates?: ReadonlyArray<"add" | "remove" | "replace"> } readonly reasoning?: { readonly supported?: boolean diff --git a/packages/ai/src/tool-updates.ts b/packages/ai/src/tool-updates.ts new file mode 100644 index 000000000000..6f721e1c82c7 --- /dev/null +++ b/packages/ai/src/tool-updates.ts @@ -0,0 +1,139 @@ +// A request's top-level `tools` is shorthand for a leading `Message.tools({ add: tools })`: tool state is one +// ordered list of declarations, that leading one and then each marker in message order. Folding the whole list +// gives the tools a route without in-place changes sends. A protocol that can send some changes in place keeps +// them where they are, so the leading declaration, and the prompt cache behind it, stays fixed. +import { Message, SystemMessage, type LLMRequest, type ToolChanges, type ToolEntry } from "./schema/messages.js" +import type { Capabilities } from "./schema/options.js" +import { flattenTools } from "./protocols/shared.js" + +export type ToolUpdate = NonNullable["updates"]>[number] + +/** What a protocol can send in place of a `Message.tools(...)` marker; the model's `tools.updates` narrows it. */ +export interface ToolUpdateEncoding { + readonly kinds: ReadonlyArray + /** Whether the marker at this message index can be sent where it is. Defaults to anywhere. */ + readonly placeable?: (request: LLMRequest, index: number) => boolean + /** Whether a tool can be added or removed in place. Defaults to every tool. */ + readonly declarable?: (tool: ToolEntry) => boolean +} + +export const toolsUpdate = (message: Message): ToolChanges | undefined => + message.role === "system" ? message.tools : undefined + +/** Whether any marker adds a tool, so a request without top-level tools still declares some. */ +export const addsTools = (request: LLMRequest) => + request.messages.some((message) => (toolsUpdate(message)?.add.length ?? 0) > 0) + +/** The changes this route sends in place: the model's `tools.updates` that the protocol's encoding covers. */ +export const toolUpdateKinds = (request: LLMRequest) => { + const encoding = request.model.route.toolUpdates + return (request.model.capabilities?.tools?.updates ?? []).filter((kind) => encoding?.kinds.includes(kind)) +} + +/** Apply one change: removals first, then additions replace a same-named tool in place or append. */ +export const foldTools = ( + tools: ReadonlyArray, + add: ReadonlyArray, + remove: ReadonlyArray, +): ReadonlyArray => { + const added = new Map(add.map((tool) => [tool.name, tool])) + const kept = tools.filter((tool) => !remove.includes(tool.name)).map((tool) => added.get(tool.name) ?? tool) + const names = new Set(kept.map((tool) => tool.name)) + return [...kept, ...[...added.values()].filter((tool) => !names.has(tool.name))] +} + +/** + * Fold the declarations up to the last one this route can't send in place into the leading one (the request's + * `tools`), and keep later markers in place, trimmed to their effective changes. Protocols send kept markers in + * message order and track what they need along the way. A marker is sent in place only after the conversation starts, when the model's + * `tools.updates` and the protocol's encoding both cover what it does: `add` a new name, `replace` a name declared + * before (even if removed since), `remove` a current tool. Removing a name that matches no current tool does nothing. + */ +export const planToolUpdates = (request: LLMRequest): LLMRequest => plan(request, toolUpdateKinds(request)) + +/** Fold every marker into the top-level tools, as a route without in-place tool changes sends them. */ +export const foldToolUpdates = (request: LLMRequest): LLMRequest => plan(request, []) + +const plan = (request: LLMRequest, supported: ReadonlyArray): LLMRequest => { + const changes = request.messages.flatMap((message, index) => + message.role === "system" && message.tools !== undefined ? [{ index, ...message.tools }] : [], + ) + if (changes.length === 0) return request + const encoding = request.model.route.toolUpdates + const declarable = (tool: ToolEntry) => encoding?.declarable?.(tool) ?? true + const firstTurn = request.messages.findIndex((message) => message.role !== "system") + const steps = changes.reduce<{ + readonly tools: ReadonlyArray + readonly declared: ReadonlySet + readonly steps: ReadonlyArray + }>( + (state, change) => { + const added = change.add.map((tool) => tool.name) + const removed = state.tools.filter((tool) => change.remove.includes(tool.name) && !added.includes(tool.name)) + const tools = foldTools(state.tools, change.add, change.remove) + const kinds = [ + ...(removed.length > 0 || withdrawnTools(state.tools, tools).length > 0 ? ["remove" as const] : []), + ...added.map((name) => (state.declared.has(name) ? ("replace" as const) : ("add" as const))), + ] + const native = + firstTurn !== -1 && + change.index > firstTurn && + kinds.every((kind) => supported.includes(kind)) && + [...change.add, ...removed].every(declarable) && + (encoding?.placeable?.(request, change.index) ?? true) + const step = { + index: change.index, + native, + tools, + changes: { add: change.add, remove: removed.map((tool) => tool.name) }, + } + return { tools, declared: new Set([...state.declared, ...added]), steps: [...state.steps, step] } + }, + { tools: request.tools, declared: new Set(request.tools.map((tool) => tool.name)), steps: [] }, + ).steps + const cut = steps.findLastIndex((step) => !step.native) + const kept = new Map(steps.slice(cut + 1).map((step) => [step.index, step.changes])) + return { + ...request, + tools: cut === -1 ? request.tools : steps[cut]!.tools, + messages: request.messages.flatMap((message, index) => { + if (message.role !== "system" || message.tools === undefined) return [message] + const tools = kept.get(index) + if (tools !== undefined && (tools.add.length > 0 || tools.remove.length > 0)) + return [new SystemMessage({ ...message, tools })] + if (message.content.length === 0) return [] + return [new SystemMessage({ id: message.id, role: "system", content: message.content })] + }), + } +} + +interface PlanStep { + readonly index: number + readonly native: boolean + readonly tools: ReadonlyArray + readonly changes: ToolChanges +} + +/** Flattened names of the tools in `before` that `after` no longer has, including tools a redefined namespace drops. */ +export const withdrawnTools = (before: ReadonlyArray, after: ReadonlyArray) => { + const kept = new Set(toolNames(after)) + return toolNames(before).filter((name) => !kept.has(name)) +} + +const toolNames = (tools: ReadonlyArray) => flattenTools(tools).map((tool) => tool.name) + +/** Rewrite the tools each marker adds, keeping the request identity when there are no markers. */ +export const mapToolUpdates = ( + request: LLMRequest, + f: (tools: ReadonlyArray) => ReadonlyArray, +): LLMRequest => { + if (!request.messages.some((message) => toolsUpdate(message) !== undefined)) return request + return { + ...request, + messages: request.messages.map((message) => + message.role === "system" && message.tools !== undefined + ? new SystemMessage({ ...message, tools: { ...message.tools, add: f(message.tools.add) } }) + : message, + ), + } +} diff --git a/packages/ai/src/tool.ts b/packages/ai/src/tool.ts index 0f5858e1f581..f279078f5779 100644 --- a/packages/ai/src/tool.ts +++ b/packages/ai/src/tool.ts @@ -6,7 +6,13 @@ import type { ToolDefinition as ToolDefinitionClass, ToolOutput as ToolOutputType, } from "./schema/index.js" -import { ToolDefinition, ToolFailure, ToolOutput, type ToolDefinitionInput } from "./schema/index.js" +import { + ToolDefinition, + ToolFailure, + ToolOutput, + type ToolDefinitionInput, + type ToolEntryInput, +} from "./schema/index.js" import { isRecord } from "./utils/record.js" /** @@ -95,6 +101,12 @@ export interface Tool + readonly remove?: ReadonlyArray +} + /** A tool with an `execute` handler, which `LLM.loop` and `ToolRuntime.dispatch` can run. */ export type ExecutableTool = any> = Tool< Input, diff --git a/packages/ai/test/executor.test.ts b/packages/ai/test/executor.test.ts index 94e272456a25..2458c3f3eca8 100644 --- a/packages/ai/test/executor.test.ts +++ b/packages/ai/test/executor.test.ts @@ -305,6 +305,77 @@ describe("RequestExecutor", () => { ) }) + it.effect("runs scoped middleware between shared and per-call middleware, outer scopes first", () => { + const calls: Array = [] + const record = + (name: string): HttpMiddleware => + (input, next) => + Effect.sync(() => calls.push(name)).pipe(Effect.andThen(next(input))) + const base = RequestExecutor.layer.pipe( + Layer.provide( + handlerLayer((input) => Effect.sync(() => calls.push("handler")).pipe(Effect.as(input.respond("ok")))), + ), + ) + return Effect.gen(function* () { + const executor = yield* RequestExecutor.Service + yield* executor + .execute(request, record("per-call")) + .pipe(RequestExecutor.withMiddleware(record("inner")), RequestExecutor.withMiddleware(record("outer"))) + expect(calls).toEqual(["shared", "outer", "inner", "per-call", "handler"]) + calls.length = 0 + // Outside the scope, nothing scoped runs. + yield* executor.execute(request) + expect(calls).toEqual(["shared", "handler"]) + }).pipe(Effect.provide(RequestExecutor.middleware(record("shared"), base))) + }) + + it.effect("applies scoped middleware to a stream and to requests sent through a per-request fetch", () => { + const seen: Array = [] + const scoped: HttpMiddleware = (input, next) => + Effect.sync(() => seen.push(input.url)).pipe(Effect.andThen(next(input))) + const fetch: typeof globalThis.fetch = Object.assign(async () => new Response("from fetch"), { + preconnect: globalThis.fetch.preconnect, + }) + return Effect.gen(function* () { + const executor = yield* RequestExecutor.Service + const body = yield* RequestExecutor.stream(executor, request).pipe( + Stream.decodeText(), + Stream.mkString, + RequestExecutor.withMiddleware(scoped), + ) + expect(body).toBe("ok") + const fetched = yield* executor + .execute(sseRequest, RequestExecutor.withFetch(fetch)) + .pipe(RequestExecutor.withMiddleware(scoped)) + expect(yield* fetched.text).toBe("from fetch") + expect(seen).toEqual([request.url, sseRequest.url]) + }).pipe( + Effect.provide( + RequestExecutor.layer.pipe(Layer.provide(handlerLayer((input) => Effect.succeed(input.respond("ok"))))), + ), + ) + }) + + it.effect("doesn't wrap a request that scoped middleware sends itself", () => { + let wrapped = 0 + return Effect.gen(function* () { + const executor = yield* RequestExecutor.Service + const scoped: HttpMiddleware = (input, next) => + Effect.gen(function* () { + wrapped++ + // Such as a token refresh made from inside an auth hook. + yield* executor.execute(sseRequest).pipe(Effect.orDie) + return yield* next(input) + }) + yield* executor.execute(request).pipe(RequestExecutor.withMiddleware(scoped)) + expect(wrapped).toBe(1) + }).pipe( + Effect.provide( + RequestExecutor.layer.pipe(Layer.provide(handlerLayer((input) => Effect.succeed(input.respond("ok"))))), + ), + ) + }) + it.effect("classifies context overflow responses", () => Effect.gen(function* () { const executor = yield* RequestExecutor.Service diff --git a/packages/ai/test/http-hooks.test.ts b/packages/ai/test/http-hooks.test.ts new file mode 100644 index 000000000000..fd273b02d016 --- /dev/null +++ b/packages/ai/test/http-hooks.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer } from "effect" +import { HttpClientResponse } from "effect/http" +import { AI, AIError, Media } from "../src/index.js" +import { RequestExecutor, type HttpMiddleware } from "../src/route.js" +import { AssemblyAI, OpenAI, XAI } from "../src/providers.js" +import { handlerLayer } from "./lib/http.js" + +// Every Promise method that talks to a provider must send its requests through the caller's `http` middleware. The +// Promise client runs the Effect API under `RequestExecutor.withMiddleware`, so this covers the Effect side too. +// Adding a method to the client fails "lists every method" until it is listed here: as a provider call, with a way to +// call it, or as a local helper. + +const openai = OpenAI.configure({ apiKey: "test", baseURL: "https://openai.test/v1" }) +const video = XAI.configure({ apiKey: "test", baseURL: "https://xai.test/v1" }).video("grok-imagine-video-1.5") +const transcription = AssemblyAI.configure({ apiKey: "test", baseURL: "https://assemblyai.test" }).transcription( + "universal-2", +) +const audio = Media.bytes(Uint8Array.from([0x49, 0x44, 0x33, 1, 2, 3]), "audio/mpeg") +const image = openai.image("gpt-image-2") +const chat = { model: openai.chat("gpt-4o-mini"), prompt: "Hello" } + +type Client = ReturnType +type Call = (ai: Client, http: HttpMiddleware) => Promise | AsyncIterable + +const providerCalls: Record = { + generate: (ai, http) => ai.generate(chat, { http }), + stream: (ai, http) => ai.stream(chat, { http }), + loop: (ai, http) => ai.loop(chat, { http }), + compact: (ai, http) => ai.compact(ai.request({ model: openai.responses("gpt-5"), prompt: "Hello" }), { http }), + "image.generate": (ai, http) => ai.image.generate({ model: image, prompt: "A lighthouse" }, { http }), + "image.stream": (ai, http) => ai.image.stream({ model: image, prompt: "A lighthouse" }, { http }), + "image.start": (ai, http) => ai.image.start({ model: image, prompt: "A lighthouse" }, { http }), + "image.status": (ai, http) => ai.image.status(image, "job", { http }), + "image.result": (ai, http) => ai.image.result(image, "job", { http }), + "image.cancel": (ai, http) => ai.image.cancel(image, "job", { http }), + "decision.generate": (ai, http) => + ai.decision.generate( + { + model: openai.decision("gpt-6-luna"), + input: "Is this a greeting? hello", + questions: [{ name: "greeting", type: "choice", instructions: "Greeting?", choices: [{ value: true }] }], + }, + { http }, + ), + "embedding.generate": (ai, http) => + ai.embedding.generate({ model: openai.embedding("text-embedding-3-small"), values: ["hello"] }, { http }), + "video.start": (ai, http) => ai.video.start({ model: video, prompt: "A balloon" }, { http }), + "video.status": (ai, http) => ai.video.status(video, "job", { http }), + "video.result": (ai, http) => ai.video.result(video, "job", { http }), + "video.cancel": (ai, http) => ai.video.cancel(video, "job", { http }), + "experimental.speech.generate": (ai, http) => + ai.experimental.speech.generate({ model: openai.speech("gpt-4o-mini-tts"), text: "Hello" }, { http }), + "experimental.speech.stream": (ai, http) => + ai.experimental.speech.stream({ model: openai.speech("gpt-4o-mini-tts"), text: "Hello" }, { http }), + "experimental.transcription.generate": (ai, http) => + ai.experimental.transcription.generate({ model: transcription, audio }, { http }), + "experimental.transcription.stream": (ai, http) => + ai.experimental.transcription.stream({ model: transcription, audio }, { http }), + "experimental.transcription.start": (ai, http) => + ai.experimental.transcription.start({ model: transcription, audio }, { http }), + "experimental.transcription.resume": (ai, http) => + ai.experimental.transcription.resume(transcription, { transcriptID: "tr_1" }, { http }), +} + +// No provider request of their own: request builders, local folds and asset helpers. Downloads use the asset's own +// `middleware` instead (see `Media.Asset`). +const local = [ + "run", + "bytes", + "base64", + "materialize", + "file", + "write", + "request", + "collect", + "canCompact", + "image.request", + "decision.request", + "embedding.request", + "video.request", + "experimental.speech.request", + "experimental.transcription.request", + "dispose", +] + +const methods = (value: object, prefix = ""): Array => + Object.entries(value).flatMap(([key, entry]) => { + if (typeof entry === "function") return [`${prefix}${key}`] + if (typeof entry === "object" && entry !== null) return methods(entry, `${prefix}${key}.`) + return [] + }) + +const settle = async (result: Promise | AsyncIterable) => { + if (Symbol.asyncIterator in result) { + for await (const _ of result) break + return + } + await result +} + +describe("http middleware", () => { + test("lists every method", () => { + const ai = AI.make() + expect(methods(ai).toSorted()).toEqual([...Object.keys(providerCalls), ...local].toSorted()) + }) + + for (const [name, call] of Object.entries(providerCalls)) + test(`${name} sends its requests through the caller's http`, async () => { + const hooked: Array = [] + const unhooked: Array = [] + const ai = AI.make({ + layer: RequestExecutor.layer.pipe( + Layer.provide( + handlerLayer((input) => + Effect.sync(() => unhooked.push(input.request.url)).pipe(Effect.andThen(Effect.die("unhooked request"))), + ), + ), + ), + }) + // Answers 400 so the call stops at once: a transport failure would be retried. + const http: HttpMiddleware = (request) => + Effect.sync(() => { + hooked.push(request.url) + return HttpClientResponse.fromWeb(request, new Response("{}", { status: 400 })) + }) + const error = await settle(call(ai, http)).then( + () => undefined, + (error: unknown) => error, + ) + await ai.dispose() + expect(unhooked).toEqual([]) + // A route that can't do the operation (no queued image route ships, xAI can't cancel) fails before any request. + if (error instanceof AIError && error.reason._tag === "UnsupportedOperation") return + expect(hooked.length).toBeGreaterThan(0) + }) +}) diff --git a/packages/ai/test/openrouter-video.test.ts b/packages/ai/test/openrouter-video.test.ts index 2f7f20b71766..9b955a9658b2 100644 --- a/packages/ai/test/openrouter-video.test.ts +++ b/packages/ai/test/openrouter-video.test.ts @@ -1,7 +1,8 @@ import { describe, expect } from "bun:test" -import { Effect, Layer } from "effect" +import { Effect, Layer, Stream } from "effect" import { Media, VideoClient, ai } from "../src/effect.js" import { OpenRouter } from "../src/providers.js" +import { RequestExecutor, type HttpMiddleware } from "../src/route.js" import { it } from "./lib/effect.js" import { dynamicResponse, json, observe, type Call, type HandlerInput } from "./lib/http.js" @@ -202,10 +203,40 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { }), ) + it.effect("keeps the caller's scoped middleware for a download on the provider's host, and drops it on another", () => + Effect.gen(function* () { + const hooked: Array = [] + const hook: HttpMiddleware = (input, next) => + Effect.sync(() => hooked.push(input.url)).pipe(Effect.andThen(next(input))) + const cdn = "https://cdn.example.test/video.mp4" + const respond = (input: HandlerInput) => { + if (input.request.url.endsWith("/content?index=0") || input.request.url === cdn) + return input.respond(Uint8Array.from([1]), { headers: { "content-type": "video/mp4" } }) + return json(input, input.request.url.endsWith("other") ? { ...completed, unsigned_urls: [cdn] } : completed) + } + yield* Effect.gen(function* () { + // Read inside the scope; downloaded after it ends, as a caller storing the result later would. + const own = yield* ai.video.result(model, id).pipe(RequestExecutor.withMiddleware(hook)) + yield* own.video.stream().pipe(Stream.runDrain) + // Downloaded inside the scope, but the URL isn't the provider's. + yield* Effect.gen(function* () { + const other = yield* ai.video.result(model, "other") + yield* other.video.stream().pipe(Stream.runDrain) + }).pipe(RequestExecutor.withMiddleware(hook)) + }).pipe(Effect.provide(layer((input) => Effect.succeed(respond(input))))) + expect(hooked).toEqual([ + "https://openrouter.test/api/v1/videos/gen-vid-1-abc", + "https://openrouter.test/api/v1/videos/gen-vid-1-abc/content?index=0", + "https://openrouter.test/api/v1/videos/other", + ]) + }), + ) + it.effect("attaches no credentials to a result URL on another host", () => Effect.gen(function* () { const response = yield* ai.video.result(model, id) - expect(response.video.headers).toEqual({}) + expect(response.video.headers).toBeUndefined() + expect(response.video.middleware).toBeUndefined() }).pipe( Effect.provide( layer((input) => diff --git a/packages/ai/test/promise-parity.types.ts b/packages/ai/test/promise-parity.types.ts index ce0b1027dc30..85cdf56aafb7 100644 --- a/packages/ai/test/promise-parity.types.ts +++ b/packages/ai/test/promise-parity.types.ts @@ -1,10 +1,10 @@ import type { Effect, Stream } from "effect" -import type { Client, GenerationHandle } from "../src/index.js" +import type { Client, GenerationHandle, RunOptions } from "../src/index.js" import type { Generation, ai } from "../src/effect.js" // The Promise `ai` mirrors the Effect `ai`: same namespaces, methods, arguments and results. The only allowed differences -// are `signal` on the options bag, Promise for Effect, AsyncIterable for Stream (in results and arguments) and -// GenerationHandle for Generation. +// are `RunOptions` (`signal`, `http`) on the options bag, Promise for Effect, AsyncIterable for Stream (in results and +// arguments) and GenerationHandle for Generation. type Equal = [A, B] extends [B, A] ? true : false type Assert> = T @@ -27,17 +27,17 @@ type Signatures = F extends { : never type Positional

= P extends readonly [infer A, ...infer Rest] - ? [Iterated>, ...Positional] + ? [Iterated>, ...Positional] : [] type Iterated = T extends Stream.Stream ? AsyncIterable : T // Paired with its keys: an options bag of optional fields is otherwise assignable to `{}` and back. type Options

= P extends readonly [unknown, ...infer Rest] ? Options : P extends readonly [(infer O)?] - ? Keyed>> + ? Keyed>> : Keyed<{}> type Keyed = [keyof T, T] -type WithoutSignal = T extends { readonly signal?: AbortSignal } ? Omit : T +type WithoutRunOptions = T extends object ? Omit : T type Promised = R extends Effect.Effect, infer _E, infer _R> diff --git a/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts b/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts index 3f2e7c28c087..c5dd2d20c1c1 100644 --- a/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts +++ b/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { ai, LanguageModel, LLMEvent, LLMResponse } from "../../src/effect.js" +import { ai, LLMEvent, LLMResponse } from "../../src/effect.js" import * as OpenAICompatible from "../../src/providers/openai-compatible.js" import * as OpenRouter from "../../src/providers/openrouter.js" import { LLMClient } from "../../src/route.js" @@ -11,28 +11,22 @@ import { expectWeatherToolLoop, goldenWeatherToolLoopRequest, runWeatherToolLoop const cases = [ { name: "OpenRouter", - model: LanguageModel.update( - OpenRouter.configure({ - apiKey: process.env.OPENROUTER_API_KEY ?? "fixture", - providerOptions: { reasoning: { max_tokens: 1024 } }, - }).model("anthropic/claude-sonnet-4.6"), - { compatibility: { reasoningField: "reasoning" } }, - ), + model: OpenRouter.configure({ + apiKey: process.env.OPENROUTER_API_KEY ?? "fixture", + providerOptions: { reasoning: { max_tokens: 1024 } }, + }).model("anthropic/claude-sonnet-4.6"), requires: ["OPENROUTER_API_KEY"], cassette: "openrouter-reasoning", structured: true, }, { name: "Vercel AI Gateway", - model: LanguageModel.update( - OpenAICompatible.configure({ - provider: "vercel-ai-gateway", - baseURL: "https://ai-gateway.vercel.sh/v1", - apiKey: process.env.AI_GATEWAY_API_KEY ?? "fixture", - http: { body: { reasoning: { enabled: true, max_tokens: 1024 } } }, - }).model("anthropic/claude-sonnet-4.6"), - { compatibility: { reasoningField: "reasoning" } }, - ), + model: OpenAICompatible.configure({ + provider: "vercel-ai-gateway", + baseURL: "https://ai-gateway.vercel.sh/v1", + apiKey: process.env.AI_GATEWAY_API_KEY ?? "fixture", + http: { body: { reasoning: { enabled: true, max_tokens: 1024 } } }, + }).model("anthropic/claude-sonnet-4.6"), requires: ["AI_GATEWAY_API_KEY"], cassette: "vercel-ai-gateway-reasoning", structured: true, diff --git a/packages/ai/test/provider/openai-chat.test.ts b/packages/ai/test/provider/openai-chat.test.ts index 026109ed5051..a64cd89c1bff 100644 --- a/packages/ai/test/provider/openai-chat.test.ts +++ b/packages/ai/test/provider/openai-chat.test.ts @@ -1332,6 +1332,85 @@ describe("OpenAI Chat route", () => { }), ) + // A mid-session model switch can keep the same provider metadata key while the new model reads reasoning from a + // declared field of its own; details replayed from the earlier model are refused by some endpoints. + it.effect("does not replay reasoning details when the model declares another reasoning field", () => + Effect.gen(function* () { + const details = [ + { type: "reasoning.text", text: "thinking", signature: "signed", format: "anthropic-claude-v1", index: 0 }, + ] + const replay = yield* compileRequest( + ai.request({ + model: LanguageModel.update(model, { compatibility: { reasoningField: "reasoning_content" } }), + messages: [ + Message.assistant([ + { + type: "reasoning", + text: "thinking", + providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } }, + }, + { type: "text", text: "Hello" }, + ]), + ], + }), + ) + + expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_content: "thinking" }]) + }), + ) + + it.effect("keeps replayed reasoning details when the model declares reasoning_details", () => + Effect.gen(function* () { + const details = [ + { type: "reasoning.text", text: "thinking", signature: "signed", format: "anthropic-claude-v1", index: 0 }, + ] + const replay = yield* compileRequest( + ai.request({ + model: LanguageModel.update(model, { compatibility: { reasoningField: "reasoning_details" } }), + messages: [ + Message.assistant([ + { + type: "reasoning", + text: "thinking", + providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } }, + }, + { type: "text", text: "Hello" }, + ]), + ], + }), + ) + + expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_details: details }]) + }), + ) + + it.effect("keeps replayed reasoning details when the model declares no reasoning field", () => + Effect.gen(function* () { + const details = [ + { type: "reasoning.text", text: "thinking", signature: "signed", format: "anthropic-claude-v1", index: 0 }, + ] + const replay = yield* compileRequest( + ai.request({ + model, + messages: [ + Message.assistant([ + { + type: "reasoning", + text: "thinking", + providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: details } }, + }, + { type: "text", text: "Hello" }, + ]), + ], + }), + ) + + expect(replay.body.messages).toEqual([ + { role: "assistant", content: "Hello", reasoning: "thinking", reasoning_details: details }, + ]) + }), + ) + it.effect("reports the cost the endpoint billed", () => Effect.gen(function* () { const response = yield* LLMClient.generate(request).pipe( diff --git a/packages/ai/test/tool-updates.test.ts b/packages/ai/test/tool-updates.test.ts new file mode 100644 index 000000000000..932f7d6f43f5 --- /dev/null +++ b/packages/ai/test/tool-updates.test.ts @@ -0,0 +1,849 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema, Stream } from "effect" +import { + ai, + LLMEvent, + Message, + tool, + ToolCallPart, + ToolDefinition, + ToolNamespace, + type LLMRequest, +} from "../src/effect.js" +import { AI } from "../src/index.js" +import { Gemini } from "../src/protocols/gemini.js" +import { TestLLM } from "../src/testing.js" +import { Auth } from "../src/route.js" +import { compileRequest } from "../src/route/client.js" +import { AnthropicMessages } from "../src/protocols/anthropic-messages.js" +import { OpenAIChat } from "../src/protocols/openai-chat.js" +import { OpenAIResponses } from "../src/protocols/openai-responses.js" +import { gatewayProtocol } from "../src/protocols/utils/gateway-protocol.js" +import { GoogleVertexMessages, OpenAI } from "../src/providers.js" +import { planToolUpdates, type ToolUpdate } from "../src/tool-updates.js" +import { it, testEffect } from "./lib/effect.js" +import { dynamicResponse } from "./lib/http.js" + +const defineTool = (name: string, description = `${name} tool`) => + ToolDefinition.make({ name, description, inputSchema: { type: "object" } }) + +const read = defineTool("read") +const edit = defineTool("edit") +const write = defineTool("write") +const jira = defineTool("jira") +const lookup = tool({ + name: "lookup", + description: "Look something up.", + input: Schema.Struct({ query: Schema.String }), + success: Schema.String, + execute: ({ query }) => Effect.succeed(`found ${query}`), +}) + +const ALL: ReadonlyArray = ["add", "remove", "replace"] +const updates = (list: ReadonlyArray) => ({ tools: { updates: list } }) + +const anthropic = (id: string, list?: ReadonlyArray) => + AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id, capabilities: list === undefined ? undefined : updates(list) }) + +const openai = (id: string, list?: ReadonlyArray) => + OpenAIResponses.route + .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") }) + .model({ id, capabilities: list === undefined ? undefined : updates(list) }) + +const chat = OpenAIChat.route + .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") }) + .model({ id: "gpt-4.1-mini", capabilities: updates(ALL) }) + +const gemini = Gemini.route + .with({ + endpoint: { baseURL: "https://generativelanguage.test/v1beta/" }, + auth: Auth.header("x-goog-api-key", "test"), + }) + .model({ id: "gemini-3.5-flash", capabilities: updates(ALL) }) + +const opus5 = anthropic("claude-opus-5", ALL) +const astra = openai("gpt-6-astra", ALL) + +const swap = Message.tools({ add: [write], remove: ["edit"] }) +const conversation = [Message.user("Fix it."), Message.assistant("Done."), swap, Message.user("Next.")] +const folded = [Message.user("Fix it."), Message.assistant("Done."), Message.user("Next.")] + +const names = (request: LLMRequest) => request.tools.map((entry) => entry.name) +const markers = (request: LLMRequest) => + request.messages.flatMap((message) => + message.role === "system" && message.tools ? [{ add: message.tools.add, remove: message.tools.remove }] : [], + ) +const changes = (add: ReadonlyArray, remove: ReadonlyArray = []) => ({ add, remove }) + +describe("Message.tools", () => { + test("builds an empty system message whose tools field round-trips through the schema", () => { + const message = Message.make( + Message.tools({ add: [{ name: "write", description: "write tool", inputSchema: { type: "object" } }] }), + ) + + expect(message.role).toBe("system") + expect(message.content).toEqual([]) + expect(message.tools).toEqual({ add: [write], remove: [] }) + const decoded = Schema.decodeUnknownSync(Message)(Schema.encodeSync(Message)(message)) + expect(decoded.role === "system" && decoded.tools).toEqual({ add: [write], remove: [] }) + expect(decoded.role === "system" && decoded.tools?.add[0]).toBeInstanceOf(ToolDefinition) + }) + + test("stores definitions for tool objects and names for removals", () => { + const message = Message.make(Message.tools({ add: [lookup], remove: [lookup, read, "edit"] })) + + expect(message.tools).toEqual({ add: [lookup._definition], remove: ["lookup", "read", "edit"] }) + expect(Message.make(Message.system("Note.")).tools).toBeUndefined() + }) +}) + +describe("planToolUpdates", () => { + test("folds every marker in history order on a route without in-place changes", () => { + const result = planToolUpdates( + ai.request({ + model: chat, + tools: [read, edit, lookup], + messages: [ + Message.user("One."), + Message.tools({ add: [write, defineTool("edit", "edit v2")] }), + Message.user("Two."), + Message.tools({ remove: [lookup, "read"] }), + { role: "system", content: "Tools changed.", tools: { add: [defineTool("read", "read v2")] } }, + ], + }), + ) + + expect(result.tools).toEqual([defineTool("edit", "edit v2"), write, defineTool("read", "read v2")]) + expect(result.messages).toEqual([Message.user("One."), Message.user("Two."), Message.system("Tools changed.")]) + }) + + test("keeps the request identity without markers", () => { + const plain = ai.request({ model: opus5, tools: [read], prompt: "hi" }) + expect(planToolUpdates(plain)).toBe(plain) + }) + + const plan = (list: ReadonlyArray | undefined, messages: ReadonlyArray) => + planToolUpdates(ai.request({ model: anthropic("claude-opus-5", list), tools: [read, edit], messages })) + const history = [ + Message.user("One."), + Message.tools({ add: [jira] }), + Message.user("Two."), + Message.tools({ remove: ["edit"] }), + Message.user("Three."), + Message.tools({ add: [write] }), + Message.user("Four."), + Message.tools({ add: [defineTool("read", "read v2")] }), + ] + + test.each([ + ["unset", undefined, ["read", "jira", "write"], []], + ["empty", [], ["read", "jira", "write"], []], + ["add", ["add"], ["read", "jira", "write"], []], + ["add + remove", ["add", "remove"], ["read", "jira", "write"], []], + [ + "add + replace", + ["add", "replace"], + ["read", "jira"], + [changes([write]), changes([defineTool("read", "read v2")])], + ], + ["remove + replace", ["remove", "replace"], ["read", "jira", "write"], [changes([defineTool("read", "read v2")])]], + [ + "all", + ALL, + ["read", "edit"], + [changes([jira]), changes([], ["edit"]), changes([write]), changes([defineTool("read", "read v2")])], + ], + ] as const)("with updates %s, folds up to the last marker the model can't take in place", (_, list, tools, kept) => { + const result = plan(list, history) + expect(names(result)).toEqual([...tools]) + expect(markers(result)).toEqual([...kept]) + }) + + test("keeps additions after the last removal in place when only additions are supported", () => { + const result = plan(["add"], history.slice(0, 6)) + expect(names(result)).toEqual(["read", "jira"]) + expect(markers(result)).toEqual([changes([write])]) + }) + + test("counts adding a tool removed earlier as a replacement", () => { + const result = plan( + ["add", "remove"], + [Message.user("One."), Message.tools({ remove: ["edit"] }), Message.user("Two."), Message.tools({ add: [edit] })], + ) + expect(names(result)).toEqual(["read", "edit"]) + expect(markers(result)).toEqual([]) + }) + + test("treats removing and adding the same name in one marker as a replacement", () => { + const v2 = defineTool("edit", "edit v2") + const messages = [Message.user("One."), Message.tools({ add: [v2], remove: ["edit"] })] + expect(markers(plan(["replace"], messages))).toEqual([changes([v2])]) + expect(markers(plan(["remove"], messages))).toEqual([]) + }) + + test("drops removals of unknown names and markers that change nothing", () => { + const result = plan(ALL, [ + Message.user("One."), + Message.tools({ remove: ["ghost", "edit"] }), + Message.tools({ remove: ["ghost"] }), + Message.tools({}), + ]) + expect(names(result)).toEqual(["read", "edit"]) + expect(result.messages.map((message) => message.role)).toEqual(["user", "system"]) + expect(markers(result)).toEqual([changes([], ["edit"])]) + }) + + test("folds markers before the conversation starts into the leading declaration", () => { + const result = plan(ALL, [Message.tools({ add: [jira], remove: ["read"] }), Message.user("One.")]) + expect(names(result)).toEqual(["edit", "jira"]) + expect(result.messages).toEqual([Message.user("One.")]) + }) + + test("counts redefining a namespace without some of its tools as a removal", () => { + const namespace = (...tools: ReadonlyArray) => ToolNamespace.make({ name: "jira", tools }) + const request = (list: ReadonlyArray) => + planToolUpdates( + ai.request({ + model: anthropic("claude-opus-5", list), + tools: [namespace(read, edit)], + messages: [Message.user("One."), Message.tools({ add: [namespace(read)] })], + }), + ) + expect(markers(request(["add", "replace"]))).toEqual([]) + expect(markers(request(ALL))).toHaveLength(1) + }) +}) + +describe("leading declaration", () => { + const routes = [ + ["OpenAI Chat", chat], + ["Gemini", gemini], + ["Anthropic without updates", anthropic("claude-opus-5")], + ["Anthropic", opus5], + ["OpenAI Responses without updates", openai("gpt-6-astra")], + ["OpenAI Responses", astra], + ] as const + + it.effect("top-level tools compile the same as a Message.tools marker that leads the history", () => + Effect.gen(function* () { + for (const [, model] of routes) { + const direct = yield* compileRequest( + ai.request({ model, tools: [read, edit], messages: conversation, cache: "none" }), + ) + const leading = yield* compileRequest( + ai.request({ model, messages: [Message.tools({ add: [read, edit] }), ...conversation], cache: "none" }), + ) + expect(leading.body).toEqual(direct.body) + } + }), + ) + + it.effect("folding every marker matches listing the final tools up front, with no empty system message", () => + Effect.gen(function* () { + for (const model of [chat, gemini, anthropic("claude-opus-5"), openai("gpt-6-astra")]) { + const withMarkers = yield* compileRequest( + ai.request({ model, tools: [read, edit], messages: conversation, cache: "none" }), + ) + const withoutMarkers = yield* compileRequest( + ai.request({ model, tools: [read, write], messages: folded, cache: "none" }), + ) + expect(withMarkers.body).toEqual(withoutMarkers.body) + } + }), + ) + + it.effect("tool objects send the same definition from top-level tools and Message.tools", () => + Effect.gen(function* () { + const added = yield* compileRequest( + ai.request({ model: chat, tools: [read], messages: [Message.user("Go."), Message.tools({ add: [lookup] })] }), + ) + const direct = yield* compileRequest(ai.request({ model: chat, tools: [read, lookup], prompt: "Go." })) + + expect(added.body).toEqual(direct.body) + }), + ) +}) + +describe("ai.loop", () => { + const loopIt = testEffect(TestLLM.testLayer()) + + loopIt.effect("runs an executable tool added mid-conversation and not one removed later", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push( + TestLLM.toolCalls( + LLMEvent.toolCall({ id: "call-1", name: "lookup", input: { query: "weather" } }), + LLMEvent.toolCall({ id: "call-2", name: "remove_me", input: {} }), + ), + TestLLM.text("Done.", "text-1"), + ) + const removeMe = AI.tool({ + name: "remove_me", + description: "Removed before the model calls it.", + input: Schema.Struct({}), + execute: () => "ran", + }) + + const events = yield* ai + .loop({ + model: chat, + tools: [removeMe], + messages: [Message.user("Look it up."), Message.tools({ add: [lookup], remove: [removeMe] })], + }) + .pipe(Stream.runCollect) + const requests = yield* client.requests() + + expect(requests[0].tools.map((entry) => entry.name)).toEqual(["remove_me"]) + expect(requests[0].messages[1]).toEqual(Message.make(Message.tools({ add: [lookup], remove: ["remove_me"] }))) + expect(Array.from(events).filter(LLMEvent.is.toolResult)).toEqual([ + expect.objectContaining({ id: "call-1", result: { type: "text", value: "found weather" } }), + expect.objectContaining({ id: "call-2", result: expect.objectContaining({ type: "error" }) }), + ]) + }), + ) +}) + +describe("protocol wrappers", () => { + test("forward the tool update encoding", () => { + const wrapped = gatewayProtocol(AnthropicMessages.protocol, { + id: "gateway-anthropic", + prepare: (request) => Effect.succeed({ request, body: {} }), + }) + expect(wrapped.toolUpdates).toBe(AnthropicMessages.protocol.toolUpdates) + + const vertex = GoogleVertexMessages.configure({ accessToken: "test", location: "global", project: "test" }) + expect(vertex.model("claude-opus-5").route.toolUpdates).toBe(AnthropicMessages.protocol.toolUpdates) + }) +}) + +describe("cache policy", () => { + it.effect("walks the tail breakpoint back past a trailing tools marker", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read, edit], + messages: [Message.user("first"), Message.assistant("reply"), Message.user("latest"), swap], + cache: { messages: { tail: 1 } }, + }), + ) + + expect(prepared.body.messages.at(-2)).toEqual({ + role: "user", + content: [{ type: "text", text: "latest", cache_control: { type: "ephemeral" } }], + }) + expect(prepared.body.messages.at(-1)?.role).toBe("system") + }), + ) +}) + +describe("Anthropic Messages tool updates", () => { + const definition = (value: ToolDefinition) => ({ + type: "tool_addition", + tool: { + type: "tool_definition", + definition: { name: value.name, description: value.description, input_schema: value.inputSchema }, + }, + }) + const removal = (name: string) => ({ type: "tool_removal", tool: { type: "tool_reference", name } }) + + it.effect("lowers markers to native system messages and keeps the top-level tools", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ model: opus5, tools: [read, edit], messages: conversation, cache: "none" }), + ) + const plain = yield* compileRequest( + ai.request({ model: opus5, tools: [read, write], prompt: "x", cache: "none" }), + ) + + expect(prepared.body.tools?.map((entry) => entry.name)).toEqual(["read", "edit"]) + expect(prepared.body.messages).toEqual([ + { role: "user", content: [{ type: "text", text: "Fix it." }] }, + { role: "assistant", content: [{ type: "text", text: "Done." }] }, + { role: "user", content: [{ type: "text", text: "Next." }] }, + { role: "system", content: [definition(write), removal("edit")] }, + ]) + const addition = prepared.body.messages[3]?.content[0] + expect(addition?.type === "tool_addition" && addition.tool.definition).toEqual(plain.body.tools?.[1]) + }), + ) + + it.effect("redefines a tool with a same-name addition and re-adds a removed one", () => + Effect.gen(function* () { + const v2 = defineTool("edit", "edit v2") + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read, edit], + messages: [ + Message.user("One."), + Message.tools({ add: [v2] }), + Message.user("Two."), + Message.tools({ remove: ["read"] }), + Message.user("Three."), + Message.tools({ add: [read] }), + ], + cache: "none", + }), + ) + + expect(prepared.body.tools?.map((entry) => entry.name)).toEqual(["read", "edit"]) + expect(prepared.body.messages.filter((message) => message.role === "system")).toEqual([ + { role: "system", content: [definition(v2)] }, + { role: "system", content: [removal("read")] }, + { role: "system", content: [definition(read)] }, + ]) + }), + ) + + it.effect("removes the tools a redefined namespace leaves out", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [ToolNamespace.make({ name: "jira", tools: [read, edit] })], + messages: [ + Message.user("One."), + Message.tools({ add: [ToolNamespace.make({ name: "jira", tools: [read] })] }), + ], + cache: "none", + }), + ) + + expect(prepared.body.messages.at(-1)).toEqual({ + role: "system", + content: [definition(defineTool("jira_read", "read tool")), removal("jira_edit")], + }) + }), + ) + + it.effect("adds tools in place with no top-level tools and keeps tool_choice", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + messages: [Message.user("Go."), Message.tools({ add: [jira] })], + toolChoice: { type: "tool", name: "jira" }, + cache: "none", + }), + ) + + expect(prepared.body.tools).toBeUndefined() + expect(prepared.body.tool_choice).toEqual({ type: "tool", name: "jira" }) + expect(prepared.body.messages.at(-1)).toEqual({ role: "system", content: [definition(jira)] }) + }), + ) + + it.effect("folds markers that no user message or tool result would precede, keeping later ones in place", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read, edit], + messages: [ + Message.user("Fix it."), + Message.assistant("Done."), + swap, + Message.assistant("More."), + Message.user("Next."), + Message.tools({ add: [jira] }), + ], + cache: "none", + }), + ) + + expect(prepared.body.tools?.map((entry) => entry.name)).toEqual(["read", "write"]) + expect(prepared.body.messages.at(-1)).toEqual({ role: "system", content: [definition(jira)] }) + expect(prepared.body.messages.filter((message) => message.role === "system")).toHaveLength(1) + }), + ) + + it.effect("sends several removals as blocks in one message and nothing for unknown names", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read, edit, write], + messages: [Message.user("Go."), Message.tools({ remove: ["read", "ghost", "write"] })], + cache: "none", + }), + ) + const unknown = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read], + messages: [Message.user("Go."), Message.tools({ remove: ["ghost"] })], + cache: "none", + }), + ) + + expect(prepared.body.messages.at(-1)).toEqual({ role: "system", content: [removal("read"), removal("write")] }) + expect(unknown.body.messages).toEqual([{ role: "user", content: [{ type: "text", text: "Go." }] }]) + }), + ) + + it.effect("moves a marker between a tool call and its result after the result", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: opus5, + tools: [read, edit], + messages: [ + Message.user("Read it."), + Message.assistant([ToolCallPart.make({ id: "call_1", name: "read", input: {} })]), + Message.tools({ add: [write] }), + Message.tool({ id: "call_1", name: "read", result: { ok: true } }), + ], + cache: "none", + }), + ) + + expect(prepared.body.messages).toEqual([ + { role: "user", content: [{ type: "text", text: "Read it." }] }, + { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "read", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '{"ok":true}' }] }, + { role: "system", content: [definition(write)] }, + ]) + }), + ) + + it.effect("requests the inline tools beta only when markers are sent", () => + Effect.gen(function* () { + for (const [messages, expected] of [ + [conversation, true], + [folded, false], + ] as const) { + const request = ai.request({ model: opus5, tools: [read, edit], messages }) + const compiled = yield* compileRequest(request) + const prepared = yield* AnthropicMessages.route.prepareTransport(compiled.body, request) + expect(prepared.request.headers["anthropic-beta"]!.split(",").includes("inline-tools-2026-09-15")).toBe( + expected, + ) + } + }), + ) + + it.effect("folds markers when the model lacks updates or system updates", () => + Effect.gen(function* () { + for (const model of [anthropic("claude-opus-5"), anthropic("claude-opus-4-5", ALL)]) { + const prepared = yield* compileRequest( + ai.request({ model, tools: [read, edit], messages: conversation, cache: "none" }), + ) + + expect(prepared.body.messages.some((message) => message.role === "system")).toBe(false) + expect(prepared.body.tools?.map((entry) => entry.name)).toEqual(["read", "write"]) + } + }), + ) +}) + +describe("OpenAI Responses tool updates", () => { + const additional = (body: OpenAIResponses.OpenAIResponsesBody) => + body.input.flatMap((item) => + "type" in item && item.type === "additional_tools" + ? [item.tools.map((entry) => ("description" in entry ? `${entry.name}: ${entry.description}` : entry.type))] + : [], + ) + const topLevel = (body: OpenAIResponses.OpenAIResponsesBody) => + body.tools?.map((entry) => ("name" in entry ? entry.name : entry.type)) + // One line per input item: declared tools, developer text, or the item type. + const trace = (body: OpenAIResponses.OpenAIResponsesBody) => + body.input.map((item) => { + if ("type" in item && item.type === "additional_tools") + return `tools: ${item.tools.map((entry) => ("name" in entry ? entry.name : entry.type)).join(", ")}` + if ("role" in item && item.role === "developer" && typeof item.content === "string") return item.content + return "role" in item ? item.role : item.type + }) + const hint = (...unavailable: ReadonlyArray) => + [ + "Tool update: the tools below are added to the ones you already have. Earlier tools stay available unless marked unavailable, and a tool declared again replaces its earlier definition.", + ...(unavailable.length === 0 ? [] : [`Still unavailable: ${unavailable.join(", ")}.`]), + ].join("\n") + + it.effect("declares every tool in a leading additional_tools item and leaves top-level tools out", () => + Effect.gen(function* () { + const prepared = yield* compileRequest(ai.request({ model: astra, tools: [read, edit], prompt: "Go." })) + const plain = yield* compileRequest( + ai.request({ model: openai("gpt-6-astra"), tools: [read, edit], prompt: "Go." }), + ) + + expect(prepared.body.tools).toBeUndefined() + expect(prepared.body.input).toEqual([ + { type: "additional_tools", role: "developer", tools: plain.body.tools }, + { type: "message", role: "user", content: [{ type: "input_text", text: "Go." }] }, + ]) + expect(additional(plain.body)).toEqual([]) + }), + ) + + it.effect("adds and redefines tools with later items, each after an incremental hint", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: astra, + tools: [read, edit], + messages: [ + Message.user("Fix it."), + Message.tools({ add: [write] }), + Message.user("Next."), + Message.tools({ add: [defineTool("edit", "edit v2")] }), + ], + }), + ) + + expect(prepared.body.tools).toBeUndefined() + expect(additional(prepared.body)).toEqual([ + ["read: read tool", "edit: edit tool"], + ["write: write tool"], + ["edit: edit v2"], + ]) + expect(trace(prepared.body)).toEqual([ + "tools: read, edit", + "user", + hint(), + "tools: write", + "user", + hint(), + "tools: edit", + ]) + }), + ) + + it.effect("sends the first item without a hint when no tools lead the request", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: astra, + messages: [ + Message.user("Go."), + Message.tools({ add: [jira] }), + Message.user("More."), + Message.tools({ add: [write] }), + ], + }), + ) + + expect(trace(prepared.body)).toEqual(["user", "tools: jira", "user", hint(), "tools: write"]) + }), + ) + + it.effect("announces removals, lists them in later hints until re-added, and keeps them declared", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: astra, + tools: [read, edit, write], + messages: [ + Message.user("One."), + Message.tools({ remove: ["edit", "write"] }), + Message.user("Two."), + Message.tools({ add: [jira] }), + Message.user("Three."), + Message.tools({ add: [edit] }), + ], + }), + ) + + expect(trace(prepared.body)).toEqual([ + "tools: read, edit, write", + "user", + "These tools are no longer available. Do not call them: edit, write.", + "user", + hint("edit", "write"), + "tools: jira", + "user", + hint("write"), + "tools: edit", + ]) + }), + ) + + it.effect("sends a redefinition and a removal in one marker as an item and an announcement", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: astra, + tools: [read, edit], + messages: [Message.user("One."), Message.tools({ add: [defineTool("read", "read v2")], remove: ["edit"] })], + }), + ) + + expect(trace(prepared.body)).toEqual([ + "tools: read, edit", + "user", + hint(), + "tools: read", + "These tools are no longer available. Do not call them: edit.", + ]) + }), + ) + + it.effect("folds removals when the model doesn't list remove", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: openai("gpt-6-astra", ["add", "replace"]), + tools: [read, edit], + messages: [...conversation, Message.tools({ add: [jira] })], + }), + ) + + expect(trace(prepared.body)).toEqual(["tools: read, write", "user", "assistant", "user", hint(), "tools: jira"]) + }), + ) + + it.effect("folds redefinitions when the model lists replace without add", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: openai("gpt-6-astra", ["replace"]), + tools: [read, edit], + messages: [Message.user("Go."), Message.tools({ add: [defineTool("edit", "edit v2")] })], + }), + ) + + expect(additional(prepared.body)).toEqual([]) + expect(prepared.body.tools?.map((entry) => ("description" in entry ? entry.description : entry.type))).toEqual([ + "read tool", + "edit v2", + ]) + }), + ) + + it.effect("folds redefinitions when the model only lists add", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: openai("gpt-6-astra", ["add"]), + tools: [read, edit], + messages: [Message.user("Go."), Message.tools({ add: [defineTool("edit", "edit v2"), jira] })], + }), + ) + + expect(additional(prepared.body)).toEqual([["read: read tool", "edit: edit v2", "jira: jira tool"]]) + }), + ) + + it.effect("keeps hosted tools top-level and folds changes to them", () => + Effect.gen(function* () { + const image = OpenAI.imageGeneration() + const prepared = yield* compileRequest(ai.request({ model: astra, tools: [read, image], prompt: "Go." })) + const added = yield* compileRequest( + ai.request({ + model: astra, + tools: [read], + messages: [Message.user("Go."), Message.tools({ add: [image] })], + }), + ) + + expect(topLevel(prepared.body)).toEqual(["image_generation"]) + expect(additional(prepared.body)).toEqual([["read: read tool"]]) + expect(topLevel(added.body)).toEqual(["image_generation"]) + expect(additional(added.body)).toEqual([["read: read tool"]]) + }), + ) + + it.effect("keeps tool_choice for tools declared only in additional_tools", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ model: astra, tools: [read], toolChoice: { type: "tool", name: "read" }, prompt: "Go." }), + ) + const added = yield* compileRequest( + ai.request({ + model: astra, + messages: [Message.user("Go."), Message.tools({ add: [jira] })], + toolChoice: "required", + }), + ) + + expect(prepared.body.tool_choice).toEqual({ type: "function", name: "read" }) + expect(added.body.tool_choice).toBe("required") + expect(additional(added.body)).toEqual([["jira: jira tool"]]) + }), + ) + + it.effect("sends a marker's own text after its tool changes", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: astra, + tools: [read], + messages: [Message.user("Go."), { role: "system", content: "Use jira now.", tools: { add: [jira] } }], + }), + ) + + expect(trace(prepared.body)).toEqual(["tools: read", "user", hint(), "tools: jira", "Use jira now."]) + }), + ) + + it.effect("adds freeform tools as custom tools and replays their calls as custom tool calls", () => + Effect.gen(function* () { + const run = ToolDefinition.make({ + name: "run", + description: "Run code", + inputSchema: { type: "object", properties: { code: { type: "string" } }, required: ["code"] }, + freeform: { type: "text" }, + }) + const prepared = yield* compileRequest( + ai.request({ + model: astra, + tools: [read], + messages: [ + Message.user("Run it."), + Message.tools({ add: [run] }), + Message.assistant([ToolCallPart.make({ id: "call_1", name: "run", input: { code: "ls" } })]), + Message.tool({ id: "call_1", name: "run", result: "ok" }), + ], + }), + ) + const plain = yield* compileRequest(ai.request({ model: openai("gpt-6-astra"), tools: [read, run], prompt: "x" })) + + expect(prepared.body.input[3]).toEqual({ + type: "additional_tools", + role: "developer", + tools: [plain.body.tools?.[1]], + }) + expect(plain.body.tools?.[1]?.type).toBe("custom") + expect(prepared.body.input[4]).toEqual({ type: "custom_tool_call", call_id: "call_1", name: "run", input: "ls" }) + }), + ) + + it.effect("keeps top-level tools and folds markers without updates", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ model: openai("gpt-6-astra"), tools: [read, edit], messages: conversation }), + ) + + expect(additional(prepared.body)).toEqual([]) + expect(topLevel(prepared.body)).toEqual(["read", "write"]) + }), + ) + + const checkpoint = { type: "compaction", id: "cmp_1", encrypted_content: "opaque" } + + testEffect( + dynamicResponse(({ request, text, respond }) => + Effect.sync(() => { + expect(new URL(request.url).pathname).toEndWith("/responses/compact") + const body = JSON.parse(text) + expect(body.tools.map((entry: { name: string }) => entry.name)).toEqual(["read", "write", "jira"]) + expect(body.input.map((item: { type: string }) => item.type)).toEqual(["message", "message", "message"]) + return respond(JSON.stringify({ object: "response.compaction", output: [checkpoint] })) + }), + ), + ).effect("folds every tool into top-level tools on the compaction endpoint", () => + Effect.gen(function* () { + const result = yield* ai.compact( + ai.request({ + model: astra, + tools: [read, edit], + messages: [...conversation, Message.tools({ add: [jira] })], + }), + { mechanism: "endpoint" }, + ) + expect(result.replacement.map((message) => message.content[0]?.type)).toEqual(["compaction"]) + }), + ) +}) diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 4662fb3105fe..ff9546fb3827 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -279,7 +279,7 @@ story("toggles the element picker from the shortcut only inside the browser pane ) }) -story("keeps in-page shortcuts like ⌘K in the page while forwarding ⌘⇧R and ⌘W to the pane", async ({ page }) => { +story("keeps in-page shortcuts in the editor and forwards toolbar, review and close shortcuts", async ({ page }) => { const root = page.getByTestId("browser-region-fixture") const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform)) const mod = mac ? "Meta" : "Control" @@ -299,6 +299,23 @@ story("keeps in-page shortcuts like ⌘K in the page while forwarding ⌘⇧R an await editor.press(`${mod}+k`) await expect(editor).toHaveValue("handled:k") + const toggle = root.getByRole("button", { name: "Toggle browser toolbar", exact: true }) + await editor.press(`${mod}+Shift+m`) + await expect(toggle).toHaveAttribute("aria-expanded", "true") + await expect(toggle).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") + // Shell shortcuts like ⌘⇧R and pane-scoped ⌘W are claimed before the page sees them. await editor.press(`${mod}+Shift+r`) await expect(root.getByTestId("review-toggles")).toHaveText("1") diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index 9c6a3376c51c..45541a7e8650 100644 --- a/packages/app/component-tests/browser-pane.spec.ts +++ b/packages/app/component-tests/browser-pane.spec.ts @@ -1,4 +1,5 @@ import { expect, sourceURL, story } from "../../stories/playwright/story" +import type { Locator, Page } from "@playwright/test" const source = (path: string) => sourceURL(new URL(path, import.meta.url)) @@ -9,6 +10,12 @@ const modules = { language: source("../src/runtime/i18n/language.tsx"), } +// Panel motion reads `navigator.platform` on each drag, so a test pins the platform whose behaviour it covers. +const pinPlatform = (page: Page, platform: string) => + page.evaluate((value) => { + Object.defineProperty(navigator, "platform", { value, configurable: true }) + }, platform) + story.beforeEach(async ({ mount, page }) => { // Any story loads the app styles; the fixture mounts the pane beside it on the real host embeds. await mount("ui-line-comment--editor") @@ -106,10 +113,11 @@ story("paints a still of the page in place of the native view while a resize han const handle = root.getByTestId("pane-resize-handle") const native = root.getByTestId("native-Alpha") const still = root.locator("#browser-panel img") + await pinPlatform(page, "Linux x86_64") - // A native view's bounds land on screen frames before the DOM around it, so one left up through a drag jumps against - // its pane on every move. A click on the handle moves nothing and must not blink the page out. Read in the same task - // as each event, so a view hidden and shown again before the next frame cannot pass. + // On Linux a native view's bounds land on screen frames before the DOM around it, so one left up through a drag jumps + // against its pane on every move. A click on the handle moves nothing and must not blink the page out. Read in the + // same task as each event, so a view hidden and shown again before the next frame cannot pass. const visible = await handle.evaluate((element) => { const read = () => document.querySelector('[data-testid="native-Alpha"]')?.getAttribute("data-visible") const box = element.getBoundingClientRect() @@ -136,11 +144,39 @@ story("paints a still of the page in place of the native view while a resize han await expect(still).toHaveCount(0) }) +story("keeps the native view live while a resize handle is dragged on macOS", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const handle = root.getByTestId("pane-resize-handle") + const still = root.locator("#browser-panel img") + await pinPlatform(page, "MacIntel") + + // macOS puts a native view's bounds and the DOM around it on the same frame, so the page keeps laying out through the + // drag instead of freezing behind a still. Read in the same task as each move, so a blink between frames cannot pass. + const visible = await handle.evaluate((element) => { + const read = () => document.querySelector('[data-testid="native-Alpha"]')?.getAttribute("data-visible") + const box = element.getBoundingClientRect() + const at = { bubbles: true, pointerId: 1, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } + element.dispatchEvent(new PointerEvent("pointerdown", { ...at, button: 0 })) + document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 40 })) + const dragging = read() + document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 80 })) + const moved = read() + document.dispatchEvent(new PointerEvent("pointerup", at)) + + return { dragging, moved } + }) + + expect(visible).toEqual({ dragging: "true", moved: "true" }) + await expect(handle).not.toHaveAttribute("data-dragging") + await expect(still).toHaveCount(0) +}) + story("shows the native view again when the window loses focus mid-drag", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const handle = root.getByTestId("pane-resize-handle") const native = root.getByTestId("native-Alpha") const still = root.locator("#browser-panel img") + await pinPlatform(page, "Linux x86_64") // Alt+Tab mid-drag delivers no pointerup; the page must not stay locked behind a still. await handle.evaluate((element) => { @@ -876,13 +912,18 @@ story("lists recent pages on a blank tab and opens one", async ({ page }) => { await expect(address).toHaveValue("http://localhost:5173/settings") }) -story("adds the whole page to the session and keeps the draft when the button is pressed again", async ({ page }) => { - const root = page.getByTestId("browser-pane-fixture") +story("keeps a page note editable beside a tiny viewport and attaches it to the session", async ({ page }) => { + const { root, viewport, width, height } = viewportControls(page) + await viewport.click() + await width.fill("8") + await height.fill("8") + await expectSize(root.getByTestId("native-Alpha"), 8, 8) const field = root.locator('[data-component="browser-address"]') const add = root.getByRole("button", { name: "Add page to session", exact: true }) await field.hover() await add.click() const editor = root.locator('[data-slot="browser-comment-editor"] textarea') + await editor.click() await editor.fill("Check the header layout") await field.hover() await add.click() @@ -913,12 +954,51 @@ story("says a failed cookie read failed and reads again on retry", async ({ page await expect(site.getByRole("button", { name: "Clear", exact: true })).toBeEnabled() }) -story("zooms the page from the browser options in view and keeps its zoom in the address field", async ({ page }) => { +function viewportControls(page: Page) { const root = page.getByTestId("browser-pane-fixture") + + const controls = root.getByRole("region", { name: "Viewport", exact: true }) + + return { + root, + controls, + viewport: root.getByRole("button", { name: "Toggle browser toolbar", exact: true }), + 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 }), + width: controls.getByLabel("Viewport width in CSS pixels", { exact: true }), + height: controls.getByLabel("Viewport height in CSS pixels", { exact: true }), + scale: controls.getByRole("button", { name: "Preview scale", exact: true }), + rotate: controls.getByRole("button", { name: "Rotate viewport", exact: true }), + } +} + +function resizePane(root: Locator, width: number) { + return root.locator("#browser-panel").evaluate((pane, width) => { + if (!pane.parentElement) throw new Error("Missing pane container") + pane.parentElement.style.width = `${width}px` + }, width) +} + +async function expectSize(native: Locator, width: number, height: number) { + await expect(native).toHaveAttribute("data-width", String(width)) + await expect(native).toHaveAttribute("data-height", String(height)) +} + +story("zooms the page from the browser options in view and keeps its zoom in the address field", async ({ page }) => { + const { root, controls, viewport, preset, option, scale } = viewportControls(page) + await viewport.click() + await preset.click() + await option("Samsung Galaxy S26").click() + await expect(preset).toHaveText("Samsung Galaxy S26") const options = root.getByRole("button", { name: "Browser options", exact: true }) await options.click() await page.getByRole("menuitem", { name: /^Zoom in/ }).click() await expect(root.getByText("Zoom: 110", { exact: true })).toBeVisible() + await expect(controls.getByRole("status")).toContainText("The page is using the pane size because page zoom changed.") + await expect(preset).toBeDisabled() + await expect(preset).toHaveText("Responsive") + await expect(scale).toBeDisabled() // The menu covered the page with a still; it closes so the zoomed page shows at once. await expect(page.getByRole("menu")).toBeHidden() await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") @@ -928,4 +1008,218 @@ story("zooms the page from the browser options in view and keeps its zoom in the await zoom.click() await expect(root.getByText("Zoom: 100", { exact: true })).toBeVisible() await expect(zoom).toBeHidden() + await expect(preset).toBeEnabled() +}) + +story("restores the full pane when the toolbar closes and keeps the selected device on reopen", async ({ page }) => { + const { root, controls, viewport, preset, option, moreDevices, width, height } = viewportControls(page) + + const native = root.getByTestId("native-Alpha") + + const fullWidth = await native.getAttribute("data-width") + + const fullHeight = await native.getAttribute("data-height") + + if (!fullWidth || !fullHeight) throw new Error("Missing native page bounds") + + await viewport.click() + await preset.press("ArrowDown") + const menu = page.getByRole("menu") + await expect(option("Responsive")).toBeChecked() + await expect(menu.getByRole("menuitemradio")).toHaveText([ + "Responsive", + "Samsung Galaxy S26", + "iPhone 18 Pro", + "iPad / iPad Air 11″", + "Laptop", + "Desktop", + ]) + await page.keyboard.press("End") + await expect(moreDevices).toBeFocused() + await page.keyboard.press("ArrowRight") + const mini = option("iPad mini") + await mini.click() + await expect(preset).toHaveText("iPad mini") + await expect(preset).toBeFocused() + await expect(native).not.toHaveAttribute("data-width", fullWidth) + await viewport.click() + await expect(controls).toBeHidden() + await expect(native).toHaveAttribute("data-width", fullWidth) + await expect(native).toHaveAttribute("data-height", fullHeight) + await expect(root.getByRole("separator", { name: "Resize viewport width" })).toBeHidden() + await viewport.click() + await expect(preset).toHaveText("iPad mini") + await expect(width).toHaveValue("756") + await expect(height).toHaveValue("1158") + // Matching the preset's dimensions by hand still counts as Custom. + await width.fill("700") + await width.fill("756") + await expect(preset).toHaveText("Custom") + await preset.click() + await expect(option("Custom")).toBeChecked() + await moreDevices.hover() + await expect(mini).not.toBeChecked() +}) + +story("fits an exact viewport while resizing and rejects invalid edits", async ({ page }) => { + const { root, viewport, preset, option, scale, width, height } = viewportControls(page) + + const native = root.getByTestId("native-Alpha") + await viewport.click() + await expect(width).toHaveValue("624") + await width.fill("1248") + await expect(scale).toHaveText("Fit - 50%") + await expect(width).toBeFocused() + await height.fill("5") + // Chromium needs whole native pixels: round the fitted height up. + await expectSize(native, 624, 3) + await expect(height).toBeFocused() + + await resizePane(root, 328) + await expect(scale).toHaveText("Fit - 25%") + await expectSize(native, 312, 2) + await expect(width).toHaveValue("1248") + await expect(height).toHaveValue("5") + + for (const edit of ["", "4097"]) { + await width.fill(edit) + await expect(width).toHaveValue(edit) + await expect(width).toHaveAttribute("aria-invalid", "true") + await expect(width).toHaveAccessibleDescription("Use whole numbers from 1 to 4096 for width and height.") + await expectSize(native, 312, 2) + } + + await width.blur() + await expect(width).toHaveValue("1248") + await expect(width).not.toHaveAttribute("aria-invalid", "true") + await preset.click() + await option("Responsive").click() + await expect(preset).toHaveText("Responsive") + await expect(width).toHaveValue("312") + await expect(scale).toHaveText("Fit - 100%") + await resizePane(root, 640) + await expect(width).toHaveValue("624") + await expect(native).toHaveAttribute("data-width", "624") +}) + +story("resizes a device with the RTL side grip by pointer and keyboard", async ({ page }) => { + const { root, viewport, preset, option, scale, width, height } = viewportControls(page) + await root.evaluate((element) => element.setAttribute("dir", "rtl")) + await viewport.click() + await preset.click() + await option("Samsung Galaxy S26").click() + await scale.click() + await option("50%").click() + await expectSize(root.getByTestId("native-Alpha"), 180, 390) + const grip = root.getByRole("separator", { name: "Resize viewport width", exact: true }) + + const box = await grip.boundingBox() + + if (!box) throw new Error("Missing viewport resize grip") + const x = box.x + box.width / 2 + + const y = box.y + box.height / 2 + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(x - 12, y) + // Both edges move 12 screen pixels, or 24 guest CSS pixels each at 50% scale. + await expect(width).toHaveValue("408") + await expect(height).toHaveValue("780") + await expect(preset).toHaveText("Custom") + await expectSize(root.getByTestId("native-Alpha"), 204, 390) + await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") + await expect(root.locator('img[elementtiming="embed-snapshot"]')).toHaveCount(0) + await page.mouse.up() + await grip.press("Shift+ArrowRight") + await expect(width).toHaveValue("398") +}) + +story("pins the responsive dimensions when a manual preview scale is selected", async ({ page }) => { + const { root, viewport, preset, option, scale, width, height } = viewportControls(page) + + const native = root.getByTestId("native-Alpha") + await viewport.click() + await expect(width).toHaveValue("624") + const responsiveHeight = await height.inputValue() + await expect(scale).toHaveText("Fit - 100%") + await scale.click() + const menu = page.getByRole("menu") + await expect(menu.getByRole("menuitemradio")).toHaveText([ + "Fit to pane", + "50%", + "75%", + "100%", + "125%", + "150%", + "200%", + ]) + const fit = option("Fit to pane") + await expect(fit).toBeChecked() + const double = option("200%") + await double.click() + await resizePane(root, 400) + await expect(scale).toHaveText("200%") + await expect(preset).toHaveText("Custom") + await expect(width).toHaveValue("624") + await expect(height).toHaveValue(responsiveHeight) + + await width.fill("120") + await height.fill("80") + await expectSize(native, 240, 160) + await scale.click() + await expect(double).toBeChecked() + await fit.click() + await expect(scale).toHaveText("Fit - 100%") + await expectSize(native, 120, 80) +}) + +story("keeps the selected device and its rotated viewport with its browser tab", async ({ page }) => { + const { root, viewport, preset, moreDevices, option, width, height, scale, rotate } = viewportControls(page) + + const switchTab = root.getByRole("button", { name: "Switch browser tab", exact: true }) + await viewport.click() + await scale.click() + await option("50%").click() + await preset.click() + await moreDevices.hover() + const pixel = option("Pixel 10") + await pixel.click() + await expect(preset).toHaveText("Pixel 10") + await rotate.click() + await expectSize(root.getByTestId("native-Alpha"), 462, 206) + + await switchTab.click() + await expect(root.getByTestId("native-Second")).toHaveAttribute("data-visible", "true") + await expect(preset).toHaveText("Responsive") + await width.fill("200") + await height.fill("180") + const second = root.getByTestId("native-Second") + await expectSize(second, 200, 180) + await expect(scale).toHaveText("Fit - 100%") + + // Wrapping the toolbar moves the centered native view on both axes without changing its size. + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + + const embed = root.locator('[data-component="browser-preview"] > div:first-child') + + const wide = await embed.boundingBox() + await resizePane(root, 320) + const narrow = await embed.boundingBox() + + if (!wide || !narrow) throw new Error("Missing preview bounds") + expect(narrow.x).toBeLessThan(wide.x) + expect(narrow.y).toBeGreaterThan(wide.y) + await expect(second).toHaveAttribute("data-x", String(Math.round(narrow.x))) + await expect(second).toHaveAttribute("data-y", String(Math.round(narrow.y))) + await expectSize(second, 200, 180) + + await switchTab.click() + await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") + await expect(width).toHaveValue("924") + await expect(height).toHaveValue("412") + await expect(preset).toHaveText("Pixel 10") + await expect(scale).toHaveText("50%") + await preset.click() + await moreDevices.hover() + await expect(pixel).toBeChecked() }) diff --git a/packages/app/component-tests/pairing.spec.ts b/packages/app/component-tests/pairing.spec.ts index 6123a645215f..e56cd4fb6247 100644 --- a/packages/app/component-tests/pairing.spec.ts +++ b/packages/app/component-tests/pairing.spec.ts @@ -1,5 +1,19 @@ import { expect, story } from "../../stories/playwright/story" +story("the connect screen can retry a failed health check after scanning a one-time QR code", async ({ mount }) => { + const component = await mount("app-connect-to-server--retry-after-scan") + await component.getByRole("button", { name: "Read fixture QR code" }).click() + await expect(component.getByRole("alert")).toHaveText( + "Could not connect. Check the server address and password, then try again.", + ) + await expect(component.getByLabel("Pairing link", { exact: true })).toHaveValue( + "https://build.example.test/auth/connect/example", + ) + + await component.getByRole("button", { name: "Connect", exact: true }).click() + await expect(component.getByRole("status")).toHaveText("Connected to https://build.example.test in this preview.") +}) + story("a Keep screen active read that fails offers Try again and keeps the switch enabled", async ({ mount, page }) => { // The page reads three more times, 1, 2 and 4 seconds apart, before it shows the failure. await page.clock.install() diff --git a/packages/app/component-tests/timeline-detail.spec.ts b/packages/app/component-tests/timeline-detail.spec.ts index c319d9c46d8b..2afb06a8fdf9 100644 --- a/packages/app/component-tests/timeline-detail.spec.ts +++ b/packages/app/component-tests/timeline-detail.spec.ts @@ -67,7 +67,7 @@ story("replaces hidden switches with solid lines and restores options", async ({ await expect(visibility).toHaveAttribute("aria-pressed", "true") await expect(label).toHaveCSS("color", color) - await expect(visibility.locator("use")).toHaveAttribute("href", "#opencode-v2-icon-outline-eye") + await expect(visibility.locator("use")).toHaveAttribute("href", "#opencode-v2-icon-eye") await expect(shell.locator('[data-slot="timeline-detail-unavailable"]')).toHaveCount(0) await expect(shell.getByRole("switch", { name: "Shell grouped", exact: true })).toBeEnabled() await expect(shell.getByRole("switch", { name: "Shell collapsed", exact: true })).toBeEnabled() @@ -103,9 +103,9 @@ story("only highlights the eye when hovering the icon, not its activity label", for (const hidden of [false, true]) { if (hidden) await label.click() await visibility.hover() - await expect(visibility).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)") + await expect(visibility).not.toHaveCSS("background-image", "none") await label.hover() - await expect(visibility).toHaveCSS("background-color", "rgba(0, 0, 0, 0)") + await expect(visibility).toHaveCSS("background-image", "none") } }) @@ -159,7 +159,7 @@ for (const direction of ["ltr", "rtl"]) { story(`fits narrow and wide layouts in ${direction}, ${theme}`, async ({ mount, page }, testInfo) => { await page.setViewportSize({ width: 900, height: 900 }) const component = await mount("settings-timeline-detail--interactive", { globals: { direction, theme } }) - await expect(component.locator('[data-slot="timeline-detail-scale"]')).toHaveCSS("margin-top", "16px") + await expect(component.locator('[data-slot="timeline-detail-scale"]')).toHaveCSS("margin-top", "4px") const advanced = component.locator('[data-slot="timeline-detail-advanced"]') await expect(advanced).toHaveCSS("margin-top", "0px") await expect(advanced).toHaveCSS("padding-top", "8px") @@ -176,23 +176,23 @@ for (const direction of ["ltr", "rtl"]) { await track.evaluate( (element, theme) => getComputedStyle(element) - .getPropertyValue(theme === "light" ? "--v2-background-bg-layer-04" : "--v2-background-bg-layer-03") + .getPropertyValue(theme === "light" ? "--v2-background-bg-layer-04" : "--v2-background-bg-layer-02") .trim(), theme, ), ) - if (theme === "light") { - await expect(track.locator("span").last()).toHaveCSS("background-image", "none") - await expect(track).toHaveCSS( - "--timeline-detail-marker-background", - await track.evaluate((element) => getComputedStyle(element).getPropertyValue("--v2-grey-500").trim()), - ) - } - - if (theme === "dark") { - await expect(track.locator("span").last()).not.toHaveCSS("background-image", "none") - } + await expect(track.locator("span").last()).toHaveCSS("background-image", "none") + await expect(track).toHaveCSS( + "--timeline-detail-marker-background", + await track.evaluate( + (element, theme) => + getComputedStyle(element) + .getPropertyValue(theme === "light" ? "--v2-grey-500" : "--v2-grey-700") + .trim(), + theme, + ), + ) await page.screenshot({ path: testInfo.outputPath(`timeline-${theme}-${direction}.png`) }) const list = component.locator('[data-slot="timeline-detail-list"]') @@ -243,7 +243,7 @@ for (const direction of ["ltr", "rtl"]) { expect(Math.abs(heading - toggle)).toBeLessThan(1) } - await expect(component.locator('[data-slot="timeline-detail-activity"]').first()).toHaveCSS("gap", "8px") + await expect(component.locator('[data-slot="timeline-detail-activity"]').first()).toHaveCSS("gap", "12px") for (const width of [900, 320]) { await page.setViewportSize({ width, height: 900 }) diff --git a/packages/app/e2e/regression/command-palette.spec.ts b/packages/app/e2e/regression/command-palette.spec.ts index ccaa605a2e5e..610a7e384042 100644 --- a/packages/app/e2e/regression/command-palette.spec.ts +++ b/packages/app/e2e/regression/command-palette.spec.ts @@ -120,7 +120,7 @@ test("titlebar search lists recent sessions and opens the typed match", async ({ const input = dialog.getByRole("combobox") await expect(input).toBeFocused() await expect(input).toHaveAttribute("placeholder", "Search sessions") - await expect(dialog.getByText("Recent sessions", { exact: true })).toBeVisible() + await expect(dialog.getByText("Recent sessions", { exact: true })).toBeHidden() await expect(dialog.getByRole("option", { name: /Palette fixture session/ })).toHaveAttribute("aria-selected", "true") // Session search lists sessions only, never commands. await input.fill("settings") diff --git a/packages/app/e2e/regression/directory-picker.spec.ts b/packages/app/e2e/regression/directory-picker.spec.ts index dae4f41cf46e..44d2882e384c 100644 --- a/packages/app/e2e/regression/directory-picker.spec.ts +++ b/packages/app/e2e/regression/directory-picker.spec.ts @@ -28,7 +28,8 @@ test("Tab and Enter while suggestions load act on the typed folder, not the prev const input = picker.getByRole("combobox") await input.fill("alp") - await expect(picker.getByRole("option")).toHaveText(["C:\\OpenCode\\Picker\\alpha/"]) + await expect(picker.getByRole("option")).toHaveCount(1) + await expect(picker.getByRole("option")).toHaveAttribute("data-directory-path", "C:/OpenCode/Picker/alpha") const search = await holdRoute(page, /\/api\/fs\/find\?(.*&)?query=beta(&|$)/) await input.fill("beta") @@ -40,7 +41,7 @@ test("Tab and Enter while suggestions load act on the typed folder, not the prev await input.press("Enter") await expect(input).toHaveValue("C:\\OpenCode\\Picker\\beta\\") - await expect(picker.locator(".directory-picker-selection-text")).toHaveText("C:\\…\\Picker\\beta") + await expect(picker.getByRole("treeitem", { name: "beta", exact: true })).toHaveAttribute("aria-selected", "true") search.release() }) @@ -103,3 +104,30 @@ test("the folder picker's tree scrolls with the mouse wheel inside the modal", a await page.mouse.wheel(0, 300) await expect.poll(scrollTop).toBeGreaterThan(0) }) + +test("Escape closes suggestions, then drops a typed path, before it closes the picker", async ({ page }) => { + const picker = await openPicker(page, { + fileList: (path) => + path === directory ? ["alpha", "beta"].map((name) => fileNode(directory, name, "directory")) : [], + findFiles: (input) => ["alpha", "beta"].filter((name) => input.query.length >= 3 && name.startsWith(input.query)), + }) + + const input = picker.getByRole("combobox") + + await picker.getByRole("treeitem", { name: "beta", exact: true }).click() + await expect(input).toHaveValue("C:\\OpenCode\\Picker\\beta\\") + + await input.fill("alp") + await expect(picker.getByRole("option")).toHaveCount(1) + await input.press("Escape") + await expect(picker.getByRole("option")).toHaveCount(0) + await expect(input).toHaveValue("alp") + + await input.press("Escape") + await expect(picker).toBeVisible() + await expect(input).toHaveValue("C:\\OpenCode\\Picker\\beta\\") + await expect(picker.getByRole("treeitem", { name: "beta", exact: true })).toHaveAttribute("aria-selected", "true") + + await input.press("Escape") + await expect(picker).toBeHidden() +}) diff --git a/packages/app/e2e/regression/home.spec.ts b/packages/app/e2e/regression/home.spec.ts index 85734ab509f0..d1f34aa6daa6 100644 --- a/packages/app/e2e/regression/home.spec.ts +++ b/packages/app/e2e/regression/home.spec.ts @@ -10,12 +10,13 @@ import { SERVER, session, sessionHref, + tabKey, T0, } from "../utils/app" import { mockOpenCodeServer, mockServers } from "../utils/mock-server" import { fixture, mockStressTimeline } from "../utils/session-fixture" import { mockRemoteServer, mockWorkspace, newSessionLocation } from "../utils/workspace" -import { APP_READY_TIMEOUT, expectAppVisible } from "../utils/waits" +import { APP_READY_TIMEOUT, expectAppVisible, expectSessionTitle } from "../utils/waits" test.use({ serviceWorkers: "block" }) @@ -53,6 +54,176 @@ test("Home keeps the session list in every interface mode", async ({ page }) => } }) +test("choosing Customize replaces Home with Settings in desktop side tabs", async ({ page }) => { + await mockWorkspace(page, { + name: "Website", + sessions: [], + seed: { settings: { appearance: { tabLayout: "vertical" } } }, + }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + const sidebar = page.locator("#vertical-tabs-sidebar") + + const main = page.getByRole("main") + + await expect(sidebar.getByRole("button", { name: "Home", exact: true })).toBeVisible() + await main.getByRole("button", { name: "Settings", exact: true }).click() + await main.getByRole("tab", { name: "Experimental", exact: true }).click() + await main.locator('[data-action="settings-sidebar-organize"]').click() + await page.getByRole("option", { name: "Customize", exact: true }).click() + await expect(sidebar.getByRole("button", { name: "Home", exact: true })).toHaveCount(0) + await main.getByRole("button", { name: "Back to app", exact: true }).click() + await expect(main.getByRole("button", { name: "New session", exact: true })).toBeVisible() + await expect(sidebar.getByRole("button", { name: "View options", exact: true })).toBeVisible() + await sidebar.getByRole("button", { name: "Settings", exact: true }).click() + await expect(page.getByTestId("settings-screen")).toBeVisible() +}) + +async function openProjects(page: Page) { + const remote = project({ id: "proj_remote_site", directory: "/work/website", name: "Website" }) + + const earlier = session({ + id: "ses_site_release", + directory: "/work/website-release", + projectID: remote.id, + title: "Update release notes", + }) + + await mockRemoteServer(page, { + name: "Build server", + project: remote, + directory: remote.worktree, + worktrees: [{ directory: remote.worktree }, { directory: earlier.directory, strategy: "git" }], + sessions: [ + earlier, + session({ id: "ses_tools", directory: "/work/tools", projectID: "proj_tools", title: "Refresh tools" }), + ], + }) + await mockWorkspace(page, { + name: "Website", + sessions: [{ id: "ses_site_local", title: "Preview local changes" }], + seed: { + tabs: [], + usedProjects: { local: ["proj_website"], [REMOTE_SERVER]: [remote.id] }, + settings: { appearance: { tabLayout: "vertical" }, general: { sidebarOrganize: "projects" } }, + }, + }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + const sidebar = page.locator("#vertical-tabs-sidebar") + + const localGroup = sidebar.getByRole("group", { name: "Local Server", exact: true }) + + const remoteGroup = sidebar.getByRole("group", { name: "Build server", exact: true }) + + return { + remote, + earlier, + sidebar, + localToggle: localGroup.getByRole("button", { name: "Local Server", exact: true }), + remoteToggle: remoteGroup.getByRole("button", { name: "Build server", exact: true }), + localProject: localGroup.getByText("Website", { exact: true }), + remoteProject: remoteGroup.getByText("Website", { exact: true }), + } +} + +async function openRemoteHistory(page: Page, view: Awaited>) { + await view.remoteProject.click({ button: "right" }) + await page.getByRole("menuitem", { name: "View session history…", exact: true }).click() + const browser = page.getByRole("dialog", { name: "Browse projects", exact: true }) + + const history = browser.getByRole("listbox", { name: "Search sessions in Website", exact: true }).getByRole("option") + + return { browser, history } +} + +test("desktop Projects groups projects by server and collapses one server at a time", async ({ page }) => { + const view = await openProjects(page) + await expect(view.localToggle).toHaveAttribute("aria-expanded", "true") + await expect(view.remoteToggle).toHaveAttribute("aria-expanded", "true") + await expect(view.localProject).toBeVisible() + await expect(view.remoteProject).toBeVisible() + await expect(view.sidebar.getByRole("button", { name: /Browse/ })).toHaveCount(0) + + await view.remoteToggle.click() + await expect(view.remoteToggle).toHaveAttribute("aria-expanded", "false") + await expect(view.remoteProject).toBeHidden() + await expect(view.localToggle).toHaveAttribute("aria-expanded", "true") + await expect(view.localProject).toBeVisible() + await view.remoteToggle.click() + await expect(view.remoteToggle).toHaveAttribute("aria-expanded", "true") +}) + +test("desktop Projects history opens the worktree session and reopens from its location menu", async ({ page }) => { + const view = await openProjects(page) + const { browser, history } = await openRemoteHistory(page, view) + await expect(history.getByText(view.earlier.title, { exact: true })).toBeVisible() + await expect(history).toHaveCount(1) + await history.click() + await expectSessionTitle(page, view.earlier.title) + + await page.locator('[data-slot="session-location-trigger"]').click() + await page.getByRole("menuitem", { name: /Website/ }).click() + await expect(browser.getByText(view.earlier.title, { exact: true })).toBeVisible() + await page.keyboard.press("Escape") + await expect(browser).toHaveCount(0) +}) + +test("desktop Projects keeps the remote project as the next session's target after its last tab closes", async ({ + page, +}) => { + const view = await openProjects(page) + const { browser, history } = await openRemoteHistory(page, view) + await history.click() + await expectSessionTitle(page, view.earlier.title) + await expect(browser).toHaveCount(0) + await view.sidebar.getByRole("button", { name: "Close tab", exact: true }).click() + + const landing = page.getByRole("main") + + await expect(landing).toContainText("Website") + await expect(landing).toContainText("Build server") + await expect(view.remoteProject).toBeVisible() + await view.sidebar.getByRole("button", { name: "Settings", exact: true }).click() + await page.getByRole("button", { name: "Back to app", exact: true }).click() + await landing.getByRole("button", { name: "New session", exact: true }).click() + await expect(newSessionLocation(page)).toContainText("Website") + await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.remote.worktree) +}) + +test("desktop Projects resumes the remembered tab when the window opens at Home", async ({ page }) => { + const earlier = { id: "ses_earlier_tab", title: "Earlier tab" } + + const recent = { id: "ses_recent_tab", title: "Remembered tab" } + + await mockRemoteServer(page, { name: "Hidden server" }) + await seed(page, { storage: { "opencode.global.dat:server": { hidden: { [REMOTE_SERVER]: true } } } }) + await mockWorkspace(page, { + name: "Restored", + sessions: [earlier, recent], + seed: { + settings: { appearance: { tabLayout: "vertical" }, general: { sidebarOrganize: "projects" } }, + storage: { + "opencode.window.windows-menu-test.dat:tabs": [recent, earlier].map(({ id }) => ({ + type: "session", + server: "sidecar", + sessionId: id, + })), + "opencode.window.windows-menu-test.dat:tabs.recent": { key: tabKey(recent.id, "sidecar") }, + }, + }, + }) + await page.goto(`/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER })}`) + await expectSessionTitle(page, recent.title) + + const projects = page.locator("#vertical-tabs-sidebar section").filter({ + has: page.getByRole("button", { name: "Projects", exact: true }), + }) + + await expect(projects.getByText("Restored", { exact: true })).toBeVisible() + await expect(projects.getByText("Local Server", { exact: true })).toHaveCount(0) + await expect(projects.getByRole("group", { name: "Local Server", exact: true })).toHaveCount(0) + await expect(projects.getByRole("group", { name: "Hidden server", exact: true })).toHaveCount(0) +}) + test("a working Home session keeps its project avatar and shows its activity ring at the end of the row", async ({ page, }) => { diff --git a/packages/app/e2e/regression/mobile-model-pickers.spec.ts b/packages/app/e2e/regression/mobile-model-pickers.spec.ts index 1ccb5fb69309..f896d85bc9dc 100644 --- a/packages/app/e2e/regression/mobile-model-pickers.spec.ts +++ b/packages/app/e2e/regression/mobile-model-pickers.spec.ts @@ -156,28 +156,40 @@ for (const direction of ["ltr", "rtl"] as const) { await expect(variant).toHaveText("max") }) - test(`model dialog arrow keys stage a variant in ${direction}`, async ({ page }) => { + test(`model dialog arrow keys choose a variant in the flyout in ${direction}`, async ({ page }) => { const { composer, model, variant, dialog } = await openDesktopPicker(page, direction) const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) - const rowA = dialog.locator('[data-option-key="opencode:mobile-a"]') + const flyout = dialog.locator('[data-slot="model-dialog-flyout"]') + const balanced = flyout.getByRole("menuitemradio", { name: "balanced", exact: true }) + const high = flyout.getByRole("menuitemradio", { name: "high", exact: true }) const next = direction === "rtl" ? "ArrowLeft" : "ArrowRight" await model.click() await expect(search).toBeFocused() + // The highlighted row's flyout opens with the dialog, and the forward arrow enters it on the current variant. + await expect(balanced).toBeVisible() await search.press(next) - await expect(rowA).toContainText("high") + await expect(balanced).toHaveAttribute("data-highlighted", "") + await search.press("ArrowDown") + await expect(high).toHaveAttribute("data-highlighted", "") + // Escape leaves the menu first, then closes the dialog. + await search.press("Escape") + await expect(high).not.toHaveAttribute("data-highlighted") + await expect(dialog).toBeVisible() await search.press("Escape") await expect(dialog).toBeHidden() await expect(variant).toHaveText("balanced") await model.click() await search.fill("Mobile Model A") + // While searching, the forward arrow edits the query until the arrows have moved through the results. await search.press(next) await expect(search).toHaveValue("Mobile Model A") - await expect(rowA).toContainText("balanced") + await expect(balanced).not.toHaveAttribute("data-highlighted") await search.press("ArrowDown") await search.press("ArrowUp") await search.press(next) - await expect(rowA).toContainText("high") + await expect(balanced).toHaveAttribute("data-highlighted", "") + await search.press("ArrowDown") await search.press("Enter") await expect(dialog).toBeHidden() await expect(model).toHaveText("Mobile Model A") @@ -191,9 +203,14 @@ for (const direction of ["ltr", "rtl"] as const) { await prompt.fill("keep me") await prompt.press("ControlOrMeta+Quote") const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) + const flyout = dialog.locator('[data-slot="model-dialog-flyout"]') await expect(search).toBeFocused() await search.press(direction === "rtl" ? "ArrowLeft" : "ArrowRight") - await expect(dialog.locator('[data-option-key="opencode:mobile-a"]')).toContainText("high") + await expect(flyout.getByRole("menuitemradio", { name: "balanced", exact: true })).toHaveAttribute( + "data-highlighted", + "", + ) + await search.press("ArrowDown") await search.press("Enter") await expect(dialog).toBeHidden() await expect(model).toHaveText("Mobile Model A") @@ -212,28 +229,38 @@ test("desktop model button shows only the choose-model hint, not the model detai await expect(tooltip.getByText("Input & Output", { exact: true })).toHaveCount(0) }) -test("model dialog flyout waits after the arrow keys and cools down after it closes", async ({ page }) => { +test("model dialog flyout follows the arrow keys, waits while one is held, and cools down after it closes", async ({ + page, +}) => { const { model, dialog } = await openDesktopPicker(page, "ltr") const flyout = dialog.locator('[data-slot="model-dialog-flyout"]') const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) const rowA = dialog.locator('[data-option-key="opencode:mobile-a"]') const rowB = dialog.locator('[data-option-key="opencode:mobile-b"]') + const rowC = dialog.locator('[data-option-key="opencode:mobile-c"]') await model.click() await expect(search).toBeFocused() + await expect(flyout.getByRole("menuitemradio", { name: "balanced", exact: true })).toBeVisible() // See "tab preview opens cold" in tabs.spec.ts: pause at a fixed offset from an explicit install time. const start = Date.now() await page.clock.install({ time: start }) await page.clock.pauseAt(start + 10_000) - // The arrow keys take over before the hover's open delay ends, so its flyout never opens. - await rowA.hover() - await search.press("ArrowDown") - await page.clock.runFor(200) + // A single press moves the flyout at once. + await page.keyboard.down("ArrowDown") await expect(rowB).toHaveAttribute("data-active", "") + await expect(flyout.getByRole("menuitemradio", { name: "max", exact: true })).toBeVisible() + + // A held key repeats: the flyout hides until the highlight rests. + await page.keyboard.down("ArrowDown") + await page.keyboard.up("ArrowDown") + await expect(rowC).toHaveAttribute("data-active", "") await expect(flyout).toHaveCount(0) + await page.clock.runFor(200) + await expect(flyout.getByText("OpenCode · 262K context", { exact: true })).toBeVisible() + // The pointer takes the flyout over at once. await rowB.hover() - await page.clock.runFor(200) await expect(flyout.getByRole("menuitemradio", { name: "max", exact: true })).toBeVisible() // Once the flyout has been closed for a moment, the next row waits for the open delay again. diff --git a/packages/app/e2e/regression/mobile-plugins.spec.ts b/packages/app/e2e/regression/mobile-plugins.spec.ts index 97e109c8fac5..bf02c8e08573 100644 --- a/packages/app/e2e/regression/mobile-plugins.spec.ts +++ b/packages/app/e2e/regression/mobile-plugins.spec.ts @@ -187,7 +187,8 @@ test("mobile changes summarize expanded diffs, stage comments, wrap by setting, const note = "Use the existing value instead" const commented = review.locator('[data-file="src/review.ts"]') await commented.getByRole("button", { expanded: false }).click() - await commented.getByText("export const value = 'after'", { exact: true }).click() + await commented.getByText("export const value = 'after'", { exact: true }).hover() + await commented.getByRole("button", { name: "Comment", exact: true, includeHidden: true }).dispatchEvent("click") await expect(commented.locator('[data-slot="line-comment-editor-label"]')).toHaveText("Commenting on line 2") await commented.getByRole("textbox").fill(note) await commented.locator('[data-slot="line-comment-action"][data-variant="primary"]').click() diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index fb9c48b71fc4..7fd2ccf56e53 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -4,8 +4,9 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { draftHref, expectPath, holdRoute, NO_PROVIDER, project, provider, seed, sessionHref, T0 } from "../utils/app" import { mockOpenCodeServer } from "../utils/mock-server" import { - newSessionBranch, + newSessionBaseBranch, newSessionLocation, + newSessionWorktree, openDraft, openSession, openWorktreeDraft, @@ -60,60 +61,58 @@ test("the new session screen does not show session details", async ({ page }) => }) test("the location shortcuts choose worktrees from every state and keep cycling", async ({ page }) => { - const root = "C:/OpenCode/LocationShortcut" - - const existing = `${root}/.worktrees/quiet-river` + const existing = "C:/OpenCode/LocationShortcut/.worktrees/quiet-river" const view = await openDraft(page, { name: "LocationShortcut", - worktrees: () => [{ directory: root }, { directory: existing, strategy: "git" }], - vcs: (directory) => - directory === existing ? { current: "fix-login", default: "main" } : { current: "main", default: "main" }, + vcs: (directory) => ({ current: directory === existing ? undefined : "dev", default: "main" }), + worktrees: () => [{ directory: "C:/OpenCode/LocationShortcut" }, { directory: existing, strategy: "git" }], }) const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) + const cycle = `${modifier}+Alt+KeyL` + + const worktree = newSessionWorktree(page) + + const base = newSessionBaseBranch(page) + const path = page.locator('[data-slot="new-session-location-path"]') const search = page.getByRole("combobox", { name: "Search worktrees", exact: true }) - const screen = page.locator('[data-component="new-session"]') - - const expectBranchOnly = async () => { - await expect(screen).not.toContainText("Local") - await expect(screen).not.toContainText("New worktree") - await expect(screen).not.toContainText("from ") - await expect(screen.locator('[data-action="prompt-worktree"]')).toHaveCount(0) - } + await expect(path).toHaveText(view.directory) + await expect(worktree).toHaveText("dev") + await view.editor.press(cycle) + await expect(base).toHaveText("from dev") + await expect(worktree).toHaveCount(0) + await expect(page.locator('[data-component="new-session"]').getByText("New worktree", { exact: true })).toHaveCount(0) + await expect(path).toHaveCount(0) + await view.editor.press(cycle) + await expect(worktree).toHaveText("dev") + await expect(base).toHaveCount(0) + await expect(path).toHaveText(view.directory) - await expect(path).toHaveText(root) - await expect(newSessionBranch(page)).toHaveText("main") - await expectBranchOnly() await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() await page.getByRole("option", { name: /^quiet-river / }).click() await expect(view.editor).toBeFocused() await expect(path).toHaveText(existing) - await expect(newSessionBranch(page)).toHaveText("fix-login") - await expectBranchOnly() + await expect(worktree).toHaveText("No branch") await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() - await page.getByRole("option", { name: /LocationShortcut main C:\/OpenCode\/LocationShortcut$/ }).click() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(path).toHaveText(root) - await view.editor.press(`${modifier}+Alt+KeyL`) - await expect(newSessionBranch(page)).toHaveText("main") - await expect(path).toHaveText(root) - await expectBranchOnly() + await page.getByRole("option", { name: /LocationShortcut dev C:\/OpenCode\/LocationShortcut$/ }).click() + await expect(view.editor).toBeFocused() + await view.editor.press(cycle) + await expect(base).toHaveText("from dev") await view.editor.press(`${modifier}+Alt+KeyO`) await expect(search).toBeFocused() await page.getByRole("option", { name: /^quiet-river / }).click() await expect(path).toHaveText(existing) - await expect(newSessionBranch(page)).toHaveText("fix-login") await expect(view.editor).toBeFocused() }) -test("a draft opened in a worktree starts on the main checkout and targets it", async ({ page }) => { +test("the main checkout shows its branch and is targeted when the draft opened in a worktree", async ({ page }) => { const root = "C:/OpenCode/LocalFromWorktree" const worktree = `${root}/.worktrees/quiet-river` @@ -134,15 +133,15 @@ test("a draft opened in a worktree starts on the main checkout and targets it", const screen = page.locator('[data-component="new-session"]') - await expect(newSessionBranch(page)).toHaveText("checkout-branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(root) + await expect(newSessionWorktree(page)).toHaveText("checkout-branch") + await expect(screen.getByText("checkout-branch", { exact: true })).toHaveCount(1) await expect(screen.getByText("worktree-branch", { exact: true })).toHaveCount(0) await view.editor.fill("Run in the main checkout") await submit(page).click() await expect.poll(() => created).toEqual([{ directory: root }]) }) -test("the branch chip holds a placeholder while the checkout loads, then reads No branch without one", async ({ +test("the main checkout trigger holds a placeholder while its branch loads, then reads No branch without one", async ({ page, }) => { const vcs = Promise.withResolvers>>() @@ -156,13 +155,13 @@ test("the branch chip holds a placeholder while the checkout loads, then reads N }) const held = await vcs.promise - const trigger = newSessionBranch(page) + const trigger = newSessionWorktree(page) await held.arrived await expect(trigger).toHaveAttribute("aria-busy", "true") await expect(trigger).toHaveAccessibleName("Choose worktree") held.release() - await expect(trigger).not.toHaveAttribute("aria-busy", "true") + await expect(trigger).toHaveAttribute("aria-busy", "false") await expect(trigger).toHaveText("No branch") await expect(trigger).toHaveAccessibleName("No branch") await trigger.click() @@ -192,7 +191,7 @@ for (const binding of ["custom", "none"]) { await expect(tooltip).toContainText("Choose project") await expect(keys).toHaveText(binding === "custom" ? [/P$/] : []) - await newSessionBranch(page).hover() + await newSessionWorktree(page).hover() await expect(tooltip).toContainText("Isolate sessions with worktrees") await expect(keys).toHaveText(binding === "custom" ? [/X$/] : []) @@ -202,20 +201,20 @@ for (const binding of ["custom", "none"]) { if (binding === "none") { await view.editor.press(`${modifier}+Alt+o`) await expect(page.getByRole("dialog")).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionWorktree(page)).toHaveText("main") return } await view.editor.press(`${modifier}+Alt+k`) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionBaseBranch(page)).toHaveText("from main") await view.editor.press(`${modifier}+Alt+x`) const search = page.getByRole("combobox", { name: "Search worktrees", exact: true }) await expect(search).toBeFocused() await search.press("Escape") await expect(page.getByRole("dialog")).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("main") + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(view.editor).toBeFocused() await view.editor.press(`${modifier}+Alt+p`) await expect(page.getByRole("combobox", { name: "Search projects", exact: true })).toBeFocused() @@ -225,37 +224,15 @@ for (const binding of ["custom", "none"]) { test("the worktree picker shortcut is disabled for non-Git projects", async ({ page }) => { const view = await openDraft(page, { name: "NoWorktrees", project: { vcs: undefined } }) - const screen = page.locator('[data-component="new-session"]') - const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) - await expect(newSessionBranch(page)).toHaveCount(0) - await expect(screen.getByText("main", { exact: true })).toHaveCount(0) + await expect(newSessionWorktree(page)).toHaveCount(0) await view.editor.press(`${modifier}+Alt+o`) await expect(page.getByRole("dialog")).toHaveCount(0) - await view.editor.press(`${modifier}+Alt+b`) - await expect(page.getByRole("dialog")).toHaveCount(0) await view.editor.fill("Keep working locally") await expect(view.editor).toHaveText("Keep working locally") -}) - -test("a detached HEAD keeps the branch chip and opens the worktree step", async ({ page }) => { - const view = await openDraft(page, { - name: "DetachedHead", - // SAFETY: the mock reads `current` for the chip; an absent branch is how git reports a detached HEAD. - vcs: () => ({ current: undefined as never, default: "main" }), - }) - - const dialog = page.getByRole("dialog") - const search = dialog.getByRole("combobox", { name: "Search worktrees", exact: true }) - - await expect(newSessionBranch(page)).toHaveText("No branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) - await newSessionBranch(page).click() - await expect(search).toBeFocused() - await expect(dialog.getByRole("option", { name: /^from No branch/ })).toBeVisible() - await page.keyboard.press("Escape") - await expect(dialog).toHaveCount(0) + await newSessionLocation(page).click() + await expect(page.getByRole("combobox", { name: "Search projects", exact: true })).toBeFocused() }) test("picker scrollbars overlay full-width rows and support dragging", async ({ page }) => { @@ -271,7 +248,7 @@ test("picker scrollbars overlay full-width rows and support dragging", async ({ })), ], }) - await newSessionBranch(page).click() + await newSessionWorktree(page).click() await expect(page.getByRole("combobox", { name: "Search worktrees", exact: true })).toBeFocused() const menu = page.locator('[data-component="menu-scroll"]') @@ -347,14 +324,14 @@ for (const row of [ }) } -test("the dialog chooses the base branch for a new worktree", async ({ page }) => { +test("a new worktree uses the base branch chosen in the draft", async ({ page }) => { const listed = Promise.withResolvers() + const searches: { directory: string; search?: string; limit?: number }[] = [] const view = await openWorktreeDraft(page, { name: "BranchContext", - project: { name: "Custom project" }, - vcs: () => ({ current: "timeline-quotes", default: "main" }), + vcs: { current: "timeline-quotes", default: "main" }, branches: (input) => { searches.push(input) @@ -362,45 +339,49 @@ test("the dialog chooses the base branch for a new worktree", async ({ page }) = }, }) - const screen = page.locator('[data-component="new-session"]') - const dialog = page.getByRole("dialog") - const search = dialog.getByRole("combobox", { name: "Search branches", exact: true }) - const options = dialog.getByRole("option") + const base = newSessionBaseBranch(page) - await expect(newSessionBranch(page)).toHaveText("timeline-quotes") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) - await expect(screen).not.toContainText("from ") - await expect(screen).not.toContainText("New worktree") - await expect(screen).not.toContainText("Local") + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) - await newSessionBranch(page).click() - const base = dialog.getByRole("option", { name: /^from timeline-quotes/ }) - await expect(base).toBeVisible() - await base.click() + await expect(base).toHaveText("from timeline-quotes") + await expect.poll(() => searches).toEqual([{ directory: view.directory, search: "", limit: 50 }]) + await base.press("Enter") + await expect(base).toHaveAttribute("aria-expanded", "true") + await expect(search).toHaveCount(0) + listed.resolve(["timeline-quotes", "release/base"]) await expect(search).toBeFocused() - listed.resolve(["timeline-quotes", "release/base", "origin/dev"]) - await expect(search).not.toHaveAttribute("aria-busy", "true") + await expect(search).toHaveAttribute("aria-busy", "false") await expect(page.getByRole("option", { name: "release/base", exact: true })).toBeVisible() await search.fill("release") - await expect(search).not.toHaveAttribute("aria-busy", "true") + await expect(search).toHaveAttribute("aria-busy", "false") await expect(page.getByRole("option")).toHaveText(["release/base"]) await page.getByRole("option", { name: "release/base", exact: true }).click() + await expect(base).toHaveText("from release/base") + await expect(view.editor).toBeFocused() + expect(searches).toEqual([ + { directory: view.directory, search: "", limit: 50 }, + { directory: view.directory, search: "release", limit: 50 }, + ]) - // Choosing a base returns to the worktree step with that branch selected. - await expect(dialog.getByRole("option", { name: /^from release\/base/ })).toBeVisible() - await expect(search).toHaveCount(0) - await dialog.getByRole("option", { name: /^New worktree/ }).click() - await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("release/base") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) + await page.setViewportSize({ width: 390, height: 844 }) + await expect(newSessionLocation(page)).toBeInViewport({ ratio: 1 }) + await expect(base).toBeInViewport({ ratio: 1 }) + // Confirming the current destination keeps the chosen base. + await newSessionLocation(page).click() + const projects = page.getByRole("combobox", { name: "Search projects", exact: true }) + await expect(projects).toBeFocused() + await expect(page.getByRole("option", { selected: true })).toContainText("BranchContext") + await projects.press("ArrowRight") + await page.getByRole("option", { name: /^New worktree/, selected: true }).click() + await expect(base).toHaveText("from release/base") + await expect(view.editor).toBeFocused() await view.editor.fill("Use the selected base") await submit(page).click() await expect .poll(() => view.worktreeRequests.map((request) => request.body)) .toEqual([expect.objectContaining({ from: view.directory, branch: "release/base" })]) - expect(searches).toContainEqual({ directory: view.directory, search: "release", limit: 50 }) - view.worktree.resolve({ status: 200, json: { directory: "C:/OpenCode/BranchContext/.worktrees/stellar-orchid" } }) + view.worktree.resolve({ status: 200, json: { directory: `${view.directory}/.worktrees/stellar-orchid` } }) await expect .poll(() => view.prompts) .toEqual([expect.objectContaining({ body: expect.objectContaining({ text: "Use the selected base" }) })]) @@ -411,36 +392,43 @@ test("the checkout branch opens the current project's worktree step", async ({ p const view = await openDraft(page, { name: "BranchWorktrees", + project: { name: "Custom project" }, vcs: (directory) => ({ current: directory === existing ? "quiet-river-branch" : "dev", default: "main" }), worktrees: () => [{ directory: "C:/OpenCode/BranchWorktrees" }, { directory: existing, strategy: "git" }], }) const screen = page.locator('[data-component="new-session"]') - // The checkout branch is the worktree control; once a worktree is chosen its trigger shows the name. - const branch = newSessionBranch(page) + + const local = newSessionWorktree(page) + const dialog = page.getByRole("dialog") + const search = dialog.getByRole("combobox", { name: "Search worktrees", exact: true }) + const options = dialog.getByRole("option") + + const selected = dialog.getByRole("option", { selected: true }) + + const main = /Custom project dev C:\/OpenCode\/BranchWorktrees$/ + + const create = dialog.getByRole("option", { name: /^New worktree/ }) + const back = dialog.getByRole("button", { name: "Back to projects", exact: true }) - await expect(screen.getByText("Local", { exact: true })).toHaveCount(0) - await branch.click() + await expect(local).toHaveText("dev") + await local.click() await expect(search).toBeFocused() await expect(back).toHaveText("Run session in") - await expect(options.locator(".command-palette-title")).toHaveText([ - "BranchWorktrees", - "New worktree", - "from dev", - "quiet-river", - ]) - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.locator(".command-palette-title")).toHaveText(["Custom project", "New worktree", "quiet-river"]) + await search.press("ArrowDown") + await expect(create).toHaveAttribute("data-active") + await expect(selected).toHaveAccessibleName(main) // Stepping back lands on the projects step with the drilled project active, as after drilling in with →. - await search.press("Backspace") + await back.click() const projects = dialog.getByRole("combobox", { name: "Search projects", exact: true }) await expect(projects).toBeFocused() - await expect(back).toHaveCount(0) - await expect(options.filter({ hasText: "BranchWorktrees" })).toHaveAttribute("aria-selected", "true") + await expect(selected).toContainText("Custom project") await projects.press("ArrowRight") await expect(search).toBeFocused() await search.press("Escape") @@ -450,72 +438,213 @@ test("the checkout branch opens the current project's worktree step", async ({ p await expect(view.editor).toBeFocused() // A directly opened worktree picker closes on Escape without showing projects first. - await branch.focus() - await page.keyboard.press("Enter") + await local.press("Enter") await expect(search).toBeFocused() await search.press("Escape") await expect(dialog).toHaveCount(0) await expect(view.editor).toBeFocused() - // Drilling in from the project picker still makes Escape step back. - await newSessionLocation(page).click() - await expect(projects).toBeFocused() - await projects.press("ArrowRight") - await expect(search).toBeFocused() - await search.press("Escape") - await expect(projects).toBeFocused() - await projects.press("Escape") - await expect(dialog).toHaveCount(0) - - await branch.click() + await view.editor.fill("Keep this draft on the main checkout") + await local.click() await options.filter({ hasText: "quiet-river" }).click() await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("quiet-river-branch") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(existing) + await expect(local).toHaveText("quiet-river-branch") + await expect(screen.getByText("quiet-river", { exact: true })).toHaveCount(0) + await expect(screen.locator('[data-slot="new-session-location-path"]')).toHaveText(existing) + await local.click() + await expect(selected).toHaveAccessibleName(/^quiet-river /) + await search.fill("Custom project") + await expect(options).toHaveCount(1) + await dialog.getByRole("option", { name: main }).click() + await expect(local).toHaveText("dev") + await expect(screen.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) await expect(view.editor).toBeFocused() - - // Reopening from the worktree starts New worktree from the checkout's branch, not the worktree's. - await newSessionBranch(page).click() - await expect(dialog.getByRole("option", { name: /^from dev/ })).toBeVisible() - await page.keyboard.press("Escape") - await expect(dialog).toHaveCount(0) + await expect(view.editor).toHaveText("Keep this draft on the main checkout") }) -test("the branch shortcut opens the base branch step", async ({ page }) => { - const view = await openDraft(page, { +test("the branch shortcut chooses a base branch and stays inactive on the main checkout", async ({ page }) => { + const view = await openWorktreeDraft(page, { name: "BranchShortcut", - vcs: () => ({ current: "dev", default: "dev" }), + vcs: { default: "dev" }, branches: () => ["dev", "release/base"], }) const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) - const dialog = page.getByRole("dialog") + const shortcut = `${modifier}+Alt+KeyB` + + const base = newSessionBaseBranch(page) + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) - await view.editor.press(`${modifier}+Alt+KeyB`) + await expect(base).toHaveAccessibleName("Choose base branch") + await base.hover() + await expect(page.getByRole("tooltip")).toContainText("Choose base branch") + await expect(page.getByRole("tooltip").locator('[data-component="keybind-v2"]')).toContainText("B") + await expect(view.editor).toBeFocused() + await view.editor.press(shortcut) await expect(search).toBeFocused() - await expect(page.getByRole("option")).toHaveText(["dev", "release/base"]) - await search.press("Escape") - await expect(dialog).toHaveCount(0) + await search.fill("release/base") + await expect(page.getByRole("option")).toHaveText(["release/base"]) + await search.press("Enter") + await expect(base).toHaveText("from release/base") await expect(view.editor).toBeFocused() - await view.editor.press(`${modifier}+Alt+KeyB`) - await page.getByRole("option", { name: "release/base", exact: true }).click() + await view.editor.press(shortcut) + await expect(search).toBeFocused() + await search.press(shortcut) + await expect(search).toHaveCount(0) + await expect(view.editor).toBeFocused() - // Choosing a base returns to the worktree step; selecting New worktree applies it to the row. - await expect(dialog.getByRole("option", { name: /^from release\/base/ })).toBeVisible() - await dialog.getByRole("option", { name: /^New worktree/ }).click() - await expect(dialog).toHaveCount(0) - await expect(newSessionBranch(page)).toHaveText("release/base") + await base.click() + await page.getByRole("option", { name: "Use main checkout", exact: true }).click() + await expect(newSessionWorktree(page)).toHaveText("No branch") + await view.editor.press(shortcut) + await expect(search).toHaveCount(0) await expect(view.editor).toBeFocused() +}) + +test("a pending branch picker can be dismissed before its results arrive", async ({ page }) => { + const listed = Promise.withResolvers() + + const view = await openWorktreeDraft(page, { + name: "BranchDismiss", + branches: () => listed.promise, + }) - await view.editor.press(`${modifier}+Alt+KeyB`) + const base = newSessionBaseBranch(page) + + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + await base.click() + await expect(base).toHaveAttribute("aria-expanded", "true") + await expect(search).toHaveCount(0) + await view.editor.click() + await expect(base).toHaveAttribute("aria-expanded", "false") + await base.click() + await base.press("Escape") + await expect(base).toHaveAttribute("aria-expanded", "false") + await base.click() + await base.click() + await expect(base).toHaveAttribute("aria-expanded", "false") + listed.resolve(["main", "origin/dev"]) + await expect(base).toHaveAttribute("aria-busy", "false") + await expect(search).toHaveCount(0) + await base.click() await expect(search).toBeFocused() - await expect(search).toHaveValue("") - await search.press("Escape") - await expect(dialog).toHaveCount(0) - await expect(view.editor).toBeFocused() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main", "origin/dev"]) +}) + +test("reopening the branch picker shows branches created since it last opened", async ({ page }) => { + let created = false + + await openWorktreeDraft(page, { + name: "BranchRefresh", + branches: () => (created ? ["main", "feature/new"] : ["main"]), + }) + + const base = newSessionBaseBranch(page) + await base.click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main"]) + await base.click() + await expect(page.getByRole("combobox", { name: "Search branches", exact: true })).toHaveCount(0) + created = true + await base.click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/, "main", "feature/new"]) +}) + +test("branch search keeps results on screen while a query is pending", async ({ page }) => { + const held = Promise.withResolvers() + + await openWorktreeDraft(page, { + name: "BranchPending", + branches: (input) => (input.search ? held.promise : ["release/base", "release/next", "timeline-quotes"]), + }) + + await newSessionBaseBranch(page).click() + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + + const options = page.getByRole("option") + await expect(options).toHaveCount(4) + // Record any moment the list renders without rows, however brief. + await page.getByRole("listbox").evaluate((list) => { + const observer = new MutationObserver(() => { + if (!list.querySelector('[role="option"]')) list.setAttribute("data-emptied", "") + }) + + observer.observe(list, { childList: true, subtree: true }) + }) + + const next = page.getByRole("option", { name: "release/next", exact: true }) + await search.press("ArrowDown") + await search.press("ArrowDown") + await expect(next).toHaveAttribute("aria-selected", "true") + await search.pressSequentially("release") + await expect(search).toHaveAttribute("aria-busy", "true") + await expect(options).toHaveText(["release/base", "release/next"]) + await expect(next).toHaveAttribute("aria-selected", "true") + await search.fill("") + await expect(options).toHaveCount(4) + await search.pressSequentially("quotes") + await expect(options).toHaveText(["timeline-quotes"]) + await search.pressSequentially("-missing") + await expect(options).toHaveText(["timeline-quotes"]) + await expect(page.getByRole("listbox")).not.toHaveAttribute("data-emptied") + + held.resolve([]) + await expect(page.getByText("No results found", { exact: true })).toBeVisible() + await expect(search).toHaveAttribute("aria-busy", "false") +}) + +test("the empty branch search state is as tall as a single result", async ({ page }) => { + await openWorktreeDraft(page, { + name: "BranchEmptyHeight", + branches: () => [], + }) + + await newSessionBaseBranch(page).click() + await expect(page.getByRole("option")).toHaveText([/^Use main checkout/]) + const panel = page.getByRole("dialog") + // Measured on open, before any search animates the panel. + const single = await panel.evaluate((element) => element.getBoundingClientRect().height) + + await page.getByRole("combobox", { name: "Search branches", exact: true }).fill("missing") + await expect(page.getByText("No results found", { exact: true })).toBeVisible() + await expect.poll(() => panel.evaluate((element) => element.getBoundingClientRect().height)).toBe(single) +}) + +test("backspacing keeps confirmed branch results until the broader search answers", async ({ page }) => { + const broader = Promise.withResolvers() + + const closed = ["closed-search-beta", "closed-session-search", "reopen-closed-tab", "recently-closed-projects"] + + await openWorktreeDraft(page, { + name: "BranchBackspace", + branches: (input) => { + if (input.search === "clo") return broader.promise + + if (input.search) return closed + + return [...closed, "origin/cloudflare-run-images", "origin/cloudflare-run-functions"] + }, + }) + + await newSessionBaseBranch(page).click() + const search = page.getByRole("combobox", { name: "Search branches", exact: true }) + + const options = page.getByRole("option") + await expect(options).toHaveCount(7) + await search.fill("closed") + await expect(search).toHaveAttribute("aria-busy", "false") + await expect(options).toHaveText(closed) + await search.press("Backspace") + await search.press("Backspace") + await search.press("Backspace") + await expect(search).toHaveValue("clo") + await expect(search).toHaveAttribute("aria-busy", "true") + await expect(options).toHaveText(closed) + broader.resolve([...closed, "clover-fix"]) + await expect(search).toHaveAttribute("aria-busy", "false") + await expect(options).toHaveText([...closed, "clover-fix"]) }) test("the dark new session panel exposes no lighter background at its rounded corners", async ({ page }) => { @@ -677,18 +806,37 @@ test("a pending worktree session keeps Session as its mobile title until the gen await expect(label).toHaveText("Generated session title") }) -test("the title and message stay stable through worktree creation", async ({ page }) => { - const mock = await openWorktreeDraft(page, pendingDraft) - const pending = await submitPending(page, mock) +test("the title and folded message stay stable through worktree creation", async ({ page }) => { + const mock = await openWorktreeDraft(page, { + ...pendingDraft, + seed: { settings: { general: { foldUserMessages: true } } }, + }) + + const wrappedPrompt = `${text} `.repeat(35).trimEnd() + + const [firstHeight, pending] = await Promise.all([ + page.waitForFunction(() => { + const message = document.querySelector('[data-component="session-preparing"] [data-component="user-message"]') + + if (message?.checkVisibility({ checkVisibilityCSS: true, checkOpacity: true })) { + return message.getBoundingClientRect().height + } + }), + submitPending(page, mock, wrappedPrompt), + ]) + + const readMore = pending.message.getByRole("button", { name: "Read more", expanded: false }) + await expect(readMore).toBeVisible() await draftFollowUp(page) - await editor(page).press("ControlOrMeta+Home") + await editor(page).evaluate((element) => getSelection()!.collapse(element, 0)) const title = page.locator("[data-session-title]").getByRole("heading", { level: 1 }) const before = await title.boundingBox() const messageBefore = await pending.message.boundingBox() + expect(await firstHeight.jsonValue()).toBe(messageBefore?.height) // Observe painted frames during the handoff, without using frame counts to wait for readiness. const observation = await page.evaluateHandle(() => { - const frames: { title: string | null; message: boolean; spinner: boolean; draft: string | null }[] = [] + const frames: { title: string | null; messageHeight: number | null; spinner: boolean; draft: string | null }[] = [] let frame = 0 const visible = (element: Element | null) => @@ -696,10 +844,13 @@ test("the title and message stay stable through worktree creation", async ({ pag const sample = () => { const title = document.querySelector("[data-session-title] h1") + + const message = document.querySelector('[data-component="user-message"]') + const editor = document.querySelector('[data-component="composer-editor"]') frames.push({ title: visible(title) ? title!.textContent : null, - message: visible(document.querySelector('[data-component="user-message"]')), + messageHeight: visible(message) ? message!.getBoundingClientRect().height : null, spinner: visible( document.querySelector('[data-titlebar-tab-slot][data-active="true"] [data-component="activity-ring"]'), ), @@ -725,7 +876,8 @@ test("the title and message stay stable through worktree creation", async ({ pag await expect(title).toHaveText("Created workspace session") await expect(pending.shimmer).toHaveCount(0) - await expect(pending.message.locator('[data-slot="user-message-text"]')).toHaveText(text) + await expect(pending.message.locator('[data-slot="user-message-fold"]')).toHaveText(wrappedPrompt) + await expect(readMore).toBeVisible() await expect(editor(page)).toHaveText(followUp) await expect(editor(page)).toBeFocused() // The DOM can reach the final state before the sampler's next frame; wait until a sample has observed it. @@ -737,7 +889,7 @@ test("the title and message stay stable through worktree creation", async ({ pag expect( frames.filter( (frame) => - !frame.message || + frame.messageHeight !== messageBefore?.height || !frame.spinner || frame.draft !== followUp || !["Session", "Created workspace session"].includes(frame.title ?? ""), @@ -827,8 +979,7 @@ for (const row of [ if (row.followUp) return await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(directory) + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(pending.message).toHaveCount(0) await expect(tabLink(page, pending.sessionID)).toHaveCount(0) expect(mock.creates).toEqual([]) @@ -845,7 +996,6 @@ test("retains the draft and reuses the created workspace after session creation await expect(page.getByText("Failed to create session", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(text) await expect(submit(page)).toBeEnabled() - await expect(newSessionBranch(page)).toHaveText("main") await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(workspace) await expect(pending.shimmer).toHaveCount(0) await expect(pending.message).toHaveCount(0) @@ -1020,8 +1170,7 @@ test("restores the draft after closing and revisiting a pending session that fai await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(`${text}\n\n${followUp}`) await expect(submit(page)).toBeEnabled() - await expect(newSessionBranch(page)).toHaveText("main") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(directory) + await expect(newSessionBaseBranch(page)).toHaveText("from main") await expect(page.locator(`[data-titlebar-tab-link][href="${draftHref(draftID)}"]`)).toHaveCount(1) await expect(tab).toHaveCount(0) await expect(pending.message).toHaveCount(0) @@ -1099,6 +1248,7 @@ test("the location dialog separates added projects from server projects and tags server: apollo, directory: remote.worktree, project: remote, + vcs: { current: "apollo-release", default: "main" }, projects: () => [remote, entry("proj_apollo_sst", "/home/dax/sst", 3)], worktrees: () => [{ directory: remote.worktree }, { directory: "/home/dax/opencode-beta", strategy: "git" }], provider: NO_PROVIDER, @@ -1115,6 +1265,7 @@ test("the location dialog separates added projects from server projects and tags usedProjects: { [apollo]: [remote.id] }, }) const local = entry("proj_opencode", "C:/work/opencode", 2) + await openDraft(page, { name: "opencode", hostname: "hailmary", @@ -1133,7 +1284,10 @@ test("the location dialog separates added projects from server projects and tags const rows = options.filter({ has: page.locator(".new-session-location-name") }) const names = options.locator(".new-session-location-name") const paths = options.locator(".command-palette-description") - const back = dialog.getByRole("button", { name: "Back to projects", exact: true }) + const back = dialog.locator(".new-session-location-back") + const arrow = dialog.locator(".new-session-location-search-back") + const leading = dialog.locator("[data-slot='text-input-v2-leading-icon']") + const input = dialog.locator("[data-slot='text-input-v2-input']") // Only the projects added to this client open expanded; other ready-server projects remain discoverable. await expect(names).toHaveText(["opencodeapollo", "opencode"]) await expect(paths).toHaveText(["/home/dax/opencode", "C:/work/opencode"]) @@ -1150,11 +1304,11 @@ test("the location dialog separates added projects from server projects and tags // It opens on the first row, not on the draft's current project (the second row). await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") - // The picker shares the palette's full-width search, compact rows, and single-line titles. - await expect(options.nth(0)).toHaveCSS("height", "28px") + // The picker shares the palette's full-width search, 32px rows, and single-line titles. + await expect(options.nth(0)).toHaveCSS("height", "32px") await expect(dialog.locator(".palette-menu-search [data-component='text-input-v2']")).toHaveCSS("height", "28px") await expect(dialog.locator(".new-session-location-hints")).toHaveCount(0) - await expect(dialog.locator("..")).toHaveCSS("width", "880px") + await expect(dialog.locator("..")).toHaveCSS("width", "720px") await expect(options.nth(0)).toHaveCSS("display", "flex") await expect(names.nth(0).locator(".command-palette-title")).toHaveCSS("font-size", "13px") await expect(names.nth(0).locator(".command-palette-title")).toHaveCSS("white-space", "nowrap") @@ -1174,12 +1328,23 @@ test("the location dialog separates added projects from server projects and tags }) .toBeLessThanOrEqual(1) + await expect(arrow).toHaveCount(0) + const leadingBox = await leading.boundingBox() + const inputBox = await input.boundingBox() + await others.click() + await expect(names).toHaveText(["console", "sstapollo"]) + await expect(back).toHaveCount(0) + await expect(arrow).toBeVisible() + await expect(search).toHaveAttribute("placeholder", "Search other projects") + expect(await leading.boundingBox()).toEqual(leadingBox) + expect(await input.boundingBox()).toEqual(inputBox) + await arrow.click() + await expect(names).toHaveText(["opencodeapollo", "opencode"]) + await expect(search).toBeFocused() await others.click() await expect(names).toHaveText(["console", "sstapollo"]) - await expect(back).toHaveText("Other projects") await search.fill("no-project-matches") await expect(options).toHaveCount(0) - await expect(back).toBeVisible() await search.fill("") await expect(names).toHaveText(["console", "sstapollo"]) await search.press("ArrowLeft") @@ -1191,9 +1356,6 @@ test("the location dialog separates added projects from server projects and tags await expect(names).toHaveText(["console", "sstapollo"]) await search.press("Escape") await expect(names).toHaveText(["opencodeapollo", "opencode"]) - await others.click() - await back.click() - await expect(names).toHaveText(["opencodeapollo", "opencode"]) await search.fill("apollo") await expect(names).toHaveText(["opencodeapollo", "sstapollo"]) @@ -1208,12 +1370,11 @@ test("the location dialog separates added projects from server projects and tags await expect(add).toHaveCount(0) await expect(back).toHaveText("Run session in") await expect(options.nth(0).locator('[data-component="tag"]')).toHaveText("apollo") - await expect(options.locator(".command-palette-title")).toHaveText([ - "opencode", - "New worktree", - "from main", - "opencode-beta", - ]) + await expect(dialog.getByRole("option", { selected: true })).toHaveCount(0) + await search.fill("apollo-release") + await expect(options).toHaveText([/opencode.*apollo-release.*\/home\/dax\/opencode/]) + await search.fill("") + await expect(options.locator(".command-palette-title")).toHaveText(["opencode", "New worktree", "opencode-beta"]) await expect(dialog.getByRole("separator")).toHaveCount(1) await search.fill("opencode-beta") await expect(options).toHaveCount(1) @@ -1225,20 +1386,16 @@ test("the location dialog separates added projects from server projects and tags const open = (await page.evaluate(() => navigator.platform.includes("Mac"))) ? "Meta+o" : "Control+o" await search.fill("open") await page.keyboard.press(open) - await expect(back).toHaveText("Servers") + await expect(back).toHaveCount(0) + await expect(search).toHaveAttribute("placeholder", "Search servers") await expect(search).toHaveValue("") await page.keyboard.press("Escape") await expect(back).toHaveText("Run session in") await expect(search).toHaveValue("open") - await expect(options.locator(".command-palette-title")).toHaveText([ - "opencode", - "New worktree", - "from main", - "opencode-beta", - ]) - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.locator(".command-palette-title")).toHaveText(["opencode", "New worktree", "opencode-beta"]) + await expect(options.nth(0)).toHaveAttribute("data-active") await search.fill("") - await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") + await expect(options.nth(0)).toHaveAttribute("data-active") await page.keyboard.press("Backspace") await expect(search).toHaveValue("opencode") await expect(rows.nth(0)).toHaveAttribute("aria-selected", "true") @@ -1249,10 +1406,10 @@ test("the location dialog separates added projects from server projects and tags await page.keyboard.press("ArrowUp") await expect(options.nth(3)).toHaveAttribute("aria-selected", "true") await page.keyboard.press(open) - await expect(back).toHaveText("Servers") + await expect(back).toHaveCount(0) // The server the app runs beside shows its hostname and "This computer" instead of its address. await expect(options).toHaveText(["hailmaryThis computer", "apollo"]) - await back.click() + await search.press("Escape") await options.filter({ hasText: "Add project" }).click() await expect(options).toHaveText(["hailmaryThis computer", "apollo"]) await options.filter({ hasText: "apollo" }).click() @@ -1424,7 +1581,7 @@ async function submitPending(page: Page, mock: Awaited + page.evaluate(() => navigator.clipboard.readText()).then((text) => text.replace(/\r\n/g, "\n")) + const notes = [ "---", "description: Release checklist", @@ -991,6 +997,8 @@ test("artifact actions copy and download content, switch source, and follow the if (path === "broken.svg") return { content: broken } + if (path === "src/greet.ts") return { content: code } + return { type: "binary", content: "AAEC", encoding: "base64" } }, pageMessages: () => ({ @@ -1003,7 +1011,7 @@ test("artifact actions copy and download content, switch source, and follow the content: [ { type: "text", - text: "---\ndescription: Chat heading\n---\n\n[Vector](vector.svg) [Table](data.csv) [Notes](notes.md) [Binary](sample.bin) [Broken](broken.svg)", + text: "---\ndescription: Chat heading\n---\n\n[Vector](vector.svg) [Table](data.csv) [Notes](notes.md) [Binary](sample.bin) [Broken](broken.svg) [Code](src/greet.ts)", }, ], time: { created: 1, completed: 2 }, @@ -1120,10 +1128,7 @@ test("artifact actions copy and download content, switch source, and follow the expect(surface.y - bar.y - bar.height).toBe(1) await expect(panel.getByRole("group", { name: "Preview controls", exact: true })).toHaveCount(0) await copy.click() - // Chromium writes CRLF to the Windows clipboard. - await expect - .poll(() => page.evaluate(() => navigator.clipboard.readText()).then((text) => text.replace(/\r\n/g, "\n"))) - .toBe(notes) + await expect.poll(clipboardText).toBe(notes) await page.getByRole("button", { name: "Dismiss", exact: true }).click() await sourceAction.click() await expect(paper).toHaveCount(0) @@ -1146,6 +1151,15 @@ test("artifact actions copy and download content, switch source, and follow the await expect(panel.getByText("Couldn't load this file.", { exact: true })).toBeVisible() await toolbar.getByRole("button", { name: "View source", exact: true }).click() await expect(panel.locator("diffs-container")).toContainText(broken) + + await page.getByRole("link", { name: "Code", exact: true }).click() + await expect(panel.locator('diffs-container [data-line="2"]')).toHaveText("return `Hello, ${name}!`") + await expect(toolbar.getByText("greet.ts", { exact: true })).toBeVisible() + await expect(toolbar.getByRole("button", { name: /^View (source|preview)$/ })).toHaveCount(0) + await copy.click() + await expect.poll(clipboardText).toBe(code) + await actions.click() + await expect(page.getByRole("menu").getByRole("menuitem")).toHaveText(["Download", "Copy path"]) }) test("Markdown and DOCX sheets stay aligned when switching at wide and narrow preview widths", async ({ page }) => { diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 2817bdc8b957..1152b0ac027c 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -6,6 +6,8 @@ import { mockRemoteServer, mockWorkspace, openSession, openSettings, type Worksp import { CONSOLE_URL, consoleGateway, consoleSignIn } from "../utils/console" import { recordNotifications } from "../utils/notifications" import { installSseTransport } from "../utils/sse-transport" +import { dict as ar } from "../../src/runtime/i18n/ar" +import { dict as en } from "../../src/runtime/i18n/en" const directory = "C:/Projects/settings-demo" @@ -61,6 +63,21 @@ test("settings has its own route and returns through app history", async ({ page const { settings } = await open(page) const home = page.getByRole("button", { name: "Home", exact: true }) await expect(page).toHaveURL("/settings") + await expect(settings.getByRole("tab")).toHaveText([ + "Preferences", + "Appearance", + "Notifications", + "Shortcuts", + "Providers", + "Models", + "Extensions", + "Projects", + "Worktrees", + "Server", + "Experimental", + "About", + ]) + await expect(settings.getByRole("tab", { name: "Preferences", exact: true })).toHaveAttribute("aria-selected", "true") await expect(home).toHaveAttribute("aria-pressed", "false") await settings.getByRole("button", { name: "Back to app", exact: true }).click() await expect(page).toHaveURL("/") @@ -274,8 +291,20 @@ test("request events use real Questions settings without disabling Permissions a .toEqual([...previews, expect.stringContaining("alert-01"), expect.stringContaining("alert-01")]) }) -for (const locale of ["en", "ar"]) { +for (const [locale, dict] of [ + ["en", en], + ["ar", ar], +] as const) { test(`background activity alignment stays physical and persists (${locale})`, async ({ page }) => { + const label = dict["settings.timeline.row.backgroundActivity.title"] + + const names = { + Hidden: dict["settings.timeline.row.backgroundActivity.off"], + Left: dict["settings.timeline.row.backgroundActivity.left"], + Center: dict["settings.timeline.row.backgroundActivity.center"], + Right: dict["settings.timeline.row.backgroundActivity.right"], + } + const id = "ses_activity_settings" const childID = "ses_activity_settings_child" const stopped: string[] = [] @@ -352,13 +381,13 @@ for (const locale of ["en", "ar"]) { for (const value of ["Center", "Right", "Hidden", "Left", "Right"] as const) { await page.keyboard.press("Control+,") const settings = page.getByTestId("settings-screen") - const control = settings.getByLabel("Background activity", { exact: true }) + const control = settings.getByLabel(label, { exact: true }) await expect(control).toBeVisible() await control.click() const options = page.getByRole("listbox") - await expect(options.getByRole("option")).toHaveText(["Hidden", "Left", "Center", "Right"]) - await options.getByRole("option", { name: value, exact: true }).click() - await expect(control).toHaveText(value) + await expect(options.getByRole("option")).toHaveText([names.Hidden, names.Left, names.Center, names.Right]) + await options.getByRole("option", { name: names[value], exact: true }).click() + await expect(control).toHaveText(names[value]) await page.goBack() if (value === "Hidden") { @@ -413,9 +442,7 @@ for (const locale of ["en", "ar"]) { .toBe("right") await page.keyboard.press("Control+,") await page.reload() - await expect(page.getByTestId("settings-screen").getByLabel("Background activity", { exact: true })).toHaveText( - "Right", - ) + await expect(page.getByTestId("settings-screen").getByLabel(label, { exact: true })).toHaveText(names.Right) }) } @@ -2224,8 +2251,17 @@ test("providers: the account options rename and remove the active account", asyn await settings.getByRole("tab", { name: "Providers", exact: true }).click() await expect(trigger).toHaveText("Shared") + const confirm = page.getByRole("dialog", { name: "Remove Shared?", exact: true }) await settings.getByRole("button", { name: "Shared options", exact: true }).click() await page.getByRole("menuitem", { name: "Remove", exact: true }).click() + await confirm.getByRole("button", { name: "Cancel", exact: true }).click() + await expect(confirm).toBeHidden() + await expect(trigger).toHaveText("Shared") + expect(removed).toEqual([]) + + await settings.getByRole("button", { name: "Shared options", exact: true }).click() + await page.getByRole("menuitem", { name: "Remove", exact: true }).click() + await confirm.getByRole("button", { name: "Remove", exact: true }).click() await expect.poll(() => removed).toEqual(["cred_work"]) }) @@ -2242,6 +2278,10 @@ test("providers: a disconnect that finds no stored credentials keeps the provide await expect(connected.getByText("OpenRouter", { exact: true })).toBeVisible() await disconnect.click() + await page + .getByRole("dialog", { name: "Disconnect OpenRouter?", exact: true }) + .getByRole("button", { name: "Disconnect", exact: true }) + .click() await expect(page.getByText("No removable credentials found for OpenRouter", { exact: true })).toBeVisible() await expect(connected.getByText("OpenRouter", { exact: true })).toBeVisible() await expect(disconnect).toBeVisible() diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index c322364f19f3..a5e18d0ccc44 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -1,4 +1,4 @@ -import { expect, test, type Page } from "@playwright/test" +import { expect, test, type Locator, type Page } from "@playwright/test" import type { OpenCodeEvent, SessionMessageInfo } from "@opencode/client/promise" import { NO_PROVIDER, @@ -504,12 +504,37 @@ test("option arrows move to the previous or next tab, and with shift to the next await expectPath(page, sessionHref(c.id)) }) -for (const navigation of ["horizontal", "vertical", "keyboard"] as const) { - test(`switching session tabs restores the caret and pastes into the destination draft (${navigation})`, async ({ +const clickTab = (_: Page, tab: Locator) => tab.click() + +const press = (key: string) => (page: Page) => page.keyboard.press(key) + +for (const row of [ + { navigation: "horizontal", toB: clickTab, toA: press("Control+Alt+ArrowLeft"), backToB: clickTab }, + { navigation: "vertical", toB: clickTab, toA: press("Control+Alt+ArrowLeft"), backToB: clickTab }, + { + navigation: "keyboard", + toB: press("Control+Alt+ArrowRight"), + toA: press("Control+Alt+ArrowLeft"), + backToB: clickTab, + }, + { + navigation: "numbered", + // Pressed in a titlebar control, which stays mounted and keeps focus while the destination composer mounts. + toB: async (page: Page) => { + const home = page.locator('[data-slot="titlebar-v2"]').getByRole("button", { name: "Home", exact: true }) + await home.focus() + await expect(home).toBeFocused() + await page.keyboard.press("ControlOrMeta+2") + }, + toA: press("ControlOrMeta+1"), + backToB: press("ControlOrMeta+2"), + }, +]) { + test(`switching session tabs restores the caret and pastes into the destination draft (${row.navigation})`, async ({ page, context, }) => { - const tabLayout = navigation === "vertical" ? "vertical" : "horizontal" + const tabLayout = row.navigation === "vertical" ? "vertical" : "horizontal" const strip = page.locator( tabLayout === "vertical" ? '[data-slot="vertical-tabs-sidebar"]' : '[data-slot="titlebar-tabs"]', @@ -525,14 +550,14 @@ for (const navigation of ["horizontal", "vertical", "keyboard"] as const) { const tabB = strip.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`) await editor.fill("Draft A") - await (navigation === "keyboard" ? page.keyboard.press("Control+Alt+ArrowRight") : tabB.click()) + await row.toB(page, tabB) await expectPath(page, sessionHref(b.id)) await expect(editor).toBeFocused() await page.evaluate(() => navigator.clipboard.writeText("Draft B")) await page.keyboard.press("ControlOrMeta+V") await expect(editor).toHaveText("Draft B") - await page.keyboard.press("Control+Alt+ArrowLeft") + await row.toA(page) await expectPath(page, sessionHref(a.id)) await expect(editor).toBeFocused() await expect(editor).toHaveText("Draft A") @@ -540,7 +565,7 @@ for (const navigation of ["horizontal", "vertical", "keyboard"] as const) { await page.keyboard.press("ControlOrMeta+V") await expect(editor).toHaveText("Draft A appended") - await tabB.click() + await row.backToB(page, tabB) await expectPath(page, sessionHref(b.id)) await expect(editor).toBeFocused() await expect(editor).toHaveText("Draft B") @@ -814,7 +839,7 @@ test("Recent shows the last 7 days, and Show more reveals 30 more rows, fetching await expect(more).toBeHidden() }) -test("Recent keeps the server's order from its last reload, which a run end or window focus triggers", async ({ +test("Recent keeps the server's order through renames, run ends and window focus, and reloads for a new session", async ({ page, }) => { const t = Date.now() - 60_000 @@ -831,6 +856,11 @@ test("Recent keeps the server's order from its last reload, which a run end or w }, }) + let pageOneLoads = 0 + page.on("request", (request) => { + if (/\/api\/session\?.*archived=false/.test(request.url())) pageOneLoads++ + }) + await page.clock.install() await page.goto( `/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER, path: sessionHref(a.id, "sidecar") })}`, ) @@ -864,22 +894,57 @@ test("Recent keeps the server's order from its last reload, which a run end or w await expect(rows.first()).toContainText("Tab B session") await expect(rows.last()).toContainText("Renamed A session") - // The window coming back reloads the list, as the iOS app does when it returns to the foreground. - await page.evaluate(() => window.dispatchEvent(new Event("focus"))) - await expect(rows).toHaveText([/Renamed A session/, /Tab B session/]) - - advance(b.id, { updated: t + 3, idle: t + 3 }) + // A run end and the window coming back leave the order alone; the rename after the run end shows it arrived. + advance(a.id, { updated: t + 3, idle: t + 3 }, "Finished A session") await workspace.push([ { id: "evt_recent_order_run_end", created: t + 3, type: "session.execution.succeeded", location: { directory: workspace.directory }, - durable: { aggregateID: b.id, seq: 1, version: 1 }, - data: { sessionID: b.id }, + durable: { aggregateID: a.id, seq: 2, version: 1 }, + data: { sessionID: a.id }, } satisfies Extract, + { + id: "evt_recent_order_rename_after_run", + created: t + 3, + type: "session.renamed", + location: { directory: workspace.directory }, + durable: { aggregateID: a.id, seq: 3, version: 1 }, + data: { sessionID: a.id, title: "Finished A session" }, + } satisfies Extract, + ]) + await expect(rows).toHaveText([/Tab B session/, /Finished A session/]) + await page.evaluate(() => { + window.dispatchEvent(new Event("focus")) + document.dispatchEvent(new Event("visibilitychange")) + }) + // Past the reload debounce, so a reload either trigger had queued would have requested page one by now. + await page.clock.runFor(1_000) + await expect(rows).toHaveText([/Tab B session/, /Finished A session/]) + expect(pageOneLoads).toBe(1) + + // A new root session reloads page one, which brings in A's newer server time too. + const created = session({ id: "ses_tab_new", title: "Fresh session", directory: workspace.directory, created: t + 4 }) + workspace.sessions.push(created) + await workspace.push([ + { + id: "evt_recent_order_created", + created: t + 4, + type: "session.created", + location: { directory: workspace.directory }, + durable: { aggregateID: created.id, seq: 1, version: 1 }, + data: { + sessionID: created.id, + projectID: workspace.projectID, + location: { directory: workspace.directory }, + slug: created.slug, + version: created.version, + }, + } satisfies Extract, ]) - await expect(rows).toHaveText([/Tab B session/, /Renamed A session/]) + await expect(rows).toHaveText([/Fresh session/, /Finished A session/, /Tab B session/]) + expect(pageOneLoads).toBe(2) }) test("an unfocused window preserves a restored manual unread reminder", async ({ page }) => { diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 38b128fb4309..324ede83bce9 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1566,17 +1566,12 @@ test.describe("compaction", () => { await expect(page.locator('[data-component="session-working"]')).toBeVisible() }) - test("shows an automatic compaction as one quiet divider with background compaction on", async ({ page }) => { - const config = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/config") - + test("shows an automatic compaction as one quiet divider", async ({ page }) => { const timeline = await setupTimeline(page, { sessionMessages: [user, completed], sessionStatus: { [sessionID]: { type: "busy" } }, - configEntries: [{ type: "document", info: { experimental: { background_compaction: true } } }], }) - await config - await timeline.send(compactionStarted({ sessionID, reason: "auto" })) await timeline.send(compactionDelta({ sessionID, text: "Partial automatic summary." })) const compaction = page.locator('[data-component="session-compaction-message"]') @@ -1640,11 +1635,17 @@ test.describe("compaction", () => { await timeline.send(compactionDelta({ sessionID, text: outcome.partial })) await expect(compactions).toHaveCount(index + 1) const compaction = compactions.nth(index) - await expect(compaction).toContainText(outcome.partial) - if (name === "interrupted") { - await expect(compaction.getByRole("status").getByLabel("Compacting", { exact: true })).toBeVisible() + // An automatic compaction runs as one quiet divider; a manual one streams its summary. + if (outcome.reason === "auto") + await expect(compaction.locator('[data-slot="session-compaction-divider"]')).toHaveAttribute( + "data-state", + "running", + ) + + if (outcome.reason === "manual") await expect(compaction).toContainText(outcome.partial) + if (name === "interrupted") { const request = page.waitForRequest( (request) => request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/interrupt`, diff --git a/packages/app/e2e/user-story/model-selection-flow.spec.ts b/packages/app/e2e/user-story/model-selection-flow.spec.ts index 1a4b3322a6ee..f2ac58478e16 100644 --- a/packages/app/e2e/user-story/model-selection-flow.spec.ts +++ b/packages/app/e2e/user-story/model-selection-flow.spec.ts @@ -84,13 +84,15 @@ test("creates a session in a new project and selects its model", async ({ page } return url.pathname === "/api/fs/list" && url.searchParams.get("path") === "C:/OpenCode" }) - await picker.getByRole("button", { name: "Parent", exact: true }).click() + await picker + .getByRole("navigation", { name: "Folder path", exact: true }) + .getByRole("button", { name: "OpenCode", exact: true }) + .click() expect(new URL((await listing).url()).searchParams.get("location[directory]")).toBe(directory) const directoryItem = picker.getByRole("treeitem", { name: "NewProject", exact: true }) await expect(directoryItem).toBeVisible() await directoryItem.click() await expect(directoryItem).toHaveAttribute("aria-selected", "true") - await expect(picker.getByText("C:\\OpenCode\\NewProject", { exact: true })).toBeVisible() const selectFolder = picker.getByRole("button", { name: "Select folder", exact: true }) await expect(selectFolder).toBeEnabled() await selectFolder.click() diff --git a/packages/app/e2e/utils/workspace.ts b/packages/app/e2e/utils/workspace.ts index 6c3edfb25122..96e738e63c22 100644 --- a/packages/app/e2e/utils/workspace.ts +++ b/packages/app/e2e/utils/workspace.ts @@ -88,19 +88,23 @@ export async function openDraft( return { ...workspace, draftID, editor } } -// Opens a draft on the local project with "New worktree" selected. Worktree creation stays pending until the test -// resolves `worktree`; POST order (`worktree`, `session`, `prompt`), worktree requests, session creates and prompts are -// recorded. The draft tab comes first, then a tab per session. // The new-session trigger that shows the draft's project and opens the location dialog on its projects. export function newSessionLocation(page: Page) { return page.locator('[data-component="new-session"] [data-action="prompt-project"]') } -// The new-session branch chip for the selected branch. It opens the project's worktree step. -export function newSessionBranch(page: Page) { - return page.locator('[data-component="new-session"] [data-action="prompt-branch"]') +// The selected checkout's branch opens the project's worktree step. +export function newSessionWorktree(page: Page) { + return page.locator('[data-component="new-session"] [data-action="prompt-worktree"]') +} + +export function newSessionBaseBranch(page: Page) { + return page.locator('[data-component="new-session"] button[aria-description="Choose base branch"]') } +// Opens a draft on the local project with "New worktree" selected. Worktree creation stays pending until the test +// resolves `worktree`; POST order (`worktree`, `session`, `prompt`), worktree requests, session creates and prompts are +// recorded. The draft tab comes first, then a tab per session. export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { draftID?: string }) { const worktree = Promise.withResolvers<{ status: number; json: unknown }>() const calls: string[] = [] @@ -148,9 +152,10 @@ export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { dr await page.goto(draftHref(draftID)) const editor = page.locator('[data-component="composer-editor"]') await expect(editor).toBeVisible({ timeout: APP_READY_TIMEOUT }) - await newSessionBranch(page).click() + await newSessionWorktree(page).click() await expect(page.getByRole("combobox", { name: "Search worktrees", exact: true })).toBeFocused() await page.getByRole("option", { name: /^New worktree/ }).click() + await expect(newSessionBaseBranch(page)).toBeVisible() await expect(editor).toBeEditable() return { ...workspace, draftID, editor, worktree, calls, worktreeRequests, creates, prompts } diff --git a/packages/app/package.json b/packages/app/package.json index 6b76d843204f..508e5d06445f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/app", - "version": "2.3.0", + "version": "2.3.1", "description": "", "type": "module", "exports": { diff --git a/packages/app/src/components-lab/dialog-story-runtime.tsx b/packages/app/src/components-lab/dialog-story-runtime.tsx index 23b0a41d06e1..8ad8d06cc8a0 100644 --- a/packages/app/src/components-lab/dialog-story-runtime.tsx +++ b/packages/app/src/components-lab/dialog-story-runtime.tsx @@ -1,4 +1,4 @@ -import type { IntegrationInfo } from "@opencode/client/promise" +import type { IntegrationInfo, PluginInfo } from "@opencode/client/promise" import { QueryClient, QueryClientProvider } from "@tanstack/solid-query" import type { ParentProps } from "solid-js" import { LocalProvider } from "@/providers/models/selection" @@ -503,6 +503,28 @@ type DialogStoryRuntimeOptions = { const REDIRECT_PASTE = ["openai", "gitlab", "snowflake-cortex"] +/** Package plugins for the Plugins tab: two with a newer version, so its update controls show. */ +const storyPlugins: PluginInfo[] = [ + { + id: "wakatime", + source: { type: "package", target: "opencode-wakatime@latest", version: "1.2.0", outdated: true }, + features: { server: true }, + state: { status: "active" }, + }, + { + id: "notifier", + source: { type: "package", target: "opencode-notifier@latest", version: "0.4.1", outdated: true }, + features: { server: true, tui: true }, + state: { status: "active" }, + }, + { + id: "review", + source: { type: "package", target: "@acme/opencode-review@latest", version: "2.0.3" }, + features: { server: true }, + state: { status: "active" }, + }, +] + export function createStoryFetch(overrides: IntegrationInfo[] = []): typeof fetch { const integrations = [ ...overrides, @@ -715,6 +737,14 @@ export function createStoryFetch(overrides: IntegrationInfo[] = []): typeof fetc if (pathname === "/api/session/active") return jsonResponse({ data: {} }) + if (pathname === "/api/plugin") return jsonResponse({ location, data: storyPlugins, ready: true }) + + if (pathname === "/api/plugin/check") return jsonResponse({ location, data: storyPlugins }) + + // Long enough to see Updating; the list keeps its flags, as a server whose check has not caught up would. + if (pathname === "/api/plugin/update") + return new Promise((resolve) => setTimeout(() => resolve(noContentResponse()), 1500)) + if (pathname === "/api/config" || pathname === "/api/config/shell") return jsonResponse([]) if (pathname === "/api/mcp/resource") return jsonResponse({ location, data: { resources: [], templates: [] } }) diff --git a/packages/app/src/components-lab/focus-rings.stories.tsx b/packages/app/src/components-lab/focus-rings.stories.tsx new file mode 100644 index 000000000000..2e604d9e0f97 --- /dev/null +++ b/packages/app/src/components-lab/focus-rings.stories.tsx @@ -0,0 +1,624 @@ +import "@/composer/editor/editor.css" +import "@/new-session/location/dialog.css" +import "@/session/composer/composer-lane.css" +import "@/session/composer/queue-panel.css" +import "@/session/timeline/search-bar.css" +import "@/settings/settings.css" +import "@/settings/workspaces/project.css" +import "@/shell/palette-menu.css" +import "@/shell/search-list.css" +import "@/shell/titlebar/titlebar.css" +import "@opencode/session-ui/sources/panel" + +import { Accordion } from "@opencode/ui/accordion" +import { Button } from "@opencode/ui/button" +import { Checkbox } from "@opencode/ui/checkbox" +import { Collapsible } from "@opencode/ui/collapsible" +import { Field } from "@opencode/ui/field" +import { Icon } from "@opencode/ui/icon" +import { IconButton } from "@opencode/ui/icon-button" +import { InlineInput } from "@opencode/ui/inline-input" +import { LineComment, LineCommentOverflowIcon } from "@opencode/ui/line-comment" +import { RadioGroup, RadioItem } from "@opencode/ui/radio" +import { SegmentedControl, SegmentedControlItem } from "@opencode/ui/segmented-control" +import { Select } from "@opencode/ui/select" +import { SplitButton, SplitButtonAction, SplitButtonMenuTrigger } from "@opencode/ui/split-button" +import { Switch } from "@opencode/ui/switch" +import { Tabs } from "@opencode/ui/tabs" +import { TextInput } from "@opencode/ui/text-input" +import { Textarea } from "@opencode/ui/textarea" +import { createEffect, For, onCleanup, type JSX } from "solid-js" +import { focusTarget, forceFocusStyles } from "./force-focus" + +type Specimen = { + name: string + source: string + render: () => JSX.Element + // The element that would hold focus. Defaults to the first focusable element in the specimen. + target?: string +} + +type Group = { name: string; css: string; specimens: Specimen[] } + +const schemes = ["lab", "light", "dark"] as const + +type FocusArgs = { scheme: (typeof schemes)[number]; forced: boolean } + +const buttonVariants = [ + "neutral", + "danger", + "warning", + "outline", + "contrast", + "submit", + "ghost", + "ghost-muted", + "ghost-faint", + "ghost-danger", +] as const + +const iconButtonVariants = ["neutral", "contrast", "submit", "ghost", "ghost-muted"] as const + +const groups: Group[] = [ + { + name: "Outline 2px, offset 2.5px", + css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 2.5px", + specimens: [ + ...buttonVariants.map((variant) => ({ + name: `Button ${variant}`, + source: "ui/src/actions/button/button.css", + render: () => , + })), + ...iconButtonVariants.map((variant) => ({ + name: `IconButton ${variant}`, + source: "ui/src/actions/icon-button/icon-button.css", + render: () => } aria-label="Add" />, + })), + { + name: "Composer lane pill", + source: "app/src/session/composer/composer-lane.css", + render: () => ( + + ), + }, + ], + }, + { + name: "Outline 2px, offset 2px", + css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px", + specimens: [ + { + name: "Checkbox compact", + source: "ui/src/forms/checkbox/checkbox-compact.css", + render: () => ( + + Compact checkbox + + ), + }, + { + name: "LineComment overflow", + source: "ui/src/data-display/line-comment/line-comment.css", + render: () => ( +

+ ), + }, + { + name: "Settings back", + source: "app/src/settings/settings.css", + render: () => ( + + ), + }, + { + name: "New session location back", + source: "app/src/new-session/location/dialog.css", + render: () => ( + + ), + }, + { + name: "Project settings server link", + source: "app/src/settings/workspaces/project.css", + render: () => ( + + Server link + + ), + }, + ], + }, + { + name: "Outline 2px, offset 1px", + css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 1px", + specimens: [ + { + name: "Switch compact", + source: "ui/src/forms/switch/switch.css", + render: () => Compact switch, + }, + { + name: "Radio", + source: "ui/src/forms/radio/radio.css", + render: () => ( + + + + + ), + }, + { + name: "SegmentedControl item", + source: "ui/src/navigation/segmented-control/segmented-control.css", + render: () => ( + + One + Two + + ), + }, + { + name: "TextInput clear button", + source: "ui/src/forms/text-input/text-input.css", + target: '[data-slot="text-input-v2-icon-button"]', + render: () => , + }, + { + name: "Question progress segment", + source: "session-ui/src/components/question-prompt.css", + render: () => ( +
+
+ ), + }, + { + name: "Field label info", + source: "ui/src/forms/field/field.css", + target: '[data-slot="field-v2-label-info"]', + render: () => ( + + Label + + + ), + }, + ], + }, + { + name: "Outline 2px, inset (offset -2px)", + css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: -2px", + specimens: [ + { + name: "SplitButton action", + source: "ui/src/actions/split-button/split-button.css", + render: () => ( + + + + + + + + + ), + }, + { + name: "SplitButton menu trigger", + source: "ui/src/actions/split-button/split-button.css", + target: '[data-component="split-button-v2-menu-trigger"]', + render: () => ( + + + + + + + + + ), + }, + { + name: "Composer toolbar Button / IconButton", + source: "app/src/composer/editor/editor.css", + render: () => ( +
+ +
+ ), + }, + { + name: "Queue panel Button / IconButton", + source: "app/src/session/composer/queue-panel.css", + render: () => ( +
+ } aria-label="Remove" /> +
+ ), + }, + ], + }, + { + name: "Field outline colour (1px, inset)", + css: ":focus-within { outline-color: var(--v2-border-border-focus); box-shadow: none } over outline: 1px solid; outline-offset: -1px", + specimens: [ + { + name: "TextInput", + source: "ui/src/forms/text-input/text-input.css", + render: () => , + }, + { + name: "Textarea", + source: "ui/src/forms/textarea/textarea.css", + render: () =>