diff --git a/AGENTS.md b/AGENTS.md
index 2a72e553..e13b0aba 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,6 +25,7 @@
- In Solid code, follow existing signal/memo/effect patterns and signal accessors like `value()`, not React-style state APIs.
- Before changing message-list virtualization, pagination, sticky navigation, row measurement, attachments, or inline editing, read `docs/message-list-virtualization.md` and preserve its identity, height, visible-anchor, and scroll-ownership invariants.
- When the user asks to "Run AI tests" or "Run fuzzy tests" (case-insensitive), follow `docs/ai-fuzzy-verification.md`. Unless the user narrows the scope, run its automated preflight and standard real-editor scenarios, use GPT Luna or Terra as specified, run realistic edit/tool streams only in the clean `tmp/opencode` fixture, save the run ledger under `artifacts/ai-fuzzy/`, and report blocked visual checks rather than treating browser or host-only tests as substitutes.
+- AI parity and regression runs must include `docs/ai-action-matrix.md`: test sends, queueing, pause/edit/resume/remove, steering, inline edits, tools, actual subagents, root/child permissions, questions, cancellation, and view ownership recovery. Report action-by-backend results; streaming-only coverage is incomplete.
- When the user asks to "Run streaming tests" (case-insensitive), follow `docs/ai-streaming-verification.md`. This separate AI-test suite selects existing OpenCode history read-only and replays it in an isolated VS Code host with short gaps preserved and long waits capped. Review selection coverage, attach AI watchers before starting playback, save evidence under `artifacts/ai-streaming/`, and never treat scheduler/canonical checks alone as a visual or performance pass. Never execute recorded tools or mutate source sessions.
- Tests must never change existing production sessions, including timestamps, permissions, titles, or messages, unless the user explicitly requests that specific change. A test request is not authorization to migrate or repair production data. Live AI tests require a verified separate database under `artifacts/ai-test-data/`; never fall back to the normal server, reuse a production editor, or bypass isolation checks. Historical session reads remain read-only; test imported copies instead.
- Before changing permission modes or rules, auto-approval, permission events or snapshots, prompt grouping, attention state, or child-session approvals, read `docs/permission-lifecycle.md` and preserve its pending-request visibility and server-acknowledgement invariants.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e3aa9e1d..ab88c3fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,25 +2,43 @@
This changelog summarizes the main user-facing improvements in each Varro minor release line. Patch releases are consolidated into their parent minor version. Dates reflect the development history.
+## 0.29.x - September 2026
+
+- Added OpenCode v2.0.5+ support alongside v1.16.0+, with automatic API detection and authenticated connections.
+- Recommend v2 via `npm install -g @opencode/cli` or the standalone Windows CLI. V1 remains available via `npm install -g opencode-ai`; updates preserve the installed package family.
+- Prefer `opencode2`, falling back to `opencode`, unless `varro.server.command` is set. Both current packages use `opencode`.
+- After installing v2, let active work finish, run `Varro: Restart Server`, and confirm the version in the status bar. See [restart recovery steps](docs/usage.md#if-restart-does-not-switch-to-v2) if Varro stays on v1.
+- Added `Varro: Import OpenCode v1 Session into v2` to copy conversations and child sessions with history intact, leaving originals unchanged.
+- Included both versions in local usage reports without double-counting migrated or imported sessions.
+- Kept v2 provider failures visible in live chat and history, even before a response starts.
+- Updated tested OpenCode v2 support to 2.0.7, including request-start timing and hidden authentication defaults.
+- Preserved session-scoped Always approvals across Default-mode sends and kept declined v2 tools out of completed-work summaries.
+
## 0.28.x - September 2026
- Added VS Code Problems context with workspace and individual diagnostic selection through the composer, slash command, and editor code actions. Captured diagnostics persist across queued messages, history, and message edits, with settings to disable inclusion.
- Added inline `$` skill references with completion and attachments, preserving skill references in message history and edits.
+- Added compact auxiliary windows for new and existing chats, with a per-window light/dark theme toggle and a remembered preference.
- Added database context and table-attachment support in the shared chat interface, including persistent snapshots and message rendering for sessions with database attachments.
- Synchronized session read state across folder and multi-root views so read conversations stay read when switching workspaces.
- Improved Windows server startup and recovery, event handling, and OpenCode update support while limiting background work under heavy load.
- Added layered permission controls for session and project rules, inherited configuration, and server-memory allowances. Simplified session choices to Default, Auto, and Full access.
- Let agents continue permitted work after a rejected permission request, required scope selection when saving an always-allow rule, and prevented startup permission recovery from changing session history or recency.
+- Show the requesting subagent in permission prompts.
- Added provider visibility and ordering controls, shared model preferences across workspaces, and usage-limit reporting for Claude Code. OpenAI and Z.ai limits now include reset details.
+- Added model pricing details and provider quota percentages to the model picker, with clearer usage and polling details in provider-limit popups.
- Coordinated provider quota polling across instances, added available Grok quota reset times, kept authentication failures visible until credentials are verified, and fixed providers disappearing when all their models are deselected.
- Added drag-and-drop and keyboard reordering for pinned sessions, with custom order preserved across session lists and navigation.
-- Expanded redacted diagnostics and Ralph verification evidence, with clearer provider failures and reconnect feedback.
+- Expanded redacted diagnostics and Ralph verification evidence, with clearer provider failures and reconnect feedback. Simplified diagnostics export to copy or save reports directly.
- Opened plans in VS Code's Markdown preview while keeping them available as editor context.
- Sped up local usage reports for large histories with worker-based database aggregation and bounded fallbacks.
- Improved pasted images, draft and queued-message persistence, and attachment cleanup.
+- Kept sent drag-and-drop files available for the lifetime of their sessions, and preserved the original attachments, agent, model, and reasoning variant when retrying failed turns.
- Strengthened sidebar and editor-chat recovery across delayed state, stalled delivery, stale documents, cross-folder prompts, concurrent session-scope changes, and asynchronous session transitions.
+- Fixed editor-session initialization when VS Code recreates a webview while reusing its document identity.
- Stabilized long conversations, scrolling during activity transitions, prompt navigation, streaming Markdown, and deeply nested session lists.
- Smoothed streamed text and activity updates, preserved scroll anchors during resizing and collapsed activity, and kept file-change previews stable across repeated edits.
+- Reduced streaming Markdown rendering work and stabilized follow-to-bottom during row resizing and resending edited messages.
- Fixed session-picker sends losing newly created sessions, highlighted reselected editor sessions, and removed stale Stop controls after completed responses.
- Fixed custom-answer submission and kept active auto-approve reviews visible.
diff --git a/README.md b/README.md
index 7cc48c25..51b05888 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,8 @@
Varro runs [OpenCode](https://opencode.ai) inside VS Code. It adds project-aware chat, parallel sessions, plan and change review, model and permission controls, commit-message generation, and usage reports.
+**OpenCode v1 and v2 are both supported.** Varro automatically detects the connected API and uses the same workbench for either version. OpenCode v2 is recommended for new installations. Supported versions start at v2 **2.0.5** and v1 **1.16.0**.
+
OpenCode remains responsible for agents, providers, models, commands, skills, MCP servers, and their configuration. Varro reads that configuration and provides a VS Code interface for it.

@@ -15,12 +17,16 @@ OpenCode remains responsible for agents, providers, models, commands, skills, MC
## Quick start
1. [Install Varro](https://marketplace.visualstudio.com/items?itemName=koltyakov.varro) from the VS Code Marketplace.
-2. Install the OpenCode CLI with `npm install -g opencode-ai`.
+2. Install [OpenCode v2](https://opencode.ai/v2/docs/) with `npm install -g @opencode/cli` on macOS, Linux, or WSL. For native Windows, download the standalone CLI from that page.
3. Run `opencode auth login`, or use `/connect` in Varro, if no provider is configured.
4. Open a folder in VS Code and select `Varro` from the Activity Bar.
5. Start a session. Varro starts or connects to OpenCode when needed.
-On native Windows, install OpenCode from a Windows terminal because Varro runs it on the local Windows extension host. In a VS Code WSL window, install OpenCode inside that WSL distribution instead. Varro and OpenCode then run on the Linux extension host. OpenCode [recommends WSL for the best Windows experience](https://opencode.ai/docs/windows-wsl), although native Windows is supported. Native OpenCode data, including `auth.json`, logs, and sessions, is under `%USERPROFILE%\.local\share\opencode`.
+Already using v1? You can keep it, or install it with `npm install -g opencode-ai`. Set `varro.server.command` to your v1 executable to select it explicitly. With this setting empty, Varro searches for `opencode2` first, then `opencode`. Current v1 and v2 packages both install `opencode`, so the command name alone does not identify the version. Run `opencode --version` to check. See [choosing and updating OpenCode](https://github.com/koltyakov/varro/blob/main/docs/usage.md#choose-and-update-opencode) before switching versions.
+
+> After switching from v1 to v2, you may need to run `Varro: Restart Server` from the Command Palette. Installing v2 does not replace an already running v1 server. If restart fails or Varro still shows v1, stop the old OpenCode process explicitly, especially on Windows, then restart with the v2 executable. Let active work finish first. See [restart recovery steps](https://github.com/koltyakov/varro/blob/main/docs/usage.md#if-restart-does-not-switch-to-v2) and confirm the connected version in Varro's status bar.
+
+Install OpenCode on the host where Varro runs. A native Windows VS Code window needs the Windows CLI; add it to `PATH` or set `varro.server.command` to its executable path. A VS Code WSL window needs OpenCode installed inside that WSL distribution. Native OpenCode data is under `%USERPROFILE%\.local\share\opencode`; WSL uses the Linux data directory.
Varro supports VS Code and VSCodium. Support for other VS Code forks is limited; see [VS Code fork compatibility](https://github.com/koltyakov/varro/blob/main/docs/vscode-forks.md).
@@ -59,6 +65,8 @@ Varro supports VS Code and VSCodium. Support for other VS Code forks is limited;
| LSP, formatters, and tools | Integrated | Show language-server status and tool activity. OpenCode owns definitions and execution. |
| Configuration and TUI | Handoff | Edit instruction files or continue a session in the OpenCode TUI. |
+Coverage depends on the connected version. The supported v2 API has no session sharing or OpenCode LSP service. Varro disables sharing on v2; VS Code Problems can still be attached as context. V2 session annotations are stored locally by Varro. See [version differences and history import](https://github.com/koltyakov/varro/blob/main/docs/usage.md#version-differences-and-history).
+
## Sessions
Varro filters sessions to the current workspace and groups them into `Recent`, `Archive`, and `Recycle Bin`. Filters identify `Running`, `Needs attention`, `Failed`, `Plan ready`, and `Completed` sessions. Rows can show queued prompts, changed files, added and removed lines, token use, duration, and current state.
@@ -95,7 +103,7 @@ Permission requests provide `Reject`, `Once`, and `Always` actions. Each session
Child sessions inherit the nearest selected mode in their session tree. Manual child requests appear in the parent conversation while remaining owned by the child session.
-Varro initially selects `Auto` unless `varro.chat.defaultPermissionMode` or a saved project/global selection says otherwise. `Default` does not mean that every action requires approval. Without custom rules, OpenCode allows most permissions, asks for `doom_loop` and `external_directory`, and blocks reading `.env` files and variants while allowing `.env.example`. See [OpenCode permissions](https://opencode.ai/docs/permissions/) to configure global or per-agent `allow`, `ask`, and `deny` rules, including rules matched by tool, command, path, subagent, URL, and external directory.
+Varro initially selects `Auto` unless `varro.chat.defaultPermissionMode` or a saved project/global selection says otherwise. `Default` follows the connected OpenCode version's global and agent rules. V2 uses ordered `permissions` rules with `action`, `resource`, and `effect`; supported v1-format rules remain accepted. See [v2 permissions](https://opencode.ai/v2/docs/permissions/) or [v1 permissions](https://opencode.ai/docs/permissions/) for syntax and defaults.
See the [Varro permissions guide](https://github.com/koltyakov/varro/blob/main/docs/permissions.md) for mode behavior, manual approvals, and automatic review details.
@@ -137,7 +145,7 @@ Varro never mixes staged and unstaged changes, stages files, or commits automati
Varro connects to `http://127.0.0.1:4096` by default. Set `varro.server.port` to another port from 1 through 65535. For manual server management, disable the deprecated debug setting `varro.server.autoStart` and run `opencode serve --port 4096`.
-The status bar shows the active OpenCode version and available updates. On macOS and Linux, `varro.server.autoUpdate` installs the latest OpenCode CLI update. Native Windows does not replace the CLI in the background. It shows an update prompt, waits for active work to finish, and stops a Varro-managed server before opening the update command so Windows releases its lock on `opencode.exe`. Stop a separately managed server yourself before updating.
+The status bar shows the active OpenCode version and available updates. On macOS and Linux, `varro.server.autoUpdate` installs updates within the installed CLI family: `@opencode/cli` for v2 or `opencode-ai` for v1. Updating v1 does not migrate it to v2. Native Windows does not replace the CLI in the background. It shows an update prompt, waits for active work to finish, and stops a Varro-managed server before opening the update command so Windows releases its lock on `opencode.exe`. Stop a separately managed server yourself before updating.
Varro reloads global OpenCode configuration when OpenCode is idle. Changes to project configuration may require `Varro: Restart Server`. This command waits for active work and only restarts a server managed by Varro. Restart a manually launched server in its terminal.
@@ -145,7 +153,7 @@ Varro reloads global OpenCode configuration when OpenCode is idle. Changes to pr
- [VS Code](https://code.visualstudio.com/) or [VSCodium](https://vscodium.com/) 1.120 or newer
- [Node.js](https://nodejs.org/) 22.22.2+ on Node 22, or Node 24.15.0+
-- [OpenCode CLI](https://opencode.ai/docs) 1.16.0 or newer on `PATH`, or configured through `varro.server.command`
+- [OpenCode v2 CLI](https://opencode.ai/v2/docs/) 2.0.5+ recommended, or [v1 CLI](https://opencode.ai/docs/) 1.16.0+, on `PATH` or configured through `varro.server.command`. Tested with v2 2.0.7 and v1 1.18.31
- A trusted, non-virtual workspace. Remote workspaces run Varro and OpenCode on the remote extension host
## Documentation
diff --git a/docs/ai-action-matrix.md b/docs/ai-action-matrix.md
new file mode 100644
index 00000000..1cdaff89
--- /dev/null
+++ b/docs/ai-action-matrix.md
@@ -0,0 +1,93 @@
+# AI action coverage matrix
+
+Use this matrix for AI parity and regression runs. Rendering a stream is one part of
+the run. A passing run must exercise the actions that create, change, interrupt, and
+resume work through the real VS Code UI.
+
+Follow [AI fuzzy verification](ai-fuzzy-verification.md) for database isolation,
+native input, model selection, fixture safety, evidence capture, and cleanup. Follow
+[Permission lifecycle](permission-lifecycle.md) when judging approvals and child
+sessions. Never use production sessions as action targets.
+
+## Coverage dimensions
+
+Record a separate result for each tested backend version. Cross the actions below
+with the states and surfaces that affect their behavior:
+
+- Session state: new draft, idle history, streaming text, running tool, pending
+ permission or question, interrupted turn, and resumed history.
+- Surface: sidebar and chat editor, including a hidden, revealed, reloaded, or closed
+ editor when ownership matters.
+- Permission mode: Default, Auto, and Full access. Include explicit mode changes
+ while a request is pending.
+- Session relationship: root, actual model-created child, and root/child navigation.
+- Content: text, attachment/context, reasoning, tool output, real fixture edit, diff,
+ question, permission prompt, and final response.
+
+Use a recorded seed to choose ordering and variations. Cover every applicable
+action row on each backend and every named state transition below. Do not claim the
+full Cartesian product. Record the exact combinations tested and any omitted ones.
+
+## Required action rows
+
+| ID | Actions and required transitions | Evidence required for a pass |
+| --- | --- | --- |
+| ACT-01 | Create a chat, send from an idle composer, append a follow-up | Exact marked users and linked responses occur once, in order; model and route are correct |
+| ACT-02 | Queue at least two messages during active work and let them dispatch | Exact queue IDs, ownership, visible counts, FIFO canonical admission, and no duplicate response |
+| ACT-03 | Pause, edit, save, resume, and remove queued messages | Paused item does not dispatch; saved content replaces the queued content; removed item never appears in canonical history |
+| ACT-04 | Send a manual steer during active work, including a paused queued row | UI acknowledges the steer, the queued row is removed once, and the server receives the intended marked input once |
+| ACT-05 | Enter inline editing, cancel, then submit a replacement prompt | Cancel preserves original history; submission replaces the intended branch; no stale or duplicate prompt remains |
+| ACT-06 | Attach context or a file, inspect it, remove it, and send retained context | Composer and canonical submitted parts agree; removed attachment is absent; content belongs to the correct session |
+| ACT-07 | Run sequential and independent parallel tools, make a bounded fixture edit, run a focused check, open/close its diff | Actual tool inputs/results, file changes, check output, and usable diff UI agree with canonical history and disk |
+| ACT-08 | Ask the model to launch a real subagent; inspect child progress; navigate child and parent | Recorded ancestry, exact child model, separate routes, visible completion, and no cross-session content leakage |
+| ACT-09 | Trigger a child permission and answer it from the parent conversation | Pending request retains its child session ID; parent fallback remains actionable; acknowledgement resumes the correct child |
+| ACT-10 | Default mode: Once, Reject, and session-scoped Always; reopen while pending | No early prompt removal; rejected action does not execute; each approval has its intended scope; reopened pending request remains actionable |
+| ACT-11 | Switch Default, Auto, and Full access; resolve an already-pending request through a mode change | Confirmed mode and rules agree; Auto remains ask-based; no stale automatic owner or orphaned request |
+| ACT-12 | Answer and skip a real question | Correct answer or rejection reaches the server once; continuation remains usable; no stale prompt returns |
+| ACT-13 | Stop active work and send a new turn | Server acknowledges cancellation, busy state clears, and the next marked turn completes normally |
+| ACT-14 | Switch sessions, hide/reveal or close an editor while work or a queue is active | Exact queue item IDs and ownership survive handoff; drafts remain session-scoped; wrong-route content never appears |
+| ACT-15 | Reload during streaming and while a permission or queue is pending | Recreated view binds by stable viewId; history, pending requests, and queued work recover without duplicates |
+| ACT-16 | Change agent/model in idle and busy states where supported | Selection is visibly confirmed; the next admitted request uses the intended configuration; unsupported transitions are explicit |
+| ACT-17 | Fork, undo/redo, rename, and archive a disposable session where supported | Correct branch and history are retained; route/title/list state agrees with the server; capability differences are recorded |
+
+Queue editing means changing and saving the text, not merely opening an edit box.
+Subagent coverage requires model delegation and actual child work, not an empty
+child created by the controller. Permission mode synchronization alone does not
+count as a permission lifecycle pass.
+
+## Scenario independence
+
+Give each action group its own verified preconditions. Short disposable histories
+are sufficient for composer, queue, steer, question, and permission lifecycle
+checks. Long virtualized histories are required for pagination and scroll tests.
+Real file/diff checks require a recorded fixture edit.
+
+An incomplete AI-07 scroll-timing check must not prevent independent action rows
+from running. Existing AI-08, AI-18, and AI-19 controllers retain their documented
+preconditions. An independently prepared action check is reported under its ACT ID;
+it must not fabricate successful AI-07 preparation or be relabeled as an AI-18/19
+pass.
+
+## Execution and reporting
+
+Before sending prompts, put the planned cells in the run ledger. For each cell,
+record backend version, starting state, surface/viewId, permission mode, model,
+session IDs, action sequence, expected result, and evidence path. Mark cells
+`PASS`, `FAIL`, or `BLOCKED`; record unexecuted cells explicitly rather than omitting
+them from a summary.
+
+Drive user actions with native input. Server reads verify outcomes; they cannot
+substitute for clicking Send, editing a queue row, replying to a permission, or
+opening a child. Observe frame-level rendering during the actions, and retain
+canonical history plus pending-request and queue evidence. A dispatched input is
+not proof of an action's effect.
+
+Reuse deterministic tests for races that cannot be produced reliably with a live
+model, including stale permission snapshots, late judge replies, and duplicate
+events. Report those separately from live editor results. Do not inject failures
+or synthetic state into the live editor to claim a real-backend pass.
+
+The overall action-matrix result passes only when every required applicable row
+passes on every requested backend. A capability unavailable by design needs a
+verified UI behavior and an explicit capability note. A missing test mechanism or
+unreached precondition is a block, not an unsupported capability.
diff --git a/docs/ai-fuzzy-verification.md b/docs/ai-fuzzy-verification.md
index ed408e8b..baf6ef0d 100644
--- a/docs/ai-fuzzy-verification.md
+++ b/docs/ai-fuzzy-verification.md
@@ -64,6 +64,10 @@ For an unqualified **Run AI tests** or **Run fuzzy tests** request:
9. A standard run is incomplete if it streams only synthetic prose or Markdown. It must include a
realistic repository task in `tmp/opencode` that produces reasoning, separate tool calls, file edits,
test output, diffs, and final response text while the UI is observed for frame-level flicker.
+10. Include the [action coverage matrix](ai-action-matrix.md). Exercise composer sends, queue changes,
+ steering, inline editing, tools, actual subagents, permissions, questions, cancellation, and
+ ownership recovery. For parity requests, report each action row for each backend version.
+ Independent lifecycle checks must still run when a scrolling scenario is blocked.
### Controller Session Safety
@@ -180,10 +184,12 @@ what was omitted.
A separate VS Code profile does not isolate OpenCode storage. Live tests must use a dedicated
OpenCode server with its database under `/artifacts/ai-test-data/`. The preparation,
-verification, live, cleanup, and editor-launch commands verify `/path` and use `lsof` to confirm
+verification, live, cleanup, and editor-launch commands verify `/path` and inspect native ownership to confirm
that the listener owns that database. They reject production storage and symlink/hard-link aliases.
Port 4096 is no longer a default. Missing isolation is a blocked test, never permission to use the
-production server. This verification currently requires macOS or Linux with `lsof`.
+production server. Verification uses `lsof` on macOS/Linux. On Windows it uses PowerShell
+`Get-NetTCPConnection` for listener ownership and the read-only Restart Manager resource query for
+database ownership; it never invokes shutdown or restart APIs.
Start a dedicated server in a tracked terminal, for example with an available port:
@@ -747,6 +753,13 @@ hides near the bottom. Return uses that button when available, otherwise native
transcript. A dispatched input counts only after measurements confirm the bottom was reached while
a tool was still running. The action record includes the attempted inputs even when return fails.
+Tool completion does not end scroll observation. Continue measuring until the viewport reaches the
+bottom or the scenario deadline expires. Record `reached-while-active`, `active-window-ended`, or
+`bottom-not-reached`, including the first sample where the running-tool window ended. Only the first
+outcome satisfies live coverage. `active-window-ended` means the timing precondition was exhausted,
+not that scrolling is broken; it must not be reported as a product scrolling failure or used to
+unlock AI-08. Smooth return can legitimately outlast a short tool call.
+
Pass invariants:
- The sticky prompt remains the same marked prompt throughout unrelated activity height changes.
diff --git a/docs/development.md b/docs/development.md
index e2718ce0..7287efa4 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -6,12 +6,14 @@ This document covers source setup, packaging, and debugging for the Varro VS Cod
- [Node.js](https://nodejs.org/) 22.22.2+ on Node 22, or Node 24.15.0+
- [VS Code](https://code.visualstudio.com/) 1.120 or newer
-- [OpenCode CLI](https://opencode.ai) installed globally
+- [OpenCode v2 CLI](https://opencode.ai/v2/docs/) 2.0.5+ recommended, or v1 1.16.0+
```sh
-npm install -g opencode-ai
+npm install -g @opencode/cli
```
+This npm command is for macOS, Linux, or WSL. On native Windows, use the standalone CLI from the v2 install page. For v1 development, use `npm install -g opencode-ai`. Both current packages install `opencode`; use separate installation directories and `varro.server.command` paths when testing both. See [choosing and updating OpenCode](usage.md#choose-and-update-opencode).
+
## Install Dependencies
```sh
@@ -155,15 +157,17 @@ See [architecture.md](architecture.md) for a deeper component-by-component break
`src/extension/server.ts` orchestrates the bridge to the local OpenCode HTTP server. Process, update, and port behavior lives in `open-code-process.ts`; REST and SSE transport lives in `open-code-transport.ts`; and `server-lifecycle.ts` coordinates lifecycle state.
-- Checks `/global/health` before spawning anything
+- Detects the API through v2 `/api/info` or `/api/status`, or v1 `/global/health`, before spawning anything
- Starts `opencode serve --port ` only when Varro first needs the server and auto-start is enabled
- Scopes workspace-sensitive requests and filters deliberately unscoped responses
-- Opens an SSE connection to `/global/event` and routes events to workspace-scoped endpoints
+- Opens an SSE connection to v2 `/api/event` or v1 `/global/event` and normalizes events for workspace-scoped endpoints
- Reconnects the event stream with backoff
- Restarts the child process a limited number of times if it exits unexpectedly
Important behavior:
+- The extension-host adapters normalize v1 and v2 into Varro's shared contracts. V2 uses authenticated requests and location-scoped APIs; the directory query/header behavior below describes the v1 transport. See [OpenCode v1 and v2 support](opencode-v2-support.md).
+
- Workspace-sensitive non-global requests carry both a `directory` query param and `x-opencode-directory` header. Global paths omit the `directory` query param; health and `/global/event` are explicitly unscoped, while generic global REST calls can still carry the directory header. Session status and most session-child routes are deliberately unscoped; Windows leaves additional session reads unscoped to avoid path casing and separator regressions. Aggregate session lists, statuses, permissions, and questions are filtered locally to the active workspace. Direct session-child routes remain ID-addressed and are normally reached through IDs from filtered session state.
- If the spawned server reports that the configured port is already in use, Varro can retry on nearby ports.
- If the SSE stream drops while REST is still available, Varro keeps the chat usable and reports the event stream as degraded.
diff --git a/docs/onboarding-verification.md b/docs/onboarding-verification.md
index ec182248..910a6e06 100644
--- a/docs/onboarding-verification.md
+++ b/docs/onboarding-verification.md
@@ -84,7 +84,8 @@ sandbox runs upload their isolated profiles as a `windows-vscode-sandbox-*` arti
Verify native Windows and VS Code WSL separately. They are different extension hosts and must not
share an assumed CLI installation.
-1. Open a normal local folder in VS Code on Windows. Install OpenCode from a Windows terminal, open
+1. Open a normal local folder in VS Code on Windows. Download the standalone v2 CLI from the
+ [install page](https://opencode.ai/v2/docs/) and set its path in `varro.server.command`, open
Varro, and run `Varro: About`. Confirm `Platform` is `win32`, the resolved binary is a Windows path,
and OpenCode data appears under `%USERPROFILE%\.local\share\opencode`.
2. Open a folder in a VS Code WSL window. Install OpenCode inside that distribution, open Varro,
@@ -93,8 +94,9 @@ share an assumed CLI installation.
3. Confirm a Windows-only CLI does not satisfy the WSL host and a WSL-only CLI does not satisfy the
native host. `varro.server.command` must also name a path that exists on the active extension host.
-OpenCode recommends [WSL for the best Windows experience](https://opencode.ai/docs/windows-wsl), but
-the native flow remains supported.
+Verify both supported CLI families. V2 is the recommended first-run choice; the missing-CLI screen
+also offers v1. Confirm that each install action uses its own package and that update recovery keeps
+the installed family. For v1 Windows setup, see the [v1 Windows guide](https://opencode.ai/docs/windows-wsl).
## Native Windows Checks
diff --git a/docs/opencode-v2-support.md b/docs/opencode-v2-support.md
new file mode 100644
index 00000000..c125e9ca
--- /dev/null
+++ b/docs/opencode-v2-support.md
@@ -0,0 +1,164 @@
+# OpenCode v1 and v2 support
+
+Research date: September 17, 2026. The implementation supports v1 from 1.16.0 and v2 from 2.0.5 through automatic extension-host adapters.
+
+V2 is recommended for new installations; v1 remains supported. See the [usage guide](usage.md#choose-and-update-opencode) for installation, version selection, updates, and configuration compatibility. Current packages both install `opencode`. Varro also recognizes older or custom `opencode2` installations and prefers that name during automatic discovery.
+
+## Implementation and verification
+
+- `src/extension/opencode-connection.ts` detects protocol families and removes startup credentials before logging, including credentials split across process-output chunks.
+- `open-code-process.ts` retains credentials in the private ownership lease for window handoff and reads registered local service credentials. CLI update lookup and recovery commands select the matching package family.
+- `open-code-transport.ts` authenticates health, REST, and SSE requests and selects the adapter from validated server responses.
+- `opencode-v2-adapter.ts`, `opencode-v2-projection.ts`, and `opencode-v2-events.ts` translate requests, transcript records, catalogs, permissions, forms, and events into the existing Varro contracts.
+- `opencode-v2-session-state.ts` persists Varro-owned metadata and timestamp overrides that the released v2 API cannot patch. These annotations live under the user's XDG state directory in `varro/opencode-v2/`.
+- Native v2 agent and permission configuration keys are preserved when Varro edits a file already using them. V1-format files retain their format.
+
+`npm run test:compatibility:adapters` installs published binaries into isolated directories and tests the production adapters. Its latest matrix passed 44 checks across `opencode-ai@1.16.0`, `opencode-ai@1.18.31`, `@opencode/cli@2.0.5`, and `@opencode/cli@2.0.7`. The checks cover managed startup, credential recovery in a second window, restart, bootstrap, session updates, deterministic streamed model responses, actual fixture-only tool execution, message pagination, tail editing, helper generation, fork/revert, deletion, and native v2 permissions/forms. The generated report is `artifacts/opencode-adapters/verified.json`.
+
+Fresh VS Code sandbox windows passed `v2-first-run` and the existing `healthy-first-run` scenario. These editor checks verify activation, ownership, health, and event-stream connection. `test:compatibility:ui` additionally exercises the actual composer, successful replies, pre-turn failures, HTTP 401 handling, recovery through a working provider, and reopening history. Full visual streaming performance remains a separate verification task.
+
+V2 control records such as agent/model selection are excluded from the transcript while their selection context is preserved. A failed execution that never created an assistant turn gets a stable error row derived from the native failure record. Live errors retain the server's diagnostic message; reopened history without that live detail still shows the recorded failure. This prevents a provider authorization error from appearing as a silently unanswered prompt.
+
+Run the v2 editor check after building:
+
+```sh
+VARRO_SANDBOX_V2_COMMAND=/absolute/path/to/opencode2 node scripts/vscode-sandbox/run.mjs v2-first-run
+```
+
+The editor profile is disposable, and its OpenCode database is isolated under `artifacts/ai-test-data/`.
+
+The released v2 API has no session-sharing route or arbitrary single-message deletion. Varro disables sharing and implements inline-edit tail deletion through file-preserving staged revert and commit. V2 also has no LSP service. Metadata annotations are local to Varro; they are not synchronized to other OpenCode clients. Switching CLI families does not perform a data migration.
+
+### 2.0.7 compatibility fixes
+
+- Default-mode sends preserve session-scoped Always approvals. V2 replaces session permission rules,
+ so the previous pre-send empty-rule update erased saved allowances. Explicit mode changes still
+ apply their rule updates. The released permission engine does honor session rules; the older
+ `tmp/opencode` checkout did not represent that released behavior.
+- V2's `The user declined this tool call` error uses Varro's permission-rejected presentation and
+ remains outside compact completed-work groups.
+- Step-start events use the 2.0.7 `started` timestamp for provider-request timing, with the event
+ timestamp as a fallback for older releases.
+- Hidden authentication fields are omitted from interactive prompts and their defaults are submitted
+ unless the caller supplies a value. Inactive conditional defaults remain omitted.
+
+The v2.0.6 to v2.0.7 release diff also adds permission policy enforcement, waits for plugin activation
+before listing integrations, and removes server-side update polling. These use existing Varro APIs.
+The new experimental filesystem-write route and ACP/UI changes do not require adapter changes.
+
+V2.0.7 still interrupts a turn when a tool permission is rejected or a question is skipped. Its config
+normalizer explicitly drops v1's `experimental.continue_loop_on_deny` option. Varro preserves that
+server outcome. The earlier v1 immediate-rename overwrite remains a server-title-generation race
+observation, not a verified Varro regression. Neither behavior is changed by this compatibility patch.
+The earlier AI-07 attempts exhausted the running-tool window during smooth return; all six reached
+the bottom afterward. This was incomplete live coverage, not an observed stuck-scroll defect or a
+backend compatibility failure. AI-08 was not executed because its AI-07 prerequisite did not pass.
+The controller now distinguishes a late successful return from failure to reach the bottom, and
+`scroll-return-tool-completion.spec.ts` checks tool completion during native return at 540 and 1,768 px.
+These browser regressions do not certify the separate full real-editor visual/performance suite.
+
+## Importing v1 conversations into v2
+
+While connected to v2, run **Varro: Import OpenCode v1 Session into v2** from the VS Code command palette. Select a local v1 conversation from the current workspace. Varro reads a consistent, read-only snapshot and imports a separate conversation titled ` (v1 copy)`.
+
+The copy receives new session and message IDs. Same-workspace child sessions and their references are copied together. Text, reasoning, completed tool results, model identities, and embedded image attachments are converted to v2 history. Original message records and session metadata are retained in import metadata, including v1-only parts. External attachment references remain references. Unfinished historical tools become interrupted results rather than active operations. Import does not execute recorded tools or start a model request; the user can send a new message after the copy opens. New copies use the destination server's permission defaults.
+
+The source v1 sessions, timestamps, and messages remain unchanged. The importer uses `OPENCODE_DB` when configured, otherwise the standard local OpenCode database. Reads are bounded to 32 MiB, 100 sessions, 10,000 messages per session, and 100,000 parts per session. A failed multi-session import removes its successfully created copies and reports any cleanup failure.
+
+Real VS Code verification on OpenCode 2.0.6 now covers creating and reopening conversations, full window reload, recycle/restore/permanent deletion, stale-catalog 404 recovery, importing a v1 parent and child, continuing the imported conversation, and reopening/reloading that copy. The fixture verifies that importing causes no provider requests and that original v1 rows remain identical. Run with:
+
+```sh
+VARRO_OPENCODE_TEST_BINARY=/absolute/path/to/opencode2 npm run test:compatibility:ui
+```
+
+V2 omits the legacy session `version` property; Varro supplies the protocol-family marker for its recycle-bin snapshots. Without that normalization, valid v2 sessions failed the snapshot validator and deletion misleadingly reported `404 Session not found`.
+
+## Historical research
+
+The remaining sections record the original startup investigation and implementation plan. They describe the pre-adapter failure and design requirements, not current limitations unless repeated in the implementation notes above.
+
+### Findings
+
+- The installed `/Users/andrew/.bun/bin/opencode2` reports `opencode v2.0.6`.
+- Published `@opencode/cli` and `@opencode/client` report `2.0.6`.
+- Published `opencode-ai` and `@opencode-ai/sdk` still report `1.18.31`.
+- The [migration guide](https://opencode.ai/v2/docs/migrate-v1/) explicitly identifies the server API as a breaking change. Supported v1 configuration remains accepted, but this does not promise v1 HTTP compatibility.
+- `tmp/opencode` was clean and current on upstream `dev`, commit `5a8335857b0ebec44ef6aa1d52b339cf25c329ca`. Its CLI and protocol can differ from the released binary. Treat those sources as architectural references, not the released contract.
+- The 2.0.6 API uses `/api/info`; Varro also probes the 2.0.5 `/api/status` endpoint to preserve the supported v2 floor.
+
+### Reproduced startup failure on v2.0.5
+
+An isolated copy of the installed binary was launched with a fresh HOME, XDG directories, explicit database path, empty workspace, and ephemeral loopback port. The probe performed HTTP GETs and opened an event subscription. It did not use production sessions or provider credentials.
+
+| Request | Without credentials | With the generated Basic credentials |
+| --- | --- | --- |
+| `/global/health` | 401 | 200, web-app HTML |
+| `/api/status` | 401 | 200, JSON with version, PID, URLs |
+| `/api/info` | 401 | 404 |
+| `/api/health` | 401 | 404 |
+| `/agent` | 401 | 200, web-app HTML |
+| `/api/agent` | 401 | 200, `{ location, data }` |
+| `/session` | 401 | 200, web-app HTML |
+| `/api/session` | 401 | 200, `{ data, cursor }` |
+| `/global/event` | Not probed | 200, web-app HTML |
+| `/api/event` | Not probed | SSE containing `{ id, type: "server.connected", data: {} }` |
+
+The authenticated `/openapi.json` lists 111 paths. The local evidence is in `tmp/v2-api-probe-q0M2WV/results.json` and `tmp/v2-api-probe-q0M2WV/openapi.json`; the reproducible probe is `tmp/opencode-v2-probe.mjs` and uses the installed binary's absolute path.
+
+Before the adapters, Varro sent unauthenticated health, REST, and SSE requests in `src/extension/open-code-transport.ts`. `src/shared/opencode-endpoints.ts` selected `/global/health` and `/global/event`. The health loop in `src/extension/server.ts` collapsed failed probes into a timeout even though the server had started successfully.
+
+Credentials alone will not fix the integration. The released server does not supply the tested v1 contracts. HTTP 200 alone is especially misleading because unknown non-API routes serve HTML.
+
+### Required compatibility design
+
+Keep one Varro UI and two extension-host protocol adapters. Select the adapter once per server connection and normalize both protocols into Varro-owned data and events before they reach session state, event batching, and the webview.
+
+1. Preserve the existing v1 support floor of 1.16.0 and its test coverage. Add a separately recorded v2 tested range. A single `version >= 1.16.0` comparison cannot establish protocol support.
+2. Respect `varro.server.command`, including custom binary names. Detect the CLI family for launch preparation, then validate the actual running server's identity and response schema. An existing server can differ from the configured CLI.
+3. For managed v2 launches, acquire the generated credential before authenticated probes. The released binary prints it during startup. If using that channel, buffer across stdout chunks and redact before any logging, diagnostic retention, or error formatting. Verify the supported credential-discovery mechanism separately for adopted and externally managed servers. Do not assume the current dev branch's `service password` command exists in 2.0.5.
+4. Authenticate health, ordinary requests, and SSE consistently. Keep credentials in the extension host and bind them to the server identity. Preserve credentials across legitimate ownership handoff and reconnect without forwarding them to the webview or unrelated origins.
+5. Distinguish authentication failure, unsupported API, malformed response, process exit, and timeout. Validate JSON schemas and SSE content types rather than accepting successful HTTP status alone.
+6. Use `@opencode/client` for v2 contract types and evaluate its generated client against Varro's cancellation, byte limits, directory scoping, and stream handling before adopting its runtime. Updating `@opencode-ai/sdk` alone does not add released v2 support.
+
+The adapter should expose semantic operations where contracts differ. Avoid growing a global string-replacement table for v1 paths. `OpenCodeServer.request()` is a useful transition boundary, but some operations need multiple calls and stateful projections.
+
+### Contract work
+
+| Area | Required adaptation |
+| --- | --- |
+| Startup | v1 health versus released v2 `/api/status`; authentication and server ownership |
+| Sessions | Unwrap v2 `data`, resolve `location`, preserve metadata and ancestry, translate body cursors into Varro pagination |
+| Messages | Project the v2 discriminated message union into stable Varro transcript identities; v1 `{ info, parts }` assumptions do not directly apply |
+| Prompt submission | v1 `prompt_async` and parts versus v2 `prompt` with text and attachments; account for separate agent/model switching and durable inbox admission |
+| Queuing | Preserve Varro queue behavior while explicitly choosing v2 delivery semantics; distinguish admitted input from a visible user message and active execution |
+| Streaming | Decode `/api/event` native envelopes and project incremental changes into the same state model used for history; verify replay, ordering, deduplication, and snapshot reconciliation |
+| Stop and compaction | Map v1 abort/summarize behavior to v2 interrupt/compact semantics |
+| Fork and revert | Preserve boundaries and ancestry across v2 fork and staged/committed revert operations |
+| Permissions | Map action/resource/effect rules and session-owned reply routes; the released request uses `decision`, and successful replies return 204 |
+| Questions | Adapt v2 session forms, pending snapshots, replies, and cancellation |
+| Models and authentication | Separate v2 model/provider catalogs and integration/credential flows; normalize model capabilities, variants, and prices |
+| Workspace services | Audit MCP, files, VCS, commands, skills, and config read/write contracts individually |
+| Updates | Detect the installed package family; v2 must not use the hard-coded `opencode-ai` update target |
+
+Primary Varro integration points are `src/extension/open-code-process.ts`, `src/extension/open-code-transport.ts`, `src/extension/server.ts`, `src/extension/rest-proxy.ts`, `src/extension/server-event-bridge.ts`, and the shared protocol, compatibility, and install modules. Hidden helper sessions, automatic permission judging, exports, trash, and model-selection persistence also consume server behavior and need coverage.
+
+### Backward compatibility requirements
+
+- Users keep the same Varro interface and settings when choosing either supported CLI family. No manual API-version switch should be necessary.
+- Keep version-specific behavior in the host adapters. Shared UI code consumes normalized models and declared capabilities.
+- Preserve stable message/part IDs across history loading, live updates, reconnects, and pagination. Follow `docs/message-list-virtualization.md`.
+- Preserve Default, Auto, and Full access semantics. A pending permission retains an actionable fallback until server acknowledgement or authoritative reconciliation. Follow `docs/permission-lifecycle.md`.
+- Continue accepting supported v1-format configuration. Do not rewrite shared user config to native-v2-only shapes as part of connection setup.
+- API compatibility does not imply shared database compatibility. Verify v1 history visibility and v2 migration using imported copies, preserving original data. Never claim that switching binaries provides bidirectional session synchronization without evidence.
+- Missing backend features must be represented explicitly rather than returning fake success or silently dropping operations. The migration guide says v2 does not run LSP services, for example; editor-supplied diagnostics should be assessed separately.
+
+### Implementation and verification order
+
+1. Add connection identity, authentication, adapter selection, and precise startup errors. Cover v1, v2, HTML fallback, 401, restart, existing-server attachment, and ownership handoff.
+2. Normalize discovery, sessions, messages, and pagination. Run the same Varro-facing contract assertions against both real backends.
+3. Implement prompt admission, streaming, tool states, interruption, child sessions, and reconnect recovery. Check stable identity and visible scroll anchors.
+4. Implement permissions/forms, configuration, provider authentication, MCP, fork/revert, helper sessions, and other consumed operations. Test acknowledgement and failure behavior, not just route existence.
+5. Extend `scripts/opencode-compatibility` to install both CLI package families and record separate support ranges. Its current probe targets `opencode-ai`, unauthenticated requests, and v1 response contracts.
+6. Verify full chat and tool flows in isolated real VS Code hosts for both families. Include v1-to-v2 and v2-to-v1 binary selection, reload, server restart, histories, and pending approvals.
+
+The original read-only probe established the startup incompatibility. The adapter and editor checks above now cover the implemented flows. Migration of production data and full visual streaming/replay performance have not been tested by this work.
diff --git a/docs/opencode-version-bumps.md b/docs/opencode-version-bumps.md
index 4d467c72..c4285381 100644
--- a/docs/opencode-version-bumps.md
+++ b/docs/opencode-version-bumps.md
@@ -1,16 +1,24 @@
-# OpenCode Version Bumps
+# OpenCode version bumps
-Use this workflow when updating Varro's tested OpenCode version.
+Use this workflow when updating Varro's tested OpenCode versions. V2 is the recommended install; keep v1 support and its verification matrix.
-1. Confirm the latest stable SDK and CLI versions with `npm view @opencode-ai/sdk version` and `npm view opencode-ai version`; they should normally match.
+1. Check both package families. For v2, run `npm view @opencode/client version` and `npm view @opencode/cli version`. For v1, run `npm view @opencode-ai/sdk version` and `npm view opencode-ai version`. Versions within each family should normally match; the `opencode-ai` dist-tag does not describe v2.
2. Prepare a current, clean upstream checkout. If `tmp/opencode` does not exist, run `git clone https://github.com/anomalyco/opencode.git tmp/opencode`. If it exists, verify it is clean with `git -C tmp/opencode status --short`, then update it with `git -C tmp/opencode pull --ff-only`. Do not discard unrelated changes from a dirty checkout.
3. Review the complete upstream release diff in `tmp/opencode` before editing Varro. Find the release commits with `git log --all --grep='v'`, then compare the previous and target release commits.
-4. Pay particular attention to public HTTP routes, `/global/event` SSE names and payloads, generated SDK/OpenAPI changes, protocol/schema types, configuration behavior, provider/model metadata, permissions/questions, session/message/part shapes, and `serve`/upgrade CLI behavior. Cross-check affected surfaces against `src/shared/opencode-types.ts`, `src/shared/protocol.ts`, `src/extension/open-code-transport.ts`, and request paths under `src/extension`.
+4. Pay particular attention to public HTTP routes, v2 `/api/event` and v1 `/global/event` SSE names and payloads, generated client/SDK/OpenAPI changes, protocol/schema types, configuration behavior, provider/model metadata, permissions/questions, session/message/part shapes, and `serve`/upgrade CLI behavior. Cross-check affected surfaces against `src/shared/opencode-types.ts`, `src/shared/protocol.ts`, `src/extension/open-code-transport.ts`, the v2 adapter modules, and request paths under `src/extension`.
5. Separate required compatibility work from optional parity work. App, desktop, TUI, localization, and styling changes usually do not require Varro changes unless they reveal behavior Varro intentionally mirrors.
-6. Update the dependency and lockfile with `npm install @opencode-ai/sdk@^`; do not hand-edit lockfile entries.
-7. Keep `MINIMUM_SUPPORTED_OPENCODE_VERSION` unchanged unless Varro starts relying on an API introduced after the current floor. The SDK dependency version records the latest tested version. It does not cap runtime support or automatic updates.
-8. After changing the manifest, run `npm run test:compatibility`. It requires Docker, probes real published servers across the support range, writes `artifacts/opencode-compatibility.json`, and regenerates the tracked `scripts/opencode-compatibility/verified.json`. Do not hand-edit the verification summary.
+6. Update the relevant dependency and lockfile with `npm install @opencode/client@^` for v2 or `npm install @opencode-ai/sdk@^` for v1; do not hand-edit lockfile entries. Retain both dependencies.
+7. Keep `MINIMUM_SUPPORTED_OPENCODE_V2_VERSION` and `MINIMUM_SUPPORTED_OPENCODE_VERSION` unchanged unless Varro starts relying on an API introduced after that family's floor. The client and SDK dependencies record tested versions, not runtime support caps or automatic-update limits.
+8. Run `npm run test:compatibility:adapters` for either family. For v1 dependency changes, also run `npm run test:compatibility`. The latter requires Docker, probes real published v1 servers across the support range, writes `artifacts/opencode-compatibility.json`, and regenerates the tracked `scripts/opencode-compatibility/verified.json`. Do not hand-edit the verification summary.
9. Let the compatibility run finish before running `npm run test -- src/shared/opencode-compatibility.test.ts`; that test reads the regenerated summary and will race if run in parallel.
-10. Update user-facing tested-version references, currently in `docs/usage.md`. Search the repository for the previous version so stale references are not left behind.
+10. Update user-facing tested-version references in `README.md`, `docs/usage.md`, and the current implementation notes in `docs/opencode-v2-support.md`. Search the repository for the previous version; preserve explicitly historical observations and lower-bound fixtures.
11. If the upstream diff changes a consumed contract, implement the smallest required adaptation and add targeted tests. Otherwise, do not churn local compatibility types merely to match SDK declarations that Varro does not consume.
12. Finish with `npm run lint:check`, `npm run typecheck`, the focused compatibility test, and `npm run build`. Report compatibility check counts and any advisory caveats separately from required failures.
+
+## V2 releases
+
+V2 publishes `@opencode/cli` and `@opencode/client`. Keep the v1 SDK and support floor when updating the v2 client. Check both package families rather than interpreting the `opencode-ai` dist-tag as the latest v2 release.
+
+Run `npm run test:compatibility:adapters` after changing either adapter or the v2 dependency. It checks the actual published binaries and records observed versions. Use the served OpenAPI document and released package contracts when upstream `dev` or the documentation differs from the release. The v2.0.5 startup endpoint is `/api/status`; the newer documentation's `/api/info` is not available in that release.
+
+The optional real-editor startup check is `VARRO_SANDBOX_V2_COMMAND=/absolute/path/to/opencode node scripts/vscode-sandbox/run.mjs v2-first-run`. Update its expected version when changing the tested v2 release.
diff --git a/docs/permission-lifecycle.md b/docs/permission-lifecycle.md
index a3fdf815..84cdc4a5 100644
--- a/docs/permission-lifecycle.md
+++ b/docs/permission-lifecycle.md
@@ -28,6 +28,10 @@ switching an existing session to default clears Varro's prior mode rules. OpenCo
and agent configuration determines whether an action is allowed, denied, or asked. If OpenCode asks
about `todowrite` or `question`, Varro replies once without installing a broader session rule.
+Ordinary sends in Default mode preserve existing session rules, including session-scoped `Always`
+approvals. Only an explicit mode change resets those rules. Sending an empty rule set is a no-op on
+v1's append-style API but clears saved approvals on v2's replacement API.
+
`Auto` is not a broader OpenCode rule set. OpenCode must still emit an ask so Varro has a
specific request ID and complete action context to judge. Giving `auto` allow-all rules would bypass
the judge and silently turn it into `full`.
diff --git a/docs/permissions.md b/docs/permissions.md
index e91a24a5..8e9df6fd 100644
--- a/docs/permissions.md
+++ b/docs/permissions.md
@@ -21,8 +21,9 @@ Changing modes affects pending requests as well as later actions. Switching to `
When OpenCode asks for permission, Varro places the request beside the action that needs it. A standalone prompt appears if that action is not currently visible.
- `Once` approves only the current request.
-- `Always` approves the request and remembers matching actions in OpenCode server memory until the
- server restarts. Its menu also offers a session-only rule or a persistent project-config rule.
+- `Always` approves the request and saves matching actions through OpenCode. V1 keeps these allowances
+ in server memory; v2 saves durable project-scoped approvals. Its menu also offers a session-only
+ rule or a persistent project-config rule.
- `Reject` denies the request.
On Varro-managed servers, rejecting a request lets the agent continue without that action. The agent
@@ -30,11 +31,14 @@ is instructed not to retry or bypass the rejection, to continue permitted work,
the denied action blocks completion. Use Stop to end the run. OpenCode may also reject other pending
requests in the same session. Skipping a question likewise lets the agent continue.
-This uses OpenCode's `experimental.continue_loop_on_deny: true` runtime default. Project or inline
+On v1, this uses OpenCode's `experimental.continue_loop_on_deny: true` runtime default. Project or inline
config can override it. If you manage the server yourself or supply `OPENCODE_CONFIG`, enable that
setting in your own OpenCode config. After updating Varro, restart its server once active work has
finished to load the new default.
+V2 does not use `experimental.continue_loop_on_deny`; that legacy setting is ignored. Rejection and
+continuation follow the v2 server's behavior and the agent's instructions.
+
Read the command, path, URL, or tool details before responding. `Always` can cover later matching actions, so use `Once` when the scope is unclear. Child-session requests appear in the parent conversation, but the permission still belongs to the child.
## How automatic review works
@@ -55,7 +59,7 @@ Commands, paths, URLs, tool metadata, and prior decisions may be sent to the sel
## Default mode and OpenCode rules
-`Default` means OpenCode decides. It does not mean every action asks for approval. Without custom rules, OpenCode allows most permissions, asks about `doom_loop` and `external_directory`, and denies reads of `.env` files and related variants while allowing files such as `.env.example`.
+`Default` means OpenCode decides. It does not mean every action asks for approval. V2's base policy allows most actions and asks for external-directory access and `.env` reads, with an allowance for `.env.example`. V1 asks about `doom_loop` and `external_directory` and denies `.env` reads except `.env.example`. V2 has no `doom_loop` or `lsp` permission action. Agent and user rules can override these defaults.
The Permissions screen keeps rule sources separate and orders them from highest to lowest
precedence. Project rules write only to the workspace `opencode.json` or `opencode.jsonc`.
@@ -68,7 +72,7 @@ OpenCode servers that do not expose saved permissions show that layer as unavail
OpenCode supports `allow`, `ask`, and `deny` rules at global, project, and agent scopes. Rules can match tools, shell commands, paths, subagents, URLs, and external directories. OpenCode uses the last matching rule.
-See [OpenCode permissions](https://opencode.ai/docs/permissions/) for configuration syntax and examples.
+See [v2 permissions](https://opencode.ai/v2/docs/permissions/) for the recommended ordered `permissions` format with `action`, `resource`, and `effect`. Supported [v1 permissions](https://opencode.ai/docs/permissions/) remain accepted by v2, so shared configuration can keep the v1 `permission` format. Native v2 uses `shell` and `subagent` where v1 uses `bash` and `task`.
## Session behavior
diff --git a/docs/usage.md b/docs/usage.md
index 4a14045e..87552fab 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -12,10 +12,10 @@ VS Code forks have limited support. See [VS Code Fork Compatibility](vscode-fork
## First Run And Connection
-Install the OpenCode CLI:
+Install the recommended [OpenCode v2 CLI](https://opencode.ai/v2/docs/) on macOS, Linux, or WSL:
```sh
-npm install -g opencode-ai
+npm install -g @opencode/cli
```
If OpenCode does not have any providers configured yet, either connect one from Varro's Models view or log in from a terminal:
@@ -24,7 +24,7 @@ If OpenCode does not have any providers configured yet, either connect one from
opencode auth login
```
-From inside Varro, `/connect` opens the provider connection dialog. The no-provider recovery screen offers the same embedded setup. Use `opencode auth login` when a provider does not expose a supported embedded method.
+From inside Varro, `/connect` opens the provider connection dialog. The no-provider recovery screen offers terminal setup. Use `opencode auth login` when a provider does not expose a supported embedded method. If you selected a custom executable such as `opencode2`, use that executable in terminal commands too.
Varro connects to `http://127.0.0.1:4096` by default. It does not start OpenCode at extension activation time. Instead, it starts or attaches to the server the first time the chat view needs it.
@@ -36,9 +36,61 @@ opencode serve --port 4096
If the CLI is installed somewhere that is not on `PATH`, set `varro.server.command` to the executable path.
-On native Windows, run the install and authentication commands in PowerShell, Command Prompt, or another Windows terminal. Varro runs on the local Windows extension host and looks for the Windows OpenCode CLI. OpenCode stores native Windows data, including credentials, logs, and sessions, under `%USERPROFILE%\.local\share\opencode`.
+When `varro.server.command` is empty, Varro searches `PATH` and common install locations for `opencode2` first, then falls back to `opencode`. Current v1 and v2 packages both install `opencode`. Check the selected executable with `--version`; its name does not determine its API version.
-OpenCode [recommends WSL for the best Windows experience](https://opencode.ai/docs/windows-wsl). Open the project in a VS Code WSL window, then install and authenticate OpenCode inside that distribution. A WSL window runs Varro and OpenCode on the Linux extension host, where data is under `~/.local/share/opencode`. A CLI installed only on Windows is not available to that host, and a CLI installed only in WSL is not available to a native VS Code window.
+On native Windows, download the standalone v2 CLI from the [install page](https://opencode.ai/v2/docs/), which does not currently support Windows package managers. Add the executable to `PATH` or set `varro.server.command` to its path. Run authentication commands in a Windows terminal. Varro runs on the local Windows extension host and looks for the Windows CLI. Native OpenCode data is under `%USERPROFILE%\.local\share\opencode`.
+
+For WSL, open the project in a VS Code WSL window, then install and authenticate OpenCode inside that distribution. A WSL window runs Varro and OpenCode on the Linux extension host, where data is under `~/.local/share/opencode`. A CLI installed only on Windows is not available to that host, and a CLI installed only in WSL is not available to a native VS Code window.
+
+### Choose and update OpenCode
+
+| Version | Minimum supported | Tested with this release | npm package |
+| --- | --- | --- | --- |
+| v2, recommended | 2.0.5 | 2.0.7 | `@opencode/cli` |
+| v1, still supported | 1.16.0 | 1.18.31 | `opencode-ai` |
+
+To keep using v1, retain your installation or run `npm install -g opencode-ai`. Set `varro.server.command` to its executable path. Setting it to `opencode` selects v1 only if that command resolves to a v1 installation. Varro detects the API automatically.
+
+Both package families now provide the same `opencode` command. When switching from a package-managed v1 installation to v2, remove the v1 package with its package manager first, then install `@opencode/cli`. For npm, use `npm uninstall -g opencode-ai`, then `npm install -g @opencode/cli`. This removes the package, not your history or configuration. If you keep both versions, use separate installation locations and explicit executable paths.
+
+If you previously used v1, installing v2 may leave Varro connected to the running v1 server. Check that `varro.server.command` points to the v2 executable if you set it explicitly. Let active work finish, then run `Varro: Restart Server` from the Command Palette. This is also needed after changing `varro.server.command`. The command only restarts a Varro-managed server; restart a manually managed server in its own terminal using the v2 executable. Confirm that Varro's status bar shows OpenCode v2 after reconnecting.
+
+Updates stay within the installed CLI family. For an npm installation, use `npm install -g @opencode/cli@latest` for v2 or `npm install -g opencode-ai@latest` for v1. Use the original installer for other installation methods. `varro.server.autoUpdate` does not switch v1 users to v2. Native Windows uses a prompt instead of replacing a running binary in the background; standalone installations should use the current download from their version's install page.
+
+Supported v1 configuration remains accepted by v2. Native v2 configuration uses fields such as `agents`, `permissions`, and `mcp.servers`; v1 cannot read those native-v2-only shapes. Keep compatible configuration if switching between versions. Plugins require a v2 port. See the [upstream migration guide](https://opencode.ai/v2/docs/migrate-v1/).
+
+### If restart does not switch to v2
+
+`Varro: Restart Server` may not be enough. An old OpenCode process can keep the port occupied, and Varro will not terminate a process it cannot identify as its own. This can also affect a leftover server from an earlier Varro run. On Windows, you may need to end the old `opencode.exe` process explicitly.
+
+1. Let active work finish in all clients using that server. Stop a manually launched server with `Ctrl+C` in its terminal. If another app or service keeps relaunching it, stop it there too.
+2. Identify the process listening on Varro's server port, `4096` by default. Use your configured `varro.server.port` if different. Run these steps on the host where Varro runs, such as the WSL distribution or SSH host for a remote workspace.
+3. Stop that old OpenCode process using the platform steps below, then run `Varro: Restart Server` again. For a manually managed server, start it with the v2 executable instead.
+4. Confirm that Varro's status bar shows OpenCode v2. If it still shows v1, check the executable rather than repeating the restart. Run your selected executable with `--version` and set `varro.server.command` to the full v2 executable path. An old `opencode2` takes precedence over `opencode` when this setting is empty. If you changed `PATH`, fully close and reopen VS Code so it picks up the new environment.
+
+On native Windows, find the listening process in PowerShell:
+
+```powershell
+Get-NetTCPConnection -LocalPort 4096 -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess
+```
+
+Match `OwningProcess` to the PID in Task Manager's **Details** tab and confirm its executable path or command line belongs to the old OpenCode server. Use **End process tree** on that process. Alternatively, run the following command, replacing `12345` with the confirmed PID:
+
+```powershell
+taskkill /PID 12345 /T /F
+```
+
+Target the confirmed server PID rather than ending every OpenCode process. If Windows reports access denied, use an elevated Task Manager or PowerShell. Stopping the process also releases Windows' lock on `opencode.exe` if it prevented replacing the old executable; complete the v2 installation before restarting.
+
+On macOS or Linux, use `lsof -nP -iTCP:4096 -sTCP:LISTEN` to find the listener. After confirming it is the old OpenCode server, run `kill `. If it does not exit, use `kill -9 `, replacing `` with that process ID.
+
+### Version differences and history
+
+- V2 does not expose session sharing or an OpenCode LSP service. Sharing is disabled on v2. VS Code Problems remain available as explicit context.
+- V2 cannot patch arbitrary session metadata. Varro keeps session annotations under the user's XDG state directory in `varro/opencode-v2/`. These annotations are local to Varro and are not synchronized to other OpenCode clients.
+- Changing CLI versions does not migrate or synchronize history. While connected to v2, run `Varro: Import OpenCode v1 Session into v2` to copy a local workspace conversation and its child sessions. The copy has new IDs and a title ending in `(v1 copy)`. You can continue it without changing the original v1 history. Imports do not execute recorded tools or send a model request.
+
+See [OpenCode v1 and v2 support](opencode-v2-support.md) for adapter details and verification coverage.
## Workspace And Remote Environments
@@ -92,7 +144,7 @@ Varro keeps at most five pasted images, with a maximum size of 5 MiB per image.
### Add Vision To A Text-Only Model
-Varro can delegate pasted images from a tool-capable text-only model, such as GLM, to an OpenCode subagent named `vision`. Add the agent to `opencode.json` and replace the example model with a model available from one of your configured providers:
+Varro can delegate pasted images from a tool-capable text-only model, such as GLM, to an OpenCode subagent named `vision`. Add the agent to `opencode.json` and replace the example model with a model available from one of your configured providers. This example uses supported v1-format configuration so it works with both v1 and v2:
```json
{
@@ -147,6 +199,7 @@ Commands offered in slash-command completion include:
- `/settings` opens VS Code Settings filtered to Varro
- `/export` opens a JSON export of the current session in the editor
- `/stats` opens a Markdown token and assistant-duration report for the last 30 days across all OpenCode projects; `/stats all` also includes retained all-time usage
+- Usage reports include local V1 and V2 sessions. For migrated sessions, including Varro imports, only the session with the latest update time contributes usage. Equal update times prefer V2.
- `/thinking` or `/reasoning` toggles thinking block visibility
- `/compact` or `/summarize` compacts conversation context
- `/fork` forks the current session
@@ -173,7 +226,7 @@ Sessions from every open workspace root appear in one catalog. Use the folder fi
- Search uses OpenCode's native root-session search across loaded and older history and returns up to 30 results. Matching fields depend on the installed OpenCode version. Run `Varro: Search Sessions` to open and focus search directly.
- Filter or jump to `Running`, `Needs attention`, `Failed`, `Plan ready`, and `Completed` sessions from the header badges.
- Open sub-agent sessions from the parent session row when they exist.
-- Top-level sessions can be renamed, pinned, or moved to the recycle bin. Drag a pinned session's handle, or focus it and press `ArrowUp` or `ArrowDown`, to reorder pinned sessions. Any session can open in the sidebar, an editor tab, or the OpenCode TUI; copy its ID; and be shared or unshared. Opening an editor session in the sidebar closes its matching editor tab. Sharing asks OpenCode to create a share link and copies it to the clipboard.
+- Top-level sessions can be renamed, pinned, or moved to the recycle bin. Drag a pinned session's handle, or focus it and press `ArrowUp` or `ArrowDown`, to reorder pinned sessions. Any session can open in the sidebar, an editor tab, or the OpenCode TUI, and its ID can be copied. Opening an editor session in the sidebar closes its matching editor tab. On v1, sharing asks OpenCode to create a share link and copies it to the clipboard; v2 sharing is unavailable.
- Deleted session roots move into a recycle bin section where you can restore them or delete them permanently for 24 hours before they expire.
- Stop the active run with `Varro: Abort Session`.
- Use `/export` to open the current session as JSON in the editor.
@@ -247,7 +300,7 @@ Choose the config scope based on where you want the agent to appear:
OpenCode merges global and project configuration. A project agent with the same name overrides the matching global agent fields. Keep provider credentials and other secrets in the global config, not in a committed project file.
-This example adds `ask`, a primary agent that can inspect local code and search documentation but cannot edit files, run commands, delegate to subagents, or call unlisted custom and MCP tools:
+This example uses supported v1-format configuration for both CLI families. It adds `ask`, a primary agent that can inspect local code and search documentation but cannot edit files, run commands, delegate to subagents, or call unlisted custom and MCP tools. The `lsp` allowance only has an effect on v1:
```json
{
@@ -280,7 +333,7 @@ Omit `model` to use the configured global model, or add a provider-qualified mod
### Session selections across editor instances
-Varro saves explicit model, reasoning variant, and agent selections in OpenCode session metadata.
+On v1, Varro saves explicit model, reasoning variant, and agent selections in OpenCode session metadata.
Opening the same session in another extension instance, including VS Code Insiders, restores those
selections ahead of local preferences and historical messages. Session updates also refresh them in
open views. Restoring a session does not write metadata or change its last-updated timestamp.
@@ -290,6 +343,8 @@ The stored fields are `metadata.varro.model`, containing `provider`, `model`, an
clears the previous reasoning selection. Existing sessions without these fields retain the previous
local and history-based fallback behavior until an explicit selection is saved.
+On v2, the adapter stores these annotations locally in Varro's state directory rather than writing them to OpenCode session metadata. Other OpenCode clients do not receive them.
+
Varro merges its fields under `metadata.varro`, preserving workspace scope and unrelated metadata:
```json
@@ -369,7 +424,7 @@ This allows a flow where the main agent orchestrates work across different model
In OpenCode, this is configured by assigning `model` per agent or subagent. If a subagent does not define its own model, it inherits the model of the primary agent that invoked it.
-Example:
+The following example uses the supported v1 format for compatibility with both versions. For native v2 configuration, use `agents` instead of `agent`, `agents.title.model` instead of `small_model`, and `request.body.temperature` instead of `temperature`. See the [v2 migration reference](https://opencode.ai/v2/docs/migrate-v1/#agents-and-modes).
```json
{
@@ -424,7 +479,7 @@ Additional recommendations:
- Explicitly pin important subagents to their own models.
- Use project `opencode.json` or `.opencode/agents/` if you want team-shared routing.
- Keep provider credentials and secrets in your user-level OpenCode config instead of project config.
-- Use `permission.task` if you want to control which subagents a primary agent is allowed to invoke.
+- Use rules with `action: "subagent"` in native v2 `permissions`, or `permission.task` in v1-format configuration, to control which subagents a primary agent may invoke.
## Permissions And Questions
@@ -443,12 +498,13 @@ parent conversation while keeping the request owned by the child session.
agent determine which actions are allowed, denied, or sent to Varro for manual approval. Varro does
not add session-level permission rules in this mode.
-Without custom OpenCode rules, most permissions are allowed. OpenCode asks before repeated identical
-tool calls (`doom_loop`) or access outside the working directory (`external_directory`), and its
-default read rules deny `.env` files and variants while allowing `.env.example`. These are OpenCode
-defaults, not additional Varro rules.
+OpenCode defaults depend on the version and agent. V2's base policy allows most actions and asks for
+external-directory access and `.env` reads, with an allowance for `.env.example`. V1 asks for
+`doom_loop` and external-directory access and denies `.env` reads except `.env.example`.
+V2 has no `doom_loop` or `lsp` permission action. Agent rules can further restrict these defaults.
-See [OpenCode permissions](https://opencode.ai/docs/permissions/) for the full list of permission keys
+See [v2 permissions](https://opencode.ai/v2/docs/permissions/) or
+[v1 permissions](https://opencode.ai/docs/permissions/) for the full list of permission keys
and configuration examples for global and per-agent `allow`, `ask`, and `deny` rules. Rules can match
tools, commands, paths, subagents, skills, URLs, and external directories. When multiple patterns
match, the last matching rule wins.
@@ -529,6 +585,7 @@ Editable user messages expose an edit action. Sending the replacement removes th
- `Varro: New Chat Editor`
- `Varro: New Terminal Editor`
- `Varro: Search Sessions`
+- `Varro: Import OpenCode v1 Session into v2`
- `Varro: Open Settings`
- `Varro: Show File Diffs` or `Varro: Hide File Diffs`
- `Varro: Usage Stats`
@@ -553,8 +610,8 @@ Server:
- `varro.server.autoStart` - auto-start `opencode serve` when Varro first needs it; defaults to `true` and is marked deprecated/debug-only in VS Code
- `varro.server.port` - port used for the local OpenCode server (default `4096`); reload the VS Code window after changing it
-- `varro.server.command` - optional path to the OpenCode CLI executable
-- `varro.server.autoUpdate` - automatically install the latest OpenCode CLI update in the background on macOS and Linux. Native Windows uses an upgrade prompt instead because a running server can lock `opencode.exe`. Before opening a Windows update command, Varro waits for active work and stops its managed server; stop a manually launched server yourself. Failed automatic updates show tailored recovery guidance.
+- `varro.server.command` - optional path to the OpenCode CLI executable. Empty prefers `opencode2`, then `opencode`; use your v1 executable's path to keep v1 selected
+- `varro.server.autoUpdate` - automatically install updates within the installed CLI family in the background on macOS and Linux. V1 stays on v1; v2 stays on v2. Native Windows uses an upgrade prompt instead because a running server can lock `opencode.exe`. Before opening a Windows update command, Varro waits for active work and stops its managed server; stop a manually launched server yourself. Failed automatic updates show tailored recovery guidance.
Chat view:
@@ -583,8 +640,10 @@ There are also deprecated debug-only settings used for development and recovery
## Troubleshooting
-- OpenCode CLI missing: install it with `npm install -g opencode-ai`.
-- OpenCode CLI incompatible: `1.16.0` is the runtime floor. `1.18.31` is the version tested with this Varro release, not a runtime maximum. Newer versions are allowed to run and remain eligible for updates.
+- OpenCode CLI missing: install v2 with `npm install -g @opencode/cli` on macOS, Linux, or WSL, or download the native Windows CLI from the [v2 install page](https://opencode.ai/v2/docs/). V1 remains available with `npm install -g opencode-ai`.
+- OpenCode CLI incompatible: Varro supports the v1 API from `1.16.0` and the v2 API from `2.0.5`. This release was tested with v1 `1.18.31` and v2 `2.0.7`. Varro selects the API automatically, including when `varro.server.command` points to a custom binary such as `opencode2`. Updates use the installed CLI's package family.
+- OpenCode v2 authentication: Varro captures managed-server credentials automatically and redacts them from output. Existing local services use their registered credentials. An externally managed server can also use `OPENCODE_SERVER_PASSWORD` and `OPENCODE_SERVER_USERNAME` from the extension host's environment.
+- OpenCode v2 session settings: Varro stores mutable session annotations locally because the released v2 API cannot update session metadata. Session sharing is unavailable through this API, so its menu action is disabled. Existing v1-format configuration remains supported.
- CLI not on `PATH`: set `varro.server.command` to the executable path.
- Windows host mismatch: install OpenCode in Windows for a native VS Code window, or inside the distribution for a VS Code WSL window. Run `Varro: About` and check `Platform` if the active extension host is unclear.
- Windows update reports a locked file: finish active sessions and close the OpenCode update terminal before retrying. Stop any OpenCode server not managed by Varro yourself.
diff --git a/e2e/tests/error-states.spec.ts b/e2e/tests/error-states.spec.ts
index c1937cc6..a9b946c9 100644
--- a/e2e/tests/error-states.spec.ts
+++ b/e2e/tests/error-states.spec.ts
@@ -6,32 +6,52 @@ test('shows the missing-cli error state and offers install actions', async ({ pa
await page.goto('/e2e/harness/index.html?scenario=server-error-missing-cli');
await expect(page.getByText('OpenCode is not installed', { exact: true })).toBeVisible();
- await expect(page.getByText('npm i -g opencode-ai', { exact: true })).toBeVisible();
- await page.getByRole('button', { name: 'Open terminal and install' }).click();
+ await expect(page.getByText('npm i -g @opencode/cli', { exact: true })).toBeVisible();
+ await page.getByRole('button', { name: 'Open terminal and install', exact: true }).click();
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { terminalCommands?: Array<{ command: string; title?: string }> };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { terminalCommands?: Array<{ command: string; title?: string }> };
+ }
+ ).__varroE2E;
return value?.terminalCommands?.[0] || null;
})
)
- .toEqual({ command: 'npm i -g opencode-ai', title: 'OpenCode Install' });
+ .toEqual({ command: 'npm i -g @opencode/cli', title: 'OpenCode Install' });
await page.getByRole('button', { name: 'Learn more at opencode.ai' }).click();
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { externalUrls?: string[] };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { externalUrls?: string[] };
+ }
+ ).__varroE2E;
return value?.externalUrls?.[0] || null;
})
)
- .toBe('https://opencode.ai');
+ .toBe('https://opencode.ai/v2/docs/');
+
+ await page.getByText('Use OpenCode v1 instead', { exact: true }).click();
+ await expect(page.getByText('npm i -g opencode-ai', { exact: true })).toBeVisible();
+ await page.getByRole('button', { name: 'Open terminal and install v1', exact: true }).click();
+ await expect
+ .poll(() =>
+ getE2EState(page, () => {
+ const value = (
+ window as Window & {
+ __varroE2E?: { terminalCommands?: Array<{ command: string; title?: string }> };
+ }
+ ).__varroE2E;
+ return value?.terminalCommands?.[1] || null;
+ })
+ )
+ .toEqual({ command: 'npm i -g opencode-ai', title: 'OpenCode Install' });
});
test('shows a generic startup error message', async ({ page }) => {
@@ -49,9 +69,11 @@ test('restarts the server from an error state without the command palette', asyn
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { serverRestartCount?: number };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { serverRestartCount?: number };
+ }
+ ).__varroE2E;
return value?.serverRestartCount || 0;
})
)
@@ -71,9 +93,11 @@ test('points at the setting when the configured CLI path is wrong', async ({ pag
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { settingsQueries?: string[] };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { settingsQueries?: string[] };
+ }
+ ).__varroE2E;
return value?.settingsQueries?.[0] || null;
})
)
@@ -94,9 +118,11 @@ test('recommends the install-specific command after a failed update', async ({ p
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { terminalCommands?: Array<{ command: string; title?: string }> };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { terminalCommands?: Array<{ command: string; title?: string }> };
+ }
+ ).__varroE2E;
return value?.terminalCommands?.[0] || null;
})
)
@@ -114,9 +140,11 @@ test('presents an update deferred by active sessions as a wait', async ({ page }
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { serverRestartCount?: number };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { serverRestartCount?: number };
+ }
+ ).__varroE2E;
return value?.serverRestartCount || 0;
})
)
@@ -133,9 +161,11 @@ test('opens the blocking setting when auto-update is disabled', async ({ page })
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: { settingsQueries?: string[] };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { settingsQueries?: string[] };
+ }
+ ).__varroE2E;
return value?.settingsQueries?.[0] || null;
})
)
diff --git a/e2e/tests/scroll-activity-handoff.spec.ts b/e2e/tests/scroll-activity-handoff.spec.ts
index 00402190..87880583 100644
--- a/e2e/tests/scroll-activity-handoff.spec.ts
+++ b/e2e/tests/scroll-activity-handoff.spec.ts
@@ -3,7 +3,7 @@ import type { ServerEvent } from '../../src/shared/protocol';
import type { AssistantMessage, MessageEntry, Session, ToolPart } from '../../src/webview/types';
for (const settleMs of [0, 600]) {
- for (const replacement of ['edit', 'text'] as const) {
+ for (const replacement of ['edit', 'text', 'streaming-patch'] as const) {
for (const shortHistory of [false, true]) {
test(`activity exit anchoring yields to ${replacement} after ${settleMs} ms with ${shortHistory ? 'short' : 'overflowing'} history`, async ({
page,
@@ -234,7 +234,12 @@ for (const settleMs of [0, 600]) {
properties: {
part: {
...part,
- state: { status: 'pending' as const, input: part.state.input, raw: '' },
+ tool: kind === 'streaming-patch' ? 'patch' : part.tool,
+ state: {
+ status: 'pending' as const,
+ input: kind === 'streaming-patch' ? {} : part.state.input,
+ raw: '',
+ },
},
},
});
@@ -275,7 +280,14 @@ for (const settleMs of [0, 600]) {
);
if (replacement === 'edit')
await expect(page.locator('.file-change-card-header').last()).toContainText('source.ts');
- else
+ else if (replacement === 'streaming-patch') {
+ const editing = page.locator('[data-msg-id="handoff-edit-message"]');
+ await expect(editing.locator('.tool-invocation-title.shimmer-progress')).toHaveText(
+ 'Editing'
+ );
+ await expect(editing.locator('.tool-status-running')).toBeVisible();
+ await expect(editing.locator('.assistant-activity-summary')).toHaveCount(0);
+ } else
await expect(page.locator('.rendered-markdown').last()).toContainText(
'Next step output.'
);
diff --git a/e2e/tests/scroll-return-tool-completion.spec.ts b/e2e/tests/scroll-return-tool-completion.spec.ts
new file mode 100644
index 00000000..93426dc9
--- /dev/null
+++ b/e2e/tests/scroll-return-tool-completion.spec.ts
@@ -0,0 +1,129 @@
+import { expect, test } from '@playwright/test';
+import type { ServerEvent } from '../../src/shared/protocol';
+import type { MessageEntry, ToolPart } from '../../src/webview/types';
+import { getScrollMetrics } from './helpers';
+
+for (const distance of [540, 1768]) {
+ test(`return to latest survives tool completion during a ${distance}px scroll`, async ({
+ page,
+ }, testInfo) => {
+ await page.setViewportSize({ width: 486, height: 900 });
+ await page.emulateMedia({ reducedMotion: 'no-preference' });
+ await page.goto('/e2e/harness/index.html?scenario=large-transcript');
+ const list = page.locator('.interactive-list');
+ await expect(page.locator('.interactive-list-track')).toHaveClass(/virtualized/);
+ await page.evaluate(() => {
+ // SAFETY: The isolated E2E page installs the typed fixture event transport.
+ const harness = (
+ window as typeof window & {
+ __varroE2E: { replayServerEvent(event: ServerEvent): void };
+ }
+ ).__varroE2E;
+ harness.replayServerEvent({
+ type: 'session.status',
+ properties: { sessionID: 'session-large-transcript', status: { type: 'busy' } },
+ });
+ harness.replayServerEvent({
+ type: 'message.part.updated',
+ properties: {
+ part: {
+ id: 'return-running-tool',
+ callID: 'return-running-tool',
+ sessionID: 'session-large-transcript',
+ messageID: 'message-large-assistant-239',
+ type: 'tool',
+ tool: 'read',
+ state: {
+ status: 'running',
+ input: { filePath: '/workspace/probe.txt' },
+ time: { start: 1 },
+ },
+ },
+ },
+ });
+ });
+ await expect
+ .poll(() => getScrollMetrics(page, '.interactive-list').then((m) => m.distanceFromBottom))
+ .toBeLessThan(2);
+ await list.hover({ position: { x: 20, y: 100 } });
+ await page.mouse.wheel(0, -distance);
+ await expect
+ .poll(() => getScrollMetrics(page, '.interactive-list').then((m) => m.distanceFromBottom))
+ .toBeGreaterThan(distance - 50);
+ const button = page.getByRole('button', { name: 'Scroll to latest message', exact: true });
+ await expect(button).toBeVisible();
+
+ const recording = list.evaluate(async (element) => {
+ // SAFETY: The isolated E2E page installs the typed fixture event transport and message store.
+ const harness = (
+ window as typeof window & {
+ __varroE2E: {
+ replayServerEvent(event: ServerEvent): void;
+ getSessionMessages(id: string): MessageEntry[];
+ };
+ }
+ ).__varroE2E;
+ const initialTop = element.scrollTop;
+ let completed = false;
+ let settledFrames = 0;
+ const samples = [];
+ for (let frame = 0; frame < 600; frame++) {
+ await new Promise((resolve) => requestAnimationFrame(() => resolve()));
+ const remaining = element.scrollHeight - element.clientHeight - element.scrollTop;
+ if (!completed && element.scrollTop > initialTop + 10) {
+ const entry = harness
+ .getSessionMessages('session-large-transcript')
+ .find((message) => message.info.id === 'message-large-assistant-239')!;
+ const tool = entry.parts.find(
+ (part): part is ToolPart => part.type === 'tool' && part.id === 'return-running-tool'
+ )!;
+ harness.replayServerEvent({
+ type: 'message.part.updated',
+ properties: {
+ part: {
+ ...tool,
+ state: {
+ status: 'completed' as const,
+ input: tool.state.input,
+ title: 'Read probe',
+ output: 'contents',
+ metadata: {},
+ time: { start: 1, end: 2 },
+ },
+ },
+ },
+ });
+ harness.replayServerEvent({
+ type: 'session.status',
+ properties: { sessionID: 'session-large-transcript', status: { type: 'idle' } },
+ });
+ completed = true;
+ }
+ const viewport = element.getBoundingClientRect();
+ const rows = Array.from(element.querySelectorAll('[data-msg-id]'));
+ samples.push({
+ remaining,
+ completed,
+ painted: rows.some((row) => {
+ const rect = row.getBoundingClientRect();
+ return rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom;
+ }),
+ duplicates: rows.length - new Set(rows.map((row) => row.dataset.msgId)).size,
+ });
+ settledFrames = completed && remaining <= 2 ? settledFrames + 1 : 0;
+ if (settledFrames >= 5) break;
+ }
+ return samples;
+ });
+ await button.click();
+ const samples = await recording;
+ await testInfo.attach('return-frames', {
+ body: JSON.stringify(samples),
+ contentType: 'application/json',
+ });
+ expect(samples.find((sample) => sample.completed)?.remaining).toBeGreaterThan(2);
+ expect(samples.at(-1)?.remaining).toBeLessThanOrEqual(2);
+ expect(samples.every((sample) => sample.painted && sample.duplicates === 0)).toBe(true);
+ await expect(button).toHaveCount(0);
+ });
+}
diff --git a/e2e/tests/server-status.spec.ts b/e2e/tests/server-status.spec.ts
index 0fb606ae..eeba8f94 100644
--- a/e2e/tests/server-status.spec.ts
+++ b/e2e/tests/server-status.spec.ts
@@ -9,17 +9,19 @@ test('shows no-provider setup actions and triggers provider setup commands', asy
await expect(page.getByText('opencode auth login', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Open terminal and add a provider' }).click();
- await page.getByRole('button', { name: 'Provider setup docs' }).click();
+ await page.getByRole('button', { name: 'Provider setup docs (v2)', exact: true }).click();
await expect
.poll(() =>
getE2EState(page, () => {
- const value = (window as Window & {
- __varroE2E?: {
- terminalCommands?: Array<{ command: string; title?: string }>;
- externalUrls?: string[];
- };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: {
+ terminalCommands?: Array<{ command: string; title?: string }>;
+ externalUrls?: string[];
+ };
+ }
+ ).__varroE2E;
return {
terminal: value?.terminalCommands?.[0] || null,
url: value?.externalUrls?.[0] || null,
@@ -28,7 +30,7 @@ test('shows no-provider setup actions and triggers provider setup commands', asy
)
.toEqual({
terminal: { command: 'opencode auth login', title: 'OpenCode Provider Setup' },
- url: 'https://opencode.ai/docs/providers',
+ url: 'https://opencode.ai/v2/docs/providers',
});
});
@@ -40,7 +42,9 @@ test('recovers when the webview reloads while startup is still in progress', asy
await page.reload();
await expect(page.getByText('Starting OpenCode...', { exact: true })).toBeVisible();
- await expect(page.getByLabel('Back to sessions').locator('..').getByText('Startup handoff')).toBeVisible();
+ await expect(
+ page.getByLabel('Back to sessions').locator('..').getByText('Startup handoff')
+ ).toBeVisible();
await expect(
page.getByText('Startup completed without losing the restored session.', { exact: true })
).toBeVisible();
@@ -53,12 +57,16 @@ test('recovers when the first startup connection attempt loses the race', async
await expect
.poll(() =>
page.evaluate(() => {
- const value = (window as Window & {
- __varroE2E?: { requests: Array<{ method: string; path: string }> };
- }).__varroE2E;
- return value?.requests.filter(
- (request) => request.method === 'GET' && request.path === '/global/health'
- ).length || 0;
+ const value = (
+ window as Window & {
+ __varroE2E?: { requests: Array<{ method: string; path: string }> };
+ }
+ ).__varroE2E;
+ return (
+ value?.requests.filter(
+ (request) => request.method === 'GET' && request.path === '/global/health'
+ ).length || 0
+ );
})
)
.toBe(2);
@@ -66,9 +74,11 @@ test('recovers when the first startup connection attempt loses the race', async
await expect
.poll(() =>
page.evaluate(() => {
- const value = (window as Window & {
- __varroE2E?: { requests: Array<{ method: string; path: string }> };
- }).__varroE2E;
+ const value = (
+ window as Window & {
+ __varroE2E?: { requests: Array<{ method: string; path: string }> };
+ }
+ ).__varroE2E;
return (value?.requests || []).map((request) => `${request.method} ${request.path}`);
})
)
@@ -81,9 +91,13 @@ test('recovers when the first startup connection attempt loses the race', async
])
);
- await expect(page.getByText('Failed to connect to OpenCode server', { exact: true })).toHaveCount(0);
+ await expect(page.getByText('Failed to connect to OpenCode server', { exact: true })).toHaveCount(
+ 0
+ );
await expect(page.getByLabel('Back to sessions')).toBeVisible();
- await expect(page.getByLabel('Back to sessions').locator('..').getByText('Startup race recovery')).toBeVisible();
+ await expect(
+ page.getByLabel('Back to sessions').locator('..').getByText('Startup race recovery')
+ ).toBeVisible();
await expect(
page.getByText('The second startup attempt connected and restored the session state.', {
exact: true,
diff --git a/package-lock.json b/package-lock.json
index 98fa8dda..ee1fad88 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,16 +1,17 @@
{
"name": "varro",
- "version": "0.28.26",
+ "version": "0.29.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "varro",
- "version": "0.28.26",
+ "version": "0.29.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@opencode-ai/sdk": "^1.18.31",
+ "@opencode/client": "^2.0.7",
"cross-spawn": "7.0.6",
"dompurify": "3.4.15",
"highlight.js": "11.12.0",
@@ -30,7 +31,7 @@
"css.escape": "1.5.1",
"esbuild": "0.28.2",
"iconoir": "7.12.1",
- "jsdom": "30.0.1",
+ "jsdom": "30.1.0",
"material-icon-theme": "5.38.1",
"oxfmt": "0.68.0",
"oxlint": "1.83.0",
@@ -62,20 +63,20 @@
}
},
"node_modules/@asamuzakjp/css-color": {
- "version": "6.0.7",
- "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-6.0.7.tgz",
- "integrity": "sha512-vC/bk1Lz7Tn/EfU9/apOTBk80/8dyGyWMowPoV1tJ52muDGsDqt2HPT2klrFUiY60MQmQv9q8yIht15JnBgDGw==",
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.0.0.tgz",
+ "integrity": "sha512-IxddtGnnoidVSO6O/aiTueptbTThHvi2qGHu9/AWuD1J7i86Ox+jl+Y5SXcDH1RixzQlP2cjH/PjnlImZiAurQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@csstools/css-calc": "^3.3.0",
- "@csstools/css-color-parser": "^4.1.10",
+ "@csstools/css-color-parser": "^4.2.0",
"@csstools/css-parser-algorithms": "^4.0.0",
"@csstools/css-tokenizer": "^4.0.0",
"lru-cache": "^11.5.2"
},
"engines": {
- "node": "^22.13.0 || >=24.0.0"
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
@@ -89,19 +90,19 @@
}
},
"node_modules/@asamuzakjp/dom-selector": {
- "version": "8.3.2",
- "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-8.3.2.tgz",
- "integrity": "sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==",
+ "version": "9.1.4",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.1.4.tgz",
+ "integrity": "sha512-ynDE7RDZM1z+YuSU+iGhRp8WcSXHqK9+G32ZEzsL35TKSoy72fYR7VfrJCQkWe3ciiIWGSTAIBc9XB5jVpqyTw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "bidi-js": "^1.0.3",
+ "bidi-js": "^1.1.0",
"css-tree": "^3.2.1",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.2"
},
"engines": {
- "node": "^22.13.0 || >=24.0.0"
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": {
@@ -669,9 +670,9 @@
}
},
"node_modules/@csstools/css-calc": {
- "version": "3.3.0",
- "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",
- "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.0.tgz",
+ "integrity": "sha512-XQKj5B7QiZcHiegCOCAzcAOJdhGgWOHbbu62h5e5mkHnn8lWcfiJhllkqWmxu5zWR9jucPHuo1iTB56P033hcg==",
"dev": true,
"funding": [
{
@@ -693,9 +694,9 @@
}
},
"node_modules/@csstools/css-color-parser": {
- "version": "4.2.2",
- "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.2.tgz",
- "integrity": "sha512-3QKjR/vxyjcSXBLgb6lP0S3MGdvwbmqSsvLPbYdVORqPDc8FX1HAJ0Spk38bxaRXgvENTA47tlhhbb5Z2e8hEg==",
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.3.tgz",
+ "integrity": "sha512-y4LpL+lmpuyKDiEFq2PnZUVFdAjsoB/qQJod79yLNokXyW7jewi+/WJ69EfItj8A2unWtxXnGjw6LYXgXu5ZjA==",
"dev": true,
"funding": [
{
@@ -710,7 +711,7 @@
"license": "MIT",
"dependencies": {
"@csstools/color-helpers": "^6.1.1",
- "@csstools/css-calc": "^3.3.0"
+ "@csstools/css-calc": "^3.4.0"
},
"engines": {
"node": ">=20.19.0"
@@ -744,9 +745,9 @@
}
},
"node_modules/@csstools/css-syntax-patches-for-csstree": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.12.tgz",
- "integrity": "sha512-3vLQK+dXxhBMR2Wx99PTCifE+vHtW2ndZWyla8yK813ev6oGhyn8Lja8jCyGAWTJ+LEYZK7EVtJxrDj8ztevJw==",
+ "version": "1.1.14",
+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.14.tgz",
+ "integrity": "sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==",
"dev": true,
"funding": [
{
@@ -1324,6 +1325,84 @@
"@chevrotain/types": "~11.1.2"
}
},
+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz",
+ "integrity": "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.4.tgz",
+ "integrity": "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.4.tgz",
+ "integrity": "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.4.tgz",
+ "integrity": "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.4.tgz",
+ "integrity": "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.4.tgz",
+ "integrity": "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@napi-rs/keyring": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring/-/keyring-1.3.0.tgz",
@@ -1565,6 +1644,48 @@
"cross-spawn": "7.0.6"
}
},
+ "node_modules/@opencode/client": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@opencode/client/-/client-2.0.7.tgz",
+ "integrity": "sha512-Latj3gobO+J3872bisjDNc449Rfy1ADZCIKnXJzcuJWTYGWp/EmDMLCRnnrxoUREcbeNCFqMCLLTbrB0/RtOyA==",
+ "license": "MIT",
+ "dependencies": {
+ "@opencode/protocol": "2.0.7",
+ "@opencode/schema": "2.0.7"
+ },
+ "peerDependencies": {
+ "effect": "4.0.0-rc.112",
+ "solid-js": ">=1.9.0"
+ },
+ "peerDependenciesMeta": {
+ "effect": {
+ "optional": true
+ },
+ "solid-js": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@opencode/protocol": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@opencode/protocol/-/protocol-2.0.7.tgz",
+ "integrity": "sha512-VmpG4EKM/VyMgVsjxY3LRl8lPtrtunlwX13fYDfmus44jg2wDdv36pbi/JhnN3yWYt5NPaMA6KFqTdBM//QDvw==",
+ "license": "MIT",
+ "dependencies": {
+ "@opencode/schema": "2.0.7",
+ "effect": "4.0.0-rc.112"
+ }
+ },
+ "node_modules/@opencode/schema": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@opencode/schema/-/schema-2.0.7.tgz",
+ "integrity": "sha512-LUEZTMYRuEqgiL9CiUo607OrjvG/euIDjoP9kDg4sfac/lA2UmFjjrT/KXatVydJq8C1uqLVxwDRYMstwapM+A==",
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "1.1.0",
+ "effect": "4.0.0-rc.112"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.150.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz",
@@ -2582,6 +2703,12 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "license": "MIT"
+ },
"node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
@@ -4060,9 +4187,9 @@
}
},
"node_modules/bidi-js": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
- "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4952,7 +5079,7 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
- "dev": true,
+ "devOptional": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
@@ -5009,6 +5136,16 @@
"url": "https://bevry.me/fund"
}
},
+ "node_modules/effect": {
+ "version": "4.0.0-rc.112",
+ "resolved": "https://registry.npmjs.org/effect/-/effect-4.0.0-rc.112.tgz",
+ "integrity": "sha512-wXxwuh1Ywnv4cPRM3Wfa0vDwuOHnZ1TsTgHJkG9XgzND6inhBH9n1vBxhg3iIXOia/OrpmvVmd3lrD4vq6bF3A==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-check": "^4.9.0",
+ "msgpackr": "^2.0.5"
+ }
+ },
"node_modules/electron-to-chromium": {
"version": "1.5.422",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.422.tgz",
@@ -5167,6 +5304,28 @@
"node": ">=12.0.0"
}
},
+ "node_modules/fast-check": {
+ "version": "4.10.1",
+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.1.tgz",
+ "integrity": "sha512-sB5Vghiu8MyCyToHoBVGsT0baZg3sZWNIY+a6Ct2EDrQJlT4YdH6MC1BSLNe3kX1k5i5g0q1O52XFgcKK/rGHg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "pure-rand": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=12.17.0"
+ }
+ },
"node_modules/fastdom": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/fastdom/-/fastdom-1.0.12.tgz",
@@ -5512,16 +5671,16 @@
"license": "MIT"
},
"node_modules/jsdom": {
- "version": "30.0.1",
- "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.0.1.tgz",
- "integrity": "sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==",
+ "version": "30.1.0",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.0.tgz",
+ "integrity": "sha512-h/Q+H+KmlGf49ITw3TrykSVbg04S75S2O7ZtJc9gMGOWBrQRZmx5AJIKLtJ01e6Kszl+/tpFthCVqxNifxhoqg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@asamuzakjp/css-color": "^6.0.5",
- "@asamuzakjp/dom-selector": "^8.3.0",
+ "@asamuzakjp/css-color": "^7.0.0",
+ "@asamuzakjp/dom-selector": "^9.1.2",
"@bramus/specificity": "^2.4.2",
- "@csstools/css-syntax-patches-for-csstree": "^1.1.7",
+ "@csstools/css-syntax-patches-for-csstree": "^1.1.13",
"@exodus/bytes": "^1.15.1",
"css-tree": "^3.2.1",
"data-urls": "^7.0.0",
@@ -5531,13 +5690,12 @@
"lru-cache": "^11.5.2",
"parse5": "^8.0.1",
"saxes": "^6.0.0",
- "symbol-tree": "^3.2.4",
"tough-cookie": "^6.0.2",
- "undici": "^8.9.0",
+ "undici": "^8.10.2",
"w3c-xmlserializer": "^5.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
- "whatwg-url": "^17.1.0",
+ "whatwg-url": "^17.1.1",
"xml-name-validator": "^5.0.0"
},
"engines": {
@@ -6199,6 +6357,37 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/msgpackr": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-2.1.0.tgz",
+ "integrity": "sha512-p/pBCVO63CsvvpkomUnNNag6+n38rULuDA6HHe70o2gtC8ODI52foF/4ko2qQcp6OiErJXTmrZeXmsGGHsIQNQ==",
+ "license": "MIT",
+ "optionalDependencies": {
+ "msgpackr-extract": "^3.0.4"
+ }
+ },
+ "node_modules/msgpackr-extract": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.4.tgz",
+ "integrity": "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-gyp-build-optional-packages": "5.2.2"
+ },
+ "bin": {
+ "download-msgpackr-prebuilds": "bin/download-prebuilds.js"
+ },
+ "optionalDependencies": {
+ "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4",
+ "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4",
+ "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4",
+ "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4",
+ "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4",
+ "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4"
+ }
+ },
"node_modules/mute-stream": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz",
@@ -6225,6 +6414,21 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/node-gyp-build-optional-packages": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
+ "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "detect-libc": "^2.0.1"
+ },
+ "bin": {
+ "node-gyp-build-optional-packages": "bin.js",
+ "node-gyp-build-optional-packages-optional": "optional.js",
+ "node-gyp-build-optional-packages-test": "build-test.js"
+ }
+ },
"node_modules/node-releases": {
"version": "2.0.54",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.54.tgz",
@@ -6562,6 +6766,22 @@
"node": ">=6"
}
},
+ "node_modules/pure-rand": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",
+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/qs": {
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
@@ -6950,13 +7170,6 @@
"integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==",
"license": "MIT"
},
- "node_modules/symbol-tree": {
- "version": "3.2.4",
- "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
- "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/tailwindcss": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz",
@@ -7791,9 +8004,9 @@
}
},
"node_modules/whatwg-url": {
- "version": "17.1.0",
- "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.0.tgz",
- "integrity": "sha512-3GeworPmc2ZfEEHP7lEbUfBX/L75wdEsi0rLNhXcXxnoN5jyq0SL5gCy06SGW2cyTIZdTvWIDQNQoza++vKeaw==",
+ "version": "17.1.1",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.1.tgz",
+ "integrity": "sha512-ohjk1mdUebJVadRt3bAhQhx8lSnISq+GDttK79LFl8EHQkAPvzwctoasC4hs8tBt6kLAncBWWyq1N52qEfKvDw==",
"dev": true,
"license": "MIT",
"dependencies": {
diff --git a/package.json b/package.json
index 08686869..b626a005 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "varro",
"displayName": "Varro: OpenCode Workbench",
- "version": "0.28.26",
+ "version": "0.29.0",
"description": "OpenCode agent workbench with project-aware chat, parallel sessions, plan and change review, model and permission controls, commit messages, and usage insights.",
"categories": [
"AI",
@@ -49,6 +49,8 @@
"test:scripts": "node --test scripts/*.test.mjs",
"test:scripts:browser": "node --test scripts/browser/*.test.mjs",
"test:compatibility": "node scripts/opencode-compatibility/run.mjs --check-floor --report artifacts/opencode-compatibility.json --summary scripts/opencode-compatibility/verified.json",
+ "test:compatibility:adapters": "node scripts/opencode-compatibility/run-adapters.mjs",
+ "test:compatibility:ui": "npm run build && node scripts/opencode-compatibility/run-ui.mjs",
"compatibility:discover": "node scripts/opencode-compatibility/run.mjs --report artifacts/opencode-compatibility.json",
"pretest:e2e": "playwright install chromium",
"test:e2e": "playwright test",
@@ -69,6 +71,7 @@
},
"dependencies": {
"@opencode-ai/sdk": "^1.18.31",
+ "@opencode/client": "^2.0.7",
"cross-spawn": "7.0.6",
"dompurify": "3.4.15",
"highlight.js": "11.12.0",
@@ -88,7 +91,7 @@
"css.escape": "1.5.1",
"esbuild": "0.28.2",
"iconoir": "7.12.1",
- "jsdom": "30.0.1",
+ "jsdom": "30.1.0",
"material-icon-theme": "5.38.1",
"oxfmt": "0.68.0",
"oxlint": "1.83.0",
@@ -129,6 +132,10 @@
]
},
"commands": [
+ {
+ "command": "varro.session.importV1",
+ "title": "Varro: Import OpenCode v1 Session into v2"
+ },
{
"command": "varro.chat.newSession",
"title": "Varro: New Session"
@@ -388,12 +395,12 @@
"varro.server.command": {
"type": "string",
"default": "",
- "description": "Optional path to the OpenCode CLI executable Varro uses for server startup and other CLI-backed actions"
+ "description": "Optional path to the OpenCode CLI executable used for startup and CLI actions. OpenCode v2 is recommended; v1 remains supported. When empty, Varro searches for opencode2 first, then opencode. Both current CLI families use opencode. Set an explicit v1 executable path to keep using v1."
},
"varro.server.autoUpdate": {
"type": "boolean",
"default": true,
- "description": "Automatically install OpenCode CLI updates"
+ "description": "Automatically install updates within the installed OpenCode CLI family on macOS and Linux: @opencode/cli for v2, opencode-ai for v1. Does not migrate v1 to v2. Native Windows uses an update prompt."
},
"varro.chat.showFileDiffs": {
"type": "boolean",
diff --git a/scripts/ai-fuzzy-activity.test.mjs b/scripts/ai-fuzzy-activity.test.mjs
index 1eba302b..f57839b3 100644
--- a/scripts/ai-fuzzy-activity.test.mjs
+++ b/scripts/ai-fuzzy-activity.test.mjs
@@ -14,26 +14,51 @@ function harness({ stale = false, settledEarly = false, attached = false } = {})
reads++;
return [
{ info: { id: 'user', role: 'user' }, parts: [{ type: 'text', text: '[marked]' }] },
- { info: { id: 'old', role: 'assistant', parentID: 'other' }, parts: [tool('old-tool', 'completed')] },
- { info: { id: 'assistant', role: 'assistant', parentID: 'user' }, parts: [
- tool('one', stale || reads > 1 ? 'completed' : 'running'),
- tool('two', stale || reads > 1 ? 'completed' : 'pending'),
- tool('final', 'running'),
- ] },
+ {
+ info: { id: 'old', role: 'assistant', parentID: 'other' },
+ parts: [tool('old-tool', 'completed')],
+ },
+ {
+ info: { id: 'assistant', role: 'assistant', parentID: 'user' },
+ parts: [
+ tool('one', stale || reads > 1 ? 'completed' : 'running'),
+ tool('two', stale || reads > 1 ? 'completed' : 'pending'),
+ tool('final', 'running'),
+ ],
+ },
];
},
};
const cdp = {
- snapshot: async () => ({ jumpToLatest: !attached, transcript: { scrollTop: attached ? 900 : 500, scrollHeight: 1000, clientHeight: 100 } }),
- click: async (selector) => { calls.push(selector); attached = true; return true; },
- key: async (selector, key) => { calls.push(`${selector}: ${key}`); attached = true; return true; },
+ snapshot: async () => ({
+ jumpToLatest: !attached,
+ transcript: { scrollTop: attached ? 900 : 500, scrollHeight: 1000, clientHeight: 100 },
+ }),
+ click: async (selector) => {
+ calls.push(selector);
+ attached = true;
+ return true;
+ },
+ key: async (selector, key) => {
+ calls.push(`${selector}: ${key}`);
+ attached = true;
+ return true;
+ },
};
return {
calls,
options: {
- cdp, client, sessionId: 'session', marker: '[marked]', scope: { messageIds: ['assistant'] },
- timeoutMs: 30, pollIntervalMs: 0,
- runActions: async (_cdp, plan) => { calls.push(...plan.map((item) => item.action)); return plan.map((item) => ({ ...item, executed: true })); },
+ cdp,
+ client,
+ sessionId: 'session',
+ marker: '[marked]',
+ scope: { messageIds: ['assistant'] },
+ timeoutMs: 30,
+ pollIntervalMs: 0,
+ runActions: async (_cdp, plan) => {
+ calls.push(...plan.map((item) => item.action));
+ return plan.map((item) => ({ ...item, executed: true }));
+ },
},
};
}
@@ -42,7 +67,11 @@ test('AI07 executes disclosure, outer wheel, two detached completions, and live
const { options, calls } = harness();
const result = await executeActivityScenario(options);
assert.equal(result.executed, true);
- assert.deepEqual(calls, ['expand disclosure', 'wheel transcript', '[aria-label="Scroll to latest message"]']);
+ assert.deepEqual(calls, [
+ 'expand disclosure',
+ 'wheel transcript',
+ '[aria-label="Scroll to latest message"]',
+ ]);
assert.deepEqual(result.completedWhileDetached, ['one', 'two']);
assert.deepEqual(result.runningAtReturn, ['final']);
assert.equal(result.visualVerification, 'NEEDS_AI_REVIEW');
@@ -77,7 +106,10 @@ test('AI07 keeps the recorded 238px detachment after the jump button hides and r
},
});
const key = options.cdp.key;
- options.cdp.key = async (...args) => { returned = true; return key(...args); };
+ options.cdp.key = async (...args) => {
+ returned = true;
+ return key(...args);
+ };
const result = await executeActivityScenario(options);
assert.equal(result.executed, true, result.reason);
assert.deepEqual(result.completedWhileDetached, ['one', 'two']);
@@ -129,7 +161,7 @@ test('AI07 still fails when the transcript actually reaches bottom before detach
test('AI07 verifies native End reaches bottom rather than trusting dispatch', async () => {
const { options } = harness();
const snapshot = options.cdp.snapshot;
- options.cdp.snapshot = async () => ({ ...await snapshot(), jumpToLatest: false });
+ options.cdp.snapshot = async () => ({ ...(await snapshot()), jumpToLatest: false });
options.cdp.key = async () => true;
const result = await executeActivityScenario(options);
assert.equal(result.executed, false);
@@ -168,7 +200,9 @@ test('AI07 fails rather than retrying around an ended stream or failed detachmen
test('AI07 preserves action failure evidence and never proceeds to return', async () => {
const { options, calls } = harness();
- options.runActions = async () => [{ action: 'expand disclosure', executed: false, reason: 'missing target' }];
+ options.runActions = async () => [
+ { action: 'expand disclosure', executed: false, reason: 'missing target' },
+ ];
const result = await executeActivityScenario(options);
assert.equal(result.failurePhase, 'disclosure-and-wheel');
assert.equal(result.actions[0].reason, 'missing target');
@@ -178,9 +212,11 @@ test('AI07 preserves action failure evidence and never proceeds to return', asyn
test('AI07 does not count busy reasoning as a running tool at return', async () => {
const { options } = harness();
const messages = options.client.messages;
- options.client.messages = async () => (await messages()).map((entry) => ({
- ...entry, parts: entry.parts.filter((part) => part.id !== 'final'),
- }));
+ options.client.messages = async () =>
+ (await messages()).map((entry) => ({
+ ...entry,
+ parts: entry.parts.filter((part) => part.id !== 'final'),
+ }));
const result = await executeActivityScenario(options);
assert.equal(result.executed, false);
assert.equal(result.failurePhase, 'return-while-tool-active');
@@ -197,6 +233,54 @@ test('AI07 rejects tools completing during the native return action', async () =
assert.equal(result.executed, false);
assert.equal(result.failurePhase, 'return-while-tool-active');
assert.equal(result.actions.at(-1).executed, false);
+ assert.equal(result.actions.at(-1).reachedBottom, true);
+ assert.equal(result.actions.at(-1).outcome, 'active-window-ended');
+ assert.match(result.reason, /coverage is incomplete/);
+});
+
+test('AI07 observes smooth return after a short tool finishes without awarding live coverage', async () => {
+ const { options } = harness();
+ const snapshot = options.cdp.snapshot;
+ let returningSamples = 0;
+ options.cdp.snapshot = async () => {
+ const state = await snapshot();
+ if (!state.jumpToLatest) {
+ returningSamples++;
+ state.transcript.scrollTop = returningSamples < 3 ? 600 + returningSamples * 50 : 900;
+ }
+ return state;
+ };
+ const messages = options.client.messages;
+ options.client.messages = async () => {
+ const entries = await messages();
+ if (returningSamples > 0) {
+ for (const entry of entries) {
+ for (const part of entry.parts) if (part.type === 'tool') part.state.status = 'completed';
+ }
+ }
+ return entries;
+ };
+ const result = await executeActivityScenario(options);
+ assert.equal(result.executed, false);
+ assert.equal(returningSamples, 3);
+ const action = result.actions.at(-1);
+ assert.equal(action.outcome, 'active-window-ended');
+ assert.equal(action.reachedBottom, true);
+ assert.ok(action.activeWindowEnded.snapshot.transcript.scrollTop < 900);
+ assert.equal(action.after.snapshot.transcript.scrollTop, 900);
+});
+
+test('AI07 still reports a stuck return when the tool ends and the viewport never reaches bottom', async () => {
+ const { options } = harness();
+ options.cdp.click = async () => {
+ options.client.isBusy = async () => false;
+ return true;
+ };
+ const result = await executeActivityScenario(options);
+ assert.equal(result.executed, false);
+ assert.equal(result.actions.at(-1).outcome, 'bottom-not-reached');
+ assert.equal(result.actions.at(-1).reachedBottom, false);
+ assert.match(result.reason, /scenario deadline/);
});
test('shipped AI07 controller installs telemetry before prompting and records execution separately', async () => {
@@ -208,5 +292,8 @@ test('shipped AI07 controller installs telemetry before prompting and records ex
assert.ok(observer > 0 && prompt > observer && execute > prompt);
assert.match(controller, /preparation: \{ passed: best\?\.missing.length === 0 \}/);
assert.match(controller, /scenarioVerification: 'NEEDS_AI_REVIEW'/);
- assert.match(controller, /activityObservation = await cdp.evaluate\('globalThis.varroAiStreamingObserver.stop\(\)'\)/);
+ assert.match(
+ controller,
+ /activityObservation = await cdp.evaluate\('globalThis.varroAiStreamingObserver.stop\(\)'\)/
+ );
});
diff --git a/scripts/ai-fuzzy-live.mjs b/scripts/ai-fuzzy-live.mjs
index 9cc30f36..883f850e 100644
--- a/scripts/ai-fuzzy-live.mjs
+++ b/scripts/ai-fuzzy-live.mjs
@@ -59,9 +59,7 @@ export function modelDisplayName(value) {
.map((part) => (part ? `${part[0].toUpperCase()}${part.slice(1)}` : part))
.join(' ')}`.trim();
}
- return parts
- .map((part) => (part ? `${part[0].toUpperCase()}${part.slice(1)}` : part))
- .join(' ');
+ return parts.map((part) => (part ? `${part[0].toUpperCase()}${part.slice(1)}` : part)).join(' ');
}
export function validateLiveModel(value) {
@@ -150,7 +148,13 @@ export function recordLivePreparationResult(manifest, scenario, result) {
return record;
}
-export function buildLivePrompt({ seed, scenario = 'AI-07', promptRun = 1, attempt, missing = [] }) {
+export function buildLivePrompt({
+ seed,
+ scenario = 'AI-07',
+ promptRun = 1,
+ attempt,
+ missing = [],
+}) {
const marker = `[VFZ:${seed}:${scenario}:R${String(promptRun)}:TOOLS-A${String(attempt)}]`;
const missingEmphasis =
missing.length === 0
@@ -191,9 +195,12 @@ export function duplicateDeliveryFailures(observation, sawBusy) {
if (!sawBusy) failures.push('active model stream was not observed');
if (!observation?.userSeen) failures.push('sent user prompt was not observed');
if (!observation?.assistantSeen) failures.push('assistant stream was not observed');
- if (!observation?.tokenSeen?.every(Boolean)) failures.push('not every required stream token was observed');
- if ((observation?.maxUserRows ?? 0) > 1) failures.push('sent user prompt rendered more than once');
- if ((observation?.maxAssistantRows ?? 0) > 1) failures.push('assistant response rendered in multiple rows');
+ if (!observation?.tokenSeen?.every(Boolean))
+ failures.push('not every required stream token was observed');
+ if ((observation?.maxUserRows ?? 0) > 1)
+ failures.push('sent user prompt rendered more than once');
+ if ((observation?.maxAssistantRows ?? 0) > 1)
+ failures.push('assistant response rendered in multiple rows');
if ((observation?.maxRawAssistantRows ?? 0) > 1) {
failures.push('assistant response occupied multiple raw rows');
}
@@ -279,8 +286,7 @@ export function promptModelFailures(messages, markers, requestedModel) {
const assistants =
users.length === 1
? messages.filter(
- (entry) =>
- entry?.info?.role === 'assistant' && entry.info.parentID === users[0].info.id
+ (entry) => entry?.info?.role === 'assistant' && entry.info.parentID === users[0].info.id
)
: [];
const observed = assistants.map((entry) => ({
@@ -292,8 +298,7 @@ export function promptModelFailures(messages, markers, requestedModel) {
if (
observed.length === 0 ||
observed.some(
- (entry) =>
- entry.providerID !== requested.providerID || entry.modelID !== requested.modelID
+ (entry) => entry.providerID !== requested.providerID || entry.modelID !== requested.modelID
)
) {
failures.push(`assistant model for ${marker} was not ${requestedModel}`);
@@ -399,7 +404,8 @@ class OpenCodeClient {
if (body !== undefined) init.body = JSON.stringify(body);
const response = await fetch(url, { ...init, redirect: 'error' });
const text = await response.text();
- if (!response.ok) throw new Error(`${method} ${route} failed (${String(response.status)}): ${text}`);
+ if (!response.ok)
+ throw new Error(`${method} ${route} failed (${String(response.status)}): ${text}`);
return text ? JSON.parse(text) : null;
}
@@ -478,7 +484,9 @@ export function selectVarroTargetDescriptor(descriptors, requested) {
.filter(Boolean)
.join(', ');
if (matching.length === 0) {
- throw new Error(`No Varro iframe matched ${wanted || 'the requested target'}; inspected: ${inspected}`);
+ throw new Error(
+ `No Varro iframe matched ${wanted || 'the requested target'}; inspected: ${inspected}`
+ );
}
throw new Error(
`Varro iframe target is ambiguous for ${wanted || 'the requested target'}; matches: ${matching.map(describeTarget).join(', ')}`
@@ -512,8 +520,7 @@ async function inspectVarroTarget(port, target) {
await controller.call('Runtime.enable');
socket.removeEventListener('message', contextListener);
const mainContext = contexts.find(
- (context) =>
- context.auxData?.frameId === frameId && context.auxData?.isDefault === true
+ (context) => context.auxData?.frameId === frameId && context.auxData?.isDefault === true
);
if (!mainContext) throw new Error('default content execution context is unavailable');
controller.mainContextId = mainContext.id;
@@ -691,7 +698,9 @@ export class CdpController {
result = await this.evaluateInCurrentContext(expression);
}
if (result.exceptionDetails) {
- throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);
+ throw new Error(
+ result.exceptionDetails.exception?.description ?? result.exceptionDetails.text
+ );
}
return result.result.value;
}
@@ -1257,9 +1266,15 @@ export class CdpController {
const normalized = shifted ? ' ' : key === 'Space' ? ' ' : key;
const code = shifted || key === 'Space' ? 'Space' : key;
const virtualKeyCode = {
- Enter: 13, Tab: 9, ' ': 32,
- PageUp: 33, PageDown: 34, End: 35, Home: 36,
- ArrowUp: 38, ArrowDown: 40,
+ Enter: 13,
+ Tab: 9,
+ ' ': 32,
+ PageUp: 33,
+ PageDown: 34,
+ End: 35,
+ Home: 36,
+ ArrowUp: 38,
+ ArrowDown: 40,
}[normalized];
for (const type of ['keyDown', 'keyUp']) {
const event = {
@@ -1311,7 +1326,8 @@ export class CdpController {
throw new Error('The current composer model control is unavailable');
}
await new Promise((resolve) => setTimeout(resolve, 300));
- if (!(await this.clickText(name))) throw new Error(`Model ${name} is not visible in the picker`);
+ if (!(await this.clickText(name)))
+ throw new Error(`Model ${name} is not visible in the picker`);
await new Promise((resolve) => setTimeout(resolve, 300));
const selected = await this.evaluate(`(() => {
const button = [...document.querySelectorAll('button')].find((candidate) =>
@@ -1334,7 +1350,9 @@ export class CdpController {
} : null;
})()`);
if (current?.providerID === providerID && current?.modelID === modelID) return current;
- const modelButton = await this.evaluate(`document.querySelector('.model-picker-btn')?.getAttribute('aria-label') ?? null`);
+ const modelButton = await this.evaluate(
+ `document.querySelector('.model-picker-btn')?.getAttribute('aria-label') ?? null`
+ );
if (!modelButton || !(await this.click('.model-picker-btn'))) {
throw new Error('The current composer model control is unavailable');
}
@@ -1372,7 +1390,8 @@ export class CdpController {
const selected = await this.evaluate(
`document.querySelector('.permission-mode-button')?.getAttribute('data-permission-mode') ?? null`
);
- if (selected !== mode) throw new Error(`Permission mode selection remained ${String(selected)}`);
+ if (selected !== mode)
+ throw new Error(`Permission mode selection remained ${String(selected)}`);
return selected;
}
@@ -1943,10 +1962,7 @@ function transcriptMovementDirection(before, after, messageOrder = []) {
if (Math.abs(delta) > 1.5) return Math.sign(delta);
}
if (hasSharedPaintedRow) return 0;
- if (
- before.transcript.sessionId &&
- before.transcript.sessionId === after.transcript.sessionId
- ) {
+ if (before.transcript.sessionId && before.transcript.sessionId === after.transcript.sessionId) {
const beforeId = before.transcript.visibleRows?.[0]?.messageId;
const afterId = after.transcript.visibleRows?.[0]?.messageId;
const directions = [
@@ -1981,7 +1997,8 @@ function transcriptMovementDirection(before, after, messageOrder = []) {
function expectedTranscriptDirection(action) {
if (action.action === 'wheel transcript') return Math.sign(action.delta ?? 0) || null;
- if (!(action.action.endsWith('on transcript') || action.action === 'key on transcript')) return null;
+ if (!(action.action.endsWith('on transcript') || action.action === 'key on transcript'))
+ return null;
const key = action.key ?? action.action.split(' ')[0];
if (['ArrowDown', 'PageDown', 'Space', 'End'].includes(key)) return 1;
if (['ArrowUp', 'PageUp', 'Shift+Space', 'Home'].includes(key)) return -1;
@@ -2073,7 +2090,11 @@ export function verifyActionEffect(action, before, after, details = {}) {
return { verified: false, reason: 'transcript moved opposite the requested direction' };
}
if (expectedDirection !== null && details.settledAfter) {
- const settledDirection = transcriptMovementDirection(after, details.settledAfter, details.messageOrder);
+ const settledDirection = transcriptMovementDirection(
+ after,
+ details.settledAfter,
+ details.messageOrder
+ );
if (settledDirection === null) {
return {
verified: false,
@@ -2108,10 +2129,7 @@ export async function executeActionPlan(cdp, plan, currentTitle, port, options =
details.handoff = await nestedHandoff(cdp, options.marker, options.scope);
dispatched = !!details.handoff.before;
} else if (action.action.endsWith('on transcript') || action.action === 'key on transcript') {
- dispatched = await cdp.key(
- '.interactive-list',
- action.key ?? action.action.split(' ')[0]
- );
+ dispatched = await cdp.key('.interactive-list', action.key ?? action.action.split(' ')[0]);
} else if (action.action.endsWith('in composer')) {
dispatched = await cdp.key(
'[aria-label="Message composer"]',
@@ -2128,7 +2146,9 @@ export async function executeActionPlan(cdp, plan, currentTitle, port, options =
const current = attempt === 0 ? before : await cdp.captureActionState(options.scope);
const target = current.disclosures
?.filter((entry) => entry.key && !tried.has(entry.key) && entry.expanded !== expected)
- .toSorted((left, right) => Number(right.visible === true) - Number(left.visible === true))[0];
+ .toSorted(
+ (left, right) => Number(right.visible === true) - Number(left.visible === true)
+ )[0];
if (!target) break;
tried.add(target.key);
const selector = `.assistant-activity-summary[data-activity-summary-group-key=${JSON.stringify(target.key)}]`;
@@ -2142,7 +2162,8 @@ export async function executeActionPlan(cdp, plan, currentTitle, port, options =
}
} else if (action.action === 'open file card and diff') {
for (let attempt = 0; attempt < 3; attempt += 1) {
- dispatched = (await cdp.click('[aria-label^="Expand changes in"]', options.scope)) || dispatched;
+ dispatched =
+ (await cdp.click('[aria-label^="Expand changes in"]', options.scope)) || dispatched;
if (!dispatched) break;
await new Promise((resolve) => setTimeout(resolve, 100));
const state = await cdp.captureActionState(options.scope);
@@ -2295,12 +2316,9 @@ export function multiWebviewScenarioFailures(evidence) {
.map((sample) => sample.phase) ?? []
);
if (
- ![
- 'sidebar-source',
- 'editor-root',
- 'editor-root-return',
- 'editor-reload',
- ].every((phase) => synchronizedPhases.has(phase))
+ !['sidebar-source', 'editor-root', 'editor-root-return', 'editor-reload'].every((phase) =>
+ synchronizedPhases.has(phase)
+ )
) {
failures.push('model and permission mode were not synchronized across views');
}
@@ -2364,7 +2382,8 @@ export function multiWebviewScenarioFailures(evidence) {
failures.push('cross-session content leakage was observed');
}
if (evidence?.counts?.accurate !== true) failures.push('queue counts were not accurate');
- if (evidence?.focus?.usable !== true) failures.push('composer focus was not usable after handoff');
+ if (evidence?.focus?.usable !== true)
+ failures.push('composer focus was not usable after handoff');
if ((evidence?.unexpectedDescendants?.length ?? 0) > 0) {
failures.push('the bounded stream created uninventoryed descendants');
}
@@ -2383,8 +2402,7 @@ export function summarizeQueuedDelivery(messages, turns) {
const assistantEntries = userEntries.map((entries) =>
entries.length === 1
? messages.filter(
- (entry) =>
- entry?.info?.role === 'assistant' && entry.info.parentID === entries[0].info.id
+ (entry) => entry?.info?.role === 'assistant' && entry.info.parentID === entries[0].info.id
)
: []
);
@@ -2927,7 +2945,9 @@ async function runMultiWebviewScenario({
evidence.editor.rootTitleRouted =
openedRoot.title === tracked.title && openedRoot.routeSessionId === tracked.id;
if (!(await restoreSidebarSessionFromPicker(sidebar, tracked.id, tracked.title))) {
- throw new Error('AI-18 could not restore the root session in the sidebar after opening the editor');
+ throw new Error(
+ 'AI-18 could not restore the root session in the sidebar after opening the editor'
+ );
}
await sampleConfiguration(editor, 'editor-root');
await enqueueTurn(editor, editorViewId, queueTurns[1], 'editor-enqueue');
@@ -3519,8 +3539,7 @@ async function runLifecycleScenario({
composerText: await editor.readComposerText(),
row: await editor.readQueueRow(queued.item.id),
}),
- (sample) =>
- sample?.row === null && !sample.composerText.includes(queueTurn.promptMarker)
+ (sample) => sample?.row === null && !sample.composerText.includes(queueTurn.promptMarker)
);
evidence.editor.revealed = visible === true && restored.routeSessionId === tracked.id;
evidence.editor.sameViewId = editor.targetContext?.viewId === editorViewId;
@@ -3583,56 +3602,90 @@ async function runLifecycleScenario({
}
export async function executeActivityScenario({
- cdp, client, sessionId, marker, scope, timeoutMs,
- pollIntervalMs = 50, runActions = executeActionPlan,
+ cdp,
+ client,
+ sessionId,
+ marker,
+ scope,
+ timeoutMs,
+ pollIntervalMs = 50,
+ runActions = executeActionPlan,
}) {
const deadline = Date.now() + timeoutMs;
const evidence = {
- executed: false, actions: [], observations: [], completedWhileDetached: [],
- runningAtReturn: [], visualVerification: 'NEEDS_AI_REVIEW',
+ executed: false,
+ actions: [],
+ observations: [],
+ completedWhileDetached: [],
+ runningAtReturn: [],
+ visualVerification: 'NEEDS_AI_REVIEW',
};
let phase = 'disclosure-and-wheel';
const read = async () => {
const [messages, snapshot, busy] = await Promise.all([
- client.messages(sessionId), cdp.snapshot(marker), client.isBusy(sessionId),
+ client.messages(sessionId),
+ cdp.snapshot(marker),
+ client.isBusy(sessionId),
]);
- const users = messages.filter((entry) => entry.info.role === 'user' &&
- entry.parts?.some((part) => part.type === 'text' && part.text?.includes(marker)));
- if (users.length !== 1) throw new Error('Marked prompt did not resolve to exactly one canonical user');
- const tools = messages.filter((entry) => entry.info.role === 'assistant' &&
- entry.info.parentID === users[0].info.id).flatMap((entry) => entry.parts ?? [])
+ const users = messages.filter(
+ (entry) =>
+ entry.info.role === 'user' &&
+ entry.parts?.some((part) => part.type === 'text' && part.text?.includes(marker))
+ );
+ if (users.length !== 1)
+ throw new Error('Marked prompt did not resolve to exactly one canonical user');
+ const tools = messages
+ .filter(
+ (entry) => entry.info.role === 'assistant' && entry.info.parentID === users[0].info.id
+ )
+ .flatMap((entry) => entry.parts ?? [])
.filter((part) => part.type === 'tool')
.map((part) => ({ id: part.id, status: part.state?.status }));
const transcript = snapshot.transcript;
// The native upward wheel establishes detachment. The jump button has its own
// visibility threshold, so it can disappear while the viewport stays detached.
- const detached = !!transcript &&
- transcript.scrollHeight - transcript.clientHeight - transcript.scrollTop > 2;
+ const detached =
+ !!transcript && transcript.scrollHeight - transcript.clientHeight - transcript.scrollTop > 2;
const sample = { at: Date.now(), busy, detached, tools, snapshot };
evidence.observations.push(sample);
return sample;
};
try {
if (!scope?.messageIds?.length) throw new Error('Marked activity scope is unavailable');
- evidence.actions = await runActions(cdp, [
- { step: 1, action: 'expand disclosure' },
- { step: 2, action: 'wheel transcript', delta: -96 },
- ], '', null, { scope, marker, sessionId, isActive: () => client.isBusy(sessionId) });
+ evidence.actions = await runActions(
+ cdp,
+ [
+ { step: 1, action: 'expand disclosure' },
+ { step: 2, action: 'wheel transcript', delta: -96 },
+ ],
+ '',
+ null,
+ { scope, marker, sessionId, isActive: () => client.isBusy(sessionId) }
+ );
if (evidence.actions.length !== 2 || evidence.actions.some((action) => !action.executed)) {
throw new Error('Required disclosure or outer wheel action failed');
}
phase = 'detached-completions';
const baseline = await read();
- if (!baseline.detached || !baseline.busy) throw new Error('Live detachment was not established');
+ if (!baseline.detached || !baseline.busy)
+ throw new Error('Live detachment was not established');
// Only tools observed unfinished after detachment can count as detached completions.
- const unfinished = new Set(baseline.tools.filter((tool) => ['pending', 'running'].includes(tool.status)).map((tool) => tool.id));
+ const unfinished = new Set(
+ baseline.tools
+ .filter((tool) => ['pending', 'running'].includes(tool.status))
+ .map((tool) => tool.id)
+ );
let sample = baseline;
while (Date.now() < deadline) {
sample = await read();
if (!sample.detached) throw new Error('Transcript reattached before two tool completions');
for (const tool of sample.tools) {
if (['pending', 'running'].includes(tool.status)) unfinished.add(tool.id);
- if (tool.status === 'completed' && unfinished.has(tool.id) && !evidence.completedWhileDetached.includes(tool.id)) {
+ if (
+ tool.status === 'completed' &&
+ unfinished.has(tool.id) &&
+ !evidence.completedWhileDetached.includes(tool.id)
+ ) {
evidence.completedWhileDetached.push(tool.id);
}
}
@@ -3640,17 +3693,27 @@ export async function executeActivityScenario({
if (!sample.busy) throw new Error('Stream settled before two detached tool completions');
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
- if (evidence.completedWhileDetached.length < 2) throw new Error('Timed out waiting for two detached tool completions');
+ if (evidence.completedWhileDetached.length < 2)
+ throw new Error('Timed out waiting for two detached tool completions');
phase = 'return-while-tool-active';
- while (sample.busy && !sample.tools.some((tool) => tool.status === 'running') && Date.now() < deadline) {
+ while (
+ sample.busy &&
+ !sample.tools.some((tool) => tool.status === 'running') &&
+ Date.now() < deadline
+ ) {
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
sample = await read();
if (!sample.detached) throw new Error('Transcript reattached before the return action');
}
- if (!sample.busy || !sample.tools.some((tool) => tool.status === 'running')) throw new Error('No running tool remained for return to bottom');
+ if (!sample.busy || !sample.tools.some((tool) => tool.status === 'running'))
+ throw new Error('No running tool remained for return to bottom');
const returnAction = {
- step: 3, action: 'return while tool active', inputs: [],
- dispatched: false, executed: false, before: sample,
+ step: 3,
+ action: 'return while tool active',
+ inputs: [],
+ dispatched: false,
+ executed: false,
+ before: sample,
};
evidence.actions.push(returnAction);
let dispatched = false;
@@ -3665,19 +3728,50 @@ export async function executeActivityScenario({
returnAction.dispatched = dispatched;
if (!dispatched) throw new Error('Native return-to-bottom control was unavailable');
let after = await read();
- while (after.busy && after.snapshot.transcript &&
- after.snapshot.transcript.scrollHeight - after.snapshot.transcript.clientHeight - after.snapshot.transcript.scrollTop > 2 &&
- Date.now() < deadline &&
- after.tools.some((tool) => tool.status === 'running')) {
+ let activeWindowEnded = null;
+ const recordActiveWindow = () => {
+ if (
+ !activeWindowEnded &&
+ (!after.busy || !after.tools.some((tool) => tool.status === 'running'))
+ ) {
+ activeWindowEnded = after;
+ }
+ };
+ recordActiveWindow();
+ // Tool duration is not a scroll deadline. Keep observing the native return so
+ // a short tool window cannot be reported as a stuck viewport.
+ while (
+ after.snapshot.transcript &&
+ after.snapshot.transcript.scrollHeight -
+ after.snapshot.transcript.clientHeight -
+ after.snapshot.transcript.scrollTop >
+ 2 &&
+ Date.now() < deadline
+ ) {
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
after = await read();
+ recordActiveWindow();
}
- evidence.runningAtReturn = after.tools.filter((tool) => tool.status === 'running').map((tool) => tool.id);
+ evidence.runningAtReturn = after.tools
+ .filter((tool) => tool.status === 'running')
+ .map((tool) => tool.id);
const transcript = after.snapshot.transcript;
- const executed = dispatched && after.busy && evidence.runningAtReturn.length > 0 &&
+ const reachedBottom =
!!transcript && transcript.scrollHeight - transcript.clientHeight - transcript.scrollTop <= 2;
- Object.assign(returnAction, { executed, after });
- if (!executed) throw new Error('Return did not reach bottom while a tool was still running');
+ const executed = reachedBottom && !activeWindowEnded;
+ const outcome = !reachedBottom
+ ? 'bottom-not-reached'
+ : activeWindowEnded
+ ? 'active-window-ended'
+ : 'reached-while-active';
+ Object.assign(returnAction, { executed, reachedBottom, outcome, activeWindowEnded, after });
+ if (!executed) {
+ throw new Error(
+ reachedBottom
+ ? 'Return reached bottom after the running-tool window ended; active-stream coverage is incomplete'
+ : 'Return did not reach measured bottom before the scenario deadline'
+ );
+ }
evidence.executed = true;
} catch (error) {
evidence.failurePhase = phase;
@@ -3782,107 +3876,361 @@ async function runLive(options) {
let activityObservationStarted = false;
try {
await (async () => {
- if (scenario === 'AI-17') {
- for (let restart = 0; restart < restartCount; restart += 1) {
- await reloadVscodeWindow(launch.remoteDebuggingPort, 20_000, cdp.targetId);
- await cdp.rebind();
+ if (scenario === 'AI-17') {
+ for (let restart = 0; restart < restartCount; restart += 1) {
+ await reloadVscodeWindow(launch.remoteDebuggingPort, 20_000, cdp.targetId);
+ await cdp.rebind();
+ }
}
- }
- if (scenario === 'AI-18') {
- await openAi18SidebarSession(
- cdp,
- tracked.id,
- tracked.title,
- launch.remoteDebuggingPort,
- manifest.runSessions.filter((session) => !session.deleted).map((session) => session.title)
- );
- } else {
- await openRunSession(cdp, tracked.id, tracked.title);
- }
- if (scenario === 'AI-08' && manifest.hostState?.fileDiffsEnabled !== true) {
- await executeVscodeCommand(launch.remoteDebuggingPort, 'Varro: Show File Diffs');
- await new Promise((resolve) => setTimeout(resolve, 300));
- manifest.hostState = {
- ...manifest.hostState,
- fileDiffsEnabled: true,
- };
- await writeJsonAtomic(manifestPath, manifest);
- }
- await cdp.click('[aria-label="Scroll to latest message"]');
- await cdp.key('.interactive-list', 'End');
- const selectedModel = await cdp.selectExactModel(requestedModel);
- const selectedPermissionMode = ['AI-07', 'AI-08'].includes(scenario)
- ? await cdp.selectPermissionMode('full')
- : null;
- const pendingInput = await waitForNoPendingInput(client, tracked.id);
- if (pendingInput.permissions.length > 0 || pendingInput.questions.length > 0) {
- throw new Error(
- `Run session has ${String(pendingInput.permissions.length)} pending permissions and ${String(pendingInput.questions.length)} pending questions`
+ if (scenario === 'AI-18') {
+ await openAi18SidebarSession(
+ cdp,
+ tracked.id,
+ tracked.title,
+ launch.remoteDebuggingPort,
+ manifest.runSessions.filter((session) => !session.deleted).map((session) => session.title)
+ );
+ } else {
+ await openRunSession(cdp, tracked.id, tracked.title);
+ }
+ if (scenario === 'AI-08' && manifest.hostState?.fileDiffsEnabled !== true) {
+ await executeVscodeCommand(launch.remoteDebuggingPort, 'Varro: Show File Diffs');
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ manifest.hostState = {
+ ...manifest.hostState,
+ fileDiffsEnabled: true,
+ };
+ await writeJsonAtomic(manifestPath, manifest);
+ }
+ await cdp.click('[aria-label="Scroll to latest message"]');
+ await cdp.key('.interactive-list', 'End');
+ const selectedModel = await cdp.selectExactModel(requestedModel);
+ const selectedPermissionMode = ['AI-07', 'AI-08'].includes(scenario)
+ ? await cdp.selectPermissionMode('full')
+ : null;
+ const pendingInput = await waitForNoPendingInput(client, tracked.id);
+ if (pendingInput.permissions.length > 0 || pendingInput.questions.length > 0) {
+ throw new Error(
+ `Run session has ${String(pendingInput.permissions.length)} pending permissions and ${String(pendingInput.questions.length)} pending questions`
+ );
+ }
+ const sessionsBefore = await client.listSessions();
+ descendantsBefore = new Set(
+ findSessionDescendants(sessionsBefore, tracked.id).map((session) => session.id)
);
- }
- const sessionsBefore = await client.listSessions();
- descendantsBefore = new Set(
- findSessionDescendants(sessionsBefore, tracked.id).map((session) => session.id)
- );
- if (playbackLabel) {
- const [session, initialMessages] = await Promise.all([
- client.getSession(tracked.id),
- client.messages(tracked.id, 1000),
- ]);
- playbackSource = { session, initialMessages };
- await cdp.startSessionEventCapture();
- }
- if (scenario === 'AI-17') {
- const tokens = [
- ...Array.from({ length: 20 }, (_, index) =>
- `VFZ-DUP-${String(index + 1).padStart(2, '0')}`
- ),
- 'VFZ-DUP-END',
- ];
- const marker = `[VFZ:${manifest.seed}:AI-17:R${String(promptRun)}:DUP]`;
- const prompt = buildDuplicateDeliveryPrompt(manifest.seed, tokens, promptRun);
- await cdp.startDuplicateDeliveryObservation(marker, tokens);
- modelMayEdit = true;
- const sent = await cdp.sendComposerPrompt(prompt);
- const disposition = sent
- ? await waitForPromptDisposition(client, cdp, tracked.id, marker)
- : { status: 'unobserved', userIds: [], queuedItemIds: [] };
- const sawBusy =
- disposition.status === 'admitted' &&
- (await waitForBusy(client, tracked.id, Math.min(timeoutMs, 15_000)));
- const settled = sawBusy ? await waitForIdle(client, tracked.id, timeoutMs) : false;
- await new Promise((resolve) => setTimeout(resolve, 500));
- const observation = await cdp.finishDuplicateDeliveryObservation();
- let canonicalDelivery;
- try {
- canonicalDelivery = summarizeCanonicalDelivery(
- await client.messages(tracked.id),
- marker,
- tokens
+ if (playbackLabel) {
+ const [session, initialMessages] = await Promise.all([
+ client.getSession(tracked.id),
+ client.messages(tracked.id, 1000),
+ ]);
+ playbackSource = { session, initialMessages };
+ await cdp.startSessionEventCapture();
+ }
+ if (scenario === 'AI-17') {
+ const tokens = [
+ ...Array.from(
+ { length: 20 },
+ (_, index) => `VFZ-DUP-${String(index + 1).padStart(2, '0')}`
+ ),
+ 'VFZ-DUP-END',
+ ];
+ const marker = `[VFZ:${manifest.seed}:AI-17:R${String(promptRun)}:DUP]`;
+ const prompt = buildDuplicateDeliveryPrompt(manifest.seed, tokens, promptRun);
+ await cdp.startDuplicateDeliveryObservation(marker, tokens);
+ modelMayEdit = true;
+ const sent = await cdp.sendComposerPrompt(prompt);
+ const disposition = sent
+ ? await waitForPromptDisposition(client, cdp, tracked.id, marker)
+ : { status: 'unobserved', userIds: [], queuedItemIds: [] };
+ const sawBusy =
+ disposition.status === 'admitted' &&
+ (await waitForBusy(client, tracked.id, Math.min(timeoutMs, 15_000)));
+ const settled = sawBusy ? await waitForIdle(client, tracked.id, timeoutMs) : false;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ const observation = await cdp.finishDuplicateDeliveryObservation();
+ let canonicalDelivery;
+ try {
+ canonicalDelivery = summarizeCanonicalDelivery(
+ await client.messages(tracked.id),
+ marker,
+ tokens
+ );
+ } catch (error) {
+ canonicalDelivery = {
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ const failures = !sent
+ ? ['native composer input was unavailable']
+ : disposition.status !== 'admitted'
+ ? [`prompt submission was ${disposition.status}`]
+ : duplicateDeliveryFailures(observation, sawBusy);
+ if (!settled) failures.push('model stream did not settle');
+ if (canonicalDelivery.error) failures.push('canonical session messages could not be read');
+ else failures.push(...canonicalDeliveryFailures(canonicalDelivery));
+ const requestedModelParts = parseModel(requestedModel);
+ if (
+ canonicalDelivery.assistants?.some(
+ (assistant) =>
+ assistant.providerID !== requestedModelParts.providerID ||
+ assistant.modelID !== requestedModelParts.modelID
+ )
+ ) {
+ failures.push(`canonical assistant did not use ${requestedModel}`);
+ }
+ const descendantInventory = inventoryVerifiedDescendants(
+ manifest,
+ await client.listSessions(),
+ tracked.id,
+ descendantsBefore,
+ scenario
);
- } catch (error) {
- canonicalDelivery = {
- error: error instanceof Error ? error.message : String(error),
+ const descendantsObserved = descendantInventory.observed;
+ if (descendantsObserved.length > 0) {
+ failures.push('controlled stream created an unexpected descendant session');
+ }
+ const fixtureAfterPreparation = await fixtureStatus(manifest.workspace);
+ if (
+ fixtureAfterPreparation.status !== fixture.status ||
+ fixtureAfterPreparation.commit !== fixture.commit ||
+ fixtureAfterPreparation.contentHash !== fixture.contentHash ||
+ JSON.stringify(fixtureAfterPreparation.changedPaths) !==
+ JSON.stringify(fixture.changedPaths)
+ ) {
+ failures.push('controlled stream changed the repository fixture');
+ }
+ const result = {
+ scenario,
+ promptRun,
+ restartCount,
+ prepared: failures.length === 0,
+ prompt,
+ model: requestedModel,
+ selectedModel,
+ selectedPermissionMode,
+ target: { ...requestedTarget, boundViewId: cdp.targetContext?.viewId ?? null },
+ sent,
+ disposition,
+ sawBusy,
+ settled,
+ observation,
+ canonicalDelivery,
+ descendantsObserved,
+ failures,
+ fixtureAfterPreparation,
};
+ recordLivePreparationResult(manifest, scenario, result);
+ await writeJsonAtomic(manifestPath, manifest);
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ if (failures.length > 0) {
+ throw new Error(`AI-17 failed: ${failures.join('; ')}`);
+ }
+ return;
}
- const failures = !sent
- ? ['native composer input was unavailable']
- : disposition.status !== 'admitted'
- ? [`prompt submission was ${disposition.status}`]
- : duplicateDeliveryFailures(observation, sawBusy);
- if (!settled) failures.push('model stream did not settle');
- if (canonicalDelivery.error) failures.push('canonical session messages could not be read');
- else failures.push(...canonicalDeliveryFailures(canonicalDelivery));
- const requestedModelParts = parseModel(requestedModel);
- if (
- canonicalDelivery.assistants?.some(
- (assistant) =>
- assistant.providerID !== requestedModelParts.providerID ||
- assistant.modelID !== requestedModelParts.modelID
- )
- ) {
- failures.push(`canonical assistant did not use ${requestedModel}`);
+ if (scenario === 'AI-18') {
+ return await runMultiWebviewScenario({
+ cdp,
+ client,
+ launch,
+ manifest,
+ manifestPath,
+ options,
+ requestedModel,
+ selectedModel,
+ tracked,
+ fixture,
+ descendantsBefore,
+ promptRun,
+ markModelMayEdit: () => {
+ modelMayEdit = true;
+ },
+ });
+ }
+ if (scenario === 'AI-19') {
+ return await runLifecycleScenario({
+ cdp,
+ client,
+ launch,
+ manifest,
+ manifestPath,
+ requestedModel,
+ selectedModel,
+ tracked,
+ fixture,
+ descendantsBefore,
+ promptRun,
+ timeoutMs,
+ markModelMayEdit: () => {
+ modelMayEdit = true;
+ },
+ });
+ }
+ let handoff = null;
+ let actions = [];
+ let scope = null;
+ let activityExecution = null;
+ if (scenario === 'AI-07') {
+ await cdp.evaluate(
+ `(() => { (${installObserver.toString()})(); globalThis.varroAiStreamingObserver.start(); })()`
+ );
+ activityObservationStarted = true;
+ }
+ for (let attempt = 1; attempt <= maxPrompts; attempt += 1) {
+ const idleDeadline = Date.now() + timeoutMs;
+ while (await client.isBusy(tracked.id)) {
+ if (Date.now() >= idleDeadline) {
+ throw new Error(
+ `Existing stream did not settle within ${String(timeoutMs)}ms; it was left running for controller-session safety`
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ const missing = best?.missing ?? [];
+ const prompt = buildLivePrompt({
+ seed: manifest.seed,
+ scenario,
+ promptRun,
+ attempt,
+ missing,
+ });
+ const marker = prompt.match(/^\[VFZ:[^\]]+\]/)?.[0] ?? '';
+ await cdp.wheel('.interactive-list', -96, 'right');
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ const reattached = await cdp.click('[aria-label="Scroll to latest message"]');
+ if (!reattached) await cdp.key('.interactive-list', 'End');
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ modelMayEdit = true;
+ const sent = await cdp.sendComposerPrompt(prompt);
+ if (!sent) throw new Error('Native composer input was unavailable');
+ const disposition = await waitForPromptDisposition(client, cdp, tracked.id, marker);
+ const promptSeen = disposition.status === 'admitted';
+ const gate = promptSeen
+ ? await waitForLiveGate({
+ client,
+ cdp,
+ sessionId: tracked.id,
+ scenario,
+ timeoutMs,
+ marker,
+ })
+ : {
+ snapshot: await cdp.snapshot(marker),
+ bestSnapshot: null,
+ missing: [`prompt submission was ${disposition.status}`],
+ latestMissing: [`prompt submission was ${disposition.status}`],
+ sawBusy: false,
+ observations: [],
+ };
+ if (promptSeen && !gate.sawBusy && gate.missing.length === 0) {
+ gate.missing = ['active model stream'];
+ }
+ best = gate;
+ gate.marker = marker;
+ const attemptRecord = {
+ attempt,
+ prompt,
+ promptSeen,
+ disposition,
+ sawBusy: gate.sawBusy,
+ missingAfterAttempt: gate.missing,
+ latestMissing: gate.latestMissing,
+ snapshot: gate.snapshot,
+ bestSnapshot: gate.bestSnapshot,
+ observations: gate.observations,
+ };
+ attempts.push(attemptRecord);
+ if (!promptSeen) break;
+ if (gate.missing.length > 0) continue;
+
+ scope = gate.bestSnapshot?.turnMessageIds?.length
+ ? {
+ messageIds: gate.bestSnapshot.turnMessageIds,
+ partIds: gate.bestSnapshot.turnPartIds,
+ renderKeys: gate.bestSnapshot.turnRenderKeys,
+ }
+ : null;
+ if (scenario === 'AI-07') {
+ attemptRecord.fixtureBeforeExecution = await fixtureStatus(manifest.workspace);
+ }
+ if (gate.bestSnapshot?.nestedActivityScroller?.hasRange) {
+ handoff = await nestedHandoff(cdp, gate.marker, scope);
+ if (shouldRetryNestedHandoff(handoff)) {
+ const firstAttempt = handoff;
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ const retry = await nestedHandoff(cdp, gate.marker, scope);
+ handoff = { ...retry, recoveryAttempts: [firstAttempt, retry] };
+ }
+ }
+ attemptRecord.handoff = handoff;
+ attemptRecord.actionScope = scope;
+ if (scenario === 'AI-07') {
+ if (handoff && !handoff.passed) {
+ activityExecution = {
+ executed: false,
+ actions: [],
+ failurePhase: 'nested-handoff',
+ reason: 'Nested-to-outer wheel ownership failed',
+ };
+ attemptRecord.activityExecution = activityExecution;
+ break;
+ }
+ activityExecution = await executeActivityScenario({
+ cdp,
+ client,
+ sessionId: tracked.id,
+ marker: gate.marker,
+ scope,
+ timeoutMs,
+ });
+ actions = activityExecution.actions;
+ attemptRecord.activityExecution = activityExecution;
+ break;
+ }
+
+ actions = await executeActionPlan(
+ cdp,
+ manifest.actionPlan,
+ tracked.title,
+ launch.remoteDebuggingPort,
+ {
+ isActive: () => client.isBusy(tracked.id),
+ readMessageOrder: async () =>
+ (await client.messages(tracked.id, 1000)).map((message) => message.info.id),
+ marker: gate.marker,
+ sessionId: tracked.id,
+ scope,
+ }
+ );
+ attemptRecord.actions = actions;
+ const attemptActionFailure = actions.find((action) => !action.executed);
+ if (!shouldRetryAi08WithFreshStream(attemptActionFailure, attempt, maxPrompts)) break;
}
+ const settled = await waitForIdle(client, tracked.id, timeoutMs);
+ let activityObservation = null;
+ if (activityObservationStarted) {
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ activityObservation = await cdp.evaluate('globalThis.varroAiStreamingObserver.stop()');
+ activityObservationStarted = false;
+ }
+ if (activityExecution) {
+ activityExecution.settled = settled;
+ activityExecution.finalSnapshot = await cdp.captureActionState(scope);
+ if (!settled || !activityExecution.finalSnapshot.disclosures?.length) {
+ activityExecution.executed = false;
+ activityExecution.failurePhase ??= 'settled-projection';
+ activityExecution.reason ??= 'Stream did not settle into a retained activity disclosure';
+ }
+ }
+ const fixtureAfterPreparation = await fixtureStatus(manifest.workspace);
+ const actionFailure = actions.find((action) => !action.executed);
+ const promptMarkers = attempts
+ .map((attempt) => attempt.prompt.match(/^\[VFZ:[^\]]+\]/)?.[0])
+ .filter(Boolean);
+ const modelEvidence = promptModelFailures(
+ await client.messages(tracked.id),
+ promptMarkers,
+ requestedModel
+ );
const descendantInventory = inventoryVerifiedDescendants(
manifest,
await client.listSessions(),
@@ -3891,311 +4239,83 @@ async function runLive(options) {
scenario
);
const descendantsObserved = descendantInventory.observed;
+ const failures = [...modelEvidence.failures];
if (descendantsObserved.length > 0) {
- failures.push('controlled stream created an unexpected descendant session');
- }
- const fixtureAfterPreparation = await fixtureStatus(manifest.workspace);
- if (
- fixtureAfterPreparation.status !== fixture.status ||
- fixtureAfterPreparation.commit !== fixture.commit ||
- fixtureAfterPreparation.contentHash !== fixture.contentHash ||
- JSON.stringify(fixtureAfterPreparation.changedPaths) !== JSON.stringify(fixture.changedPaths)
- ) {
- failures.push('controlled stream changed the repository fixture');
+ failures.push('bounded live scenario created an unexpected descendant session');
}
const result = {
scenario,
promptRun,
- restartCount,
- prepared: failures.length === 0,
- prompt,
+ prepared:
+ best?.missing.length === 0 &&
+ (handoff === null || handoff.passed === true) &&
+ !actionFailure &&
+ failures.length === 0,
model: requestedModel,
selectedModel,
selectedPermissionMode,
+ modelEvidence,
target: { ...requestedTarget, boundViewId: cdp.targetContext?.viewId ?? null },
- sent,
- disposition,
- sawBusy,
- settled,
- observation,
- canonicalDelivery,
+ attempts,
+ handoff,
+ actions,
+ actionScope: scope,
descendantsObserved,
failures,
+ terminalMissing: best?.missing ?? ['live gate was not sampled'],
+ actionFailure: actionFailure ?? null,
+ settled,
fixtureAfterPreparation,
};
+ if (scenario === 'AI-07') {
+ Object.assign(result, {
+ preparation: { passed: best?.missing.length === 0 },
+ activityExecution,
+ activityObservation,
+ scenarioVerification: 'NEEDS_AI_REVIEW',
+ });
+ }
recordLivePreparationResult(manifest, scenario, result);
await writeJsonAtomic(manifestPath, manifest);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
- if (failures.length > 0) {
- throw new Error(`AI-17 failed: ${failures.join('; ')}`);
- }
- return;
- }
- if (scenario === 'AI-18') {
- return await runMultiWebviewScenario({
- cdp,
- client,
- launch,
- manifest,
- manifestPath,
- options,
- requestedModel,
- selectedModel,
- tracked,
- fixture,
- descendantsBefore,
- promptRun,
- markModelMayEdit: () => {
- modelMayEdit = true;
- },
- });
- }
- if (scenario === 'AI-19') {
- return await runLifecycleScenario({
- cdp,
- client,
- launch,
- manifest,
- manifestPath,
- requestedModel,
- selectedModel,
- tracked,
- fixture,
- descendantsBefore,
- promptRun,
- timeoutMs,
- markModelMayEdit: () => {
- modelMayEdit = true;
- },
- });
- }
- let handoff = null;
- let actions = [];
- let scope = null;
- let activityExecution = null;
- if (scenario === 'AI-07') {
- await cdp.evaluate(`(() => { (${installObserver.toString()})(); globalThis.varroAiStreamingObserver.start(); })()`);
- activityObservationStarted = true;
- }
- for (let attempt = 1; attempt <= maxPrompts; attempt += 1) {
- const idleDeadline = Date.now() + timeoutMs;
- while (await client.isBusy(tracked.id)) {
- if (Date.now() >= idleDeadline) {
- throw new Error(
- `Existing stream did not settle within ${String(timeoutMs)}ms; it was left running for controller-session safety`
- );
- }
- await new Promise((resolve) => setTimeout(resolve, 500));
- }
- const missing = best?.missing ?? [];
- const prompt = buildLivePrompt({
- seed: manifest.seed,
- scenario,
- promptRun,
- attempt,
- missing,
- });
- const marker = prompt.match(/^\[VFZ:[^\]]+\]/)?.[0] ?? '';
- await cdp.wheel('.interactive-list', -96, 'right');
- await new Promise((resolve) => setTimeout(resolve, 100));
- const reattached = await cdp.click('[aria-label="Scroll to latest message"]');
- if (!reattached) await cdp.key('.interactive-list', 'End');
- await new Promise((resolve) => setTimeout(resolve, 100));
- modelMayEdit = true;
- const sent = await cdp.sendComposerPrompt(prompt);
- if (!sent) throw new Error('Native composer input was unavailable');
- const disposition = await waitForPromptDisposition(client, cdp, tracked.id, marker);
- const promptSeen = disposition.status === 'admitted';
- const gate = promptSeen
- ? await waitForLiveGate({
- client,
- cdp,
- sessionId: tracked.id,
- scenario,
- timeoutMs,
- marker,
- })
- : {
- snapshot: await cdp.snapshot(marker),
- bestSnapshot: null,
- missing: [`prompt submission was ${disposition.status}`],
- latestMissing: [`prompt submission was ${disposition.status}`],
- sawBusy: false,
- observations: [],
- };
- if (promptSeen && !gate.sawBusy && gate.missing.length === 0) {
- gate.missing = ['active model stream'];
- }
- best = gate;
- gate.marker = marker;
- const attemptRecord = {
- attempt,
- prompt,
- promptSeen,
- disposition,
- sawBusy: gate.sawBusy,
- missingAfterAttempt: gate.missing,
- latestMissing: gate.latestMissing,
- snapshot: gate.snapshot,
- bestSnapshot: gate.bestSnapshot,
- observations: gate.observations,
- };
- attempts.push(attemptRecord);
- if (!promptSeen) break;
- if (gate.missing.length > 0) continue;
-
- scope = gate.bestSnapshot?.turnMessageIds?.length
- ? {
- messageIds: gate.bestSnapshot.turnMessageIds,
- partIds: gate.bestSnapshot.turnPartIds,
- renderKeys: gate.bestSnapshot.turnRenderKeys,
- }
- : null;
- if (scenario === 'AI-07') {
- attemptRecord.fixtureBeforeExecution = await fixtureStatus(manifest.workspace);
+ if (scenario === 'AI-07' && activityExecution && !activityExecution.executed) {
+ throw new Error(
+ `AI-07 execution failed at ${activityExecution.failurePhase}: ${activityExecution.reason}`
+ );
}
- if (gate.bestSnapshot?.nestedActivityScroller?.hasRange) {
- handoff = await nestedHandoff(cdp, gate.marker, scope);
- if (shouldRetryNestedHandoff(handoff)) {
- const firstAttempt = handoff;
- await new Promise((resolve) => setTimeout(resolve, 250));
- const retry = await nestedHandoff(cdp, gate.marker, scope);
- handoff = { ...retry, recoveryAttempts: [firstAttempt, retry] };
- }
+ if (!result.prepared) {
+ const reason = actionFailure
+ ? `native action ${String(actionFailure.step)} (${actionFailure.action}) was unavailable`
+ : `missing ${result.terminalMissing.join(', ')}`;
+ throw new Error(
+ `${scenario} preparation exhausted ${String(attempts.length)}/${String(maxPrompts)} prompt attempts: ${reason}`
+ );
}
- attemptRecord.handoff = handoff;
- attemptRecord.actionScope = scope;
- if (scenario === 'AI-07') {
- if (handoff && !handoff.passed) {
- activityExecution = { executed: false, actions: [], failurePhase: 'nested-handoff', reason: 'Nested-to-outer wheel ownership failed' };
- attemptRecord.activityExecution = activityExecution;
- break;
- }
- activityExecution = await executeActivityScenario({
- cdp, client, sessionId: tracked.id, marker: gate.marker, scope, timeoutMs,
- });
- actions = activityExecution.actions;
- attemptRecord.activityExecution = activityExecution;
- break;
+ if (!settled) {
+ throw new Error(
+ `${scenario} actions ran, but the stream did not settle within ${String(timeoutMs)}ms; changed paths were recorded and the stream was left running`
+ );
}
-
- actions = await executeActionPlan(
- cdp,
- manifest.actionPlan,
- tracked.title,
- launch.remoteDebuggingPort,
- {
- isActive: () => client.isBusy(tracked.id),
- readMessageOrder: async () => (await client.messages(tracked.id, 1000)).map((message) => message.info.id),
- marker: gate.marker,
- sessionId: tracked.id,
- scope,
- }
- );
- attemptRecord.actions = actions;
- const attemptActionFailure = actions.find((action) => !action.executed);
- if (!shouldRetryAi08WithFreshStream(attemptActionFailure, attempt, maxPrompts)) break;
- }
- const settled = await waitForIdle(client, tracked.id, timeoutMs);
- let activityObservation = null;
- if (activityObservationStarted) {
- await new Promise((resolve) => setTimeout(resolve, 250));
- activityObservation = await cdp.evaluate('globalThis.varroAiStreamingObserver.stop()');
- activityObservationStarted = false;
- }
- if (activityExecution) {
- activityExecution.settled = settled;
- activityExecution.finalSnapshot = await cdp.captureActionState(scope);
- if (!settled || !activityExecution.finalSnapshot.disclosures?.length) {
- activityExecution.executed = false;
- activityExecution.failurePhase ??= 'settled-projection';
- activityExecution.reason ??= 'Stream did not settle into a retained activity disclosure';
+ if (scenario === 'AI-07' && !activityExecution?.executed) {
+ throw new Error(
+ `AI-07 execution failed at ${activityExecution?.failurePhase ?? 'preparation'}: ${activityExecution?.reason ?? 'execution was not reached'}`
+ );
}
- }
- const fixtureAfterPreparation = await fixtureStatus(manifest.workspace);
- const actionFailure = actions.find((action) => !action.executed);
- const promptMarkers = attempts.map((attempt) => attempt.prompt.match(/^\[VFZ:[^\]]+\]/)?.[0]).filter(Boolean);
- const modelEvidence = promptModelFailures(
- await client.messages(tracked.id),
- promptMarkers,
- requestedModel
- );
- const descendantInventory = inventoryVerifiedDescendants(
- manifest,
- await client.listSessions(),
- tracked.id,
- descendantsBefore,
- scenario
- );
- const descendantsObserved = descendantInventory.observed;
- const failures = [...modelEvidence.failures];
- if (descendantsObserved.length > 0) {
- failures.push('bounded live scenario created an unexpected descendant session');
- }
- const result = {
- scenario,
- promptRun,
- prepared:
- best?.missing.length === 0 &&
- (handoff === null || handoff.passed === true) &&
- !actionFailure &&
- failures.length === 0,
- model: requestedModel,
- selectedModel,
- selectedPermissionMode,
- modelEvidence,
- target: { ...requestedTarget, boundViewId: cdp.targetContext?.viewId ?? null },
- attempts,
- handoff,
- actions,
- actionScope: scope,
- descendantsObserved,
- failures,
- terminalMissing: best?.missing ?? ['live gate was not sampled'],
- actionFailure: actionFailure ?? null,
- settled,
- fixtureAfterPreparation,
- };
- if (scenario === 'AI-07') {
- Object.assign(result, {
- preparation: { passed: best?.missing.length === 0 },
- activityExecution,
- activityObservation,
- scenarioVerification: 'NEEDS_AI_REVIEW',
- });
- }
- recordLivePreparationResult(manifest, scenario, result);
- await writeJsonAtomic(manifestPath, manifest);
- process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
- if (scenario === 'AI-07' && activityExecution && !activityExecution.executed) {
- throw new Error(`AI-07 execution failed at ${activityExecution.failurePhase}: ${activityExecution.reason}`);
- }
- if (!result.prepared) {
- const reason = actionFailure
- ? `native action ${String(actionFailure.step)} (${actionFailure.action}) was unavailable`
- : `missing ${result.terminalMissing.join(', ')}`;
- throw new Error(
- `${scenario} preparation exhausted ${String(attempts.length)}/${String(maxPrompts)} prompt attempts: ${reason}`
- );
- }
- if (!settled) {
- throw new Error(
- `${scenario} actions ran, but the stream did not settle within ${String(timeoutMs)}ms; changed paths were recorded and the stream was left running`
- );
- }
- if (scenario === 'AI-07' && !activityExecution?.executed) {
- throw new Error(`AI-07 execution failed at ${activityExecution?.failurePhase ?? 'preparation'}: ${activityExecution?.reason ?? 'execution was not reached'}`);
- }
})();
} catch (error) {
controllerError = error;
}
if (activityObservationStarted) {
try {
- manifest.livePreparation[scenario].activityObservation = await cdp.evaluate('globalThis.varroAiStreamingObserver.stop()');
+ manifest.livePreparation[scenario].activityObservation = await cdp.evaluate(
+ 'globalThis.varroAiStreamingObserver.stop()'
+ );
await writeJsonAtomic(manifestPath, manifest);
} catch (error) {
- controllerError = new AggregateError([controllerError, error].filter(Boolean), 'AI-07 frame observation cleanup failed');
+ controllerError = new AggregateError(
+ [controllerError, error].filter(Boolean),
+ 'AI-07 frame observation cleanup failed'
+ );
}
}
if (playbackSource) {
@@ -4217,9 +4337,13 @@ async function runLive(options) {
process.stdout.write(`${JSON.stringify({ playback }, null, 2)}\n`);
} catch (error) {
controllerError = controllerError
- ? new AggregateError([controllerError, error], 'Live scenario and playback capture failed', {
- cause: controllerError,
- })
+ ? new AggregateError(
+ [controllerError, error],
+ 'Live scenario and playback capture failed',
+ {
+ cause: controllerError,
+ }
+ )
: error;
}
}
diff --git a/scripts/ai-streaming-selection.mjs b/scripts/ai-streaming-selection.mjs
index 79e69c09..c5f14a51 100644
--- a/scripts/ai-streaming-selection.mjs
+++ b/scripts/ai-streaming-selection.mjs
@@ -4,6 +4,7 @@ import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdir, open, realpath, writeFile } from 'node:fs/promises';
import path from 'node:path';
+import { fileURLToPath } from 'node:url';
import { DatabaseSync } from 'node:sqlite';
import {
@@ -34,7 +35,7 @@ function hasForeignSessionReference(value, sessionId) {
}
export async function readActiveSessions(
- { serverUrl, sourceDatabase, directory, pid = process.env.OPENCODE_PID },
+ { serverUrl, sourceDatabase, directory, pid = process.env.OPENCODE_PID, platform = process.platform },
execute = promisify(execFile)
) {
let explicit;
@@ -55,7 +56,14 @@ export async function readActiveSessions(
throw new Error('Active-session status requires --server-url or OPENCODE_PID');
}
const canonicalDatabase = await realpath(sourceDatabase);
- const { stdout } = await execute(
+ const windows = platform === 'win32'
+ ? JSON.parse((await execute('powershell.exe', [
+ '-NoProfile', '-NonInteractive', '-File',
+ fileURLToPath(new URL('./windows-database-ownership.ps1', import.meta.url)),
+ '-Database', canonicalDatabase,
+ ], { timeout: 30_000 })).stdout)
+ : undefined;
+ const { stdout } = windows ? { stdout: '' } : await execute(
'lsof',
explicit
? ['-nP', '-a', `-iTCP:${explicit.port || 80}`, '-sTCP:LISTEN', '-Fpn']
@@ -63,6 +71,26 @@ export async function readActiveSessions(
{ timeout: 5_000 }
);
const listeners = new Map();
+ if (windows) {
+ if (!Array.isArray(windows.listeners) || !Array.isArray(windows.databaseOwners) ||
+ windows.databaseOwners.some((owner) => !Number.isSafeInteger(owner) || owner <= 0)) {
+ throw new Error('Invalid Windows database ownership evidence');
+ }
+ for (const listener of windows.listeners) {
+ if (!Number.isSafeInteger(listener.pid) || listener.pid <= 0 ||
+ !Number.isInteger(listener.port) || listener.port < 1 || listener.port > 65535) {
+ throw new Error('Invalid Windows listener ownership evidence');
+ }
+ if (!['127.0.0.1', '::1', '0.0.0.0', '::'].includes(listener.address)) continue;
+ if (!explicit && String(listener.pid) !== String(pid)) continue;
+ const ipv6 = listener.address.includes(':');
+ const host = ipv6 ? '[::1]' : '127.0.0.1';
+ const url = new URL(`http://${host}:${listener.port}`).origin;
+ if (explicit && url !== explicit.origin) continue;
+ if (!listeners.has(url)) listeners.set(url, new Set());
+ listeners.get(url).add(String(listener.pid));
+ }
+ }
let owner;
for (const line of stdout.split('\n')) {
if (/^p\d+$/.test(line)) owner = line.slice(1);
@@ -81,7 +109,7 @@ export async function readActiveSessions(
if (owners.size !== 1) throw new Error('Ambiguous status listener ownership');
const serverPid = [...owners][0];
// lsof's path selection uses file identity, including symlink and hard-link aliases.
- const held = await execute(
+ const held = windows ? undefined : await execute(
'lsof',
['-nP', '-a', '-p', serverPid, '-Fpf', '--', canonicalDatabase],
{ timeout: 5_000 }
@@ -90,7 +118,8 @@ export async function readActiveSessions(
`Cannot verify status server PID ${serverPid} holds source database: ${error.message}`
);
});
- if (!held.stdout.split('\n').includes(`p${serverPid}`) || !/^f\d+/m.test(held.stdout))
+ if (windows ? !windows.databaseOwners.includes(Number(serverPid)) :
+ !held.stdout.split('\n').includes(`p${serverPid}`) || !/^f\d+/m.test(held.stdout))
throw new Error(`Status server PID ${serverPid} does not hold source database`);
try {
const url = new URL(value);
@@ -113,7 +142,9 @@ export async function readActiveSessions(
serverUrl: url.origin,
serverPid: Number(serverPid),
sourceDatabase: canonicalDatabase,
- association: 'lsof-listener-owner-and-open-database',
+ association: windows
+ ? 'windows-listener-owner-and-restart-manager-database'
+ : 'lsof-listener-owner-and-open-database',
checkedAt: new Date().toISOString(),
activeSessionIds: Object.keys(status).filter((id) => status[id].type !== 'idle'),
});
diff --git a/scripts/ai-streaming-selection.test.mjs b/scripts/ai-streaming-selection.test.mjs
index e74efbed..d3044e06 100644
--- a/scripts/ai-streaming-selection.test.mjs
+++ b/scripts/ai-streaming-selection.test.mjs
@@ -8,9 +8,14 @@ import test from 'node:test';
import http from 'node:http';
import { buildReplayTimeline, readPlaybackCapture } from './ai-session-playback.mjs';
-import { prepareStreamingRun, readActiveSessions } from './ai-streaming-selection.mjs';
+import { prepareStreamingRun, readActiveSessions as readPlatformActiveSessions } from './ai-streaming-selection.mjs';
import { createStreamingServer } from './ai-streaming-server.mjs';
+// Existing mocked discovery fixtures describe lsof output on every test host.
+const readActiveSessions = (options, execute) => readPlatformActiveSessions(
+ { ...options, platform: execute ? 'linux' : process.platform }, execute
+);
+
// Real listener/database ownership checks require lsof. Mocked discovery tests run everywhere.
const ownershipTest = process.platform === 'win32' ? test.skip : test;
@@ -521,6 +526,33 @@ ownershipTest(
}
);
+test('Windows status discovery requires one matching listener and database owner', async (t) => {
+ const f = await fixture(t);
+ const listener = { address: '127.0.0.1', port: Number(new URL(f.serverUrl).port), pid: 123 };
+ const options = { sourceDatabase: f.sourceDatabase, directory: '/workspace',
+ serverUrl: f.serverUrl, platform: 'win32' };
+ const evidence = { listeners: [listener], databaseOwners: [123] };
+ const execute = async (command, args) => {
+ assert.equal(command, 'powershell.exe');
+ assert.ok(args.includes('-NonInteractive'));
+ assert.equal(args.at(-1), await realpath(f.sourceDatabase));
+ return { stdout: JSON.stringify(evidence) };
+ };
+ const result = await readPlatformActiveSessions(options, execute);
+ assert.equal(result.serverPid, 123);
+ assert.equal(result.association, 'windows-listener-owner-and-restart-manager-database');
+ evidence.databaseOwners = [456];
+ await assert.rejects(readPlatformActiveSessions(options, execute), /does not hold source database/);
+ evidence.databaseOwners = [123];
+ evidence.listeners.push({ ...listener, pid: 456 });
+ await assert.rejects(readPlatformActiveSessions(options, execute), /one listener owner/);
+ evidence.listeners = [];
+ await assert.rejects(readPlatformActiveSessions(options, execute), /one listener owner/);
+ evidence.listeners = [listener];
+ evidence.databaseOwners = ['123'];
+ await assert.rejects(readPlatformActiveSessions(options, execute), /Invalid Windows database ownership/);
+});
+
test('automatic and explicit status endpoints fail closed without matching open database ownership', async (t) => {
const f = await fixture(t);
for (const serverUrl of [undefined, f.serverUrl]) {
diff --git a/scripts/ai-test-isolation.mjs b/scripts/ai-test-isolation.mjs
index 8f9732a4..455d4384 100644
--- a/scripts/ai-test-isolation.mjs
+++ b/scripts/ai-test-isolation.mjs
@@ -46,7 +46,7 @@ export async function requireIsolatedTestServer(
if (await realpath(database) !== database || (await stat(database)).nlink !== 1) {
throw new Error('AI test database must not be a symlink or hard link');
}
- // A claimed /path alone is insufficient: verify the listener actually holds this database.
+ // A claimed /path alone is insufficient: verify native listener and database ownership.
const evidence = await readActiveSessions({ serverUrl, sourceDatabase: database, directory });
return { ...evidence, data, xdgDataHome: path.dirname(data) };
}
diff --git a/scripts/ai-test-isolation.test.mjs b/scripts/ai-test-isolation.test.mjs
index 1b8e82fd..5f399bfd 100644
--- a/scripts/ai-test-isolation.test.mjs
+++ b/scripts/ai-test-isolation.test.mjs
@@ -1,4 +1,6 @@
import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
import { mkdir, mkdtemp, realpath, rm, symlink, link } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
@@ -16,8 +18,7 @@ test('live tests cannot silently select production or a redirect-capable remote
assert.equal(testServerOrigin('http://127.0.0.1:49001/'), 'http://127.0.0.1:49001');
});
-// Real ownership verification uses lsof, which is unavailable on Windows.
-test('requires a distinct test database held by the actual listener and rejects production aliases', { skip: process.platform === 'win32' }, async (t) => {
+test('requires a distinct test database held by the actual listener and rejects production aliases', async (t) => {
const temporary = await mkdtemp(path.join(os.tmpdir(), 'test-isolation-'));
const root = await realpath(temporary);
const testRoot = path.join(root, 'tests');
@@ -60,16 +61,35 @@ test('requires a distinct test database held by the actual listener and rejects
const unopenedData = path.join(testRoot, 'unopened');
await mkdir(unopenedData);
new DatabaseSync(path.join(unopenedData, 'opencode.db')).close();
- await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, unopenedData), /holds source database/);
+ await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, unopenedData), /holds? source database/);
+ // An open database is insufficient when a different process owns the listener.
+ const holder = spawn(process.execPath, ['--input-type=module', '-e',
+ "import { DatabaseSync } from 'node:sqlite'; const db = new DatabaseSync(process.argv[1]); process.stdout.write('ready'); process.stdin.resume();",
+ path.join(unopenedData, 'opencode.db')], { stdio: ['pipe', 'pipe', 'pipe'] });
+ const holderExited = once(holder, 'exit');
+ t.after(async () => {
+ if (holder.exitCode === null && holder.signalCode === null) holder.kill();
+ await holderExited;
+ });
+ await Promise.race([
+ once(holder.stdout, 'data'),
+ holderExited.then(() => { throw new Error('Database holder exited before readiness'); }),
+ ]);
+ try {
+ await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, unopenedData), /holds? source database/);
+ } finally {
+ holder.kill();
+ await holderExited;
+ }
await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, production), /separate OpenCode database/);
reportedData = unopenedData;
- await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, null), /holds source database/);
+ await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, null), /holds? source database/);
reportedData = production;
await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, data), /does not match/);
await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, null), /separate OpenCode database/);
const alias = path.join(testRoot, 'alias');
- await symlink(production, alias);
+ await symlink(production, alias, process.platform === 'win32' ? 'junction' : 'dir');
reportedData = alias;
await assert.rejects(requireIsolatedTestServer(url, '/fixture', testRoot, null), /separate OpenCode database/);
const hardAlias = path.join(testRoot, 'hard-alias');
diff --git a/scripts/opencode-compatibility/README.md b/scripts/opencode-compatibility/README.md
index bbb6ed39..40eff5c1 100644
--- a/scripts/opencode-compatibility/README.md
+++ b/scripts/opencode-compatibility/README.md
@@ -25,3 +25,29 @@ npm run compatibility:discover -- --versions 1.17.18,1.17.17,1.17.16
The detected floor is the oldest release in the newest contiguous required-check-compatible range when the sampled window contains an incompatible release. The declared floor is a support policy and may intentionally be newer than the oldest technically compatible release. Floor-check mode requires every sampled release from the declared floor through the declared ceiling to pass, and also samples the floor's immediate predecessor for discovery. Deep MCP lifecycle checks are required for the declared ceiling and advisory for historical samples; advisory failures are reported as compatibility caveats so release-specific MCP regressions remain visible without making a repaired historical hole redefine the supported API range.
The report also records and explicitly probes the OpenCode version declared by `@opencode-ai/sdk` in Varro's `package.json`. A successful floor check updates the tracked `verified.json` summary, and unit tests reject a manifest ceiling change until that release has passed the real Docker probe. This version records test coverage only. It does not cap runtime support or background updates.
+
+## Dual-version adapter tests
+
+```sh
+npm run test:compatibility:adapters
+```
+
+This separate matrix installs the declared v1 floor, tested v1 SDK version, and tested v2 client version using their matching CLI packages. It exercises Varro's production transport, adapters, and process manager against real isolated servers. A local deterministic provider tests streaming and a read tool without external model credentials. V2 also gets real permission and form request/reply checks.
+
+CLI installations and the generated verification report live under `artifacts/opencode-adapters/`. Each server gets a distinct database, configuration, state directory, and fixture repository under `artifacts/ai-test-data/`. The suite does not use production sessions. Native v2 form/permission cases are explicitly skipped for v1.
+
+To test an existing binary directly:
+
+```sh
+VARRO_OPENCODE_TEST_BINARY=/absolute/path/to/opencode npm run test -- src/extension/opencode-v2.integration.test.ts src/extension/opencode-startup.integration.test.ts
+```
+
+## Real-editor v2 chat check
+
+```sh
+VARRO_OPENCODE_TEST_BINARY=/absolute/path/to/opencode2 npm run test:compatibility:ui
+```
+
+This launches a fresh VS Code development window and drives the actual Varro composer. It verifies a visible streamed reply, a visible failure before an assistant turn starts, an HTTP 401 with a Re-authenticate action, a subsequent reply from a working provider, reopening the transcript, and a complete window reload. Internal agent/model records must not become user bubbles.
+
+The fixture uses local deterministic model endpoints and verifies that the server PID owns its separate database under `artifacts/ai-test-data/` before sending prompts. It deletes the sessions it created, checks cleanup, and closes its editor. Screenshots, native events, and the result are retained in the fixture directory. This command requires VS Code and POSIX `lsof`; use `VARRO_VSCODE_EXECUTABLE` to override the default macOS executable path.
diff --git a/scripts/opencode-compatibility/run-adapters.mjs b/scripts/opencode-compatibility/run-adapters.mjs
new file mode 100644
index 00000000..87fbfd5e
--- /dev/null
+++ b/scripts/opencode-compatibility/run-adapters.mjs
@@ -0,0 +1,73 @@
+import { spawnSync } from 'node:child_process';
+import crossSpawn from 'cross-spawn';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+
+const root = resolve(import.meta.dirname, '../..');
+const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
+const sources = await readFile(join(root, 'src/shared/opencode-compatibility.ts'), 'utf8');
+const floor = sources.match(/MINIMUM_SUPPORTED_OPENCODE_VERSION\s*=\s*'([^']+)'/)?.[1];
+const v2Floor = sources.match(/MINIMUM_SUPPORTED_OPENCODE_V2_VERSION\s*=\s*'([^']+)'/)?.[1];
+const v1 = String(manifest.dependencies['@opencode-ai/sdk']).match(/\d+\.\d+\.\d+/)?.[0];
+const v2 = String(manifest.dependencies['@opencode/client']).match(/\d+\.\d+\.\d+/)?.[0];
+if (!floor || !v2Floor || !v1 || !v2)
+ throw new Error('Could not read the declared adapter versions');
+const versions = [...new Set([floor, v1, v2Floor, v2])];
+const directory = join(root, 'artifacts', 'opencode-adapters');
+await mkdir(directory, { recursive: true });
+const run = await mkdtemp(join(directory, 'run-'));
+const results = [];
+for (const version of versions) {
+ const packageName = version.startsWith('2.') ? '@opencode/cli' : 'opencode-ai';
+ const prefix = join(run, version);
+ const install = crossSpawn.sync(
+ 'npm',
+ ['install', '--prefix', prefix, `${packageName}@${version}`],
+ { cwd: root, encoding: 'utf8', timeout: 120_000 }
+ );
+ if (install.status !== 0)
+ throw new Error(
+ `Could not install ${packageName}@${version}: ${install.stderr || install.error}`
+ );
+ const binary = join(
+ prefix,
+ 'node_modules',
+ '.bin',
+ process.platform === 'win32' ? 'opencode.cmd' : 'opencode'
+ );
+ process.stdout.write(`Testing ${packageName}@${version}\n`);
+ const test = spawnSync(
+ process.execPath,
+ [
+ 'scripts/run-tests.mjs',
+ 'src/extension/opencode-v2.integration.test.ts',
+ 'src/extension/opencode-startup.integration.test.ts',
+ ],
+ {
+ cwd: root,
+ encoding: 'utf8',
+ timeout: 180_000,
+ maxBuffer: 10 * 1024 * 1024,
+ env: {
+ ...process.env,
+ VARRO_OPENCODE_TEST_BINARY: binary,
+ VARRO_OPENCODE_TEST_VERSION: version,
+ },
+ }
+ );
+ const log = `${test.stdout ?? ''}${test.stderr ?? ''}`;
+ await writeFile(join(run, `${version}.log`), log);
+ results.push({
+ package: packageName,
+ version,
+ passed: test.status === 0,
+ log: join(run, `${version}.log`),
+ });
+ process.stdout.write(log);
+}
+await writeFile(
+ join(directory, 'verified.json'),
+ JSON.stringify({ date: new Date().toISOString(), versions, results }, null, 2)
+);
+if (results.some((result) => !result.passed)) process.exitCode = 1;
+process.stdout.write(`Adapter compatibility report: ${join(directory, 'verified.json')}\n`);
diff --git a/scripts/opencode-compatibility/run-ui.mjs b/scripts/opencode-compatibility/run-ui.mjs
new file mode 100644
index 00000000..f8bf9511
--- /dev/null
+++ b/scripts/opencode-compatibility/run-ui.mjs
@@ -0,0 +1,744 @@
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
+import { mkdir, mkdtemp, readFile, realpath, stat, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { chromium, expect } from '@playwright/test';
+import { DatabaseSync } from 'node:sqlite';
+import {
+ executeVscodeCommand,
+ reserveLoopbackPort,
+ writeVscodeLaunchMetadata,
+} from '../vscode-launch-process.mjs';
+
+const project = resolve(import.meta.dirname, '../..');
+const binary = process.env.VARRO_OPENCODE_TEST_BINARY;
+if (!binary) throw new Error('Set VARRO_OPENCODE_TEST_BINARY to the released CLI being tested');
+const executable =
+ process.env.VARRO_VSCODE_EXECUTABLE || '/Applications/Visual Studio Code.app/Contents/MacOS/Code';
+const parent = join(project, 'artifacts/ai-test-data');
+await mkdir(parent, { recursive: true });
+const root = await mkdtemp(join(parent, 'v2-ui-'));
+const profiles = join(tmpdir(), 'opencode');
+await mkdir(profiles, { recursive: true });
+const profile = await mkdtemp(join(profiles, 'vui-'));
+const workspace = join(root, 'workspace');
+const database = join(root, 'data', 'opencode.db');
+for (const path of [
+ workspace,
+ join(workspace, '.vscode'),
+ join(root, 'data'),
+ join(root, 'home'),
+ join(profile, 'user'),
+ join(profile, 'extensions'),
+])
+ await mkdir(path, { recursive: true });
+assert.equal(spawnSync('git', ['init', '--quiet'], { cwd: workspace }).status, 0);
+const port = await reserveLoopbackPort();
+const debugPort = await reserveLoopbackPort();
+const serverUrl = `http://127.0.0.1:${port}`;
+const errors = [];
+const requests = [];
+const provider = createServer(async (request, response) => {
+ const chunks = [];
+ for await (const chunk of request) chunks.push(chunk);
+ const source = Buffer.concat(chunks).toString();
+ const body = source ? JSON.parse(source) : {};
+ requests.push({ path: request.url, model: body.model, stream: body.stream });
+ if (body.model === 'unauthorized') {
+ response.writeHead(401, { 'content-type': 'application/json' });
+ response.end(
+ JSON.stringify({
+ error: {
+ message: 'UI fixture authentication rejected',
+ type: 'authentication_error',
+ code: 'invalid_api_key',
+ },
+ })
+ );
+ return;
+ }
+ if (!body.stream) {
+ response.writeHead(200, { 'content-type': 'application/json' });
+ response.end(
+ JSON.stringify({
+ id: 'completion-ui',
+ object: 'chat.completion',
+ created: 1,
+ model: 'fixture',
+ choices: [
+ {
+ index: 0,
+ message: { role: 'assistant', content: 'UI adapter reply.' },
+ finish_reason: 'stop',
+ },
+ ],
+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
+ })
+ );
+ return;
+ }
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ for (const content of ['UI ', 'adapter ', 'reply.']) {
+ response.write(
+ `data: ${JSON.stringify({ id: 'completion-ui', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: { content }, finish_reason: null }] })}\n\n`
+ );
+ await delay(100);
+ }
+ response.end(
+ `data: ${JSON.stringify({ id: 'completion-ui', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } })}\n\ndata: [DONE]\n\n`
+ );
+});
+await new Promise((done) => provider.listen(0, '127.0.0.1', done));
+const modelUrl = `http://127.0.0.1:${provider.address().port}/v1`;
+await writeFile(
+ join(workspace, 'opencode.json'),
+ JSON.stringify({
+ model: 'fixture/fixture',
+ small_model: 'fixture/fixture',
+ agents: { title: { model: 'fixture/fixture' } },
+ provider: {
+ fixture: {
+ npm: '@ai-sdk/openai-compatible',
+ name: 'UI fixture',
+ options: { baseURL: modelUrl, apiKey: 'fixture-only' },
+ models: {
+ fixture: { name: 'UI fixture model', limit: { context: 32000, output: 1000 } },
+ unauthorized: {
+ name: 'UI authorization failure',
+ limit: { context: 32000, output: 1000 },
+ },
+ },
+ },
+ recovery: {
+ npm: '@ai-sdk/openai-compatible',
+ name: 'UI recovery fixture',
+ options: { baseURL: modelUrl, apiKey: 'fixture-only' },
+ models: {
+ recovery: { name: 'UI recovery model', limit: { context: 32000, output: 1000 } },
+ },
+ },
+ openai: { options: { baseURL: modelUrl } },
+ missing: {
+ name: 'Missing provider fixture',
+ models: {
+ broken: { name: 'UI preflight failure', limit: { context: 32000, output: 1000 } },
+ },
+ },
+ },
+ })
+);
+await writeFile(
+ join(workspace, '.vscode/settings.json'),
+ JSON.stringify({
+ 'varro.server.command': resolve(binary),
+ 'varro.server.port': port,
+ 'varro.server.autoUpdate': false,
+ 'security.workspace.trust.enabled': false,
+ 'workbench.startupEditor': 'none',
+ 'telemetry.telemetryLevel': 'off',
+ })
+);
+const env = {
+ PATH: process.env.PATH,
+ TMPDIR: tmpdir(),
+ HOME: join(root, 'home'),
+ XDG_DATA_HOME: join(root, 'data'),
+ XDG_CONFIG_HOME: join(root, 'config'),
+ XDG_STATE_HOME: join(root, 'state'),
+ XDG_CACHE_HOME: join(root, 'cache'),
+ OPENCODE_DB: database,
+ OPENCODE_TEST_HOME: join(root, 'home'),
+ VARRO_TEST_SERVER_URL: serverUrl,
+};
+const code = spawn(
+ executable,
+ [
+ '--no-sandbox',
+ '--disable-gpu-sandbox',
+ '--password-store=basic',
+ '--use-mock-keychain',
+ '--disable-updates',
+ '--disable-workspace-trust',
+ '--skip-welcome',
+ '--skip-release-notes',
+ '--new-window',
+ `--remote-debugging-port=${debugPort}`,
+ `--user-data-dir=${join(profile, 'user')}`,
+ `--extensions-dir=${join(profile, 'extensions')}`,
+ `--extensionDevelopmentPath=${project}`,
+ workspace,
+ ],
+ { cwd: project, env, stdio: ['ignore', 'pipe', 'pipe'] }
+);
+let codeLog = '';
+code.stdout.on('data', (data) => {
+ codeLog = (codeLog + data).slice(-20000);
+});
+code.stderr.on('data', (data) => {
+ codeLog = (codeLog + data).slice(-20000);
+});
+let browser;
+let frame;
+let authorization;
+const ownedServerPids = new Set();
+const ownsDatabase = (pid) =>
+ spawnSync('lsof', ['-t', '-a', '-p', String(pid), database], { encoding: 'utf8' })
+ .stdout.trim()
+ .split(/\s+/)
+ .includes(String(pid));
+const sessions = new Set();
+const events = [];
+const stream = new AbortController();
+const api = async (method, path, body) => {
+ const options = {
+ method,
+ headers: { Authorization: authorization, 'content-type': 'application/json' },
+ redirect: 'error',
+ signal: AbortSignal.timeout(10000),
+ };
+ if (body !== undefined && method !== 'GET' && method !== 'HEAD')
+ options.body = JSON.stringify(body);
+ const response = await fetch(serverUrl + path, options);
+ if (response.status === 204) return null;
+ if (response.status === 404 && method === 'DELETE') return null;
+ if (!response.ok) throw new Error(`Fixture ${method} ${path}: ${response.status}`);
+ return response.json();
+};
+const serverInfo = async () => {
+ const response = await fetch(serverUrl + '/api/info', {
+ headers: { Authorization: authorization },
+ redirect: 'error',
+ signal: AbortSignal.timeout(10000),
+ });
+ return response.ok ? response.json() : api('GET', '/api/status');
+};
+const findFrame = async () => {
+ for (let attempt = 0; attempt < 150; attempt++) {
+ for (const page of browser.contexts().flatMap((context) => context.pages())) {
+ for (const candidate of page.frames()) {
+ if (
+ await candidate
+ .locator('.model-picker-btn')
+ .first()
+ .isVisible()
+ .catch(() => false)
+ )
+ return candidate;
+ }
+ }
+ await delay(200);
+ }
+ throw new Error('The isolated Varro composer did not appear');
+};
+let outcome;
+try {
+ await writeVscodeLaunchMetadata(join(root, 'launch.json'), {
+ pid: code.pid,
+ executable,
+ profileRoot: profile,
+ userDataDir: join(profile, 'user'),
+ extensionsDir: join(profile, 'extensions'),
+ workspace,
+ remoteDebuggingPort: debugPort,
+ });
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ browser = await chromium.connectOverCDP(`http://127.0.0.1:${debugPort}`);
+ break;
+ } catch {
+ await delay(200);
+ }
+ }
+ assert.ok(browser, `Could not connect to the isolated editor: ${codeLog}`);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await executeVscodeCommand(debugPort, 'View: Focus on Varro View');
+ break;
+ } catch (error) {
+ if (attempt >= 100) throw error;
+ await delay(200);
+ }
+ }
+ frame = await findFrame();
+ let lease;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ lease = JSON.parse(
+ await readFile(join(tmpdir(), `varro-opencode-server-${port}.json`), 'utf8')
+ );
+ if (lease.password) break;
+ } catch {}
+ await delay(200);
+ }
+ assert.ok(lease?.password, 'The v2 fixture did not create an authenticated ownership lease');
+ assert.equal(lease.port, port);
+ assert.equal(await realpath(database), database);
+ assert.equal((await stat(database)).nlink, 1);
+ const owner = spawnSync('lsof', ['-t', '-a', '-p', String(lease.pid), database], {
+ encoding: 'utf8',
+ });
+ assert.ok(
+ owner.stdout.trim().split(/\s+/).includes(String(lease.pid)),
+ 'The fixture listener does not hold the isolated database'
+ );
+ ownedServerPids.add(lease.pid);
+ authorization = `Basic ${Buffer.from(`opencode:${lease.password}`).toString('base64')}`;
+ assert.equal((await serverInfo()).pid, lease.pid);
+ assert.equal((await api('GET', '/api/session')).data.length, 0);
+ void (async () => {
+ const response = await fetch(serverUrl + '/api/event', {
+ headers: { Authorization: authorization },
+ signal: stream.signal,
+ });
+ let buffer = '';
+ for await (const chunk of response.body) {
+ buffer += new TextDecoder().decode(chunk);
+ let end;
+ while ((end = buffer.indexOf('\n\n')) >= 0) {
+ const text = buffer
+ .slice(0, end)
+ .split('\n')
+ .find((line) => line.startsWith('data:'))
+ ?.slice(5);
+ buffer = buffer.slice(end + 2);
+ if (!text) continue;
+ const event = JSON.parse(text);
+ events.push(event);
+ if (event.type === 'session.created') sessions.add(event.data.sessionID);
+ }
+ }
+ })().catch((error) => {
+ if (!stream.signal.aborted) errors.push(error.message);
+ });
+ await frame.locator('.model-picker-btn').click();
+ await frame.locator('.model-picker-item').filter({ hasText: 'UI fixture model' }).click();
+ await frame.getByLabel('Select agent', { exact: true }).click();
+ await frame.locator('.agent-popover').getByText('Build', { exact: true }).click();
+ const composer = frame.locator('[role="textbox"][aria-multiline="true"]').first();
+ await composer.fill('UI healthy probe.');
+ await composer.press('Enter');
+ await expect(frame.locator('.chat-turn-assistant')).toContainText('UI adapter reply.', {
+ timeout: 30000,
+ });
+ await expect(frame.locator('.chat-turn-assistant').last()).toBeVisible();
+ await frame.page().screenshot({ path: join(root, 'healthy.png') });
+ await frame
+ .locator('.chat-header-session-title')
+ .filter({ visible: true })
+ .first()
+ .click({ button: 'right' });
+ await expect(frame.getByRole('menu', { name: 'Session actions' })).toBeVisible();
+ await expect(frame.getByRole('menuitem', { name: /^(?:Unshare|Share) session$/ })).toHaveCount(0);
+ await frame.page().screenshot({ path: join(root, 'unsupported-actions-hidden.png') });
+ await frame.page().keyboard.press('Escape');
+
+ const approvalSession = (await api('GET', '/api/session')).data[0];
+ assert.ok(approvalSession?.id);
+ await api('PATCH', `/api/session/${approvalSession.id}`, {
+ permissions: [{ action: '*', resource: '*', effect: 'ask' }],
+ });
+ for (const action of ['Allow once', 'Reject']) {
+ const pending = fetch(`${serverUrl}/api/session/${approvalSession.id}/permission`, {
+ method: 'POST',
+ headers: { Authorization: authorization, 'content-type': 'application/json' },
+ body: JSON.stringify({
+ action: 'shell',
+ resources: [`fixture ${action}`],
+ save: [],
+ metadata: {},
+ }),
+ signal: AbortSignal.timeout(30000),
+ }).then(async (response) => ({ status: response.status, body: await response.json() }));
+ await expect(frame.locator('.permission-prompt')).toBeVisible({ timeout: 10000 });
+ await frame.getByLabel('Back to sessions').first().click();
+ await frame.locator('.session-item').first().click();
+ await expect(frame.locator('.permission-prompt')).toBeVisible();
+ await frame.getByRole('button', { name: action, exact: true }).click();
+ await pending;
+ await expect(frame.locator('.permission-prompt')).toHaveCount(0);
+ assert.equal((await api('GET', '/api/permission/request')).data.length, 0);
+ }
+ const question = (
+ await api('POST', `/api/session/${approvalSession.id}/form`, {
+ title: 'Deep parity choice',
+ fields: [
+ {
+ key: 'choice',
+ type: 'string',
+ title: 'Choose a rollout',
+ options: [
+ { value: 'canary', label: 'Canary' },
+ { value: 'all', label: 'All users' },
+ ],
+ },
+ ],
+ })
+ ).data;
+ await expect(frame.getByRole('radio', { name: /Canary/ })).toBeVisible();
+ await frame.getByLabel('Back to sessions').first().click();
+ await frame.locator('.session-item').first().click();
+ await frame.getByRole('radio', { name: /Canary/ }).click();
+ await frame.getByRole('button', { name: 'Submit', exact: true }).click();
+ await expect(frame.getByRole('radio', { name: /Canary/ })).toHaveCount(0);
+ assert.equal((await api('GET', '/api/form')).data.length, 0);
+ const answered = (await api('GET', `/api/session/${approvalSession.id}/form/${question.id}`))
+ .data;
+ assert.equal(answered.state.status, 'answered');
+ assert.equal(answered.state.answer.choice, 'canary');
+ await api('POST', `/api/session/${approvalSession.id}/form`, {
+ title: 'Deep parity cancel',
+ fields: [{ key: 'answer', type: 'string', title: 'Optional detail' }],
+ });
+ await expect(frame.getByRole('button', { name: 'Skip', exact: true })).toBeVisible();
+ await frame.getByRole('button', { name: 'Skip', exact: true }).click();
+ await expect(frame.getByRole('button', { name: 'Skip', exact: true })).toHaveCount(0);
+ assert.equal((await api('GET', '/api/form')).data.length, 0);
+ await frame.page().screenshot({ path: join(root, 'approvals-settled.png') });
+ await frame.locator('.model-picker-btn').click();
+ await frame.locator('.model-picker-item').filter({ hasText: 'UI preflight failure' }).click();
+ await composer.fill('UI failed probe.');
+ await composer.press('Enter');
+ await expect(frame.locator('.assistant-message-flow-item-error')).toBeVisible({ timeout: 30000 });
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(2);
+ await frame.page().screenshot({ path: join(root, 'failed-visible.png') });
+ await frame.locator('.model-picker-btn').click();
+ await frame.locator('.model-picker-item').filter({ hasText: 'UI authorization failure' }).click();
+ await composer.fill('UI authentication probe.');
+ await composer.press('Enter');
+ await expect(frame.locator('.assistant-message-flow-item-error').last()).toContainText(
+ 'Re-authenticate',
+ { timeout: 30000 }
+ );
+ await expect(
+ frame
+ .locator('.assistant-message-flow-item-error')
+ .last()
+ .getByRole('button', { name: 'Re-authenticate', exact: true })
+ ).toBeVisible();
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(3);
+ await expect(frame.locator('.assistant-message-flow-item-error')).toHaveCount(2);
+ await frame.page().screenshot({ path: join(root, 'auth-failure.png') });
+ await frame.locator('.model-picker-btn').click();
+ await frame.locator('.model-picker-item').filter({ hasText: 'UI recovery model' }).click();
+ await composer.fill('UI recovery probe.');
+ await composer.press('Enter');
+ await expect(frame.locator('.chat-turn-assistant').last()).toContainText('UI adapter reply.', {
+ timeout: 30000,
+ });
+ await expect(frame.locator('.chat-turn-assistant').last()).toBeVisible();
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(4);
+ await frame.getByLabel('Back to sessions').first().click();
+ await frame.locator('.session-item').first().click();
+ await expect(frame.locator('.assistant-message-flow-item-error')).toHaveCount(2, {
+ timeout: 10000,
+ });
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(4);
+ await frame.page().screenshot({ path: join(root, 'reopened.png') });
+ stream.abort();
+ const previousFrame = frame;
+ await executeVscodeCommand(debugPort, 'Developer: Reload Window');
+ await expect.poll(() => previousFrame.isDetached(), { timeout: 15000 }).toBe(true);
+ frame = await findFrame();
+ await expect(frame.locator('.assistant-message-flow-item-error')).toHaveCount(2, {
+ timeout: 20000,
+ });
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(4);
+ await frame.page().screenshot({ path: join(root, 'reloaded.png') });
+ const renewed = JSON.parse(
+ await readFile(join(tmpdir(), `varro-opencode-server-${port}.json`), 'utf8')
+ );
+ const renewedOwner = spawnSync('lsof', ['-t', '-a', '-p', String(renewed.pid), database], {
+ encoding: 'utf8',
+ });
+ assert.ok(renewedOwner.stdout.trim().split(/\s+/).includes(String(renewed.pid)));
+ ownedServerPids.add(renewed.pid);
+ authorization = `Basic ${Buffer.from(`opencode:${renewed.password}`).toString('base64')}`;
+ assert.equal((await serverInfo()).pid, renewed.pid);
+ await frame.getByLabel('Back to sessions').first().click();
+ const activeSession = frame.locator('.session-item:not(.recycle-bin-item)').first();
+ await activeSession.click({ button: 'right' });
+ await expect(frame.getByRole('menuitem', { name: /^(?:Unshare|Share) session$/ })).toHaveCount(0);
+ await frame.getByText('Move to Recycle Bin', { exact: true }).click();
+ await expect(frame.locator('.session-item:not(.recycle-bin-item)')).toHaveCount(0);
+ if (await frame.getByLabel('Expand Recycle Bin', { exact: true }).isVisible())
+ await frame.getByLabel('Expand Recycle Bin', { exact: true }).click();
+ await expect(frame.locator('.recycle-bin-item')).toHaveCount(1);
+ await frame.locator('.recycle-bin-item').getByLabel('Restore', { exact: true }).click();
+ await expect(activeSession).toBeVisible();
+ await activeSession.click();
+ await expect(frame.locator('.chat-turn-user')).toHaveCount(4);
+ await frame.getByLabel('Back to sessions').first().click();
+ await activeSession.click({ button: 'right' });
+ await frame.getByText('Move to Recycle Bin', { exact: true }).click();
+ await expect(frame.locator('.session-item:not(.recycle-bin-item)')).toHaveCount(0);
+ if (await frame.getByLabel('Expand Recycle Bin', { exact: true }).isVisible())
+ await frame.getByLabel('Expand Recycle Bin', { exact: true }).click();
+ await frame
+ .locator('.recycle-bin-item')
+ .getByLabel('Delete permanently', { exact: true })
+ .click();
+ await frame.getByLabel('Confirm permanent delete', { exact: true }).click();
+ await expect(frame.locator('.session-item')).toHaveCount(0);
+ assert.equal((await api('GET', '/api/session')).data.length, 0);
+ await frame.page().screenshot({ path: join(root, 'deleted.png') });
+ const legacy = new DatabaseSync(database);
+ const unavailable = (
+ await api('POST', '/api/session', {
+ title: 'Unavailable backend fixture',
+ location: { directory: workspace },
+ })
+ ).data;
+ sessions.add(unavailable.id);
+ const unavailableRow = frame
+ .locator('.session-item')
+ .filter({ hasText: 'Unavailable backend fixture' });
+ await expect(unavailableRow).toBeVisible();
+ // Remove only this tracked fixture row without a deletion event, reproducing a stale backend catalog.
+ legacy.prepare('DELETE FROM session_v2 WHERE id=?').run(unavailable.id);
+ await unavailableRow.click();
+ await expect(
+ frame.getByText('This conversation is unavailable on the connected OpenCode server.', {
+ exact: false,
+ })
+ ).toBeVisible();
+ await expect(unavailableRow).toHaveCount(0);
+ await expect(frame.getByLabel('Search sessions', { exact: true })).toBeVisible();
+ await frame.page().screenshot({ path: join(root, 'unavailable-session.png') });
+ legacy.exec(`
+ CREATE TABLE session (id TEXT PRIMARY KEY, parent_id TEXT, directory TEXT, title TEXT, time_created INTEGER, time_updated INTEGER, model TEXT);
+ CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);
+ CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, data TEXT);
+ `);
+ const seedMessage = (id, sessionID, role, text, at) => {
+ const info = {
+ role,
+ time: { created: at },
+ agent: 'build',
+ providerID: 'fixture',
+ modelID: 'fixture',
+ finish: 'stop',
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ };
+ if (role === 'assistant') info.time.completed = at + 1;
+ legacy
+ .prepare('INSERT INTO message VALUES (?,?,?,?)')
+ .run(id, sessionID, at, JSON.stringify(info));
+ legacy
+ .prepare('INSERT INTO part VALUES (?,?,?,?,?)')
+ .run('part_' + id, sessionID, id, at, JSON.stringify({ type: 'text', text }));
+ };
+ legacy
+ .prepare('INSERT INTO session VALUES (?,?,?,?,?,?,?)')
+ .run(
+ 'ses_legacy_fixture',
+ null,
+ workspace,
+ 'Legacy fixture root',
+ 1,
+ 4,
+ JSON.stringify({ providerID: 'fixture', modelID: 'fixture' })
+ );
+ legacy
+ .prepare('INSERT INTO session VALUES (?,?,?,?,?,?,?)')
+ .run('ses_legacy_child', 'ses_legacy_fixture', workspace, 'Legacy fixture child', 2, 3, null);
+ seedMessage('msg_legacy_user', 'ses_legacy_fixture', 'user', 'Legacy question.', 1);
+ seedMessage('msg_legacy_assistant', 'ses_legacy_fixture', 'assistant', 'Imported v1 answer.', 4);
+ seedMessage('msg_child_user', 'ses_legacy_child', 'user', 'Inspect a fixture.', 2);
+ seedMessage('msg_child_assistant', 'ses_legacy_child', 'assistant', 'Child fixture result.', 3);
+ legacy.prepare('INSERT INTO part VALUES (?,?,?,?,?)').run(
+ 'part_tool_fixture',
+ 'ses_legacy_fixture',
+ 'msg_legacy_assistant',
+ 3,
+ JSON.stringify({
+ type: 'tool',
+ callID: 'call_legacy',
+ tool: 'task',
+ state: {
+ status: 'completed',
+ input: { prompt: 'Inspect a fixture.' },
+ output: 'Child fixture result.',
+ metadata: { sessionId: 'ses_legacy_child' },
+ time: { start: 2, end: 3 },
+ },
+ })
+ );
+ const legacySnapshot = () =>
+ JSON.stringify(
+ ['session', 'message', 'part'].map((table) =>
+ legacy.prepare(`SELECT * FROM ${table} ORDER BY id`).all()
+ )
+ );
+ const beforeImport = legacySnapshot();
+ const beforeProviderRequests = requests.length;
+ await executeVscodeCommand(debugPort, 'Varro: Import OpenCode v1 Session into v2');
+ await frame
+ .page()
+ .locator('.quick-input-widget')
+ .getByText('Legacy fixture root', { exact: true })
+ .click();
+ await expect(frame.locator('.chat-turn-assistant')).toContainText('Imported v1 answer.', {
+ timeout: 30000,
+ });
+ assert.equal(
+ requests.length,
+ beforeProviderRequests,
+ 'Import must not execute historical tools or start a model turn'
+ );
+ const imported = (await api('GET', '/api/session')).data;
+ assert.equal(imported.length, 2);
+ for (const session of imported) sessions.add(session.id);
+ const importedRoot = imported.find((session) => !session.parentID);
+ assert.ok(importedRoot && importedRoot.id !== 'ses_legacy_fixture');
+ assert.equal(imported.find((session) => session.parentID)?.parentID, importedRoot.id);
+ const importedMessages = (await api('GET', `/api/session/${importedRoot.id}/message`)).data;
+ assert.ok(importedMessages.every((message) => !message.id.startsWith('msg_legacy_')));
+ await frame.page().screenshot({ path: join(root, 'imported.png') });
+ await frame
+ .locator('[role="textbox"][aria-multiline="true"]')
+ .first()
+ .fill('Continue the imported conversation.');
+ await frame.locator('[role="textbox"][aria-multiline="true"]').first().press('Enter');
+ await expect(frame.locator('.chat-turn-assistant').last()).toContainText('UI adapter reply.', {
+ timeout: 30000,
+ });
+ assert.equal(
+ legacySnapshot(),
+ beforeImport,
+ 'Import and continuation changed the original v1 history'
+ );
+ legacy.close();
+ await frame.page().screenshot({ path: join(root, 'import-continued.png') });
+ await frame.getByLabel('Back to sessions').first().click();
+ await frame
+ .locator('.session-item')
+ .filter({ hasText: 'Legacy fixture root (v1 copy)' })
+ .first()
+ .click();
+ await expect(frame.locator('.chat-turn-assistant')).toContainText([
+ 'Imported v1 answer.',
+ 'UI adapter reply.',
+ ]);
+ const importedFrame = frame;
+ await executeVscodeCommand(debugPort, 'Developer: Reload Window');
+ await expect.poll(() => importedFrame.isDetached(), { timeout: 15000 }).toBe(true);
+ frame = await findFrame();
+ await expect(frame.locator('.chat-turn-assistant')).toContainText(
+ ['Imported v1 answer.', 'UI adapter reply.'],
+ { timeout: 20000 }
+ );
+ const importedLease = JSON.parse(
+ await readFile(join(tmpdir(), `varro-opencode-server-${port}.json`), 'utf8')
+ );
+ assert.ok(
+ spawnSync('lsof', ['-t', '-a', '-p', String(importedLease.pid), database], { encoding: 'utf8' })
+ .stdout.trim()
+ .split(/\s+/)
+ .includes(String(importedLease.pid))
+ );
+ ownedServerPids.add(importedLease.pid);
+ authorization = `Basic ${Buffer.from(`opencode:${importedLease.password}`).toString('base64')}`;
+ await frame.page().screenshot({ path: join(root, 'import-reloaded.png') });
+ outcome = { passed: true };
+} catch (error) {
+ outcome = { passed: false, error: error.stack };
+ if (browser)
+ await writeFile(
+ join(root, 'frames.json'),
+ JSON.stringify(
+ browser
+ .contexts()
+ .flatMap((context) => context.pages())
+ .map((page) => ({
+ url: page.url(),
+ frames: page.frames().map((candidate) => candidate.url()),
+ })),
+ null,
+ 2
+ )
+ );
+ if (frame) {
+ await writeFile(
+ join(root, 'dom.txt'),
+ await frame
+ .locator('body')
+ .innerText()
+ .catch(() => 'Frame closed')
+ );
+ await frame
+ .page()
+ .screenshot({ path: join(root, 'failure.png') })
+ .catch(() => {});
+ }
+ process.exitCode = 1;
+} finally {
+ stream.abort();
+ try {
+ const cleanupLease = JSON.parse(
+ await readFile(join(tmpdir(), `varro-opencode-server-${port}.json`), 'utf8')
+ );
+ if (ownsDatabase(cleanupLease.pid)) {
+ ownedServerPids.add(cleanupLease.pid);
+ authorization = `Basic ${Buffer.from(`opencode:${cleanupLease.password}`).toString('base64')}`;
+ }
+ } catch (error) {
+ if (error.code !== 'ENOENT') errors.push(`Could not read fixture lease: ${error.message}`);
+ }
+ if (authorization) {
+ const inventory = await api('GET', '/api/session').catch(() => ({ data: [] }));
+ for (const session of inventory.data) {
+ if (
+ ['ses_legacy_fixture', 'ses_legacy_child'].includes(
+ session.metadata?.varroLegacyImport?.sourceSessionID
+ )
+ )
+ sessions.add(session.id);
+ }
+ }
+ for (const sessionID of sessions) {
+ try {
+ await api('DELETE', `/api/session/${sessionID}`);
+ } catch (error) {
+ errors.push(`Cleanup ${sessionID}: ${error.message}`);
+ }
+ }
+ if (authorization) {
+ try {
+ const remaining = await api('GET', '/api/session');
+ if (remaining.data.length)
+ errors.push(
+ `Fixture sessions remain: ${remaining.data.map((session) => session.id).join(', ')}`
+ );
+ } catch (error) {
+ errors.push(`Could not verify fixture cleanup: ${error.message}`);
+ }
+ }
+ await browser?.close();
+ code.kill('SIGTERM');
+ await Promise.race([new Promise((done) => code.once('exit', done)), delay(3000)]);
+ if (code.exitCode === null && code.signalCode === null) code.kill('SIGKILL');
+ for (const pid of ownedServerPids) {
+ if (!ownsDatabase(pid)) continue;
+ process.kill(pid, 'SIGTERM');
+ for (let attempt = 0; attempt < 20 && ownsDatabase(pid); attempt++) await delay(100);
+ if (ownsDatabase(pid)) process.kill(pid, 'SIGKILL');
+ for (let attempt = 0; attempt < 20 && ownsDatabase(pid); attempt++) await delay(100);
+ if (ownsDatabase(pid)) errors.push(`Fixture server ${pid} did not stop`);
+ }
+ provider.closeAllConnections();
+ await new Promise((done) => provider.close(done));
+ if (errors.length) {
+ outcome.passed = false;
+ process.exitCode = 1;
+ }
+ await writeFile(
+ join(root, 'result.json'),
+ JSON.stringify({ ...outcome, database, requests, errors }, null, 2)
+ );
+ await writeFile(join(root, 'events.json'), JSON.stringify(events, null, 2));
+ process.stdout.write(`${JSON.stringify({ ...outcome, artifacts: root, errors })}\n`);
+}
diff --git a/scripts/opencode-compatibility/verified.json b/scripts/opencode-compatibility/verified.json
index 050a13db..f093e165 100644
--- a/scripts/opencode-compatibility/verified.json
+++ b/scripts/opencode-compatibility/verified.json
@@ -1,5 +1,5 @@
{
- "generatedAt": "2026-09-14T23:38:57.706Z",
+ "generatedAt": "2026-09-17T13:26:01.066Z",
"declaredFloor": "1.16.0",
"declaredCeiling": "1.18.31",
"results": [
diff --git a/scripts/vscode-launch-process.mjs b/scripts/vscode-launch-process.mjs
index 949a086e..26c9d47f 100644
--- a/scripts/vscode-launch-process.mjs
+++ b/scripts/vscode-launch-process.mjs
@@ -130,7 +130,11 @@ export async function verifyVscodeLaunchIdentity(launch) {
}
const [birthIdentity, commandResult] = await Promise.all([
readProcessBirthIdentity(launch.pid),
- execFileAsync('ps', ['-p', String(launch.pid), '-o', 'command=']),
+ process.platform === 'win32'
+ ? readWindowsProcess(launch.pid).then((processInfo) => ({
+ stdout: processInfo.command.replaceAll('"', ''),
+ }))
+ : execFileAsync('ps', ['-p', String(launch.pid), '-o', 'command=']),
]);
if (birthIdentity !== launch.birthIdentity) {
throw new Error(`VS Code process ${String(launch.pid)} no longer matches its launch identity`);
@@ -263,9 +267,10 @@ export async function executeVscodeCommand(remoteDebuggingPort, commandLabel) {
for (const type of ['keyDown', 'keyUp']) {
await requests.call('Input.dispatchKeyEvent', {
type,
- key: 'P',
- code: 'KeyP',
- modifiers: process.platform === 'darwin' ? 12 : 10,
+ key: process.platform === 'win32' ? 'F1' : 'P',
+ code: process.platform === 'win32' ? 'F1' : 'KeyP',
+ windowsVirtualKeyCode: process.platform === 'win32' ? 112 : 80,
+ modifiers: process.platform === 'win32' ? 0 : process.platform === 'darwin' ? 12 : 10,
});
}
await new Promise((resolve) => setTimeout(resolve, 250));
@@ -273,7 +278,9 @@ export async function executeVscodeCommand(remoteDebuggingPort, commandLabel) {
// Filtering the command palette is asynchronous on a cold workbench.
await new Promise((resolve) => setTimeout(resolve, 250));
for (const type of ['keyDown', 'keyUp']) {
- await requests.call('Input.dispatchKeyEvent', { type, key: 'Enter', code: 'Enter' });
+ await requests.call('Input.dispatchKeyEvent', {
+ type, key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
+ });
}
} finally {
requests.dispose();
@@ -445,9 +452,23 @@ export async function reloadVscodeWindow(
}
async function readProcessBirthIdentity(pid) {
- if (process.platform === 'win32') return `win32:${String(pid)}`;
+ if (process.platform === 'win32') {
+ const processInfo = await readWindowsProcess(pid);
+ return `win32:${processInfo.birthIdentity}`;
+ }
const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'lstart=']);
const startedAt = stdout.trim();
if (!startedAt) throw new Error(`Could not read start time for VS Code process ${String(pid)}`);
return `${process.platform}:${startedAt}`;
}
+
+async function readWindowsProcess(pid) {
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid VS Code process ID');
+ const { stdout } = await execFileAsync('powershell.exe', [
+ '-NoProfile', '-NonInteractive', '-Command',
+ `$ErrorActionPreference = 'Stop'; $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; ` +
+ "if (!$p) { throw 'VS Code process is unavailable' }; " +
+ '@{ command = $p.CommandLine; birthIdentity = $p.CreationDate.ToUniversalTime().Ticks.ToString() } | ConvertTo-Json -Compress',
+ ], { timeout: 10_000 });
+ return JSON.parse(stdout);
+}
diff --git a/scripts/vscode-sandbox/run.mjs b/scripts/vscode-sandbox/run.mjs
index 24ba2288..d9e8cf49 100644
--- a/scripts/vscode-sandbox/run.mjs
+++ b/scripts/vscode-sandbox/run.mjs
@@ -12,6 +12,7 @@ const projectRoot = path.resolve(scriptDirectory, '../..');
const suitePath = path.join(scriptDirectory, 'suite.cjs');
const fakeCliPath = path.join(scriptDirectory, 'fake-opencode.mjs');
const keepSandboxes = process.env.VARRO_KEEP_VSCODE_SANDBOX === '1';
+const OPTIONAL_SCENARIOS = ['v2-first-run'];
const SCENARIOS = [
'clean-install-missing-cli',
@@ -33,12 +34,12 @@ const SCENARIOS = [
function selectScenarios(args) {
const requested = args.filter((arg) => !arg.startsWith('-'));
if (args.includes('--list')) {
- process.stdout.write(`${SCENARIOS.join('\n')}\n`);
+ process.stdout.write(`${[...SCENARIOS, ...OPTIONAL_SCENARIOS].join('\n')}\n`);
process.exit(0);
}
if (requested.length === 0) return SCENARIOS;
for (const scenario of requested) {
- if (!SCENARIOS.includes(scenario)) {
+ if (![...SCENARIOS, ...OPTIONAL_SCENARIOS].includes(scenario)) {
throw new Error(`Unknown VS Code sandbox scenario: ${scenario}`);
}
}
@@ -140,6 +141,7 @@ function getScenarioSettings(scenario, port, fakeCommand, missingCommand) {
case 'auto-start-disabled':
return { ...common, 'varro.server.autoStart': false };
case 'required-update-disabled':
+ case 'v2-first-run':
return {
...common,
'varro.server.autoUpdate': false,
@@ -272,6 +274,12 @@ async function stopFakeCli(pidFile) {
async function runScenario(scenario, vscodeExecutable) {
// Keep this short: macOS limits local IPC socket paths to roughly 103 bytes.
const root = await mkdtemp(path.join(os.tmpdir(), 'vr-'));
+ let dataRoot = root;
+ if (scenario === 'v2-first-run') {
+ const parent = path.join(projectRoot, 'artifacts', 'ai-test-data');
+ await mkdir(parent, { recursive: true });
+ dataRoot = await mkdtemp(path.join(parent, 'vscode-v2-'));
+ }
const workspace = path.join(root, 'w');
const settingsDirectory = path.join(workspace, '.vscode');
const userData = path.join(root, 'u');
@@ -297,9 +305,23 @@ async function runScenario(scenario, vscodeExecutable) {
);
}
const port = await reservePort();
- const fakeCommand = await createFakeCliLauncher(root);
+ const fakeCommand = scenario === 'v2-first-run' ? process.env.VARRO_SANDBOX_V2_COMMAND : await createFakeCliLauncher(root);
+ if (!fakeCommand) throw new Error('Set VARRO_SANDBOX_V2_COMMAND to a released v2 binary');
+ await access(fakeCommand);
const missingCommand = path.join(root, 'missing-opencode');
const settings = getScenarioSettings(scenario, port, fakeCommand, missingCommand);
+ const environment = { ...process.env, ...getScenarioEnvironment(scenario, root) };
+ if (scenario === 'v2-first-run') {
+ for (const key of Object.keys(environment)) {
+ if (/^OPENCODE_|_API_KEY$|_TOKEN$|^AWS_|^AZURE_|^GOOGLE_|^ANTHROPIC_/.test(key)) delete environment[key];
+ }
+ environment.HOME = path.join(root, 'home');
+ environment.USERPROFILE = path.join(root, 'home');
+ environment.OPENCODE_TEST_HOME = path.join(root, 'home');
+ environment.VARRO_TEST_SERVER_URL = `http://127.0.0.1:${port}`;
+ environment.OPENCODE_CONFIG = path.join(dataRoot, 'opencode.json');
+ await writeFile(environment.OPENCODE_CONFIG, JSON.stringify({ enabled_providers: [] }));
+ }
await writeFile(
path.join(settingsDirectory, 'settings.json'),
`${JSON.stringify(settings, null, 2)}\n`
@@ -331,13 +353,12 @@ async function runScenario(scenario, vscodeExecutable) {
workspace,
],
{
- ...process.env,
- ...getScenarioEnvironment(scenario, root),
- XDG_DATA_HOME: path.join(root, 'data'),
- XDG_STATE_HOME: path.join(root, 'state'),
- XDG_CACHE_HOME: path.join(root, 'cache'),
- XDG_CONFIG_HOME: path.join(root, 'config'),
- OPENCODE_DB: path.join(root, 'opencode.db'),
+ ...environment,
+ XDG_DATA_HOME: path.join(dataRoot, 'data'),
+ XDG_STATE_HOME: path.join(dataRoot, 'state'),
+ XDG_CACHE_HOME: path.join(dataRoot, 'cache'),
+ XDG_CONFIG_HOME: path.join(dataRoot, 'config'),
+ OPENCODE_DB: path.join(dataRoot, 'opencode.db'),
OPENCODE_PID: '',
VARRO_SANDBOX_LAUNCH_FILE: launchFile,
VARRO_SANDBOX_PID_FILE: pidFile,
@@ -355,6 +376,7 @@ async function runScenario(scenario, vscodeExecutable) {
}
);
process.stdout.write(`VS Code sandbox scenario passed: ${scenario}\n`);
+ if (scenario === 'v2-first-run') await writeFile(path.join(dataRoot, 'result.json'), JSON.stringify({ scenario, passed: true, command: fakeCommand, database: path.join(dataRoot, 'opencode.db') }, null, 2));
} finally {
await stopFakeCli(pidFile);
if (conflictServer) await new Promise((resolve) => conflictServer.close(resolve));
diff --git a/scripts/vscode-sandbox/suite.cjs b/scripts/vscode-sandbox/suite.cjs
index 98698cca..20c10dc0 100644
--- a/scripts/vscode-sandbox/suite.cjs
+++ b/scripts/vscode-sandbox/suite.cjs
@@ -27,7 +27,8 @@ const EXPECTATIONS = {
' - **Health:** healthy',
],
'malformed-cli-version': [
- ' - **Version:** `not found`',
+ // Managed startup recovers the version from the healthy server response.
+ ' - **Version:** `1.18.15`',
' - **Status:** `running, event stream healthy`',
' - **Health:** healthy',
],
@@ -81,6 +82,12 @@ const EXPECTATIONS = {
' - **Status:** `running, event stream healthy`',
' - **Health:** healthy',
],
+ 'v2-first-run': [
+ '- **Version:** `2.0.7`',
+ '- **Ownership:** managed by Varro',
+ ' - **Status:** `running, event stream healthy`',
+ ' - **Health:** healthy',
+ ],
};
function delay(milliseconds) {
diff --git a/scripts/windows-database-ownership.ps1 b/scripts/windows-database-ownership.ps1
new file mode 100644
index 00000000..9a88d174
--- /dev/null
+++ b/scripts/windows-database-ownership.ps1
@@ -0,0 +1,70 @@
+param([Parameter(Mandatory = $true)][string]$Database)
+
+$ErrorActionPreference = 'Stop'
+Add-Type -TypeDefinition @'
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+
+public static class VarroDatabaseOwners {
+ [StructLayout(LayoutKind.Sequential)]
+ public struct UniqueProcess {
+ public uint ProcessId;
+ public System.Runtime.InteropServices.ComTypes.FILETIME StartTime;
+ }
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ public struct ProcessInfo {
+ public UniqueProcess Process;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string AppName;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string ServiceName;
+ public uint ApplicationType;
+ public uint AppStatus;
+ public uint SessionId;
+ [MarshalAs(UnmanagedType.Bool)] public bool Restartable;
+ }
+ [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
+ static extern int RmStartSession(out uint session, uint flags, StringBuilder key);
+ [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
+ static extern int RmRegisterResources(uint session, uint fileCount, string[] files,
+ uint appCount, UniqueProcess[] apps, uint serviceCount, string[] services);
+ [DllImport("rstrtmgr.dll")]
+ static extern int RmGetList(uint session, out uint needed, ref uint count,
+ [In, Out] ProcessInfo[] processes, ref uint reasons);
+ [DllImport("rstrtmgr.dll")]
+ static extern int RmEndSession(uint session);
+
+ public static uint[] Read(string file) {
+ uint session;
+ int error = RmStartSession(out session, 0, new StringBuilder(33));
+ if (error != 0) throw new Win32Exception(error);
+ try {
+ error = RmRegisterResources(session, 1, new[] { file }, 0, null, 0, null);
+ if (error != 0) throw new Win32Exception(error);
+ uint needed, count = 0, reasons = 0;
+ ProcessInfo[] processes = null;
+ for (int attempt = 0; attempt < 4; attempt++) {
+ error = RmGetList(session, out needed, ref count, processes, ref reasons);
+ if (error == 0) {
+ uint[] result = new uint[count];
+ for (int i = 0; i < count; i++) result[i] = processes[i].Process.ProcessId;
+ return result;
+ }
+ if (error != 234) throw new Win32Exception(error);
+ count = needed;
+ processes = new ProcessInfo[count];
+ }
+ throw new InvalidOperationException("Database owners kept changing during verification");
+ } finally {
+ RmEndSession(session);
+ }
+ }
+}
+'@
+
+# Read-only ownership inspection. Never call Restart Manager shutdown/restart APIs.
+$owners = @([VarroDatabaseOwners]::Read($Database))
+$listeners = @(Get-NetTCPConnection -State Listen | ForEach-Object {
+ @{ address = $_.LocalAddress; port = $_.LocalPort; pid = $_.OwningProcess }
+})
+@{ databaseOwners = $owners; listeners = $listeners } | ConvertTo-Json -Depth 3 -Compress
diff --git a/src/extension/commands.test.ts b/src/extension/commands.test.ts
index 5327930f..8417908b 100644
--- a/src/extension/commands.test.ts
+++ b/src/extension/commands.test.ts
@@ -427,34 +427,38 @@ describe('About command', () => {
);
});
- it('hides the update notice when OpenCode is at the tested update ceiling', async () => {
- register('/repo', {
- readServerInfo: vi.fn().mockResolvedValue({
- status: { state: 'running', url: 'http://127.0.0.1:4096' },
- url: 'http://127.0.0.1:4096',
- port: 4096,
- command: 'opencode',
- managedProcess: true,
- cliVersion: MAXIMUM_TESTED_OPENCODE_VERSION,
- cliVersionError: null,
- installMethod: 'bun',
- resolvedCommand: '/home/me/.bun/bin/opencode',
- searchedPaths: [],
- activeAgentCount: 0,
- activeAgentError: null,
- health: { healthy: true, version: MAXIMUM_TESTED_OPENCODE_VERSION },
- workspaceCwd: '/repo',
- }),
- });
+ it.each([1, 2] as const)(
+ 'hides the update notice at the v%s tested update ceiling',
+ async (apiVersion) => {
+ const testedVersion = readMaximumTestedOpenCodeVersion(undefined, apiVersion);
+ register('/repo', {
+ readServerInfo: vi.fn().mockResolvedValue({
+ status: { state: 'running', url: 'http://127.0.0.1:4096' },
+ url: 'http://127.0.0.1:4096',
+ port: 4096,
+ command: 'opencode',
+ managedProcess: true,
+ cliVersion: testedVersion,
+ cliVersionError: null,
+ installMethod: 'bun',
+ resolvedCommand: '/home/me/.bun/bin/opencode',
+ searchedPaths: [],
+ activeAgentCount: 0,
+ activeAgentError: null,
+ health: { healthy: true, version: testedVersion },
+ workspaceCwd: '/repo',
+ }),
+ });
- await runCommand('varro.about');
+ await runCommand('varro.about');
- expect(vscodeMock.workspace.openTextDocument).toHaveBeenCalledWith(
- expect.objectContaining({
- content: expect.not.stringContaining('is available'),
- })
- );
- });
+ expect(vscodeMock.workspace.openTextDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: expect.not.stringContaining('is available'),
+ })
+ );
+ }
+ );
});
function fileUri(fsPath: string) {
diff --git a/src/extension/commands.ts b/src/extension/commands.ts
index 0df16b93..56c8a34b 100644
--- a/src/extension/commands.ts
+++ b/src/extension/commands.ts
@@ -17,6 +17,9 @@ import { renderAboutHtml } from './about-view';
import { diagnosticTimeline } from './diagnostics';
import { parseExtensionMessage } from '../shared/extension-message';
import { toEditorDiagnostic } from './workspace-problems';
+import { LegacySessionImport } from './legacy-session-import';
+import { asRecord, isString } from '../shared/type-utils';
+import { openCodeApiVersion } from './opencode-connection';
type ExtensionPackageJson = {
name?: unknown;
@@ -47,6 +50,53 @@ export function registerCommands(
let aboutDiagnosticsWithPaths = '';
context.subscriptions.push(
+ vscode.commands.registerCommand('varro.session.importV1', async () => {
+ try {
+ await server.start();
+ const health = asRecord(await server.request('GET', '/global/health'));
+ if (!isString(health?.version) || openCodeApiVersion(health.version) !== 2) {
+ throw new Error('Connect Varro to OpenCode v2 before importing v1 history');
+ }
+ const importer = new LegacySessionImport((method, path, body) =>
+ server.request(method, path, body)
+ );
+ const directory = server.getWorkspaceCwd();
+ if (!directory) throw new Error('Open a workspace before importing v1 history');
+ const choices = await importer.list(directory);
+ if (!choices.length) {
+ await vscode.window.showInformationMessage(
+ 'No local OpenCode v1 conversations were found for this workspace.'
+ );
+ return;
+ }
+ const selected = await vscode.window.showQuickPick(
+ choices.map((choice) => ({
+ label: choice.title,
+ description: choice.id,
+ detail: choice.directory,
+ choice,
+ })),
+ {
+ title: 'Import a v1 conversation into v2',
+ placeHolder: 'Select a conversation to copy. Its original v1 history is preserved.',
+ }
+ );
+ if (!selected) return;
+ const sessionID = await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: 'Importing v1 conversation into v2',
+ },
+ () => importer.importCopy(selected.choice)
+ );
+ await revealSidebar();
+ await sidebar.openSessionInSidebar(sessionID, selected.choice.directory);
+ } catch (error) {
+ void vscode.window.showErrorMessage(
+ `Could not import v1 history: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ }),
vscode.languages.registerCodeActionsProvider(
{ scheme: 'file' },
{
@@ -513,7 +563,8 @@ function renderAboutMarkdown(context: vscode.ExtensionContext, serverInfo: OpenC
const description =
getString(pkg.description) || 'An OpenCode agent workbench built for Visual Studio Code.';
const version = getString(pkg.version) || 'unknown';
- const maximumTestedVersion = readMaximumTestedOpenCodeVersion();
+ const apiVersion = serverInfo.cliVersion?.startsWith('2.') ? 2 : 1;
+ const maximumTestedVersion = readMaximumTestedOpenCodeVersion(undefined, apiVersion);
const autoUpdate = vscode.workspace
.getConfiguration('varro')
.get('server.autoUpdate', true);
@@ -527,7 +578,11 @@ function renderAboutMarkdown(context: vscode.ExtensionContext, serverInfo: OpenC
const updateAvailable =
installedVersion !== null && compareVersions(installedVersion, maximumTestedVersion) < 0;
const updateCommand = updateAvailable
- ? getUpgradeCommand(serverInfo.installMethod, process.platform)
+ ? getUpgradeCommand(
+ serverInfo.installMethod,
+ process.platform,
+ apiVersion === 2 ? '@opencode/cli' : 'opencode-ai'
+ )
: null;
const updateNoticeLines = !updateAvailable
? []
@@ -614,11 +669,16 @@ function createAboutViewData(
? `Error: ${serverInfo.status.message}`
: serverInfo.status.state;
const cliVersion = serverInfo.cliVersion ? extractVersion(serverInfo.cliVersion) : null;
- const maximumTestedVersion = readMaximumTestedOpenCodeVersion();
+ const apiVersion = cliVersion?.startsWith('2.') ? 2 : 1;
+ const maximumTestedVersion = readMaximumTestedOpenCodeVersion(undefined, apiVersion);
const updateAvailable =
cliVersion !== null && compareVersions(cliVersion, maximumTestedVersion) < 0;
const updateCommand = updateAvailable
- ? getUpgradeCommand(serverInfo.installMethod, process.platform)
+ ? getUpgradeCommand(
+ serverInfo.installMethod,
+ process.platform,
+ apiVersion === 2 ? '@opencode/cli' : 'opencode-ai'
+ )
: null;
return {
diff --git a/src/extension/error-hub.test.ts b/src/extension/error-hub.test.ts
index 545a68b8..15311f41 100644
--- a/src/extension/error-hub.test.ts
+++ b/src/extension/error-hub.test.ts
@@ -145,9 +145,9 @@ describe('ErrorHub', () => {
hub.reportCliMissing('CLI not found');
await vi.waitFor(() => {
- expect(vscodeMock.Uri.parse).toHaveBeenCalledWith('https://opencode.ai/');
+ expect(vscodeMock.Uri.parse).toHaveBeenCalledWith('https://opencode.ai/v2/docs/');
expect(vscodeMock.env.openExternal).toHaveBeenCalledWith({
- value: 'https://opencode.ai/',
+ value: 'https://opencode.ai/v2/docs/',
});
});
diff --git a/src/extension/error-hub.ts b/src/extension/error-hub.ts
index 5b882de5..894f8a09 100644
--- a/src/extension/error-hub.ts
+++ b/src/extension/error-hub.ts
@@ -1,6 +1,7 @@
/* oxlint-disable anti-slop/no-runtime-typeof -- Error causes cross an untyped JavaScript boundary and are checked before access. */
/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- SAFETY: Error records are checked for object shape before fields are read. */
import * as vscode from 'vscode';
+import { OPENCODE_INSTALL_DOCS_URL } from '../shared/opencode-install';
import { logger } from './logger';
export type ErrorAction = {
@@ -96,7 +97,7 @@ export class ErrorHub {
actions: [
{
title: 'Install instructions',
- run: () => vscode.env.openExternal(vscode.Uri.parse('https://opencode.ai/')),
+ run: () => vscode.env.openExternal(vscode.Uri.parse(OPENCODE_INSTALL_DOCS_URL)),
},
{
title: 'Show logs',
diff --git a/src/extension/extension-manifest.ts b/src/extension/extension-manifest.ts
index b07f349a..a13c3699 100644
--- a/src/extension/extension-manifest.ts
+++ b/src/extension/extension-manifest.ts
@@ -5,12 +5,14 @@ import { getMaximumTestedOpenCodeVersion } from '../shared/opencode-compatibilit
const maximumTestedVersionByManifestPath = new Map();
export function readMaximumTestedOpenCodeVersion(
- packageJsonPath = join(__dirname, '..', '..', 'package.json')
+ packageJsonPath = join(__dirname, '..', '..', 'package.json'),
+ apiVersion: 1 | 2 = 1
) {
- const cached = maximumTestedVersionByManifestPath.get(packageJsonPath);
+ const cacheKey = `${packageJsonPath}:${apiVersion}`;
+ const cached = maximumTestedVersionByManifestPath.get(cacheKey);
if (cached) return cached;
const packageJson: unknown = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
- const version = getMaximumTestedOpenCodeVersion(packageJson);
- maximumTestedVersionByManifestPath.set(packageJsonPath, version);
+ const version = getMaximumTestedOpenCodeVersion(packageJson, apiVersion);
+ maximumTestedVersionByManifestPath.set(cacheKey, version);
return version;
}
diff --git a/src/extension/legacy-session-import.test.ts b/src/extension/legacy-session-import.test.ts
new file mode 100644
index 00000000..699793b5
--- /dev/null
+++ b/src/extension/legacy-session-import.test.ts
@@ -0,0 +1,154 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, rm } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { LegacySessionImport } from './legacy-session-import';
+import { asRecord, type UnknownRecord } from '../shared/type-utils';
+
+const directories: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))
+ );
+});
+
+async function fixture() {
+ const parent = resolve('artifacts/ai-test-data');
+ await mkdir(parent, { recursive: true });
+ const directory = await mkdtemp(join(parent, 'legacy-import-'));
+ directories.push(directory);
+ const database = join(directory, 'opencode.db');
+ const db = new DatabaseSync(database);
+ db.exec(`CREATE TABLE session (id TEXT PRIMARY KEY, parent_id TEXT, directory TEXT, title TEXT, time_created INTEGER, time_updated INTEGER);
+ CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);
+ CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, data TEXT);`);
+ for (const [id, parentID] of [
+ ['root', null],
+ ['child', 'root'],
+ ] as const) {
+ db.prepare('INSERT INTO session VALUES (?,?,?,?,?,?)').run(id, parentID, '/fixture', id, 1, 2);
+ db.prepare('INSERT INTO message VALUES (?,?,?,?)').run(
+ `message-${id}`,
+ id,
+ 1,
+ JSON.stringify({
+ role: 'assistant',
+ agent: 'build',
+ modelID: 'model',
+ providerID: 'provider',
+ time: { created: 1, completed: 2 },
+ finish: 'stop',
+ })
+ );
+ db.prepare('INSERT INTO part VALUES (?,?,?,?,?)').run(
+ `part-${id}`,
+ id,
+ `message-${id}`,
+ 1,
+ JSON.stringify({
+ type: 'tool',
+ tool: 'task',
+ callID: `call-${id}`,
+ state: {
+ status: 'completed',
+ input: {},
+ output: 'Retained output',
+ metadata: { sessionId: 'child' },
+ time: { start: 1, end: 2 },
+ },
+ })
+ );
+ }
+ const before = JSON.stringify(
+ ['session', 'message', 'part'].map((table) => db.prepare(`SELECT * FROM ${table}`).all())
+ );
+ db.close();
+ return { database, before };
+}
+
+describe('explicit legacy session copy import', () => {
+ it('copies a tree with new identities, remaps child links, and preserves source records', async () => {
+ const { database, before } = await fixture();
+ const payloads: UnknownRecord[] = [];
+ const request: ConstructorParameters[0] = vi.fn(
+ async (method, path, body) => {
+ if (method === 'GET' && path.startsWith('/api/location'))
+ return { project: { id: 'project' } };
+ expect(method).toBe('POST');
+ expect(path).toBe('/api/experimental/session/import');
+ payloads.push(asRecord(body)!);
+ return {};
+ }
+ );
+ const importer = new LegacySessionImport(request, database);
+ const choices = await importer.list('/fixture');
+ expect(choices).toEqual([{ id: 'root', title: 'root', directory: '/fixture' }]);
+ expect(await importer.list('/other')).toEqual([]);
+ const id = await importer.importCopy(choices[0]!);
+ expect(id).not.toBe('root');
+ expect(payloads).toHaveLength(2);
+ expect(payloads[0]).toMatchObject({
+ info: { id, metadata: { varroLegacyImport: { sourceSessionID: 'root' } } },
+ });
+ const childID = asRecord(payloads[1]?.info)?.id;
+ expect(payloads[1]).toMatchObject({ info: { parentID: id } });
+ expect(payloads[0]).toMatchObject({
+ messages: [
+ {
+ content: [
+ {
+ name: 'subagent',
+ state: {
+ status: 'completed',
+ metadata: { sessionId: childID },
+ content: [{ type: 'text', text: 'Retained output' }],
+ },
+ },
+ ],
+ metadata: {
+ varroLegacy: {
+ info: { id: 'message-root', sessionID: 'root' },
+ parts: [{ state: { metadata: { sessionId: 'child' } } }],
+ },
+ },
+ },
+ ],
+ });
+ const source = new DatabaseSync(database, { readOnly: true });
+ expect(
+ JSON.stringify(
+ ['session', 'message', 'part'].map((table) =>
+ source.prepare(`SELECT * FROM ${table}`).all()
+ )
+ )
+ ).toBe(before);
+ source.close();
+ });
+
+ it('removes only newly imported copies when a descendant import fails', async () => {
+ const { database } = await fixture();
+ const created: string[] = [];
+ const deleted: string[] = [];
+ const request: ConstructorParameters[0] = vi.fn(
+ async (method, path, body) => {
+ if (method === 'GET') return { project: { id: 'project' } };
+ if (method === 'DELETE') {
+ deleted.push(path);
+ return {};
+ }
+ if (created.length) throw new Error('Import rejected');
+ created.push(String(asRecord(asRecord(body)?.info)?.id));
+ return {};
+ }
+ );
+ await expect(
+ new LegacySessionImport(request, database).importCopy({
+ id: 'root',
+ title: 'root',
+ directory: '/fixture',
+ })
+ ).rejects.toThrow('Import rejected');
+ expect(deleted).toEqual([`/api/session/${created[0]}`]);
+ expect(created[0]).not.toBe('root');
+ });
+});
diff --git a/src/extension/legacy-session-import.ts b/src/extension/legacy-session-import.ts
new file mode 100644
index 00000000..632271d3
--- /dev/null
+++ b/src/extension/legacy-session-import.ts
@@ -0,0 +1,312 @@
+/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- SQLite JSON and worker replies are decoded at the import boundary; opaque original records are retained without narrowing away v1-only fields. */
+import { randomBytes } from 'node:crypto';
+import { join } from 'node:path';
+import { Worker } from 'node:worker_threads';
+import { resolveOpenCodeDataDirectory } from '../shared/opencode-data-directory';
+import { asRecord, isString, type UnknownRecord } from '../shared/type-utils';
+import { v2Action, v2ModelRef } from './opencode-v2-projection';
+
+type Request = (method: string, path: string, body?: unknown) => Promise;
+export type LegacySessionChoice = { id: string; title: string; directory: string };
+
+/** Explicit copy import. All source database access is read-only and isolated in a bounded worker. */
+export class LegacySessionImport {
+ constructor(
+ private readonly request: Request,
+ private readonly databasePath = process.env.OPENCODE_DB ??
+ join(resolveOpenCodeDataDirectory(), 'opencode.db')
+ ) {}
+
+ async list(directory: string): Promise {
+ const result = await this.read(directory);
+ if (!Array.isArray(result)) throw new Error('Invalid legacy session catalog');
+ return result.map((value: unknown) => {
+ const row = asRecord(value);
+ if (!isString(row?.id) || !isString(row.directory)) throw new Error('Invalid legacy session');
+ return {
+ id: row.id,
+ directory: row.directory,
+ title: isString(row.title) ? row.title : 'Untitled',
+ };
+ });
+ }
+
+ async importCopy(choice: LegacySessionChoice): Promise {
+ const snapshot = await this.read(choice.directory, choice.id);
+ if (!Array.isArray(snapshot) || !snapshot.length)
+ throw new Error('The selected v1 session is no longer available');
+ const records = snapshot.map((value: unknown) => {
+ const record = asRecord(value);
+ const session = asRecord(record?.session);
+ if (!isString(session?.id) || !Array.isArray(record?.messages))
+ throw new Error('Invalid legacy session snapshot');
+ return { session, messages: record.messages };
+ });
+ const ids = new Map();
+ const id = (source: string, prefix: string) => {
+ if (!ids.has(source)) ids.set(source, `${prefix}_${randomBytes(16).toString('hex')}`);
+ return ids.get(source)!;
+ };
+ for (const record of records) {
+ id(String(record.session.id), 'ses');
+ for (const value of record.messages) {
+ const message = asRecord(value);
+ const info = asRecord(message?.info);
+ if (!isString(info?.id)) throw new Error('Legacy message is missing its ID');
+ id(info.id, 'msg');
+ }
+ }
+ const location = asRecord(
+ await this.request(
+ 'GET',
+ `/api/location?location[directory]=${encodeURIComponent(choice.directory)}`
+ )
+ );
+ const projectID = asRecord(location?.project)?.id;
+ if (!isString(projectID)) throw new Error('Could not resolve the destination v2 project');
+ const imported: string[] = [];
+ try {
+ for (const { session, messages } of records) {
+ const sessionID = ids.get(String(session.id))!;
+ const remap = (value: unknown): unknown => {
+ if (isString(value)) return ids.get(value) ?? value;
+ if (Array.isArray(value)) return value.map(remap);
+ const record = asRecord(value);
+ return record
+ ? Object.fromEntries(
+ Object.entries(record).map(([key, item]) => [
+ key,
+ key === 'varroLegacy' || key === 'varroLegacyImport' ? item : remap(item),
+ ])
+ )
+ : value;
+ };
+ const converted = messages.map((value: unknown) => convertMessage(value, ids));
+ // Retain the complete original records, including v1-only parts, in message metadata.
+ const payload = remap({
+ location: { directory: choice.directory },
+ info: {
+ id: sessionID,
+ parentID: isString(session.parent_id) ? ids.get(session.parent_id) : undefined,
+ projectID,
+ title: `${isString(session.title) ? session.title : 'Untitled'} (v1 copy)`,
+ location: { directory: choice.directory },
+ agent: session.agent ?? undefined,
+ model: v2ModelRef(parseJson(session.model)),
+ time: { created: session.time_created, updated: Date.now() },
+ cost: session.cost ?? 0,
+ tokens: {
+ input: session.tokens_input ?? 0,
+ output: session.tokens_output ?? 0,
+ reasoning: session.tokens_reasoning ?? 0,
+ cache: {
+ read: session.tokens_cache_read ?? 0,
+ write: session.tokens_cache_write ?? 0,
+ },
+ },
+ metadata: {
+ varroLegacyImport: {
+ sourceSessionID: session.id,
+ source: session,
+ importedAt: Date.now(),
+ },
+ },
+ },
+ messages: converted,
+ });
+ await this.request('POST', '/api/experimental/session/import', payload);
+ imported.push(sessionID);
+ }
+ } catch (error) {
+ const cleanup = await Promise.allSettled(
+ imported
+ .toReversed()
+ .map((sessionID) => this.request('DELETE', `/api/session/${sessionID}`))
+ );
+ const remaining = imported
+ .toReversed()
+ .filter((_, index) => cleanup[index]?.status === 'rejected');
+ if (remaining.length)
+ throw new Error(`Import failed; incomplete copies remain: ${remaining.join(', ')}`, {
+ cause: error,
+ });
+ throw error;
+ }
+ return ids.get(choice.id)!;
+ }
+
+ private read(directory: string, sessionID?: string): Promise {
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(LEGACY_READER, {
+ eval: true,
+ workerData: { databasePath: this.databasePath, directory, sessionID },
+ });
+ const timer = setTimeout(() => {
+ void worker.terminate();
+ reject(new Error('Reading v1 history timed out'));
+ }, 10_000);
+ worker.once('message', (value: unknown) => {
+ clearTimeout(timer);
+ const result = asRecord(value);
+ if (isString(result?.error)) reject(new Error(result.error));
+ else resolve(result?.data);
+ });
+ worker.once('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ worker.once('exit', (code) => {
+ clearTimeout(timer);
+ if (code !== 0) reject(new Error(`Legacy history reader exited with code ${code}`));
+ });
+ });
+ }
+}
+
+function parseJson(value: unknown): unknown {
+ return isString(value) ? JSON.parse(value) : value;
+}
+
+function convertMessage(value: unknown, ids: Map): UnknownRecord {
+ const entry = asRecord(value);
+ const info = asRecord(entry?.info);
+ if (!info || !isString(info.id) || !Array.isArray(entry?.parts))
+ throw new Error('Invalid legacy message');
+ const parts = entry.parts.map((part: unknown) => asRecord(part) ?? {});
+ const time = asRecord(info.time) ?? {};
+ const base = { id: ids.get(info.id), metadata: { varroLegacy: entry } };
+ if (info.role === 'user') {
+ const files = parts
+ .filter((part) => part.type === 'file')
+ .flatMap((part) => {
+ const match = isString(part.url) ? /^data:([^;,]+);base64,([\s\S]*)$/.exec(part.url) : null;
+ return match
+ ? [{ mime: match[1], data: match[2], name: part.filename, source: { type: 'inline' } }]
+ : [];
+ });
+ const text = parts.flatMap((part) =>
+ part.type === 'text'
+ ? [part.text]
+ : part.type === 'file' && isString(part.url) && !part.url.startsWith('data:')
+ ? [`[File attachment: ${String(part.filename ?? part.url)}]`]
+ : []
+ );
+ return { ...base, type: 'user', time: { created: time.created }, text: text.join('\n'), files };
+ }
+ if (info.role !== 'assistant')
+ throw new Error(`Unsupported legacy message role: ${String(info.role)}`);
+ return {
+ ...base,
+ type: 'assistant',
+ time: { ...time, completed: time.completed ?? time.created },
+ agent: info.agent ?? info.mode ?? 'build',
+ model: { providerID: info.providerID, id: info.modelID },
+ finish: time.completed ? info.finish : 'error',
+ cost: info.cost,
+ tokens: info.tokens,
+ error: info.error
+ ? {
+ type: 'unknown',
+ message: asRecord(asRecord(info.error)?.data)?.message ?? 'Imported assistant error',
+ }
+ : undefined,
+ content: parts.flatMap((part): UnknownRecord[] => {
+ if (part.type === 'text' || part.type === 'reasoning') {
+ const timing = asRecord(part.time);
+ return [
+ {
+ type: part.type,
+ text: part.text ?? '',
+ time:
+ part.type === 'reasoning'
+ ? {
+ created: timing?.start ?? time.created,
+ completed: timing?.end ?? time.completed ?? time.created,
+ }
+ : undefined,
+ },
+ ];
+ }
+ if (part.type !== 'tool') return [];
+ const state = asRecord(part.state) ?? {};
+ const timing = asRecord(state.time) ?? {};
+ const completed = state.status === 'completed';
+ return [
+ {
+ type: 'tool',
+ id: part.callID ?? part.id,
+ name: v2Action(String(part.tool)),
+ time: {
+ created: timing.start ?? time.created,
+ ran: timing.start,
+ completed: timing.end ?? time.completed ?? time.created,
+ },
+ state: completed
+ ? {
+ status: 'completed',
+ input: state.input ?? {},
+ metadata: state.metadata,
+ content: [
+ {
+ type: 'text',
+ text: isString(state.output)
+ ? state.output
+ : JSON.stringify(state.output ?? ''),
+ },
+ ],
+ }
+ : {
+ status: 'error',
+ input: state.input ?? {},
+ metadata: state.metadata,
+ error: {
+ type: 'unknown',
+ message: isString(state.error)
+ ? state.error
+ : 'Tool was unfinished in the imported v1 snapshot',
+ },
+ },
+ },
+ ];
+ }),
+ };
+}
+
+const LEGACY_READER = String.raw`
+const { parentPort, workerData } = require('node:worker_threads');
+const { DatabaseSync } = require('node:sqlite');
+let db;
+try {
+ db = new DatabaseSync(workerData.databasePath, { readOnly: true });
+ db.exec('BEGIN');
+ if (!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='session'").get()) {
+ parentPort.postMessage({ data: [] });
+ } else if (!workerData.sessionID) {
+ parentPort.postMessage({ data: db.prepare('SELECT id,title,directory FROM session WHERE directory=? AND parent_id IS NULL ORDER BY time_updated DESC LIMIT 1000').all(workerData.directory) });
+ } else {
+ const rows = db.prepare('WITH RECURSIVE tree(id,depth) AS (SELECT id,0 FROM session WHERE id=? AND directory=? UNION ALL SELECT s.id,t.depth+1 FROM session s JOIN tree t ON s.parent_id=t.id WHERE t.depth<32 AND s.directory=?) SELECT s.* FROM tree t JOIN session s ON s.id=t.id ORDER BY t.depth LIMIT 101').all(workerData.sessionID, workerData.directory, workerData.directory);
+ if (rows.length > 100) throw new Error('The selected session tree is too large to import');
+ let bytes = 0;
+ const data = rows.map(session => {
+ const messages = db.prepare('SELECT * FROM message WHERE session_id=? ORDER BY time_created,id LIMIT 10001').all(session.id);
+ const parts = db.prepare('SELECT * FROM part WHERE session_id=? ORDER BY time_created,id LIMIT 100001').all(session.id);
+ if (messages.length > 10000 || parts.length > 100000) throw new Error('The selected history is too large to import');
+ const byMessage = new Map();
+ for (const part of parts) {
+ bytes += Buffer.byteLength(part.data);
+ if (bytes > 32 * 1024 * 1024) throw new Error('The selected history exceeds the 32 MiB import limit');
+ if (!byMessage.has(part.message_id)) byMessage.set(part.message_id, []);
+ byMessage.get(part.message_id).push({ ...JSON.parse(part.data), id: part.id, messageID: part.message_id, sessionID: session.id });
+ }
+ return { session, messages: messages.map(message => {
+ bytes += Buffer.byteLength(message.data);
+ if (bytes > 32 * 1024 * 1024) throw new Error('The selected history exceeds the 32 MiB import limit');
+ return { info: { ...JSON.parse(message.data), id: message.id, sessionID: session.id }, parts: byMessage.get(message.id) ?? [] };
+ }) };
+ });
+ parentPort.postMessage({ data });
+ }
+ db.exec('ROLLBACK');
+} catch (error) { parentPort.postMessage({ error: error.message }); }
+finally { db?.close(); }
+`;
diff --git a/src/extension/message-router.test.ts b/src/extension/message-router.test.ts
index c3fa7073..e5f3db0c 100644
--- a/src/extension/message-router.test.ts
+++ b/src/extension/message-router.test.ts
@@ -39,6 +39,7 @@ function createCallbacks(): MessageRouterCallbacks {
openSessionInOpenCode: vi.fn(),
openSessionInEditor: vi.fn(),
openSessionInSidebar: vi.fn(),
+ importLegacySession: vi.fn(() => Promise.resolve()),
openNewEditor: vi.fn(),
openNewWindow: vi.fn(),
editorRouteChanged: vi.fn(),
@@ -521,6 +522,7 @@ const DISPATCH_EXPECTATIONS = {
],
'session/open-in-sidebar': [{ callback: 'openSessionInSidebar', args: ['session-1'] }],
'session/open-in-opencode': [{ callback: 'openSessionInOpenCode', args: ['session-1'] }],
+ 'session/import-v1': [{ callback: 'importLegacySession', args: ['session-1', '/workspace'] }],
'editor/route-changed': [
{ callback: 'editorRouteChanged', args: [{ type: 'session', sessionId: 'session-1' }] },
],
diff --git a/src/extension/message-router.ts b/src/extension/message-router.ts
index aebf1c2c..bd9d51a8 100644
--- a/src/extension/message-router.ts
+++ b/src/extension/message-router.ts
@@ -83,6 +83,7 @@ export interface MessageRouterCallbacks {
inWindow?: boolean
): void | Promise;
openSessionInSidebar(sessionId: string, directory?: string): void | Promise;
+ importLegacySession(sessionId: string, directory: string): Promise;
openNewEditor(): void | Promise;
openNewWindow(): void | Promise;
editorRouteChanged(
@@ -267,6 +268,9 @@ export class MessageRouter {
? this.callbacks.openSessionInSidebar(msg.payload.sessionId, msg.payload.directory)
: this.callbacks.openSessionInSidebar(msg.payload.sessionId));
break;
+ case 'session/import-v1':
+ await this.callbacks.importLegacySession(msg.payload.sessionId, msg.payload.directory);
+ break;
case 'chat/new-editor':
await this.callbacks.openNewEditor();
break;
diff --git a/src/extension/open-code-process.test.ts b/src/extension/open-code-process.test.ts
index 53386dfe..17d64b35 100644
--- a/src/extension/open-code-process.test.ts
+++ b/src/extension/open-code-process.test.ts
@@ -16,6 +16,7 @@ import { tmpdir } from 'os';
import { dirname, join } from 'path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as ServerUtils from './server-utils';
+import { Service } from '@opencode/client/service';
const { loggerMock, spawnMock, vscodeMock, waitForProcessExitMock } = vi.hoisted(() => ({
loggerMock: {
@@ -42,6 +43,7 @@ const { loggerMock, spawnMock, vscodeMock, waitForProcessExitMock } = vi.hoisted
}));
vi.mock('vscode', () => vscodeMock);
+vi.mock('@opencode/client/service', () => ({ Service: { discover: vi.fn() } }));
vi.mock('./logger', () => ({ logger: loggerMock }));
vi.mock('child_process', () => ({ spawn: spawnMock, default: { spawn: spawnMock } }));
vi.mock('cross-spawn', () => ({ default: spawnMock, spawn: spawnMock }));
@@ -84,7 +86,151 @@ describe('appendBoundedCliOutput', () => {
});
});
+describe('v2 shared service routing', () => {
+ it('uses the registered service port and credentials without spawning a second runner', async () => {
+ const manager = new OpenCodeProcess(4096, true, 'opencode2');
+ manager.rememberInstalledCliVersion('2.0.6');
+ vi.mocked(Service.discover).mockResolvedValue({
+ url: 'http://127.0.0.1:43123',
+ auth: { type: 'basic', username: 'opencode', password: 'fixture-password' },
+ });
+
+ expect(await manager.discoverSharedServer()).toBe(true);
+ expect(manager.url).toBe('http://127.0.0.1:43123');
+ expect(manager.serverAuthorization).toBe(
+ `Basic ${Buffer.from('opencode:fixture-password').toString('base64')}`
+ );
+ expect(spawnMock).not.toHaveBeenCalled();
+ expect(manager.managedProcess).toBe(false);
+ });
+
+ it('does not discover a v2 service for a v1 CLI', async () => {
+ const manager = new OpenCodeProcess(4096, true, 'opencode');
+ manager.rememberInstalledCliVersion('1.18.31');
+ expect(await manager.discoverSharedServer()).toBe(false);
+ expect(Service.discover).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {
+ name: 'matching legacy service',
+ host: '127.0.0.1',
+ pid: process.pid,
+ version: '2.0.5',
+ status: 200,
+ expected: true,
+ },
+ {
+ name: 'different process',
+ host: '127.0.0.1',
+ pid: process.pid + 1,
+ version: '2.0.5',
+ status: 200,
+ expected: false,
+ },
+ {
+ name: 'different version',
+ host: '127.0.0.1',
+ pid: process.pid,
+ version: '2.0.6',
+ status: 200,
+ expected: false,
+ },
+ {
+ name: 'rejected credentials',
+ host: '127.0.0.1',
+ pid: process.pid,
+ version: '2.0.5',
+ status: 401,
+ expected: false,
+ },
+ {
+ name: 'remote registration',
+ host: 'example.com',
+ pid: process.pid,
+ version: '2.0.5',
+ status: 200,
+ expected: false,
+ },
+ ])(
+ 'validates $name when the newer client cannot discover it',
+ async ({ host, pid, version, status, expected }) => {
+ const root = await mkdtemp(join(tmpdir(), 'varro-legacy-discovery-'));
+ await mkdir(join(root, 'opencode'));
+ const registration = JSON.stringify({
+ url: `http://${host}:43123`,
+ pid: process.pid,
+ version: '2.0.5',
+ password: 'legacy-fixture-password',
+ });
+ const path = join(root, 'opencode/service.json');
+ await writeFile(path, registration);
+ vi.stubEnv('XDG_STATE_HOME', root);
+ vi.mocked(Service.discover).mockResolvedValue(undefined);
+ const fetchMock = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(JSON.stringify({ pid, version }), { status }));
+ try {
+ const manager = new OpenCodeProcess(
+ 4096,
+ true,
+ 'opencode2',
+ false,
+ undefined,
+ join(root, 'lease.json')
+ );
+ manager.rememberInstalledCliVersion('2.0.6');
+ expect(await manager.discoverSharedServer()).toBe(expected);
+ expect(manager.port).toBe(expected ? 43123 : 4096);
+ if (host === '127.0.0.1') {
+ expect(fetchMock).toHaveBeenCalledWith(
+ new URL('http://127.0.0.1:43123/api/status'),
+ expect.objectContaining({
+ headers: {
+ Authorization: `Basic ${Buffer.from('opencode:legacy-fixture-password').toString('base64')}`,
+ },
+ redirect: 'error',
+ signal: expect.any(AbortSignal),
+ })
+ );
+ } else expect(fetchMock).not.toHaveBeenCalled();
+ expect(await readFile(path, 'utf8')).toBe(registration);
+ expect(spawnMock).not.toHaveBeenCalled();
+ expect(manager.managedProcess).toBe(false);
+ } finally {
+ vi.unstubAllEnvs();
+ await rm(root, { recursive: true, force: true });
+ }
+ }
+ );
+
+ it('registers a new v2 server for nested CLI discovery', () => {
+ const child = Object.assign(new EventEmitter(), {
+ stdout: new EventEmitter(),
+ stderr: new EventEmitter(),
+ exitCode: null,
+ signalCode: null,
+ });
+ spawnMock.mockReturnValue(child);
+ const manager = new OpenCodeProcess(4096, true, 'opencode2');
+ manager.rememberInstalledCliVersion('2.0.6');
+ manager.launchServer({
+ getWorkspaceCwd: () => '/repo',
+ onStdout: vi.fn(),
+ onStderr: vi.fn(),
+ onExit: vi.fn(),
+ onError: vi.fn(),
+ });
+ expect(spawnMock).toHaveBeenCalledWith(
+ manager.resolveCommand(),
+ ['serve', '--service', '--port', '4096'],
+ expect.anything()
+ );
+ });
+});
+
beforeEach(() => {
+ vi.mocked(Service.discover).mockReset();
delete process.env.OPENCODE_CONFIG;
delete process.env.OPENCODE_CONFIG_CONTENT;
delete process.env.XDG_CONFIG_HOME;
@@ -439,6 +585,74 @@ describe('OpenCodeProcess Windows termination', () => {
});
describe('OpenCodeProcess update notification actions', () => {
+ it.each([
+ ['1.14.20', '1.14.22', 'opencode-ai'],
+ ['2.0.0', '2.0.1', '@opencode%2Fcli'],
+ ])('checks the registry for selected CLI %s', async (installed, latest, packageName) => {
+ const manager = new OpenCodeProcess(4096, false);
+ // A stale cache must not override the version passed by maintenance.
+ manager.rememberInstalledCliVersion(installed.startsWith('1.') ? '2.0.0' : '1.14.20');
+ const fetchMock = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(JSON.stringify({ version: latest })));
+
+ await expect(manager.readLatestCliVersion(installed)).resolves.toBe(latest);
+ expect(fetchMock).toHaveBeenCalledWith(
+ `https://registry.npmjs.org/${packageName}/latest`,
+ expect.any(Object)
+ );
+ });
+
+ it('does not check for updates when no CLI is installed', async () => {
+ const manager = new OpenCodeProcess(4096, false);
+ vi.spyOn(manager, 'readInstalledCliVersion').mockResolvedValue(null);
+ const fetchMock = vi.spyOn(globalThis, 'fetch');
+ await expect(manager.readLatestCliVersion()).resolves.toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a registry release from another major version', async () => {
+ const manager = new OpenCodeProcess(4096, false);
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ version: '2.0.1' }))
+ );
+ await expect(manager.readLatestCliVersion('1.14.20')).resolves.toBeNull();
+ });
+
+ it('does not promote or automatically upgrade v1 to v2', async () => {
+ const manager = new OpenCodeProcess(4096, false, '/custom/opencode-v1');
+ const upgradeRunningServer = vi.fn();
+ const upgradeCli = vi.spyOn(manager, 'upgradeCli');
+ await manager.maybeSuggestCliUpdate('1.14.20', {
+ readLatestCliVersion: vi.fn().mockResolvedValue('2.0.1'),
+ upgradeRunningServer,
+ requestMaintenanceCheck: vi.fn(),
+ getWorkspaceCwd: () => undefined,
+ prepareForWindowsCliUpgrade: vi.fn(),
+ });
+ expect(upgradeRunningServer).not.toHaveBeenCalled();
+ expect(upgradeCli).not.toHaveBeenCalled();
+ expect(vscodeMock.window.showInformationMessage).not.toHaveBeenCalled();
+ });
+
+ it('automatically updates the selected v2 CLI', async () => {
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ const manager = new OpenCodeProcess(4096, false, '/custom/opencode2');
+ const upgradeCli = vi.spyOn(manager, 'upgradeCli').mockResolvedValue('');
+ vi.spyOn(manager, 'readInstalledCliVersion').mockResolvedValue('2.0.1');
+ await expect(
+ manager.maybeSuggestCliUpdate('2.0.0', {
+ readLatestCliVersion: vi.fn().mockResolvedValue('2.0.1'),
+ upgradeRunningServer: vi.fn().mockResolvedValue(false),
+ requestMaintenanceCheck: vi.fn(),
+ getWorkspaceCwd: () => undefined,
+ prepareForWindowsCliUpgrade: vi.fn(),
+ })
+ ).resolves.toBe('2.0.1');
+ expect(upgradeCli).toHaveBeenCalledWith('2.0.1');
+ expect(vscodeMock.window.showInformationMessage).not.toHaveBeenCalled();
+ });
+
it('logs a rejected update action chain instead of leaving it unhandled', async () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
vscodeMock.window.showInformationMessage.mockResolvedValueOnce('Run Upgrade');
@@ -2666,6 +2880,55 @@ describe('OpenCodeProcess config ownership', () => {
});
describe('OpenCodeProcess install resolution', () => {
+ it.each([
+ ['darwin', ''],
+ ['linux', ''],
+ ['win32', '.exe'],
+ ['win32', '.cmd'],
+ ['win32', '.bat'],
+ ])('prefers v2 across search directories on %s with suffix %s', async (platform, suffix) => {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ const directory = await mkdtemp(join(tmpdir(), 'varro-opencode-discovery-'));
+ const v1Directory = join(directory, 'v1');
+ const v2Directory = join(directory, 'v2');
+ await mkdir(v1Directory);
+ await mkdir(v2Directory);
+ const v1 = join(v1Directory, `opencode${suffix}`);
+ const v2 = join(v2Directory, `opencode2${suffix}`);
+ await writeFile(v1, '');
+ await writeFile(v2, '');
+ const manager = new OpenCodeProcess(4096, true, ' ');
+ vi.spyOn(
+ manager as unknown as { serverPathEntries(): string[] },
+ 'serverPathEntries'
+ ).mockReturnValue([v1Directory, v2Directory]);
+ try {
+ expect(manager.resolveCommandInfo()).toEqual({ command: v2, found: true });
+
+ manager.updateLaunchSettings({ autoStart: true, command: 'opencode' });
+ expect(manager.resolveCommandInfo()).toEqual({ command: v1, found: true });
+
+ manager.updateLaunchSettings({ autoStart: true, command: v1 });
+ expect(manager.resolveCommandInfo()).toEqual({ command: v1, found: true });
+
+ manager.updateLaunchSettings({ autoStart: true, command: '' });
+ expect(manager.resolveCommandInfo()).toEqual({ command: v2, found: true });
+
+ await rm(v2);
+ manager.clearResolvedCommandCache();
+ expect(manager.resolveCommandInfo()).toEqual({ command: v1, found: true });
+
+ await rm(v1);
+ manager.clearResolvedCommandCache();
+ expect(manager.resolveCommandInfo()).toEqual({
+ command: platform === 'win32' ? 'opencode.cmd' : 'opencode',
+ found: false,
+ });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
it('reports a configured path that does not exist as missing', () => {
const missingPath = join(tmpdir(), 'varro-missing-opencode-binary');
const manager = new OpenCodeProcess(4096, true, missingPath);
diff --git a/src/extension/open-code-process.ts b/src/extension/open-code-process.ts
index 517052d8..ecb129cd 100644
--- a/src/extension/open-code-process.ts
+++ b/src/extension/open-code-process.ts
@@ -4,6 +4,8 @@ import type { ChildProcess, SpawnOptions } from 'child_process';
import { spawn } from 'child_process';
import { randomBytes } from 'crypto';
import crossSpawn from 'cross-spawn';
+import { Service } from '@opencode/client/service';
+import type { Endpoint } from '@opencode/client/service';
import type { Dirent } from 'fs';
import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
import {
@@ -29,15 +31,22 @@ import {
describeUpgradeFailure,
detectInstallMethod,
getRecoveryCommand,
+ OPENCODE_INSTALL_COMMAND,
type OpenCodeInstallMethod,
type OpenCodeUpgradeFailureKind,
} from '../shared/opencode-install';
import type { ServerStatus } from '../shared/protocol';
+import { asRecord } from '../shared/type-utils';
import {
parseManagedServerOwnershipLease,
type ManagedServerOwnershipLease,
} from '../shared/server-ownership';
import { logger } from './logger';
+import {
+ basicAuthorization,
+ OpenCodeStartupOutput,
+ openCodeApiVersion,
+} from './opencode-connection';
import {
compareVersions,
extractVersion,
@@ -45,6 +54,7 @@ import {
waitForProcessExit,
} from './server-utils';
import { buildServerEnv, getServerPathEntries } from './util/server-path';
+import { runWindowsCliUpdate } from './util/windows-cli-update';
const CLI_OUTPUT_MAX_CHARS = 1024 * 1024;
const CLI_OUTPUT_TRUNCATED_MARKER = '[earlier output truncated]\n';
@@ -936,8 +946,7 @@ export function sweepStaleInjectedConfigDirectories(now = Date.now()): Promise {
+ if (openCodeApiVersion(this.installedCliVersionCache?.value ?? '') !== 2) return false;
+ return Service.discover({
+ version: (version) => openCodeApiVersion(version) === 2,
+ }).then(async (discovered) => {
+ const endpoint = discovered ?? (await this.discoverLegacySharedServer());
+ if (!endpoint) return false;
+ const url = new URL(endpoint.url);
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || !url.port) return false;
+ this._port = validateServerPort(Number(url.port));
+ this.serverPassword = endpoint.auth?.password;
+ this.credentialUrl = this.url;
+ return true;
+ });
+ }
+
+ private async discoverLegacySharedServer(): Promise {
+ // The 2.0.6 client rejects 2.0.5 registrations because that release uses /api/status.
+ const path = join(
+ process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'),
+ 'opencode',
+ 'service.json'
+ );
+ try {
+ const registration = asRecord(JSON.parse(await readFile(path, 'utf8')));
+ if (
+ registration?.version !== '2.0.5' ||
+ typeof registration.url !== 'string' ||
+ typeof registration.pid !== 'number' ||
+ !Number.isSafeInteger(registration.pid) ||
+ registration.pid <= 0 ||
+ typeof registration.password !== 'string' ||
+ !registration.password ||
+ registration.password.length > 4096
+ )
+ return undefined;
+ const url = new URL(registration.url);
+ if (
+ url.protocol !== 'http:' ||
+ url.hostname !== '127.0.0.1' ||
+ !url.port ||
+ url.username ||
+ url.password
+ )
+ return undefined;
+ process.kill(registration.pid, 0);
+ const response = await fetch(new URL('/api/status', url), {
+ headers: { Authorization: basicAuthorization(registration.password) },
+ redirect: 'error',
+ signal: AbortSignal.timeout(3000),
+ });
+ if (!response.ok) return undefined;
+ const status = asRecord(await response.json());
+ if (status?.pid !== registration.pid || status.version !== registration.version)
+ return undefined;
+ return {
+ url: url.origin,
+ auth: { type: 'basic', username: 'opencode', password: registration.password },
+ };
+ } catch {
+ // A missing, stale, or unhealthy legacy registration is not an attachable service.
+ return undefined;
+ }
+ }
+
+ get serverAuthorization(): string | undefined {
+ if (this.serverPassword && this.credentialUrl === this.url)
+ return basicAuthorization(this.serverPassword);
+ const password = process.env.OPENCODE_SERVER_PASSWORD;
+ return password
+ ? basicAuthorization(password, process.env.OPENCODE_SERVER_USERNAME)
+ : undefined;
+ }
+
+ async discoverServerCredentials(): Promise {
+ const lease = this.ownershipLeaseCandidate ?? this.ownershipLease;
+ if (lease?.password && lease.port === this._port && (await this.matchesOwnershipLease(lease))) {
+ this.serverPassword = lease.password;
+ this.credentialUrl = this.url;
+ return;
+ }
+ // The released v2 client discovers credentials from this registration file.
+ // Read only a registration for our target; never ensure/restart the user's service.
+ const path = join(
+ process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'),
+ 'opencode',
+ 'service.json'
+ );
+ try {
+ const registration = JSON.parse(await readFile(path, 'utf8')) as {
+ url?: unknown;
+ password?: unknown;
+ pid?: unknown;
+ };
+ if (
+ registration.url !== this.url ||
+ typeof registration.password !== 'string' ||
+ !registration.password ||
+ registration.password.length > 4096
+ )
+ return;
+ if (typeof registration.pid !== 'number' || registration.pid <= 0) return;
+ process.kill(registration.pid, 0);
+ this.serverPassword = registration.password;
+ this.credentialUrl = this.url;
+ } catch {
+ // No live registered service for this endpoint; managed launches provide their own credential.
+ }
+ }
private readonly ownershipMarkerPath: string;
constructor(
@@ -1521,6 +1641,8 @@ export class OpenCodeProcess {
createdAt: Date.now(),
};
if (launch.configPath) lease.configPath = launch.configPath;
+ if (this.serverPassword && this.credentialUrl === this.url)
+ lease.password = this.serverPassword;
try {
await this.writeOwnershipMarker(lease);
launch.ownershipMarkerWritten = true;
@@ -1787,7 +1909,18 @@ export class OpenCodeProcess {
}
const command = this.resolveCommand();
- const args = ['serve', '--port', String(this._port)];
+ // Register v2 launches so a CLI invoked by a tool joins this server instead of
+ // starting another runner against the same session database.
+ const args = [
+ 'serve',
+ ...(openCodeApiVersion(this.installedCliVersionCache?.value ?? '') === 2
+ ? ['--service']
+ : []),
+ '--port',
+ String(this._port),
+ ];
+ this.serverPassword = undefined;
+ this.credentialUrl = undefined;
logger.info(`Starting OpenCode server with command: ${command}`);
const configPath = this.injectedConfigPath;
@@ -1831,9 +1964,22 @@ export class OpenCodeProcess {
}
this._managedProcess = true;
+ const capturePassword = (password: string) => {
+ if (this._process !== proc) return;
+ this.serverPassword = password;
+ this.credentialUrl = this.url;
+ };
+ const stdout = new OpenCodeStartupOutput(capturePassword);
+ const stderr = new OpenCodeStartupOutput(capturePassword);
const listeners: ProcessListeners = {
- stdout: callbacks.onStdout,
- stderr: callbacks.onStderr,
+ stdout: (data) => {
+ const text = stdout.write(data);
+ if (text.length) callbacks.onStdout(text);
+ },
+ stderr: (data) => {
+ const text = stderr.write(data);
+ if (text.length) callbacks.onStderr(text);
+ },
exit: (code, signal) => callbacks.onExit(proc, code, signal),
error: (err) => callbacks.onError(proc, err),
};
@@ -2726,7 +2872,10 @@ export class OpenCodeProcess {
return null;
}
this.lastCliUpdateCheckAt = now;
- if (compareVersions(latestCliVersion, installedCliVersion) <= 0) {
+ if (
+ openCodeApiVersion(latestCliVersion) !== openCodeApiVersion(installedCliVersion) ||
+ compareVersions(latestCliVersion, installedCliVersion) <= 0
+ ) {
return null;
}
@@ -2758,7 +2907,7 @@ export class OpenCodeProcess {
return null;
}
- const upgradeCommand = OpenCodeProcess.CLI_UPGRADE_COMMAND;
+ const upgradeCommand = this.cliUpgradeCommand(latestCliVersion);
const message = `OpenCode CLI ${latestCliVersion} is available (installed: ${installedCliVersion}). Update with: ${upgradeCommand}`;
logger.info(message);
void Promise.resolve(
@@ -2789,12 +2938,16 @@ export class OpenCodeProcess {
const cause = err instanceof Error ? err.message : String(err);
const { installMethod } = this.getInstallInfo();
const kind = classifyUpgradeFailure(cause, process.platform);
+ const packageName =
+ openCodeApiVersion(this.installedCliVersionCache?.value ?? '') === 2
+ ? '@opencode/cli'
+ : 'opencode-ai';
return {
cause,
kind,
installMethod,
- guidance: describeUpgradeFailure(kind, installMethod, process.platform),
- suggestedCommand: getRecoveryCommand(kind, installMethod, process.platform),
+ guidance: describeUpgradeFailure(kind, installMethod, process.platform, packageName),
+ suggestedCommand: getRecoveryCommand(kind, installMethod, process.platform, packageName),
};
}
@@ -2889,16 +3042,20 @@ export class OpenCodeProcess {
}
}
- async readLatestCliVersion(): Promise {
+ async readLatestCliVersion(installedVersion?: string | null): Promise {
try {
- const res = await fetch('https://registry.npmjs.org/opencode-ai/latest', {
+ const version = installedVersion ?? (await this.readInstalledCliVersion());
+ if (!version) return null;
+ const packageName = openCodeApiVersion(version) === 2 ? '@opencode%2Fcli' : 'opencode-ai';
+ const res = await fetch(`https://registry.npmjs.org/${packageName}/latest`, {
signal: AbortSignal.timeout(OpenCodeProcess.CLI_REGISTRY_TIMEOUT_MS),
});
if (!res.ok) {
throw new Error(`Failed to fetch latest OpenCode CLI version: ${res.status}`);
}
const data = (await res.json()) as { version?: unknown };
- return typeof data.version === 'string' ? extractVersion(data.version) : null;
+ const latest = typeof data.version === 'string' ? extractVersion(data.version) : null;
+ return latest && openCodeApiVersion(latest) === openCodeApiVersion(version) ? latest : null;
} catch (err) {
logger.warn(
`Failed to check for OpenCode CLI updates: ${err instanceof Error ? err.message : String(err)}`
@@ -2977,7 +3134,18 @@ export class OpenCodeProcess {
if (process.platform === 'win32') {
await callbacks.prepareForWindowsCliUpgrade(targetVersion);
}
- await this.runInTerminal(OpenCodeProcess.CLI_UPGRADE_COMMAND, 'OpenCode Upgrade', callbacks);
+ await this.runInTerminal(
+ this.cliUpgradeCommand(targetVersion),
+ 'OpenCode Upgrade',
+ callbacks,
+ true
+ );
+ }
+
+ private cliUpgradeCommand(targetVersion: string): string {
+ const command = this.resolveCommand();
+ const quoted = `'${command.replace(/'/g, process.platform === 'win32' ? "''" : "'\\''")}'`;
+ return `${process.platform === 'win32' ? '& ' : ''}${quoted} upgrade ${targetVersion}`;
}
resolveCommand(): string {
@@ -3033,17 +3201,18 @@ export class OpenCodeProcess {
};
}
- const candidates =
- process.platform === 'win32'
- ? ['opencode.exe', 'opencode.cmd', 'opencode.bat']
- : ['opencode'];
-
- for (const dir of this.serverPathEntries()) {
- for (const candidate of candidates) {
- const fullPath = join(dir, candidate);
- if (existsSync(fullPath)) {
- this.resolvedCommandCache = { key: cacheKey, value: fullPath, found: true };
- return { command: fullPath, found: true };
+ const directories = this.serverPathEntries();
+ // Prefer the v2 CLI across all install locations before falling back to v1.
+ for (const name of ['opencode2', 'opencode']) {
+ const candidates =
+ process.platform === 'win32' ? [`${name}.exe`, `${name}.cmd`, `${name}.bat`] : [name];
+ for (const dir of directories) {
+ for (const candidate of candidates) {
+ const fullPath = join(dir, candidate);
+ if (existsSync(fullPath)) {
+ this.resolvedCommandCache = { key: cacheKey, value: fullPath, found: true };
+ return { command: fullPath, found: true };
+ }
}
}
}
@@ -3215,27 +3384,28 @@ export class OpenCodeProcess {
callbacks: {
getWorkspaceCwd: () => string | undefined;
finishWindowsCliUpgrade?: () => void | Promise;
- }
+ },
+ usePowerShell = false
) {
const text = command.trim();
if (!text) return;
try {
- const terminal = vscode.window.createTerminal({
- name: title,
- cwd: callbacks.getWorkspaceCwd(),
- });
if (process.platform === 'win32' && callbacks.finishWindowsCliUpgrade) {
- const disposable = vscode.window.onDidCloseTerminal((closedTerminal) => {
- if (closedTerminal !== terminal) return;
- disposable.dispose();
- void Promise.resolve(callbacks.finishWindowsCliUpgrade?.()).catch((err: unknown) => {
- logger.warn(
- `Failed to finish Windows OpenCode CLI update: ${err instanceof Error ? err.message : String(err)}`
- );
- });
- });
+ await runWindowsCliUpdate(
+ text,
+ title,
+ callbacks.getWorkspaceCwd(),
+ callbacks.finishWindowsCliUpgrade
+ );
+ return;
}
+ const options: vscode.TerminalOptions = {
+ name: title,
+ cwd: callbacks.getWorkspaceCwd(),
+ };
+ if (usePowerShell && process.platform === 'win32') options.shellPath = 'powershell.exe';
+ const terminal = vscode.window.createTerminal(options);
terminal.show(false);
terminal.sendText(text, true);
} catch (err) {
diff --git a/src/extension/open-code-transport.test.ts b/src/extension/open-code-transport.test.ts
index 232ed258..55fa2c22 100644
--- a/src/extension/open-code-transport.test.ts
+++ b/src/extension/open-code-transport.test.ts
@@ -153,6 +153,51 @@ afterEach(() => {
vi.useRealTimers();
});
+describe('v1 session compatibility', () => {
+ it.each(['/session?limit=100', '/session/parent/children'])(
+ 'hides v2 headers in %s without hiding empty or older sessions',
+ async (path) => {
+ const visible = [
+ { id: 'legacy', version: '1.18.31' },
+ { id: 'old', version: '0.15.0' },
+ { id: 'dev', version: 'dev' },
+ { id: 'empty' },
+ ];
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json([...visible, { id: 'v2', version: '2.0.6' }])
+ );
+ expect(await createTransport().request('GET', path)).toEqual(visible);
+ }
+ );
+
+ it('preserves the next cursor when an entire page is incompatible', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ Response.json([{ id: 'v2', version: '2.0.6' }], { headers: { 'x-next-cursor': 'next-page' } })
+ );
+ expect(
+ await createTransport().request('GET', '/session?limit=1', undefined, {
+ captureNextCursor: true,
+ })
+ ).toEqual({ data: [], nextCursor: 'next-page' });
+ });
+
+ it.each(['session.created', 'session.updated'])(
+ 'does not reintroduce incompatible sessions through %s events',
+ async (type) => {
+ const transport = createTransport();
+ const event = { type, properties: { info: { id: 'v2', version: '2.0.6' } } };
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) =>
+ createEventResponse(init!.signal!, event)
+ );
+ const started = transport.startEventStream();
+ await vi.waitFor(() => expect(updateEventStreamStateMock).toHaveBeenCalledWith('healthy'));
+ transport.stopEventStream();
+ await started;
+ expect(emitEventMock).not.toHaveBeenCalled();
+ }
+ );
+});
+
describe('AI test server isolation', () => {
it('blocks metadata mutations, health checks, and event connections to an unverified server', async () => {
vi.stubEnv('VARRO_TEST_SERVER_URL', 'http://127.0.0.1:49999');
diff --git a/src/extension/open-code-transport.ts b/src/extension/open-code-transport.ts
index 7e5b059a..bfa8462d 100644
--- a/src/extension/open-code-transport.ts
+++ b/src/extension/open-code-transport.ts
@@ -1,6 +1,7 @@
/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- HTTP and SSE payloads remain untyped until endpoint-specific consumers validate them. */
/* oxlint-disable anti-slop/no-known-value-widening -- Request headers intentionally use the Fetch API dictionary contract. */
import { parseHealthResponse } from '../shared/health';
+import { isNumber, isString } from '../shared/type-utils';
import { CURRENT_OPENCODE_ENDPOINTS } from '../shared/opencode-endpoints';
import {
MAX_SERVER_EVENT_ID_LENGTH,
@@ -12,9 +13,18 @@ import { logger } from './logger';
import { diagnosticRoute, diagnosticTimeline } from './diagnostics';
import { getOpenCodeDirectoryHeaders, scopeOpenCodeRequest } from './util/opencode-request';
import { anySignal, asRecord, findSseChunkBoundary, getString } from './server-utils';
+import { OpenCodeV2Adapter } from './opencode-v2-adapter';
+import { OpenCodeV2SessionState } from './opencode-v2-session-state';
+import { projectV2Event } from './opencode-v2-events';
+import { openCodeApiVersion, type OpenCodeApiVersion } from './opencode-connection';
type EventStreamState = 'healthy' | 'degraded';
+function isV2Session(value: unknown): boolean {
+ const version = asRecord(value)?.version;
+ return isString(version) && openCodeApiVersion(version) === 2;
+}
+
export type OpenCodeResponseMetadata = {
data: unknown;
nextCursor?: string;
@@ -49,6 +59,9 @@ export type OpenCodeRescopeResult = {
const EVENT_STREAM_PATH = CURRENT_OPENCODE_ENDPOINTS.eventStream;
interface OpenCodeTransportOptions {
+ openExternal?: (url: string) => Promise;
+ sessionStateDirectory?: string;
+ getAuthorization?: () => string | undefined;
getUrl: () => string;
getWorkspaceCwd: () => string | undefined;
getStatus: () => ServerStatus;
@@ -87,6 +100,14 @@ export class OpenCodeTransport {
private readonly requestSettlementWaiters = new Set<() => void>();
private readonly pendingAttentionRequests = new Map();
private readonly observedSessionDirectories = new Map();
+ private apiVersion: OpenCodeApiVersion = 1;
+ private apiIdentityUrl: string | undefined;
+ private healthFailure: string | undefined;
+ private readonly v2: OpenCodeV2Adapter;
+
+ get healthError(): string | undefined {
+ return this.healthFailure;
+ }
constructor(options: OpenCodeTransportOptions) {
const testServerUrl = this.testServerUrl;
@@ -101,6 +122,11 @@ export class OpenCodeTransport {
},
};
this.requestWorkspaceDirectory = options.getWorkspaceCwd();
+ this.v2 = new OpenCodeV2Adapter(
+ (method, path, body, requestOptions) => this.requestWire(method, path, body, requestOptions),
+ new OpenCodeV2SessionState(options.sessionStateDirectory),
+ options.openExternal
+ );
}
async request(
@@ -108,6 +134,47 @@ export class OpenCodeTransport {
path: string,
body?: unknown,
options?: OpenCodeRequestOptions
+ ): Promise {
+ // Validate the caller path before any adapter can construct authenticated requests.
+ if (this.apiVersion === 2) {
+ scopeOpenCodeRequest(this.options.getUrl(), path);
+ const directory = options?.unscoped
+ ? undefined
+ : (options?.directory ?? this.getWorkspaceDirectoryForRequest(method, path));
+ const controller = new AbortController();
+ this.requestControllers.add(controller);
+ const signal = options?.signal
+ ? anySignal(options.signal, controller.signal)
+ : controller.signal;
+ try {
+ const result =
+ method === 'GET' && path === CURRENT_OPENCODE_ENDPOINTS.health
+ ? await this.readHealthInfo(signal)
+ : await this.v2.request(method, path, body, { ...options, directory, signal });
+ signal.throwIfAborted();
+ const maxBytes =
+ options?.maxProjectedResponseBytes ??
+ options?.maxResponseBytes ??
+ OpenCodeTransport.RESPONSE_MAX_BYTES;
+ if (result !== undefined && Buffer.byteLength(JSON.stringify(result)) > maxBytes)
+ throw new OpenCodeResponseTooLargeError(maxBytes);
+ return result;
+ } finally {
+ this.requestControllers.delete(controller);
+ if (!this.requestControllers.size) {
+ for (const resolve of this.requestSettlementWaiters) resolve();
+ this.requestSettlementWaiters.clear();
+ }
+ }
+ }
+ return this.requestWire(method, path, body, options);
+ }
+
+ private async requestWire(
+ method: string,
+ path: string,
+ body?: unknown,
+ options?: OpenCodeRequestOptions
): Promise {
const scoped = scopeOpenCodeRequest(
this.options.getUrl(),
@@ -125,6 +192,7 @@ export class OpenCodeTransport {
const timeoutSignal = AbortSignal.timeout(this.getRequestTimeoutMs(method, path));
this.requestControllers.add(controller);
const headers: Record = {
+ ...this.authorizationHeaders(),
...getOpenCodeDirectoryHeaders(scoped.directory),
};
const init: RequestInit = {
@@ -158,6 +226,21 @@ export class OpenCodeTransport {
const msg = getResponseErrorMessage(data, res.statusText);
throw new Error(`${res.status} ${msg}`);
}
+ if (
+ this.apiVersion === 2 &&
+ res.status !== 204 &&
+ res.headers.get('content-type')?.includes('text/html')
+ ) {
+ throw new Error(`OpenCode returned HTML instead of API data: ${path.split('?')[0]}`);
+ }
+ // V2 writes shared session headers, but v1 cannot read their transcript storage.
+ // Filter before wrapping pagination metadata so an empty page retains its cursor.
+ if (this.apiVersion === 1 && method === 'GET' && Array.isArray(data)) {
+ const pathname = new URL(scoped.url).pathname;
+ if (pathname === '/session' || /^\/session\/[^/]+\/children$/.test(pathname)) {
+ data = data.filter((session: unknown) => !isV2Session(session));
+ }
+ }
if (options?.captureNextCursor) {
const nextCursor = res.headers.get('x-next-cursor')?.trim();
const metadata: OpenCodeResponseMetadata = { data };
@@ -252,15 +335,58 @@ export class OpenCodeTransport {
return this.requestWorkspaceDirectory;
}
- async readHealthInfo(): Promise<{ healthy: boolean; version?: string }> {
+ async readHealthInfo(signal?: AbortSignal): Promise<{ healthy: boolean; version?: string }> {
let health: { healthy: boolean; version?: string } = { healthy: false };
+ this.healthFailure = undefined;
try {
- const res = await fetch(`${this.options.getUrl()}${CURRENT_OPENCODE_ENDPOINTS.health}`, {
- redirect: 'error',
- signal: AbortSignal.timeout(OpenCodeTransport.HEALTH_TIMEOUT_MS),
- });
- if (res.ok) health = parseHealthResponse(await res.json()) ?? { healthy: false };
+ const url = this.options.getUrl();
+ if (this.apiIdentityUrl !== url) {
+ this.apiVersion = 1;
+ this.v2.reset();
+ this.apiIdentityUrl = url;
+ }
+ const paths =
+ this.apiVersion === 2
+ ? ['/api/status', '/api/info', CURRENT_OPENCODE_ENDPOINTS.health]
+ : [CURRENT_OPENCODE_ENDPOINTS.health, '/api/status', '/api/info'];
+ for (const path of paths) {
+ signal?.throwIfAborted();
+ const timeout = AbortSignal.timeout(OpenCodeTransport.HEALTH_TIMEOUT_MS);
+ const res = await fetch(`${url}${path}`, {
+ redirect: 'error',
+ headers: this.authorizationHeaders(),
+ signal: signal ? anySignal(signal, timeout) : timeout,
+ });
+ if (res.status === 401 || res.status === 403) {
+ this.healthFailure =
+ 'OpenCode server authentication failed. Supply the server credentials or restart the Varro-managed server.';
+ break;
+ }
+ if (!res.ok) {
+ if (res.status !== 404) break;
+ continue;
+ }
+ const contentType = res.headers?.get('content-type');
+ if (contentType?.includes('text/html')) continue;
+ const data = await res.json();
+ if (path === CURRENT_OPENCODE_ENDPOINTS.health)
+ health = parseHealthResponse(data) ?? health;
+ else {
+ const info = asRecord(data);
+ if (isString(info?.version) && (isNumber(info.pid) || info.ready === true))
+ health = { healthy: true, version: info.version };
+ }
+ if (health.healthy) {
+ const family = openCodeApiVersion(health.version ?? '');
+ if (!family) {
+ this.healthFailure = `Unsupported OpenCode server version: ${health.version ?? 'unknown'}`;
+ health = { healthy: false };
+ } else this.apiVersion = family;
+ break;
+ }
+ }
} catch {
+ signal?.throwIfAborted();
// A failed probe is represented by the unhealthy snapshot below.
}
if (this.diagnosticHealth !== health.healthy) {
@@ -273,6 +399,11 @@ export class OpenCodeTransport {
return health;
}
+ private authorizationHeaders(): Record {
+ const authorization = this.options.getAuthorization?.();
+ return authorization ? { Authorization: authorization } : {};
+ }
+
async checkHealth(): Promise {
const data = await this.readHealthInfo();
return data.healthy === true;
@@ -303,7 +434,11 @@ export class OpenCodeTransport {
let continuityEstablished = false;
let connectedAt = 0;
let reconnectBackoffReset = false;
- const eventStreamRequest = scopeOpenCodeRequest(serverUrl, EVENT_STREAM_PATH, undefined);
+ const eventStreamRequest = scopeOpenCodeRequest(
+ serverUrl,
+ this.apiVersion === 2 ? '/api/event' : EVENT_STREAM_PATH,
+ undefined
+ );
let idleTimer: ReturnType | null = null;
let connectTimer: ReturnType | null = null;
const isCurrentStream = () => this.isCurrentEventStream(controller, generation);
@@ -337,6 +472,7 @@ export class OpenCodeTransport {
try {
const headers: Record = {
+ ...this.authorizationHeaders(),
Accept: 'text/event-stream',
...getOpenCodeDirectoryHeaders(eventStreamRequest.directory),
};
@@ -349,6 +485,8 @@ export class OpenCodeTransport {
clearConnectTimer();
if (!isCurrentStream()) return;
if (!res.ok || !res.body) throw new Error(`Failed to open event stream: ${res.status}`);
+ if (this.apiVersion === 2 && !res.headers.get('content-type')?.includes('text/event-stream'))
+ throw new Error('OpenCode returned an invalid event stream content type');
continuityEstablished = true;
connectedAt = Date.now();
diagnosticTimeline.record({ event: 'stream-healthy', operationId });
@@ -559,15 +697,39 @@ export class OpenCodeTransport {
);
return;
}
- try {
- this.observeServerEvent(parsed);
- } catch (err) {
- logger.warn(`Event observation threw: ${err instanceof Error ? err.message : String(err)}`);
+ const record = asRecord(parsed);
+ if (this.apiVersion === 2 && isString(record?.type) && asRecord(record.data)) {
+ this.v2.observe(
+ record.type,
+ asRecord(record.data)!,
+ isString(record.id) ? record.id : undefined
+ );
}
- try {
- this.options.emitEvent(parsed);
- } catch (err) {
- logger.warn(`Event listener threw: ${err instanceof Error ? err.message : String(err)}`);
+ const sessionID = asRecord(record?.data)?.sessionID;
+ const events =
+ this.apiVersion === 2
+ ? projectV2Event(parsed, isString(sessionID) ? this.v2.eventContext(sessionID) : undefined)
+ : [parsed];
+ for (const event of events) {
+ if (this.apiVersion === 1) {
+ const parsedEvent = parseServerEvent(event);
+ if (
+ (parsedEvent?.type === 'session.created' || parsedEvent?.type === 'session.updated') &&
+ isV2Session(asRecord(parsedEvent.properties)?.info)
+ ) {
+ continue;
+ }
+ }
+ try {
+ this.observeServerEvent(event);
+ } catch (err) {
+ logger.warn(`Event observation threw: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ try {
+ this.options.emitEvent(event);
+ } catch (err) {
+ logger.warn(`Event listener threw: ${err instanceof Error ? err.message : String(err)}`);
+ }
}
}
diff --git a/src/extension/opencode-connection.ts b/src/extension/opencode-connection.ts
new file mode 100644
index 00000000..31c9d2a0
--- /dev/null
+++ b/src/extension/opencode-connection.ts
@@ -0,0 +1,73 @@
+export type OpenCodeApiVersion = 1 | 2;
+
+export function openCodeApiVersion(version: string): OpenCodeApiVersion | null {
+ const major = version.match(/^(?:opencode\s+v?)?(\d+)\./)?.[1];
+ return major === '1' ? 1 : major === '2' ? 2 : null;
+}
+
+export function basicAuthorization(password: string, username = 'opencode'): string {
+ return `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
+}
+
+/** Consume credentials before startup output reaches logs, including split stdout chunks. */
+export class OpenCodeStartupOutput {
+ private pending: Buffer = Buffer.alloc(0);
+ private discarding = false;
+ private static readonly PREFIX = Buffer.from('server password');
+
+ constructor(private readonly onPassword: (password: string) => void) {}
+
+ write(chunk: Buffer): Buffer {
+ let source = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;
+ this.pending = Buffer.alloc(0);
+ const output: Buffer[] = [];
+ while (source.length) {
+ if (this.discarding) {
+ const end = source.indexOf(10);
+ if (end < 0) break;
+ this.discarding = false;
+ source = source.subarray(end + 1);
+ }
+ const start = source.indexOf(OpenCodeStartupOutput.PREFIX);
+ if (start < 0) {
+ let held = 0;
+ for (
+ let size = Math.min(source.length, OpenCodeStartupOutput.PREFIX.length - 1);
+ size > 0;
+ size--
+ ) {
+ if (
+ (source.length === size || source[source.length - size - 1] === 10) &&
+ source.subarray(-size).equals(OpenCodeStartupOutput.PREFIX.subarray(0, size))
+ ) {
+ held = size;
+ break;
+ }
+ }
+ output.push(held ? source.subarray(0, source.length - held) : source);
+ if (held) this.pending = Buffer.from(source.subarray(-held));
+ break;
+ }
+ output.push(source.subarray(0, start));
+ const end = source.indexOf(10, start);
+ if (end < 0) {
+ if (source.length - start <= 8192) this.pending = Buffer.from(source.subarray(start));
+ else {
+ this.discarding = true;
+ output.push(Buffer.from('server password [redacted]\n'));
+ }
+ break;
+ }
+ if (end - start <= 8192) {
+ const password = source
+ .subarray(start + OpenCodeStartupOutput.PREFIX.length, end)
+ .toString('utf8')
+ .trim();
+ if (password && password.length <= 4096) this.onPassword(password);
+ }
+ output.push(Buffer.from('server password [redacted]\n'));
+ source = source.subarray(end + 1);
+ }
+ return output.length === 1 ? output[0]! : Buffer.concat(output);
+ }
+}
diff --git a/src/extension/opencode-startup.integration.test.ts b/src/extension/opencode-startup.integration.test.ts
new file mode 100644
index 00000000..f182a99d
--- /dev/null
+++ b/src/extension/opencode-startup.integration.test.ts
@@ -0,0 +1,123 @@
+/* oxlint-disable anti-slop/no-module-mocking -- Only the editor API is substituted; process launch, ownership, HTTP, and credential recovery are real. */
+import { describe, expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { createServer } from 'node:net';
+import { spawnSync } from 'node:child_process';
+import { asRecord, isString } from '../shared/type-utils';
+import { OpenCodeServer } from './server';
+
+const editor = vi.hoisted(() => ({ directory: '' }));
+const logs = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));
+vi.mock('./logger', () => ({ logger: logs }));
+vi.mock('vscode', () => ({
+ workspace: {
+ get workspaceFolders() {
+ return [{ uri: { fsPath: editor.directory } }];
+ },
+ getConfiguration: () => ({
+ get: (key: string, fallback?: T) => (key === 'server.autoUpdate' ? false : fallback),
+ }),
+ },
+ window: {
+ activeTextEditor: undefined,
+ showInformationMessage: vi.fn(),
+ showWarningMessage: vi.fn(),
+ },
+}));
+
+describe.skipIf(!process.env.VARRO_OPENCODE_TEST_BINARY)('released managed startup', () => {
+ it('starts, authenticates a second window, restarts, and stops its own isolated server', async () => {
+ const binary = process.env.VARRO_OPENCODE_TEST_BINARY!;
+ const parent = resolve('artifacts/ai-test-data');
+ await mkdir(parent, { recursive: true });
+ const root = await mkdtemp(join(parent, 'startup-'));
+ for (const directory of ['home', 'data', 'state', 'cache', 'config', 'workspace'])
+ await mkdir(join(root, directory));
+ editor.directory = join(root, 'workspace');
+ const git = spawnSync('git', ['init', '--quiet'], { cwd: editor.directory });
+ expect(git.status).toBe(0);
+ await writeFile(
+ join(editor.directory, 'opencode.json'),
+ JSON.stringify({ enabled_providers: [] })
+ );
+ const listener = createServer();
+ await new Promise((done) => listener.listen(0, '127.0.0.1', done));
+ const address = listener.address();
+ if (!address || isString(address)) throw new Error('No fixture port');
+ await new Promise((done) => listener.close(() => done()));
+ const url = `http://127.0.0.1:${address.port}`;
+ for (const key of Object.keys(process.env)) {
+ if (/^OPENCODE_|_API_KEY$|_TOKEN$|^AWS_|^AZURE_|^GOOGLE_|^ANTHROPIC_/.test(key))
+ vi.stubEnv(key, undefined);
+ }
+ vi.stubEnv('HOME', join(root, 'home'));
+ vi.stubEnv('XDG_DATA_HOME', join(root, 'data'));
+ vi.stubEnv('XDG_CONFIG_HOME', join(root, 'config'));
+ vi.stubEnv('XDG_STATE_HOME', join(root, 'state'));
+ vi.stubEnv('XDG_CACHE_HOME', join(root, 'cache'));
+ vi.stubEnv('OPENCODE_DB', join(root, 'data/test.db'));
+ vi.stubEnv('OPENCODE_TEST_HOME', join(root, 'home'));
+ vi.stubEnv('VARRO_TEST_SERVER_URL', url);
+ const leasePath = join(root, 'lease.json');
+ const server = new OpenCodeServer(address.port, true, binary, false, undefined, leasePath);
+ let attached: OpenCodeServer | undefined;
+ try {
+ expect(await server.start()).toBe(url);
+ const info = await server.readServerInfo();
+ expect(info.health.healthy).toBe(true);
+ expect(info.managedProcess).toBe(true);
+ if (process.env.VARRO_OPENCODE_TEST_VERSION)
+ expect(info.health.version).toBe(process.env.VARRO_OPENCODE_TEST_VERSION);
+ const lease = asRecord(JSON.parse(await readFile(leasePath, 'utf8')));
+ if (info.health.version?.startsWith('2.')) {
+ const registrationPath = join(root, 'state/opencode/service.json');
+ const registration = await readFile(registrationPath, 'utf8');
+ expect(asRecord(JSON.parse(registration))?.url).toBe(url);
+ const cli = spawnSync(binary, ['api', 'get', '/api/session?limit=1'], {
+ cwd: editor.directory,
+ encoding: 'utf8',
+ timeout: 10000,
+ });
+ expect(cli.status, cli.stderr).toBe(0);
+ expect(await readFile(registrationPath, 'utf8')).toBe(registration);
+ expect(lease?.password).toBeTruthy();
+ const output = JSON.stringify([
+ logs.info.mock.calls,
+ logs.warn.mock.calls,
+ logs.error.mock.calls,
+ ]);
+ expect(output).not.toContain(String(lease?.password));
+ }
+ attached = new OpenCodeServer(address.port, false, binary, false, undefined, leasePath);
+ expect(await attached.start()).toBe(url);
+ expect((await attached.readServerInfo()).health.healthy).toBe(true);
+ await attached.dispose();
+ attached = undefined;
+ if (info.health.version?.startsWith('2.')) {
+ await new Promise((done) => listener.listen(0, '127.0.0.1', done));
+ const otherAddress = listener.address();
+ if (!otherAddress || isString(otherAddress)) throw new Error('No second fixture port');
+ await new Promise((done) => listener.close(() => done()));
+ attached = new OpenCodeServer(
+ otherAddress.port,
+ true,
+ binary,
+ false,
+ undefined,
+ join(root, 'other-lease.json')
+ );
+ expect(await attached.start()).toBe(url);
+ expect((await attached.readServerInfo()).managedProcess).toBe(false);
+ await attached.dispose();
+ attached = undefined;
+ }
+ expect(await server.restart()).toBe(url);
+ expect((await server.readServerInfo()).health.healthy).toBe(true);
+ } finally {
+ await attached?.dispose();
+ await server.dispose();
+ vi.unstubAllEnvs();
+ }
+ }, 60000);
+});
diff --git a/src/extension/opencode-v2-adapter.ts b/src/extension/opencode-v2-adapter.ts
new file mode 100644
index 00000000..39d0084b
--- /dev/null
+++ b/src/extension/opencode-v2-adapter.ts
@@ -0,0 +1,1035 @@
+/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/require-safety-comment-for-type-assertion -- HTTP envelopes are validated here; endpoint payload assertions use the pinned released client contract. */
+import type {
+ AgentInfo,
+ CommandInfo,
+ FormInfo,
+ IntegrationInfo,
+ ModelInfo,
+ PermissionRequest,
+ ProviderInfo,
+ SessionInfo,
+ SessionActive,
+ SessionMessageInfo,
+ SessionMessagesResponse,
+ SessionInboxInfo,
+ SessionsResponse,
+ ModelRef,
+} from '@opencode/client';
+import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
+import { asRecord, isString, type UnknownRecord } from '../shared/type-utils';
+import type { ProviderAuthMethod } from '../shared/opencode-types';
+import { OpenCodeResponseTooLargeError, type OpenCodeRequestOptions } from './open-code-transport';
+import { OpenCodeV2SessionState } from './opencode-v2-session-state';
+import {
+ projectV2Agent,
+ projectV2Form,
+ projectV2Message,
+ projectV2Model,
+ projectV2Permission,
+ projectV2Session,
+ v1Action,
+ v2ModelRef,
+ v2Rules,
+ isV2TranscriptMessage,
+ normalizeV2Error,
+ type V2MessageContext,
+} from './opencode-v2-projection';
+
+type WireRequest = (
+ method: string,
+ path: string,
+ body?: unknown,
+ options?: OpenCodeRequestOptions
+) => Promise;
+
+function legacyModel(value: unknown): string | undefined {
+ if (isString(value)) return value;
+ const model = asRecord(value);
+ if (!isString(model?.providerID) || !isString(model.model)) return undefined;
+ return `${model.providerID}/${model.model}${isString(model.variant) ? `#${model.variant}` : ''}`;
+}
+
+function legacyRules(value: unknown): UnknownRecord[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ return value.map((item) => {
+ const rule = asRecord(item) ?? {};
+ return {
+ permission: v1Action(String(rule.action)),
+ pattern: rule.resource,
+ action: rule.effect,
+ };
+ });
+}
+
+function mergeConfiguration(target: UnknownRecord, patch: UnknownRecord): void {
+ for (const [key, value] of Object.entries(patch)) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
+ const record = asRecord(value);
+ if (record) {
+ const merged = { ...asRecord(target[key]) };
+ mergeConfiguration(merged, record);
+ target[key] = merged;
+ } else target[key] = value;
+ }
+}
+
+function v1AuthMethods(integration: IntegrationInfo | undefined): ProviderAuthMethod[] {
+ return (
+ integration?.methods
+ .filter((item) => item.type === 'oauth' || item.type === 'key')
+ .map((item) => ({
+ type: item.type === 'key' ? 'api' : 'oauth',
+ label: item.label ?? 'API key',
+ prompts: item.form?.flatMap[number]>((field) => {
+ if (field.type === 'external' || field.hidden) return [];
+ const base = { key: field.key, message: field.title ?? field.description ?? field.key };
+ if (field.type === 'string' && field.options)
+ return [
+ {
+ ...base,
+ type: 'select' as const,
+ options: field.options.map((option) => ({
+ label: option.label,
+ value: option.value,
+ hint: option.description,
+ })),
+ },
+ ];
+ return [{ ...base, type: 'text' as const }];
+ }),
+ })) ?? []
+ );
+}
+
+export class OpenCodeV2Adapter {
+ private readonly permissions = new Map();
+ private readonly forms = new Map();
+ private readonly messageParents = new Map();
+ private readonly contexts = new Map();
+ private readonly inputTypes = new Map();
+ private readonly failures = new Map();
+ private readonly submissions = new Map>();
+ private readonly oauth = new Map();
+
+ constructor(
+ private readonly wire: WireRequest,
+ private readonly annotations = new OpenCodeV2SessionState(),
+ private readonly openExternal: (url: string) => Promise = async () => false
+ ) {}
+
+ observe(type: string, data: UnknownRecord, eventID?: string): void {
+ if (isString(data.sessionID)) {
+ const context = { ...this.contexts.get(data.sessionID) };
+ const directory = asRecord(data.location)?.directory;
+ if (isString(directory)) context.directory = directory;
+ if (type === 'session.agent.selected' && isString(data.agent)) context.agent = data.agent;
+ const model = asRecord(data.model);
+ if (type === 'session.model.selected' && isString(model?.id) && isString(model.providerID))
+ context.model = model as ModelRef;
+ if (type === 'session.inbox.enqueued' && isString(data.inboxID))
+ this.inputTypes.set(data.inboxID, String(asRecord(data.item)?.type));
+ if (type === 'session.inbox.delivered' && isString(data.inboxID)) {
+ if (this.inputTypes.get(data.inboxID) === 'user') {
+ context.parentID = data.inboxID;
+ context.hasAssistant = false;
+ }
+ this.inputTypes.delete(data.inboxID);
+ }
+ if (type === 'session.step.started') context.hasAssistant = true;
+ if (type === 'session.execution.failed' && eventID) {
+ const error = normalizeV2Error(data.error);
+ if (error) this.failures.set(eventID.replace(/^evt_/, 'msg_'), { ...context, error });
+ }
+ this.contexts.set(data.sessionID, context);
+ for (const map of [this.contexts, this.inputTypes, this.failures])
+ while (map.size > 4096) map.delete(map.keys().next().value!);
+ }
+ if (type === 'permission.asked' && isString(data.id) && isString(data.sessionID))
+ this.permissions.set(data.id, data.sessionID);
+ if (type === 'permission.replied' && isString(data.requestID))
+ this.permissions.delete(data.requestID);
+ if (type === 'form.created') {
+ const form = asRecord(data.form);
+ if (form && isString(form.id) && isString(form.sessionID) && Array.isArray(form.fields))
+ this.forms.set(form.id, form as FormInfo);
+ }
+ if ((type === 'form.replied' || type === 'form.cancelled') && isString(data.id))
+ this.forms.delete(data.id);
+ }
+
+ reset(): void {
+ this.permissions.clear();
+ this.forms.clear();
+ this.messageParents.clear();
+ this.contexts.clear();
+ this.inputTypes.clear();
+ this.failures.clear();
+ this.oauth.clear();
+ }
+
+ eventContext(sessionID: string): V2MessageContext | undefined {
+ return this.contexts.get(sessionID);
+ }
+
+ async request(
+ method: string,
+ path: string,
+ body: unknown,
+ options: OpenCodeRequestOptions = {}
+ ): Promise {
+ const url = new URL(path, 'http://localhost');
+ const route = url.pathname;
+ // VS Code lowercases drive letters. OpenCode 2.0.6 can overflow its instruction
+ // discovery stack when that differs from the filesystem's uppercase drive.
+ const directory = (url.searchParams.get('directory') ?? options.directory)?.replace(
+ /^[a-z]:[\\/]/,
+ (drive) => drive.toUpperCase()
+ );
+ const query = (targetPath: string, location = false) => {
+ const target = new URL(targetPath, 'http://localhost');
+ if (location && directory) target.searchParams.set('location[directory]', directory);
+ return target.pathname + target.search;
+ };
+ const raw = (verb: string, targetPath: string, payload?: unknown) => {
+ options.signal?.throwIfAborted();
+ return this.wire(verb, targetPath, payload, {
+ ...options,
+ unscoped: true,
+ captureNextCursor: false,
+ stripMessageParts: false,
+ stripSummaryDiffs: false,
+ });
+ };
+ const data = async (verb: string, targetPath: string, payload?: unknown): Promise => {
+ const response = asRecord(await raw(verb, targetPath, payload));
+ if (!response || !('data' in response))
+ throw new Error(`Invalid OpenCode v2 response for ${targetPath.split('?')[0]}`);
+ return response.data as T;
+ };
+ const input = asRecord(body) ?? {};
+
+ // Internal callers already use a few native permission endpoints.
+ if (route.startsWith('/api/')) return raw(method, query(path, true), body);
+ if (route === '/agent' && method === 'GET') {
+ const agents = (await data('GET', query('/api/agent', true))).map(
+ projectV2Agent
+ );
+ const config = asRecord(await this.request('GET', '/config', undefined, options));
+ for (const [name, value] of Object.entries(asRecord(config?.agent) ?? {})) {
+ const agent = asRecord(value);
+ if (!agent) continue;
+ const existing = agents.findIndex((item) => item.name === name);
+ if (agent.disabled === true) {
+ if (existing >= 0) agents.splice(existing, 1);
+ continue;
+ }
+ const model = v2ModelRef(agent.model);
+ const normalized = {
+ mode: 'primary',
+ hidden: false,
+ ...agents[existing],
+ ...agent,
+ name,
+ model: model
+ ? {
+ providerID: model.providerID,
+ modelID: model.id,
+ variant: model.variant,
+ }
+ : agents[existing]?.model,
+ };
+ if (existing >= 0) agents[existing] = normalized;
+ else agents.push(normalized);
+ }
+ return agents;
+ }
+ if (route === '/provider' || route === '/config/providers')
+ return this.providers(route, directory, options);
+ if (route === '/provider/auth') {
+ const providers = await data('GET', query('/api/provider', true));
+ const integrations = await data('GET', query('/api/integration', true));
+ return {
+ ...Object.fromEntries(
+ integrations.map((integration) => [integration.id, v1AuthMethods(integration)])
+ ),
+ ...Object.fromEntries(
+ providers.map((provider) => [
+ provider.id,
+ v1AuthMethods(
+ integrations.find((item) => item.id === (provider.integrationID ?? provider.id))
+ ),
+ ])
+ ),
+ };
+ }
+ if (route === '/model/default') {
+ const config = asRecord(await this.request('GET', '/config', undefined, options));
+ if (isString(config?.model)) {
+ const match = config.model.match(/^([^/]+)\/(.+?)(?:#(.+))?$/);
+ if (match) return { providerID: match[1], modelID: match[2], variant: match[3] };
+ }
+ const model = await data('GET', query('/api/model/default', true));
+ return model ? { providerID: model.providerID, modelID: model.id } : null;
+ }
+ if (route === '/config' || route === '/global/config') {
+ if (method !== 'GET')
+ throw new Error('OpenCode v2 configuration updates must target a configuration file');
+ const entries = await raw('GET', query('/api/config', true));
+ const documents = Array.isArray(entries) ? entries : asRecord(entries)?.data;
+ if (!Array.isArray(documents)) throw new Error('Invalid OpenCode v2 configuration response');
+ const config: UnknownRecord = {};
+ for (const document of documents) {
+ const entry = asRecord(document);
+ const info = asRecord(entry?.info);
+ if (info) mergeConfiguration(config, info);
+ }
+ const agents = Object.fromEntries(
+ Object.entries(asRecord(config.agents) ?? {}).map(([name, value]) => {
+ const agent = asRecord(value) ?? {};
+ return [
+ name,
+ {
+ ...agent,
+ model: legacyModel(agent.model),
+ prompt: agent.system,
+ permission: legacyRules(agent.permissions),
+ },
+ ];
+ })
+ );
+ return {
+ ...config,
+ model: legacyModel(config.model),
+ small_model: asRecord(agents.title)?.model,
+ agent: agents,
+ provider: config.providers,
+ command: config.commands,
+ permission: legacyRules(config.permissions),
+ compaction: {
+ ...asRecord(config.compaction),
+ reserved: asRecord(config.compaction)?.buffer,
+ },
+ };
+ }
+ if (route === '/session/status') {
+ const active = await data>('GET', '/api/session/active');
+ return Object.fromEntries(
+ Object.entries(active).map(([id, status]) => {
+ if (status.type !== 'running')
+ throw new Error('Invalid OpenCode v2 active-session status');
+ return [id, { type: 'busy' }];
+ })
+ );
+ }
+ if ((route === '/session' || route === '/experimental/session') && method === 'GET') {
+ const target = new URL('/api/session', 'http://localhost');
+ for (const key of ['limit', 'search', 'parentID', 'cursor', 'order']) {
+ const value = url.searchParams.get(key);
+ if (value) target.searchParams.set(key, value);
+ }
+ if (route === '/session' && directory) target.searchParams.set('directory', directory);
+ if (url.searchParams.get('roots') === 'true') target.searchParams.set('parentID', 'null');
+ const result = (await raw('GET', target.pathname + target.search)) as SessionsResponse;
+ if (!Array.isArray(result?.data)) throw new Error('Invalid OpenCode v2 session list');
+ const sessions = await Promise.all(result.data.map((session) => this.session(session)));
+ return options.captureNextCursor
+ ? { data: sessions, nextCursor: result.cursor?.next ?? undefined }
+ : sessions;
+ }
+ if (route === '/session' && method === 'POST') {
+ const session = await data('POST', '/api/session', {
+ title: input.title,
+ id: input.id,
+ metadata: input.metadata,
+ permissions: input.permission !== undefined ? v2Rules(input.permission) : undefined,
+ model: v2ModelRef(input.model),
+ agent: input.agent,
+ location: directory ? { directory } : undefined,
+ });
+ if (input.parentID) await this.annotations.update(session.id, { parentID: input.parentID });
+ return this.session(session);
+ }
+ if (route === '/permission' && method === 'GET') {
+ const requests = await data(
+ 'GET',
+ query('/api/permission/request', true)
+ );
+ for (const request of requests) this.permissions.set(request.id, request.sessionID);
+ return requests.map(projectV2Permission);
+ }
+ if (route === '/question' && method === 'GET') {
+ const forms = await data('GET', query('/api/form', true));
+ for (const form of forms) this.forms.set(form.id, form);
+ return forms.map(projectV2Form);
+ }
+ const approval = route.match(/^\/(permission|question)\/([^/]+)\/(reply|reject)$/);
+ if (approval) {
+ const id = decodeURIComponent(approval[2]!);
+ const kind = approval[1];
+ if (kind === 'permission') {
+ if (!this.permissions.has(id)) await this.request('GET', '/permission', undefined, options);
+ const sessionID = this.permissions.get(id);
+ if (!sessionID) throw new Error('OpenCode permission request is no longer pending');
+ await raw(
+ 'POST',
+ `/api/session/${encodeURIComponent(sessionID)}/permission/${encodeURIComponent(id)}/reply`,
+ { decision: input.reply, message: input.message }
+ );
+ this.permissions.delete(id);
+ } else {
+ if (!this.forms.has(id)) await this.request('GET', '/question', undefined, options);
+ const form = this.forms.get(id);
+ if (!form) throw new Error('OpenCode question is no longer pending');
+ const target = `/api/session/${encodeURIComponent(form.sessionID)}/form/${encodeURIComponent(id)}`;
+ if (approval[3] === 'reject') await raw('DELETE', target);
+ else {
+ if (!Array.isArray(input.answers)) throw new Error('Invalid question answers');
+ const answers = input.answers;
+ const answer = Object.fromEntries(
+ form.fields.map((field, index) => {
+ const selected = Array.isArray(answers[index]) ? (answers[index] as string[]) : [];
+ const values = selected.map((label) =>
+ 'options' in field
+ ? (field.options?.find((option) => option.label === label)?.value ?? label)
+ : label
+ );
+ return [
+ field.key,
+ field.type === 'multiselect'
+ ? values
+ : field.type === 'boolean'
+ ? values[0] === 'Yes'
+ : field.type === 'number' || field.type === 'integer'
+ ? Number(values[0])
+ : (values[0] ?? ''),
+ ];
+ })
+ );
+ await raw('POST', `${target}/reply`, { answer });
+ }
+ this.forms.delete(id);
+ }
+ return true;
+ }
+ const sessionRoute = route.match(/^\/session\/([^/]+)(?:\/(.*))?$/);
+ if (sessionRoute) {
+ const sessionID = decodeURIComponent(sessionRoute[1]!);
+ const endpoint = `/api/session/${encodeURIComponent(sessionID)}`;
+ const action = sessionRoute[2] ?? '';
+ if (!action) {
+ if (method === 'GET') return this.session(await data('GET', endpoint));
+ if (method === 'DELETE') {
+ await raw('DELETE', endpoint);
+ await this.annotations.remove(sessionID);
+ return true;
+ }
+ if (method === 'PATCH') {
+ if (input.title !== undefined || input.permission !== undefined)
+ await raw('PATCH', endpoint, {
+ title: input.title,
+ permissions: input.permission !== undefined ? v2Rules(input.permission) : undefined,
+ });
+ const patch: UnknownRecord = {};
+ if (input.metadata !== undefined) patch.metadata = input.metadata;
+ if (input.time !== undefined) patch.time = input.time;
+ if (Object.keys(patch).length) await this.annotations.update(sessionID, patch);
+ return this.session(await data('GET', endpoint));
+ }
+ }
+ if (action === 'children') {
+ const result = (await raw(
+ 'GET',
+ `/api/session?parentID=${encodeURIComponent(sessionID)}&limit=1000`
+ )) as SessionsResponse;
+ return Promise.all(result.data.map((session) => this.session(session)));
+ }
+ if (action === 'message' && method === 'GET') {
+ const target = new URL(`${endpoint}/message`, 'http://localhost');
+ target.searchParams.set('order', 'desc');
+ const limit = url.searchParams.has('limit')
+ ? Number(url.searchParams.get('limit'))
+ : Infinity;
+ if (!(limit > 0)) throw new Error('Invalid message page limit');
+ const collected: SessionMessageInfo[] = [];
+ const records: SessionMessageInfo[] = [];
+ let cursor = url.searchParams.get('before') ?? undefined;
+ const seen = new Set();
+ let bytes = 0;
+ // Read pending inputs first so delivery between the two reads cannot hide a prompt.
+ // Older pages keep their transcript-only boundaries and cursor semantics.
+ const inbox = cursor ? [] : await data('GET', `${endpoint}/inbox`);
+ if (!Array.isArray(inbox)) throw new Error('Invalid OpenCode v2 session inbox');
+ bytes += Buffer.byteLength(JSON.stringify(inbox));
+ do {
+ target.searchParams.set('limit', String(Math.min(200, limit - collected.length)));
+ if (cursor) {
+ target.searchParams.set('cursor', cursor);
+ target.searchParams.delete('order');
+ }
+ const result = (await raw(
+ 'GET',
+ target.pathname + target.search
+ )) as SessionMessagesResponse;
+ if (!Array.isArray(result?.data)) throw new Error('Invalid OpenCode v2 message page');
+ bytes += Buffer.byteLength(JSON.stringify(result.data));
+ if (bytes > (options.maxResponseBytes ?? 16 * 1024 * 1024))
+ throw new OpenCodeResponseTooLargeError(options.maxResponseBytes ?? 16 * 1024 * 1024);
+ records.push(...result.data);
+ collected.push(...result.data.filter(isV2TranscriptMessage));
+ cursor = result.cursor?.next ?? undefined;
+ if (cursor && seen.has(cursor))
+ throw new Error('OpenCode repeated a message pagination cursor');
+ if (cursor) seen.add(cursor);
+ } while (cursor && collected.length < limit);
+ const ordered = records.toReversed();
+ const firstAssistant = ordered.findIndex(
+ (message) =>
+ message.type === 'assistant' ||
+ message.type === 'skill' ||
+ message.type === 'shell' ||
+ (message.type === 'idle' && message.outcome === 'failed')
+ );
+ const firstUser = ordered.findIndex((message) => message.type === 'user');
+ let parent =
+ firstAssistant >= 0 ? (this.messageParents.get(ordered[firstAssistant]!.id) ?? '') : '';
+ let assistantFailed = false;
+ // V2 messages omit parent IDs. Read context outside the page without adding rows or changing its cursor.
+ if (!parent && firstAssistant >= 0 && (firstUser < 0 || firstAssistant < firstUser)) {
+ let contextCursor = cursor;
+ const contextCursors = new Set();
+ while (contextCursor) {
+ if (contextCursors.has(contextCursor))
+ throw new Error('OpenCode repeated a context pagination cursor');
+ contextCursors.add(contextCursor);
+ const context = (await raw(
+ 'GET',
+ `${endpoint}/message?limit=200&cursor=${encodeURIComponent(contextCursor)}`
+ )) as SessionMessagesResponse;
+ if (!Array.isArray(context?.data)) throw new Error('Invalid OpenCode v2 context page');
+ bytes += Buffer.byteLength(JSON.stringify(context.data));
+ if (bytes > (options.maxResponseBytes ?? 16 * 1024 * 1024))
+ throw new OpenCodeResponseTooLargeError(options.maxResponseBytes ?? 16 * 1024 * 1024);
+ const user = context.data.find((message) => message.type === 'user');
+ const preceding = context.data.slice(0, user ? context.data.indexOf(user) : undefined);
+ assistantFailed ||= preceding.some(
+ (message) => message.type === 'assistant' && !!message.error
+ );
+ if (user) {
+ parent = user.id;
+ break;
+ }
+ if (!context.data.length) break;
+ contextCursor = context.cursor?.next ?? undefined;
+ }
+ }
+ const context = { ...this.contexts.get(sessionID) };
+ const messages = ordered.flatMap((message) => {
+ if (message.type === 'agent-switched') context.agent = message.agent;
+ if (message.type === 'model-switched') context.model = message.model;
+ if (!isV2TranscriptMessage(message)) return [];
+ if (message.type === 'idle' && assistantFailed) return [];
+ const projected = projectV2Message(message, sessionID, directory, parent, {
+ ...context,
+ ...this.failures.get(message.id),
+ });
+ if (message.type === 'user') {
+ parent = message.id;
+ assistantFailed = false;
+ }
+ if (message.type === 'assistant' && message.error) assistantFailed = true;
+ if (projected.info.role === 'assistant' && parent)
+ this.messageParents.set(message.id, parent);
+ if (options.stripMessageParts) projected.parts = [];
+ return [projected];
+ });
+ while (this.messageParents.size > 4096)
+ this.messageParents.delete(this.messageParents.keys().next().value!);
+ if (!messages.length && cursor) {
+ url.searchParams.set('before', cursor);
+ return this.request(method, url.pathname + url.search, body, options);
+ }
+ const messageIDs = new Set(messages.map((message) => message.info.id));
+ for (const item of inbox.toSorted((a, b) => a.time.created - b.time.created)) {
+ if (item.type !== 'user' || messageIDs.has(item.id)) continue;
+ const projected = projectV2Message(
+ { ...item.payload, id: item.id, type: 'user', time: item.time },
+ sessionID,
+ directory,
+ '',
+ context
+ );
+ if (options.stripMessageParts) projected.parts = [];
+ messages.push(projected);
+ messageIDs.add(item.id);
+ }
+ return options.captureNextCursor ? { data: messages, nextCursor: cursor } : messages;
+ }
+ if (action.startsWith('message/') && method === 'GET') {
+ const message = await data('GET', `${endpoint}/${action}`);
+ return projectV2Message(
+ message,
+ sessionID,
+ directory,
+ this.messageParents.get(message.id),
+ this.contexts.get(sessionID)
+ );
+ }
+ if (action.startsWith('message/') && method === 'DELETE') {
+ const messageID = decodeURIComponent(action.slice('message/'.length));
+ const page = await data(
+ 'GET',
+ `${endpoint}/message?limit=20&order=desc`
+ );
+ const last = page.find(isV2TranscriptMessage);
+ if (last?.id !== messageID)
+ throw new Error('OpenCode v2 can only delete messages from the end of the transcript');
+ await raw('POST', `${endpoint}/revert/stage`, { messageID, files: false });
+ await raw('POST', `${endpoint}/revert/commit`, {});
+ return true;
+ }
+ if (['prompt_async', 'prompt', 'message', 'command'].includes(action) && method === 'POST') {
+ return this.submit(sessionID, async () => {
+ const model = v2ModelRef(input.model);
+ if (model && input.variant !== undefined) model.variant = input.variant;
+ const parts = Array.isArray(input.parts)
+ ? input.parts.map(asRecord).filter((part) => part !== null)
+ : [];
+ const text = parts
+ .filter((part) => part.type === 'text')
+ .map((part) => part.text ?? '')
+ .join('\n');
+ if (action === 'message' && (input.system || input.format)) {
+ const format = asRecord(input.format);
+ const prompt = [
+ input.system,
+ text,
+ format?.type === 'json_schema'
+ ? `Return only JSON matching this schema:\n${JSON.stringify(format.schema)}`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+ if (model) await raw('POST', `${endpoint}/model`, { model });
+ const result = await data('POST', `${endpoint}/generate`, { prompt });
+ const response = isString(result.text) ? result.text : '';
+ return {
+ info: { id: `msg_${randomUUID().replaceAll('-', '')}`, sessionID, role: 'assistant' },
+ parts: [{ type: 'text', text: response }],
+ };
+ }
+ if (input.agent) await raw('POST', `${endpoint}/agent`, { agent: input.agent });
+ if (model) await raw('POST', `${endpoint}/model`, { model });
+ // A staged edit is committed only when the replacement input is submitted.
+ const current = await data('GET', endpoint);
+ if (current.revert) await raw('POST', `${endpoint}/revert/commit`, {});
+ // V2 prompt bodies have no system field; keep host context in a replaceable entry.
+ if (isString(input.system)) {
+ await raw(
+ 'PUT',
+ `/api/experimental/session/${encodeURIComponent(sessionID)}/instructions/entries/varro.system`,
+ { value: input.system }
+ );
+ }
+ const payload = {
+ id: input.messageID,
+ text: action === 'command' ? (input.arguments ?? text) : text,
+ files: parts
+ .filter((part) => part.type === 'file')
+ .map((part) => ({ uri: part.url, name: part.filename })),
+ agents: parts
+ .filter((part) => part.type === 'agent')
+ .map((part) => ({ name: part.name })),
+ // Keep the prompt with pending context, including Plan mode's synthetic reminder.
+ // Queuing by default lets the reminder run as a separate provider turn.
+ delivery: input.delivery === 'queue' ? 'queue' : 'steer',
+ resume: input.noReply ? false : undefined,
+ };
+ const admitted = await raw(
+ 'POST',
+ `${endpoint}/${action === 'command' ? 'command' : 'prompt'}`,
+ action === 'command' ? { ...payload, name: input.command } : payload
+ );
+ if (action === 'prompt_async' || action === 'command' || input.noReply) return admitted;
+ await raw('POST', `/api/experimental/session/${encodeURIComponent(sessionID)}/wait`, {});
+ const messages = await data(
+ 'GET',
+ `${endpoint}/message?limit=50&order=desc`
+ );
+ const message = messages.find((candidate) => candidate.type === 'assistant');
+ if (!message) throw new Error('OpenCode finished without an assistant message');
+ return projectV2Message(message, sessionID, directory);
+ });
+ }
+ if (action === 'abort') {
+ await raw('POST', `${endpoint}/interrupt`, {});
+ return true;
+ }
+ if (action === 'summarize') {
+ await raw('POST', `${endpoint}/compact`, {});
+ return true;
+ }
+ if (action === 'fork')
+ return this.session(
+ await data('POST', `${endpoint}/fork`, { before: input.messageID })
+ );
+ if (action === 'revert') {
+ await raw('POST', `${endpoint}/revert/stage`, { messageID: input.messageID, files: true });
+ return this.session(await data('GET', endpoint));
+ }
+ if (action === 'unrevert') {
+ await raw('DELETE', `${endpoint}/revert`);
+ return this.session(await data('GET', endpoint));
+ }
+ if (action === 'diff')
+ return data(
+ 'GET',
+ `${endpoint}/diff${url.searchParams.has('messageID') ? `?from=${encodeURIComponent(url.searchParams.get('messageID')!)}` : ''}`
+ );
+ if (action === 'todo') {
+ const messages = await data(
+ 'GET',
+ `${endpoint}/message?limit=100&order=desc`
+ );
+ for (const message of messages) {
+ if (message.type !== 'assistant') continue;
+ for (const content of message.content.toReversed()) {
+ if (
+ content.type === 'tool' &&
+ content.name === 'todowrite' &&
+ content.state.status !== 'streaming' &&
+ Array.isArray(content.state.input.todos)
+ )
+ return content.state.input.todos;
+ }
+ }
+ return [];
+ }
+ }
+ if (route === '/command' && method === 'GET') {
+ // V2 exposes executable callbacks, not their templates. Keep the UI's text fields defined.
+ const commands = (await data('GET', query('/api/command', true))).map(
+ (command) => ({
+ ...command,
+ description: command.description ?? '',
+ template: '',
+ hints: [],
+ })
+ );
+ const config = asRecord(await this.request('GET', '/config', undefined, options));
+ for (const [name, value] of Object.entries(asRecord(config?.commands) ?? {})) {
+ const command = asRecord(value);
+ if (!command || !isString(command.template)) continue;
+ const normalized = {
+ name,
+ description: isString(command.description) ? command.description : '',
+ template: command.template,
+ hints: [],
+ };
+ const existing = commands.findIndex((entry) => entry.name === name);
+ if (existing >= 0) commands[existing] = normalized;
+ else commands.push(normalized);
+ }
+ return commands;
+ }
+ if (['/skill', '/project', '/vcs', '/vcs/status'].includes(route) && method === 'GET')
+ return data('GET', query(`/api${route}`, true));
+ if (route === '/project/current' || route === '/path') {
+ const location = await raw('GET', query('/api/location', true));
+ const record = asRecord(location) ?? {};
+ const project = asRecord(record.project) ?? {};
+ return route === '/project/current'
+ ? { ...project, worktree: project.directory }
+ : { directory: record.directory, worktree: project.directory, config: '', state: '' };
+ }
+ if (route === '/mcp' && method === 'GET') {
+ const servers = await data('GET', query('/api/mcp', true));
+ return Object.fromEntries(servers.map((server) => [String(server.name), server.status]));
+ }
+ const mcpAuth = route.match(/^\/mcp\/([^/]+)\/auth(?:\/(authenticate|callback))?$/);
+ if (mcpAuth) {
+ const name = decodeURIComponent(mcpAuth[1]!);
+ const servers = await data('GET', query('/api/mcp', true));
+ const integrationID = servers.find((server) => server.name === name)?.integrationID;
+ if (!isString(integrationID))
+ throw new Error('This MCP server does not expose an OpenCode authentication integration');
+ const key = `mcp:${name}`;
+ if (method === 'DELETE') {
+ await this.authenticate(key, undefined, method, input, directory, options, integrationID);
+ return { success: true };
+ }
+ if (mcpAuth[2] === 'callback') {
+ await this.authenticate(key, 'callback', 'POST', input, directory, options, integrationID);
+ return asRecord(await this.request('GET', '/mcp', undefined, options))?.[name];
+ }
+ const authorization = asRecord(
+ await this.authenticate(key, 'authorize', 'POST', input, directory, options, integrationID)
+ );
+ if (!isString(authorization?.url))
+ throw new Error('OpenCode did not provide an MCP authentication URL');
+ if (mcpAuth[2] !== 'authenticate')
+ return { authorizationUrl: authorization.url, oauthState: this.oauth.get(key)?.attemptID };
+ if (!(await this.openExternal(authorization.url)))
+ throw new Error('Could not open the MCP authentication page');
+ await this.authenticate(key, 'callback', 'POST', {}, directory, options, integrationID);
+ return true;
+ }
+ const mcp = route.match(/^\/mcp\/([^/]+)\/(connect|disconnect)$/);
+ if (mcp) {
+ await raw('POST', query(`/api/experimental/mcp/${mcp[1]}/${mcp[2]}`, true), {});
+ return true;
+ }
+ if (route === '/lsp') return []; // V2 intentionally has no LSP service.
+ if (route === '/experimental/workspace/status') return []; // V2 does not expose legacy workspace warp jobs.
+ const auth = route.match(/^\/(?:auth|provider)\/([^/]+)(?:\/oauth\/(authorize|callback))?$/);
+ if (auth)
+ return this.authenticate(
+ decodeURIComponent(auth[1]!),
+ auth[2],
+ method,
+ input,
+ directory,
+ options
+ );
+ throw new Error(`OpenCode v2 does not support this Varro operation: ${method} ${route}`);
+ }
+
+ private async session(value: SessionInfo): Promise {
+ const projected = projectV2Session(value);
+ const annotations = await this.annotations.read(value.id);
+ return { ...projected, ...annotations, time: { ...value.time, ...asRecord(annotations.time) } };
+ }
+
+ private async providers(
+ route: string,
+ directory: string | undefined,
+ options: OpenCodeRequestOptions
+ ): Promise {
+ const query = directory ? `?location[directory]=${encodeURIComponent(directory)}` : '';
+ const [providerResult, modelResult, configResult, integrationResult] = await Promise.all([
+ this.wire('GET', `/api/provider${query}`, undefined, { ...options, unscoped: true }),
+ this.wire('GET', `/api/model${query}`, undefined, { ...options, unscoped: true }),
+ this.request('GET', '/config', undefined, { ...options, directory }),
+ this.wire('GET', `/api/integration${query}`, undefined, { ...options, unscoped: true }),
+ ]);
+ const providers = asRecord(providerResult)?.data as ProviderInfo[];
+ const models = asRecord(modelResult)?.data as ModelInfo[];
+ if (!Array.isArray(providers) || !Array.isArray(models))
+ throw new Error('Invalid OpenCode v2 provider catalog');
+ const all = providers.map((provider) => ({
+ ...provider,
+ env: [],
+ source: 'config',
+ options: provider.settings ?? {},
+ models: Object.fromEntries(
+ models
+ .filter((model) => model.providerID === provider.id)
+ .map((model) => [model.id, projectV2Model(model)])
+ ),
+ }));
+ const integrations = asRecord(integrationResult)?.data as IntegrationInfo[];
+ if (!Array.isArray(integrations)) throw new Error('Invalid OpenCode v2 integration catalog');
+ for (const integration of integrations) {
+ if (
+ !all.some(
+ (provider) => provider.integrationID === integration.id || provider.id === integration.id
+ )
+ )
+ all.push({
+ id: integration.id,
+ integrationID: integration.id,
+ name: integration.name,
+ package: '',
+ activation: 'auto',
+ env: [],
+ source: 'api',
+ options: {},
+ models: {},
+ });
+ }
+ // 2.0.5's catalog omits custom configuration entries even though prompt resolution accepts them.
+ const configured = asRecord(asRecord(configResult)?.providers) ?? {};
+ for (const [id, entry] of Object.entries(configured)) {
+ const provider = asRecord(entry);
+ if (!provider) continue;
+ let target = all.find((item) => item.id === id);
+ if (!target) {
+ target = {
+ id,
+ name: isString(provider.name) ? provider.name : id,
+ package: String(provider.package ?? ''),
+ activation: 'enabled',
+ env: [],
+ source: 'config',
+ options: {},
+ models: {},
+ };
+ all.push(target);
+ }
+ for (const [modelID, definition] of Object.entries(asRecord(provider.models) ?? {})) {
+ const model = asRecord(definition);
+ if (!model) continue;
+ const existing = target.models[modelID];
+ target.models[modelID] = {
+ id: modelID,
+ providerID: id,
+ name: model.name ?? modelID,
+ api: { id: model.modelID ?? modelID, npm: provider.package ?? '', url: '' },
+ cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
+ capabilities: { tools: true, input: ['text'], output: ['text'] },
+ limit: { context: 0, output: 0 },
+ ...existing,
+ ...model,
+ enabled: model.disabled !== true,
+ variants: Array.isArray(model.variants)
+ ? Object.fromEntries(
+ model.variants.map((variant) => [String(asRecord(variant)?.id), variant])
+ )
+ : (existing?.variants ?? {}),
+ };
+ }
+ }
+ const defaults = Object.fromEntries(
+ all.map((provider) => [
+ provider.id,
+ Object.keys(provider.models).find((id) => provider.models[id]?.enabled !== false) ?? '',
+ ])
+ );
+ return route === '/config/providers'
+ ? { providers: all, default: defaults }
+ : {
+ all,
+ default: defaults,
+ connected: all
+ .filter((provider) =>
+ Object.values(provider.models).some((model) => model.enabled !== false)
+ )
+ .map((provider) => provider.id),
+ };
+ }
+
+ private async authenticate(
+ providerID: string,
+ action: string | undefined,
+ method: string,
+ input: UnknownRecord,
+ directory: string | undefined,
+ options: OpenCodeRequestOptions,
+ integrationOverride?: string
+ ): Promise {
+ const suffix = directory ? `?location[directory]=${encodeURIComponent(directory)}` : '';
+ const raw = (verb: string, path: string, body?: unknown) =>
+ this.wire(verb, path + suffix, body, { ...options, unscoped: true });
+ let integrationID = integrationOverride ?? providerID;
+ if (!integrationOverride) {
+ try {
+ const provider = asRecord(
+ asRecord(await raw('GET', `/api/provider/${encodeURIComponent(providerID)}`))?.data
+ );
+ if (isString(provider?.integrationID)) integrationID = provider.integrationID;
+ } catch (error) {
+ if (!(error instanceof Error) || !error.message.startsWith('404 ')) throw error;
+ // Disconnected integrations need not have a registered provider yet.
+ }
+ }
+ const base = `/api/integration/${encodeURIComponent(integrationID)}`;
+ if (method === 'PUT' && input.type === 'api') {
+ await raw('POST', `${base}/connect/key`, { key: input.key });
+ return true;
+ }
+ if (method === 'DELETE') {
+ const integration = asRecord(await raw('GET', base))?.data as IntegrationInfo;
+ const credentials = integration.connections.filter(
+ (connection) => connection.type === 'credential'
+ );
+ if (!credentials.length && integration.connections.length)
+ throw new Error(
+ 'Remove the provider environment variable to disconnect this OpenCode integration'
+ );
+ for (const credential of credentials)
+ await raw('DELETE', `/api/credential/${encodeURIComponent(credential.id)}`);
+ return true;
+ }
+ if (action === 'authorize') {
+ const integration = asRecord(await raw('GET', base))?.data as IntegrationInfo;
+ const methods = integration.methods.filter(
+ (item) => item.type === 'key' || item.type === 'oauth'
+ );
+ const selected = methods[Number(input.method ?? 0)];
+ if (selected?.type !== 'oauth') throw new Error('Unsupported OpenCode authentication method');
+ const answer = { ...asRecord(input.inputs) };
+ for (const field of selected.form ?? []) {
+ if (field.type === 'external' || !field.hidden || answer[field.key] !== undefined) continue;
+ if (
+ field.when?.some((condition) =>
+ condition.op === 'eq'
+ ? answer[condition.key] !== condition.value
+ : answer[condition.key] === condition.value
+ )
+ )
+ continue;
+ if (field.default !== undefined) answer[field.key] = field.default;
+ }
+ const result = asRecord(
+ asRecord(
+ await raw('POST', `${base}/connect/oauth`, {
+ methodID: selected.id,
+ answer: Object.keys(answer).length > 0 ? answer : input.inputs,
+ })
+ )?.data
+ );
+ if (!isString(result?.attemptID)) throw new Error('Invalid OpenCode OAuth attempt');
+ this.oauth.set(providerID, { integrationID, attemptID: result.attemptID });
+ return {
+ url: result.url,
+ method: result.mode === 'code' ? 'code' : 'auto',
+ instructions: result.instructions ?? '',
+ };
+ }
+ if (action === 'callback') {
+ const attempt = this.oauth.get(providerID);
+ if (!attempt) throw new Error('OpenCode OAuth attempt was not started');
+ if (input.code)
+ await raw(
+ 'POST',
+ `/api/integration/${encodeURIComponent(attempt.integrationID)}/connect/oauth/${encodeURIComponent(attempt.attemptID)}/complete`,
+ { code: input.code }
+ );
+ const deadline = Date.now() + 5 * 60_000;
+ while (true) {
+ options.signal?.throwIfAborted();
+ const result = asRecord(
+ asRecord(
+ await raw(
+ 'GET',
+ `/api/integration/${encodeURIComponent(attempt.integrationID)}/connect/oauth/${encodeURIComponent(attempt.attemptID)}`
+ )
+ )?.data
+ );
+ if (result?.status === 'complete') break;
+ if (result?.status !== 'pending' || Date.now() >= deadline)
+ throw new Error(
+ isString(result?.message) ? result.message : 'OpenCode authentication did not complete'
+ );
+ await delay(500, undefined, { signal: options.signal });
+ }
+ this.oauth.delete(providerID);
+ return true;
+ }
+ throw new Error('This credential operation requires OpenCode v2 credential management');
+ }
+
+ private async submit(sessionID: string, run: () => Promise): Promise {
+ const previous = this.submissions.get(sessionID);
+ const operation = (async () => {
+ await previous?.catch(() => {});
+ return run();
+ })();
+ this.submissions.set(sessionID, operation);
+ try {
+ return await operation;
+ } finally {
+ if (this.submissions.get(sessionID) === operation) this.submissions.delete(sessionID);
+ }
+ }
+}
diff --git a/src/extension/opencode-v2-events.ts b/src/extension/opencode-v2-events.ts
new file mode 100644
index 00000000..90427ba8
--- /dev/null
+++ b/src/extension/opencode-v2-events.ts
@@ -0,0 +1,229 @@
+/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/require-safety-comment-for-type-assertion -- Native event envelopes are narrowed before projecting released payload contracts. */
+import type { FormInfo, PermissionRequest } from '@opencode/client';
+import { asRecord, isString, isNumber, type UnknownRecord } from '../shared/type-utils';
+import { parseServerEvent } from '../shared/protocol';
+import {
+ projectV2Form,
+ projectV2Permission,
+ v1Action,
+ v2PartId,
+ v2ToolOutput,
+ projectV2Message,
+ normalizeV2Error,
+ type V2MessageContext,
+} from './opencode-v2-projection';
+
+/** Translate released v2 events into the existing Varro event vocabulary. */
+export function projectV2Event(value: unknown, context: V2MessageContext = {}): unknown[] {
+ const event = asRecord(value);
+ const data = asRecord(event?.data);
+ if (!event || !isString(event.type) || !data) return [];
+ const properties: UnknownRecord = { ...data, timestamp: event.created };
+ const location = asRecord(event.location) ?? asRecord(data.location);
+ const durable = asRecord(event.durable);
+ const base = {
+ id: event.id,
+ seq: durable?.seq,
+ workspaceDirectory: location?.directory ?? context.directory,
+ };
+ const emit = (type: string, props = properties): unknown[] => [
+ { ...base, type, properties: props },
+ ];
+ const sessionID = isString(data.sessionID) ? data.sessionID : '';
+ if (event.type === 'server.connected') return emit('server.connected');
+ if (event.type === 'session.created')
+ return emit('session.created', {
+ info: {
+ ...data,
+ id: sessionID,
+ directory: location?.directory,
+ time: { created: event.created, updated: event.created },
+ title: data.title ?? '',
+ },
+ });
+ if (event.type === 'session.renamed')
+ return emit('session.updated', {
+ info: { id: sessionID, title: data.title, time: { updated: event.created } },
+ });
+ if (event.type === 'session.deleted')
+ return emit('session.deleted', { sessionID, info: { id: sessionID } });
+ if (event.type === 'session.status.updated') return emit('session.status');
+ if (event.type === 'session.execution.started')
+ return emit('session.status', { sessionID, status: { type: 'busy' } });
+ if (
+ [
+ 'session.execution.succeeded',
+ 'session.execution.interrupted',
+ 'session.execution.failed',
+ ].includes(event.type)
+ ) {
+ if (event.type !== 'session.execution.failed')
+ return emit('session.status', { sessionID, status: { type: 'idle' } });
+ // Record the failure before settling busy state, so an idle notification cannot report success.
+ const error = normalizeV2Error(data.error);
+ const messages: unknown[] = [];
+ if (!context.hasAssistant && isString(event.id)) {
+ const failed = projectV2Message(
+ {
+ id: event.id.replace(/^evt_/, 'msg_'),
+ type: 'idle',
+ outcome: 'failed',
+ time: { created: isNumber(event.created) ? event.created : 0 },
+ },
+ sessionID,
+ context.directory,
+ context.parentID,
+ { ...context, error }
+ );
+ messages.push({
+ ...base,
+ id: `${event.id}:message`,
+ seq: undefined,
+ type: 'message.updated',
+ properties: { info: failed.info },
+ });
+ }
+ return [
+ ...messages,
+ ...emit('session.error', {
+ sessionID,
+ error: {
+ name: 'APIError',
+ data: {
+ message: error?.message ?? 'OpenCode execution failed',
+ statusCode: error?.status,
+ },
+ },
+ }),
+ {
+ ...base,
+ id: `${String(event.id)}:idle`,
+ seq: undefined,
+ type: 'session.status',
+ properties: { sessionID, status: { type: 'idle' } },
+ },
+ ];
+ }
+ if (event.type === 'permission.asked' && isString(data.id) && Array.isArray(data.resources))
+ return emit('permission.asked', projectV2Permission(data as PermissionRequest));
+ if (event.type === 'permission.replied') return emit('permission.replied');
+ if (event.type === 'form.created') {
+ const form = asRecord(data.form);
+ return form && Array.isArray(form.fields)
+ ? emit('question.asked', projectV2Form(form as FormInfo))
+ : [];
+ }
+ if (event.type === 'form.replied' || event.type === 'form.cancelled')
+ return emit(event.type === 'form.replied' ? 'question.replied' : 'question.rejected', {
+ ...properties,
+ requestID: data.id,
+ });
+ if (event.type === 'session.inbox.enqueued')
+ return emit('session.next.prompt.admitted', { ...properties, messageID: data.inboxID });
+ if (event.type === 'session.inbox.delivered')
+ return emit('session.next.prompted', { ...properties, messageID: data.inboxID });
+ if (event.type === 'session.skill.activated') return emit('session.next.synthetic');
+ if (event.type === 'session.shell.started' || event.type === 'session.shell.ended')
+ return emit(event.type.replace('session.', 'session.next.'), {
+ ...properties,
+ callID: asRecord(data.shell)?.id,
+ output: asRecord(data.output)?.output,
+ });
+ if (event.type === 'session.agent.selected') return emit('session.next.agent.switched');
+ if (event.type === 'session.model.selected')
+ return emit('session.next.model.switched', {
+ ...properties,
+ model: { ...asRecord(data.model), modelID: asRecord(data.model)?.id },
+ });
+ if (event.type === 'session.retry.scheduled')
+ return emit('session.status', {
+ sessionID,
+ status: {
+ type: 'retry',
+ attempt: data.attempt,
+ next: data.at,
+ message: asRecord(data.error)?.message ?? 'Retrying',
+ },
+ });
+ if (/^session\.(text|reasoning)\./.test(event.type)) {
+ if (!isString(data.assistantMessageID) || !isNumber(data.ordinal)) return [];
+ const type = event.type.startsWith('session.text.') ? 'text' : 'reasoning';
+ const partID = v2PartId(data.assistantMessageID, type, data.ordinal);
+ return emit(event.type.replace('session.', 'session.next.'), {
+ ...properties,
+ textID: partID,
+ reasoningID: partID,
+ });
+ }
+ if (event.type.startsWith('session.tool.')) {
+ return emit(event.type.replace('session.', 'session.next.'), {
+ ...properties,
+ callID: data.id,
+ structured: data.metadata,
+ provider: data.state,
+ result: data.resultState,
+ name: isString(data.name) ? v1Action(data.name) : undefined,
+ output: v2ToolOutput(data.content),
+ });
+ }
+ if (event.type.startsWith('session.step.')) {
+ if (event.type === 'session.step.streamed')
+ return emit('session.next.context.updated', { sessionID });
+ const model = asRecord(data.model);
+ return emit(event.type.replace('session.', 'session.next.'), {
+ ...properties,
+ timestamp:
+ event.type === 'session.step.started' && isNumber(data.started)
+ ? data.started
+ : properties.timestamp,
+ model: model ? { ...model, modelID: model.id } : undefined,
+ executionContinues: true,
+ });
+ }
+ if (
+ /^session\.(compaction|revert)\./.test(event.type) ||
+ ['session.synthetic', 'session.moved'].includes(event.type)
+ ) {
+ if (event.type === 'session.compaction.failed')
+ return [
+ ...emit('session.next.compaction.ended'),
+ {
+ ...base,
+ id: `${event.id}:error`,
+ seq: undefined,
+ type: 'session.error',
+ properties: {
+ sessionID,
+ error: {
+ name: 'APIError',
+ data: { message: asRecord(data.error)?.message ?? 'Compaction failed' },
+ },
+ },
+ },
+ ];
+ return emit(event.type.replace('session.', 'session.next.'));
+ }
+ if (
+ [
+ 'provider.updated',
+ 'model.updated',
+ 'agent.updated',
+ 'integration.updated',
+ 'credential.updated',
+ ].includes(event.type)
+ )
+ return emit('catalog.updated');
+ if (event.type === 'config.updated') return emit('global.disposed');
+ if (parseServerEvent(event)) return [event];
+ // Account for durable events which have no UI representation, without fabricating activity.
+ return sessionID && isNumber(durable?.seq)
+ ? [
+ {
+ ...base,
+ type: 'session.next.context.updated',
+ sequenceOnly: true,
+ properties: { sessionID },
+ },
+ ]
+ : [];
+}
diff --git a/src/extension/opencode-v2-inbox.test.ts b/src/extension/opencode-v2-inbox.test.ts
new file mode 100644
index 00000000..41f73238
--- /dev/null
+++ b/src/extension/opencode-v2-inbox.test.ts
@@ -0,0 +1,128 @@
+/* oxlint-disable anti-slop/no-module-mocking -- The adapter's transport imports the VS Code output channel. */
+import { describe, expect, it, vi } from 'vitest';
+import type { SessionInboxUser, SessionMessageUser } from '@opencode/client';
+import { OpenCodeV2Adapter } from './opencode-v2-adapter';
+import { projectV2Message } from './opencode-v2-projection';
+
+vi.mock('./logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+const pending: SessionInboxUser = {
+ id: 'msg_steer',
+ sessionID: 'ses_one',
+ type: 'user',
+ delivery: 'steer',
+ time: { created: 3 },
+ payload: {
+ text: 'Focus on the adapter',
+ files: [
+ {
+ name: 'example.png',
+ mime: 'image/png',
+ data: 'aGVsbG8=',
+ source: { type: 'uri', uri: 'file:///repo/example.png' },
+ },
+ ],
+ agents: [{ name: 'build' }],
+ },
+};
+
+const delivered: SessionMessageUser = {
+ ...pending.payload,
+ id: pending.id,
+ type: 'user',
+ time: pending.time,
+};
+
+const original: SessionMessageUser = {
+ id: 'msg_original',
+ type: 'user',
+ time: { created: 1 },
+ text: 'Review the changes',
+};
+
+describe('v2 pending steering history', () => {
+ it('restores pending prompts on reopen and keeps their identities after delivery', async () => {
+ let consumed = false;
+ const wire = vi.fn(async (_method: string, path: string) => {
+ if (path.endsWith('/inbox')) return { data: consumed ? [] : [pending] };
+ return { data: consumed ? [delivered, original] : [original] };
+ });
+ const reopen = () =>
+ new OpenCodeV2Adapter(wire).request('GET', '/session/ses_one/message', undefined);
+ const expected = [
+ projectV2Message(original, 'ses_one'),
+ projectV2Message(delivered, 'ses_one'),
+ ];
+ expect(await reopen()).toEqual(expected);
+ expect(await reopen()).toEqual(expected);
+ consumed = true;
+ expect(await reopen()).toEqual(expected);
+ });
+
+ it('deduplicates a prompt delivered between the inbox and transcript reads', async () => {
+ const paths: string[] = [];
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => {
+ paths.push(path);
+ return { data: path.endsWith('/inbox') ? [pending] : [delivered, original] };
+ });
+ expect(await adapter.request('GET', '/session/ses_one/message', undefined)).toEqual([
+ projectV2Message(original, 'ses_one'),
+ projectV2Message(delivered, 'ses_one'),
+ ]);
+ expect(paths).toEqual([
+ '/api/session/ses_one/inbox',
+ '/api/session/ses_one/message?order=desc&limit=200',
+ ]);
+ });
+
+ it('appends only user inputs in creation order without changing the history cursor', async () => {
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => {
+ if (path.endsWith('/inbox'))
+ return {
+ data: [
+ { ...pending, id: 'msg_queue', delivery: 'queue', time: { created: 4 } },
+ { ...pending, id: 'msg_internal', type: 'synthetic' },
+ pending,
+ ],
+ };
+ return { data: [original], cursor: { next: 'older' } };
+ });
+ expect(
+ await adapter.request('GET', '/session/ses_one/message?limit=1', undefined, {
+ captureNextCursor: true,
+ stripMessageParts: true,
+ })
+ ).toMatchObject({
+ data: [
+ { info: { id: 'msg_original' }, parts: [] },
+ { info: { id: 'msg_steer' }, parts: [] },
+ { info: { id: 'msg_queue' }, parts: [] },
+ ],
+ nextCursor: 'older',
+ });
+ });
+
+ it('does not append pending inputs to older history pages', async () => {
+ const wire = vi.fn(async () => ({ data: [original] }));
+ const adapter = new OpenCodeV2Adapter(wire);
+ expect(
+ await adapter.request('GET', '/session/ses_one/message?before=older&limit=1', undefined)
+ ).toEqual([projectV2Message(original, 'ses_one')]);
+ expect(wire).toHaveBeenCalledTimes(1);
+ expect(wire).toHaveBeenCalledWith(
+ 'GET',
+ '/api/session/ses_one/message?limit=1&cursor=older',
+ undefined,
+ expect.anything()
+ );
+ });
+
+ it('shows pending inputs even before the first transcript message exists', async () => {
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => ({
+ data: path.endsWith('/inbox') ? [pending] : [],
+ }));
+ expect(await adapter.request('GET', '/session/ses_one/message', undefined)).toEqual([
+ projectV2Message(delivered, 'ses_one'),
+ ]);
+ });
+});
diff --git a/src/extension/opencode-v2-projection.ts b/src/extension/opencode-v2-projection.ts
new file mode 100644
index 00000000..f92e65a7
--- /dev/null
+++ b/src/extension/opencode-v2-projection.ts
@@ -0,0 +1,451 @@
+/* oxlint-disable anti-slop/no-unknown-parameters -- This adapter validates and projects external protocol records. */
+import type {
+ AgentInfo,
+ ModelInfo,
+ PermissionRequest,
+ SessionInfo,
+ SessionMessageInfo,
+ SessionMessageAssistantTool,
+ FormInfo,
+ ModelRef,
+ SessionStructuredError,
+} from '@opencode/client';
+import { asRecord, isNumber, isString, type UnknownRecord } from '../shared/type-utils';
+import { formatSkillAttachment } from '../shared/skill-reference';
+
+export function v2PartId(messageID: string, type: string, ordinal: number): string {
+ return `${messageID}:${type}:${ordinal}`;
+}
+
+export function v2ModelRef(value: unknown): UnknownRecord | undefined {
+ if (isString(value)) {
+ const match = value.match(/^([^/]+)\/(.+?)(?:#([^#]+))?$/);
+ return match ? { providerID: match[1], id: match[2], variant: match[3] } : undefined;
+ }
+ const model = asRecord(value);
+ if (!model || !isString(model.providerID)) return undefined;
+ const id = model.modelID ?? model.id ?? model.model;
+ return isString(id)
+ ? {
+ providerID: model.providerID,
+ id,
+ variant: isString(model.variant) ? model.variant : undefined,
+ }
+ : undefined;
+}
+
+export function v2Action(action: string): string {
+ if (action === 'bash') return 'shell';
+ if (action === 'task') return 'subagent';
+ if (action === 'write' || action === 'patch') return 'edit';
+ return action;
+}
+
+export function v1Action(action: string): string {
+ if (action === 'shell') return 'bash';
+ if (action === 'subagent') return 'task';
+ return action;
+}
+
+export function v2Rules(value: unknown): UnknownRecord[] {
+ if (!Array.isArray(value)) throw new Error('Invalid OpenCode permission rules');
+ return value.map((item: unknown) => {
+ const rule = asRecord(item);
+ const action = rule?.permission ?? rule?.action;
+ const resource = rule?.pattern ?? rule?.resource;
+ const effect = rule?.permission !== undefined ? rule.action : rule?.effect;
+ if (
+ !isString(action) ||
+ !isString(resource) ||
+ !['allow', 'deny', 'ask'].includes(String(effect))
+ )
+ throw new Error('Invalid OpenCode permission rule');
+ return { action: v2Action(action), resource, effect };
+ });
+}
+
+export function projectV2Session(session: SessionInfo): UnknownRecord {
+ return {
+ ...session,
+ sharingSupported: false,
+ // Native v2 omits the legacy version field required by recycle-bin snapshots.
+ version: '2',
+ title: session.title ?? '',
+ directory: session.location.directory,
+ permission: session.permissions?.map((rule) => ({
+ permission: v1Action(rule.action),
+ pattern: rule.resource,
+ action: rule.effect,
+ })),
+ model: session.model ? { ...session.model, modelID: session.model.id } : undefined,
+ revert: session.revert,
+ };
+}
+
+export function projectV2Permission(request: PermissionRequest): UnknownRecord {
+ const source = asRecord(request.source);
+ return {
+ ...request,
+ permission: v1Action(request.action),
+ patterns: request.resources,
+ always: request.save ?? request.resources,
+ metadata: request.metadata ?? {},
+ tool: source ? { messageID: source.messageID, callID: source.callID ?? source.id } : undefined,
+ };
+}
+
+export function projectV2Agent(agent: AgentInfo): UnknownRecord {
+ return {
+ ...agent,
+ name: agent.id,
+ prompt: agent.system,
+ model: agent.model
+ ? { providerID: agent.model.providerID, modelID: agent.model.id }
+ : undefined,
+ variant: agent.model?.variant,
+ permission: agent.permissions.map((rule) => ({
+ permission: v1Action(rule.action),
+ pattern: rule.resource,
+ action: rule.effect,
+ })),
+ options: agent.request.body ?? {},
+ };
+}
+
+export function projectV2Model(model: ModelInfo): UnknownRecord {
+ const cost = model.cost.find((tier) => !tier.tier) ?? model.cost[0];
+ const released = new Date(model.time.released);
+ return {
+ ...model,
+ release_date:
+ model.time.released > 0 && Number.isFinite(released.getTime())
+ ? released.toISOString().slice(0, 10)
+ : undefined,
+ api: { id: model.modelID, npm: model.package ?? '', url: '' },
+ cost: {
+ input: cost?.input ?? 0,
+ output: cost?.output ?? 0,
+ cache_read: cost?.cache.read ?? 0,
+ cache_write: cost?.cache.write ?? 0,
+ cache: { read: cost?.cache.read ?? 0, write: cost?.cache.write ?? 0 },
+ tiers: model.cost.filter((tier) => tier.tier),
+ },
+ variants: Object.fromEntries(model.variants.map((variant) => [variant.id, variant])),
+ capabilities: model.capabilities,
+ options: model.settings ?? {},
+ };
+}
+
+export function v2ToolOutput(value: unknown): string {
+ if (!Array.isArray(value)) return '';
+ return value
+ .map((item: unknown) => asRecord(item))
+ .filter((item) => item?.type === 'text')
+ .map((item) => item?.text ?? '')
+ .join('\n');
+}
+
+function projectTool(
+ tool: SessionMessageAssistantTool,
+ sessionID: string,
+ messageID: string
+): UnknownRecord {
+ const base = {
+ id: tool.id,
+ callID: tool.id,
+ sessionID,
+ messageID,
+ type: 'tool',
+ tool: v1Action(tool.name),
+ };
+ const state = tool.state;
+ const time = {
+ start: tool.time.ran ?? tool.time.created,
+ end: tool.time.completed,
+ };
+ if (state.status === 'streaming')
+ return { ...base, state: { status: 'pending', input: {}, raw: state.input } };
+ const metadata = state.metadata ?? {};
+ if (state.status === 'running') return { ...base, state: { ...state, metadata, time } };
+ const attachments = state.content
+ ?.filter((content) => content.type === 'file')
+ .map((content, index) => ({
+ id: `${tool.id}:file:${index}`,
+ sessionID,
+ messageID,
+ type: 'file',
+ url: content.uri,
+ mime: content.mime,
+ filename: content.name,
+ }));
+ return {
+ ...base,
+ state: {
+ ...state,
+ metadata,
+ title: isString(metadata.title) ? metadata.title : undefined,
+ time,
+ output: v2ToolOutput(state.content),
+ error: state.status === 'error' ? state.error.message : undefined,
+ attachments,
+ },
+ };
+}
+
+export type ProjectedV2Message = { info: UnknownRecord; parts: UnknownRecord[] };
+
+export type V2MessageContext = {
+ agent?: string;
+ model?: ModelRef;
+ parentID?: string;
+ directory?: string;
+ hasAssistant?: boolean;
+ error?: SessionStructuredError;
+};
+
+export function normalizeV2Error(value: unknown): SessionStructuredError | undefined {
+ const error = asRecord(value);
+ if (!isString(error?.message)) return undefined;
+ const authorization = /^(?:Integration\.Authorization:\s*)?Request failed:\s*(401|403)\b/i.exec(
+ error.message
+ );
+ return {
+ type: isString(error.type) ? error.type : 'unknown',
+ message: error.message.slice(0, 16384),
+ status: isNumber(error.status)
+ ? error.status
+ : authorization
+ ? Number(authorization[1])
+ : undefined,
+ };
+}
+
+export function isV2TranscriptMessage(message: SessionMessageInfo): boolean {
+ return (
+ message.type === 'user' ||
+ message.type === 'assistant' ||
+ message.type === 'compaction' ||
+ message.type === 'skill' ||
+ message.type === 'shell' ||
+ (message.type === 'idle' && message.outcome === 'failed')
+ );
+}
+
+export function projectV2Message(
+ message: SessionMessageInfo,
+ sessionID: string,
+ directory = '',
+ parentID = '',
+ context: V2MessageContext = {}
+): ProjectedV2Message {
+ const base = { id: message.id, sessionID, time: message.time };
+ const part = (ordinal: number, type: string, fields: UnknownRecord): UnknownRecord => ({
+ id: v2PartId(message.id, message.type === 'assistant' ? type : 'content', ordinal),
+ sessionID,
+ messageID: message.id,
+ type,
+ ...fields,
+ });
+ if (message.type === 'skill' || message.type === 'shell') {
+ const completed = message.type === 'skill' || message.status !== 'running';
+ const time = {
+ created: message.time.created,
+ completed: completed
+ ? ((message.type === 'shell' ? message.time.completed : undefined) ?? message.time.created)
+ : undefined,
+ };
+ const input: Record =
+ message.type === 'skill' ? { name: message.skill } : { command: message.command };
+ const output = message.type === 'skill' ? message.text : (message.output?.output ?? '');
+ const shellFailure =
+ message.type === 'shell'
+ ? message.status === 'timeout' || message.status === 'killed'
+ ? `Shell ${message.status}`
+ : message.status === 'exited' && message.exit !== undefined && message.exit !== 0
+ ? `Shell exited with code ${message.exit}`
+ : undefined
+ : undefined;
+ const error = shellFailure
+ ? {
+ type: 'ShellError',
+ message: [output, shellFailure].filter(Boolean).join('\n'),
+ }
+ : undefined;
+ return projectV2Message(
+ {
+ id: message.id,
+ type: 'assistant',
+ agent: context.agent ?? '',
+ model: context.model ?? { providerID: '', id: '' },
+ time,
+ content: [
+ {
+ type: 'tool',
+ id: message.type === 'shell' ? message.shellID : v2PartId(message.id, 'content', 0),
+ name: message.type,
+ time,
+ state: error
+ ? { status: 'error', input, error }
+ : completed
+ ? { status: 'completed', input, content: [{ type: 'text', text: output }] }
+ : { status: 'running', input, metadata: { output } },
+ },
+ ],
+ },
+ sessionID,
+ directory,
+ parentID,
+ context
+ );
+ }
+ if (message.type === 'idle' && message.outcome === 'failed') {
+ const error = normalizeV2Error(context.error);
+ return {
+ info: {
+ ...base,
+ role: 'assistant',
+ parentID,
+ agent: context.agent ?? '',
+ mode: context.agent ?? '',
+ modelID: context.model?.id ?? '',
+ providerID: context.model?.providerID ?? '',
+ path: { cwd: directory, root: directory },
+ time: { created: message.time.created, completed: message.time.created },
+ cost: 0,
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
+ error: {
+ name:
+ error?.status === 401 || error?.status === 403 ? 'ProviderAuthError' : 'UnknownError',
+ data: {
+ providerID: context.model?.providerID,
+ statusCode: error?.status,
+ message:
+ error?.message ??
+ 'OpenCode failed before a response was recorded. Check the provider connection and the OpenCode server log.',
+ },
+ },
+ },
+ parts: [],
+ };
+ }
+ if (message.type === 'assistant') {
+ // V2 stream ordinals count within each content type, including empty blocks.
+ const ordinals = { text: 0, reasoning: 0 };
+ return {
+ info: {
+ ...base,
+ role: 'assistant',
+ parentID,
+ agent: message.agent,
+ mode: message.agent,
+ providerID: message.model.providerID,
+ modelID: message.model.id,
+ variant: message.model.variant,
+ path: { cwd: directory, root: directory },
+ cost: message.cost ?? 0,
+ tokens: message.tokens ?? {
+ input: 0,
+ output: 0,
+ reasoning: 0,
+ cache: { read: 0, write: 0 },
+ },
+ finish: message.finish,
+ error: message.error
+ ? {
+ name: message.error.type,
+ data: { message: message.error.message, statusCode: message.error.status },
+ }
+ : undefined,
+ },
+ parts: message.content.map((content) =>
+ content.type === 'tool'
+ ? projectTool(content, sessionID, message.id)
+ : part(ordinals[content.type]++, content.type, {
+ text: content.text,
+ time:
+ content.type === 'reasoning'
+ ? {
+ start: content.time?.created ?? message.time.created,
+ end: content.time?.completed,
+ }
+ : undefined,
+ })
+ ),
+ };
+ }
+ const info: UnknownRecord = {
+ ...base,
+ role: 'user',
+ agent: context.agent ?? '',
+ model: {
+ providerID: context.model?.providerID ?? '',
+ modelID: context.model?.id ?? '',
+ variant: context.model?.variant,
+ },
+ };
+ if (message.type === 'user') {
+ return {
+ info,
+ parts: [
+ part(0, 'text', { text: message.text }),
+ ...(message.files ?? []).map((file, index) =>
+ part(index + 1, 'file', {
+ mime: file.mime,
+ filename: file.name,
+ url:
+ file.source.type === 'uri'
+ ? file.source.uri
+ : `data:${file.mime};base64,${file.data}`,
+ })
+ ),
+ ...(message.agents ?? []).map((agent, index) =>
+ part((message.files?.length ?? 0) + index + 1, 'agent', { name: agent.name })
+ ),
+ ...(message.skills ?? []).map((skill, index) =>
+ part((message.files?.length ?? 0) + (message.agents?.length ?? 0) + index + 1, 'text', {
+ text: formatSkillAttachment(skill.name),
+ synthetic: true,
+ })
+ ),
+ ],
+ };
+ }
+ if (message.type === 'compaction')
+ return {
+ info,
+ parts: [
+ part(0, 'compaction', {
+ auto: message.reason === 'auto',
+ status: message.status,
+ error: message.status === 'failed' ? message.error.message : undefined,
+ }),
+ ],
+ };
+ // Control records and internal instructions must stay invisible on direct reads too.
+ return { info, parts: [] };
+}
+
+export function projectV2Form(form: FormInfo): UnknownRecord {
+ return {
+ id: form.id,
+ sessionID: form.sessionID,
+ questions: form.fields.map((field) => ({
+ header: field.title ?? form.title,
+ question: field.description ?? field.title ?? form.title,
+ multiple: field.type === 'multiselect',
+ custom: 'custom' in field ? field.custom !== false : true,
+ options:
+ 'options' in field
+ ? (field.options?.map((option) => ({
+ label: option.label,
+ description: option.description ?? '',
+ })) ?? [])
+ : field.type === 'boolean'
+ ? [
+ { label: 'Yes', description: '' },
+ { label: 'No', description: '' },
+ ]
+ : [],
+ })),
+ };
+}
diff --git a/src/extension/opencode-v2-session-state.ts b/src/extension/opencode-v2-session-state.ts
new file mode 100644
index 00000000..6824d503
--- /dev/null
+++ b/src/extension/opencode-v2-session-state.ts
@@ -0,0 +1,65 @@
+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { asRecord, type UnknownRecord } from '../shared/type-utils';
+
+/** V2 cannot patch metadata or archive timestamps. These are Varro-owned annotations. */
+export class OpenCodeV2SessionState {
+ private readonly operations = new Map>();
+
+ constructor(
+ private readonly directory = join(
+ process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'),
+ 'varro',
+ 'opencode-v2'
+ )
+ ) {}
+
+ async read(sessionID: string): Promise {
+ try {
+ return asRecord(JSON.parse(await readFile(this.path(sessionID), 'utf8'))) ?? {};
+ } catch (error) {
+ if (asRecord(error)?.code === 'ENOENT') return {};
+ throw new Error('Could not read Varro OpenCode v2 session annotations', { cause: error });
+ }
+ }
+
+ async update(sessionID: string, patch: UnknownRecord): Promise {
+ const previous = this.operations.get(sessionID);
+ const operation = (async () => {
+ await previous?.catch(() => {});
+ const current = await this.read(sessionID);
+ const next = {
+ ...current,
+ ...patch,
+ time: { ...asRecord(current.time), ...asRecord(patch.time) },
+ };
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
+ const path = this.path(sessionID);
+ const temporary = `${path}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(temporary, JSON.stringify(next), { mode: 0o600 });
+ await rename(temporary, path);
+ } finally {
+ await rm(temporary, { force: true });
+ }
+ })();
+ this.operations.set(sessionID, operation);
+ try {
+ await operation;
+ } finally {
+ if (this.operations.get(sessionID) === operation) this.operations.delete(sessionID);
+ }
+ }
+
+ async remove(sessionID: string): Promise {
+ await this.operations.get(sessionID);
+ await rm(this.path(sessionID), { force: true });
+ }
+
+ private path(sessionID: string): string {
+ if (!/^[a-zA-Z0-9_-]{1,256}$/.test(sessionID)) throw new Error('Invalid OpenCode session ID');
+ return join(this.directory, `${sessionID}.json`);
+ }
+}
diff --git a/src/extension/opencode-v2-transcript.test.ts b/src/extension/opencode-v2-transcript.test.ts
new file mode 100644
index 00000000..8eb9ca23
--- /dev/null
+++ b/src/extension/opencode-v2-transcript.test.ts
@@ -0,0 +1,258 @@
+/* oxlint-disable anti-slop/no-module-mocking -- The HTTP adapter imports the extension logger; transcript fixtures run without a VS Code host. */
+import { describe, expect, it, vi } from 'vitest';
+import type { SessionMessageInfo } from '@opencode/client';
+import { OpenCodeV2Adapter } from './opencode-v2-adapter';
+import { projectV2Event } from './opencode-v2-events';
+import { projectV2Message } from './opencode-v2-projection';
+import { parseServerEvent } from '../shared/protocol';
+import { parseSkillAttachment } from '../shared/skill-reference';
+
+vi.mock('./logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+describe('V2 generated transcript records', () => {
+ const base = { id: 'msg_generated', time: { created: 10 } };
+
+ it.each(['running', 'completed', 'failed'] as const)(
+ 'keeps %s compaction out of user text and preserves its status',
+ async (status) => {
+ const record: SessionMessageInfo =
+ status === 'failed'
+ ? {
+ ...base,
+ type: 'compaction',
+ status,
+ reason: 'auto',
+ error: { type: 'unknown', message: 'Summary failed' },
+ }
+ : {
+ ...base,
+ type: 'compaction',
+ status,
+ reason: 'auto',
+ summary: '## Objective\n\nGenerated instructions',
+ recent: '',
+ };
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => ({
+ data: path.endsWith('/inbox') ? [] : [record],
+ cursor: {},
+ }));
+ const projected = projectV2Message(record, 'ses_one');
+ expect(projected.parts).toEqual([
+ expect.objectContaining({ type: 'compaction', auto: true, status }),
+ ]);
+ if (status === 'failed') expect(projected.parts[0]?.error).toBe('Summary failed');
+ expect(await adapter.request('GET', '/session/ses_one/message', undefined)).toEqual([
+ projected,
+ ]);
+ expect(
+ await new OpenCodeV2Adapter(async () => ({ data: record })).request(
+ 'GET',
+ '/session/ses_one/message/msg_generated',
+ undefined
+ )
+ ).toEqual(projected);
+ }
+ );
+
+ it('renders skill activation as assistant activity instead of a user instruction bubble', () => {
+ const projected = projectV2Message(
+ {
+ ...base,
+ type: 'skill',
+ skill: 'review',
+ name: 'Review',
+ text: 'Internal skill instructions',
+ },
+ 'ses_one'
+ );
+ expect(projected.info).toMatchObject({
+ role: 'assistant',
+ time: { created: 10, completed: 10 },
+ });
+ expect(projected.parts).toEqual([
+ expect.objectContaining({
+ type: 'tool',
+ tool: 'skill',
+ state: expect.objectContaining({
+ status: 'completed',
+ input: { name: 'review' },
+ output: 'Internal skill instructions',
+ }),
+ }),
+ ]);
+ });
+
+ it('preserves user-selected skill attachments without exposing their expanded instructions', () => {
+ const projected = projectV2Message(
+ {
+ ...base,
+ type: 'user',
+ text: 'Review this',
+ agents: [{ name: 'build' }],
+ skills: [{ id: 'review', name: 'Code review', text: 'Internal skill instructions' }],
+ },
+ 'ses_one'
+ );
+ expect(projected.info.role).toBe('user');
+ expect(projected.parts[0]).toMatchObject({ type: 'text', text: 'Review this' });
+ expect(projected.parts[1]).toMatchObject({ type: 'agent', name: 'build' });
+ expect(parseSkillAttachment(String(projected.parts[2]?.text))).toBe('Code review');
+ expect(JSON.stringify(projected.parts)).not.toContain('Internal skill instructions');
+ expect(new Set(projected.parts.map((part) => part.id)).size).toBe(3);
+ });
+
+ it('retains unsuccessful shell exit status and output', () => {
+ expect(
+ projectV2Message(
+ {
+ ...base,
+ type: 'shell',
+ shellID: 'shell_failed',
+ command: 'false',
+ status: 'exited',
+ exit: 1,
+ output: { output: 'Command failed', cursor: 14, size: 14, truncated: false },
+ },
+ 'ses_one'
+ ).parts[0]
+ ).toMatchObject({
+ type: 'tool',
+ state: { status: 'error', error: 'Command failed\nShell exited with code 1' },
+ });
+ });
+
+ it.each(['running', 'exited', 'timeout', 'killed'] as const)(
+ 'renders %s shell output as a command activity',
+ (status) => {
+ const projected = projectV2Message(
+ {
+ ...base,
+ type: 'shell',
+ shellID: 'shell_one',
+ command: 'pwd',
+ status,
+ time: { created: 10, completed: status === 'running' ? undefined : 20 },
+ output: { output: '/workspace', cursor: 10, size: 10, truncated: false },
+ },
+ 'ses_one'
+ );
+ expect(projected.info.role).toBe('assistant');
+ expect(projected.parts).toEqual([
+ expect.objectContaining({
+ type: 'tool',
+ tool: 'bash',
+ callID: 'shell_one',
+ state: expect.objectContaining({
+ status: status === 'running' ? 'running' : status === 'exited' ? 'completed' : 'error',
+ input: { command: 'pwd' },
+ }),
+ }),
+ ]);
+ if (status === 'exited')
+ expect(projected.parts[0]).toMatchObject({ state: { output: '/workspace' } });
+ if (status === 'timeout' || status === 'killed') {
+ expect(projected.parts[0]).toMatchObject({
+ state: { error: expect.stringContaining(status) },
+ });
+ }
+ }
+ );
+
+ it.each(['system', 'synthetic'] as const)(
+ 'does not expose %s text on direct message reads',
+ async (type) => {
+ const adapter = new OpenCodeV2Adapter(async () => ({
+ data: { ...base, type, text: 'Internal instructions' },
+ }));
+ expect(
+ await adapter.request('GET', '/session/ses_one/message/msg_generated', undefined)
+ ).toMatchObject({ parts: [] });
+ }
+ );
+
+ it.each(['skill', 'shell'] as const)(
+ 'keeps a paginated %s activity attached to the original prompt',
+ async (type) => {
+ const record: SessionMessageInfo =
+ type === 'skill'
+ ? { ...base, type, skill: 'review', name: 'Review', text: 'Instructions' }
+ : { ...base, type, shellID: 'shell_one', command: 'pwd', status: 'exited' };
+ const wire = vi.fn(async (_method: string, path: string) => {
+ if (path.endsWith('/inbox')) return { data: [] };
+ if (path.endsWith('/msg_generated')) return { data: record };
+ if (path.includes('cursor=older'))
+ return {
+ data: [{ id: 'msg_user', type: 'user', text: 'Review', time: { created: 1 } }],
+ cursor: {},
+ };
+ return { data: [record], cursor: { next: 'older' } };
+ });
+ const adapter = new OpenCodeV2Adapter(wire);
+ adapter.observe('session.model.selected', {
+ sessionID: 'ses_one',
+ model: { id: 'model', providerID: 'provider' },
+ });
+ expect(
+ await adapter.request('GET', '/session/ses_one/message?limit=1', undefined, {
+ captureNextCursor: true,
+ })
+ ).toMatchObject({
+ data: [{ info: { role: 'assistant', parentID: 'msg_user', modelID: 'model' } }],
+ nextCursor: 'older',
+ });
+ expect(
+ await adapter.request('GET', '/session/ses_one/message/msg_generated', undefined)
+ ).toMatchObject({
+ info: { role: 'assistant', parentID: 'msg_user', modelID: 'model' },
+ });
+ }
+ );
+
+ it.each(['started', 'ended'] as const)('refreshes native shell %s records', (phase) => {
+ const events = projectV2Event({
+ id: 'evt_shell',
+ created: 10,
+ type: `session.shell.${phase}`,
+ durable: { seq: 5 },
+ data: { sessionID: 'ses_one', shell: { id: 'shell_one', command: 'pwd' } },
+ }).map(parseServerEvent);
+ expect(events).toEqual([
+ expect.objectContaining({
+ type: `session.next.shell.${phase}`,
+ seq: 5,
+ properties: expect.objectContaining({ sessionID: 'ses_one' }),
+ }),
+ ]);
+ });
+
+ it('refreshes skill activation records', () => {
+ expect(
+ projectV2Event({
+ id: 'evt_skill',
+ created: 10,
+ type: 'session.skill.activated',
+ durable: { seq: 6 },
+ data: { sessionID: 'ses_one', id: 'review', name: 'Review', text: 'Instructions' },
+ }).map(parseServerEvent)
+ ).toEqual([expect.objectContaining({ type: 'session.next.synthetic', seq: 6 })]);
+ });
+
+ it('refreshes failed compaction before reporting the failure, consuming its sequence once', () => {
+ const events = projectV2Event({
+ id: 'evt_failed',
+ created: 10,
+ type: 'session.compaction.failed',
+ durable: { seq: 7 },
+ data: {
+ sessionID: 'ses_one',
+ reason: 'auto',
+ error: { type: 'unknown', message: 'Summary failed' },
+ },
+ }).map(parseServerEvent);
+ expect(events).toMatchObject([
+ { type: 'session.next.compaction.ended', seq: 7 },
+ { type: 'session.error', properties: { error: { data: { message: 'Summary failed' } } } },
+ ]);
+ expect(events.filter((event) => event?.seq !== undefined)).toHaveLength(1);
+ });
+});
diff --git a/src/extension/opencode-v2.integration.test.ts b/src/extension/opencode-v2.integration.test.ts
new file mode 100644
index 00000000..9922dbd9
--- /dev/null
+++ b/src/extension/opencode-v2.integration.test.ts
@@ -0,0 +1,679 @@
+/* oxlint-disable anti-slop/no-module-mocking, anti-slop/require-safety-comment-for-type-assertion -- The VS Code logger is mocked; all OpenCode requests use an isolated real server. Assertions narrow fixture response shapes. */
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { spawnSync, type ChildProcess } from 'node:child_process';
+import crossSpawn from 'cross-spawn';
+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { createServer, type Server } from 'node:http';
+import { setTimeout as delay } from 'node:timers/promises';
+import { asRecord, isString, type UnknownRecord } from '../shared/type-utils';
+import { parseServerEvent } from '../shared/protocol';
+import { parseHealthResponse } from '../shared/health';
+import { OpenCodeTransport } from './open-code-transport';
+import { basicAuthorization, OpenCodeStartupOutput } from './opencode-connection';
+
+vi.mock('./logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+const binary = process.env.VARRO_OPENCODE_TEST_BINARY;
+
+describe.skipIf(!binary)('released OpenCode adapter contract', () => {
+ let child: ChildProcess;
+ let modelServer: Server;
+ let transport: OpenCodeTransport;
+ let root: string;
+ let url = '';
+ let authorization: string | undefined;
+ const events: unknown[] = [];
+ const modelRequests: unknown[] = [];
+ let sessionID = '';
+ let streamGate: Promise | undefined;
+ const providerPrompts: unknown[][] = [];
+
+ beforeAll(async () => {
+ const parent = resolve('artifacts/ai-test-data');
+ await mkdir(parent, { recursive: true });
+ root = await mkdtemp(join(parent, 'adapter-'));
+ for (const name of ['home', 'data', 'config', 'state', 'cache', 'workspace'])
+ await mkdir(join(root, name));
+ const git = spawnSync('git', ['init', '--quiet'], { cwd: join(root, 'workspace') });
+ if (git.status !== 0) throw new Error('Could not initialize isolated fixture repository');
+ await writeFile(join(root, 'workspace/probe.txt'), 'isolated tool fixture\n');
+ modelServer = createServer(async (request, response) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const payload = asRecord(JSON.parse(Buffer.concat(chunks).toString()));
+ modelRequests.push(payload);
+ if (payload?.stream === true) {
+ await streamGate;
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ const messages = Array.isArray(payload.messages) ? payload.messages.map(asRecord) : [];
+ providerPrompts.push(messages);
+ const lastUser = messages.findLastIndex((message) => message?.role === 'user');
+ const tools = Array.isArray(payload.tools) ? payload.tools.map(asRecord) : [];
+ const read = tools
+ .map((tool) => asRecord(tool?.function))
+ .find((tool) => tool?.name === 'read');
+ if (
+ read &&
+ JSON.stringify(messages[lastUser]?.content).includes('RUN_READ_FIXTURE') &&
+ !messages.slice(lastUser + 1).some((message) => message?.role === 'tool')
+ ) {
+ const fields = asRecord(asRecord(read.parameters)?.properties) ?? {};
+ const args = {
+ [fields.filePath ? 'filePath' : 'path']: join(root, 'workspace/probe.txt'),
+ };
+ response.write(
+ `data: ${JSON.stringify({ id: 'chatcmpl-tool', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'call_fixture_read', type: 'function', function: { name: 'read', arguments: JSON.stringify(args) } }] }, finish_reason: null }] })}\n\n`
+ );
+ response.end(
+ `data: ${JSON.stringify({ id: 'chatcmpl-tool', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }], usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 } })}\n\ndata: [DONE]\n\n`
+ );
+ return;
+ }
+ for (const text of ['Adapter ', 'stream ', 'verified.']) {
+ response.write(
+ `data: ${JSON.stringify({ id: 'chatcmpl-fixture', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: { content: text }, finish_reason: null }] })}\n\n`
+ );
+ await delay(20);
+ }
+ response.end(
+ `data: ${JSON.stringify({ id: 'chatcmpl-fixture', object: 'chat.completion.chunk', created: 1, model: 'fixture', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 } })}\n\ndata: [DONE]\n\n`
+ );
+ } else {
+ response.writeHead(200, { 'content-type': 'application/json' });
+ response.end(
+ JSON.stringify({
+ id: 'chatcmpl-fixture',
+ object: 'chat.completion',
+ created: 1,
+ model: 'fixture',
+ choices: [
+ {
+ index: 0,
+ message: { role: 'assistant', content: 'Adapter stream verified.' },
+ finish_reason: 'stop',
+ },
+ ],
+ usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 },
+ })
+ );
+ }
+ });
+ await new Promise((done) => modelServer.listen(0, '127.0.0.1', done));
+ const address = modelServer.address();
+ if (!address || isString(address)) throw new Error('Fixture server did not bind');
+ await writeFile(
+ join(root, 'workspace/opencode.json'),
+ JSON.stringify({
+ model: 'fixture/fixture',
+ command: { 'fixture-note': { template: 'Reply with the fixture response.' } },
+ provider: {
+ fixture: {
+ npm: '@ai-sdk/openai-compatible',
+ name: 'Fixture',
+ options: { baseURL: `http://127.0.0.1:${address.port}/v1`, apiKey: 'fixture-only' },
+ models: { fixture: { name: 'Fixture', limit: { context: 32000, output: 1000 } } },
+ },
+ },
+ })
+ );
+ const output = new OpenCodeStartupOutput((password) => {
+ authorization = basicAuthorization(password);
+ });
+ let logs = '';
+ child = crossSpawn(binary!, ['serve', '--hostname', '127.0.0.1', '--port', '0'], {
+ cwd: join(root, 'workspace'),
+ env: {
+ PATH: process.env.PATH,
+ HOME: join(root, 'home'),
+ XDG_DATA_HOME: join(root, 'data'),
+ XDG_CONFIG_HOME: join(root, 'config'),
+ XDG_STATE_HOME: join(root, 'state'),
+ XDG_CACHE_HOME: join(root, 'cache'),
+ OPENCODE_DB: join(root, 'data/probe.db'),
+ OPENCODE_TEST_HOME: join(root, 'home'),
+ OPENCODE_DISABLE_AUTOUPDATE: 'true',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const collect = (chunk: Buffer) => {
+ logs += output.write(chunk);
+ url = logs.match(/server listening on (http:\/\/\S+)/)?.[1] ?? '';
+ };
+ child.stdout?.on('data', collect);
+ child.stderr?.on('data', collect);
+ await vi.waitFor(
+ () => {
+ if (child.exitCode !== null) throw new Error(logs);
+ expect(url).not.toBe('');
+ },
+ { timeout: 20000 }
+ );
+ transport = new OpenCodeTransport({
+ getUrl: () => url,
+ getWorkspaceCwd: () => join(root, 'workspace'),
+ getStatus: () => ({ state: 'running', url }),
+ isDisposing: () => false,
+ updateEventStreamState: () => {},
+ emitEvent: (event) => events.push(event),
+ getAuthorization: () => authorization,
+ sessionStateDirectory: join(root, 'annotations'),
+ });
+ await vi.waitFor(async () => expect((await transport.readHealthInfo()).healthy).toBe(true), {
+ timeout: 20000,
+ });
+ if (process.env.VARRO_OPENCODE_TEST_VERSION)
+ expect((await transport.readHealthInfo()).version).toBe(
+ process.env.VARRO_OPENCODE_TEST_VERSION
+ );
+ void transport.startEventStream();
+ await vi.waitFor(() => expect(events.length).toBeGreaterThan(0));
+ }, 60000);
+
+ afterAll(async () => {
+ transport?.stopEventStream();
+ transport?.abortRequests();
+ child?.kill('SIGTERM');
+ if (child) await Promise.race([new Promise((done) => child.once('exit', done)), delay(3000)]);
+ if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ modelServer?.closeAllConnections();
+ await new Promise((done) => (modelServer ? modelServer.close(() => done()) : done()));
+ if (root) await writeFile(join(root, 'events.json'), JSON.stringify(events, null, 2));
+ });
+
+ it('loads bootstrap catalogs', async () => {
+ // Exercise the webview's public health route, not only the process startup probe.
+ const health = parseHealthResponse(await transport.request('GET', '/global/health'));
+ expect(health?.healthy).toBe(true);
+ if (process.env.VARRO_OPENCODE_TEST_VERSION)
+ expect(health?.version).toBe(process.env.VARRO_OPENCODE_TEST_VERSION);
+ const agents = await transport.request('GET', '/agent');
+ expect(Array.isArray(agents)).toBe(true);
+ const commands = (await transport.request('GET', '/command')) as UnknownRecord[];
+ const command = commands.find((entry) => entry.name === 'fixture-note');
+ expect(command).toBeDefined();
+ expect(isString(command?.description || command?.template)).toBe(true);
+ const providers = asRecord(await transport.request('GET', '/provider'));
+ await writeFile(
+ join(root, 'native-bootstrap.json'),
+ JSON.stringify(
+ {
+ default: await transport.request('GET', '/api/model/default'),
+ providers: await transport.request('GET', '/api/provider'),
+ models: await transport.request('GET', '/api/model'),
+ },
+ null,
+ 2
+ )
+ );
+ await writeFile(join(root, 'providers.json'), JSON.stringify(providers, null, 2));
+ await writeFile(
+ join(root, 'bootstrap.json'),
+ JSON.stringify(
+ {
+ location: await transport.request('GET', '/path'),
+ config: await transport.request('GET', '/config'),
+ },
+ null,
+ 2
+ )
+ );
+ expect(providers?.connected).toContain('fixture');
+ expect(asRecord(await transport.request('GET', '/config/providers'))?.providers).toBeInstanceOf(
+ Array
+ );
+ expect(await transport.request('GET', '/permission')).toEqual([]);
+ expect(await transport.request('GET', '/question')).toEqual([]);
+ expect(await transport.request('GET', '/session/status')).toEqual({});
+ expect(await transport.request('GET', '/experimental/session?limit=1000')).toEqual([]);
+ }, 60000);
+
+ it('creates, updates, and reads a session through the common API', async () => {
+ const session = asRecord(
+ await transport.request('POST', '/session', {
+ title: 'Adapter fixture',
+ metadata: { varro: { permissionMode: 'default' } },
+ })
+ );
+ expect(session?.directory).toBe(join(root, 'workspace'));
+ sessionID = String(session?.id);
+ const updated = asRecord(
+ await transport.request('PATCH', `/session/${sessionID}`, {
+ title: 'Adapter renamed',
+ metadata: { varro: { permissionMode: 'full' } },
+ permission: [{ permission: '*', pattern: '*', action: 'allow' }],
+ })
+ );
+ expect(updated?.title).toBe('Adapter renamed');
+ expect(updated?.metadata).toEqual({ varro: { permissionMode: 'full' } });
+ expect(updated?.permission).toEqual([{ permission: '*', pattern: '*', action: 'allow' }]);
+ }, 30000);
+
+ it('answers the first Plan prompt without a separate reminder-only turn', async () => {
+ const session = asRecord(
+ await transport.request('POST', '/session', { title: 'Plan fixture' })
+ );
+ const id = String(session?.id);
+ const start = providerPrompts.length;
+ const text = 'Create a dummy plan. Reply with the fixture response without calling tools.';
+ await transport.request('POST', `/session/${id}/prompt_async`, {
+ agent: 'plan',
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text }],
+ });
+ await vi.waitFor(
+ async () => {
+ const messages = (await transport.request(
+ 'GET',
+ `/session/${id}/message?limit=20`
+ )) as Array<{
+ info: UnknownRecord;
+ parts: UnknownRecord[];
+ }>;
+ expect(
+ messages.some(
+ (message) =>
+ message.info.role === 'user' && message.parts.some((part) => part.text === text)
+ )
+ ).toBe(true);
+ expect(
+ messages.some(
+ (message) => message.info.role === 'assistant' && asRecord(message.info.time)?.completed
+ )
+ ).toBe(true);
+ expect(asRecord(await transport.request('GET', '/session/status'))?.[id]).toBeUndefined();
+ },
+ { timeout: 45000, interval: 200 }
+ );
+ const prompts = providerPrompts.slice(start);
+ expect(prompts).toHaveLength(1);
+ expect(JSON.stringify(prompts[0])).toContain(text);
+ }, 60000);
+
+ it.skipIf(process.platform !== 'win32')(
+ 'loads instructions for a lowercase Windows drive',
+ async () => {
+ const directory = join(root, 'workspace').replace(/^[A-Z]:/, (drive) => drive.toLowerCase());
+ const session = asRecord(
+ await transport.request(
+ 'POST',
+ '/session',
+ { title: 'Windows instructions fixture' },
+ { directory }
+ )
+ );
+ const id = String(session?.id);
+ await transport.request(
+ 'POST',
+ `/session/${id}/prompt_async`,
+ {
+ agent: 'build',
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text: 'Say the fixture response. Do not call tools.' }],
+ },
+ { directory }
+ );
+ await vi.waitFor(
+ async () => {
+ const messages = await transport.request(
+ 'GET',
+ `/session/${id}/message?limit=20`,
+ undefined,
+ { directory }
+ );
+ expect(JSON.stringify(messages)).not.toContain('Instruction initialization blocked');
+ expect(JSON.stringify(messages)).toContain('Adapter stream verified.');
+ },
+ { timeout: 15000, interval: 200 }
+ );
+ },
+ 30000
+ );
+
+ it('streams a real prompt and projects stable history', async () => {
+ let release: (() => void) | undefined;
+ streamGate = new Promise((complete) => {
+ release = complete;
+ });
+ try {
+ await transport.request('POST', `/session/${sessionID}/prompt_async`, {
+ agent: 'build',
+ system: 'The VS Code workspace roots are /fixture/repo-a and /fixture/repo-b.',
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text: 'Say the fixture response. Do not call tools.' }],
+ });
+ await vi.waitFor(async () =>
+ expect(
+ asRecord(asRecord(await transport.request('GET', '/session/status'))?.[sessionID])?.type
+ ).toBe('busy')
+ );
+ } finally {
+ release?.();
+ streamGate = undefined;
+ }
+ let messages: Array<{ info: UnknownRecord; parts: UnknownRecord[] }> = [];
+ await vi.waitFor(
+ async () => {
+ messages = (await transport.request(
+ 'GET',
+ `/session/${sessionID}/message?limit=20`
+ )) as typeof messages;
+ expect(
+ messages.some((message) =>
+ message.parts.some((part) => part.text === 'Adapter stream verified.')
+ )
+ ).toBe(true);
+ expect(
+ messages.some(
+ (message) => message.info.role === 'assistant' && asRecord(message.info.time)?.completed
+ )
+ ).toBe(true);
+ },
+ { timeout: 45000, interval: 200 }
+ );
+ const assistant = messages.find((message) => message.info.role === 'assistant')!;
+ expect(JSON.stringify(modelRequests)).toContain(
+ 'The VS Code workspace roots are /fixture/repo-a and /fixture/repo-b.'
+ );
+ expect(assistant.info.modelID).toBe('fixture');
+ const text = assistant.parts.find((part) => part.type === 'text')!;
+ const delta = events
+ .map(parseServerEvent)
+ .find(
+ (event) =>
+ asRecord(event?.properties)?.textID === text.id ||
+ asRecord(event?.properties)?.partID === text.id
+ );
+ expect(delta).toBeDefined();
+ const page = asRecord(
+ await transport.request('GET', `/session/${sessionID}/message?limit=1`, undefined, {
+ captureNextCursor: true,
+ })
+ );
+ expect(page?.data).toHaveLength(1);
+ expect(page?.nextCursor).toBeTruthy();
+ expect(
+ asRecord(
+ await transport.request(
+ 'GET',
+ `/session/${sessionID}/message?limit=1&before=${encodeURIComponent(String(page?.nextCursor))}`,
+ undefined,
+ { captureNextCursor: true }
+ )
+ )?.data
+ ).toHaveLength(1);
+ }, 60000);
+
+ it('streams and reconciles an actual tool execution in the fixture', async () => {
+ await transport.request('POST', `/session/${sessionID}/prompt_async`, {
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text: 'RUN_READ_FIXTURE: read probe.txt with the read tool.' }],
+ });
+ await vi.waitFor(
+ async () => {
+ const messages = (await transport.request(
+ 'GET',
+ `/session/${sessionID}/message`
+ )) as Array<{ parts: UnknownRecord[] }>;
+ const tool = messages
+ .flatMap((message) => message.parts)
+ .find((part) => part.type === 'tool' && asRecord(part.state)?.status === 'completed');
+ expect(tool?.tool).toBe('read');
+ expect(asRecord(tool?.state)?.output).toContain('isolated tool fixture');
+ const matched = events
+ .map(parseServerEvent)
+ .some(
+ (event) =>
+ asRecord(event?.properties)?.callID === tool?.id ||
+ asRecord(asRecord(event?.properties)?.part)?.id === tool?.id
+ );
+ expect(matched).toBe(true);
+ const status = asRecord(await transport.request('GET', '/session/status'))?.[sessionID];
+ expect(status === undefined || asRecord(status)?.type === 'idle').toBe(true);
+ },
+ { timeout: 30000, interval: 100 }
+ );
+ }, 45000);
+
+ it('runs helper generation through the common message API', async () => {
+ const result = asRecord(
+ await transport.request('POST', `/session/${sessionID}/message`, {
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ system: 'Return the fixture response.',
+ parts: [{ type: 'text', text: 'Generate the response.' }],
+ })
+ );
+ expect(
+ (result?.parts as UnknownRecord[] | undefined)?.find((part) => part.type === 'text')?.text
+ ).toBe('Adapter stream verified.');
+ }, 30000);
+
+ it('executes a configured slash command through the common API', async () => {
+ const session = asRecord(
+ await transport.request('POST', '/session', { title: 'Command fixture' })
+ );
+ const id = String(session?.id);
+ try {
+ await transport.request('POST', `/session/${id}/command`, {
+ command: 'fixture-note',
+ arguments: '',
+ agent: 'build',
+ model: 'fixture/fixture',
+ });
+ await vi.waitFor(
+ async () => {
+ const messages = (await transport.request('GET', `/session/${id}/message`)) as Array<{
+ info: UnknownRecord;
+ parts: UnknownRecord[];
+ }>;
+ expect(messages.some((message) => message.info.role === 'user')).toBe(true);
+ expect(
+ messages.some(
+ (message) =>
+ message.info.role === 'assistant' &&
+ asRecord(message.info.time)?.completed &&
+ message.parts.some((part) => part.text === 'Adapter stream verified.')
+ )
+ ).toBe(true);
+ },
+ { timeout: 30000 }
+ );
+ } finally {
+ await transport.request('DELETE', `/session/${id}`);
+ }
+ }, 45000);
+
+ it('aborts an active provider request and accepts the next prompt', async () => {
+ const session = asRecord(
+ await transport.request('POST', '/session', { title: 'Abort fixture' })
+ );
+ const id = String(session?.id);
+ const start = modelRequests.length;
+ let release: (() => void) | undefined;
+ streamGate = new Promise((complete) => {
+ release = complete;
+ });
+ try {
+ await transport.request('POST', `/session/${id}/prompt_async`, {
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text: 'Wait for cancellation.' }],
+ });
+ await vi.waitFor(() => expect(modelRequests.length).toBeGreaterThan(start), {
+ timeout: 30000,
+ });
+ expect(await transport.request('POST', `/session/${id}/abort`, {})).toBe(true);
+ await vi.waitFor(async () => {
+ const status = asRecord(await transport.request('GET', '/session/status'))?.[id];
+ expect(status === undefined || asRecord(status)?.type === 'idle').toBe(true);
+ });
+ release?.();
+ streamGate = undefined;
+ await transport.request('POST', `/session/${id}/prompt_async`, {
+ model: { providerID: 'fixture', modelID: 'fixture' },
+ parts: [{ type: 'text', text: 'Reply after cancellation.' }],
+ });
+ await vi.waitFor(
+ async () => {
+ const messages = (await transport.request('GET', `/session/${id}/message`)) as Array<{
+ info: UnknownRecord;
+ parts: UnknownRecord[];
+ }>;
+ const last = messages.at(-1);
+ expect(last?.info.role).toBe('assistant');
+ expect(asRecord(last?.info.time)?.completed).toBeTruthy();
+ expect(last?.parts.some((part) => part.text === 'Adapter stream verified.')).toBe(true);
+ expect(messages.filter((message) => message.info.role === 'user')).toHaveLength(2);
+ },
+ { timeout: 30000 }
+ );
+ } finally {
+ release?.();
+ streamGate = undefined;
+ await transport.request('DELETE', `/session/${id}`);
+ }
+ }, 45000);
+
+ it('keeps native permission and form requests actionable through acknowledgement', async (context) => {
+ const health = await transport.readHealthInfo();
+ if (!health.version?.startsWith('2.')) {
+ context.skip();
+ return;
+ }
+ await transport.request('PATCH', `/session/${sessionID}`, {
+ permission: [{ permission: '*', pattern: '*', action: 'ask' }],
+ });
+ const waiting = transport.request('POST', `/api/session/${sessionID}/permission`, {
+ action: 'shell',
+ resources: ['fixture permission only'],
+ save: ['fixture permission only'],
+ metadata: {},
+ });
+ let permission: UnknownRecord | undefined;
+ await vi.waitFor(async () => {
+ const pending = (await transport.request('GET', '/permission')) as UnknownRecord[];
+ permission = pending.find((request) => request.sessionID === sessionID);
+ expect(permission?.permission).toBe('bash');
+ });
+ expect(
+ await transport.request('POST', `/permission/${permission?.id}/reply`, { reply: 'once' })
+ ).toBe(true);
+ expect(asRecord(asRecord(await waiting)?.data)?.effect).toBe('ask');
+ expect(await transport.request('GET', '/permission')).toEqual([]);
+ // Session-scoped Always uses a session rule plus a once reply, not the
+ // server's project-scoped native Always decision.
+ await transport.request('PATCH', `/session/${sessionID}`, {
+ permission: [{ permission: 'bash', pattern: 'fixture permission only', action: 'allow' }],
+ });
+ expect(asRecord(await transport.request('GET', `/session/${sessionID}`))?.permission).toEqual([
+ { permission: 'bash', pattern: 'fixture permission only', action: 'allow' },
+ ]);
+ const repeated = await transport.request('POST', `/api/session/${sessionID}/permission`, {
+ action: 'shell',
+ resources: ['fixture permission only'],
+ save: ['fixture permission only'],
+ metadata: {},
+ });
+ expect(asRecord(asRecord(repeated)?.data)?.effect).toBe('allow');
+ expect(await transport.request('GET', '/permission')).toEqual([]);
+ const form = asRecord(
+ asRecord(
+ await transport.request('POST', `/api/session/${sessionID}/form`, {
+ title: 'Fixture question',
+ fields: [
+ {
+ key: 'choice',
+ type: 'string',
+ title: 'Choose',
+ options: [{ value: 'accepted', label: 'Accept' }],
+ },
+ ],
+ })
+ )?.data
+ );
+ expect(form?.id).toBeTruthy();
+ const pending = (await transport.request('GET', '/question')) as UnknownRecord[];
+ expect(pending.some((request) => request.id === form?.id)).toBe(true);
+ expect(
+ await transport.request('POST', `/question/${form?.id}/reply`, { answers: [['Accept']] })
+ ).toBe(true);
+ expect(await transport.request('GET', '/question')).toEqual([]);
+ const cancelled = asRecord(
+ asRecord(
+ await transport.request('POST', `/api/session/${sessionID}/form`, {
+ title: 'Cancel fixture',
+ fields: [{ key: 'text', type: 'string' }],
+ })
+ )?.data
+ );
+ expect(await transport.request('POST', `/question/${cancelled?.id}/reject`, {})).toBe(true);
+ expect(await transport.request('GET', '/question')).toEqual([]);
+ }, 30000);
+
+ it('retains a pre-turn failure as an assistant error instead of an empty transcript', async (context) => {
+ if (!(await transport.readHealthInfo()).version?.startsWith('2.')) {
+ context.skip();
+ return;
+ }
+ const created = asRecord(
+ await transport.request('POST', '/session', { title: 'Adapter preflight failure' })
+ );
+ const id = String(created?.id);
+ try {
+ await transport.request('POST', `/session/${id}/prompt_async`, {
+ agent: 'build',
+ model: { providerID: 'missing', modelID: 'missing' },
+ parts: [{ type: 'text', text: 'Preflight failure fixture' }],
+ });
+ await vi.waitFor(
+ async () => {
+ const messages = (await transport.request('GET', `/session/${id}/message`)) as Array<{
+ info: UnknownRecord;
+ parts: UnknownRecord[];
+ }>;
+ expect(messages).toHaveLength(2);
+ expect(messages[0]?.info.role).toBe('user');
+ expect(messages[1]?.info.role).toBe('assistant');
+ expect(messages[1]?.info.error).toBeTruthy();
+ },
+ { timeout: 10000 }
+ );
+ expect(
+ events
+ .map(parseServerEvent)
+ .some(
+ (event) =>
+ event?.type === 'session.next.step.started' &&
+ asRecord(event.properties)?.sessionID === id
+ )
+ ).toBe(false);
+ } finally {
+ await transport.request('DELETE', `/session/${id}`);
+ }
+ });
+
+ it('forks, stages and clears a revert, then deletes test sessions', async () => {
+ const messages = (await transport.request('GET', `/session/${sessionID}/message`)) as Array<{
+ info: UnknownRecord;
+ }>;
+ const user = messages.find((message) => message.info.role === 'user')!;
+ const fork = asRecord(await transport.request('POST', `/session/${sessionID}/fork`, {}));
+ expect(fork?.id).toBeTruthy();
+ const forkMessages = (await transport.request('GET', `/session/${fork?.id}/message`)) as Array<{
+ info: UnknownRecord;
+ }>;
+ const tail = forkMessages.at(-1)!;
+ expect(await transport.request('DELETE', `/session/${fork?.id}/message/${tail.info.id}`)).toBe(
+ true
+ );
+ await transport.request('POST', `/session/${sessionID}/revert`, { messageID: user.info.id });
+ expect(
+ asRecord(asRecord(await transport.request('GET', `/session/${sessionID}`))?.revert)?.messageID
+ ).toBe(user.info.id);
+ await transport.request('POST', `/session/${sessionID}/unrevert`, {});
+ expect(
+ asRecord(await transport.request('GET', `/session/${sessionID}`))?.revert
+ ).toBeUndefined();
+ expect(await transport.request('DELETE', `/session/${fork?.id}`)).toBe(true);
+ expect(await transport.request('DELETE', `/session/${sessionID}`)).toBe(true);
+ }, 30000);
+});
diff --git a/src/extension/opencode-v2.test.ts b/src/extension/opencode-v2.test.ts
new file mode 100644
index 00000000..b5548648
--- /dev/null
+++ b/src/extension/opencode-v2.test.ts
@@ -0,0 +1,887 @@
+/* oxlint-disable anti-slop/no-module-mocking -- Tests exercise HTTP boundaries with deterministic wire responses and typed fixture assertions. */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import type { ModelInfo, SessionMessageAssistant, SessionInfo } from '@opencode/client';
+import { OpenCodeStartupOutput, openCodeApiVersion } from './opencode-connection';
+import {
+ projectV2Message,
+ projectV2Model,
+ projectV2Permission,
+ v2Action,
+ v2Rules,
+} from './opencode-v2-projection';
+import { projectV2Event } from './opencode-v2-events';
+import { OpenCodeV2Adapter } from './opencode-v2-adapter';
+import { OpenCodeV2SessionState } from './opencode-v2-session-state';
+import { OpenCodeTransport } from './open-code-transport';
+import { asRecord } from '../shared/type-utils';
+import { parseServerEvent } from '../shared/protocol';
+import { parseHealthResponse } from '../shared/health';
+import { normalizeRecycleBinSession } from '../shared/recycle-bin';
+
+vi.mock('./logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+afterEach(() => vi.unstubAllGlobals());
+
+describe('v2 Windows location paths', () => {
+ it.each([
+ ['c:\\Users\\Andrew\\Repo', 'C:\\Users\\Andrew\\Repo'],
+ ['d:/Projects/Repo', 'D:/Projects/Repo'],
+ ['C:\\Repo', 'C:\\Repo'],
+ ['/workspaces/repo', '/workspaces/repo'],
+ ['\\\\server\\share\\Repo', '\\\\server\\share\\Repo'],
+ ['c:relative', 'c:relative'],
+ ])('sends %s as %s in location queries', async (directory, expected) => {
+ const targets: string[] = [];
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => {
+ targets.push(path);
+ return {};
+ });
+ for (const path of ['/path', `/path?directory=${encodeURIComponent(directory)}`]) {
+ await adapter.request('GET', path, undefined, { directory });
+ const target = new URL(targets.at(-1) ?? '', 'http://localhost');
+ expect(target.searchParams.get('location[directory]')).toBe(expected);
+ }
+ });
+});
+
+describe('v2 prompt delivery', () => {
+ it.each([undefined, 0, 1000])('uses the provider request start timestamp %s', (started) => {
+ expect(
+ projectV2Event({
+ id: 'evt_started',
+ type: 'session.step.started',
+ created: 2000,
+ data: { sessionID: 'ses_one', assistantMessageID: 'msg_one', started },
+ })
+ ).toMatchObject([
+ { type: 'session.next.step.started', properties: { timestamp: started ?? 2000 } },
+ ]);
+ });
+
+ it.each([
+ [undefined, 'steer'],
+ ['steer', 'steer'],
+ ['queue', 'queue'],
+ ])('maps %s delivery to %s', async (delivery, expected) => {
+ const wire = vi.fn(async () => ({ data: { id: 'ses_delivery' } }));
+ const adapter = new OpenCodeV2Adapter(wire);
+ await adapter.request('POST', '/session/ses_delivery/prompt_async', {
+ delivery,
+ parts: [{ type: 'text', text: 'Create a plan' }],
+ });
+ expect(wire).toHaveBeenLastCalledWith(
+ 'POST',
+ '/api/session/ses_delivery/prompt',
+ expect.objectContaining({ text: 'Create a plan', delivery: expected }),
+ expect.anything()
+ );
+ });
+});
+
+describe('v2 session system instructions', () => {
+ it.each(['prompt_async', 'prompt', 'message', 'command'])(
+ 'saves updated workspace instructions before submitting %s',
+ async (action) => {
+ const calls: Array<{ method: string; path: string; body: unknown }> = [];
+ const adapter = new OpenCodeV2Adapter(async (method, path, body) => {
+ calls.push({ method, path, body });
+ return { data: { id: 'ses_workspace' } };
+ });
+ // The message route with a system prompt is reserved for one-shot generation.
+ if (action === 'message') {
+ await adapter.request('POST', '/session/ses_workspace/message', {
+ system: 'Generate a title',
+ parts: [{ type: 'text', text: 'Title this session' }],
+ });
+ expect(calls).toEqual([
+ {
+ method: 'POST',
+ path: '/api/session/ses_workspace/generate',
+ body: { prompt: 'Generate a title\n\nTitle this session' },
+ },
+ ]);
+ return;
+ }
+ for (const system of ['Workspace roots: /repo-a, /repo-b', 'Workspace roots: /repo-b']) {
+ calls.length = 0;
+ await adapter.request('POST', `/session/ses_workspace/${action}`, {
+ system,
+ command: 'review',
+ noReply: true,
+ parts: [{ type: 'text', text: 'What folders are in the workspace?' }],
+ });
+ expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([
+ 'GET /api/session/ses_workspace',
+ 'PUT /api/experimental/session/ses_workspace/instructions/entries/varro.system',
+ `POST /api/session/ses_workspace/${action === 'command' ? 'command' : 'prompt'}`,
+ ]);
+ expect(calls[1]?.body).toEqual({ value: system });
+ expect(calls[2]?.body).toMatchObject({ text: 'What folders are in the workspace?' });
+ }
+ }
+ );
+
+ it('does not submit a prompt when saving its instructions fails', async () => {
+ const wire = vi.fn(async (method: string) => {
+ if (method === 'PUT') throw new Error('Instruction update failed');
+ return { data: { id: 'ses_workspace' } };
+ });
+ const adapter = new OpenCodeV2Adapter(wire);
+ await expect(
+ adapter.request('POST', '/session/ses_workspace/prompt_async', {
+ system: 'Workspace roots: /repo-a, /repo-b',
+ parts: [{ type: 'text', text: 'List the workspace roots' }],
+ })
+ ).rejects.toThrow('Instruction update failed');
+ expect(wire.mock.calls.map(([method]) => method)).toEqual(['GET', 'PUT']);
+ });
+});
+
+describe('v2 hidden authentication fields', () => {
+ it.each([undefined, { server: 'https://custom.example' }])(
+ 'omits hidden prompts and sends their defaults unless supplied: %j',
+ async (inputs) => {
+ const integration = {
+ id: 'opencode',
+ methods: [
+ {
+ id: 'login',
+ type: 'oauth',
+ label: 'Sign in',
+ form: [
+ { key: 'server', type: 'string', hidden: true, default: 'https://console.example' },
+ { key: 'account', type: 'string', title: 'Account' },
+ {
+ key: 'inactive',
+ type: 'boolean',
+ hidden: true,
+ default: true,
+ when: [{ key: 'account', op: 'eq', value: 'other' }],
+ },
+ ],
+ },
+ ],
+ };
+ const wire = vi.fn(async (_method: string, path: string) => {
+ if (path === '/api/provider') return { data: [] };
+ if (path === '/api/integration') return { data: [integration] };
+ if (path === '/api/provider/opencode') return { data: { integrationID: 'opencode' } };
+ if (path === '/api/integration/opencode') return { data: integration };
+ if (path.endsWith('/connect/oauth')) return { data: { attemptID: 'attempt-one' } };
+ throw new Error(`Unexpected request: ${path}`);
+ });
+ const adapter = new OpenCodeV2Adapter(wire);
+ expect(await adapter.request('GET', '/provider/auth', undefined)).toEqual({
+ opencode: [
+ {
+ type: 'oauth',
+ label: 'Sign in',
+ prompts: [{ key: 'account', message: 'Account', type: 'text' }],
+ },
+ ],
+ });
+ await adapter.request('POST', '/provider/opencode/oauth/authorize', { method: 0, inputs });
+ expect(wire).toHaveBeenLastCalledWith(
+ 'POST',
+ '/api/integration/opencode/connect/oauth',
+ { methodID: 'login', answer: { server: inputs?.server ?? 'https://console.example' } },
+ expect.anything()
+ );
+ }
+ );
+});
+
+describe('v2 model release dates', () => {
+ const model: ModelInfo = {
+ id: 'model',
+ modelID: 'model',
+ providerID: 'provider',
+ name: 'Model',
+ capabilities: { tools: true, input: ['text'], output: ['text'] },
+ variants: [],
+ time: { released: Date.parse('2026-09-17T12:00:00Z') },
+ cost: [],
+ status: 'active',
+ enabled: true,
+ limit: { context: 400_000, output: 32_000 },
+ };
+
+ it('projects the native timestamp into the release date used by model ordering and display', () => {
+ expect(projectV2Model(model).release_date).toBe('2026-09-17');
+ });
+
+ it.each([0, -1, NaN, Infinity, 1e20])(
+ 'omits unknown or invalid release timestamps: %s',
+ (released) => {
+ expect(projectV2Model({ ...model, time: { released } }).release_date).toBeUndefined();
+ }
+ );
+});
+
+describe('OpenCode connection discovery', () => {
+ it('recognizes supported families without relying on the binary name', () => {
+ expect(openCodeApiVersion('opencode v2.0.5')).toBe(2);
+ expect(openCodeApiVersion('1.18.31')).toBe(1);
+ expect(openCodeApiVersion('3.0.0')).toBeNull();
+ });
+
+ it('captures and redacts passwords at every chunk boundary', () => {
+ const bytes = Buffer.from('listening\nserver password private-password\nready\n');
+ for (let split = 1; split < bytes.length; split++) {
+ const passwords: string[] = [];
+ const reader = new OpenCodeStartupOutput((password) => passwords.push(password));
+ const first = reader.write(bytes.subarray(0, split));
+ const second = reader.write(bytes.subarray(split));
+ expect(Buffer.concat([first, second]).toString()).toBe(
+ 'listening\nserver password [redacted]\nready\n'
+ );
+ expect(passwords).toEqual(['private-password']);
+ }
+ });
+
+ it('keeps large ordinary output undecoded and drops oversized credential lines', () => {
+ const capture = vi.fn();
+ const reader = new OpenCodeStartupOutput(capture);
+ const bulk = Buffer.alloc(1024 * 1024, 'x');
+ expect(reader.write(bulk)).toBe(bulk);
+ const text = Buffer.concat([
+ reader.write(Buffer.from(`server password ${'secret'.repeat(3000)}`)),
+ reader.write(Buffer.from('more-secret\nready\n')),
+ ]).toString();
+ expect(text).toBe('server password [redacted]\nready\n');
+ expect(capture).not.toHaveBeenCalled();
+ });
+
+ it.each(['/api/status', '/api/info'])(
+ 'detects v2 behind HTML fallback and authenticates translated requests using %s',
+ async (healthPath) => {
+ const calls: Array<{ url: string; headers: Headers }> = [];
+ vi.stubGlobal('fetch', async (url: string, init: RequestInit) => {
+ calls.push({ url, headers: new Headers(init.headers) });
+ const path = new URL(url).pathname;
+ if (path === '/global/health')
+ return new Response('app', { headers: { 'content-type': 'text/html' } });
+ if (path === healthPath) return Response.json({ version: '2.0.5', pid: 123, urls: [] });
+ if (path === '/api/status') return new Response('', { status: 404 });
+ if (path === '/api/session/active')
+ return Response.json({ data: { ses_busy: { type: 'running' } } });
+ throw new Error(`Unexpected request: ${path}`);
+ });
+ const transport = new OpenCodeTransport({
+ getUrl: () => 'http://localhost:4096',
+ getWorkspaceCwd: () => '/workspace',
+ getStatus: () => ({ state: 'stopped' }),
+ isDisposing: () => false,
+ updateEventStreamState: () => {},
+ emitEvent: () => {},
+ getAuthorization: () => 'Basic fixture',
+ });
+ expect(await transport.readHealthInfo()).toEqual({ healthy: true, version: '2.0.5' });
+ expect(parseHealthResponse(await transport.request('GET', '/global/health'))).toEqual({
+ healthy: true,
+ version: '2.0.5',
+ });
+ expect(calls.at(-1)?.url).toBe(`http://localhost:4096${healthPath}`);
+ expect(await transport.request('GET', '/session/status')).toEqual({
+ ses_busy: { type: 'busy' },
+ });
+ expect(calls.every((call) => call.headers.get('authorization') === 'Basic fixture')).toBe(
+ true
+ );
+ await expect(transport.request('GET', 'https://example.com/session')).rejects.toThrow(
+ 'Unsupported OpenCode API path'
+ );
+ expect(calls).toHaveLength(healthPath === '/api/status' ? 4 : 6);
+ }
+ );
+
+ it('cancels an in-flight v2 webview health request when the transport stops', async () => {
+ vi.stubGlobal('fetch', async (url: string) =>
+ new URL(url).pathname === '/api/status'
+ ? Response.json({ version: '2.0.5', pid: 123, urls: [] })
+ : new Response('', { status: 404 })
+ );
+ const transport = new OpenCodeTransport({
+ getUrl: () => 'http://localhost:4096',
+ getWorkspaceCwd: () => undefined,
+ getStatus: () => ({ state: 'stopped' }),
+ isDisposing: () => false,
+ updateEventStreamState: () => {},
+ emitEvent: () => {},
+ });
+ expect((await transport.readHealthInfo()).healthy).toBe(true);
+ vi.stubGlobal(
+ 'fetch',
+ (_url: string, init: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true });
+ })
+ );
+ const pending = transport.request('GET', '/global/health');
+ const rejected = expect(pending).rejects.toThrow();
+ transport.abortRequests();
+ await rejected;
+ await transport.waitForRequestsToSettle();
+ });
+
+ it('distinguishes failed authentication from a startup timeout', async () => {
+ vi.stubGlobal('fetch', async () => new Response('', { status: 401 }));
+ const transport = new OpenCodeTransport({
+ getUrl: () => 'http://localhost:4096',
+ getWorkspaceCwd: () => undefined,
+ getStatus: () => ({ state: 'stopped' }),
+ isDisposing: () => false,
+ updateEventStreamState: () => {},
+ emitEvent: () => {},
+ });
+ expect(await transport.readHealthInfo()).toEqual({ healthy: false });
+ expect(transport.healthError).toContain('authentication failed');
+ });
+});
+
+describe('v2 transcript and permission projection', () => {
+ it('normalizes description-less native commands for slash-command search', async () => {
+ const adapter = new OpenCodeV2Adapter(async (_method, path) =>
+ path.startsWith('/api/config')
+ ? [{ type: 'document', info: { commands: { local: { template: 'Local prompt' } } } }]
+ : { data: [{ name: 'inspect' }, { name: 'explain', description: 'Explain this code' }] }
+ );
+ expect(await adapter.request('GET', '/command', undefined)).toEqual([
+ { name: 'inspect', description: '', template: '', hints: [] },
+ { name: 'explain', description: 'Explain this code', template: '', hints: [] },
+ { name: 'local', description: '', template: 'Local prompt', hints: [] },
+ ]);
+ });
+ const message: SessionMessageAssistant = {
+ id: 'msg_assistant',
+ type: 'assistant',
+ time: { created: 10, completed: 20 },
+ agent: 'build',
+ model: { id: 'model', providerID: 'provider' },
+ content: [
+ { type: 'text', text: 'Hello' },
+ { type: 'reasoning', text: 'Thinking' },
+ {
+ type: 'tool',
+ id: 'tool_call',
+ name: 'shell',
+ state: {
+ status: 'completed',
+ input: { command: 'pwd' },
+ content: [
+ { type: 'text', text: '/workspace' },
+ { type: 'file', uri: 'file:///workspace/output.png', mime: 'image/png' },
+ ],
+ metadata: { title: 'Working directory' },
+ },
+ time: { created: 11, ran: 12, completed: 15 },
+ },
+ ],
+ };
+
+ it('uses the same part identities for history and incremental events', () => {
+ const history = projectV2Message(message, 'ses_one');
+ const text = parseServerEvent(
+ projectV2Event({
+ id: 'evt_text',
+ created: 10,
+ type: 'session.text.delta',
+ data: { sessionID: 'ses_one', assistantMessageID: message.id, ordinal: 0, delta: 'Hello' },
+ })[0]
+ );
+ expect(asRecord(text?.properties)?.textID).toBe(history.parts[0]?.id);
+ const reasoning = parseServerEvent(
+ projectV2Event({
+ id: 'evt_reasoning',
+ created: 10,
+ type: 'session.reasoning.delta',
+ data: {
+ sessionID: 'ses_one',
+ assistantMessageID: message.id,
+ ordinal: 0,
+ delta: 'Thinking',
+ },
+ })[0]
+ );
+ expect(asRecord(reasoning?.properties)?.reasoningID).toBe(history.parts[1]?.id);
+ expect(asRecord(reasoning?.properties)?.reasoningID).not.toBe(
+ asRecord(text?.properties)?.textID
+ );
+ expect(history.parts[2]).toMatchObject({
+ id: 'tool_call',
+ callID: 'tool_call',
+ tool: 'bash',
+ state: {
+ status: 'completed',
+ title: 'Working directory',
+ output: '/workspace',
+ time: { start: 12, end: 15 },
+ attachments: [{ url: 'file:///workspace/output.png' }],
+ },
+ });
+ });
+
+ it.each(['started', 'delta', 'ended'])(
+ 'matches type-local ordinals for interleaved text and reasoning %s events',
+ (phase) => {
+ const interleaved: SessionMessageAssistant = {
+ ...message,
+ content: [
+ { type: 'reasoning', text: 'Inspecting' },
+ message.content[2]!,
+ { type: 'text', text: '' },
+ { type: 'reasoning', text: 'Checked' },
+ { type: 'text', text: 'Final answer' },
+ ],
+ };
+ const history = projectV2Message(interleaved, 'ses_one');
+ const identities: unknown[] = [];
+ for (const [type, ordinal, index] of [
+ ['reasoning', 0, 0],
+ ['text', 0, 2],
+ ['reasoning', 1, 3],
+ ['text', 1, 4],
+ ] as const) {
+ const event = parseServerEvent(
+ projectV2Event({
+ id: `evt_${type}_${ordinal}`,
+ created: 10,
+ type: `session.${type}.${phase}`,
+ data: {
+ sessionID: 'ses_one',
+ assistantMessageID: message.id,
+ ordinal,
+ delta: 'chunk',
+ text: 'Final answer',
+ },
+ })[0]
+ );
+ const id = asRecord(event?.properties)?.[`${type}ID`];
+ expect(id).toBe(history.parts[index]?.id);
+ identities.push(id);
+ }
+ expect(new Set(identities).size).toBe(4);
+ }
+ );
+
+ it('leaves untitled shell calls available for the command-preview fallback', () => {
+ const untitled: SessionMessageAssistant = {
+ ...message,
+ content: message.content.map((part) =>
+ part.type === 'tool' ? { ...part, state: { ...part.state, metadata: {} } } : part
+ ),
+ };
+ const projected = projectV2Message(untitled, 'ses_one');
+ expect(projected.parts[2]).toMatchObject({
+ tool: 'bash',
+ state: { input: { command: 'pwd' }, title: undefined },
+ });
+ });
+
+ it('resolves an assistant parent outside the requested page without changing page identity', async () => {
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => {
+ if (path.endsWith('/inbox')) return { data: [] };
+ const url = new URL(path, 'http://localhost');
+ return url.searchParams.get('cursor') === 'older'
+ ? {
+ data: [
+ {
+ id: 'msg_user',
+ type: 'user',
+ text: 'Hi',
+ time: { created: 1 },
+ files: [],
+ agents: [],
+ skills: [],
+ },
+ ],
+ cursor: {},
+ }
+ : { data: [message], cursor: { next: 'older' } };
+ });
+ const page = asRecord(
+ await adapter.request('GET', '/session/ses_one/message?limit=1', undefined, {
+ captureNextCursor: true,
+ })
+ );
+ expect(page?.data).toHaveLength(1);
+ expect(page?.data).toMatchObject([{ info: { id: 'msg_assistant', parentID: 'msg_user' } }]);
+ expect(page?.nextCursor).toBe('older');
+ });
+
+ it('preserves action rules, ordering, and child request ownership', () => {
+ expect(
+ v2Rules([
+ { permission: '*', pattern: '*', action: 'ask' },
+ { permission: 'task', pattern: '*', action: 'allow' },
+ { permission: 'bash', pattern: 'git push *', action: 'ask' },
+ ])
+ ).toEqual([
+ { action: '*', resource: '*', effect: 'ask' },
+ { action: 'subagent', resource: '*', effect: 'allow' },
+ { action: 'shell', resource: 'git push *', effect: 'ask' },
+ ]);
+ expect(v2Action('toString')).toBe('toString');
+ expect(
+ projectV2Permission({
+ id: 'perm_one',
+ sessionID: 'ses_child',
+ action: 'shell',
+ resources: ['git push'],
+ source: { type: 'tool', messageID: 'msg_child', id: 'call_child' },
+ })
+ ).toMatchObject({
+ id: 'perm_one',
+ sessionID: 'ses_child',
+ permission: 'bash',
+ tool: { messageID: 'msg_child', callID: 'call_child' },
+ });
+ expect(() => v2Rules([{ permission: '*', pattern: '*', action: 'invalid' }])).toThrow(
+ 'Invalid OpenCode permission rule'
+ );
+ });
+
+ it('preserves sequence accounting and waits for the execution boundary', () => {
+ const ended = parseServerEvent(
+ projectV2Event({
+ id: 'evt_one',
+ created: 50,
+ type: 'session.step.ended',
+ durable: { seq: 7 },
+ location: { directory: '/repo' },
+ data: { sessionID: 'ses_one', assistantMessageID: 'msg_one', finish: 'stop' },
+ })[0]
+ );
+ expect(ended).toMatchObject({
+ type: 'session.next.step.ended',
+ seq: 7,
+ workspaceDirectory: '/repo',
+ properties: { executionContinues: true },
+ });
+ const idle = parseServerEvent(
+ projectV2Event({
+ id: 'evt_two',
+ created: 51,
+ type: 'session.execution.succeeded',
+ durable: { seq: 8 },
+ data: { sessionID: 'ses_one' },
+ })[0]
+ );
+ expect(idle).toMatchObject({
+ type: 'session.status',
+ seq: 8,
+ properties: { status: { type: 'idle' } },
+ });
+ const unknown = parseServerEvent(
+ projectV2Event({
+ id: 'evt_three',
+ type: 'session.future.event',
+ durable: { seq: 9 },
+ data: { sessionID: 'ses_one' },
+ })[0]
+ );
+ expect(unknown).toMatchObject({ sequenceOnly: true, seq: 9 });
+ });
+
+ it('delivers execution failures before idle and advances the durable sequence once', () => {
+ const events = projectV2Event(
+ {
+ id: 'evt_failed',
+ created: 20,
+ type: 'session.execution.failed',
+ durable: { seq: 8 },
+ data: {
+ sessionID: 'ses_one',
+ error: { type: 'api', message: 'Provider failed', status: 503 },
+ },
+ },
+ { hasAssistant: true }
+ ).map(parseServerEvent);
+ expect(events[0]).toMatchObject({
+ type: 'session.error',
+ seq: 8,
+ properties: { error: { data: { message: 'Provider failed', statusCode: 503 } } },
+ });
+ expect(events[1]).toMatchObject({
+ type: 'session.status',
+ properties: { status: { type: 'idle' } },
+ });
+ expect(events[1]?.seq).toBeUndefined();
+ });
+
+ it('creates an error row before reporting a pre-turn authentication failure', () => {
+ const events = projectV2Event(
+ {
+ id: 'evt_failed',
+ created: 20,
+ type: 'session.execution.failed',
+ durable: { seq: 8 },
+ data: { sessionID: 'ses_one', error: { type: 'unknown', message: 'Request failed: 401' } },
+ },
+ { agent: 'build', model: { providerID: 'openai', id: 'model' }, parentID: 'msg_user' }
+ ).map(parseServerEvent);
+ expect(events[0]).toMatchObject({
+ type: 'message.updated',
+ properties: {
+ info: {
+ id: 'msg_failed',
+ parentID: 'msg_user',
+ role: 'assistant',
+ providerID: 'openai',
+ error: { data: { statusCode: 401 } },
+ },
+ },
+ });
+ expect(events[1]).toMatchObject({ type: 'session.error', seq: 8 });
+ expect(events[2]).toMatchObject({
+ type: 'session.status',
+ properties: { status: { type: 'idle' } },
+ });
+ expect(events.filter((event) => event?.seq !== undefined)).toHaveLength(1);
+ });
+
+ it('paginates past internal instructions without exposing user bubbles', async () => {
+ const wire = vi.fn(async (_method: string, path: string) => {
+ if (path.endsWith('/inbox')) return { data: [] };
+ const cursor = new URL(path, 'http://localhost').searchParams.get('cursor');
+ if (!cursor)
+ return {
+ data: [
+ {
+ id: 'msg_catalog',
+ type: 'system',
+ text: 'The Code Mode tool catalog has changed.',
+ time: { created: 3 },
+ },
+ {
+ id: 'msg_restart',
+ type: 'synthetic',
+ text: 'The server restarted while you were working.',
+ time: { created: 2 },
+ },
+ ],
+ cursor: { next: 'older' },
+ };
+ expect(cursor).toBe('older');
+ return {
+ data: [{ id: 'msg_user', type: 'user', text: 'Continue', time: { created: 1 } }],
+ cursor: {},
+ };
+ });
+ const adapter = new OpenCodeV2Adapter(wire);
+ const page = await adapter.request('GET', '/session/ses_one/message?limit=2', undefined, {
+ captureNextCursor: true,
+ });
+ expect(page).toMatchObject({
+ data: [{ info: { id: 'msg_user', role: 'user' }, parts: [{ text: 'Continue' }] }],
+ nextCursor: undefined,
+ });
+ expect(asRecord(page)?.data).toHaveLength(1);
+ expect(wire).toHaveBeenCalledTimes(3);
+ });
+
+ it('hides v2 control records and retains failures when history is reopened', async () => {
+ const records = [
+ { id: 'msg_failed', type: 'idle', outcome: 'failed', time: { created: 4 } },
+ {
+ id: 'msg_user',
+ type: 'user',
+ text: 'Test message',
+ time: { created: 3 },
+ files: [],
+ agents: [],
+ skills: [],
+ },
+ {
+ id: 'msg_model',
+ type: 'model-switched',
+ model: { providerID: 'openai', id: 'model' },
+ time: { created: 2 },
+ },
+ { id: 'msg_agent', type: 'agent-switched', agent: 'build', time: { created: 1 } },
+ ];
+ const wire = async (_method: string, path: string) => ({
+ data: path.endsWith('/inbox') ? [] : records,
+ cursor: {},
+ });
+ const adapter = new OpenCodeV2Adapter(wire);
+ adapter.observe(
+ 'session.execution.failed',
+ { sessionID: 'ses_one', error: { type: 'unknown', message: 'Request failed: 401' } },
+ 'evt_failed'
+ );
+ const messages = await adapter.request('GET', '/session/ses_one/message', undefined);
+ expect(messages).toMatchObject([
+ {
+ info: {
+ id: 'msg_user',
+ role: 'user',
+ agent: 'build',
+ model: { providerID: 'openai', modelID: 'model' },
+ },
+ parts: [{ text: 'Test message' }],
+ },
+ {
+ info: {
+ id: 'msg_failed',
+ role: 'assistant',
+ parentID: 'msg_user',
+ error: { data: { statusCode: 401, message: 'Request failed: 401' } },
+ },
+ },
+ ]);
+ expect(messages).toHaveLength(2);
+ const reopened = await new OpenCodeV2Adapter(wire).request(
+ 'GET',
+ '/session/ses_one/message',
+ undefined
+ );
+ expect(reopened).toMatchObject([
+ { info: { id: 'msg_user' } },
+ {
+ info: {
+ id: 'msg_failed',
+ error: { data: { message: expect.stringContaining('Check the provider connection') } },
+ },
+ },
+ ]);
+ expect(reopened).toHaveLength(2);
+ });
+
+ it('keeps a cached authentication failure attached to its original provider', async () => {
+ const adapter = new OpenCodeV2Adapter(async (_method, path) => ({
+ data: path.endsWith('/inbox')
+ ? []
+ : [{ id: 'msg_failed', type: 'idle', outcome: 'failed', time: { created: 4 } }],
+ cursor: {},
+ }));
+ adapter.observe('session.model.selected', {
+ sessionID: 'ses_one',
+ model: { providerID: 'openai', id: 'original' },
+ });
+ adapter.observe(
+ 'session.execution.failed',
+ { sessionID: 'ses_one', error: { type: 'unknown', message: 'Request failed: 401' } },
+ 'evt_failed'
+ );
+ adapter.observe('session.model.selected', {
+ sessionID: 'ses_one',
+ model: { providerID: 'different', id: 'recovery' },
+ });
+ expect(
+ await adapter.request('GET', '/session/ses_one/message?limit=1', undefined)
+ ).toMatchObject([
+ {
+ info: {
+ providerID: 'openai',
+ modelID: 'original',
+ error: { data: { providerID: 'openai', statusCode: 401 } },
+ },
+ },
+ ]);
+ });
+
+ it('maps v2 provider updates to a recognized catalog event', () => {
+ expect(
+ parseServerEvent(
+ projectV2Event({ id: 'evt_provider', type: 'provider.updated', data: {} })[0]
+ )?.type
+ ).toBe('catalog.updated');
+ });
+
+ it('does not discard requests when the server rejects the reply', async () => {
+ const calls: string[] = [];
+ const adapter = new OpenCodeV2Adapter(async (_method, path, body) => {
+ calls.push(path);
+ if (path.endsWith('/reply')) {
+ expect(body).toEqual({ decision: 'once', message: undefined });
+ throw new Error('503 busy');
+ }
+ throw new Error('Unexpected snapshot request');
+ });
+ adapter.observe('permission.asked', { id: 'perm_one', sessionID: 'ses_child' });
+ await expect(
+ adapter.request('POST', '/permission/perm_one/reply', { reply: 'once' })
+ ).rejects.toThrow('503 busy');
+ await expect(
+ adapter.request('POST', '/permission/perm_one/reply', { reply: 'once' })
+ ).rejects.toThrow('503 busy');
+ expect(calls).toEqual([
+ '/api/session/ses_child/permission/perm_one/reply',
+ '/api/session/ses_child/permission/perm_one/reply',
+ ]);
+ });
+
+ it('uses native OAuth attempts for MCP authentication and waits for completion', async () => {
+ const opened = vi.fn(async () => true);
+ const adapter = new OpenCodeV2Adapter(
+ async (method, path, body) => {
+ const route = new URL(path, 'http://localhost').pathname;
+ if (route === '/api/mcp')
+ return { data: [{ name: 'fixture', integrationID: 'fixture-integration' }] };
+ if (route === '/api/integration/fixture-integration')
+ return { data: { methods: [{ id: 'login', type: 'oauth', label: 'Sign in' }] } };
+ if (route.endsWith('/connect/oauth') && method === 'POST') {
+ expect(body).toMatchObject({ methodID: 'login' });
+ return {
+ data: {
+ attemptID: 'attempt-one',
+ url: 'https://example.com/fixture-auth',
+ mode: 'auto',
+ instructions: 'Sign in',
+ },
+ };
+ }
+ if (route.endsWith('/connect/oauth/attempt-one')) return { data: { status: 'complete' } };
+ throw new Error(`Unexpected OAuth request ${method} ${route}`);
+ },
+ undefined,
+ opened
+ );
+ expect(await adapter.request('POST', '/mcp/fixture/auth/authenticate', {})).toBe(true);
+ expect(opened).toHaveBeenCalledWith('https://example.com/fixture-auth');
+ });
+
+ it('persists host annotations without issuing unsupported native patches', async () => {
+ const parent = resolve('artifacts/ai-test-data');
+ await mkdir(parent, { recursive: true });
+ const directory = await mkdtemp(join(parent, 'annotations-'));
+ const session: SessionInfo = {
+ id: 'ses_local',
+ title: 'Original',
+ projectID: 'project',
+ location: { directory: '/repo' },
+ time: { created: 1, updated: 2 },
+ cost: 0,
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
+ };
+ const wire = vi.fn(async () => ({ data: session }));
+ const state = new OpenCodeV2SessionState(directory);
+ const adapter = new OpenCodeV2Adapter(wire, state);
+ expect(
+ normalizeRecycleBinSession(await adapter.request('GET', '/session/ses_local', undefined))
+ ).toMatchObject({
+ id: session.id,
+ directory: '/repo',
+ version: '2',
+ });
+ wire.mockClear();
+ const metadata = { varro: { permissionMode: 'auto' } };
+ await adapter.request('PATCH', '/session/ses_local', { metadata });
+ expect(wire.mock.calls).toHaveLength(1);
+ expect(
+ asRecord(
+ await new OpenCodeV2Adapter(wire, new OpenCodeV2SessionState(directory)).request(
+ 'GET',
+ '/session/ses_local',
+ undefined
+ )
+ )?.metadata
+ ).toEqual(metadata);
+ expect(JSON.parse(await readFile(join(directory, 'ses_local.json'), 'utf8'))).toMatchObject({
+ metadata,
+ });
+ await expect(state.read('../escape')).rejects.toThrow('Could not read');
+ });
+});
diff --git a/src/extension/rest-proxy.test.ts b/src/extension/rest-proxy.test.ts
index fe7b7c5e..a49f784d 100644
--- a/src/extension/rest-proxy.test.ts
+++ b/src/extension/rest-proxy.test.ts
@@ -2318,26 +2318,29 @@ describe('RestProxy handleRequest', () => {
expect(callbacks.postApiResponse).toHaveBeenCalledWith(1, { id: 82, data: model });
});
- it('routes session title fallback requests after server startup', async () => {
- const { proxy, callbacks } = createProxy({
- sessionTitleFallback: {
- renameIfUntitled: vi.fn(() => Promise.resolve({ id: 'session-1', title: 'Fix build' })),
- },
- });
+ it.each(['', '?directory=%2Frepo'])(
+ 'routes session title fallback requests after server startup with query %s',
+ async (query) => {
+ const { proxy, callbacks } = createProxy({
+ sessionTitleFallback: {
+ renameIfUntitled: vi.fn(() => Promise.resolve({ id: 'session-1', title: 'Fix build' })),
+ },
+ });
- await proxy.handleRequest(
- makePayload(1, 'POST', '/varro/session/session-1/rename-if-untitled')
- );
+ await proxy.handleRequest(
+ makePayload(1, 'POST', `/varro/session/session-1/rename-if-untitled${query}`)
+ );
- expect(callbacks.sessionTitleFallback.renameIfUntitled).toHaveBeenCalledWith(
- 'session-1',
- '/repo'
- );
- expect(callbacks.postApiResponse).toHaveBeenCalledWith(1, {
- id: 1,
- data: { id: 'session-1', title: 'Fix build' },
- });
- });
+ expect(callbacks.sessionTitleFallback.renameIfUntitled).toHaveBeenCalledWith(
+ 'session-1',
+ '/repo'
+ );
+ expect(callbacks.postApiResponse).toHaveBeenCalledWith(1, {
+ id: 1,
+ data: { id: 'session-1', title: 'Fix build' },
+ });
+ }
+ );
it('returns only aggregate session edit and token data to the webview', async () => {
const serverRequest = vi.fn((_method: string, path: string) => {
@@ -6620,6 +6623,92 @@ describe('RestProxy handleRequest', () => {
expect(markSessionBusy).not.toHaveBeenCalled();
});
+ it('reads and updates native v2 permission rules without adding a shadowed v1 key', async () => {
+ let raw = JSON.stringify({
+ permissions: [{ action: 'shell', resource: '*', effect: 'ask' }],
+ agents: { review: { model: 'openai/model#high' } },
+ });
+ mocks.vscode.workspace.fs.readFile.mockImplementation(async (uri: { fsPath: string }) => {
+ if (uri.fsPath !== '/repo/opencode.json') throw { code: 'FileNotFound' };
+ return new TextEncoder().encode(raw);
+ });
+ mocks.vscode.workspace.fs.stat.mockResolvedValue({ mtime: 1, size: 3, type: 0, ctime: 1 });
+ mocks.vscode.workspace.fs.writeFile.mockImplementation(
+ async (_uri: { fsPath: string }, encoded: Uint8Array) => {
+ raw = new TextDecoder().decode(encoded);
+ }
+ );
+ const { proxy, callbacks } = createProxy();
+ await proxy.handleRequest(makePayload(403, 'GET', '/varro/opencode-config/permissions'));
+ expect(callbacks.postApiResponse).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ id: 403,
+ data: expect.objectContaining({
+ projectRules: [{ permission: 'bash', pattern: '*', action: 'ask' }],
+ }),
+ })
+ );
+ await proxy.handleRequest(
+ makePayload(404, 'POST', '/varro/opencode-config/permissions', {
+ rules: [
+ { permission: '*', pattern: '*', action: 'ask' },
+ { permission: 'bash', pattern: 'npm test', action: 'allow' },
+ ],
+ })
+ );
+ expect(JSON.parse(raw)).toMatchObject({
+ permissions: [
+ { action: '*', resource: '*', effect: 'ask' },
+ { action: 'shell', resource: 'npm test', effect: 'allow' },
+ ],
+ agents: { review: { model: 'openai/model#high' } },
+ });
+ expect(JSON.parse(raw).permission).toBeUndefined();
+ });
+
+ it('updates model routing in the existing native v2 agent map', async () => {
+ let raw = JSON.stringify({
+ agents: {
+ review: { model: { providerID: 'openai', model: 'old' }, system: 'Keep this prompt' },
+ },
+ });
+ mocks.vscode.workspace.fs.readFile.mockImplementation(async (uri: { fsPath: string }) => {
+ if (uri.fsPath !== '/repo/opencode.json') throw { code: 'FileNotFound' };
+ return new TextEncoder().encode(raw);
+ });
+ mocks.vscode.workspace.fs.stat.mockResolvedValue({ mtime: 1, size: 3, type: 0, ctime: 1 });
+ mocks.vscode.workspace.fs.writeFile.mockImplementation(
+ async (_uri: { fsPath: string }, encoded: Uint8Array) => {
+ raw = new TextDecoder().decode(encoded);
+ }
+ );
+ const { proxy } = createProxy();
+ await proxy.handleRequest(
+ makePayload(405, 'POST', '/varro/opencode-config/model-routing', {
+ target: 'agent',
+ agentName: 'review',
+ providerID: 'openai',
+ modelID: 'new',
+ })
+ );
+ await proxy.handleRequest(
+ makePayload(406, 'POST', '/varro/opencode-config/model-routing', {
+ target: 'small_model',
+ providerID: 'openai',
+ modelID: 'small',
+ })
+ );
+ expect(JSON.parse(raw)).toMatchObject({
+ agents: {
+ review: { model: 'openai/new', system: 'Keep this prompt' },
+ title: { model: 'openai/small' },
+ },
+ });
+ expect(JSON.parse(raw).agent).toBeUndefined();
+ expect(JSON.parse(raw).small_model).toBeUndefined();
+ });
+
it('serializes concurrent project model routing updates across proxy instances', async () => {
let raw = '{}\n';
let synchronizedReads = 0;
diff --git a/src/extension/rest-proxy.ts b/src/extension/rest-proxy.ts
index 67bf60b7..861cbfde 100644
--- a/src/extension/rest-proxy.ts
+++ b/src/extension/rest-proxy.ts
@@ -48,6 +48,7 @@ import type { LocalSessionSummaryData } from './local-session-summary';
import { sessionSummary } from './session-summary';
import { logger } from './logger';
import { ModelPricingCatalog } from './model-pricing';
+import { v1Action, v2Action } from './opencode-v2-projection';
import type { ProviderLimitService } from './provider-limit-service';
import type { PinnedSessionManager } from './pinned-session-manager';
import type { OpenCodeServer } from './server';
@@ -3969,7 +3970,9 @@ export class RestProxy {
private parseRenameIfUntitledRequest(method: string, path: string) {
if (method !== 'POST') return null;
- const match = path.match(/^\/varro\/session\/([^/?#]+)\/rename-if-untitled$/);
+ const match = new URL(path, 'http://localhost').pathname.match(
+ /^\/varro\/session\/([^/?#]+)\/rename-if-untitled$/
+ );
return match?.[1] ? decodeURIComponent(match[1]) : null;
}
@@ -4022,17 +4025,17 @@ export class RestProxy {
}
private normalizeOpenCodeModelRouting(config: Record): OpenCodeModelRouting {
- const smallModel = parseModelRoute(config.small_model);
+ const smallModel = parseModelRoute(
+ asRecord(asRecord(config.agents)?.title)?.model ?? config.small_model
+ );
const agentModels: Record = {};
- const agents = asRecord(config.agent);
-
- if (agents) {
- for (const [name, value] of Object.entries(agents)) {
- const agentConfig = asRecord(value);
- const route = parseModelRoute(agentConfig?.model);
- if (route) {
- agentModels[name] = route;
- }
+ const agents = { ...asRecord(config.agent), ...asRecord(config.agents) };
+
+ for (const [name, value] of Object.entries(agents)) {
+ const agentConfig = asRecord(value);
+ const route = parseModelRoute(agentConfig?.model);
+ if (route) {
+ agentModels[name] = route;
}
}
@@ -4077,7 +4080,7 @@ export class RestProxy {
}
}
- const providers = asRecord(config.provider);
+ const providers = asRecord(config.providers) ?? asRecord(config.provider);
if (!providers) continue;
for (const providerID of Object.keys(providers)) {
(providerConfigPaths[providerID] ??= []).push(path);
@@ -4152,31 +4155,33 @@ export class RestProxy {
}
const modelRef = `${request.providerID}/${request.modelID}`;
- if (request.target === 'small_model') {
+ const agentKey = target.config.agents !== undefined ? 'agents' : 'agent';
+ const nativeTitle = request.target === 'small_model' && agentKey === 'agents';
+ if (request.target === 'small_model' && !nativeTitle) {
nextRaw = applyJsoncChange(
nextRaw,
['small_model'],
request.unset ? undefined : modelRef
);
} else {
- const agentName = request.agentName;
+ const agentName = nativeTitle ? 'title' : request.agentName;
if (!agentName) {
throw new Error('Agent name is required');
}
nextRaw = applyJsoncChange(
nextRaw,
- ['agent', agentName, 'model'],
+ [agentKey, agentName, 'model'],
request.unset ? undefined : modelRef
);
if (request.unset) {
let nextConfig = parseOpenCodeConfig(nextRaw, target.path);
- const agentConfig = asRecord(asRecord(nextConfig.agent)?.[agentName]);
+ const agentConfig = asRecord(asRecord(nextConfig[agentKey])?.[agentName]);
if (agentConfig && Object.keys(agentConfig).length === 0) {
- nextRaw = applyJsoncChange(nextRaw, ['agent', agentName], undefined);
+ nextRaw = applyJsoncChange(nextRaw, [agentKey, agentName], undefined);
nextConfig = parseOpenCodeConfig(nextRaw, target.path);
- const agents = asRecord(nextConfig.agent);
+ const agents = asRecord(nextConfig[agentKey]);
if (agents && Object.keys(agents).length === 0) {
- nextRaw = applyJsoncChange(nextRaw, ['agent'], undefined);
+ nextRaw = applyJsoncChange(nextRaw, [agentKey], undefined);
}
}
}
@@ -4245,7 +4250,11 @@ export class RestProxy {
const targetPermissionConfig = target.config.permission;
const effectivePermissionConfig = currentSnapshot.config.permission;
const scalarConfigPermission = isScalarConfigPermission(permission);
- if (scalarConfigPermission && patterns.some((pattern) => pattern !== '*')) {
+ if (
+ !Array.isArray(target.config.permissions) &&
+ scalarConfigPermission &&
+ patterns.some((pattern) => pattern !== '*')
+ ) {
throw new Error(
`Project permission ${permission} only supports the wildcard pattern in OpenCode config`
);
@@ -4255,7 +4264,20 @@ export class RestProxy {
: isPermissionAction(effectivePermissionConfig)
? effectivePermissionConfig
: null;
- if (fallbackAction) {
+ if (Array.isArray(target.config.permissions)) {
+ nextRaw = applyJsoncChange(
+ nextRaw,
+ ['permissions'],
+ [
+ ...target.config.permissions,
+ ...patterns.map((resource) => ({
+ action: v2Action(permission),
+ resource,
+ effect: 'allow',
+ })),
+ ]
+ );
+ } else if (fallbackAction) {
const permissionConfig: Record = { '*': fallbackAction };
permissionConfig[permission] = scalarConfigPermission
? 'allow'
@@ -4294,6 +4316,18 @@ export class RestProxy {
}
private normalizeOpenCodePermissionRules(value: unknown): PermissionRule[] {
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => {
+ const rule = asRecord(item);
+ if (
+ typeof rule?.action !== 'string' ||
+ typeof rule.resource !== 'string' ||
+ !isPermissionAction(rule.effect)
+ )
+ return [];
+ return [{ permission: v1Action(rule.action), pattern: rule.resource, action: rule.effect }];
+ });
+ }
if (isPermissionAction(value)) {
return [{ permission: '*', pattern: '*', action: value }];
}
@@ -4513,14 +4547,18 @@ export class RestProxy {
const effectiveConfig = mergeOpenCodeConfig(globalConfig.config, snapshot.config);
return {
targetPath: snapshot.target.path,
- projectRules: this.normalizeOpenCodePermissionRules(snapshot.target.config.permission),
+ projectRules: this.normalizeOpenCodePermissionRules(
+ snapshot.target.config.permissions ?? snapshot.target.config.permission
+ ),
inheritedSources: [
...globalConfig.sources,
...snapshot.files
.filter((file) => getCanonicalOpenCodeConfigPath(file.path) !== targetPath)
.map((file) => ({
path: file.path,
- rules: this.normalizeOpenCodePermissionRules(file.config.permission),
+ rules: this.normalizeOpenCodePermissionRules(
+ file.config.permissions ?? file.config.permission
+ ),
scope: isSameWorkspacePath(
getOpenCodePathApi(file.path).dirname(file.path),
snapshot.workspacePath
@@ -4531,7 +4569,9 @@ export class RestProxy {
]
.filter((source) => source.rules.length > 0)
.toReversed(),
- effectiveRules: this.normalizeOpenCodePermissionRules(effectiveConfig.permission),
+ effectiveRules: this.normalizeOpenCodePermissionRules(
+ effectiveConfig.permissions ?? effectiveConfig.permission
+ ),
};
}
@@ -4552,7 +4592,7 @@ export class RestProxy {
effectiveConfig = mergeOpenCodeConfig(effectiveConfig, config);
sources.push({
path,
- rules: this.normalizeOpenCodePermissionRules(config.permission),
+ rules: this.normalizeOpenCodePermissionRules(config.permissions ?? config.permission),
scope: 'global',
});
} catch {
@@ -4595,8 +4635,9 @@ export class RestProxy {
string,
PermissionRule['action'] | Record
> = {};
+ const native = Array.isArray(target.config.permissions);
for (const rule of rules) {
- if (isScalarConfigPermission(rule.permission)) {
+ if (!native && isScalarConfigPermission(rule.permission)) {
if (rule.pattern !== '*') {
throw new Error(
`Project permission ${rule.permission} only supports the wildcard pattern in OpenCode config`
@@ -4613,8 +4654,16 @@ export class RestProxy {
}
nextRaw = applyJsoncChange(
nextRaw,
- ['permission'],
- rules.length > 0 ? permissionConfig : undefined
+ [native ? 'permissions' : 'permission'],
+ native
+ ? rules.map((rule) => ({
+ action: v2Action(rule.permission),
+ resource: rule.pattern,
+ effect: rule.action,
+ }))
+ : rules.length > 0
+ ? permissionConfig
+ : undefined
);
const latestStat = await this.readConfigStat(target.uri);
@@ -4641,9 +4690,13 @@ export class RestProxy {
snapshot.files.toReversed().find((file) => {
const route =
request.target === 'small_model'
- ? parseModelRoute(file.config.small_model)
+ ? parseModelRoute(
+ asRecord(asRecord(file.config.agents)?.title)?.model ?? file.config.small_model
+ )
: parseModelRoute(
- asRecord(asRecord(file.config.agent)?.[request.agentName || ''])?.model
+ asRecord(
+ asRecord(file.config.agents ?? file.config.agent)?.[request.agentName || '']
+ )?.model
);
return route?.providerID === request.providerID && route.modelID === request.modelID;
}) ?? null
diff --git a/src/extension/server.test.ts b/src/extension/server.test.ts
index fbc9f54e..9bb94b7b 100644
--- a/src/extension/server.test.ts
+++ b/src/extension/server.test.ts
@@ -44,7 +44,11 @@ const { getConfigurationMock, loggerMock, mkdirMock, spawnMock, vscodeMock, writ
}));
vi.mock('./logger', () => ({ logger: loggerMock }));
+vi.mock('./util/windows-cli-update', () => ({ runWindowsCliUpdate: vi.fn() }));
vi.mock('vscode', () => vscodeMock);
+vi.mock('@opencode/client/service', () => ({
+ Service: { discover: vi.fn().mockResolvedValue(undefined) },
+}));
vi.mock('child_process', () => ({ spawn: spawnMock, default: { spawn: spawnMock } }));
vi.mock('cross-spawn', () => ({ default: spawnMock, spawn: spawnMock }));
vi.mock('os', async () => {
@@ -80,6 +84,7 @@ vi.mock('fs/promises', async () => {
import { OpenCodeServer as RealOpenCodeServer } from './server';
import { readMaximumTestedOpenCodeVersion } from './extension-manifest';
+import { runWindowsCliUpdate } from './util/windows-cli-update';
let serverOwnershipPathSequence = 0;
class OpenCodeServer extends RealOpenCodeServer {
@@ -1273,7 +1278,9 @@ describe('OpenCodeServer maintenance', () => {
expect(readLatestCliVersion).toHaveBeenCalledTimes(1);
expect(vscodeMock.window.showInformationMessage).toHaveBeenCalledWith(
- 'OpenCode CLI 1.14.22 is available (installed: 1.14.20). Update with: opencode upgrade',
+ expect.stringMatching(
+ /OpenCode CLI 1\.14\.22 is available \(installed: 1\.14\.20\)\. Update with: .* upgrade 1\.14\.22$/
+ ),
'Run Upgrade'
);
});
@@ -1326,7 +1333,10 @@ describe('OpenCodeServer maintenance', () => {
cwd: undefined,
});
expect(terminal.show).toHaveBeenCalledWith(false);
- expect(terminal.sendText).toHaveBeenCalledWith('opencode upgrade', true);
+ expect(terminal.sendText).toHaveBeenCalledWith(
+ expect.stringMatching(/^'.+' upgrade 1\.14\.22$/),
+ true
+ );
});
it('uses the running server upgrade endpoint when the notification action is selected', async () => {
@@ -1419,7 +1429,9 @@ describe('OpenCodeServer maintenance', () => {
expect(spawnMock).not.toHaveBeenCalled();
expect(vscodeMock.window.showInformationMessage).toHaveBeenCalledWith(
- `OpenCode CLI ${latestVersion} is available (installed: ${installedVersion}). Update with: opencode upgrade`,
+ expect.stringContaining(
+ `OpenCode CLI ${latestVersion} is available (installed: ${installedVersion}). Update with: `
+ ),
'Run Upgrade'
);
});
@@ -1492,10 +1504,6 @@ describe('OpenCodeServer maintenance', () => {
const server = new OpenCodeServer(4096, false);
const readLatestCliVersion = vi.fn().mockResolvedValue('1.14.22');
- const terminal = {
- show: vi.fn(),
- sendText: vi.fn(),
- };
const api = server as unknown as {
readLatestCliVersion: () => Promise;
readHealthInfo: ReturnType;
@@ -1504,17 +1512,23 @@ describe('OpenCodeServer maintenance', () => {
api.readLatestCliVersion = readLatestCliVersion;
api.readHealthInfo = vi.fn().mockResolvedValue({ healthy: false });
vscodeMock.window.showInformationMessage.mockResolvedValueOnce('Run Upgrade');
- vscodeMock.window.createTerminal.mockReturnValueOnce(terminal);
await maybeSuggestCliUpdate(server, '1.14.20');
await flushMicrotasks();
await flushMicrotasks();
expect(vscodeMock.window.showInformationMessage).toHaveBeenCalledWith(
- 'OpenCode CLI 1.14.22 is available (installed: 1.14.20). Update with: opencode upgrade',
+ expect.stringMatching(
+ /OpenCode CLI 1\.14\.22 is available \(installed: 1\.14\.20\)\. Update with: & '.+' upgrade 1\.14\.22$/
+ ),
'Run Upgrade'
);
- expect(terminal.sendText).toHaveBeenCalledWith('opencode upgrade', true);
+ expect(runWindowsCliUpdate).toHaveBeenCalledWith(
+ expect.stringMatching(/^& '.+' upgrade 1\.14\.22$/),
+ 'OpenCode Upgrade',
+ undefined,
+ expect.any(Function)
+ );
});
it('stops the managed process before running a Windows CLI upgrade', async () => {
@@ -1522,10 +1536,6 @@ describe('OpenCodeServer maintenance', () => {
const server = new OpenCodeServer(4096, false);
const readLatestCliVersion = vi.fn().mockResolvedValue('1.14.22');
- const terminal = {
- show: vi.fn(),
- sendText: vi.fn(),
- };
const kill = vi.fn();
const statuses: ServerStatus[] = [];
server.on('status', (status) => statuses.push(status));
@@ -1564,7 +1574,6 @@ describe('OpenCodeServer maintenance', () => {
});
setRunning(server);
vscodeMock.window.showInformationMessage.mockResolvedValueOnce('Run Upgrade');
- vscodeMock.window.createTerminal.mockReturnValueOnce(terminal);
await maybeSuggestCliUpdate(server, '1.14.20');
await flushMicrotasks();
@@ -1572,7 +1581,12 @@ describe('OpenCodeServer maintenance', () => {
expect(kill).not.toHaveBeenCalled();
expect(statuses.some((status) => status.state === 'stopped')).toBe(true);
- expect(terminal.sendText).toHaveBeenCalledWith('opencode upgrade', true);
+ expect(runWindowsCliUpdate).toHaveBeenCalledWith(
+ expect.stringMatching(/^& '.+' upgrade 1\.14\.22$/),
+ 'OpenCode Upgrade',
+ undefined,
+ expect.any(Function)
+ );
});
it('does not stop a managed Windows process while sessions are active', async () => {
@@ -1647,7 +1661,11 @@ describe('OpenCodeServer maintenance', () => {
it('verifies the terminal update and restores a previously managed server after failure', async () => {
stubPlatform('win32');
const server = new OpenCodeServer(4096, true);
- const startOperation = vi.fn().mockResolvedValue(server.url);
+ const startOperation = vi.fn(async () => {
+ setRunning(server);
+ await server.request('GET', '/session');
+ return server.url;
+ });
const clearResolvedCommandCache = vi.fn();
const api = server as unknown as {
managedProcess: boolean;
@@ -1658,6 +1676,7 @@ describe('OpenCodeServer maintenance', () => {
startOperation: typeof startOperation;
getWorkspaceCwd: ReturnType;
processManager: { clearResolvedCommandCache: typeof clearResolvedCommandCache };
+ transport: { request: ReturnType };
};
api.managedProcess = true;
api.readHealthInfo = vi.fn().mockResolvedValue({ healthy: true, version: '1.17.0' });
@@ -1669,6 +1688,7 @@ describe('OpenCodeServer maintenance', () => {
api.startOperation = startOperation;
api.getWorkspaceCwd = vi.fn(() => '/repo');
api.processManager.clearResolvedCommandCache = clearResolvedCommandCache;
+ api.transport.request = vi.fn().mockResolvedValue([]);
setRunning(server);
await server.prepareForWindowsCliUpgrade('1.18.0');
@@ -1680,6 +1700,7 @@ describe('OpenCodeServer maintenance', () => {
'Windows OpenCode terminal update closed, but CLI 1.17.0 is older than requested 1.18.0'
);
expect(startOperation).toHaveBeenCalledOnce();
+ expect(api.transport.request).toHaveBeenCalledWith('GET', '/session', undefined, undefined);
});
it('releases a failed terminal update without restoring into a different workspace', async () => {
@@ -1884,7 +1905,7 @@ describe('OpenCodeServer compatibility gate', () => {
expect(requestMaintenanceCheck).toHaveBeenCalledOnce();
});
- it('uses a healthy server from a newer major version without a compatibility prompt', async () => {
+ it('uses a healthy supported v2 server without a compatibility prompt', async () => {
const server = new OpenCodeServer(4096, true);
const prepareForHealthyExistingServer = vi.fn().mockResolvedValue(undefined);
const api = server as unknown as {
@@ -1895,7 +1916,7 @@ describe('OpenCodeServer compatibility gate', () => {
prepareForHealthyExistingServer: typeof prepareForHealthyExistingServer;
};
};
- api.readHealthInfo = vi.fn().mockResolvedValue({ healthy: true, version: '2.0.0' });
+ api.readHealthInfo = vi.fn().mockResolvedValue({ healthy: true, version: '2.0.5' });
api.startEventStream = vi.fn(() => {
expect(server.status.state).not.toBe('running');
});
@@ -2255,14 +2276,14 @@ describe('OpenCodeServer compatibility gate', () => {
});
describe('OpenCodeServer startup health polling', () => {
- it('does not launch a Windows CLI version probe before managed startup', async () => {
+ it('checks the Windows CLI major before choosing the managed startup mode', async () => {
stubPlatform('win32');
const server = new OpenCodeServer(4096, true);
const { api } = configureManagedStartup(server);
await expect(server.start()).resolves.toBe(server.url);
- expect(api.readInstalledCliVersion).not.toHaveBeenCalled();
+ expect(api.readInstalledCliVersion).toHaveBeenCalledOnce();
});
it('keeps the original pollHealth callbacks across recursive retries', async () => {
diff --git a/src/extension/server.ts b/src/extension/server.ts
index c039cdad..074f4557 100644
--- a/src/extension/server.ts
+++ b/src/extension/server.ts
@@ -2,12 +2,15 @@
/* oxlint-disable anti-slop/no-known-value-widening, anti-slop/require-safety-comment-for-type-assertion -- SAFETY: Server assertions follow lifecycle, process, and response validation. */
import type { ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
+import * as vscode from 'vscode';
import {
MINIMUM_SUPPORTED_OPENCODE_VERSION,
+ MINIMUM_SUPPORTED_OPENCODE_V2_VERSION,
OPENCODE_UPDATE_REQUIRED_PREFIX,
} from '../shared/opencode-compatibility';
import {
getUpgradeCommand,
+ OPENCODE_INSTALL_COMMAND,
OPENCODE_UPGRADE_COMMAND,
type OpenCodeInstallMethod,
} from '../shared/opencode-install';
@@ -40,6 +43,7 @@ import {
normalizeRunningStatus,
} from './server-utils';
import { FULL_SESSION_LIST_LIMIT } from './util/session-list';
+import { openCodeApiVersion } from './opencode-connection';
export type { OpenCodeCompactionSettings };
@@ -115,10 +119,18 @@ export class RestartBlockedError extends Error {
function isSupportedOpenCodeVersion(version: string | undefined): boolean {
const normalized = typeof version === 'string' ? extractVersion(version) : null;
return (
- normalized !== null && compareVersions(normalized, MINIMUM_SUPPORTED_OPENCODE_VERSION) >= 0
+ normalized !== null &&
+ openCodeApiVersion(normalized) !== null &&
+ compareVersions(normalized, minimumVersion(normalized)) >= 0
);
}
+function minimumVersion(version: string | undefined): string {
+ return openCodeApiVersion(extractVersion(version ?? '') ?? '') === 2
+ ? MINIMUM_SUPPORTED_OPENCODE_V2_VERSION
+ : MINIMUM_SUPPORTED_OPENCODE_VERSION;
+}
+
/**
* Builds the message and the structured detail together so the two can never
* disagree. The closing instruction is the important part: after an upgrade
@@ -132,10 +144,15 @@ function createUpdateRequiredError(options: {
installMethod?: OpenCodeInstallMethod;
failure?: UpgradeFailureReport;
}): { message: string; detail: ServerErrorDetail } {
- const summary = `${OPENCODE_UPDATE_REQUIRED_PREFIX} Varro requires OpenCode ${MINIMUM_SUPPORTED_OPENCODE_VERSION} or newer, but ${options.observed}. ${options.reason}`;
+ const required = minimumVersion(options.observed);
+ const summary = `${OPENCODE_UPDATE_REQUIRED_PREFIX} Varro requires OpenCode ${required} or newer, but ${options.observed}. ${options.reason}`;
const installMethod = options.failure?.installMethod ?? options.installMethod;
const suggestedCommand = installMethod
- ? getUpgradeCommand(installMethod, process.platform) || OPENCODE_UPGRADE_COMMAND
+ ? getUpgradeCommand(
+ installMethod,
+ process.platform,
+ openCodeApiVersion(required) === 2 ? '@opencode/cli' : 'opencode-ai'
+ ) || OPENCODE_UPGRADE_COMMAND
: OPENCODE_UPGRADE_COMMAND;
const canSuggestCommand =
!options.blockedBy ||
@@ -171,7 +188,7 @@ function createUpdateRequiredError(options: {
: options.blockedBy
? 'update-blocked'
: 'update-required',
- required: MINIMUM_SUPPORTED_OPENCODE_VERSION,
+ required,
observed: options.observed,
};
if (installMethod) detail.installMethod = installMethod;
@@ -246,6 +263,13 @@ export class OpenCodeServer extends EventEmitter {
isDisposing: () => this.isDisposing,
updateEventStreamState: (eventStream) => this.updateEventStreamState(eventStream),
emitEvent: (event) => this.handleServerEvent(event),
+ getAuthorization: () => this.processManager.serverAuthorization,
+ openExternal: async (value) => {
+ const url = new URL(value);
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
+ throw new Error('Unsupported OpenCode authentication URL');
+ return vscode.env.openExternal(vscode.Uri.parse(url.href));
+ },
});
}
@@ -445,7 +469,22 @@ export class OpenCodeServer extends EventEmitter {
await this.processManager.stopServerForRestart();
this.throwIfStartCancelled(disposeGeneration, signal);
}
- const health = await this.readHealthInfo();
+ let health = await this.readHealthInfo();
+ if (this.transport.healthError?.startsWith('Unsupported OpenCode')) {
+ const message = this.transport.healthError;
+ this.setStatus({ state: 'error', message });
+ throw new Error(message);
+ }
+ if (!health.healthy && this.transport.healthError?.includes('authentication')) {
+ await this.processManager.discoverServerCredentials();
+ this.throwIfStartCancelled(disposeGeneration, signal);
+ health = await this.readHealthInfo();
+ if (!health.healthy && this.transport.healthError?.includes('authentication')) {
+ const message = this.transport.healthError;
+ this.setStatus({ state: 'error', message });
+ throw new Error(message);
+ }
+ }
this.throwIfStartCancelled(disposeGeneration, signal);
if (health.healthy) {
if (isSupportedOpenCodeVersion(health.version)) {
@@ -482,9 +521,8 @@ export class OpenCodeServer extends EventEmitter {
}
this.throwIfStartCancelled(disposeGeneration, signal);
- if (process.platform !== 'win32') {
- await this.ensureCompatibleCliForLaunch(undefined, disposeGeneration, signal);
- }
+ // The CLI major determines whether startup must join/register the v2 service.
+ await this.ensureCompatibleCliForLaunch(undefined, disposeGeneration, signal);
this.throwIfStartCancelled(disposeGeneration, signal);
return this.launchManagedServer(disposeGeneration, preserveRetryCount, signal);
@@ -497,6 +535,19 @@ export class OpenCodeServer extends EventEmitter {
signal: AbortSignal
): Promise {
this.throwIfStartCancelled(disposeGeneration, signal);
+ const sharedServer = this.processManager.discoverSharedServer();
+ if (sharedServer && (await sharedServer)) {
+ this.throwIfStartCancelled(disposeGeneration, signal);
+ const health = await this.readHealthInfo();
+ this.throwIfStartCancelled(disposeGeneration, signal);
+ if (!health.healthy || !isSupportedOpenCodeVersion(health.version)) {
+ throw new Error('The registered OpenCode service is unavailable or unsupported');
+ }
+ logger.info(`Found shared OpenCode service at ${this.url}`);
+ this.beginRunningEventStream();
+ this.startExistingServerPreparation(disposeGeneration, signal, health.version);
+ return this.url;
+ }
await this.syncInjectedConfigFile();
try {
this.throwIfStartCancelled(disposeGeneration, signal);
@@ -1128,7 +1179,7 @@ export class OpenCodeServer extends EventEmitter {
if (attempt > 50) {
this.cancelPollHealth();
this.setStatus({ state: 'error', message: 'Server failed to start within timeout' });
- reject(new Error('Server health check timeout'));
+ reject(new Error(this.transport.healthError ?? 'Server health check timeout'));
return;
}
@@ -1144,6 +1195,10 @@ export class OpenCodeServer extends EventEmitter {
let health: { healthy: boolean; version?: string };
try {
health = await readHealth();
+ if (!health.healthy && this.transport.healthError?.includes('authentication')) {
+ await this.processManager.discoverServerCredentials();
+ health = await readHealth();
+ }
} catch (err) {
reject(err instanceof Error ? err : new Error(String(err)));
return;
@@ -1411,7 +1466,7 @@ export class OpenCodeServer extends EventEmitter {
`OpenCode server ${serverVersion || 'unknown'} is older than required ${MINIMUM_SUPPORTED_OPENCODE_VERSION}; attempting a safe update`
);
this.throwIfStartCancelled(disposeGeneration, signal);
- await this.upgradeRunningServer(MINIMUM_SUPPORTED_OPENCODE_VERSION);
+ await this.upgradeRunningServer(minimumVersion(serverVersion));
this.throwIfStartCancelled(disposeGeneration, signal);
// The upgrade request can take long enough for another client to start
// work, so the initial check is not sufficient authorization to stop.
@@ -1442,6 +1497,11 @@ export class OpenCodeServer extends EventEmitter {
}
if (!installedVersion || isSupportedOpenCodeVersion(installedVersion)) return;
+ if (Number(installedVersion.split('.')[0]) > 2) {
+ const message = `Unsupported OpenCode CLI version: ${installedVersion}. Varro supports the v1 and v2 APIs.`;
+ this.setStatus({ state: 'error', message });
+ throw new Error(message);
+ }
const observed = observedServer || `the installed CLI is ${installedVersion}`;
if (!this.processManager.isAutoUpdateEnabled) {
@@ -1452,14 +1512,14 @@ export class OpenCodeServer extends EventEmitter {
}
logger.info(
- `Updating OpenCode CLI ${installedVersion} to meet Varro's minimum ${MINIMUM_SUPPORTED_OPENCODE_VERSION}`
+ `Updating OpenCode CLI ${installedVersion} to meet Varro's minimum ${minimumVersion(installedVersion)}`
);
// Kept for the case below: `opencode upgrade` can print why it failed and
// still exit 0, and that text is the only basis for actionable guidance.
let upgradeDiagnostics = '';
try {
this.throwIfStartCancelled(disposeGeneration, signal);
- upgradeDiagnostics = await this.processManager.upgradeCli(MINIMUM_SUPPORTED_OPENCODE_VERSION);
+ upgradeDiagnostics = await this.processManager.upgradeCli(minimumVersion(installedVersion));
this.throwIfStartCancelled(disposeGeneration, signal);
} catch (err) {
this.throwIfStartCancelled(disposeGeneration, signal);
@@ -1546,7 +1606,7 @@ export class OpenCodeServer extends EventEmitter {
message: OpenCodeProcess.MISSING_CLI_MESSAGE,
detail: {
kind: 'cli-missing',
- suggestedCommand: 'npm i -g opencode-ai',
+ suggestedCommand: OPENCODE_INSTALL_COMMAND,
settingId: 'varro.server.command',
searchedPaths: install.searchedPaths,
},
@@ -1802,7 +1862,7 @@ export class OpenCodeServer extends EventEmitter {
private async maybeSuggestCliUpdate(installedCliVersion: string | null) {
return this.processManager.maybeSuggestCliUpdate(installedCliVersion, {
- readLatestCliVersion: () => this.readLatestCliVersion(),
+ readLatestCliVersion: () => this.readLatestCliVersion(installedCliVersion),
upgradeRunningServer: (targetVersion) => this.upgradeRunningServer(targetVersion),
requestMaintenanceCheck: () => this.requestMaintenanceCheck(true),
getWorkspaceCwd: () => this.getWorkspaceCwd(),
@@ -1893,7 +1953,9 @@ export class OpenCodeServer extends EventEmitter {
return (
this.terminalCliUpgradePreparationOperation !== null ||
this.pendingTerminalCliUpgrades > 0 ||
- this.terminalCliUpgradeFinishOperation !== null
+ // Restoration publishes running before the finish operation resolves.
+ // Snapshot requests triggered by that status must reach the restored server.
+ (this.terminalCliUpgradeFinishOperation !== null && this._status.state !== 'running')
);
}
@@ -1966,8 +2028,8 @@ export class OpenCodeServer extends EventEmitter {
return this.processManager.readInstalledCliVersion();
}
- private async readLatestCliVersion(): Promise {
- return this.processManager.readLatestCliVersion();
+ private async readLatestCliVersion(installedVersion?: string | null): Promise {
+ return this.processManager.readLatestCliVersion(installedVersion);
}
private async readHealthInfo(): Promise<{ healthy: boolean; version?: string }> {
diff --git a/src/extension/session-state-manager.test.ts b/src/extension/session-state-manager.test.ts
index eb28bb28..4a8ebaf4 100644
--- a/src/extension/session-state-manager.test.ts
+++ b/src/extension/session-state-manager.test.ts
@@ -252,6 +252,26 @@ describe('SessionStateManager notifications', () => {
);
});
+ it('keeps v2 execution busy after a provider step ends', () => {
+ const manager = createManager();
+ manager.markSessionBusy('session-1');
+ manager.handleServerEvent({
+ type: 'session.next.step.started',
+ properties: { sessionID: 'session-1', assistantMessageID: 'message-1' },
+ });
+ manager.handleServerEvent({
+ type: 'session.next.step.ended',
+ properties: { sessionID: 'session-1', finish: 'stop', executionContinues: true },
+ });
+ expect(manager.busy.has('session-1')).toBe(true);
+ expect(manager.completed.has('session-1')).toBe(false);
+ manager.handleServerEvent({
+ type: 'session.status',
+ properties: { sessionID: 'session-1', status: { type: 'idle' } },
+ });
+ expect(manager.busy.has('session-1')).toBe(false);
+ });
+
it('clears a busy session on session.status idle', () => {
const manager = createManager();
diff --git a/src/extension/session-state-manager.ts b/src/extension/session-state-manager.ts
index 30d3d364..05fb4438 100644
--- a/src/extension/session-state-manager.ts
+++ b/src/extension/session-state-manager.ts
@@ -674,6 +674,7 @@ export class SessionStateManager {
break;
}
case 'session.next.step.ended': {
+ if (props?.executionContinues === true) break;
const sessionID = getString(props?.sessionID);
if (!sessionID || isContinuationFinish(getString(props?.finish))) break;
changed =
diff --git a/src/extension/sidebar-provider-actions.test.ts b/src/extension/sidebar-provider-actions.test.ts
index 762a6de9..a61c0535 100644
--- a/src/extension/sidebar-provider-actions.test.ts
+++ b/src/extension/sidebar-provider-actions.test.ts
@@ -171,6 +171,7 @@ function createActionFixture() {
openSessionInTerminal: vi.fn(),
openSessionInEditor: vi.fn(),
openSessionInSidebar: vi.fn(),
+ importLegacySession: vi.fn(() => Promise.resolve()),
openNewEditor: vi.fn(),
openNewWindow: vi.fn(),
editorRouteChanged: vi.fn(),
diff --git a/src/extension/sidebar-provider-actions.ts b/src/extension/sidebar-provider-actions.ts
index 294e070d..9c5c52d0 100644
--- a/src/extension/sidebar-provider-actions.ts
+++ b/src/extension/sidebar-provider-actions.ts
@@ -80,6 +80,7 @@ export interface SidebarProviderActionDeps {
inWindow?: boolean
): void | Promise;
openSessionInSidebar(sessionId: string, directory?: string): void | Promise;
+ importLegacySession: MessageRouterCallbacks['importLegacySession'];
openNewEditor(): void | Promise;
openNewWindow(): void | Promise;
editorRouteChanged(route: WebviewRoute): void;
@@ -213,6 +214,7 @@ export function createSidebarProviderActions(
);
await deps.openSessionInSidebar(sessionId, validatedDirectory);
},
+ importLegacySession: (sessionId, directory) => deps.importLegacySession(sessionId, directory),
openNewEditor: () => deps.openNewEditor(),
openNewWindow: () => deps.openNewWindow(),
editorRouteChanged: (route) => deps.editorRouteChanged(route),
diff --git a/src/extension/sidebar-provider-utils.ts b/src/extension/sidebar-provider-utils.ts
index 2eec4612..3bdbda53 100644
--- a/src/extension/sidebar-provider-utils.ts
+++ b/src/extension/sidebar-provider-utils.ts
@@ -24,12 +24,24 @@ export function normalizeCliOutput(value: unknown): string {
}
export function parseModelRoute(value: unknown): OpenCodeModelRoute | null {
+ const model = asRecord(value);
+ if (
+ model &&
+ typeof model.providerID === 'string' &&
+ typeof model.model === 'string' &&
+ model.providerID &&
+ model.model
+ ) {
+ return { providerID: model.providerID, modelID: model.model };
+ }
if (typeof value !== 'string') return null;
const separatorIndex = value.indexOf('/');
if (separatorIndex <= 0 || separatorIndex === value.length - 1) return null;
+ const modelID = value.slice(separatorIndex + 1).split('#')[0]!;
+ if (!modelID) return null;
return {
providerID: value.slice(0, separatorIndex),
- modelID: value.slice(separatorIndex + 1),
+ modelID,
};
}
diff --git a/src/extension/sidebar-provider.messages.test.ts b/src/extension/sidebar-provider.messages.test.ts
index 5857fa66..331818cd 100644
--- a/src/extension/sidebar-provider.messages.test.ts
+++ b/src/extension/sidebar-provider.messages.test.ts
@@ -1,5 +1,5 @@
/* oxlint-disable anti-slop/no-chained-type-assertions, anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/require-safety-comment-for-type-assertion -- SAFETY: These tests call private message handlers with protocol-shaped fixtures and untyped persistence values. */
-import { describe, expect, it, vi, type Mock } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { getSafeDefaultPermissionRules } from '../shared/permission-rules';
import type { PermissionMode } from '../shared/protocol';
import type { Session } from '../shared/opencode-types';
@@ -981,9 +981,11 @@ describe('SidebarProvider terminal commands', () => {
expect(server.prepareForWindowsCliUpgrade).toHaveBeenCalledTimes(2);
});
- it('keeps a Windows update reserved until its terminal closes', async () => {
+ it('restores the server when the Windows update task finishes with its terminal still open', async () => {
+ const windowsCliUpdate = await import('./util/windows-cli-update');
const originalPlatform = process.platform;
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ const update = vi.spyOn(windowsCliUpdate, 'runWindowsCliUpdate').mockResolvedValue();
try {
const server = createServer();
const { provider } = await createSidebarProviderInstance({ server });
@@ -991,18 +993,19 @@ describe('SidebarProvider terminal commands', () => {
await runInTerminal(provider, 'npm install -g opencode-ai@latest', 'OpenCode Update');
- const terminal = getVscodeMock().window.createTerminal.mock.results[0]?.value;
- const onDidCloseTerminal = getVscodeMock().window.onDidCloseTerminal as Mock<
- (listener: (terminal: object) => void) => { dispose(): void }
- >;
- const closeListener = onDidCloseTerminal.mock.calls[0]?.[0];
- expect(closeListener).toBeTypeOf('function');
+ expect(update).toHaveBeenCalledWith(
+ 'npm install -g opencode-ai@latest',
+ 'OpenCode Update',
+ '/repo',
+ expect.any(Function)
+ );
expect(server.finishWindowsCliUpgrade).not.toHaveBeenCalled();
- if (terminal) closeListener?.(terminal);
+ await update.mock.calls[0]?.[3]();
expect(server.finishWindowsCliUpgrade).toHaveBeenCalledOnce();
} finally {
+ update.mockRestore();
Object.defineProperty(process, 'platform', {
value: originalPlatform,
configurable: true,
diff --git a/src/extension/sidebar-provider.permissions.test.ts b/src/extension/sidebar-provider.permissions.test.ts
index 45111edd..6c82c77f 100644
--- a/src/extension/sidebar-provider.permissions.test.ts
+++ b/src/extension/sidebar-provider.permissions.test.ts
@@ -318,9 +318,7 @@ describe('SidebarProvider permission replay', () => {
});
expect(statusBarItem.show).not.toHaveBeenCalled();
- expect(openCodeStatusBarItem.text).toBe(
- `$(robot) OpenCode ${readMaximumTestedOpenCodeVersion()}`
- );
+ expect(openCodeStatusBarItem.text).toBe('$(robot) OpenCode');
expect(provider.getStatusBarClickAction()).toBe('focus');
providerState.sessionState.handleServerEvent({
@@ -710,6 +708,46 @@ describe('SidebarProvider permission replay', () => {
expect(readServerInfo).toHaveBeenCalledTimes(2);
});
+ it('shows no guessed version during startup and ignores version reads from before a restart', async () => {
+ const v2Version = readMaximumTestedOpenCodeVersion(undefined, 2);
+ let resolveOldInfo!: (info: {
+ cliVersion: string;
+ health: { healthy: boolean; version: string };
+ }) => void;
+ const oldInfo = new Promise<{
+ cliVersion: string;
+ health: { healthy: boolean; version: string };
+ }>((resolve) => {
+ resolveOldInfo = resolve;
+ });
+ const readServerInfo = vi
+ .fn()
+ .mockReturnValueOnce(oldInfo)
+ .mockResolvedValueOnce({
+ cliVersion: v2Version,
+ health: { healthy: true, version: v2Version },
+ });
+ const server = createServer({ readServerInfo });
+ await createSidebarProviderInstance({ server });
+ const statusHandler = server.on.mock.calls.findLast(([event]) => event === 'status')?.[1];
+ const createStatusBarItem = getVscodeMock().window.createStatusBarItem;
+ const itemIndex = createStatusBarItem.mock.calls.findIndex(
+ ([id]) => id === 'varro.opencode-version'
+ );
+ const item = createStatusBarItem.mock.results[itemIndex]?.value;
+ expect(item.text).toBe('$(robot) OpenCode');
+ statusHandler?.({ state: 'running', url: 'http://127.0.0.1:4096' });
+ statusHandler?.({ state: 'stopped' });
+ expect(item.text).toBe('$(robot) OpenCode');
+ statusHandler?.({ state: 'running', url: 'http://127.0.0.1:4096' });
+ await vi.waitFor(() => expect(item.text).toBe(`$(robot) OpenCode ${v2Version}`));
+ resolveOldInfo({ cliVersion: '1.18.31', health: { healthy: true, version: '1.18.31' } });
+ await oldInfo;
+ await Promise.resolve();
+ expect(item.text).toBe(`$(robot) OpenCode ${v2Version}`);
+ expect(item.tooltip).not.toContain('1.18.31');
+ });
+
it('describes an uninstalled patch update without repeating the verified version', async () => {
await getVscodeMock().workspace.getConfiguration().update('server.autoUpdate', false);
const maximumTestedVersion = readMaximumTestedOpenCodeVersion();
diff --git a/src/extension/sidebar-provider.ts b/src/extension/sidebar-provider.ts
index 7406436d..35509ea3 100644
--- a/src/extension/sidebar-provider.ts
+++ b/src/extension/sidebar-provider.ts
@@ -91,6 +91,7 @@ import { DroppedFilesService } from './dropped-files-service';
import { DraftImageStore } from './draft-image-store';
import { readExtensionConfigState } from './extension-config';
import { readMaximumTestedOpenCodeVersion } from './extension-manifest';
+import { runWindowsCliUpdate } from './util/windows-cli-update';
import { FileSearchService } from './file-search-service';
import { GeneratedDependencyTreeGuard } from './generated-dependency-tree-guard';
import { HiddenSessionManager } from './hidden-session-manager';
@@ -125,6 +126,7 @@ import { SessionHistoryScopeStore } from './session-history-scope-store';
import { SessionTitleFallback } from './session-title-fallback';
import { SessionTrashManager } from './session-trash-manager';
import { createSidebarProviderActions } from './sidebar-provider-actions';
+import { LegacySessionImport } from './legacy-session-import';
import { SidebarProviderBridge } from './sidebar-provider-bridge';
import { SidebarProviderContextFiles } from './sidebar-provider-context-files';
import { SidebarProviderRuntime } from './sidebar-provider-runtime';
@@ -134,8 +136,6 @@ import { UsageReportService } from './usage-report-service';
import { getWorkspaceSessionIdsForEvent } from './sidebar-provider-utils';
import { resolveServerLaunch } from './util/server-launch';
-const maximumTestedOpenCodeVersion = readMaximumTestedOpenCodeVersion();
-
function differsByMajorOrMinor(left: string, right: string) {
const [leftMajor, leftMinor] = left.split('.').map(Number);
const [rightMajor, rightMinor] = right.split('.').map(Number);
@@ -197,6 +197,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
private attentionStatusBarItemVisible = false;
private hiddenStatusBarState: Extract | null = null;
private openCodeVersionCheck: 'idle' | 'checking' | 'checked' = 'idle';
+ private openCodeVersionGeneration = 0;
private openCodeUpdateAvailable = false;
private openCodeCliVersion: string | null = null;
private openCodeServerVersion: string | null = null;
@@ -956,6 +957,30 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
this.openSessionInEditor(sessionId, title, model, rootSessionId, directory, inWindow),
openSessionInSidebar: (sessionId, directory) =>
this.openSessionInSidebar(sessionId, directory),
+ importLegacySession: async (sessionId, directory) => {
+ try {
+ const workspacePath = this.contextProvider.getOpenWorkspaceRoot(directory);
+ if (!workspacePath) throw new Error('Session workspace folder is not open');
+ const importer = new LegacySessionImport((method, path, body) =>
+ endpointServer.request(method, path, body)
+ );
+ const importedSessionId = await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: 'Importing v1 conversation into v2',
+ },
+ () => importer.importCopy({ id: sessionId, title: 'Untitled', directory })
+ );
+ post({
+ type: 'command/open-session',
+ payload: { sessionId: importedSessionId, directory },
+ });
+ } catch (error) {
+ void vscode.window.showErrorMessage(
+ `Could not import v1 history: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ },
openNewEditor: () => this.openNewEditor(),
openNewWindow: () => this.openNewWindow(),
editorRouteChanged: (route) => this.editorRouteChanged(webviewContext.viewId, route),
@@ -3103,22 +3128,13 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
}
try {
- const terminal = vscode.window.createTerminal({ name: title, cwd: workspacePath });
if (replacesBinary && process.platform === 'win32') {
- const disposable = vscode.window.onDidCloseTerminal((closedTerminal) => {
- if (closedTerminal !== terminal) return;
- disposable.dispose();
- void (async () => {
- try {
- await this.server.finishWindowsCliUpgrade();
- } catch (err) {
- logger.warn(
- `Failed to finish Windows OpenCode CLI update: ${err instanceof Error ? err.message : String(err)}`
- );
- }
- })();
- });
+ await runWindowsCliUpdate(text, title, workspacePath, () =>
+ this.server.finishWindowsCliUpgrade()
+ );
+ return;
}
+ const terminal = vscode.window.createTerminal({ name: title, cwd: workspacePath });
terminal.show(false);
terminal.sendText(text, true);
} catch (err) {
@@ -3190,6 +3206,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
private refreshOpenCodeVersionStatus() {
if (this.serverEventBridge.getStatus().state !== 'running') {
+ this.openCodeVersionGeneration += 1;
this.openCodeVersionCheck = 'idle';
this.openCodeUpdateAvailable = false;
this.openCodeCliVersion = null;
@@ -3199,14 +3216,24 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
if (this.openCodeVersionCheck !== 'idle') return;
this.openCodeVersionCheck = 'checking';
+ const generation = this.openCodeVersionGeneration;
void this.server
.readServerInfo()
.then((info) => {
- if (this.disposing || this.serverEventBridge.getStatus().state !== 'running') return;
+ if (
+ this.disposing ||
+ generation !== this.openCodeVersionGeneration ||
+ this.serverEventBridge.getStatus().state !== 'running'
+ )
+ return;
this.openCodeCliVersion = info.cliVersion ? extractVersion(info.cliVersion) : null;
this.openCodeServerVersion = info.health.version
? extractVersion(info.health.version)
: null;
+ const maximumTestedOpenCodeVersion = readMaximumTestedOpenCodeVersion(
+ undefined,
+ this.openCodeCliVersion?.startsWith('2.') ? 2 : 1
+ );
this.openCodeUpdateAvailable =
(this.openCodeCliVersion !== null &&
compareVersions(this.openCodeCliVersion, maximumTestedOpenCodeVersion) < 0) ||
@@ -3217,14 +3244,18 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
this.renderOpenCodeStatusBarItem();
})
.catch(() => {
+ if (generation !== this.openCodeVersionGeneration) return;
this.openCodeVersionCheck = 'checked';
});
}
private renderOpenCodeStatusBarItem() {
const updateMarker = this.openCodeUpdateAvailable ? '*' : '';
- const displayedVersion =
- this.openCodeServerVersion ?? this.openCodeCliVersion ?? maximumTestedOpenCodeVersion;
+ const displayedVersion = this.openCodeServerVersion ?? this.openCodeCliVersion;
+ const maximumTestedOpenCodeVersion = readMaximumTestedOpenCodeVersion(
+ undefined,
+ (this.openCodeCliVersion ?? displayedVersion)?.startsWith('2.') ? 2 : 1
+ );
const autoUpdatesEnabled = vscode.workspace
.getConfiguration('varro')
.get('server.autoUpdate', true);
@@ -3264,7 +3295,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
}
const openCodeStatusBarItem = this.serverEventBridge.getOpenCodeStatusBarItem();
- openCodeStatusBarItem.text = `$(robot) OpenCode ${displayedVersion}${updateMarker}`;
+ openCodeStatusBarItem.text = `$(robot) OpenCode${displayedVersion ? ` ${displayedVersion}${updateMarker}` : ''}`;
openCodeStatusBarItem.tooltip = versionLines.join('\n');
openCodeStatusBarItem.show();
}
diff --git a/src/extension/usage-report-database.test.ts b/src/extension/usage-report-database.test.ts
new file mode 100644
index 00000000..8cef7bc2
--- /dev/null
+++ b/src/extension/usage-report-database.test.ts
@@ -0,0 +1,172 @@
+/* oxlint-disable anti-slop/no-module-mocking -- Only the VS Code UI is mocked; usage queries run in real SQLite workers against isolated fixtures. */
+import { mkdir, mkdtemp, rm } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { ProgressOptions } from 'vscode';
+import { UsageReportService } from './usage-report-service';
+
+const mocks = vi.hoisted(() => ({ content: '' }));
+vi.mock('vscode', () => ({
+ ProgressLocation: { Notification: 15 },
+ commands: { executeCommand: vi.fn() },
+ workspace: {
+ openTextDocument: async (options: { content: string }) => {
+ mocks.content = options.content;
+ return { uri: 'untitled:usage' };
+ },
+ },
+ window: {
+ withProgress: async (_options: ProgressOptions, task: () => Promise) => task(),
+ showTextDocument: vi.fn(),
+ showErrorMessage: vi.fn(),
+ },
+}));
+
+const directories: string[] = [];
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ await Promise.all(
+ directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))
+ );
+});
+
+async function fixture(versions: number[]) {
+ const parent = resolve('artifacts/ai-test-data');
+ await mkdir(parent, { recursive: true });
+ const directory = await mkdtemp(join(parent, 'usage-'));
+ directories.push(directory);
+ const path = join(directory, 'opencode.db');
+ vi.stubEnv('OPENCODE_DB', path);
+ const database = new DatabaseSync(path);
+ if (versions.includes(1)) {
+ database.exec(`CREATE TABLE session (id TEXT PRIMARY KEY, time_updated INTEGER);
+ CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, data TEXT);
+ CREATE INDEX message_session_idx ON message(session_id);`);
+ }
+ if (versions.includes(2)) {
+ database.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY, time_updated INTEGER, metadata TEXT);
+ CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, data TEXT);
+ CREATE INDEX session_message_session_type_seq_idx ON session_message(session_id, type, seq);`);
+ }
+ const now = Date.now();
+ function add(version: number, id: string, updated: number, model: string, sourceID?: string) {
+ const data = {
+ role: version === 1 ? 'assistant' : undefined,
+ parentID: version === 1 ? `${id}-prompt` : undefined,
+ providerID: version === 1 ? 'provider' : undefined,
+ modelID: version === 1 ? model : undefined,
+ model: version === 2 ? { providerID: 'provider', id: model } : undefined,
+ time: { created: now - 2_000, completed: now },
+ tokens: { input: 10, output: 5, reasoning: 2, cache: { read: 3, write: 1 } },
+ };
+ if (version === 1) {
+ database.prepare('INSERT INTO session VALUES (?, ?)').run(id, updated);
+ database
+ .prepare('INSERT INTO message VALUES (?, ?, ?)')
+ .run(`${id}-reply`, id, JSON.stringify(data));
+ } else {
+ database
+ .prepare('INSERT INTO session_v2 VALUES (?, ?, ?)')
+ .run(
+ id,
+ updated,
+ sourceID ? JSON.stringify({ varroLegacyImport: { sourceSessionID: sourceID } }) : null
+ );
+ const insert = database.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?)');
+ insert.run(`${id}-prompt`, id, 'user', 1, '{}');
+ insert.run(`${id}-reply`, id, 'assistant', 2, JSON.stringify(data));
+ insert.run(`${id}-reply-2`, id, 'assistant', 3, JSON.stringify(data));
+ }
+ }
+ async function report(allTime = false) {
+ const before = database.prepare('SELECT name, sql FROM sqlite_master ORDER BY name').all();
+ database.close();
+ const request = vi.fn();
+ const start = vi.fn();
+ await new UsageReportService({ request }, start).openReport(allTime);
+ expect(request).not.toHaveBeenCalled();
+ expect(start).not.toHaveBeenCalled();
+ const check = new DatabaseSync(path, { readOnly: true });
+ expect(check.prepare('SELECT name, sql FROM sqlite_master ORDER BY name').all()).toEqual(
+ before
+ );
+ check.close();
+ return mocks.content;
+ }
+ return { add, report, now, database };
+}
+
+describe('local usage database versions', () => {
+ it.each([1, 2])('reads a V%i-only database', async (version) => {
+ const { add, report, now } = await fixture([version]);
+ add(version, 'only', now, 'only-model');
+ const content = await report();
+ expect(content).toContain('from 1 sessions scanned');
+ expect(content).toContain(
+ version === 1
+ ? '| provider | only-model | 1 | 21 | 2s | 10 | 5 | 2 | 3 | 1 |'
+ : '| provider | only-model | 1 | 42 | 4s | 20 | 10 | 4 | 6 | 2 |'
+ );
+ });
+
+ it.each([false, true])(
+ 'merges versions and selects the newest complete session, allTime=%s',
+ async (allTime) => {
+ const { add, report, now } = await fixture([1, 2]);
+ add(1, 'legacy-only', now, 'legacy');
+ add(2, 'native-only', now, 'native');
+ add(1, 'v2-newer', now - 1, 'discard-v1');
+ add(2, 'v2-newer', now, 'newer-v2');
+ add(1, 'v1-newer', now, 'newer-v1');
+ add(2, 'v1-newer', now - 1, 'discard-v2');
+ add(1, 'tie', now, 'discard-tie');
+ add(2, 'tie', now, 'tie-v2');
+ add(1, 'import-source', now - 1, 'discard-source');
+ add(2, 'import-copy', now, 'imported', 'import-source');
+ add(2, 'older-copy', now - 1, 'discard-copy', 'import-source');
+ add(1, 'source-newer', now, 'updated-source');
+ add(2, 'copy-older', now - 1, 'discard-import', 'source-newer');
+ const content = await report(allTime);
+ expect(content).toContain('from 7 sessions scanned');
+ expect(content).not.toContain('discard');
+ for (const model of [
+ 'legacy',
+ 'native',
+ 'newer-v2',
+ 'newer-v1',
+ 'tie-v2',
+ 'imported',
+ 'updated-source',
+ ]) {
+ expect(content).toContain(`| provider | ${model} | 1 |`);
+ }
+ expect(content).toContain('| **Total** | | 7 | 231 | 22s | 110 | 55 | 22 | 33 | 11 |');
+ }
+ );
+
+ it('filters old sessions after resolving migrated identities', async () => {
+ const { add, report, now } = await fixture([1, 2]);
+ const old = now - 40 * 24 * 60 * 60 * 1_000;
+ add(1, 'old', old, 'discard-old');
+ add(2, 'old', old + 1, 'discard-old-v2');
+ add(1, 'active', old, 'discard-legacy');
+ add(2, 'active', now, 'active-v2');
+ const content = await report();
+ expect(content).toContain('from 1 sessions scanned');
+ expect(content).not.toContain('discard');
+ expect(content).toContain('| provider | active-v2 | 1 | 42 |');
+ });
+
+ it('does not decode message bodies from old or superseded sessions', async () => {
+ const { add, report, now, database } = await fixture([1, 2]);
+ add(1, 'old', 0, 'old-model');
+ add(1, 'migrated', now - 1, 'legacy-model');
+ add(2, 'migrated', now, 'current-model');
+ // Invalid bodies make an accidental full-history JSON scan fail deterministically.
+ database.prepare('UPDATE message SET data = ?').run('unreadable excluded message');
+ const content = await report();
+ expect(content).toContain('from 1 sessions scanned');
+ expect(content).toContain('| provider | current-model | 1 | 42 |');
+ });
+});
diff --git a/src/extension/usage-report-service.ts b/src/extension/usage-report-service.ts
index a3e84526..8d7cd184 100644
--- a/src/extension/usage-report-service.ts
+++ b/src/extension/usage-report-service.ts
@@ -310,7 +310,8 @@ async function readLocalUsageDatabase(
now = Date.now(),
includeAllTime = false
): Promise {
- const databasePath = join(resolveOpenCodeDataDirectory(), 'opencode.db');
+ const databasePath =
+ process.env.OPENCODE_DB ?? join(resolveOpenCodeDataDirectory(), 'opencode.db');
const windows = createReportWindows(now, includeAllTime);
return new Promise((resolve, reject) => {
@@ -407,17 +408,37 @@ try {
} else {
const database = new DatabaseSync(workerData.databasePath, { readOnly: true });
try {
- const sessionCount = workerData.start === null
- ? database.prepare('SELECT count(*) AS count FROM session').get().count
- : database.prepare('SELECT count(*) AS count FROM session WHERE time_updated >= ?')
- .get(workerData.start).count;
+ database.exec('BEGIN');
+ const tables = new Set(database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
+ const sources = [];
+ if (tables.has('session') && tables.has('message')) {
+ sources.push("SELECT id, id AS identity, time_updated, 1 AS version FROM session");
+ }
+ if (tables.has('session_v2') && tables.has('session_message')) {
+ sources.push("SELECT id, coalesce(json_extract(metadata, '$.varroLegacyImport.sourceSessionID'), id) AS identity, time_updated, 2 AS version FROM session_v2");
+ }
+ if (!sources.length) throw new Error('No supported OpenCode usage tables found.');
+ // Select a complete session before filtering dates or reading messages. Equal timestamps prefer v2.
+ const selected = 'WITH ranked AS (SELECT *, row_number() OVER (PARTITION BY identity ORDER BY time_updated DESC, version DESC, id DESC) AS rank FROM (' + sources.join(' UNION ALL ') + ')), selected AS (SELECT * FROM ranked WHERE rank = 1' + (workerData.start === null ? '' : ' AND time_updated >= ?') + ') ';
+ const parameters = workerData.start === null ? [] : [workerData.start];
+ const sessionCount = database.prepare(selected + 'SELECT count(*) AS count FROM selected').get(...parameters).count;
+ const messages = [];
+ // Keep selected sessions as the outer loop. Otherwise SQLite can scan and decode
+ // every message in both versions before checking whether its session was selected.
+ if (tables.has('session') && tables.has('message')) {
+ messages.push("SELECT m.session_id, m.data, json_extract(m.data, '$.parentID') AS parentID FROM selected s CROSS JOIN message m ON s.id = m.session_id WHERE s.version = 1 AND length(m.data) <= ? AND json_extract(m.data, '$.role') = 'assistant'");
+ }
+ if (tables.has('session_v2') && tables.has('session_message')) {
+ messages.push("SELECT m.session_id, m.data, coalesce(json_extract(m.data, '$.parentID'), (SELECT u.id FROM session_message u WHERE u.session_id = m.session_id AND u.type = 'user' AND u.seq < m.seq ORDER BY u.seq DESC LIMIT 1)) AS parentID FROM selected s CROSS JOIN session_message m ON s.id = m.session_id WHERE s.version = 2 AND m.type = 'assistant' AND length(m.data) <= ?");
+ }
const query = [
+ selected,
'SELECT m.session_id AS sessionID,',
"json_extract(m.data, '$.providerID') AS providerID,",
"json_extract(m.data, '$.model.providerID') AS nestedProviderID,",
"json_extract(m.data, '$.modelID') AS modelID,",
- "json_extract(m.data, '$.model.modelID') AS nestedModelID,",
- "json_extract(m.data, '$.parentID') AS parentID,",
+ "coalesce(json_extract(m.data, '$.model.id'), json_extract(m.data, '$.model.modelID')) AS nestedModelID,",
+ 'm.parentID AS parentID,',
"json_extract(m.data, '$.time.created') AS timeCreated,",
"json_extract(m.data, '$.time.completed') AS timeCompleted,",
"coalesce(json_extract(m.data, '$.time.completed'), json_extract(m.data, '$.time.created')) AS created,",
@@ -427,16 +448,11 @@ try {
"json_extract(m.data, '$.tokens.reasoning') AS reasoning,",
"json_extract(m.data, '$.tokens.cache.read') AS cacheRead,",
"json_extract(m.data, '$.tokens.cache.write') AS cacheWrite",
- 'FROM message m',
- workerData.start === null
- ? "WHERE length(m.data) <= ? AND json_extract(m.data, '$.role') = 'assistant'"
- : "WHERE m.session_id IN (SELECT id FROM session WHERE time_updated >= ?) AND length(m.data) <= ? AND json_extract(m.data, '$.role') = 'assistant'",
+ 'FROM (' + messages.join(' UNION ALL ') + ') m',
'LIMIT ?',
].join(' ');
const statement = database.prepare(query);
- const rows = workerData.start === null
- ? statement.iterate(workerData.maxMessageDataBytes, workerData.maxScannedAssistantRows + 1)
- : statement.iterate(workerData.start, workerData.maxMessageDataBytes, workerData.maxScannedAssistantRows + 1);
+ const rows = statement.iterate(...parameters, ...messages.map(() => workerData.maxMessageDataBytes), workerData.maxScannedAssistantRows + 1);
const aggregates = workerData.windows.map(() => ({
groups: new Map(),
promptIDs: new Set(),
diff --git a/src/extension/util/webview-message.test-support.ts b/src/extension/util/webview-message.test-support.ts
index edff2207..56c8ff15 100644
--- a/src/extension/util/webview-message.test-support.ts
+++ b/src/extension/util/webview-message.test-support.ts
@@ -88,6 +88,10 @@ export const VALID_WEBVIEW_MESSAGES = {
type: 'session/open-in-opencode',
payload: { sessionId: 'session-1' },
},
+ 'session/import-v1': {
+ type: 'session/import-v1',
+ payload: { sessionId: 'session-1', directory: '/workspace' },
+ },
'editor/route-changed': {
type: 'editor/route-changed',
payload: { route: { type: 'session', sessionId: 'session-1' } },
diff --git a/src/extension/util/webview-message.test.ts b/src/extension/util/webview-message.test.ts
index 910b3595..6ba5faf9 100644
--- a/src/extension/util/webview-message.test.ts
+++ b/src/extension/util/webview-message.test.ts
@@ -433,6 +433,13 @@ describe('webview message validation', () => {
// cover them the buttons silently did nothing in production while component
// and e2e tests - which never run this parser - kept passing.
it.each([
+ 'npm i -g @opencode/cli',
+ 'npm install -g @opencode/cli@latest',
+ 'pnpm add -g --allow-build=@opencode/cli @opencode/cli@latest',
+ 'yarn global add @opencode/cli@latest',
+ 'bun add -g --trust @opencode/cli@latest',
+ 'brew upgrade anomalyco/tap/opencode-v2',
+ 'curl -fsSL https://opencode.ai/v2/install | bash',
'npm i -g opencode-ai',
'opencode upgrade',
'npm install -g opencode-ai@latest',
diff --git a/src/extension/util/webview-message.ts b/src/extension/util/webview-message.ts
index c7c9b904..f041e5f9 100644
--- a/src/extension/util/webview-message.ts
+++ b/src/extension/util/webview-message.ts
@@ -135,6 +135,7 @@ export const WEBVIEW_MESSAGE_TYPES = {
'session/open-in-editor': true,
'session/open-in-sidebar': true,
'session/open-in-opencode': true,
+ 'session/import-v1': true,
'chat/new-editor': true,
'chat/new-window': true,
'window-chat-theme/set-reversed': true,
@@ -512,6 +513,14 @@ export function parseWebviewMessage(value: unknown): WebviewMessage | null {
return { type, payload: parsedPayload };
}
+ case 'session/import-v1': {
+ const payload = asRecord(message?.payload);
+ const sessionId = getBoundedString(payload?.sessionId, 512);
+ const directory = getBoundedString(payload?.directory, MAX_PATH_LENGTH);
+ if (!sessionId || !/^[A-Za-z0-9_-]+$/.test(sessionId) || !directory) return null;
+ return { type, payload: { sessionId, directory } };
+ }
+
case 'editor/route-changed': {
const payload = asRecord(message?.payload);
const route = asRecord(payload?.route);
diff --git a/src/extension/util/windows-cli-update.test.ts b/src/extension/util/windows-cli-update.test.ts
new file mode 100644
index 00000000..5eebc5ac
--- /dev/null
+++ b/src/extension/util/windows-cli-update.test.ts
@@ -0,0 +1,83 @@
+/* oxlint-disable anti-slop/no-module-mocking -- Model VS Code task completion without launching an actual CLI update. */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as vscode from 'vscode';
+
+const mocks = vi.hoisted(() => ({
+ end: vi.fn<(listener: (event: vscode.TaskEndEvent) => void) => vscode.Disposable>(),
+ execute: vi.fn(),
+ dispose: vi.fn(),
+ warn: vi.fn(),
+}));
+
+vi.mock('vscode', () => ({
+ Task: class {
+ presentationOptions = {};
+ constructor(
+ readonly definition: vscode.TaskDefinition,
+ readonly scope: vscode.TaskScope,
+ readonly name: string,
+ readonly source: string,
+ readonly execution: vscode.ShellExecution
+ ) {}
+ },
+ ShellExecution: class {
+ constructor(
+ readonly commandLine: string,
+ readonly options: vscode.ShellExecutionOptions
+ ) {}
+ },
+ TaskScope: { Workspace: 2 },
+ TaskRevealKind: { Always: 1 },
+ TaskPanelKind: { New: 2 },
+ tasks: { onDidEndTask: mocks.end, executeTask: mocks.execute },
+}));
+vi.mock('../logger', () => ({ logger: { warn: mocks.warn } }));
+
+import { runWindowsCliUpdate } from './windows-cli-update';
+
+describe('Windows CLI update tasks', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.end.mockReturnValue({ dispose: mocks.dispose });
+ mocks.execute.mockResolvedValue(undefined);
+ });
+
+ it('finishes only the matching task without waiting for the terminal to close', async () => {
+ const finish = vi.fn();
+ await runWindowsCliUpdate(
+ "& 'C:\\Program Files\\OpenCode\\opencode2.exe' upgrade 2.0.7",
+ 'OpenCode Upgrade',
+ 'C:\\repo',
+ finish
+ );
+ const task: vscode.Task = mocks.execute.mock.calls[0]![0];
+ const listener = mocks.end.mock.calls[0]![0];
+ expect(task.execution).toMatchObject({
+ commandLine: "& 'C:\\Program Files\\OpenCode\\opencode2.exe' upgrade 2.0.7",
+ options: {
+ cwd: 'C:\\repo',
+ executable: 'powershell.exe',
+ shellArgs: ['-NoProfile', '-Command'],
+ },
+ });
+ listener({
+ execution: { task: { ...task, definition: { type: 'other' } }, terminate: vi.fn() },
+ });
+ await Promise.resolve();
+ expect(finish).not.toHaveBeenCalled();
+ listener({ execution: { task, terminate: vi.fn() } });
+ await Promise.resolve();
+ expect(finish).toHaveBeenCalledOnce();
+ expect(mocks.dispose).toHaveBeenCalledOnce();
+ });
+
+ it('cleans up the completion listener if VS Code cannot start the task', async () => {
+ const finish = vi.fn();
+ mocks.execute.mockRejectedValue(new Error('Task launch failed'));
+ await expect(
+ runWindowsCliUpdate('opencode2 upgrade', 'Update', undefined, finish)
+ ).rejects.toThrow('Task launch failed');
+ expect(mocks.dispose).toHaveBeenCalledOnce();
+ expect(finish).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/extension/util/windows-cli-update.ts b/src/extension/util/windows-cli-update.ts
new file mode 100644
index 00000000..ca2e0910
--- /dev/null
+++ b/src/extension/util/windows-cli-update.ts
@@ -0,0 +1,50 @@
+import { randomUUID } from 'crypto';
+import * as vscode from 'vscode';
+import { logger } from '../logger';
+
+// Task completion works even when terminal shell integration is disabled. Keep
+// the output visible without requiring the user to close the terminal to reconnect.
+export async function runWindowsCliUpdate(
+ command: string,
+ title: string,
+ cwd: string | undefined,
+ onFinish: () => void | Promise
+): Promise {
+ const id = randomUUID();
+ const task = new vscode.Task(
+ { type: 'varro-opencode-update', id },
+ vscode.TaskScope.Workspace,
+ title,
+ 'Varro',
+ new vscode.ShellExecution(command, {
+ cwd,
+ executable: 'powershell.exe',
+ shellArgs: ['-NoProfile', '-Command'],
+ }),
+ []
+ );
+ task.presentationOptions = {
+ reveal: vscode.TaskRevealKind.Always,
+ focus: true,
+ panel: vscode.TaskPanelKind.New,
+ showReuseMessage: false,
+ };
+ const completion = vscode.tasks.onDidEndTask((event) => {
+ if (event.execution.task.definition.id !== id) return;
+ completion.dispose();
+ void Promise.resolve()
+ .then(onFinish)
+ // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Promise rejections can contain any value; narrow before logging.
+ .catch((err: unknown) => {
+ logger.warn(
+ `Failed to finish Windows OpenCode CLI update: ${err instanceof Error ? err.message : String(err)}`
+ );
+ });
+ });
+ try {
+ await vscode.tasks.executeTask(task);
+ } catch (err) {
+ completion.dispose();
+ throw err;
+ }
+}
diff --git a/src/shared/error-classification.test.ts b/src/shared/error-classification.test.ts
index 0547d6d4..fa9a9e3f 100644
--- a/src/shared/error-classification.test.ts
+++ b/src/shared/error-classification.test.ts
@@ -456,6 +456,18 @@ describe('isAbortedToolError', () => {
});
describe('isPermissionRejectedToolError', () => {
+ it('detects the v2 declined-tool error without counting it as completed work', () => {
+ expect(
+ isPermissionRejectedToolError({ status: 'error', error: 'The user declined this tool call' })
+ ).toBe(true);
+ expect(
+ isPermissionRejectedToolError({
+ status: 'completed',
+ error: 'The user declined this tool call',
+ })
+ ).toBe(false);
+ });
+
it('detects the OpenCode permission rejection error', () => {
expect(
isPermissionRejectedToolError({
diff --git a/src/shared/error-classification.ts b/src/shared/error-classification.ts
index 7cc853ce..82432083 100644
--- a/src/shared/error-classification.ts
+++ b/src/shared/error-classification.ts
@@ -220,8 +220,10 @@ export function isAbortedToolError(state: { status: string; error?: string }) {
export function isPermissionRejectedToolError(state: { status: string; error?: string }) {
if (state.status !== 'error') return false;
- return normalizeAbortText(state.error).includes(
- 'user rejected permission to use this specific tool call'
+ const error = normalizeAbortText(state.error);
+ return (
+ error.includes('user rejected permission to use this specific tool call') ||
+ error === 'the user declined this tool call'
);
}
diff --git a/src/shared/model-variant.test.ts b/src/shared/model-variant.test.ts
index 221dcd47..f296a730 100644
--- a/src/shared/model-variant.test.ts
+++ b/src/shared/model-variant.test.ts
@@ -9,6 +9,7 @@ describe('normalizeModelVariant', () => {
it('preserves other variants and normalizes empty values to null', () => {
expect(normalizeModelVariant('gpt-5.4', 'minimal')).toBe('minimal');
expect(normalizeModelVariant('gpt-5.5', '')).toBeNull();
+ expect(normalizeModelVariant('gpt-6-astra', 'default')).toBeNull();
expect(normalizeModelVariant(null, undefined)).toBeNull();
});
});
diff --git a/src/shared/model-variant.ts b/src/shared/model-variant.ts
index 8c736f44..ab939394 100644
--- a/src/shared/model-variant.ts
+++ b/src/shared/model-variant.ts
@@ -2,6 +2,7 @@ export function normalizeModelVariant(
modelID: string | null | undefined,
variant: string | null | undefined
) {
+ if (variant === 'default') return null;
if (modelID === 'gpt-5.5' && variant === 'minimal') return 'low';
return variant || null;
}
diff --git a/src/shared/opencode-compatibility.test.ts b/src/shared/opencode-compatibility.test.ts
index aae3b128..ce074106 100644
--- a/src/shared/opencode-compatibility.test.ts
+++ b/src/shared/opencode-compatibility.test.ts
@@ -8,6 +8,19 @@ import {
} from './opencode-compatibility';
describe('getMaximumTestedOpenCodeVersion', () => {
+ it('uses the v2 client dependency for v2 servers', () => {
+ expect(
+ getMaximumTestedOpenCodeVersion(
+ {
+ dependencies: {
+ '@opencode-ai/sdk': '^1.18.31',
+ '@opencode/client': '^2.0.7',
+ },
+ },
+ 2
+ )
+ ).toBe('2.0.7');
+ });
it('reads the exact version from the SDK dependency range', () => {
expect(
getMaximumTestedOpenCodeVersion({
diff --git a/src/shared/opencode-compatibility.ts b/src/shared/opencode-compatibility.ts
index 51d580ff..d811dce1 100644
--- a/src/shared/opencode-compatibility.ts
+++ b/src/shared/opencode-compatibility.ts
@@ -1,10 +1,11 @@
// Bump this only when Varro starts relying on APIs from a newer OpenCode release.
// Keeping it explicit avoids forcing a CLI update for SDK-only patch releases.
export const MINIMUM_SUPPORTED_OPENCODE_VERSION = '1.16.0';
+export const MINIMUM_SUPPORTED_OPENCODE_V2_VERSION = '2.0.5';
export const OPENCODE_SDK_PACKAGE_NAME = '@opencode-ai/sdk';
-export function getMaximumTestedOpenCodeVersion(packageJson: T): string {
+export function getMaximumTestedOpenCodeVersion(packageJson: T, apiVersion: 1 | 2 = 1): string {
const packageRecord = asRecord(packageJson);
if (!packageRecord) {
throw new Error('Varro package.json is not an object');
@@ -15,14 +16,15 @@ export function getMaximumTestedOpenCodeVersion(packageJson: T): string {
throw new Error('Varro package.json does not declare dependencies');
}
- const declaredVersion = dependencies[OPENCODE_SDK_PACKAGE_NAME];
+ const packageName = apiVersion === 2 ? '@opencode/client' : OPENCODE_SDK_PACKAGE_NAME;
+ const declaredVersion = dependencies[packageName];
if (!isString(declaredVersion)) {
- throw new Error(`Varro package.json does not declare ${OPENCODE_SDK_PACKAGE_NAME}`);
+ throw new Error(`Varro package.json does not declare ${packageName}`);
}
const version = declaredVersion.match(/\d+\.\d+\.\d+/)?.[0];
if (!version) {
- throw new Error(`Invalid ${OPENCODE_SDK_PACKAGE_NAME} version: ${declaredVersion}`);
+ throw new Error(`Invalid ${packageName} version: ${declaredVersion}`);
}
return version;
}
diff --git a/src/shared/opencode-install.test.ts b/src/shared/opencode-install.test.ts
index 04283d3e..044ae0a7 100644
--- a/src/shared/opencode-install.test.ts
+++ b/src/shared/opencode-install.test.ts
@@ -144,6 +144,19 @@ describe('getUpgradeCommand', () => {
expect(getUpgradeCommand('curl', 'win32')).toBeNull();
});
+ it.each([
+ ['npm', 'npm install -g @opencode/cli@latest'],
+ ['pnpm', 'pnpm add -g --allow-build=@opencode/cli @opencode/cli@latest'],
+ ['yarn', 'yarn global add @opencode/cli@latest'],
+ ['bun', 'bun add -g --trust @opencode/cli@latest'],
+ ['brew', 'brew upgrade anomalyco/tap/opencode-v2'],
+ ['curl', 'curl -fsSL https://opencode.ai/v2/install | bash'],
+ ] as const)('keeps v2 %s recovery in the v2 package family', (method, expected) => {
+ expect(getUpgradeCommand(method, 'darwin', '@opencode/cli')).toBe(expected);
+ expect(getRecoveryCommand('network', method, 'darwin', '@opencode/cli')).toBe(expected);
+ expect(OPENCODE_TERMINAL_COMMANDS).toContain(expected);
+ });
+
it('recommends nothing for custom or unknown installs', () => {
expect(getUpgradeCommand('custom', 'darwin')).toBeNull();
expect(getUpgradeCommand('unknown', 'darwin')).toBeNull();
@@ -280,6 +293,7 @@ describe('OPENCODE_TERMINAL_COMMANDS', () => {
}
}
expect(OPENCODE_TERMINAL_COMMANDS).toContain('npm i -g opencode-ai');
+ expect(OPENCODE_TERMINAL_COMMANDS).toContain('npm i -g @opencode/cli');
expect(OPENCODE_TERMINAL_COMMANDS).toContain('opencode upgrade');
});
});
diff --git a/src/shared/opencode-install.ts b/src/shared/opencode-install.ts
index e3a95370..428b596a 100644
--- a/src/shared/opencode-install.ts
+++ b/src/shared/opencode-install.ts
@@ -20,10 +20,11 @@ export type OpenCodeUpgradeFailureKind =
| 'network'
| 'unknown';
-export const OPENCODE_INSTALL_DOCS_URL = 'https://opencode.ai';
+export const OPENCODE_INSTALL_DOCS_URL = 'https://opencode.ai/v2/docs/';
/** The command Varro offers when OpenCode is not installed at all. */
-export const OPENCODE_INSTALL_COMMAND = 'npm i -g opencode-ai';
+export const OPENCODE_INSTALL_COMMAND = 'npm i -g @opencode/cli';
+export const OPENCODE_V1_INSTALL_COMMAND = 'npm i -g opencode-ai';
/** OpenCode's own updater, used until it has proven it cannot update this install. */
export const OPENCODE_UPGRADE_COMMAND = 'opencode upgrade';
@@ -31,6 +32,7 @@ export const OPENCODE_UPGRADE_COMMAND = 'opencode upgrade';
// This module is compiled into the webview bundle too, so it must not reach
// for Node globals: callers pass the platform in.
export type InstallPlatform = string;
+export type OpenCodeCliPackage = 'opencode-ai' | '@opencode/cli';
function normalizeBinaryPath(command: string): string {
return command.replace(/\\/g, '/').toLowerCase();
@@ -98,26 +100,32 @@ export function detectInstallMethod(options: {
*/
export function getUpgradeCommand(
method: OpenCodeInstallMethod,
- platform: InstallPlatform
+ platform: InstallPlatform,
+ packageName: OpenCodeCliPackage = 'opencode-ai'
): string | null {
switch (method) {
case 'curl':
- // The shell installer is POSIX-only; on Windows the OpenCode docs point
- // at the package managers instead, so do not invent a command here.
- return platform === 'win32' ? null : 'curl -fsSL https://opencode.ai/install | bash';
+ // The shell installer is POSIX-only. Keep recovery in the installed CLI family.
+ return platform === 'win32'
+ ? null
+ : `curl -fsSL https://opencode.ai/${packageName === '@opencode/cli' ? 'v2/' : ''}install | bash`;
case 'npm':
- return 'npm install -g opencode-ai@latest';
+ return `npm install -g ${packageName}@latest`;
case 'pnpm':
- return 'pnpm add -g opencode-ai@latest';
+ return packageName === '@opencode/cli'
+ ? 'pnpm add -g --allow-build=@opencode/cli @opencode/cli@latest'
+ : `pnpm add -g ${packageName}@latest`;
case 'yarn':
- return 'yarn global add opencode-ai@latest';
+ return `yarn global add ${packageName}@latest`;
case 'bun':
- return 'bun add -g opencode-ai@latest';
+ return packageName === '@opencode/cli'
+ ? 'bun add -g --trust @opencode/cli@latest'
+ : `bun add -g ${packageName}@latest`;
case 'brew':
- // Unqualified on purpose: OpenCode now ships as the homebrew/core
- // `opencode` formula, and Homebrew resolves the bare name against
- // whichever tap actually installed it.
- return 'brew upgrade opencode';
+ // V1 uses the core formula; v2 uses the separate upstream tap formula.
+ return packageName === '@opencode/cli'
+ ? 'brew upgrade anomalyco/tap/opencode-v2'
+ : 'brew upgrade opencode';
case 'custom':
case 'unknown':
return null;
@@ -142,9 +150,13 @@ const ALL_INSTALL_METHODS: OpenCodeInstallMethod[] = [
*/
export const OPENCODE_TERMINAL_COMMANDS: readonly string[] = [
OPENCODE_INSTALL_COMMAND,
+ OPENCODE_V1_INSTALL_COMMAND,
OPENCODE_UPGRADE_COMMAND,
...ALL_INSTALL_METHODS.flatMap((method) =>
- ['darwin', 'linux', 'win32'].map((platform) => getUpgradeCommand(method, platform))
+ ['darwin', 'linux', 'win32'].flatMap((platform) => [
+ getUpgradeCommand(method, platform),
+ getUpgradeCommand(method, platform, '@opencode/cli'),
+ ])
).filter((command): command is string => command !== null),
];
@@ -228,10 +240,11 @@ export function classifyUpgradeFailure(
export function getRecoveryCommand(
kind: OpenCodeUpgradeFailureKind,
method: OpenCodeInstallMethod,
- platform: InstallPlatform
+ platform: InstallPlatform,
+ packageName: OpenCodeCliPackage = 'opencode-ai'
): string | null {
if (kind === 'missing-package-manager') return null;
- return getUpgradeCommand(method, platform);
+ return getUpgradeCommand(method, platform, packageName);
}
/**
@@ -241,9 +254,10 @@ export function getRecoveryCommand(
export function describeUpgradeFailure(
kind: OpenCodeUpgradeFailureKind,
method: OpenCodeInstallMethod,
- platform: InstallPlatform
+ platform: InstallPlatform,
+ packageName: OpenCodeCliPackage = 'opencode-ai'
): string {
- const command = getUpgradeCommand(method, platform);
+ const command = getUpgradeCommand(method, platform, packageName);
const fallback = command
? `Update it manually with: ${command}`
: `Reinstall OpenCode using the method you originally used (${describeInstallMethod(method)}), then restart the server.`;
diff --git a/src/shared/opencode-types.ts b/src/shared/opencode-types.ts
index efe4a317..c6f8493b 100644
--- a/src/shared/opencode-types.ts
+++ b/src/shared/opencode-types.ts
@@ -333,6 +333,8 @@ export type CompactionPart = {
messageID: string;
type: 'compaction';
auto: boolean;
+ status?: 'running' | 'completed' | 'failed';
+ error?: string;
overflow?: boolean;
tail_start_id?: string;
};
@@ -358,6 +360,7 @@ export type PermissionRule = {
};
export type Session = {
+ sharingSupported?: boolean;
id: string;
slug?: string;
projectID: string;
@@ -944,6 +947,7 @@ export type ServerEventPropertiesByName = {
snapshot?: string;
};
'session.next.step.ended': {
+ executionContinues?: boolean;
timestamp?: number;
sessionID: string;
assistantMessageID?: string;
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index d5c38af8..c95404a1 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -1015,6 +1015,7 @@ export type WebviewMessage =
}
| { type: 'session/open-in-sidebar'; payload: { sessionId: string; directory?: string } }
| { type: 'session/open-in-opencode'; payload: { sessionId: string; directory?: string } }
+ | { type: 'session/import-v1'; payload: { sessionId: string; directory: string } }
| { type: 'chat/new-editor' }
| { type: 'chat/new-window' }
| { type: 'window-chat-theme/set-reversed'; payload: { reversed: boolean } }
diff --git a/src/shared/server-ownership.ts b/src/shared/server-ownership.ts
index 401fc070..802d0ec5 100644
--- a/src/shared/server-ownership.ts
+++ b/src/shared/server-ownership.ts
@@ -11,6 +11,8 @@ export interface ManagedServerOwnershipLease {
state: 'active' | 'relinquished';
createdAt: number;
configPath?: string;
+ /** Host-only credential, persisted in the private ownership file for window handoff. */
+ password?: string;
}
export function parseManagedServerOwnershipLease(value: T): ManagedServerOwnershipLease | null {
@@ -48,6 +50,11 @@ export function parseManagedServerOwnershipLease(value: T): ManagedServerOwne
if (record.state !== 'active' && record.state !== 'relinquished') return null;
if (!isNumber(record.createdAt) || !Number.isFinite(record.createdAt)) return null;
if (record.configPath !== undefined && !isString(record.configPath)) return null;
+ if (
+ record.password !== undefined &&
+ (!isString(record.password) || !record.password || record.password.length > 4096)
+ )
+ return null;
const lease: ManagedServerOwnershipLease = {
version: 1,
@@ -65,6 +72,7 @@ export function parseManagedServerOwnershipLease(value: T): ManagedServerOwne
lease.hostBirthIdentity = record.hostBirthIdentity;
}
if (record.configPath) lease.configPath = record.configPath;
+ if (isString(record.password)) lease.password = record.password;
return lease;
}
import { asRecord, isNumber, isString } from './type-utils';
diff --git a/src/shared/skill-reference.ts b/src/shared/skill-reference.ts
new file mode 100644
index 00000000..f9c50570
--- /dev/null
+++ b/src/shared/skill-reference.ts
@@ -0,0 +1,25 @@
+export function formatSkillReference(name: string): string {
+ return `$[${encodeURIComponent(name)}]`;
+}
+
+export function getSkillReferences(text: string): string[] {
+ const names = new Set();
+ for (const match of text.matchAll(/\$\[([^\]\s]+)\]/g)) {
+ try {
+ const name = decodeURIComponent(match[1]!);
+ if (name && formatSkillReference(name) === match[0]) names.add(name);
+ } catch {
+ // Malformed pasted markers remain ordinary text.
+ }
+ }
+ return [...names];
+}
+
+export function formatSkillAttachment(name: string): string {
+ return `[Attached skill: ${formatSkillReference(name)}]\nUse the skill tool to load ${JSON.stringify(name)} before responding. ${formatSkillReference(name)} in the prompt refers to this skill.`;
+}
+
+export function parseSkillAttachment(text: string): string | null {
+ const name = getSkillReferences(text)[0];
+ return name && text === formatSkillAttachment(name) ? name : null;
+}
diff --git a/src/webview/components/ChatInput.test.ts b/src/webview/components/ChatInput.test.ts
index 4525490f..fb6a6aca 100644
--- a/src/webview/components/ChatInput.test.ts
+++ b/src/webview/components/ChatInput.test.ts
@@ -9594,6 +9594,44 @@ describe('ChatInput', () => {
).toContain('Default');
});
+ it.each([undefined, '', 'default'])(
+ 'does not warn for an unchanged default variant %j',
+ (variant) => {
+ setState('providers', [
+ {
+ id: 'meta',
+ name: 'Meta',
+ source: 'api',
+ models: {
+ 'muse-1.3c': {
+ id: 'muse-1.3c',
+ name: 'Muse 1.3c',
+ capabilities: { toolcall: true, reasoning: true },
+ cost: { input: 0, output: 0 },
+ variants: { '': {}, high: {} },
+ },
+ },
+ },
+ ]);
+ setState('activeSessionId', 'session-1');
+ setState('selectedModel', { providerID: 'meta', modelID: 'muse-1.3c' });
+ const response = assistantMessageEntry({ input: 400, output: 100 });
+ setState('messages', [
+ {
+ ...response,
+ info: { ...response.info, providerID: 'meta', modelID: 'muse-1.3c', variant },
+ },
+ ]);
+
+ cleanup = render(() => ChatInput(), container!);
+
+ expect(container?.querySelector('.model-selection-cost-warning')).toBeNull();
+
+ setState('selectedModel', { providerID: 'meta', modelID: 'muse-1.3c', variant: 'high' });
+ expect(container?.querySelector('.model-selection-cost-warning')).not.toBeNull();
+ }
+ );
+
it('warns when the model or reasoning level changes after a session request', async () => {
vi.useFakeTimers();
setState('providers', [
diff --git a/src/webview/components/ChatInput.tsx b/src/webview/components/ChatInput.tsx
index cc5f2e0c..b3f2c5e1 100644
--- a/src/webview/components/ChatInput.tsx
+++ b/src/webview/components/ChatInput.tsx
@@ -138,6 +138,7 @@ import {
updatePermissionModeForSession,
} from '../hooks/useOpenCode';
import { deriveSelectedModelFromMessages } from '../hooks/routing-state';
+import { normalizeModelVariant } from '../../shared/model-variant';
import {
editingMessage,
getMessageEditDraftBackup,
@@ -4484,7 +4485,8 @@ export function ChatInput(props: { newSession?: boolean; onBeforeSend?: () => vo
const changed =
previous.providerID !== current.providerID ||
previous.modelID !== current.modelID ||
- (previous.variant ?? null) !== effectiveVariant();
+ normalizeModelVariant(previous.modelID, previous.variant) !==
+ normalizeModelVariant(current.modelID, effectiveVariant());
if (!changed) return null;
const provider = state.providers.find((item) => item.id === previous.providerID);
diff --git a/src/webview/components/Message.test.ts b/src/webview/components/Message.test.ts
index f83d009c..5bcee3a3 100644
--- a/src/webview/components/Message.test.ts
+++ b/src/webview/components/Message.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render } from 'solid-js/web';
import { createSignal } from 'solid-js';
-import type { FilePart, Part, Session, ToolPart } from '../types';
+import type { FilePart, MessageEntry, Part, Session, ToolPart } from '../types';
import { client } from '../lib/client';
import { editingMessage, resetMessageEditState } from '../lib/message-edit-state';
import {
@@ -24,6 +24,7 @@ import {
import { resetToolCallExpansionState } from './ToolCall';
import { fixture } from '../test-fixtures';
import type { UnknownRecord } from '../../shared/type-utils';
+import { projectV2Message } from '../../extension/opencode-v2-projection';
const retryMessageMock = vi.hoisted(() => vi.fn());
const selectSessionMock = vi.hoisted(() => vi.fn());
@@ -118,6 +119,57 @@ function compactionPart(id: string, options?: { auto?: boolean; overflow?: boole
};
}
+describe('V2 generated transcript rendering', () => {
+ it('renders a completed native summary as a context divider without a user card', () => {
+ const projected = projectV2Message(
+ {
+ id: 'msg_compaction',
+ type: 'compaction',
+ time: { created: 1_000 },
+ status: 'completed',
+ reason: 'auto',
+ summary: '## Objective\n\nGenerated context',
+ recent: '',
+ },
+ 'session-1'
+ );
+ cleanup = render(() => Message(fixture(projected)), container!);
+ expect(container?.querySelector('.user-message-card')).toBeNull();
+ expect(container?.querySelector('.message-compaction-divider')?.textContent).toContain(
+ 'Context compacted (auto)'
+ );
+ expect(container?.textContent).not.toContain('Generated context');
+ });
+
+ it.each([
+ {
+ id: 'msg_skill',
+ type: 'skill',
+ time: { created: 1_000 },
+ skill: 'review',
+ name: 'Review',
+ text: 'Internal instructions',
+ },
+ {
+ id: 'msg_shell',
+ type: 'shell',
+ time: { created: 1_000, completed: 2_000 },
+ shellID: 'shell_one',
+ command: 'pwd',
+ status: 'exited',
+ },
+ ] as const)('renders $type records as tool activity without a user card', (record) => {
+ const projected = projectV2Message(record, 'session-1');
+ cleanup = render(() => Message(fixture(projected)), container!);
+ expect(container?.querySelector('.user-message-card')).toBeNull();
+ const activity = container?.querySelector('.assistant-activity-summary');
+ expect(activity?.textContent).toContain(record.type === 'skill' ? '1 skill' : '1 command');
+ activity?.click();
+ expect(container?.querySelector('.chat-tool-invocation-part')).not.toBeNull();
+ expect(container?.textContent).not.toContain('Internal instructions');
+ });
+});
+
function userMessage(id: string) {
return {
id,
diff --git a/src/webview/components/MessageList.presentation.test.ts b/src/webview/components/MessageList.presentation.test.ts
index 3a8a9b82..a3783aa1 100644
--- a/src/webview/components/MessageList.presentation.test.ts
+++ b/src/webview/components/MessageList.presentation.test.ts
@@ -2,9 +2,21 @@ import { describe, expect, it, vi } from 'vitest';
import { batch } from 'solid-js';
import { render } from 'solid-js/web';
import { reconcile } from 'solid-js/store';
-import { replaceMessages, setState, state, upsertPart } from '../lib/state';
+import type { SessionMessageAssistant } from '@opencode/client';
+import {
+ replaceMessages,
+ setMessagesIncremental,
+ setShowFileDiffs,
+ setState,
+ state,
+ upsertPart,
+} from '../lib/state';
import { flushMessagePresentation } from '../lib/message-list-layout';
-import type { ToolPart } from '../types';
+import type { Part, ToolPart } from '../types';
+import { projectV2Event } from '../../extension/opencode-v2-events';
+import { projectV2Message } from '../../extension/opencode-v2-projection';
+import { parseServerEvent } from '../../shared/protocol';
+import { createProjectedSessionEventHandler } from '../hooks/session/session-projected-events';
import { MessageList } from './MessageList';
import {
assistantMessage,
@@ -54,7 +66,7 @@ function completeSearch(part: ToolPart): ToolPart {
};
}
-function openChat(parts: ToolPart[] = []) {
+function openChat(parts: Part[] = []) {
setState('activeSessionId', 'session-1');
setState('sessionStatus', reconcile({ 'session-1': { type: 'busy' } }));
replaceMessages([
@@ -65,6 +77,105 @@ function openChat(parts: ToolPart[] = []) {
}
describe('streaming presentation handoff', () => {
+ it.each([false, true])(
+ 'keeps a v2 answer visible through snapshot reconciliation with preserveExtraParts=%s',
+ async (preserveExtraParts) => {
+ const native: SessionMessageAssistant = {
+ id: 'answer',
+ type: 'assistant',
+ agent: 'build',
+ model: { providerID: 'provider', id: 'model' },
+ time: { created: 1 },
+ content: [
+ { type: 'reasoning', text: 'Inspecting the queue', time: { created: 1, completed: 2 } },
+ {
+ type: 'tool',
+ id: 'search',
+ name: 'grep',
+ time: { created: 2, completed: 3 },
+ state: {
+ status: 'completed',
+ input: { pattern: 'queue' },
+ content: [{ type: 'text', text: 'Found matches' }],
+ },
+ },
+ ],
+ };
+ // SAFETY: This typed native fixture projects into the legacy parts consumed by the webview.
+ const initialParts = projectV2Message(native, 'session-1').parts as Part[];
+ openChat(initialParts);
+ const handle = createProjectedSessionEventHandler({
+ isSessionInActiveTree: (sessionId) => sessionId === 'session-1',
+ getMessages: () => state.messages,
+ findAssistantMessage: (_sessionId, id) =>
+ state.messages.find((entry) => entry.info.id === id) ?? null,
+ findPart: (messageID, partID) =>
+ state.messages
+ .find((entry) => entry.info.id === messageID)
+ ?.parts.find((part) => part.id === partID) ?? null,
+ scheduleActiveMessageSync: vi.fn(),
+ syncTodosFromMessages: vi.fn(),
+ });
+ const answer = 'The queue is ready.';
+ const event = parseServerEvent(
+ projectV2Event({
+ id: 'evt_answer',
+ type: 'session.text.ended',
+ created: 4,
+ data: { sessionID: 'session-1', assistantMessageID: 'answer', ordinal: 0, text: answer },
+ })[0]
+ );
+ if (!event?.properties) throw new Error('Expected a projected v2 text event');
+ expect(handle(event.type, event.properties)).toBe(true);
+ await vi.advanceTimersByTimeAsync(350);
+ expect(container?.textContent).toContain(answer);
+
+ // SAFETY: The completed native snapshot uses the same projection as initial hydration.
+ const finalParts = projectV2Message(
+ { ...native, content: [...native.content, { type: 'text', text: answer }] },
+ 'session-1'
+ ).parts as Part[];
+ setMessagesIncremental(
+ [state.messages[0]!, { info: state.messages[1]!.info, parts: finalParts }],
+ { preserveExtraParts }
+ );
+ for (let frame = 0; frame < 150; frame += 1) {
+ if (frame === 60) {
+ batch(() => {
+ setState('messages', 1, 'info', 'time', { created: 1, completed: 5 });
+ setState('sessionStatus', reconcile({ 'session-1': { type: 'idle' } }));
+ });
+ }
+ expect(container?.textContent).toContain(answer);
+ await vi.advanceTimersByTimeAsync(16);
+ }
+ expect(state.messages[1]?.parts.map((part) => part.type)).toEqual([
+ 'reasoning',
+ 'tool',
+ 'text',
+ ]);
+ }
+ );
+
+ it.each([false, true])(
+ 'shows a streaming v2 patch before its input arrives with diffs=%s',
+ async (diffs) => {
+ setShowFileDiffs(diffs);
+ openChat([completeSearch(searchPart())]);
+ upsertPart({
+ ...toolPart('patch-streaming', 'answer', 'patch-call'),
+ tool: 'patch',
+ state: { status: 'pending', input: {}, raw: '' },
+ });
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(
+ container?.querySelector('.tool-status-running'),
+ container?.textContent
+ ).not.toBeNull();
+ expect(container?.textContent).toContain('Editing');
+ }
+ );
+
it('flushes available text when Stop interrupts an activity preview', async () => {
openChat();
upsertPart(completeSearch(searchPart()));
diff --git a/src/webview/components/MessageList.rendering.test.ts b/src/webview/components/MessageList.rendering.test.ts
index 796ae1b0..5a603738 100644
--- a/src/webview/components/MessageList.rendering.test.ts
+++ b/src/webview/components/MessageList.rendering.test.ts
@@ -2366,113 +2366,122 @@ describe('MessageList compact activity', () => {
);
});
- it('keeps pending apply_patch calls out of shared activity summaries', async () => {
- const patch = toolPart('patch-pending', 'assistant-1', 'call-patch-pending');
- patch.tool = 'apply_patch';
- patch.state = { status: 'pending', input: {}, raw: '' };
- const read = toolPart('read-1', 'assistant-1', 'call-read-1');
- read.tool = 'read';
- read.state = {
- status: 'completed',
- input: { filePath: 'src/app.ts' },
- output: 'source',
- title: 'src/app.ts',
- metadata: {},
- time: { start: 1, end: 2 },
- };
- setState('activeSessionId', 'session-1');
- replaceMessages([
- { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Inspect and edit')] },
- {
- info: assistantMessage('assistant-1', { parentID: 'user-1' }),
- parts: [patch, read],
- },
- ]);
-
- cleanup = render(() => MessageList(), container!);
- await Promise.resolve();
-
- expect(container?.querySelector('.assistant-activity-summary')?.textContent).toContain(
- 'Explored: 1 file'
- );
- expect(container?.querySelector('.assistant-activity-summary')?.textContent).not.toContain(
- 'edit'
- );
- expect(container?.querySelector('.tool-invocation-title')?.textContent).toBe('apply_patch');
- });
+ it.each(['apply_patch', 'patch'])(
+ 'keeps pending %s calls out of shared activity summaries',
+ async (tool) => {
+ const patch = toolPart('patch-pending', 'assistant-1', 'call-patch-pending');
+ patch.tool = tool;
+ patch.state = { status: 'pending', input: {}, raw: '' };
+ const read = toolPart('read-1', 'assistant-1', 'call-read-1');
+ read.tool = 'read';
+ read.state = {
+ status: 'completed',
+ input: { filePath: 'src/app.ts' },
+ output: 'source',
+ title: 'src/app.ts',
+ metadata: {},
+ time: { start: 1, end: 2 },
+ };
+ setState('activeSessionId', 'session-1');
+ replaceMessages([
+ { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Inspect and edit')] },
+ {
+ info: assistantMessage('assistant-1', { parentID: 'user-1' }),
+ parts: [patch, read],
+ },
+ ]);
- it('renders an isolated pending apply_patch row immediately', async () => {
- const patch = toolPart('patch-pending', 'assistant-2', 'call-patch-pending');
- patch.tool = 'apply_patch';
- patch.state = { status: 'pending', input: {}, raw: '' };
- setState('activeSessionId', 'session-1');
- setState('sessionStatus', reconcile({ 'session-1': { type: 'busy' } }));
- replaceMessages([
- { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Update the files')] },
- {
- info: assistantMessage('assistant-1', { parentID: 'user-1' }),
- parts: [textPart('commentary-1', 'I will update the recovery path.')],
- },
- {
- info: assistantMessage('assistant-2', {
- parentID: 'user-1',
- time: { created: 2 },
- }),
- parts: [patch],
- },
- ]);
+ cleanup = render(() => MessageList(), container!);
+ await Promise.resolve();
- cleanup = render(() => MessageList(), container!);
- await Promise.resolve();
+ expect(container?.querySelector('.assistant-activity-summary')?.textContent).toContain(
+ 'Explored: 1 file'
+ );
+ expect(container?.querySelector('.assistant-activity-summary')?.textContent).not.toContain(
+ 'edit'
+ );
+ expect(container?.querySelector('.tool-invocation-title')?.textContent).toBe('Editing');
+ }
+ );
+
+ it.each(['apply_patch', 'patch'])(
+ 'renders an isolated pending %s row immediately',
+ async (tool) => {
+ const patch = toolPart('patch-pending', 'assistant-2', 'call-patch-pending');
+ patch.tool = tool;
+ patch.state = { status: 'pending', input: {}, raw: '' };
+ setState('activeSessionId', 'session-1');
+ setState('sessionStatus', reconcile({ 'session-1': { type: 'busy' } }));
+ replaceMessages([
+ { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Update the files')] },
+ {
+ info: assistantMessage('assistant-1', { parentID: 'user-1' }),
+ parts: [textPart('commentary-1', 'I will update the recovery path.')],
+ },
+ {
+ info: assistantMessage('assistant-2', {
+ parentID: 'user-1',
+ time: { created: 2 },
+ }),
+ parts: [patch],
+ },
+ ]);
- const patchRow = container?.querySelector('[data-msg-id="assistant-2"]');
- expect(patchRow?.classList).not.toContain('interactive-item-render-empty');
- expect(patchRow?.querySelector('.tool-invocation-title')?.textContent).toBe('apply_patch');
- expect(patchRow?.querySelector('.tool-status-running')).not.toBeNull();
- });
+ cleanup = render(() => MessageList(), container!);
+ await Promise.resolve();
- it('removes a pending tool from Explored when it is identified as apply_patch', async () => {
- const patch = toolPart('patch-pending', 'assistant-1', 'call-patch-pending');
- patch.tool = '';
- patch.state = { status: 'pending', input: {}, raw: '' };
- const read = toolPart('read-1', 'assistant-1', 'call-read-1');
- read.tool = 'read';
- read.state = {
- status: 'completed',
- input: { filePath: 'src/app.ts' },
- output: 'source',
- title: 'src/app.ts',
- metadata: {},
- time: { start: 1, end: 2 },
- };
- setState('activeSessionId', 'session-1');
- setState('sessionStatus', reconcile({ 'session-1': { type: 'busy' } }));
- replaceMessages([
- { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Inspect and edit')] },
- {
- info: assistantMessage('assistant-1', { parentID: 'user-1' }),
- parts: [read, patch],
- },
- ]);
+ const patchRow = container?.querySelector('[data-msg-id="assistant-2"]');
+ expect(patchRow?.classList).not.toContain('interactive-item-render-empty');
+ expect(patchRow?.querySelector('.tool-invocation-title')?.textContent).toBe('Editing');
+ expect(patchRow?.querySelector('.tool-status-running')).not.toBeNull();
+ }
+ );
+
+ it.each(['apply_patch', 'patch'])(
+ 'removes a pending tool from Explored when it is identified as %s',
+ async (tool) => {
+ const patch = toolPart('patch-pending', 'assistant-1', 'call-patch-pending');
+ patch.tool = '';
+ patch.state = { status: 'pending', input: {}, raw: '' };
+ const read = toolPart('read-1', 'assistant-1', 'call-read-1');
+ read.tool = 'read';
+ read.state = {
+ status: 'completed',
+ input: { filePath: 'src/app.ts' },
+ output: 'source',
+ title: 'src/app.ts',
+ metadata: {},
+ time: { start: 1, end: 2 },
+ };
+ setState('activeSessionId', 'session-1');
+ setState('sessionStatus', reconcile({ 'session-1': { type: 'busy' } }));
+ replaceMessages([
+ { info: userMessage('user-1'), parts: [textPart('prompt-1', 'Inspect and edit')] },
+ {
+ info: assistantMessage('assistant-1', { parentID: 'user-1' }),
+ parts: [read, patch],
+ },
+ ]);
- cleanup = render(() => MessageList(), container!);
- await vi.advanceTimersByTimeAsync(500);
- container?.querySelector('.assistant-activity-summary')?.click();
+ cleanup = render(() => MessageList(), container!);
+ await vi.advanceTimersByTimeAsync(500);
+ container?.querySelector('.assistant-activity-summary')?.click();
- upsertPart({ ...patch, tool: 'functions.apply_patch' });
+ upsertPart({ ...patch, tool: `functions.${tool}` });
- const patchTitle = [...(container?.querySelectorAll('.tool-invocation-title') || [])].find(
- (element) => element.textContent?.endsWith('apply_patch')
- );
- expect(patchTitle).not.toBeUndefined();
- expect(patchTitle?.closest('.assistant-activity-details')).toBeNull();
- expect(container?.querySelector('.assistant-activity-summary')?.textContent).toContain(
- 'Explored: 1 file'
- );
- expect(container?.querySelector('.assistant-activity-summary')?.textContent).not.toContain(
- 'tool call'
- );
- });
+ const patchTitle = [...(container?.querySelectorAll('.tool-invocation-title') || [])].find(
+ (element) => element.textContent === 'Editing'
+ );
+ expect(patchTitle).not.toBeUndefined();
+ expect(patchTitle?.closest('.assistant-activity-details')).toBeNull();
+ expect(container?.querySelector('.assistant-activity-summary')?.textContent).toContain(
+ 'Explored: 1 file'
+ );
+ expect(container?.querySelector('.assistant-activity-summary')?.textContent).not.toContain(
+ 'tool call'
+ );
+ }
+ );
it('keeps an expanded activity group open when history extends it backward', async () => {
const command = toolPart('command-1', 'assistant-1', 'call-command-1');
diff --git a/src/webview/components/ModelPicker.test.ts b/src/webview/components/ModelPicker.test.ts
index 923f12fe..2480d917 100644
--- a/src/webview/components/ModelPicker.test.ts
+++ b/src/webview/components/ModelPicker.test.ts
@@ -386,6 +386,9 @@ describe('ModelPicker', () => {
await flushMicrotasks();
expect(container?.querySelector('.model-picker-details')?.textContent).toContain('OpenAI');
+ expect(container?.querySelector('.model-picker-details')?.textContent).toContain(
+ 'Released2026/01/01'
+ );
expect(container?.querySelector('.model-picker-details')?.textContent).toContain(
'text, image, pdf'
);
@@ -426,6 +429,7 @@ describe('ModelPicker', () => {
const anchor = container?.querySelector('.model-picker-anchor');
const details = container?.querySelector('.model-picker-details');
+ expect(details?.textContent).not.toContain('Released');
expect(anchor?.classList).toContain('details-on-top');
expect(details?.classList).toContain('top');
expect(details?.textContent).toContain('OpenAI');
diff --git a/src/webview/components/ModelPicker.tsx b/src/webview/components/ModelPicker.tsx
index 24e6a4e7..22d43bfd 100644
--- a/src/webview/components/ModelPicker.tsx
+++ b/src/webview/components/ModelPicker.tsx
@@ -14,6 +14,7 @@ import {
import {
formatVariantLabel as formatThinkingLabel,
formatContextLimit,
+ formatModelReleaseDate,
formatProviderLimitTitle,
formatProviderLimitCompact,
formatProviderLimitCompactPrefix,
@@ -695,6 +696,14 @@ export function ModelPicker(props: {
Provider
{entry().provider.name}
+
+ {(releaseDate) => (
+
+
Released
+ {releaseDate()}
+
+ )}
+
Inputs
{formatModelInputs(entry().model.capabilities.input)}
diff --git a/src/webview/components/ServerStatus.test.ts b/src/webview/components/ServerStatus.test.ts
index 351331e0..e2614599 100644
--- a/src/webview/components/ServerStatus.test.ts
+++ b/src/webview/components/ServerStatus.test.ts
@@ -91,7 +91,8 @@ describe('ServerStatus', () => {
renderServerStatus();
expect(container?.textContent).toContain('OpenCode is not installed');
- expect(container?.textContent).toContain('npm i -g opencode-ai');
+ expect(container?.textContent).toContain('npm i -g @opencode/cli');
+ expect(container?.textContent).toContain('Use OpenCode v1 instead');
// Recovery is a button now, not an instruction to open the Command Palette.
expect(container?.textContent).toContain('Restart Server');
expect(container?.textContent).toContain('varro.server.command');
@@ -105,11 +106,11 @@ describe('ServerStatus', () => {
expect(postMessageMock).toHaveBeenNthCalledWith(1, {
type: 'vscode/open-external',
- payload: { url: 'https://opencode.ai' },
+ payload: { url: 'https://opencode.ai/v2/docs/' },
});
expect(postMessageMock).toHaveBeenNthCalledWith(2, {
type: 'vscode/open-external',
- payload: { url: 'https://opencode.ai' },
+ payload: { url: 'https://opencode.ai/v2/docs/' },
});
});
@@ -126,7 +127,7 @@ describe('ServerStatus', () => {
expect(postMessageMock).toHaveBeenCalledWith({
type: 'terminal/run',
- payload: { command: 'npm i -g opencode-ai', title: 'OpenCode Install' },
+ payload: { command: 'npm i -g @opencode/cli', title: 'OpenCode Install' },
});
});
@@ -138,13 +139,13 @@ describe('ServerStatus', () => {
renderServerStatus();
const copyButton = container?.querySelector(
- 'button[aria-label="Copy command: npm i -g opencode-ai"]'
+ 'button[aria-label="Copy command: npm i -g @opencode/cli"]'
);
expect(copyButton).not.toBeNull();
copyButton?.click();
await Promise.resolve();
- expect(writeText).toHaveBeenCalledWith('npm i -g opencode-ai');
+ expect(writeText).toHaveBeenCalledWith('npm i -g @opencode/cli');
});
it('shows actionable guidance when OpenCode must be updated', () => {
@@ -317,7 +318,7 @@ describe('ServerStatus', () => {
expect(container?.textContent).toContain('/opt/nope/opencode');
// Telling someone with a configured path to reinstall via npm is the wrong fix.
expect(container?.textContent).not.toContain('OpenCode is not installed');
- expect(container?.textContent).not.toContain('npm i -g opencode-ai');
+ expect(container?.textContent).not.toContain('npm i -g @opencode/cli');
});
it('restarts the server from any error state', () => {
@@ -357,7 +358,7 @@ describe('ServerStatus', () => {
expect(openProviderSetupMock).toHaveBeenCalledTimes(1);
expect(postMessageMock).toHaveBeenCalledWith({
type: 'vscode/open-external',
- payload: { url: 'https://opencode.ai/docs/providers' },
+ payload: { url: 'https://opencode.ai/v2/docs/providers' },
});
});
});
diff --git a/src/webview/components/ServerStatus.tsx b/src/webview/components/ServerStatus.tsx
index d03fd52f..014b7e22 100644
--- a/src/webview/components/ServerStatus.tsx
+++ b/src/webview/components/ServerStatus.tsx
@@ -4,6 +4,7 @@ import {
OPENCODE_INSTALL_COMMAND,
OPENCODE_INSTALL_DOCS_URL,
OPENCODE_UPGRADE_COMMAND,
+ OPENCODE_V1_INSTALL_COMMAND,
} from '../../shared/opencode-install';
import type { ServerErrorDetail } from '../../shared/protocol';
import { postMessage } from '../lib/bridge';
@@ -269,12 +270,19 @@ export function ServerStatus() {
Open terminal and add a provider
+ openExternal('https://opencode.ai/v2/docs/providers')}
+ >
+ Provider setup docs (v2)
+
openExternal('https://opencode.ai/docs/providers')}
>
- Provider setup docs
+ Provider setup docs (v1)
@@ -299,10 +307,10 @@ function MissingCliState() {
{' '}
a native UI.
- Install the CLI to get started.
+ Install OpenCode v2 to get started. V1 is also supported.
-
+
Open terminal and install
+
+ Use npm on macOS, Linux, or WSL. On native Windows, download the CLI from the install docs
+ below and set its path in varro.server.command.
+
+
+ Use OpenCode v1 instead
+
+
+
runInTerminal(OPENCODE_V1_INSTALL_COMMAND, 'OpenCode Install')}
+ />
+
+ Set varro.server.command to your v1 executable to keep using v1. Both versions now use
+ the opencode command; use separate executable paths if you keep both.
+
+
+
{/* Installs under a Node version manager land outside the directories
Varro can scan, so point at the escape hatch instead of insisting
diff --git a/src/webview/components/ToolCall.test.ts b/src/webview/components/ToolCall.test.ts
index 210f9914..3c3ca59a 100644
--- a/src/webview/components/ToolCall.test.ts
+++ b/src/webview/components/ToolCall.test.ts
@@ -161,6 +161,12 @@ describe('formatToolTitle', () => {
);
});
+ it('uses the command preview for completed bash calls without a title', () => {
+ expect(formatToolTitle('bash', completedState({ command: 'npm run lint' }, ''))).toBe(
+ 'npm run lint'
+ );
+ });
+
it('uses the description as the task title', () => {
expect(
formatToolTitle('task', completedState({ description: 'Trace Varro diff logic' }, 'Working'))
@@ -326,7 +332,7 @@ describe('ToolCall', () => {
expect(container?.querySelector('.tool-invocation-detail')).toBeNull();
});
- it('animates pending apply_patch calls as in-progress tools', () => {
+ it.each(['apply_patch', 'patch'])('animates pending %s calls as in-progress tools', (tool) => {
vi.useFakeTimers();
vi.setSystemTime(10_000);
const part: ToolPart = {
@@ -335,7 +341,7 @@ describe('ToolCall', () => {
messageID: 'message-1',
type: 'tool',
callID: 'call-1',
- tool: 'apply_patch',
+ tool,
state: {
status: 'pending',
input: {},
@@ -358,18 +364,20 @@ describe('ToolCall', () => {
expect(container?.querySelector('.tool-invocation-duration')?.textContent).toBe('1m 9s');
});
- it('shows files from running apply_patch input in the compact edit card', () => {
- const part: ToolPart = {
- id: 'tool-1',
- sessionID: 'session-1',
- messageID: 'message-1',
- type: 'tool',
- callID: 'call-1',
- tool: 'apply_patch',
- state: {
- status: 'running',
- input: {
- patchText: `*** Begin Patch
+ it.each(['apply_patch', 'patch'])(
+ 'shows files from running %s input in the compact edit card',
+ (tool) => {
+ const part: ToolPart = {
+ id: 'tool-1',
+ sessionID: 'session-1',
+ messageID: 'message-1',
+ type: 'tool',
+ callID: 'call-1',
+ tool,
+ state: {
+ status: 'running',
+ input: {
+ patchText: `*** Begin Patch
*** Update File: src/app.ts
@@
-old
@@ -379,37 +387,38 @@ describe('ToolCall', () => {
-old
+new
*** End Patch`,
+ },
+ title: 'apply_patch',
+ metadata: {},
+ time: { start: 0 },
},
- title: 'apply_patch',
- metadata: {},
- time: { start: 0 },
- },
- };
+ };
- cleanup = render(() => ToolCall({ part }), container!);
+ cleanup = render(() => ToolCall({ part }), container!);
- expect(container?.querySelector('.file-change-card-header')?.textContent).not.toContain(
- '2 files'
- );
- expect(
- Array.from(container?.querySelectorAll('.file-edit-path-link') || []).map(
- (link) => link.textContent
- )
- ).toEqual(['src/app.ts', 'src/theme.css']);
- expect(container?.querySelector('.file-change-card-header')?.textContent).not.toContain(
- 'editing…'
- );
- expect(container?.querySelector('.tool-invocation-header')).toBeNull();
- });
+ expect(container?.querySelector('.file-change-card-header')?.textContent).not.toContain(
+ '2 files'
+ );
+ expect(
+ Array.from(container?.querySelectorAll('.file-edit-path-link') || []).map(
+ (link) => link.textContent
+ )
+ ).toEqual(['src/app.ts', 'src/theme.css']);
+ expect(container?.querySelector('.file-change-card-header')?.textContent).not.toContain(
+ 'editing…'
+ );
+ expect(container?.querySelector('.tool-invocation-header')).toBeNull();
+ }
+ );
- it('animates a pending apply_patch file-change card', () => {
+ it.each(['apply_patch', 'patch'])('animates a pending %s file-change card', (tool) => {
const part: ToolPart = {
id: 'tool-1',
sessionID: 'session-1',
messageID: 'message-1',
type: 'tool',
callID: 'call-1',
- tool: 'apply_patch',
+ tool,
state: {
status: 'pending',
input: {
diff --git a/src/webview/components/ToolCall.tsx b/src/webview/components/ToolCall.tsx
index 3898df7b..59bb2cfb 100644
--- a/src/webview/components/ToolCall.tsx
+++ b/src/webview/components/ToolCall.tsx
@@ -284,6 +284,13 @@ export function formatToolTitle(toolName: string, state: ToolPart['state']) {
const title = getStateTitle(state);
const normalizedToolName = normalizeToolName(toolName);
+ if (
+ isApplyPatchTool(normalizedToolName) &&
+ (state.status === 'pending' || state.status === 'running')
+ ) {
+ return 'Editing';
+ }
+
if (getToolKind(normalizedToolName) === 'search') {
const pattern = getSearchPattern(input);
if (pattern) return `Search: ${pattern}`;
@@ -295,6 +302,13 @@ export function formatToolTitle(toolName: string, state: ToolPart['state']) {
if (isString(description) && description.trim()) return description.trim();
}
+ if (normalizedToolName === 'skill') {
+ for (const key of ['id', 'name']) {
+ const name = input[key];
+ if (isString(name) && name.trim()) return `Skill: ${name.trim()}`;
+ }
+ }
+
if (normalizedToolName === 'webfetch') {
const url = input.url;
if (isString(url) && url.trim()) return url.trim();
diff --git a/src/webview/components/chat/SessionActionsMenu.tsx b/src/webview/components/chat/SessionActionsMenu.tsx
index d488ad73..999b1b0c 100644
--- a/src/webview/components/chat/SessionActionsMenu.tsx
+++ b/src/webview/components/chat/SessionActionsMenu.tsx
@@ -261,13 +261,15 @@ export function SessionActionsMenu(props: {
void copySessionId()}>
Copy session ID
- (props.session.share?.url ? void unshare() : void copyShareLink())}
- >
- {props.session.share?.url ? 'Unshare session' : 'Share session'}
-
+
+ (props.session.share?.url ? void unshare() : void copyShareLink())}
+ >
+ {props.session.share?.url ? 'Unshare session' : 'Share session'}
+
+
= {}): CompactionPart
}
describe('CompactionDivider', () => {
+ it.each([
+ ['running', 'Compacting context (auto)'],
+ ['failed', 'Context compaction failed (auto): Summary failed'],
+ ['completed', 'Context compacted (auto)'],
+ ] as const)('labels %s compaction accurately', (status, label) => {
+ cleanup = render(
+ () =>
+ CompactionDivider({
+ part: {
+ ...compactionPart({ auto: true }),
+ status,
+ error: status === 'failed' ? 'Summary failed' : undefined,
+ },
+ timestamp: 1_000,
+ }),
+ container!
+ );
+ expect(container?.textContent).toContain(label);
+ });
+
it('renders the manual compaction label by default', () => {
cleanup = render(
() => CompactionDivider({ part: compactionPart(), timestamp: 1_000 }),
diff --git a/src/webview/components/message/CompactionDivider.tsx b/src/webview/components/message/CompactionDivider.tsx
index 53613ca7..3812deb6 100644
--- a/src/webview/components/message/CompactionDivider.tsx
+++ b/src/webview/components/message/CompactionDivider.tsx
@@ -14,6 +14,10 @@ export function CompactionDivider(props: {
const [isHoverIntentActive, setIsHoverIntentActive] = createSignal(false);
const label = () => {
const kind = props.part.auto ? 'auto' : 'manual';
+ if (props.part.status === 'running') return `Compacting context (${kind})`;
+ if (props.part.status === 'failed') {
+ return `Context compaction failed (${kind})${props.part.error ? `: ${props.part.error}` : ''}`;
+ }
return props.part.overflow
? `Context compacted (${kind}, after overflow)`
: `Context compacted (${kind})`;
diff --git a/src/webview/hooks/runtime/open-code-runtime-instance.ts b/src/webview/hooks/runtime/open-code-runtime-instance.ts
index d1c79607..a7249f10 100644
--- a/src/webview/hooks/runtime/open-code-runtime-instance.ts
+++ b/src/webview/hooks/runtime/open-code-runtime-instance.ts
@@ -531,10 +531,22 @@ function mergeSessionMessages(
sessions: Session[] = appStore.state.sessions
): MessageEntry[] {
const sessionMessages = incoming.filter((entry) => entry.info.sessionID === sessionId);
- if (!current.some((entry) => entry.info.sessionID !== sessionId)) return incoming;
+ const pendingOptimisticMessages = current.filter(
+ (entry) =>
+ entry.info.sessionID === sessionId &&
+ entry.info.role === 'user' &&
+ entry.parts.some((part) => part.id.startsWith(`${entry.info.id}-part-`)) &&
+ !sessionMessages.some((candidate) => candidate.info.id === entry.info.id)
+ );
+ const incomingWithPendingOptimistic =
+ pendingOptimisticMessages.length > 0
+ ? [...sessionMessages, ...pendingOptimisticMessages]
+ : sessionMessages;
+ if (!current.some((entry) => entry.info.sessionID !== sessionId))
+ return incomingWithPendingOptimistic;
const incomingIndexById = new Map(
- sessionMessages.map((entry, index) => [entry.info.id, index] as const)
+ incomingWithPendingOptimistic.map((entry, index) => [entry.info.id, index] as const)
);
const hasOverlap = current.some(
(entry) => entry.info.sessionID === sessionId && incomingIndexById.has(entry.info.id)
@@ -543,7 +555,11 @@ function mergeSessionMessages(
const firstSessionIndex = current.findIndex((entry) => entry.info.sessionID === sessionId);
const session = sessions.find((candidate) => candidate.id === sessionId);
if (firstSessionIndex < 0 && !session?.parentID) {
- return mergeParentSnapshotWithRecoveredSessions(sessionMessages, current, sessions);
+ return mergeParentSnapshotWithRecoveredSessions(
+ incomingWithPendingOptimistic,
+ current,
+ sessions
+ );
}
const insertionIndex =
firstSessionIndex < 0
@@ -551,7 +567,7 @@ function mergeSessionMessages(
: firstSessionIndex;
return [
...current.slice(0, insertionIndex).filter((entry) => entry.info.sessionID !== sessionId),
- ...sessionMessages,
+ ...incomingWithPendingOptimistic,
...current.slice(insertionIndex).filter((entry) => entry.info.sessionID !== sessionId),
];
}
@@ -566,9 +582,11 @@ function mergeSessionMessages(
const matchingIndex = incomingIndexById.get(entry.info.id);
if (matchingIndex === undefined || matchingIndex < incomingIndex) continue;
- while (incomingIndex <= matchingIndex) merged.push(sessionMessages[incomingIndex++]!);
+ while (incomingIndex <= matchingIndex)
+ merged.push(incomingWithPendingOptimistic[incomingIndex++]!);
}
- while (incomingIndex < sessionMessages.length) merged.push(sessionMessages[incomingIndex++]!);
+ while (incomingIndex < incomingWithPendingOptimistic.length)
+ merged.push(incomingWithPendingOptimistic[incomingIndex++]!);
return merged;
}
@@ -1978,8 +1996,23 @@ export function createOpenCodeRuntime(): OpenCodeRuntime {
await Promise.all([dataLoaders.refreshRoutingState(), loadCompatibilityState()]);
}
+ function removeUnavailableSession(sessionId: string) {
+ // A missing record on another server is not a deletion of its saved drafts or settings.
+ batch(() => {
+ sessionStore.setSessions(
+ appStore.state.sessions.filter((session) => session.id !== sessionId)
+ );
+ if (appStore.state.activeSessionId === sessionId) {
+ sessionLifecycleOperations.clearActiveSessionState();
+ uiStore.setShowSessionPicker(true);
+ }
+ });
+ }
+
async function reconcileServerState() {
const activeSessionId = appStore.state.activeSessionId;
+ const connection = connectionGeneration;
+ const workspace = workspaceGeneration;
const results = await Promise.allSettled([
loadSessions(),
loadRecycleBin(),
@@ -1990,7 +2023,22 @@ export function createOpenCodeRuntime(): OpenCodeRuntime {
loadLsps(),
reloadWorkspaceCatalogs(),
loadCompatibilityState(),
- ...(activeSessionId ? [syncSession(activeSessionId)] : []),
+ ...(activeSessionId
+ ? [
+ syncSession(activeSessionId).catch((error) => {
+ if (
+ connection === connectionGeneration &&
+ workspace === workspaceGeneration &&
+ error instanceof Error &&
+ /^404\b.*session not found/i.test(error.message)
+ ) {
+ removeUnavailableSession(activeSessionId);
+ return;
+ }
+ throw error;
+ }),
+ ]
+ : []),
]);
for (const result of results) {
if (result.status === 'rejected') logError('reconcileServerState', result.reason);
@@ -2212,7 +2260,10 @@ export function createOpenCodeRuntime(): OpenCodeRuntime {
getSession: (id) => appStore.state.sessions.find((session) => session.id === id),
buildPermissionRules: (mode) => getSessionPermissionRulesForMode(mode, 'update'),
getPermissionMode: permissionsStore.getPermissionModeForSession,
- updateSessionPermission: (id, input) => client.session.update(id, input, options),
+ updateSessionPermission: (id, input) =>
+ client.session.update(id, input, {
+ directory: options?.directory ?? getSessionDirectory(id),
+ }),
upsertSession,
setError: uiStore.setError,
},
@@ -2262,6 +2313,9 @@ export function createOpenCodeRuntime(): OpenCodeRuntime {
const sessionSyncOperations = new SessionSyncOperations(
{
+ removeUnavailableSession,
+ importLegacySession: (sessionId, directory) =>
+ postMessage({ type: 'session/import-v1', payload: { sessionId, directory } }),
getActiveSessionId: () => appStore.state.activeSessionId,
setActiveSessionId: sessionStore.setActiveSessionId,
clearPendingAbort,
diff --git a/src/webview/hooks/session-event-handlers.test.ts b/src/webview/hooks/session-event-handlers.test.ts
index 3c0a2b78..6981b538 100644
--- a/src/webview/hooks/session-event-handlers.test.ts
+++ b/src/webview/hooks/session-event-handlers.test.ts
@@ -2447,33 +2447,36 @@ describe('registerSessionEventHandlers', () => {
expect(syncSessionMessages).not.toHaveBeenCalled();
});
- it.each(['session.next.prompted', 'session.next.synthetic', 'session.next.shell.started'])(
- 'resyncs transcript records for an in-order %s event',
- async (eventName) => {
- const handlers = installHandlers();
- const syncSessionMessages = vi.fn().mockResolvedValue(undefined);
+ it.each([
+ 'session.next.prompted',
+ 'session.next.synthetic',
+ 'session.next.shell.started',
+ 'session.next.compaction.started',
+ 'session.next.compaction.ended',
+ ])('resyncs transcript records for an in-order %s event', async (eventName) => {
+ const handlers = installHandlers();
+ const syncSessionMessages = vi.fn().mockResolvedValue(undefined);
- registerSessionEventHandlers(
- createDefaultDeps({
- getActiveSessionId: () => 'session-1',
- syncSessionMessages,
- })
- );
+ registerSessionEventHandlers(
+ createDefaultDeps({
+ getActiveSessionId: () => 'session-1',
+ syncSessionMessages,
+ })
+ );
- handlers.get(eventName)?.({
- properties: {
- sessionID: 'session-1',
- messageID: 'message-1',
- callID: 'call-1',
- },
- seq: 1,
- });
+ handlers.get(eventName)?.({
+ properties: {
+ sessionID: 'session-1',
+ messageID: 'message-1',
+ callID: 'call-1',
+ },
+ seq: 1,
+ });
- await vi.waitFor(() => {
- expect(syncSessionMessages).toHaveBeenCalledWith('session-1');
- });
- }
- );
+ await vi.waitFor(() => {
+ expect(syncSessionMessages).toHaveBeenCalledWith('session-1');
+ });
+ });
it('runs a trailing transcript sync when shell completion arrives during a sync', async () => {
const handlers = installHandlers();
@@ -2509,6 +2512,25 @@ describe('registerSessionEventHandlers', () => {
await vi.waitFor(() => expect(syncSessionMessages).toHaveBeenCalledTimes(2));
});
+ it.each(['session.next.synthetic', 'session.next.shell.started', 'session.next.shell.ended'])(
+ 'fetches %s records even when the loaded assistant has finished',
+ async (eventName) => {
+ const handlers = installHandlers();
+ const syncSessionMessages = vi.fn().mockResolvedValue(undefined);
+ loadingStartedAt.mockReturnValue(1);
+ registerSessionEventHandlers(
+ createDefaultDeps({
+ getActiveSessionId: () => 'session-1',
+ getMessages: () => [createCompletedAssistantEntry(1, 2)],
+ syncSessionMessages,
+ })
+ );
+ handlers.get(eventName)?.({ properties: { sessionID: 'session-1', timestamp: 3 }, seq: 1 });
+ await vi.waitFor(() => expect(syncSessionMessages).toHaveBeenCalledWith('session-1'));
+ loadingStartedAt.mockReturnValue(null);
+ }
+ );
+
it('does not run a trailing transcript sync after cleanup', async () => {
const handlers = installHandlers();
let resolveFirstSync: (() => void) | undefined;
@@ -3304,6 +3326,72 @@ describe('registerSessionEventHandlers', () => {
expect(syncSessionMessages).not.toHaveBeenCalled();
});
+ it('loads the next v2 step after a completed tool step and streams its final answer', async () => {
+ const handlers = installHandlers();
+ const completed = createCompletedAssistantEntry(1, 2);
+ const next = createAssistantEntry({ id: 'assistant-2', time: { created: 3 } });
+ let messages = [completed];
+ const syncSessionMessages = vi.fn(async () => {
+ messages = [completed, next];
+ });
+ const cleanups = registerSessionEventHandlers(
+ createDefaultDeps({
+ getActiveSessionId: () => 'session-1',
+ getMessages: () => messages,
+ syncSessionMessages,
+ })
+ );
+ loadingStartedAt.mockReturnValue(1);
+ applyMessagePartDelta.mockClear();
+
+ emitServerEvent(handlers, 'session.next.step.ended', {
+ seq: 10,
+ properties: {
+ sessionID: 'session-1',
+ assistantMessageID: 'assistant-1',
+ executionContinues: true,
+ },
+ });
+ emitServerEvent(handlers, 'session.next.step.started', {
+ seq: 11,
+ properties: {
+ sessionID: 'session-1',
+ assistantMessageID: 'assistant-2',
+ executionContinues: true,
+ },
+ });
+ await Promise.resolve();
+
+ expect(syncSessionMessages).toHaveBeenCalledWith('session-1');
+ emitServerEvent(handlers, 'session.next.text.delta', {
+ properties: {
+ sessionID: 'session-1',
+ assistantMessageID: 'assistant-2',
+ textID: 'text-final',
+ delta: 'Fixed.',
+ },
+ });
+ expect(applyMessagePartDelta).toHaveBeenCalledWith(
+ 'assistant-2',
+ 'text-final',
+ 'Fixed.',
+ 'session-1',
+ 'text'
+ );
+ applyMessagePartDelta.mockClear();
+ emitServerEvent(handlers, 'session.next.text.delta', {
+ properties: {
+ sessionID: 'session-1',
+ assistantMessageID: 'assistant-1',
+ textID: 'text-old',
+ delta: 'Stale replay',
+ },
+ });
+ expect(applyMessagePartDelta).not.toHaveBeenCalled();
+ for (const cleanup of cleanups) cleanup();
+ loadingStartedAt.mockReturnValue(null);
+ });
+
it('ignores stale active progress events after the assistant already completed', () => {
const handlers = installHandlers();
const setSessionStatusEntry = vi.fn();
diff --git a/src/webview/hooks/session-selection.test.ts b/src/webview/hooks/session-selection.test.ts
index 0a2e2809..cfaecfdf 100644
--- a/src/webview/hooks/session-selection.test.ts
+++ b/src/webview/hooks/session-selection.test.ts
@@ -108,6 +108,44 @@ function createSelectionDependencies(
}
describe('session-selection helpers', () => {
+ it('removes a confirmed unavailable catalog entry and explains how to import legacy history', async () => {
+ const removeUnavailableSession = vi.fn();
+ const deps = createSelectionDependencies({
+ getActiveSessionId: () => 'session-1',
+ loadSession: async () => {
+ throw new Error('404 Session not found: session-1');
+ },
+ removeUnavailableSession,
+ });
+ await selectSessionWithDependencies(deps, { next: () => 1 }, 'session-1');
+ expect(removeUnavailableSession).toHaveBeenCalledExactlyOnceWith('session-1');
+ expect(deps.setError).toHaveBeenCalledWith(
+ expect.stringContaining('Import OpenCode v1 Session into v2')
+ );
+ expect(deps.persistActiveSessionId).not.toHaveBeenCalled();
+ });
+
+ it('requests a copy import when v2 cannot load a cataloged v1 session', async () => {
+ const importLegacySession = vi.fn();
+ const removeUnavailableSession = vi.fn();
+ const legacy = loadedSession('session-1').session;
+ const deps = createSelectionDependencies({
+ getActiveSessionId: () => 'session-1',
+ getSession: () => legacy,
+ loadSession: async () => {
+ throw new Error('404 Session not found: session-1');
+ },
+ importLegacySession,
+ removeUnavailableSession,
+ });
+
+ await selectSessionWithDependencies(deps, { next: () => 1 }, 'session-1');
+
+ expect(removeUnavailableSession).toHaveBeenCalledExactlyOnceWith('session-1');
+ expect(importLegacySession).toHaveBeenCalledExactlyOnceWith('session-1', '/repo');
+ expect(deps.setError).not.toHaveBeenCalled();
+ expect(deps.persistActiveSessionId).not.toHaveBeenCalled();
+ });
it('restores metadata ahead of stale local and message selections even while busy', async () => {
const model = { providerID: 'openai', modelID: 'saved-model' };
const oldModel = { providerID: 'openai', modelID: 'old-model', variant: 'high' };
diff --git a/src/webview/hooks/session-send.test.ts b/src/webview/hooks/session-send.test.ts
index 93a809f4..eebc1ccd 100644
--- a/src/webview/hooks/session-send.test.ts
+++ b/src/webview/hooks/session-send.test.ts
@@ -1690,7 +1690,7 @@ describe('session-send helpers', () => {
expect(upsertSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'session-1' }));
});
- it('clears session permission overrides in default mode', async () => {
+ it('preserves session-scoped Always approvals when sending in default mode', async () => {
const updateSessionPermission = vi.fn(
async (_sessionId: string, input: { permission: PermissionRule[] }) => ({
id: 'session-1',
@@ -1706,7 +1706,7 @@ describe('session-send helpers', () => {
const ok = await ensureSessionPermissionWithDependencies(
{
getSession: () => ({
- permission: [{ permission: '*', pattern: '*', action: 'ask' }],
+ permission: [{ permission: 'read', pattern: '/repo/README.md', action: 'allow' }],
}),
buildPermissionRules: () => [],
getPermissionMode: () => 'default',
@@ -1718,7 +1718,7 @@ describe('session-send helpers', () => {
);
expect(ok).toBe(true);
- expect(updateSessionPermission).toHaveBeenCalledWith('session-1', { permission: [] });
+ expect(updateSessionPermission).not.toHaveBeenCalled();
});
it('appends resolved default rules after stale full-access rules', async () => {
diff --git a/src/webview/hooks/session/session-event-handlers.ts b/src/webview/hooks/session/session-event-handlers.ts
index e44f5bee..5ef1110a 100644
--- a/src/webview/hooks/session/session-event-handlers.ts
+++ b/src/webview/hooks/session/session-event-handlers.ts
@@ -1008,6 +1008,8 @@ export function registerSessionEventHandlers(deps: EventHandlerDependencies) {
return messageId;
};
const settleAssistantStepEnd = (sessionId: string, props: UnknownRecord) => {
+ // V2 has an explicit execution boundary; a provider turn can finish before queued input runs.
+ if (props.executionContinues === true) return false;
if (isContinuationStepEnd('session.next.step.ended', props)) return false;
return settleAssistantStepCompletion(
sessionId,
@@ -1441,7 +1443,7 @@ export function registerSessionEventHandlers(deps: EventHandlerDependencies) {
const partialPart = asRecord(rawPart);
const partSessionID = isString(partialPart?.sessionID) ? partialPart.sessionID : undefined;
if (partSessionID && partialPart?.type === 'compaction') {
- sessionStore.setSessionCompacting(partSessionID, false);
+ sessionStore.setSessionCompacting(partSessionID, partialPart.status === 'running');
}
if (!isSessionInActiveTree(partSessionID)) return;
@@ -1526,10 +1528,21 @@ export function registerSessionEventHandlers(deps: EventHandlerDependencies) {
if (toolTimingUpdate?.ended) {
updateExistingToolPartExecutionTime(toolTimingUpdate.sessionId, toolTimingUpdate.callId);
}
+ const assistantMessageID = getEventString(p, 'assistantMessageID');
if (
!eventName.startsWith('session.next.compaction.') &&
- ignoreStaleProgressAfterFinishedAssistant(sessionID)
+ (assistantMessageID
+ ? ignoreStaleProgressForCompletedMessage(sessionID, assistantMessageID)
+ : ignoreStaleProgressAfterFinishedAssistant(sessionID))
) {
+ // A completed assistant does not mean later shell or skill records are already loaded.
+ if (
+ TRANSCRIPT_SYNC_SESSION_EVENTS.has(eventName) &&
+ seqStatus !== 'gap' &&
+ isSessionInActiveTree(sessionID)
+ ) {
+ scheduleMessageSync(sessionID, true);
+ }
return;
}
const activeTreeEvent = isSessionInActiveTree(sessionID);
@@ -1539,6 +1552,15 @@ export function registerSessionEventHandlers(deps: EventHandlerDependencies) {
return;
}
markSessionProgress(sessionID);
+ if (
+ eventName === 'session.next.compaction.started' ||
+ eventName === 'session.next.compaction.ended'
+ ) {
+ sessionStore.setSessionCompacting(
+ sessionID,
+ eventName === 'session.next.compaction.started'
+ );
+ }
if (
eventName === 'session.next.shell.started' ||
eventName === 'session.next.tool.called'
@@ -1566,7 +1588,15 @@ export function registerSessionEventHandlers(deps: EventHandlerDependencies) {
// Synchronized events arrive in durable order, so a contiguous seq means we have
// not missed anything. Events that create transcript records still need a fetch
// because Varro does not project those record types directly.
- const transcriptSync = TRANSCRIPT_SYNC_SESSION_EVENTS.has(eventName);
+ // V2 creates a separate assistant message for each step. A contiguous event
+ // sequence still needs a fetch when that new message is not loaded yet.
+ const transcriptSync =
+ TRANSCRIPT_SYNC_SESSION_EVENTS.has(eventName) ||
+ (eventName === 'session.next.step.started' &&
+ 'executionContinues' in p &&
+ p.executionContinues === true &&
+ !!assistantMessageID &&
+ !findAssistantMessage(sessionID, assistantMessageID));
if (seqStatus !== 'gap' && (transcriptSync || seqStatus !== 'ok')) {
scheduleMessageSync(sessionID, transcriptSync);
}
diff --git a/src/webview/hooks/session/session-event-utils.ts b/src/webview/hooks/session/session-event-utils.ts
index 121d1a13..69e7552b 100644
--- a/src/webview/hooks/session/session-event-utils.ts
+++ b/src/webview/hooks/session/session-event-utils.ts
@@ -176,6 +176,8 @@ export const TRANSCRIPT_SYNC_SESSION_EVENTS = new Set([
'session.next.synthetic',
'session.next.shell.started',
'session.next.shell.ended',
+ 'session.next.compaction.started',
+ 'session.next.compaction.ended',
]);
// After the final assistant text finishes streaming with no tools in flight, we
diff --git a/src/webview/hooks/session/session-projected-events.test.ts b/src/webview/hooks/session/session-projected-events.test.ts
index 4accb154..ae63612d 100644
--- a/src/webview/hooks/session/session-projected-events.test.ts
+++ b/src/webview/hooks/session/session-projected-events.test.ts
@@ -190,7 +190,7 @@ describe('projected text events', () => {
expect(upsertPart).not.toHaveBeenCalled();
});
- it('falls back to the loaded assistant when a projected text event uses its v2 id', () => {
+ it('waits for the named v2 assistant instead of putting its answer on the previous step', () => {
const harness = createHarness();
expect(
@@ -199,11 +199,21 @@ describe('projected text events', () => {
textID: 'text-1',
delta: 'hello',
})
- ).toBe(true);
- expect(upsertPart).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'text-1', messageID: MESSAGE_ID, type: 'text' })
- );
- expect(harness.scheduleActiveMessageSync).not.toHaveBeenCalled();
+ ).toBe(false);
+ expect(upsertPart).not.toHaveBeenCalled();
+ expect(applyMessagePartDelta).not.toHaveBeenCalled();
+ expect(harness.scheduleActiveMessageSync).toHaveBeenCalledWith(SESSION_ID);
+
+ harness.messages.push({ info: assistantInfo('v2-assistant-1'), parts: [] });
+ emit(harness, 'session.next.text.ended', {
+ assistantMessageID: 'v2-assistant-1',
+ textID: 'text-1',
+ text: 'hello',
+ });
+ expect(harness.messages[0]?.parts).toEqual([]);
+ expect(harness.messages[1]?.parts).toEqual([
+ expect.objectContaining({ id: 'text-1', messageID: 'v2-assistant-1', text: 'hello' }),
+ ]);
});
});
@@ -446,7 +456,7 @@ describe('projected tool input lifecycle', () => {
expect(currentToolPart(harness).messageID).toBe(MESSAGE_ID);
});
- it('falls back to the latest active assistant when the streamed assistant id does not match', () => {
+ it('does not attach a named tool to the previous assistant while its owner loads', () => {
const harness = createHarness();
expect(
@@ -454,13 +464,22 @@ describe('projected tool input lifecycle', () => {
assistantMessageID: 'v2-assistant-1',
name: 'apply_patch',
})
+ ).toBe(false);
+ expect(upsertPart).not.toHaveBeenCalled();
+ expect(harness.messages[0]?.parts).toEqual([]);
+ expect(harness.scheduleActiveMessageSync).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('uses the latest assistant for legacy events without an explicit owner', () => {
+ const harness = createHarness();
+
+ expect(
+ emit(harness, 'session.next.tool.input.started', {
+ assistantMessageID: undefined,
+ name: 'bash',
+ })
).toBe(true);
- expect(currentToolPart(harness)).toMatchObject({
- messageID: MESSAGE_ID,
- tool: 'apply_patch',
- state: { status: 'pending' },
- });
- expect(harness.scheduleActiveMessageSync).not.toHaveBeenCalled();
+ expect(currentToolPart(harness).messageID).toBe(MESSAGE_ID);
});
it('schedules a resync when the owning assistant message is not loaded', () => {
diff --git a/src/webview/hooks/session/session-projected-events.ts b/src/webview/hooks/session/session-projected-events.ts
index 1def2c7d..7c3dcbd6 100644
--- a/src/webview/hooks/session/session-projected-events.ts
+++ b/src/webview/hooks/session/session-projected-events.ts
@@ -107,8 +107,9 @@ export function createProjectedSessionEventHandler(ctx: ProjectedSessionEventCon
const pendingToolInput = new Map();
const runningToolProviders = new Map();
const findProjectedAssistant = (sessionId: string, assistantMessageID?: string) =>
- ctx.findAssistantMessage(sessionId, assistantMessageID) ||
- latestAssistantMessageForSession(ctx.getMessages(), sessionId);
+ assistantMessageID
+ ? ctx.findAssistantMessage(sessionId, assistantMessageID)
+ : latestAssistantMessageForSession(ctx.getMessages(), sessionId);
const applyProjectedPart = (
sessionId: string,
assistantMessageID: string | undefined,
diff --git a/src/webview/hooks/session/session-reasoning-events.test.ts b/src/webview/hooks/session/session-reasoning-events.test.ts
index 0b648e87..97ff8556 100644
--- a/src/webview/hooks/session/session-reasoning-events.test.ts
+++ b/src/webview/hooks/session/session-reasoning-events.test.ts
@@ -127,6 +127,7 @@ describe('session.next.reasoning.started', () => {
id: REASONING_ID,
type: 'reasoning',
text: '',
+ time: { start: 0 },
messageID: MESSAGE_ID,
sessionID: SESSION_ID,
})
@@ -228,6 +229,7 @@ describe('session.next.reasoning.ended', () => {
id: REASONING_ID,
type: 'reasoning',
text: 'the complete reasoning',
+ time: { start: 0, end: expect.any(Number) },
messageID: MESSAGE_ID,
})
);
@@ -250,7 +252,12 @@ describe('session.next.reasoning.ended', () => {
assistantMessageID: MESSAGE_ID,
});
- expect(upsertPart).not.toHaveBeenCalled();
+ expect(upsertPart).toHaveBeenCalledWith(
+ expect.objectContaining({
+ text: 'streamed so far',
+ time: { start: 0, end: expect.any(Number) },
+ })
+ );
});
it('requires a reasoning id', () => {
@@ -301,8 +308,12 @@ describe('reasoning message resolution', () => {
);
});
- it('falls back to the latest message when the named one is not loaded', () => {
- const harness = install({ messages: [entry('assistant-latest')] });
+ it('loads the named message without attaching its reasoning to the previous step', async () => {
+ const messages = [entry('assistant-latest')];
+ const syncSessionMessages = vi.fn().mockImplementation(async () => {
+ messages.push(entry('assistant-missing'));
+ });
+ const harness = install({ messages, syncSessionMessages });
harness.emit('session.next.reasoning.ended', {
sessionID: SESSION_ID,
@@ -311,9 +322,13 @@ describe('reasoning message resolution', () => {
text: 'recovered',
});
- expect(upsertPart).toHaveBeenCalledWith(
- expect.objectContaining({ messageID: 'assistant-latest' })
+ expect(upsertPart).not.toHaveBeenCalled();
+ await vi.waitFor(() =>
+ expect(upsertPart).toHaveBeenCalledWith(
+ expect.objectContaining({ messageID: 'assistant-missing', text: 'recovered' })
+ )
);
+ expect(messages[0]?.parts).toEqual([]);
});
it('syncs messages and retries when no assistant message is loaded yet', async () => {
diff --git a/src/webview/hooks/session/session-reasoning-events.ts b/src/webview/hooks/session/session-reasoning-events.ts
index 95022c88..f19e90b7 100644
--- a/src/webview/hooks/session/session-reasoning-events.ts
+++ b/src/webview/hooks/session/session-reasoning-events.ts
@@ -1,7 +1,8 @@
import { serverEvents } from '../../lib/client';
import { sessionStore } from '../../lib/stores/session-store';
import { uiStore } from '../../lib/stores/ui-store';
-import type { MessageEntry, Part } from '../../types';
+import type { MessageEntry } from '../../types';
+import { isNumber } from '../../../shared/type-utils';
import { getEventString, latestAssistantMessageForSession } from './session-event-utils';
type ReasoningEventContext = {
@@ -16,9 +17,8 @@ type ReasoningEventContext = {
};
export function registerReasoningEventHandlers(ctx: ReasoningEventContext): Array<() => void> {
- // v2 reasoning events carry the owning assistantMessageID. When that message is loaded
- // we attach directly to it; otherwise we fall back to the "latest active assistant"
- // heuristic, preserving the pre-v2 behavior for older servers / not-yet-synced messages.
+ // An explicit owner may not be loaded yet. Fetch it rather than attaching its
+ // reasoning to the previous step while the transcript catches up.
const findReasoningMessage = (sessionId: string, assistantMessageID?: string) => {
if (assistantMessageID) {
const named = ctx
@@ -29,7 +29,7 @@ export function registerReasoningEventHandlers(ctx: ReasoningEventContext): Arra
entry.info.sessionID === sessionId &&
entry.info.role === 'assistant'
);
- if (named) return named;
+ return named ?? null;
}
return latestAssistantMessageForSession(ctx.getMessages(), sessionId);
};
@@ -41,14 +41,14 @@ export function registerReasoningEventHandlers(ctx: ReasoningEventContext): Arra
const message = findReasoningMessage(sessionId, assistantMessageID);
if (!message) return null;
if (!message.parts.some((part) => part.id === reasoningId)) {
- // SAFETY: The surrounding shape or discriminator check establishes the owner type contract used below.
sessionStore.upsertPart({
id: reasoningId,
sessionID: sessionId,
messageID: message.info.id,
type: 'reasoning',
text: '',
- } as Part);
+ time: { start: message.info.time.created },
+ });
}
return message.info.id;
};
@@ -160,15 +160,20 @@ export function registerReasoningEventHandlers(ctx: ReasoningEventContext): Arra
reasoningID,
(messageID) => {
ctx.recordSessionMessageSnapshotMutation(sessionID);
- if (!text) return;
- // SAFETY: The surrounding shape or discriminator check establishes the owner type contract used below.
+ const message = ctx.getMessages().find((entry) => entry.info.id === messageID);
+ const existing = message?.parts.find((part) => part.id === reasoningID);
+ const reasoning = existing?.type === 'reasoning' ? existing : undefined;
sessionStore.upsertPart({
id: reasoningID,
sessionID,
messageID,
type: 'reasoning',
- text,
- } as Part);
+ text: text || reasoning?.text || '',
+ time: {
+ start: reasoning?.time.start ?? message?.info.time.created ?? Date.now(),
+ end: isNumber(p?.timestamp) ? p.timestamp : Date.now(),
+ },
+ });
},
assistantMessageID
);
diff --git a/src/webview/hooks/session/session-selection.ts b/src/webview/hooks/session/session-selection.ts
index dd185121..71256d50 100644
--- a/src/webview/hooks/session/session-selection.ts
+++ b/src/webview/hooks/session/session-selection.ts
@@ -69,8 +69,14 @@ type SessionSelectionDeps = {
startLoading(): void;
stopLoading(): void;
setError(message: string): void;
+ removeUnavailableSession?(sessionId: string): void;
+ importLegacySession?(sessionId: string, directory: string): void;
};
+function isV1Session(session: Session | undefined): boolean {
+ return Boolean(session && /^v?1(?:\.|$)/i.test(session.version.trim()));
+}
+
export async function selectSessionWithDependencies(
deps: SessionSelectionDeps,
generationRef: { next(): number },
@@ -129,12 +135,25 @@ export async function selectSessionWithDependencies(
let loaded: { session: Session; messages: MessageEntry[] };
try {
loaded = await deps.loadSession(id, isCurrentSelection);
- } catch {
+ } catch (error) {
if (!isCurrentSelection()) {
clearMessagesLoadingIfOwned();
return;
}
clearMessagesLoadingIfOwned();
+ if (error instanceof Error && /^404\b.*session not found/i.test(error.message)) {
+ const legacySession = deps.getSession(id);
+ const directory = options?.directory ?? legacySession?.directory;
+ deps.removeUnavailableSession?.(id);
+ if (directory && isV1Session(legacySession)) {
+ deps.importLegacySession?.(id, directory);
+ return;
+ }
+ deps.setError(
+ 'This conversation is unavailable on the connected OpenCode server. For v1 history, run "Varro: Import OpenCode v1 Session into v2".'
+ );
+ return;
+ }
deps.setError('Failed to load messages');
return;
}
diff --git a/src/webview/hooks/session/session-send.ts b/src/webview/hooks/session/session-send.ts
index bd7fa33a..1acf19cf 100644
--- a/src/webview/hooks/session/session-send.ts
+++ b/src/webview/hooks/session/session-send.ts
@@ -1273,6 +1273,7 @@ export async function sendMessageWithDependencies(
if (sendBody.variant === undefined) delete sendBody.variant;
const expectsAssistantReply = !sendBody.noReply && sendBody.delivery !== 'steer';
+ const isSteerDelivery = sendBody.delivery === 'steer';
const optimisticMessage = createOptimisticUserMessage(
sessionId,
messageId,
@@ -1337,9 +1338,10 @@ export async function sendMessageWithDependencies(
if (isForeignQueuedDispatch) return true;
const syncResults = await Promise.allSettled([
deps.syncSession(sessionId),
- deps.syncSessionMessages(sessionId),
+ ...(isSteerDelivery ? [] : [deps.syncSessionMessages(sessionId)]),
deps.recheckSessionStatus(sessionId),
]);
+ if (isSteerDelivery) await retryPostSendMessageSync(deps, sessionId, true);
if (deps.getMessageCount(sessionId) === 0) {
if (optimisticMessage) deps.appendOptimisticMessage?.(optimisticMessage);
await retryPostSendMessageSync(deps, sessionId);
@@ -1498,7 +1500,11 @@ export async function ensureSessionPermissionWithDependencies(
sessionId: string
): Promise {
const session = deps.getSession(sessionId);
- const permission = deps.buildPermissionRules(deps.getPermissionMode(sessionId));
+ const mode = deps.getPermissionMode(sessionId);
+ const permission = deps.buildPermissionRules(mode);
+ // Default-mode resets belong to explicit mode changes. V2 replaces the rules,
+ // so sending an empty set here would erase session-scoped Always approvals.
+ if (mode === 'default' && permission.length === 0) return true;
if (hasPermissionRules(session?.permission, permission)) return true;
try {
@@ -1531,11 +1537,12 @@ async function retryPostSendMessageSync(
syncSessionMessages(sessionId: string): Promise;
logError?(context: string, cause: unknown): void;
},
- sessionId: string
+ sessionId: string,
+ force = false
) {
for (const delayMs of [250, 750]) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
- if (deps.getMessageCount(sessionId) > 0) return;
+ if (!force && deps.getMessageCount(sessionId) > 0) return;
try {
await deps.syncSessionMessages(sessionId);
} catch (err) {
diff --git a/src/webview/hooks/useOpenCode.sendMessage.test.ts b/src/webview/hooks/useOpenCode.sendMessage.test.ts
index f7249697..313d673d 100644
--- a/src/webview/hooks/useOpenCode.sendMessage.test.ts
+++ b/src/webview/hooks/useOpenCode.sendMessage.test.ts
@@ -1,5 +1,6 @@
import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
+import type { PermissionRule } from '../../shared/opencode-types';
import type { onMessage } from '../lib/bridge';
import {
assistantMessage,
@@ -35,6 +36,82 @@ function sessionInWorkspace(id: string) {
}
describe('sendMessage', () => {
+ it('updates permissions in the new workspace session directory before sending', async () => {
+ const { stateModule, hookModule } = await loadModules();
+ stateModule.setState('editorContext', {
+ workspacePath: '/repo-a',
+ workspaceDirectory: '/workspace',
+ workspaceFolders: [
+ { name: 'Repo A', path: '/repo-a' },
+ { name: 'Repo B', path: '/repo-b' },
+ ],
+ activeFile: null,
+ selection: null,
+ diagnostics: [],
+ });
+ stateModule.setPermissionModeForSession(null, 'full');
+ stateModule.setState('providers', [
+ provider('openai', {
+ 'gpt-4o': {
+ id: 'gpt-4o',
+ name: 'GPT-4o',
+ capabilities: { toolcall: true },
+ cost: { input: 0, output: 0 },
+ },
+ }),
+ ]);
+ stateModule.setSelectedModel({ providerID: 'openai', modelID: 'gpt-4o' });
+ const created = { ...session('session-workspace'), directory: '/workspace' };
+ clientMocks.sessionCreate.mockImplementation(
+ async (body?: { permission?: PermissionRule[] }) => ({
+ ...created,
+ // V2 projects both shell aliases back to bash, triggering the pre-send rule update.
+ permission: body?.permission?.map((rule) => ({
+ ...rule,
+ permission: rule.permission === 'shell' ? 'bash' : rule.permission,
+ })),
+ })
+ );
+ clientMocks.sessionUpdate.mockImplementation(async (_id, body, options) => {
+ if (options?.directory !== created.directory) throw new Error('404 Session not found');
+ return { ...created, ...body };
+ });
+ clientMocks.varroSessionUpdatePermissionMode.mockImplementation(async () => {
+ // The host confirms the mode through a snapshot before the update resolves.
+ stateModule.applySessionPermissionModesSnapshot({ [created.id]: 'full' });
+ return created;
+ });
+ clientMocks.sessionGet.mockResolvedValue(created);
+ clientMocks.sessionMessages.mockResolvedValue([]);
+ clientMocks.sessionSendAsync.mockResolvedValue(undefined);
+
+ expect(
+ await hookModule.sendMessage('List workspace projects', {
+ newSessionWorkspace: { scope: 'workspace', directory: '/workspace' },
+ })
+ ).toBe(true);
+ expect(clientMocks.varroSessionUpdatePermissionMode).toHaveBeenCalledWith(created.id, 'full', {
+ directory: '/workspace',
+ preconfigured: true,
+ });
+ expect(stateModule.getPermissionModeForSession(created.id)).toBe('full');
+ expect(clientMocks.sessionUpdate).toHaveBeenCalledWith(
+ created.id,
+ expect.objectContaining({
+ permission: expect.arrayContaining([{ permission: '*', pattern: '*', action: 'allow' }]),
+ }),
+ { directory: '/workspace' }
+ );
+ expect(clientMocks.sessionUpdate.mock.invocationCallOrder[0]).toBeLessThan(
+ clientMocks.sessionSendAsync.mock.invocationCallOrder[0]!
+ );
+ expect(clientMocks.sessionSendAsync).toHaveBeenCalledWith(
+ created.id,
+ expect.objectContaining({ parts: [{ type: 'text', text: 'List workspace projects' }] }),
+ { directory: '/workspace' }
+ );
+ });
+
it('requests bottom follow when an edited replacement is published before send completes', async () => {
const { stateModule, hookModule } = await loadModules();
stateModule.setState('activeSessionId', 'session-1');
diff --git a/src/webview/hooks/useOpenCode.sessionState.test.ts b/src/webview/hooks/useOpenCode.sessionState.test.ts
index 2f0c9879..3197e3b0 100644
--- a/src/webview/hooks/useOpenCode.sessionState.test.ts
+++ b/src/webview/hooks/useOpenCode.sessionState.test.ts
@@ -587,8 +587,8 @@ describe('useOpenCode session state flows', () => {
const slowSession = Promise.resolve({ ...session('session-1'), title: 'Slow session' });
const fastSession = Promise.resolve({ ...session('session-2'), title: 'Fast session' });
- const slowMessages = Promise.resolve([{ info: userMessage('user-1'), parts: [] }]);
- const fastMessages = Promise.resolve([{ info: userMessage('user-2'), parts: [] }]);
+ const slowMessages = Promise.resolve([userEntry('user-1', 'session-1')]);
+ const fastMessages = Promise.resolve([userEntry('user-2', 'session-2')]);
clientMocks.sessionGet.mockImplementation(async (id: string) =>
id === 'session-1' ? slowSession : fastSession
diff --git a/src/webview/lib/assistant-activity.test.ts b/src/webview/lib/assistant-activity.test.ts
index 32f23001..ef4a2519 100644
--- a/src/webview/lib/assistant-activity.test.ts
+++ b/src/webview/lib/assistant-activity.test.ts
@@ -127,6 +127,20 @@ describe('assistant activity summaries', () => {
});
it('keeps actionable and delegated activity outside compact groups', () => {
+ expect(
+ shouldCompactAssistantActivityPart(
+ {
+ ...completedTool('read-rejected', 'read'),
+ state: {
+ status: 'error',
+ input: { path: '/repo/README.md' },
+ error: 'The user declined this tool call',
+ time: { start: 1, end: 2 },
+ },
+ },
+ { keepEditInline: false, keepReasoningInline: false }
+ )
+ ).toBe(false);
expect(isAssistantActivityPart(completedTool('read-1', 'read'))).toBe(true);
expect(isAssistantActivityPart(completedTool('question-1', 'question'))).toBe(false);
expect(isAssistantActivityPart(completedTool('question-2', 'functions.question'))).toBe(false);
diff --git a/src/webview/lib/bridge.test.ts b/src/webview/lib/bridge.test.ts
index 8ad4e39b..f9e0358f 100644
--- a/src/webview/lib/bridge.test.ts
+++ b/src/webview/lib/bridge.test.ts
@@ -400,6 +400,49 @@ describe('bridge', () => {
expect(window.__sendToExtension).not.toHaveBeenCalled();
});
+ it('sends reactive prompt data through a structured-clone transport', async () => {
+ const bridge = await loadBridge();
+ const { createStore } = await import('solid-js/store');
+ const [state] = createStore({
+ model: { providerID: 'openai', modelID: 'gpt-5.6-luna' },
+ parts: [{ type: 'text', text: 'A prompt from reactive session state' }],
+ });
+ expect(() => structuredClone(state.model)).toThrow();
+ const send = vi.fn((message: TestRuntimeValue) => {
+ const cloned = structuredClone(message);
+ const request = fixture<{ payload: { id: number } }>(cloned);
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ data: { type: 'api/response', payload: { id: request.payload.id, data: null } },
+ })
+ );
+ });
+ window.__sendToExtension = send;
+
+ await expect(
+ bridge.apiCall(
+ 'POST',
+ '/session/session-1/prompt_async',
+ {
+ model: state.model,
+ parts: state.parts,
+ },
+ { retries: 0 }
+ )
+ ).resolves.toBeNull();
+ expect(send).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ type: 'api/request',
+ payload: expect.objectContaining({
+ body: {
+ model: { providerID: 'openai', modelID: 'gpt-5.6-luna' },
+ parts: [{ type: 'text', text: 'A prompt from reactive session state' }],
+ },
+ }),
+ })
+ );
+ });
+
it('rejects synchronous extension sender failures without leaving a pending request', async () => {
const bridge = await loadBridge();
window.__sendToExtension = vi.fn(() => {
diff --git a/src/webview/lib/bridge.ts b/src/webview/lib/bridge.ts
index 0a738879..7d385dc7 100644
--- a/src/webview/lib/bridge.ts
+++ b/src/webview/lib/bridge.ts
@@ -1,4 +1,5 @@
import { batch } from 'solid-js';
+import { unwrap } from 'solid-js/store';
import type { ExtensionMessage, WebviewMessage } from '../../shared/protocol';
import { parseExtensionMessage } from '../../shared/extension-message';
import { isString, type UnknownRecord, isObject } from './runtime-values';
@@ -135,7 +136,8 @@ function sendToExtension(msg: WebviewMessage): SendResult {
const send = bridgeWindow.__sendToExtension;
if (!send) return { sent: false };
try {
- send(msg);
+ // Solid store proxies cannot cross the host's structured-clone boundary.
+ send(unwrap(msg));
return { sent: true };
} catch (error) {
return { sent: false, error };
diff --git a/src/webview/lib/skill-reference.ts b/src/webview/lib/skill-reference.ts
index f9c50570..83c6cb60 100644
--- a/src/webview/lib/skill-reference.ts
+++ b/src/webview/lib/skill-reference.ts
@@ -1,25 +1,6 @@
-export function formatSkillReference(name: string): string {
- return `$[${encodeURIComponent(name)}]`;
-}
-
-export function getSkillReferences(text: string): string[] {
- const names = new Set();
- for (const match of text.matchAll(/\$\[([^\]\s]+)\]/g)) {
- try {
- const name = decodeURIComponent(match[1]!);
- if (name && formatSkillReference(name) === match[0]) names.add(name);
- } catch {
- // Malformed pasted markers remain ordinary text.
- }
- }
- return [...names];
-}
-
-export function formatSkillAttachment(name: string): string {
- return `[Attached skill: ${formatSkillReference(name)}]\nUse the skill tool to load ${JSON.stringify(name)} before responding. ${formatSkillReference(name)} in the prompt refers to this skill.`;
-}
-
-export function parseSkillAttachment(text: string): string | null {
- const name = getSkillReferences(text)[0];
- return name && text === formatSkillAttachment(name) ? name : null;
-}
+export {
+ formatSkillReference,
+ getSkillReferences,
+ formatSkillAttachment,
+ parseSkillAttachment,
+} from '../../shared/skill-reference';
diff --git a/src/webview/lib/state-messages.optimistic.test.ts b/src/webview/lib/state-messages.optimistic.test.ts
index dd287b64..67dad462 100644
--- a/src/webview/lib/state-messages.optimistic.test.ts
+++ b/src/webview/lib/state-messages.optimistic.test.ts
@@ -263,6 +263,54 @@ describe('optimistic user message reconciliation', () => {
expect(partIds()).toEqual([['server-part-0', 'server-part-1']]);
});
+ it.each(['snapshot first', 'part first', 'metadata first'])(
+ 'reconciles a combined v2 prompt and attachment reference with %s',
+ (timing) => {
+ const info = userMessage('msg-1');
+ const prompt =
+ 'Check documentation, installation, update notes and embedded into the code instructions and align with the realms when we support OpenCode v1 and v2. Promote v2 by default, but also show an option, that v1 still can be used.';
+ const canonical = textPart('msg-1:content:0', 'msg-1', `${prompt}\nREADME.md`);
+ const image = imagePart('msg-1-part-2', 'msg-1');
+ upsertMessage({
+ info,
+ parts: [
+ textPart('msg-1-part-0', 'msg-1', prompt),
+ textPart('msg-1-part-1', 'msg-1', 'README.md'),
+ image,
+ ],
+ });
+
+ if (timing === 'metadata first') upsertMessageInfo(info);
+ if (timing !== 'snapshot first') upsertPart(canonical);
+ else setMessagesIncremental([{ info, parts: [canonical] }], { preserveExtraParts: true });
+
+ expect(state.messages[0]!.parts.filter((part) => part.type === 'text')).toEqual([canonical]);
+ expect(state.messages[0]!.parts.filter((part) => part.type === 'file')).toHaveLength(1);
+
+ const canonicalImage = { ...image, id: 'msg-1:content:1' };
+ upsertPart(canonicalImage);
+ upsertPart(canonical);
+ setMessagesIncremental([{ info, parts: [canonical, canonicalImage] }], {
+ preserveExtraParts: true,
+ });
+ expect(state.messages[0]!.parts).toEqual([canonical, canonicalImage]);
+ }
+ );
+
+ it('preserves unmatched local context when a snapshot only contains the prompt', () => {
+ const info = userMessage('msg-1');
+ const context = textPart('msg-1-part-1', 'msg-1', 'README.md');
+ const canonical = textPart('msg-1:content:0', 'msg-1', 'Review README.md');
+ upsertMessage({
+ info,
+ parts: [textPart('msg-1-part-0', 'msg-1', 'Review README.md'), context],
+ });
+
+ setMessagesIncremental([{ info, parts: [canonical] }], { preserveExtraParts: true });
+
+ expect(state.messages[0]!.parts).toEqual([canonical, context]);
+ });
+
it('does not preserve an optimistic prompt beside its trimmed canonical part', () => {
const info = userMessage('msg-1');
upsertMessage({
diff --git a/src/webview/lib/state-messages.ts b/src/webview/lib/state-messages.ts
index d57ad496..f211c62c 100644
--- a/src/webview/lib/state-messages.ts
+++ b/src/webview/lib/state-messages.ts
@@ -151,6 +151,19 @@ export function upsertPart(part: Part) {
return;
}
if (isOptimisticUserMessage(msgs[idx]!) && !isLocalOptimisticPartId(nextPart.id, msgId)) {
+ const combinedTextIds = getCombinedOptimisticTextPartIds(msgs[idx]!, [nextPart]);
+ if (combinedTextIds) {
+ const firstId = combinedTextIds.values().next().value;
+ msgs[idx]!.parts = msgs[idx]!.parts.flatMap((currentPart) =>
+ !combinedTextIds.has(currentPart.id)
+ ? [currentPart]
+ : currentPart.id === firstId
+ ? [nextPart]
+ : []
+ );
+ messageIndex.invalidate();
+ return;
+ }
const optimisticPartIndex = findMatchingOptimisticPartIndex(msgs[idx]!, nextPart);
if (optimisticPartIndex !== -1) {
const currentPart = msgs[idx]!.parts[optimisticPartIndex];
@@ -218,6 +231,31 @@ function areMatchingOptimisticParts(left: Part, right: Part) {
return left.url === right.url && left.mime === right.mime && left.filename === right.filename;
}
+function getCombinedOptimisticTextPartIds(entry: MessageEntry, incoming: Part[]) {
+ if (entry.info.role !== 'user') return null;
+ const localTextParts = entry.parts.filter(
+ (part): part is Extract =>
+ part.type === 'text' && isLocalOptimisticPartId(part.id, entry.info.id)
+ );
+ if (localTextParts.length < 2) return null;
+
+ // V2 joins the prompt and text-based attachment references into one text part.
+ const combined = {
+ ...localTextParts[0]!,
+ text: localTextParts.map((part) => part.text).join('\n'),
+ };
+ if (
+ !incoming.some(
+ (part) =>
+ !isLocalOptimisticPartId(part.id, entry.info.id) &&
+ areMatchingOptimisticParts(combined, part)
+ )
+ ) {
+ return null;
+ }
+ return new Set(localTextParts.map((part) => part.id));
+}
+
function isPartRenderVisibilityChanged(previous: Part | undefined, current: Part) {
return isPartPotentiallyVisible(previous) !== isPartPotentiallyVisible(current);
}
@@ -878,10 +916,12 @@ function mergeMessageEntry(
}
const incomingPartIds = new Set(next.parts.map((part) => part.id));
+ const combinedTextIds = getCombinedOptimisticTextPartIds(current, next.parts);
const matchedOptimisticPartIndexes = new Set();
for (const part of current.parts) {
if (isOptimisticImageFilePart(part)) continue;
if (incomingPartIds.has(part.id)) continue;
+ if (combinedTextIds?.has(part.id)) continue;
if (current.info.role === 'user' && isLocalOptimisticPartId(part.id, current.info.id)) {
const matchIndex = next.parts.findIndex(
(incomingPart, index) =>
diff --git a/src/webview/lib/state-session-lifecycle.markers.test.ts b/src/webview/lib/state-session-lifecycle.markers.test.ts
index 82774163..df07334f 100644
--- a/src/webview/lib/state-session-lifecycle.markers.test.ts
+++ b/src/webview/lib/state-session-lifecycle.markers.test.ts
@@ -96,6 +96,33 @@ describe('catalog marker restoration', () => {
expect(state.state.lastSeenSessions.active).toBe(200);
});
+ it('clears known unread markers on the first read when the server clock is ahead', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ const state = await import('./state');
+ state.setSessions([{ ...session('chat', '/repo'), time: { created: 1, updated: 2_000 } }]);
+ state.markSessionResponseCompleted('chat', 3_000);
+
+ state.markSessionSeen('chat');
+
+ expect(state.isSessionUnread('chat', 2_000)).toBe(false);
+ expect(state.isSessionCompletedResponseUnread('chat')).toBe(false);
+ expect(state.state.lastSeenSessions.chat).toBe(3_000);
+
+ state.markSessionResponseCompleted('chat', 3_001);
+ expect(state.isSessionCompletedResponseUnread('chat')).toBe(true);
+ });
+
+ it('does not acknowledge a newer completion when only an older message was seen', async () => {
+ const state = await import('./state');
+ state.setSessions([session('chat', '/repo')]);
+ state.markSessionResponseCompleted('chat', 300);
+
+ state.markSessionSeen('chat', 200);
+
+ expect(state.state.lastSeenSessions.chat).toBe(200);
+ expect(state.isSessionCompletedResponseUnread('chat')).toBe(true);
+ });
+
it('keeps zero timestamps, skipped-plan updates, and selective removal synchronous', async () => {
const state = await import('./state');
state.setSessions([session('first', '/repo'), session('second', '/repo')]);
diff --git a/src/webview/lib/state-session-lifecycle.ts b/src/webview/lib/state-session-lifecycle.ts
index 04fa7428..d84cca6f 100644
--- a/src/webview/lib/state-session-lifecycle.ts
+++ b/src/webview/lib/state-session-lifecycle.ts
@@ -108,7 +108,16 @@ export function consumeInterruptedSessionIds() {
}
export function markSessionSeen(id: string, updatedAt?: number) {
- const timestamp = nextSessionMarkerTimestamp(state.lastSeenSessions[id], updatedAt);
+ // Opening a session acknowledges its known markers even when the server clock is ahead.
+ // Explicit message timestamps acknowledge only that message, not newer activity.
+ const seenAt =
+ updatedAt ??
+ Math.max(
+ Date.now(),
+ state.sessions.find((session) => session.id === id)?.time.updated ?? 0,
+ state.completedSessionResponses[id] ?? 0
+ );
+ const timestamp = nextSessionMarkerTimestamp(state.lastSeenSessions[id], seenAt);
if (timestamp === null) return false;
setState('lastSeenSessions', id, timestamp);
writeMarkerForSession(STORAGE_KEYS.lastSeenSessions, id, timestamp);
diff --git a/src/webview/lib/tool-normalization.ts b/src/webview/lib/tool-normalization.ts
index 58c71962..5cabd921 100644
--- a/src/webview/lib/tool-normalization.ts
+++ b/src/webview/lib/tool-normalization.ts
@@ -40,7 +40,7 @@ const EDIT_TOOL_NAMES = new Set([
'file_rename',
]);
const TODO_TOOL_NAMES = new Set(['update_plan', 'updateplan']);
-const STRUCTURED_TOOL_NAMES = new Set(['task', 'apply_patch', 'webfetch']);
+const STRUCTURED_TOOL_NAMES = new Set(['task', 'apply_patch', 'patch', 'webfetch']);
export function normalizeToolName(toolName: string): string {
const normalized = toolName.trim().toLowerCase();
@@ -75,7 +75,8 @@ export function getToolKind(toolName: string): ToolKind {
}
export function isApplyPatchTool(toolName: string): boolean {
- return normalizeToolName(toolName) === 'apply_patch';
+ const normalized = normalizeToolName(toolName);
+ return normalized === 'apply_patch' || normalized === 'patch';
}
export function isStructuredTool(toolName: string): boolean {
diff --git a/src/webview/perf/assistant-message-content.perf.test.ts b/src/webview/perf/assistant-message-content.perf.test.ts
index 8242e03c..59e37674 100644
--- a/src/webview/perf/assistant-message-content.perf.test.ts
+++ b/src/webview/perf/assistant-message-content.perf.test.ts
@@ -60,7 +60,8 @@ function createReadPart(index: number): ToolPart {
};
}
-describe('AssistantMessageContent perf guards', () => {
+// These guards count observers and rendered parts, not wall-clock render time under suite load.
+describe('AssistantMessageContent perf guards', { timeout: 30_000 }, () => {
beforeEach(() => {
container = document.createElement('div');
container.className = 'interactive-list';
diff --git a/src/webview/perf/message-list-virtualization.perf.test.ts b/src/webview/perf/message-list-virtualization.perf.test.ts
index 3aff86cc..c68004fe 100644
--- a/src/webview/perf/message-list-virtualization.perf.test.ts
+++ b/src/webview/perf/message-list-virtualization.perf.test.ts
@@ -208,7 +208,9 @@ function resizeObserverEntry(
};
}
-describe('MessageList virtualization perf guards', () => {
+// Exact-height bootstrap mounts the full fixture before bounding the window. Allow for DOM
+// setup under parallel suite load; the assertions below enforce row and work-count budgets.
+describe('MessageList virtualization perf guards', { timeout: 60_000 }, () => {
beforeEach(() => {
resetDefaultAppState();
activityGroupingPasses.value = 0;
@@ -394,6 +396,8 @@ describe('MessageList virtualization perf guards', () => {
});
it('keeps the rendered row window bounded while inline editing', async () => {
+ // Use a production-sized history page, still well above the 80-row mount budget.
+ const messageCount = 200;
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
this: HTMLElement
) {
@@ -401,13 +405,13 @@ describe('MessageList virtualization perf guards', () => {
return new DOMRect(0, 0, 500, 120);
}
if (this.classList.contains('interactive-list-track')) {
- return new DOMRect(0, 0, 500, 120_000);
+ return new DOMRect(0, 0, 500, messageCount * 120);
}
return new DOMRect(0, 0, 500, 500);
});
replaceMessages(
- Array.from({ length: 1_000 }, (_, index) => {
+ Array.from({ length: messageCount }, (_, index) => {
const id = `message-${index}`;
const info = index % 2 === 0 ? createUserMessage(id) : createAssistantMessage(id);
return entry(info, [createTextPart(`part-${index}`, id, `Message ${index}`)]);
@@ -425,7 +429,7 @@ describe('MessageList virtualization perf guards', () => {
expect(container?.querySelector('.inline-edit-composer-slot')).toBeTruthy();
expect(container?.querySelectorAll('[data-msg-id]').length).toBeLessThan(80);
expect(container?.querySelector('.virtual-spacer-bottom')).toBeTruthy();
- }, 10_000);
+ });
it('does not rebuild assistant dialog summaries as the virtual window scrolls', async () => {
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
@@ -478,7 +482,7 @@ describe('MessageList virtualization perf guards', () => {
await settlePerfEffects();
expect(assistantDialogSummaryPasses.value).toBe(initialPasses + 1);
- }, 10_000);
+ });
it('coalesces sticky viewport and virtual-range work into one frame pass', async () => {
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (