feat(plugin): add OpenCode Desktop GUI plugins (#55246)

This commit is contained in:
Luke Parker 2026-10-27 10:54:50 +10:00 • committed by GitHub
parent 0b050ac5cd
commit dae4077a96
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1179 changed files with 14710 additions and 9093 deletions

View file

@ -34,7 +34,7 @@ jobs:
- name: Typecheck (TypeScript 7.1)
run: bun run typecheck:tsc
# Every GUI package file (app, desktop, gui-extensions, ui, session-ui) a pull request adds or edits must be free of
# Every GUI package file (app, desktop, gui-plugins, the plugin package's GUI SDK, ui, session-ui) a pull request adds or edits must be free of
# oxlint problems, warn-level rules (anti-slop) included. Other packages are not affected.
- name: Lint changed files
if: github.event_name == 'pull_request'

View file

@ -77,7 +77,7 @@ Most of these rarely reproduce on an idle local machine.
- **Use the harness's signals.** `holdRoute(...).arrived` resolves when the request reaches the route, and `transport.send` resolves after delivery. `setupTimeline(...).waitForPart` resolves once a part renders (`timeline.ts:328`).
- **Decide which side is wrong.** Three of eight investigated e2e flakes were product bugs, each since fixed in the product:
- a stale scroll offset restored when a scroll settles (`src/session/timeline/observe-element-offset.ts`);
- a video double-click that also entered native fullscreen (`packages/gui-extensions/src/file/artifact-view.tsx:617`);
- a video double-click that also entered native fullscreen (`packages/gui-plugins/src/file/artifact-view.tsx:612`);
- shortcuts dropped while a dialog closed.
If a user could hit the interleaving, fix the product and keep the assertion.

View file

@ -1,6 +1,6 @@
---
name: component-tests
description: Use when writing, changing, debugging, or reviewing the Playwright component tests that mount stories. That covers specs in packages/app/component-tests or packages/session-ui/component-tests, `*.fixture.tsx` files there or beside source (such as packages/gui-extensions/src/browser/panel.fixture.tsx), the stories they mount, and the shared harness in packages/stories (playwright/config.ts, playwright/story.ts, vite.config.ts, src/frame.tsx, src/index-plugin.ts, mocks). Also use when a component test is flaky, passed on retry, or fails with "Execution context was destroyed", "Failed to fetch dynamically imported module", or `#story-root` hidden. Covers mount args, source modules imported by URL, Vite dependency pre-bundling and reloads, a cold vs warm story server, mobile drawers, geometry, and checks before pushing.
description: Use when writing, changing, debugging, or reviewing the Playwright component tests that mount stories. That covers specs in packages/app/component-tests or packages/session-ui/component-tests, `*.fixture.tsx` files there or beside source (such as packages/gui-plugins/src/browser/panel.fixture.tsx), the stories they mount, and the shared harness in packages/stories (playwright/config.ts, playwright/story.ts, vite.config.ts, src/frame.tsx, src/index-plugin.ts, mocks). Also use when a component test is flaky, passed on retry, or fails with "Execution context was destroyed", "Failed to fetch dynamically imported module", or `#story-root` hidden. Covers mount args, source modules imported by URL, Vite dependency pre-bundling and reloads, a cold vs warm story server, mobile drawers, geometry, and checks before pushing.
---
# Component tests
@ -15,7 +15,7 @@ Read these first rather than repeating them:
## Stories and `mount`
- **Location.** Put the story next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-extensions`. The story server indexes `*.stories.tsx` files in those four trees (`packages/stories/vite.config.ts`, `src/index-plugin.ts`), reading each file's `export default { title, id }` and its `export const` stories from source.
- **Location.** Put the story next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-plugins`. The story server indexes `*.stories.tsx` files in those four trees (`packages/stories/vite.config.ts`, `src/index-plugin.ts`), reading each file's `export default { title, id }` and its `export const` stories from source.
- **Story ID.** It is the meta `id` if one is set (`packages/session-ui/src/components/session-review.stories.tsx:25`). Otherwise it is the kebab-cased `title`, then `--`, then the kebab-cased export. Check it at `http://127.0.0.1:6006/?id=<id>` on a running story server (`bun --cwd packages/stories dev`). A wrong ID renders nothing (the page throws `No story has the id …`), so `mount` waits out its full 30 s root wait (`story.ts:39`) and then fails.
- **URL args.** `mount(id, { args, globals })` writes them into the URL as `key:value` pairs (`story.ts:20-36`). The frame reads every one: a value becomes a boolean or number when the story's own default for that key is one, `!true`/`!false`/`!null`/`!undefined` keep Storybook's meaning, and anything else stays text.
- Give every arg a typed default. With `args: { split: false }` (`session-review.stories.tsx:129`), `split:false` arrives as a boolean.
@ -29,7 +29,7 @@ Read these first rather than repeating them:
Use these when the contract is not visible in a story, such as construction counts, unmount races or cache state.
- **Fixture file.** Put a `*.fixture.tsx` file in `component-tests/` or beside the source it drives (`packages/gui-extensions/src/browser/panel.fixture.tsx`). It exports a `mountX()` that renders into a host with a `data-testid` (`packages/session-ui/component-tests/basic-tool.fixture.tsx:7-46`). Never end the name in `.spec` or `.test`.
- **Fixture file.** Put a `*.fixture.tsx` file in `component-tests/` or beside the source it drives (`packages/gui-plugins/src/browser/panel.fixture.tsx`). It exports a `mountX()` that renders into a host with a `data-testid` (`packages/session-ui/component-tests/basic-tool.fixture.tsx:7-46`). Never end the name in `.spec` or `.test`.
- **Mount it in three steps.**
1. Mount a light story first, so that the app styles load.
2. Import the fixture and call it inside `page.evaluate`.
@ -40,7 +40,7 @@ Use these when the contract is not visible in a story, such as construction coun
- **Module URLs.** Build each one with `sourceURL(new URL("<relative path with extension>", import.meta.url))` (`story.ts:10`), written as a string literal in the spec (`browser-pane-restore.spec.ts:6-24`). Any other spelling either fails to load or loads a second module instance whose contexts the page never provides; a hand-written `/@fs//...` is the documented second-instance case (`story.ts:6-9`). The literal also matters for pre-bundling (next section).
- **Aliases.** A module imported by URL is the real file. App code that reaches the same module through a `vite.config.ts` alias gets the mock (`browser-pane-restore.spec.ts:95-96`). Decide which of the two the contract needs.
- **Spec imports.** Import source modules into the spec with `import type` only (`browser-pane-restore.spec.ts:2-4`). A value import runs browser code in the Node runner.
- **Async order.** Let the test decide the order through deferreds the fixture exposes (`mountExtensionHost`, `packages/app/component-tests/extension-host.fixture.tsx:135`). Await the outcome they lead to (`extension-host.spec.ts:46-77`), or poll in-page state with `until` (`extension-host.fixture.tsx:124-132`). Do not copy the fixed in-page `setTimeout` waits that other cases in `extension-host.spec.ts` (`:38`, `:88-90`, `:108-119`) use to prove a negative.
- **Async order.** Let the test decide the order through deferreds the fixture exposes (`mountPluginHost`, `packages/app/component-tests/plugin-host.fixture.tsx:151`). Await the outcome they lead to (`plugin-host.spec.ts:38-69`), or poll in-page state with `until` (`plugin-host.fixture.tsx:141-148`). Do not copy the fixed in-page `setTimeout` waits that other cases in `plugin-host.spec.ts` (`:30`, `:80-82`, `:100-111`) use to prove a negative.
## Vite pre-bundling and reloads
@ -102,7 +102,7 @@ From the owning package (`packages/session-ui` or `packages/app`):
- Do not skip on Windows, and do not raise `config.ts` timeouts, retries or the `mount` wait.
- If one test does genuinely expensive work, call `story.setTimeout(...)` in that test, with a comment that names the work.
6. **Confirm CI ran the component legs.** E2E never runs on pushes to dev (`check-test.yml:28`), so no post-merge run catches a regression.
- The `affected` gate filters on `@opencode/app` and `@opencode/stories` (`check-test.yml:60-61`). `ui`, `session-ui` and `gui-extensions` count through app's dependencies. `workflow_dispatch` forces the legs on (`check-test.yml:56-59`).
- The `affected` gate filters on `@opencode/app` and `@opencode/stories` (`check-test.yml:60-61`). `ui`, `session-ui` and `gui-plugins` count through app's dependencies. `workflow_dispatch` forces the legs on (`check-test.yml:56-59`).
- `check-test.yml` is listed in `globalDependencies` (`turbo.json:8`), so editing it marks every package affected.
- The required `e2e (linux)` and `e2e (windows)` checks also pass when no leg was needed (`check-test.yml:329-352`). Look for `e2e (<os>, session-ui-components)` and `e2e (<os>, app-components)`.
- If CI skipped them, report your local cold run in the PR.

View file

@ -132,7 +132,7 @@ opencode debug heap-dump
It discovers the already-running service (never starts or replaces one), calls `POST /api/debug/heap-dump`, waits until the file is complete, and prints its server-local path. Pass `--server <url>` (with `OPENCODE_PASSWORD`) for a server started with `serve`, and `--directory <dir>` to write somewhere other than the server's log directory (the server creates it; a server that predates the option ignores it and the CLI warns). A 404 means the running server predates the endpoint.
For desktop memory, run **Capture heap snapshots** from the desktop command palette (`packages/gui-extensions/src/debug/main.ts`). It writes `~/Downloads/opencode-heap-<time>/` with the desktop's own (local) server, which writes straight into the folder, every app window renderer, and the Electron main process. Heap snapshots only hold GC-managed objects, so it also records Chromium's memory-infra dump (`memory-infra.json`, open in Perfetto) and summarizes it per process and allocator in `memory.json` (MiB: `malloc`, `partition_alloc`, `cc/tile_memory`, `gpu`, `v8`, …), next to each window's DOM size and decoded images and the server's `process.memoryUsage()`. `manifest.json` (PIDs, `app.getAppMetrics()` before and after) is written last. Start with `memory.json` when a process is larger than its heap snapshot. In a dev desktop build you can drive it over CDP (`OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT`, default 9222): press `Control+Shift+P`, type `heap snapshots`, press Enter.
For desktop memory, run **Capture heap snapshots** from the desktop command palette (`packages/gui-plugins/src/debug/main.ts`). It writes `~/Downloads/opencode-heap-<time>/` with the desktop's own (local) server, which writes straight into the folder, every app window renderer, and the Electron main process. Heap snapshots only hold GC-managed objects, so it also records Chromium's memory-infra dump (`memory-infra.json`, open in Perfetto) and summarizes it per process and allocator in `memory.json` (MiB: `malloc`, `partition_alloc`, `cc/tile_memory`, `gpu`, `v8`, …), next to each window's DOM size and decoded images and the server's `process.memoryUsage()`. `manifest.json` (PIDs, `app.getAppMetrics()` before and after) is written last. Start with `memory.json` when a process is larger than its heap snapshot. In a dev desktop build you can drive it over CDP (`OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT`, default 9222): press `Control+Shift+P`, type `heap snapshots`, press Enter.
The Unix `SIGUSR1` listener in `packages/cli/src/heap.ts` shares the same writer (`packages/util/src/heap-snapshot.ts`) and is still useful for a process that is not an HTTP server, such as a TUI client:

View file

@ -1,6 +1,6 @@
---
name: unit-tests
description: Use when writing, reviewing, speeding up, or fixing a flaky `bun test` unit test in any package (core, cli, server, ai, codemode, util, client, sdk, plugin, http-recorder, merman, app src and test-browser, desktop, gui-extensions, ui, session-ui, latex, ...), except OpenTUI renderer tests (see tui-tests). Also use when a test "timed out after 5000ms" on Windows CI, fails only on Windows, when the unit job is slow, when adding cli subprocess or service tests, or when adding a package's test task to turbo.json. Covers controlling time instead of sleeping, per-test timeouts, process and git spawn cost on Windows, Windows-only failures, temp dirs and process state, leaks between files, and reading CI timeouts.
description: Use when writing, reviewing, speeding up, or fixing a flaky `bun test` unit test in any package (core, cli, server, ai, codemode, util, client, sdk, plugin, http-recorder, merman, app src and test-browser, desktop, gui-plugins, ui, session-ui, latex, ...), except OpenTUI renderer tests (see tui-tests). Also use when a test "timed out after 5000ms" on Windows CI, fails only on Windows, when the unit job is slow, when adding cli subprocess or service tests, or when adding a package's test task to turbo.json. Covers controlling time instead of sleeping, per-test timeouts, process and git spawn cost on Windows, Windows-only failures, temp dirs and process state, leaks between files, and reading CI timeouts.
---
# Fast, Reliable Unit Tests
@ -10,7 +10,7 @@ CI runs `bun turbo test --affected --concurrency=3` on 4-vCPU Linux and Windows
Read these first; this skill does not repeat them:
- Root `AGENTS.md`: the Testing and Style Guide sections.
- `packages/app/AGENTS.md` Tests (`packages/desktop` and `packages/gui-extensions` follow it): one owner per contract, and no production seams for tests.
- `packages/app/AGENTS.md` Tests (`packages/desktop` and `packages/gui-plugins` follow it): one owner per contract, and no production seams for tests.
- `packages/ai/AGENTS.md`: cassettes. The `effect` skill: `it.effect` and `it.live`.
Sibling skills: `tui-tests` (OpenTUI renderer tests in tui and cli), `app-e2e-tests` (Playwright in `packages/app/e2e`), `component-tests` (Playwright on stories, `packages/stories`). This skill owns cli subprocess and service tests.
@ -19,7 +19,7 @@ Sibling skills: `tui-tests` (OpenTUI renderer tests in tui and cli), `app-e2e-te
- Bun's default per-test timeout is 5000ms. Check the package's `test` script:
- 30s: ai, cli, desktop, http-recorder, latex, merman, simulation, theme and tui pass `--timeout 30000`; core's `script/test.ts` passes `--timeout=30000`.
- 5s: client, httpapi-codegen and sdk pass `--timeout 5000`; app, codemode, function, gui-extensions, plugin, plugin-browser, script, server, session-ui, ui and util use the default.
- 5s: client, httpapi-codegen and sdk pass `--timeout 5000`; app, codemode, function, gui-plugins, plugin, plugin-browser, script, server, session-ui, ui and util use the default.
- Size Windows risk by counting spawns, not by local wall time.
- npm.test.ts "installs a Git package from an npm ::path: subdirectory at a branch" takes 0.4s locally and hit 5000ms on Windows CI. Each Npm.add Git case makes about 75 git process events: 3 `clone --recurse-submodules`, which run the git-submodule shell script.
- Assume roughly 40ms per Git-for-Windows spawn (estimated from an earlier git.test run on Windows CI: ~24s for 564 spawns). Some core file groups run 5-9x slower on Windows than locally.
@ -40,7 +40,7 @@ Sibling skills: `tui-tests` (OpenTUI renderer tests in tui and cli), `app-e2e-te
- **Product Effect code must stay on the caller's clock**, which is what makes both patterns above possible. Read time through `Clock`, wait with `Effect.sleep` or `Schedule`, and run nested effects with the caller's context.
- A bare `Effect.runPromise` runs on the default real clock. McpStdio does this (`packages/core/src/mcp/stdio.ts:66`, `:82`, `:109`), so `packages/core/test/mcp.test.ts:832` waits the real 2s `CLOSE_GRACE` on every OS.
- Capture `yield* Effect.context()` and use `Effect.runPromiseWith(context)`, as `packages/cli/src/acp/agent.ts:27` does.
- **Code outside Effect** (app, desktop, ui, session-ui): `jest.useFakeTimers()` and `setSystemTime` from `bun:test`, restored in `afterEach` (`packages/desktop/src/main/extension/lifecycle.test.ts:27-32`, `packages/desktop/src/main/storage/drafts.test.ts:15-17`).
- **Code outside Effect** (app, desktop, ui, session-ui): `jest.useFakeTimers()` and `setSystemTime` from `bun:test`, restored in `afterEach` (`packages/desktop/src/main/plugin/lifecycle.test.ts:27-32`, `packages/desktop/src/main/storage/drafts.test.ts:15-17`).
- **Advance fake timers to the next timer** (`jest.advanceTimersToNextTimer()`, `jest.runOnlyPendingTimers()`), not in small fixed steps. The 10ms-step `advance` at `lifecycle.test.ts:37` turns the 1,000-seed fuzz test (`:607`) into about 430k event-loop turns: 2.8-3.8s on Windows, 0.56s on Linux.
## Real-time waits: deadlines, not attempt counts
@ -64,7 +64,7 @@ To avoid adding more:
- Shorten a production duration through an option, not by waiting it out. Precedent: real product options (`Flock.Options` in `packages/util/src/flock.ts:41-47`, `idleTimeout`/`flushInterval` in `packages/client/src/solid/connection.ts`) and client's hidden seam `withEnsureTiming` (`packages/client/src/service-timing.ts:31`, used by `packages/client/test/fixture/service-timing.ts`).
- For a spawned process the value must reach the child, as `timeoutMs` does through the worker payload at `packages/core/test/util/flock.test.ts:50-58`.
- server-process.ts has no override today, so its 15s tests cannot be shortened from the test side.
- app, desktop and gui-extensions forbid such seams (their AGENTS.md Tests sections); core, cli, util, client and tui have no such ban.
- app, desktop and gui-plugins forbid such seams (their AGENTS.md Tests sections); core, cli, util, client and tui have no such ban.
- Retry timing belongs in core under TestClock. `packages/server/test/fetch.test.ts:363-408` spends about 5.8s of server's 16s in real 200ms bind retries (`packages/core/src/plugin/provider/openai.ts:21`). The fixed ports 1455/1457 are the contract there; new server tests cover routing and error mapping only. Elsewhere bind port 0 (`packages/app/src/runtime/server/global-sync/bootstrap.test.ts:81`).
## Do not assert wall-clock speed
@ -105,11 +105,11 @@ To avoid adding more:
- Do not use `mock.module`; it leaks across files.
- It is why app's scripts pass `--isolate`: app unit went from 2.4s to 9.9s locally, and unit plus browser from 5.3s to 12-20s on CI.
- `packages/cli/test/mini-config.test.ts:25` and `packages/core/test/plugin/provider-gitlab.test.ts:74` already leak in non-isolated suites; do not copy them.
- In Effect packages, provide the dependency through a test layer. In app, desktop and gui-extensions, drive the real module and entry point, and inject only through a parameter the product already has.
- In Effect packages, provide the dependency through a test layer. In app, desktop and gui-plugins, drive the real module and entry point, and inject only through a parameter the product already has.
- Never add `--isolate` or bare `--parallel` (which implies `--isolate`) to a test script: ai went from 7.6s to 26.3s with `--parallel=2`.
- `--parallel=N --no-isolate` keeps the shared registry and measured 0.47-0.68x serial wall time at about the same CPU in core. It also exposed load-sensitive tests (browser-idle and integration's `eventually`, both since fixed).
- Adopting it is a runner decision for maintainers once CI passes on both OSes, not a fix for one slow test.
- Runtime imports run in every file that loads the module. `packages/desktop/src/main/storage/store.ts:3` imports `electron` only for `getStore`, so `src/main/extension/storage.test.ts` and `src/main/storage/store.test.ts` download the ~100MB Electron binary on a fresh install. On a first local run, storage.test.ts took 5.3s of file time for 0.1s of test bodies. Use `import type` for types (`packages/desktop/src/main/ipc-transport.test.ts:4`).
- Runtime imports run in every file that loads the module. `packages/desktop/src/main/storage/store.ts:3` imports `electron` only for `getStore`, so `src/main/plugin/storage.test.ts` and `src/main/storage/store.test.ts` download the ~100MB Electron binary on a fresh install. On a first local run, storage.test.ts took 5.3s of file time for 0.1s of test bodies. Use `import type` for types (`packages/desktop/src/main/ipc-transport.test.ts:4`).
## Turbo test tasks

View file

@ -27,7 +27,8 @@
"files": [
"packages/app/**",
"packages/desktop/**",
"packages/gui-extensions/**",
"packages/gui-plugins/**",
"packages/plugin/src/gui/**",
"packages/ui/**",
"packages/session-ui/**"
],
@ -54,7 +55,13 @@
}
},
{
"files": ["packages/app/**", "packages/desktop/**", "packages/gui-extensions/**", "packages/session-ui/**"],
"files": [
"packages/app/**",
"packages/desktop/**",
"packages/gui-plugins/**",
"packages/plugin/src/gui/**",
"packages/session-ui/**"
],
"rules": {
"anti-slop-effect/no-manual-effect-error-tag": "warn",
"anti-slop-effect/no-manual-tag-comparison": "warn",
@ -64,7 +71,7 @@
}
},
{
"files": ["packages/gui-extensions/src/*.ts", "packages/gui-extensions/src/*.tsx"],
"files": ["packages/gui-plugins/src/*.ts", "packages/gui-plugins/src/*.tsx"],
"rules": {
"no-restricted-imports": [
"error",
@ -73,7 +80,7 @@
{
"name": "solid-js",
"importNames": ["createEffect", "createRenderEffect", "createComputed"],
"message": "Extension code runs side effects through the SDK: createKeyed(source, fn, { otherwise }) per provider generation or value, createMemo or a plain function for derived values, createLatest for async data, createVisitState for per-visit state, and the handler for logic a user action causes. An escape hatch needs an oxlint-disable comment with a reason."
"message": "GUI plugin code runs side effects through the SDK: createKeyed(source, fn, { otherwise }) per provider generation or value, createMemo or a plain function for derived values, createLatest for async data, createVisitState for per-visit state, and the handler for logic a user action causes. An escape hatch needs an oxlint-disable comment with a reason."
}
]
}
@ -81,7 +88,7 @@
}
},
{
"files": ["packages/gui-extensions/src/*/**"],
"files": ["packages/gui-plugins/src/*/**"],
"rules": {
"no-restricted-imports": [
"error",
@ -90,21 +97,21 @@
{
"name": "solid-js",
"importNames": ["createEffect", "createRenderEffect", "createComputed"],
"message": "Extension code runs side effects through the SDK: createKeyed(source, fn, { otherwise }) per provider generation or value, createMemo or a plain function for derived values, createLatest for async data, createVisitState for per-visit state, and the handler for logic a user action causes. An escape hatch needs an oxlint-disable comment with a reason."
"message": "GUI plugin code runs side effects through the SDK: createKeyed(source, fn, { otherwise }) per provider generation or value, createMemo or a plain function for derived values, createLatest for async data, createVisitState for per-visit state, and the handler for logic a user action causes. An escape hatch needs an oxlint-disable comment with a reason."
}
],
"patterns": [
{
"regex": "^@opencode/(app|desktop)(/|$)",
"message": "GUI extensions never import the app or desktop packages. Use the SDK."
"message": "GUI plugins never import the app or desktop packages. Use the SDK."
},
{
"regex": "^@/",
"message": "GUI extensions never import app internals. Use the SDK."
"message": "GUI plugins never import app internals. Use the SDK."
},
{
"group": ["../*/*", "!../*/contract", "!../sdk/*"],
"message": "Import another extension only through its contract.ts."
"group": ["../*/*", "!../*/contract"],
"message": "Import another built-in plugin only through its contract.ts."
},
{
"regex": "\\.css$",
@ -116,7 +123,7 @@
}
},
{
"files": ["packages/gui-extensions/src/sdk/**"],
"files": ["packages/plugin/src/gui/**"],
"rules": {
"no-restricted-imports": [
"error",
@ -124,19 +131,15 @@
"patterns": [
{
"regex": "^@opencode/(app|desktop)(/|$)",
"message": "GUI extensions never import the app or desktop packages. Use the SDK."
"message": "The GUI SDK never imports the app or desktop packages; the hosts implement it."
},
{
"regex": "^@opencode/gui-plugins(/|$)",
"message": "The GUI SDK never imports the built-in plugins; they import the SDK."
},
{
"regex": "^@/",
"message": "GUI extensions never import app internals. Use the SDK."
},
{
"group": ["../*/*", "!../*/contract", "!../sdk/*"],
"message": "Import another extension only through its contract.ts."
},
{
"regex": "\\.css$",
"message": "Import CSS with ?inline and contribute it with ctx.add(Style, css)."
"message": "The GUI SDK never imports app internals."
}
]
}

View file

@ -65,7 +65,8 @@
"@ibm/plex": "6.4.1",
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
"@opencode/gui-extensions": "workspace:*",
"@opencode/gui-plugins": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
"@opencode/session-ui": "workspace:*",
"@opencode/ui": "workspace:*",
@ -336,7 +337,8 @@
"@lydell/node-pty": "catalog:",
"@opencode/app": "workspace:*",
"@opencode/client": "workspace:*",
"@opencode/gui-extensions": "workspace:*",
"@opencode/gui-plugins": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
"@opencode/ui": "workspace:*",
"@sentry/solid": "catalog:",
@ -382,8 +384,8 @@
"typescript": "catalog:",
},
},
"packages/gui-extensions": {
"name": "@opencode/gui-extensions",
"packages/gui-plugins": {
"name": "@opencode/gui-plugins",
"version": "2.1.4",
"dependencies": {
"@betteroffice/docx": "0.4.3",
@ -396,6 +398,7 @@
"@effect/platform-node": "catalog:",
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/plugin-browser": "workspace:*",
"@opencode/schema": "workspace:*",
"@opencode/session-ui": "workspace:*",
@ -525,20 +528,29 @@
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@typescript/native": "catalog:",
"electron": "44.9.1",
"solid-js": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-solid": "catalog:",
},
"peerDependencies": {
"@opencode/theme": "workspace:*",
"@opentui/core": "0.7.0",
"@opentui/solid": "0.7.0",
"electron": "*",
"solid-js": ">=1.9.0",
"vite": ">=6",
"vite-plugin-solid": ">=2.11",
},
"optionalPeers": [
"@opencode/theme",
"@opentui/core",
"@opentui/solid",
"electron",
"solid-js",
"vite",
"vite-plugin-solid",
],
},
"packages/plugin-browser": {
@ -2000,7 +2012,7 @@
"@opencode/function": ["@opencode/function@workspace:packages/function"],
"@opencode/gui-extensions": ["@opencode/gui-extensions@workspace:packages/gui-extensions"],
"@opencode/gui-plugins": ["@opencode/gui-plugins@workspace:packages/gui-plugins"],
"@opencode/http-recorder": ["@opencode/http-recorder@workspace:packages/http-recorder"],
@ -5364,7 +5376,11 @@
"@opencode/console-app/wrangler": ["wrangler@4.50.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.0", "@cloudflare/unenv-preset": "2.7.11", "blake3-wasm": "2.1.5", "esbuild": "0.25.4", "miniflare": "4.20251118.1", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20251118.0" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20251118.0" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-+nuZuHZxDdKmAyXOSrHlciGshCoAPiy5dM+t6mEohWm7HpXvTHmWQGUf/na9jjWlWJHCJYOWzkA1P5HBJqrIEA=="],
"@opencode/gui-extensions/vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],
"@opencode/gui-plugins/vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],
"@opencode/plugin/vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],
"@opencode/plugin/vite-plugin-solid": ["vite-plugin-solid@2.11.10", "", { "dependencies": { "@babel/core": "^7.23.3", "@types/babel__core": "^7.20.4", "babel-preset-solid": "^1.8.4", "merge-anything": "^5.1.7", "solid-refresh": "^0.6.3", "vitefu": "^1.0.4" }, "peerDependencies": { "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.*", "solid-js": "^1.7.2", "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-Yr1dQybmtDtDAHkii6hXuc1oVH9CPcS/Zb2jN/P36qqcrkNnVPsMTzQ06jyzFPFjj3U1IYKMVt/9ZqcwGCEbjw=="],
"@opencode/session-ui/vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],

View file

@ -17,7 +17,7 @@
"dev:stats": "bun sst shell --stage=production -- bun run --cwd packages/stats/app dev",
"dev:www": "bun run --cwd services/www dev",
"bench:devex": "bun run --cwd packages/app test:bench:devex",
"lint": "oxlint && ast-grep scan -c script/ast-grep/gui-extensions/sgconfig.yml && bun script/sdk-docs.ts",
"lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && bun script/sdk-docs.ts",
"lint:changed": "bun script/lint-changed.ts",
"lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/util/src packages/core/src packages/server/src packages/protocol/src packages/cli/src",
"lint:effect-simplifications": "ast-grep scan -c script/ast-grep/effect-simplifications/sgconfig.yml --off=unused-suppression packages",

View file

@ -45,23 +45,23 @@ A flash, a blanked area, a dialog that resizes or a reset scroll on first open a
## Fonts
Users choose three fonts in Settings > Appearance. Every surface uses one of these roles. This section is the single source for font rules across `app`, `ui`, `session-ui`, `gui-extensions` and `desktop`.
Users choose three fonts in Settings > Appearance. Every surface uses one of these roles. This section is the single source for font rules across `app`, `ui`, `session-ui`, `gui-plugins` and `desktop`.
| Role | Use for | Use |
| ------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| UI font | Prose, labels, titles, controls | Inherit, or `var(--font-family-sans)`, `var(--v2-font-family-sans)`, `font-sans` |
| Code font | Shell commands, code, paths shown as code, diffs, logs, tool input | `var(--font-family-mono)`, `var(--v2-font-family-code)`, `font-mono`, or a `<code>` / `<pre>` element |
| Terminal font | Terminal output only | `appearance.font("mono")` from the extension SDK |
| Terminal font | Terminal output only | `appearance.font("mono")` from the GUI plugin SDK |
- Never write a literal family (`Inter`, `"IBM Plex Mono"`, `monospace`, `Menlo`, `system-ui`) in production CSS, classes, inline styles, canvas `font` strings or widget options. A literal ignores the user's setting.
- Never add an `@font-face`, font file, or font package outside `packages/app/src/index.css`. That file is the only place the app ships faces: Inter (variable), IBM Plex Mono Text (weights below 600), Bold (600 and up) and Text Italic, and JetBrainsMono Nerd Font Mono Regular and Bold. If a design needs a face that is not shipped, add it there and say why in the PR.
- Show shell commands with the timeline shell metrics: code font, `13px`, weight `440`, `-0.04px` letter spacing. Do not invent another size for the same content.
- Prefer weight tokens (`font-medium`, `var(--font-weight-medium)`) over literal weights. Mono at `600` or more renders IBM Plex Mono Bold, so reserve it for real emphasis.
- Do not read font settings directly. `src/settings/model.tsx` writes them to the CSS variables above, and the extension host passes the terminal font through `appearance.font`.
- Do not read font settings directly. `src/settings/model.tsx` writes them to the CSS variables above, and the plugin host passes the terminal font through `appearance.font`.
## Loading Indicators
This section is the single source for loading indicators across `app`, `ui`, `session-ui`, `gui-extensions` and `desktop`.
This section is the single source for loading indicators across `app`, `ui`, `session-ui`, `gui-plugins` and `desktop`.
- The dot-matrix `Spinner` (`@opencode/ui/spinner`, and `SessionProgressIndicatorV2` and `ActivityRing`, which render it) means the AI is working: a running session, turn, subagent or tool call. Use it only for those states.
- Every other loading state uses `Loader` (`@opencode/ui/loader`): page, pane and file loads, browser reload, search, connecting, authenticating, sending, installing. Use a purpose-built indicator only when the state has one, such as the titlebar update ring.
@ -69,7 +69,7 @@ This section is the single source for loading indicators across `app`, `ui`, `se
## Scrolling
This section is the single source for scroll containers across `app`, `ui`, `session-ui`, `gui-extensions` and `desktop`.
This section is the single source for scroll containers across `app`, `ui`, `session-ui`, `gui-plugins` and `desktop`.
- Scroll with a plain element: `overflow-y-auto` (or `overflow-x-auto`, `overflow-auto`) plus `min-h-0` or a max height. `packages/ui/src/styles/scrollbar.css` gives every native scrollbar the shared thumb. Do not add `ScrollView` to fix how a scrollbar looks.
- Mark each scroll container with `data-scrollable`. Nested-scroll handling (the timeline, Home, `createAutoScroll`) uses it to let the inner container scroll first.

View file

@ -1,32 +1,32 @@
import { expect, sourceURL, story } from "../../stories/playwright/story"
import type { Accessor, ParentProps } from "solid-js"
import type { Command, MenuItem } from "@opencode/gui-extensions/sdk"
import type { Item } from "../src/runtime/extension/host"
import type { Command, MenuItem } from "@opencode/plugin/gui"
import type { Item } from "../src/runtime/plugin/host"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("../../gui-extensions/src/browser/panel.fixture.tsx"),
host: source("../src/runtime/extension/host.tsx"),
panels: source("../src/runtime/extension/panels.tsx"),
closed: source("../src/runtime/extension/closed-tabs.ts"),
fixture: source("../../gui-plugins/src/browser/panel.fixture.tsx"),
host: source("../src/runtime/plugin/host.tsx"),
panels: source("../src/runtime/plugin/panels.tsx"),
closed: source("../src/runtime/plugin/closed-tabs.ts"),
language: source("../src/runtime/i18n/language.tsx"),
browser: source("../../gui-extensions/src/browser/index.ts"),
browserRenderer: source("../../gui-extensions/src/browser/renderer.tsx"),
browserPanel: source("../../gui-extensions/src/browser/panel.tsx"),
file: source("../../gui-extensions/src/file/index.ts"),
fileRenderer: source("../../gui-extensions/src/file/renderer.tsx"),
browser: source("../../gui-plugins/src/browser/index.ts"),
browserRenderer: source("../../gui-plugins/src/browser/renderer.tsx"),
browserPanel: source("../../gui-plugins/src/browser/panel.tsx"),
file: source("../../gui-plugins/src/file/index.ts"),
fileRenderer: source("../../gui-plugins/src/file/renderer.tsx"),
commands: source("../src/shell/commands/command.tsx"),
extensionCommands: source("../src/runtime/extension/commands.tsx"),
sdk: source("../../gui-extensions/src/sdk/index.ts"),
render: source("../src/runtime/extension/render.tsx"),
pluginCommands: source("../src/runtime/plugin/commands.tsx"),
sdk: source("../../plugin/src/gui/index.ts"),
render: source("../src/runtime/plugin/render.tsx"),
settings: source("../src/settings/model.tsx"),
platform: source("../src/runtime/platform/platform.tsx"),
solid: source("./extension-host.fixture.tsx"),
solid: source("./plugin-host.fixture.tsx"),
}
story.beforeEach(async ({ mount, page }) => {
// Any story loads the app styles; the fixture mounts the real side region and extensions beside it.
// Any story loads the app styles; the fixture mounts the real side region and plugins beside it.
await mount("ui-line-comment--editor")
await page.evaluate(async (modules) => {
const [
@ -43,7 +43,7 @@ story.beforeEach(async ({ mount, page }) => {
platform,
solid,
closed,
extensionCommands,
pluginCommands,
] = await Promise.all([
import(modules.fixture),
import(modules.host),
@ -58,7 +58,7 @@ story.beforeEach(async ({ mount, page }) => {
import(modules.platform),
import(modules.solid),
import(modules.closed),
import(modules.extensionCommands),
import(modules.pluginCommands),
// Load the pane before mounting: Vite must not reload the page to optimize its dependencies mid-fixture.
import(modules.browserPanel),
])
@ -66,13 +66,13 @@ story.beforeEach(async ({ mount, page }) => {
const closedTabs = closed.createClosedTabs()
mountBrowserRegion({
LanguageProvider: language.LanguageProvider,
ExtensionHostProvider: host.ExtensionHostProvider,
useExtensionHost: host.useExtensionHost,
PluginHostProvider: host.PluginHostProvider,
usePluginHost: host.usePluginHost,
createRegion: (region: Omit<Parameters<typeof panels.createRegion>[0], "closed" | "open">) =>
panels.createRegion({ ...region, closed: closedTabs, open() {} }),
definitions: [
{ ...browser.default, renderer: () => import(modules.browserRenderer) },
{ ...file.default, renderer: () => import(modules.fileRenderer) },
{ ...browser.default, id: "browser", windowEntry: () => import(modules.browserRenderer) },
{ ...file.default, id: "file", windowEntry: () => import(modules.fileRenderer) },
],
Shell: (props: ParentProps) =>
solid.createComponent(platform.PlatformProvider, {
@ -114,10 +114,15 @@ story.beforeEach(async ({ mount, page }) => {
let inSide = (_event: Event) => false
const owner = solid.getOwner()
queueMicrotask(() => (inSide = solid.runWithOwner(owner, closed.createSideFocus)!))
const extensions = host.useExtensionHost()
const pluginHost = host.usePluginHost()
// What the side strip's + shows beside the browser item, through the host's own formatter.
props.shortcut(() => {
const item = extensions.list(sdk.MenuItem).find((value: MenuItem) => value.menu === "session.panel")
const item = pluginHost
.items(sdk.MenuItem)
.find(
(entry: { plugin: string; value: MenuItem }) =>
entry.plugin === "browser" && entry.value.menu === "session.panel",
)?.value
return item?.menu === "session.panel" && item.keybind ? command.keybind(item.keybind) : ""
})
@ -125,7 +130,7 @@ story.beforeEach(async ({ mount, page }) => {
// As the session's commands: ⌘T and ⌘W inside the side region, unless the focused panel binds the key there.
const sideKey = (event: KeyboardEvent) =>
!!props.side()?.focus(event) &&
!extensionCommands.extensionClaims(extensions.items(sdk.Command), command.matches, event)
!pluginCommands.pluginClaims(pluginHost.items(sdk.Command), command.matches, event)
command.register("fixture-session", () => [
{
@ -181,14 +186,14 @@ story.beforeEach(async ({ mount, page }) => {
onSelect: props.review,
},
])
// The story server aliases the app's command hook to a no-op. Bridge the real extension contributions
// The story server aliases the app's command hook to a no-op. Bridge the real plugin contributions
// to the real dispatcher imported by source URL, so the shortcut runs rather than its alias.
command.register("fixture-extensions", () =>
extensions.items(sdk.Command).map((item: Item<Command>) => {
command.register("fixture-plugins", () =>
pluginHost.items(sdk.Command).map((item: Item<Command>) => {
const scope = item.value.scope
return {
id: `${item.extension}.${item.value.id}`,
id: `${item.plugin}.${item.value.id}`,
title: item.value.title,
keybind: item.value.bind,
disabled: item.value.enabled === false,
@ -648,7 +653,7 @@ story(
await root.getByRole("button", { name: "First inventory", exact: true }).click()
await expect(tabs).toHaveText(["beta.ts", "Preview"])
// The pane's main extension reloads: every binding goes with it, and the strip keeps the tab it will restore.
// The pane's main plugin reloads: every binding goes with it, and the strip keeps the tab it will restore.
await root.getByRole("button", { name: "Pane away", exact: true }).click()
await expect(tabs).toHaveText(["beta.ts", "Preview"])
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")

View file

@ -3,8 +3,8 @@ import { expect, sourceURL, story } from "../../stories/playwright/story"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("../../gui-extensions/src/browser/panel.fixture.tsx"),
embeds: source("../src/runtime/extension/embeds.tsx"),
fixture: source("../../gui-plugins/src/browser/panel.fixture.tsx"),
embeds: source("../src/runtime/plugin/embeds.tsx"),
language: source("../src/runtime/i18n/language.tsx"),
}

View file

@ -1,9 +1,9 @@
import { expect, sourceURL, story } from "../../stories/playwright/story"
const modules = {
fixture: sourceURL(new URL("./extension-host.fixture.tsx", import.meta.url)),
debug: sourceURL(new URL("../../gui-extensions/src/debug/index.ts", import.meta.url)),
renderer: sourceURL(new URL("../../gui-extensions/src/debug/renderer.tsx", import.meta.url)),
fixture: sourceURL(new URL("./plugin-host.fixture.tsx", import.meta.url)),
debug: sourceURL(new URL("../../gui-plugins/src/debug/index.ts", import.meta.url)),
renderer: sourceURL(new URL("../../gui-plugins/src/debug/renderer.tsx", import.meta.url)),
}
story.beforeEach(async ({ mount }) => {
@ -13,17 +13,17 @@ story.beforeEach(async ({ mount }) => {
// Reloads and updates are fresh mounts over the same storage, so a mount seeded with what the last one wrote is one.
story("the debug bar stays open across a remount until its close button hides it", async ({ page }) => {
const result = await page.evaluate(async (modules) => {
const { mountExtensions, until } = await import(modules.fixture)
const { mountPlugins, until } = await import(modules.fixture)
const debug = await import(modules.debug)
const definition = { ...debug.default, renderer: () => import(modules.renderer) }
const definition = { ...debug.default, id: "debug", windowEntry: () => import(modules.renderer) }
const bar = (host: { container: HTMLElement }) => host.container.querySelector("aside")
const close = (host: { container: HTMLElement }) =>
host.container.querySelector<HTMLButtonElement>('button[aria-label="Hide debug bar"]')
const first = mountExtensions({
const first = mountPlugins({
definitions: [definition],
stored: { "extension.debug.bar": { visible: true, motion: false } },
stored: { "plugin.debug.bar": { visible: true, motion: false } },
})
first.release()
@ -33,12 +33,12 @@ story("the debug bar stays open across a remount until its close button hides it
close(first)?.click()
await until(() => bar(first) === null)
await until(() => first.saved()["extension.debug.bar"]?.visible === false)
await until(() => first.saved()["plugin.debug.bar"]?.visible === false)
const saved = first.saved()
first.unmount()
const second = mountExtensions({ definitions: [definition], stored: saved })
const second = mountPlugins({ definitions: [definition], stored: saved })
second.release()
await until(() => second.ready())
@ -46,7 +46,7 @@ story("the debug bar stays open across a remount until its close button hides it
const reopened = bar(second) !== null
second.unmount()
return { opened, saved: saved["extension.debug.bar"], reopened }
return { opened, saved: saved["plugin.debug.bar"], reopened }
}, modules)
expect(result).toEqual({ opened: true, saved: { visible: false, motion: false }, reopened: false })
@ -63,13 +63,13 @@ story("a feature page's Enabled switch turns that feature on after another featu
const first = experiment("switches.first", "First")
const second = experiment("switches.second", "Second")
const { mountExtensions, until } = await import(modules.fixture)
const { mountPlugins, until } = await import(modules.fixture)
const debug = await import(modules.debug)
const definition = { ...debug.default, renderer: () => import(modules.renderer) }
const definition = { ...debug.default, id: "debug", windowEntry: () => import(modules.renderer) }
const host = mountExtensions({
const host = mountPlugins({
definitions: [definition],
stored: { "extension.debug.bar": { visible: true, motion: true } },
stored: { "plugin.debug.bar": { visible: true, motion: true } },
})
host.release()
@ -131,13 +131,13 @@ story("a feature page's preset chips go through the feature model, modes include
})
const shipped = spring().duration
const { mountExtensions, until } = await import(modules.fixture)
const { mountPlugins, until } = await import(modules.fixture)
const debug = await import(modules.debug)
const definition = { ...debug.default, renderer: () => import(modules.renderer) }
const definition = { ...debug.default, id: "debug", windowEntry: () => import(modules.renderer) }
const host = mountExtensions({
const host = mountPlugins({
definitions: [definition],
stored: { "extension.debug.bar": { visible: true, motion: true } },
stored: { "plugin.debug.bar": { visible: true, motion: true } },
})
host.release()

View file

@ -1,83 +0,0 @@
import type { Definition } from "@opencode/gui-extensions/sdk"
import { expect, sourceURL, story } from "../../stories/playwright/story"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("./extension-host.fixture.tsx"),
builtins: source("../../gui-extensions/src/renderer.ts"),
}
story.beforeEach(async ({ mount }) => {
// Any story loads the app; the fixture mounts the real host beside it.
await mount("ui-line-comment--editor")
})
// The built-in renderer composition as a graph: `requires` edges must not form a cycle, and every optional (`uses`)
// edge gets one row that boots the real host with that provider disabled. The first row disables nothing.
story("built-ins: no requires cycle, and each consumer activates without each optional provider", async ({ page }) => {
const result = await page.evaluate(async (modules) => {
const [{ mountExtensions, until }, { builtins }] = await Promise.all([
import(modules.fixture),
import(modules.builtins),
])
// The window this host serves has no OS, so OS-specific built-ins are left out as the app leaves them out.
const composition: readonly Definition[] = builtins
const definitions = composition.filter((definition) => !definition.os)
const ids = (tokens: Definition["provides"]) => Object.values(tokens ?? {}).map((token) => token.id)
const providerOf = (token: string) => definitions.find((definition) => ids(definition.provides).includes(token))?.id
const requires = new Map(
definitions.map((definition) => [
definition.id,
ids(definition.requires).flatMap((token) => providerOf(token) ?? []),
]),
)
const cycles = definitions.flatMap((definition) => {
const walk = (id: string, path: readonly string[]): string[][] =>
path.includes(id)
? id === definition.id
? [[...path, id]]
: []
: (requires.get(id) ?? []).flatMap((next) => walk(next, [...path, id]))
return walk(definition.id, [])
})
// A renderer that uses the Ipc its own main entry provides depends on no other extension.
const edges = definitions.flatMap((consumer) =>
ids(consumer.uses).flatMap((token) => {
const provider = providerOf(token)
return provider && provider !== consumer.id ? [{ consumer: consumer.id, provider, token }] : []
}),
)
const rows = [{ consumer: "*", provider: "", token: "" }, ...edges]
const outcomes = []
for (const row of rows) {
const host = mountExtensions({ definitions, disabled: row.provider ? [row.provider] : [] })
host.release()
await until(() => host.ready())
const consumers = row.consumer === "*" ? definitions.map((definition) => definition.id) : [row.consumer]
outcomes.push({
...row,
results: consumers.map((id) => ({ id, status: host.status(id), failure: host.failure(id)?.error ?? null })),
})
host.unmount()
}
return { cycles, outcomes }
}, modules)
expect(result.cycles).toEqual([])
expect(result.outcomes).toEqual(
result.outcomes.map((outcome) => ({
...outcome,
results: outcome.results.map((item) => ({ id: item.id, status: "active", failure: null })),
})),
)
})

View file

@ -0,0 +1,61 @@
import { expect, sourceURL, story } from "../../stories/playwright/story"
import type { Entry } from "@opencode/plugin/gui/host"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("./plugin-host.fixture.tsx"),
builtins: source("../../gui-plugins/src/renderer.ts"),
}
story.beforeEach(async ({ mount }) => {
// Any story loads the app; the fixture mounts the real host beside it.
await mount("ui-line-comment--editor")
})
// Built-ins read each other's contracts at runtime with `ctx.use`, so each must keep working without any other. Every
// row boots the real host with one built-in disabled; the first row disables nothing.
story("built-ins: each activates without each other built-in", async ({ page }) => {
const outcomes = await page.evaluate(async (modules) => {
const [{ mountPlugins, until }, { builtins }] = await Promise.all([
import(modules.fixture),
import(modules.builtins),
])
// The window this host serves has no OS, so OS-specific built-ins are left out as the app leaves them out.
const composition: readonly Entry[] = builtins
const definitions = composition.filter((definition) => !definition.os)
const rows = ["", ...definitions.map((definition) => definition.id)]
const results = []
for (const disabled of rows) {
const host = mountPlugins({ definitions, disabled: disabled ? [disabled] : [] })
host.release()
await until(() => host.ready())
results.push({
disabled,
results: definitions.flatMap((definition) =>
definition.id === disabled
? []
: [
{
id: definition.id,
status: host.status(definition.id),
failure: host.failure(definition.id)?.error ?? null,
},
],
),
})
host.unmount()
}
return results
}, modules)
expect(outcomes).toEqual(
outcomes.map((outcome) => ({
...outcome,
results: outcome.results.map((item) => ({ id: item.id, status: "active", failure: null })),
})),
)
})

View file

@ -3,20 +3,21 @@ import { DialogProvider } from "@opencode/ui/context/dialog"
import {
Panel,
type Appearance,
type Build,
type Definition,
type App,
type Keybinds,
type Layout,
type Locale,
type MountedSession,
type Router,
type Servers,
type SessionScreen,
type Setup,
type Ipc,
type IpcClient,
type IpcSpec,
type Plugin,
type Storage,
type StoreOptions,
type Workspaces,
} from "@opencode/gui-extensions/sdk"
} from "@opencode/plugin/gui"
import type { BuiltinLayout, BuiltinLocale } from "@opencode/plugin/gui/builtin"
import {
createComponent,
createMemo,
@ -33,22 +34,33 @@ import { render } from "solid-js/web"
import { PlatformProvider, type Platform } from "@/runtime/platform/platform"
import { Persist, persisted } from "@/runtime/persistence/storage"
import { ServerScope } from "@/runtime/server/scope"
import { ExtensionHostProvider, useExtensionHost, type HostApiFactories } from "../src/runtime/extension/host"
import { createHostApis } from "../src/runtime/extension/host-apis"
import { createInstalled } from "../src/runtime/extension/installed"
import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge"
import { createRegion, RegionContent } from "../src/runtime/extension/panels"
import { createClosedTabs } from "../src/runtime/extension/closed-tabs"
import { ExtensionSlot } from "../src/runtime/extension/render"
import { persistedHandle } from "../src/runtime/extension/stores"
import { PluginHostProvider, usePluginHost, type HostApiFactories } from "../src/runtime/plugin/host"
import { createHostApis } from "../src/runtime/plugin/host-apis"
import { createInstalled } from "../src/runtime/plugin/installed"
import { pluginEnabled, type Entry } from "@opencode/plugin/gui/host"
import { createRegion, RegionContent } from "../src/runtime/plugin/panels"
import { createClosedTabs } from "../src/runtime/plugin/closed-tabs"
import { PluginSlot } from "../src/runtime/plugin/render"
import { persistedHandle } from "../src/runtime/plugin/stores"
import { LanguageProvider } from "../src/runtime/i18n/language"
import { GuiExtensionsSettings } from "../src/runtime/extension/settings-page-dev"
import { PluginsSettings } from "../src/runtime/plugin/settings-plugins"
import { SessionPluginPills } from "../src/session/composer/plugin-pills"
export { bindExtension, useExtension, Contract, createKeyed, Panel, Slot, Store } from "@opencode/gui-extensions/sdk"
export {
bindPlugin,
usePlugin,
ComposerPill,
Contract,
createKeyed,
Ipc,
Panel,
Slot,
Store,
} from "@opencode/plugin/gui"
export { Schema }
type ExtensionHost = ReturnType<typeof useExtensionHost>
type PluginHost = ReturnType<typeof usePluginHost>
/** What the app interface hands the real host APIs when it mounts. */
type Interface = Parameters<ReturnType<typeof createHostApis>["attach"]>[0]
@ -61,7 +73,7 @@ type Json = string | number | boolean | null | readonly Json[] | { readonly [key
export { createComponent, createMemo, createSignal, getOwner, onCleanup, runWithOwner }
const layout: Layout = {
const layout: BuiltinLayout = {
narrow: () => false,
ready: () => true,
open() {},
@ -79,9 +91,9 @@ const layout: Layout = {
command() {},
}
const build: Build = { version: "", channel: "dev", platform: "desktop", packaged: false }
const about: App = { name: "opencode", version: "", channel: "dev", platform: "desktop", packaged: false }
const locale: Locale = { locale: () => "en", direction: () => "ltr", setDirection() {} }
const locale: BuiltinLocale = { locale: () => "en", direction: () => "ltr", setDirection() {} }
const appearance: Appearance = { font: () => "monospace" }
@ -94,9 +106,9 @@ const servers: Servers = { list: () => [], get: () => undefined }
const workspaces: Workspaces = { on: () => () => undefined }
/** Every HostApi faked at its boundary, with the given storage. */
function fakeApis(storage: (extension: string) => Storage): HostApiFactories {
function fakeApis(storage: (plugin: string) => Storage): HostApiFactories {
return {
build: () => build,
app: () => about,
locale: () => locale,
appearance: () => appearance,
router: () => router,
@ -120,9 +132,9 @@ function mounted(run: () => void) {
return () => undefined
}
/** Storage that no test of `mountExtensionHost` reads. */
/** Storage that no test of `mountPluginHost` reads. */
const unused = (): Storage => {
throw new Error("The fixture extension reads no storage")
throw new Error("The fixture plugin reads no storage")
}
/** Resolves once `check` holds, checking every frame; rejects after five seconds. */
@ -135,16 +147,16 @@ export async function until(check: () => boolean) {
}
}
/** Mounts the real extension host with one extension whose every renderer load settles when the test says so. */
export function mountExtensionHost() {
const loads: PromiseWithResolvers<{ default: Setup<Definition> }>[] = []
/** Mounts the real plugin host with one plugin whose every renderer load settles when the test says so. */
export function mountPluginHost() {
const loads: PromiseWithResolvers<{ default: Plugin.Setup<Entry> }>[] = []
const [disabled, setDisabled] = createSignal<ReadonlySet<string>>(new Set())
const hosts: ExtensionHost[] = []
const hosts: PluginHost[] = []
const container = document.createElement("div")
document.body.appendChild(container)
function Capture() {
hosts.push(useExtensionHost())
hosts.push(usePluginHost())
return null
}
@ -153,12 +165,12 @@ export function mountExtensionHost() {
() => (
<LanguageProvider locale="en">
<DialogProvider>
<ExtensionHostProvider
definitions={[
<PluginHostProvider
definitions={() => [
{
id: "fixture",
renderer: () => {
const load = Promise.withResolvers<{ default: Setup<Definition> }>()
windowEntry: () => {
const load = Promise.withResolvers<{ default: Plugin.Setup<Entry> }>()
loads.push(load)
return load.promise
@ -170,7 +182,7 @@ export function mountExtensionHost() {
whenMounted={mounted}
>
<Capture />
</ExtensionHostProvider>
</PluginHostProvider>
</DialogProvider>
</LanguageProvider>
),
@ -183,7 +195,7 @@ export function mountExtensionHost() {
container.remove()
},
/** Resolves the nth renderer load (the first by default) with this setup. */
load: (setup: Setup<Definition>, index = 0) => loads[index].resolve({ default: setup }),
load: (setup: Plugin.Setup<Entry>, index = 0) => loads[index].resolve({ default: setup }),
/** Rejects the nth renderer load. */
fail: (index: number, cause: unknown) => loads[index].reject(cause),
/** Renderer loads requested so far. */
@ -202,24 +214,28 @@ export function mountExtensionHost() {
* boundary. Storage is the real persisted store of a desktop window whose reads wait until `release()`; `stored` seeds
* it. Renders the `window.bottom` slot once the startup gate opens.
*/
export function mountExtensions(input: {
definitions: readonly Definition[]
export function mountPlugins(input: {
definitions: readonly Entry[]
disabled?: readonly string[]
bridge?: Parameters<typeof createInstalled>[0]
stored?: Readonly<Record<string, Json>>
/** Shows the production developer settings page for status-label contracts. */
/** Shows the production Settings > Plugins page for status-label contracts. */
settings?: boolean
/** The client of an Ipc while main provides it, as a desktop window's bridge reports it. Omitted: the web. */
ipc?: (token: Ipc) => IpcClient<IpcSpec> | undefined
}) {
const held = Promise.withResolvers<void>()
const saved = { ...input.stored }
const [disabled, setDisabled] = createSignal<ReadonlySet<string>>(new Set(input.disabled ?? []))
const hosts: ExtensionHost[] = []
const [definitions, setDefinitions] = createSignal(input.definitions)
const hosts: PluginHost[] = []
const container = document.createElement("div")
document.body.appendChild(container)
const platform: Platform = {
platform: "desktop",
windowID: "extension-host-fixture",
plugins: input.bridge,
windowID: "plugin-host-fixture",
openExternal: () => undefined,
openDirectoryPickerDialog: async () => null,
restart: async () => undefined,
@ -237,9 +253,9 @@ export function mountExtensions(input: {
}),
}
const storage = (extension: string): Storage => ({
const storage = (plugin: string): Storage => ({
store<S extends Schema.ConstraintCodec<object, unknown>>(key: string, options: StoreOptions<S>) {
const pair = persisted(Persist.global(`extension.${extension}.${key}`), options.schema, options.initial, platform)
const pair = persisted(Persist.global(`plugin.${plugin}.${key}`), options.schema, options.initial, platform)
return persistedHandle({ store: pair[0], set: pair[1], init: pair[3].promise })
},
@ -262,43 +278,48 @@ export function mountExtensions(input: {
if (!state) return undefined
return new Set(
input.definitions.flatMap((definition) => (extensionEnabled(definition, state) ? [] : [definition.id])),
definitions().flatMap((definition) =>
pluginEnabled({ id: definition.id, builtin: false }, state) ? [] : [definition.id],
),
)
})
return (
<ExtensionHostProvider
definitions={input.definitions}
<PluginHostProvider
definitions={definitions}
disabled={disabledState}
apis={fakeApis(storage)}
whenMounted={mounted}
ipc={input.ipc}
>
<Capture />
</ExtensionHostProvider>
</PluginHostProvider>
)
}
function Capture() {
const host = useExtensionHost()
const host = usePluginHost()
hosts.push(host)
return (
<Show when={host.ready()}>
<Show when={input.settings}>
<GuiExtensionsSettings />
<PluginsSettings />
</Show>
<ExtensionSlot at="window.bottom" input={{}} />
<PluginSlot at="window.bottom" input={{}} />
</Show>
)
}
const dispose = render(
() => (
<LanguageProvider locale="en">
<DialogProvider>
<MountedHost />
</DialogProvider>
</LanguageProvider>
<PlatformProvider value={platform}>
<LanguageProvider locale="en">
<DialogProvider>
<MountedHost />
</DialogProvider>
</LanguageProvider>
</PlatformProvider>
),
container,
)
@ -314,6 +335,8 @@ export function mountExtensions(input: {
/** Lets the held storage reads answer. */
release: () => held.resolve(),
disable: (ids: readonly string[]) => setDisabled(new Set(ids)),
/** Replaces the definitions, as plugin GUIs join, reload and leave. */
define: (next: readonly Entry[]) => setDefinitions(next),
reload: (id: string) => hosts[0]?.reload(id),
ready: () => hosts[0]?.ready() ?? false,
status: (id: string) => hosts[0]?.state.status[id],
@ -365,40 +388,40 @@ function standIn(overrides: Partial<Interface>): Interface {
}
/** The real host over the real HostApis of a web window; `mounted`, when given, attaches as the app interface. */
function RealHost(props: ParentProps<{ definitions: readonly Definition[]; captured: Captured; mounted?: Interface }>) {
function RealHost(props: ParentProps<{ definitions: readonly Entry[]; captured: Captured; mounted?: Interface }>) {
const apis = createHostApis()
props.captured.apis = apis
if (props.mounted) onCleanup(apis.attach(props.mounted))
return (
<ExtensionHostProvider
definitions={props.definitions}
<PluginHostProvider
definitions={() => props.definitions}
disabled={() => new Set<string>()}
apis={apis.apis}
whenMounted={apis.whenMounted}
>
{props.children}
</ExtensionHostProvider>
</PluginHostProvider>
)
}
/**
* Mounts the real host and HostApis, and the parts of the session screen that render extension content for the routed
* Mounts the real host and HostApis, and the parts of the session screen that render plugin content for the routed
* session: the side region (`createRegion`, `RegionContent`) with every panel's tabs stored, and the
* `session.panel.end` slot, whose input the screen builds this way. `route(id)` routes a session the way the screen
* does: a new session object each time, delivered through the same reactive inputs, while the one screen object
* `ctx.screen` returns follows the route. Its composer records which session each attachment reached.
*/
export function mountSessionRegion(input: {
definitions: readonly Definition[]
definitions: readonly Entry[]
active: string
/** The routed session's messages, as its server holds them. */
messages?: readonly SessionMessageInfo[]
}) {
const container = document.createElement("div")
document.body.appendChild(container)
const hosts: ExtensionHost[] = []
const hosts: PluginHost[] = []
const captured: Captured = {}
const attached: string[] = []
@ -413,7 +436,7 @@ export function mountSessionRegion(input: {
server: { data: { session: { message: { list: () => input.messages ?? [] } } } },
}
// SAFETY: the region and slot pass the object through; the test's extensions read only `key`, `id` and the
// SAFETY: the region and slot pass the object through; the test's plugins read only `key`, `id` and the
// server's message list.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
return value as unknown as MountedSession
@ -426,17 +449,17 @@ export function mountSessionRegion(input: {
composer: { attach: () => void attached.push(view().id), update() {}, detach() {} },
}
// SAFETY: the test's extension reads only `composer.attach` of the screen.
// SAFETY: the test's plugin reads only `composer.attach` of the screen.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const screen = route as unknown as SessionScreen
const sidebar = { opened: () => false, width: () => 0, transition: () => false, resize() {}, toggle() {} }
function Region() {
const host = useExtensionHost()
const host = usePluginHost()
hosts.push(host)
// Every panel's `main` tab is stored, and `active` selected, as a strip restored after a reload.
const all = () => host.items(Panel).map((item) => `${item.extension}:main`)
const all = () => host.items(Panel).map((item) => `${item.plugin}:main`)
const region = createRegion({
region: "side",
@ -458,7 +481,7 @@ export function mountSessionRegion(input: {
return (
<Show when={host.ready()}>
<ExtensionSlot
<PluginSlot
at="session.panel.end"
input={{
get session() {
@ -519,17 +542,76 @@ export function mountSessionRegion(input: {
}
}
/**
* Mounts the real host and the composer lane's plugin pills for one session, as the composer region renders them
* (right-aligned). The session's directory is `/repo`.
*/
export function mountComposerPills(input: { definitions: readonly Entry[] }) {
const container = document.createElement("div")
container.dataset.testid = "composer-pills"
container.style.position = "relative"
container.style.marginTop = "240px"
document.body.appendChild(container)
const hosts: PluginHost[] = []
const captured: Captured = {}
const value = { key: "fixture\na", id: "a", directory: "/repo", visit: {} }
// SAFETY: the pill renderer passes the session through; the test's plugins read only `directory`.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const session = value as unknown as MountedSession
// SAFETY: as above; the test's plugins never read the screen.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const screen = {} as unknown as SessionScreen
function Pills() {
const host = usePluginHost()
hosts.push(host)
return (
<Show when={host.ready()}>
<SessionPluginPills session={session} screen={screen} alignment={() => "end"} />
</Show>
)
}
const dispose = render(
() => (
<LanguageProvider locale="en">
<PlatformProvider value={web}>
<DialogProvider>
<RealHost definitions={input.definitions} captured={captured}>
<Pills />
</RealHost>
</DialogProvider>
</PlatformProvider>
</LanguageProvider>
),
container,
)
return {
status: (id: string) => hosts[0]?.state.status[id],
failure: (id: string) => hosts[0]?.state.failures[id],
unmount: () => {
dispose()
container.remove()
},
}
}
/**
* Mounts the real host over the real HostApis of a web window, before the app interface mounts. `attach()` mounts a
* stand-in for the interface: its layout records each write and reports a tab it opened as visible, its server is
* the local one, and its mono font is "fixture mono".
*/
export function mountHostApis(input: { definitions: readonly Definition[] }) {
export function mountHostApis(input: { definitions: readonly Entry[] }) {
const container = document.createElement("div")
document.body.appendChild(container)
const writes: string[] = []
const [opened, setOpened] = createSignal<readonly string[]>([])
const hosts: ExtensionHost[] = []
const hosts: PluginHost[] = []
const captured: Captured = {}
const layout = standIn({}).layout
@ -549,7 +631,7 @@ export function mountHostApis(input: { definitions: readonly Definition[] }) {
})
function Capture() {
hosts.push(useExtensionHost())
hosts.push(usePluginHost())
return null
}

View file

@ -1,26 +1,18 @@
import type { Component, Owner } from "solid-js"
import type {
Context,
Contract,
DialogHandle,
Dialogs,
Live,
PanelTab,
SessionRef,
SessionScreen,
} from "@opencode/gui-extensions/sdk"
import type { Bridge, BridgeMessage, EnableState, Installed } from "@opencode/gui-extensions/sdk/bridge"
import type { Context, Contract, DialogHandle, Dialogs, Live, SessionRef, SessionScreen } from "@opencode/plugin/gui"
import type { BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import type { Bridge, BridgeMessage, EnableState, Installed } from "@opencode/plugin/gui/host"
import { expect, sourceURL, story } from "../../stories/playwright/story"
const fixture = sourceURL(new URL("./extension-host.fixture.tsx", import.meta.url))
const fixture = sourceURL(new URL("./plugin-host.fixture.tsx", import.meta.url))
/** What the scoped-registration case keeps from inside its extension. */
/** What the scoped-registration case keeps from inside its plugin. */
type Scope = { owner?: Owner | null; end: () => void; ctx?: Context }
/** The context the session-routing case keeps from inside its extension. */
/** The context the session-routing case keeps from inside its plugin. */
type Kept = { ctx?: Context }
/** What the pre-mount case reads from inside its extension's setup. */
/** What the pre-mount case reads from inside its plugin's setup. */
type Reads = { state?: () => string; font?: () => string; prefs?: { value?: { count: number }; ready(): boolean } }
story.beforeEach(async ({ mount }) => {
@ -28,10 +20,10 @@ story.beforeEach(async ({ mount }) => {
await mount("ui-line-comment--editor")
})
story("an extension that finishes loading after the host unmounts is never set up", async ({ page }) => {
story("a plugin that finishes loading after the host unmounts is never set up", async ({ page }) => {
const setups = await page.evaluate(async (fixture) => {
const { mountExtensionHost } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost } = await import(fixture)
const host = mountPluginHost()
const state = { setups: 0 }
host.unmount()
host.load(() => void state.setups++)
@ -45,8 +37,8 @@ story("an extension that finishes loading after the host unmounts is never set u
story("async work from synchronous setup cannot register after the host unmounts", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensionHost, onCleanup } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost, onCleanup } = await import(fixture)
const host = mountPluginHost()
const started = Promise.withResolvers<void>()
const resume = Promise.withResolvers<void>()
const done = Promise.withResolvers<void>()
@ -78,8 +70,8 @@ story("async work from synchronous setup cannot register after the host unmounts
story("older loads neither set up nor fail over the replacement after reloads", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensionHost } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost } = await import(fixture)
const host = mountPluginHost()
const setups: string[] = []
host.reload()
host.reload()
@ -99,8 +91,8 @@ story("older loads neither set up nor fail over the replacement after reloads",
story("a dialog service kept from before a reload opens and closes nothing under the replacement", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensionHost } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost } = await import(fixture)
const host = mountPluginHost()
const dialogs: Dialogs[] = []
const setup = (ctx: Context) => void dialogs.push(ctx.dialogs)
const text = (value: string) => () => Object.assign(document.createElement("p"), { textContent: value })
@ -128,8 +120,8 @@ story("a dialog service kept from before a reload opens and closes nothing under
story("a dialog handle closes its own dialog, and a dialog closes with the scope that opened it", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensionHost, createKeyed, createSignal } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost, createKeyed, createSignal } = await import(fixture)
const host = mountPluginHost()
const text = (value: string) => () => Object.assign(document.createElement("p"), { textContent: value })
const shown = () =>
@ -172,8 +164,8 @@ story("a dialog handle closes its own dialog, and a dialog closes with the scope
story("a dialog pushed in the same tick as a reload never mounts", async ({ page }) => {
const shown = await page.evaluate(async (fixture) => {
const { mountExtensionHost } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost } = await import(fixture)
const host = mountPluginHost()
const dialogs: Dialogs[] = []
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
host.load((ctx: Context) => void dialogs.push(ctx.dialogs), 0)
@ -219,7 +211,7 @@ story(
definitions: [
{
id: "single",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
const tab = { id: "main", title: "Single" }
kept.ctx = ctx
@ -230,7 +222,7 @@ story(
},
{
id: "grouped",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
const tab = { id: "main", title: "Grouped", group: "group" }
ctx.add(Panel, { id: "main", region: "side", list: () => [tab], render: render("grouped") })
@ -242,7 +234,7 @@ story(
await until(() => mounts.single > 0 && mounts.grouped > 0 && mounts.slot > 0)
// Session A's object, as an extension keeps it, and the screen while it routes A.
// Session A's object, as a plugin keeps it, and the screen while it routes A.
const session = kept.ctx?.sessions.current()
const screen = kept.ctx?.screen.current()
@ -310,7 +302,7 @@ story(
definitions: [
{
id: "fixture",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
// Setup runs before the interface mounts, as every built-in's does.
ctx.layout.open("fixture:main", session)
@ -373,7 +365,7 @@ story(
)
// Selection follows opt-in tier order, not the strip's pinned-first order. Unrelated regular tabs never opt in.
const tiers: readonly { name: string; tabs: readonly PanelTab[]; active?: string; expected: string }[] = [
const tiers: readonly { name: string; tabs: readonly BuiltinPanelTab[]; active?: string; expected: string }[] = [
{
name: "regular tabs, in stored order",
tabs: [
@ -428,7 +420,7 @@ tiers.forEach((row) => {
active: input.row.active ?? "gone:main",
definitions: input.row.tabs.map((tab) => ({
id: tab.id,
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
const item = { ...tab, id: "main" }
ctx.add(Panel, { id: "main", region: "side", list: () => [item], render: () => ctx.id })
@ -450,10 +442,10 @@ tiers.forEach((row) => {
})
})
story("an extension reloaded while disabled starts when it is enabled again", async ({ page }) => {
story("a plugin reloaded while disabled starts when it is enabled again", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensionHost } = await import(fixture)
const host = mountExtensionHost()
const { mountPluginHost } = await import(fixture)
const host = mountPluginHost()
const setups: string[] = []
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
host.load(() => void setups.push("first"), 0)
@ -463,7 +455,7 @@ story("an extension reloaded while disabled starts when it is enabled again", as
host.reload()
const afterReload = host.status()
// A load the reload started finishes while the extension is still disabled.
// A load the reload started finishes while the plugin is still disabled.
if (host.count() > 1) host.load(() => void setups.push("while disabled"), 1)
await wait(20)
host.enable()
@ -483,15 +475,15 @@ story(
"a registration is withdrawn with the scope that made it, and at once when that scope already ended",
async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensions, until, createKeyed, createSignal, getOwner, runWithOwner } = await import(fixture)
const { mountPlugins, until, createKeyed, createSignal, getOwner, runWithOwner } = await import(fixture)
const registry = { kind: "registry" as const, id: "fixture-scoped" }
const scope: Scope = { end: () => {} }
const host = mountExtensions({
const host = mountPlugins({
definitions: [
{
id: "fixture",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
const [on, set] = createSignal(true)
scope.end = () => set(false)
@ -524,14 +516,14 @@ story(
story("a contribution that throws renders nothing and records the error; the others stay", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensions, until, Slot } = await import(fixture)
const { mountPlugins, until, Slot } = await import(fixture)
const text = (value: string) => () => Object.assign(document.createElement("p"), { textContent: value })
const host = mountExtensions({
const host = mountPlugins({
definitions: [
{
id: "fixture",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
ctx.add(Slot, {
at: "window.bottom",
@ -545,7 +537,7 @@ story("a contribution that throws renders nothing and records the error; the oth
},
{
id: "other",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => void ctx.add(Slot, { at: "window.bottom", render: text("other") }),
}),
},
@ -573,103 +565,230 @@ story("a contribution that throws renders nothing and records the error; the oth
})
})
story("an extension that requires a contract starts once it is active and restarts with it", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensions, until, Contract, onCleanup } = await import(fixture)
const Tree: Contract<{ version: number }, "provider.tree"> = Contract.define("provider.tree")
const providerLoad = Promise.withResolvers<void>()
const log: string[] = []
const versions = { value: 0 }
story(
"plugin GUIs join, hot-reload in place, run their returned cleanup and leave, without holding startup",
async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountPlugins, until } = await import(fixture)
const builtinLoad = Promise.withResolvers<void>()
const log: string[] = []
const definitions = [
{
id: "provider",
provides: { tree: Tree },
renderer: async () => {
await providerLoad.promise
// Each setup returns its cleanup, as a server or TUI plugin's setup does.
const entry = (name: string) => async () => ({
default: () => {
log.push(`setup ${name}`)
return { default: (ctx: Context) => void ctx.provide(Tree, { version: ++versions.value }) }
return () => void log.push(`cleanup ${name}`)
},
},
{
id: "consumer",
requires: { tree: Tree },
renderer: async () => ({
default: (ctx: Context & { requires: { tree: { version: number } } }) => {
const version = ctx.requires.tree.version
log.push(`setup ${version}`)
onCleanup(() => void log.push(`cleanup ${version}`))
},
}),
},
]
})
// Hard contracts gate startup: a consumer whose provider is disabled settles the gate without starting.
const gated = mountExtensions({ definitions: [definitions[1], definitions[0]], disabled: ["provider"] })
await until(() => gated.ready())
const blocked = { status: gated.status("consumer"), log: [...log] }
gated.unmount()
const builtin = {
id: "builtin",
windowEntry: async () => {
await builtinLoad.promise
const failed = mountExtensions({
definitions: [
{
...definitions[0],
renderer: async () => {
throw new Error("provider failed")
},
return entry("builtin")()
},
definitions[1],
],
}
const host = mountPlugins({ definitions: [builtin] })
// A plugin that joins before the built-ins settle, and never loads, must not hold the app's first render.
host.define([builtin, { id: "stuck", windowEntry: () => new Promise<never>(() => {}) }])
builtinLoad.resolve()
await until(() => host.ready())
const startup = { ready: host.ready(), stuck: host.status("stuck") }
host.define([builtin, { id: "acme", windowEntry: entry("acme 1") }])
await until(() => host.status("acme") === "active")
// A new revision of the plugin's bundle is a new definition under the same id.
host.define([builtin, { id: "acme", windowEntry: entry("acme 2") }])
await until(() => log.includes("setup acme 2"))
const reloaded = [...log]
host.define([builtin])
await until(() => log.includes("cleanup acme 2"))
const outcome = { startup, reloaded, log: [...log], gone: host.status("acme") ?? "none" }
host.unmount()
return outcome
}, fixture)
expect(result).toEqual({
startup: { ready: true, stuck: "loading" },
reloaded: ["setup builtin", "setup acme 1", "cleanup acme 1", "setup acme 2"],
log: ["setup builtin", "setup acme 1", "cleanup acme 1", "setup acme 2", "cleanup acme 2"],
gone: "none",
})
},
)
await until(() => failed.ready())
const failedProvider = { status: failed.status("consumer"), log: [...log] }
failed.unmount()
story(
"a plugin follows another's contract across load, reload and disable, provides only its own, and a failed one stays failed",
async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountPlugins, until, Contract } = await import(fixture)
const Tree: Contract<{ version: number }, "provider.tree"> = Contract.define("provider.tree")
const providerLoad = Promise.withResolvers<void>()
const versions = { value: 0 }
const thiefLoads = { value: 0 }
const observed = { read: (): Live<{ version: number }> => ({ status: "pending" }) }
const host = mountExtensions({ definitions })
await new Promise((resolve) => setTimeout(resolve, 50))
const waiting = { status: host.status("consumer"), log: [...log] }
providerLoad.resolve()
await until(() => host.status("consumer") === "active")
host.reload("provider")
await until(() => log.length === 3)
host.disable(["provider"])
await until(() => log.length === 4)
const outcome = { blocked, failedProvider, waiting, log, after: host.status("consumer") }
host.unmount()
const host = mountPlugins({
definitions: [
{
id: "consumer",
windowEntry: async () => ({ default: (ctx: Context) => void (observed.read = ctx.use(Tree)) }),
},
{
id: "provider",
windowEntry: async () => {
await providerLoad.promise
return outcome
}, fixture)
return { default: (ctx: Context) => void ctx.provide(Tree, { version: ++versions.value }) }
},
},
// Another plugin cannot provide the provider's contract: its setup fails, and the contract stays the provider's.
{
id: "thief",
windowEntry: async () => {
thiefLoads.value++
expect(result).toEqual({
blocked: { status: "blocked", log: [] },
failedProvider: { status: "blocked", log: [] },
waiting: { status: "loading", log: [] },
log: ["setup 1", "cleanup 1", "setup 2", "cleanup 2"],
after: "blocked",
})
})
return { default: (ctx: Context) => void ctx.provide(Tree, { version: 0 }) }
},
},
],
})
await until(() => host.status("consumer") === "active" && host.status("thief") === "failed")
const loading = observed.read().status
providerLoad.resolve()
await until(() => observed.read().status === "active")
const first = observed.read()
host.reload("provider")
await until(() => {
const live = observed.read()
return live.status === "active" && live.generation === 2
})
const second = observed.read()
host.disable(["provider"])
await until(() => observed.read().status === "inactive")
const outcome = {
loading,
first,
second,
disabled: observed.read(),
thief: host.failure("thief")?.error.includes('provides only its own contracts, not "provider.tree"'),
// Disabling another plugin does not retry the failed one; only Reload or a new revision does.
thiefLoads: thiefLoads.value,
}
host.unmount()
return outcome
}, fixture)
expect(result).toEqual({
loading: "pending",
first: { status: "active", value: { version: 1 }, generation: 1 },
second: { status: "active", value: { version: 2 }, generation: 2 },
disabled: { status: "inactive", reason: "disabled" },
thief: true,
thiefLoads: 1,
})
},
)
story(
"a plugin's own main client waits for main, follows its state, and rejects once main cannot answer",
async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountPlugins, until, Ipc, Schema, createSignal } = await import(fixture)
const Awake = Ipc.define({ id: "acme.awake", methods: { get: { output: Schema.Boolean } } })
const Other = Ipc.define({ id: "other.ipc", methods: {} })
const [available, setAvailable] = createSignal(false)
const [awake, setAwake] = createSignal(false)
const kept: Kept = {}
const client = {
get: async () => awake(),
state: () => ({ awake: awake() }),
on: () => () => {},
}
const host = mountPlugins({
ipc: (token: { readonly id: string }) => (token.id === Awake.id && available() ? client : undefined),
definitions: [{ id: "acme", windowEntry: async () => ({ default: (ctx: Context) => void (kept.ctx = ctx) }) }],
})
await until(() => !!kept.ctx)
const ctx = kept.ctx
if (!ctx) throw new Error("the plugin never set up")
const main = ctx.main(Awake)
const waiting = main.get()
const before = main.state()
setAwake(true)
setAvailable(true)
const answered = await waiting
const state = main.state()
const foreign = (() => {
try {
ctx.main(Other)
return false
} catch (cause) {
return String(cause).includes('calls only its own main entry, not Ipc "other.ipc"')
}
})()
host.disable(["acme"])
const rejected = await main.get().then(
() => false,
(cause: unknown) => String(cause).includes("unavailable"),
)
host.unmount()
return { before, answered, state, foreign, rejected, same: ctx.main(Awake) === main }
}, fixture)
expect(result).toEqual({
before: undefined,
answered: true,
state: { awake: true },
foreign: true,
rejected: true,
same: true,
})
},
)
story("a contract component reads its provider context and preserves reactive props", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { bindExtension, createComponent, createSignal, Contract, mountExtensions, Slot, until, useExtension } =
await import(fixture)
const { bindPlugin, createComponent, createSignal, Contract, mountPlugins, Slot, until, usePlugin } = await import(
fixture
)
const View: Contract<{ View: Component<{ readonly label: string }> }, "provider.view"> =
Contract.define("provider.view")
const observed = { context: "", read: () => "", change: () => {}, mounts: 0 }
const host = mountExtensions({
const host = mountPlugins({
definitions: [
{
id: "provider",
provides: { view: View },
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
ctx.provide(View, {
View: bindExtension((props: { readonly label: string }) => {
observed.context = useExtension().id
View: bindPlugin((props: { readonly label: string }) => {
observed.context = usePlugin().id
observed.read = () => props.label
observed.mounts++
@ -681,19 +800,25 @@ story("a contract component reads its provider context and preserves reactive pr
},
{
id: "consumer",
requires: { view: View },
renderer: async () => ({
default: (ctx: Context & { requires: { view: { View: Component<{ readonly label: string }> } } }) => {
windowEntry: async () => ({
default: (ctx: Context) => {
const view = ctx.use(View)
const [label, setLabel] = createSignal("before")
observed.change = () => setLabel("after")
ctx.add(Slot, {
at: "window.bottom",
render: () =>
createComponent(ctx.requires.view.View, {
get label() {
return label()
},
}),
ctx.add(Slot, () => {
const live = view()
if (live.status !== "active") return undefined
return {
at: "window.bottom",
render: () =>
createComponent(live.value.View, {
get label() {
return label()
},
}),
}
})
},
}),
@ -713,91 +838,59 @@ story("a contract component reads its provider context and preserves reactive pr
expect(result).toEqual({ context: "provider", mounts: 1, before: "before", after: "after" })
})
story("developer settings show a blocked hard dependency instead of loading forever", async ({ page }, info) => {
story("Settings > Plugins shows where each part of a plugin from the config is turned off", async ({ page }, info) => {
await page.evaluate(async (fixture) => {
const { Contract, mountExtensions, until } = await import(fixture)
const Tree = Contract.define("provider.tree")
const { mountPlugins, until } = await import(fixture)
const host = mountExtensions({
settings: true,
disabled: ["provider"],
definitions: [
{ id: "provider", provides: { tree: Tree }, renderer: async () => ({ default: () => {} }) },
{ id: "consumer", requires: { tree: Tree }, renderer: async () => ({ default: () => {} }) },
],
})
const installed: Installed[] = [
{ id: "terminal", builtin: true, enabled: true },
{ id: "acme", builtin: false, enabled: true, server: true, tui: true },
// A package with only a GUI part has no other part to tag.
{ id: "notes", builtin: false, enabled: false, server: false, tui: false },
// A plugin whose `os` leaves out this system keeps a row that says so, and never loads.
{ id: "windows-only", builtin: false, enabled: true, server: true, unsupported: true },
]
await until(() => !!host.container.textContent?.includes("consumer"))
}, fixture)
const settings = page.getByRole("region", { name: "Extensions", exact: true })
await settings.screenshot({ path: info.outputPath("requires-status.png") })
await expect(settings.getByText("Blocked", { exact: true })).toBeVisible()
await expect(settings.getByText("Loading", { exact: true })).toHaveCount(0)
})
story("blocked chains expose their own reason and recover regardless of definition order", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { Contract, mountExtensions, until } = await import(fixture)
const Root: Contract<number, "root.value"> = Contract.define("root.value")
const Branch: Contract<number, "branch.value"> = Contract.define("branch.value")
const observed = { read: (): Live<number> => ({ status: "pending" }), starts: 0 }
const host = mountExtensions({
disabled: ["root"],
definitions: [
{
id: "leaf",
requires: { branch: Branch },
renderer: async () => ({
default: () => {
observed.starts++
},
}),
},
{
id: "observer",
uses: { branch: Branch },
renderer: async () => ({
default: (ctx: Context & { uses: { branch: () => Live<number> } }) => {
observed.read = ctx.uses.branch
},
}),
},
{
id: "branch",
requires: { root: Root },
provides: { branch: Branch },
renderer: async () => ({ default: (ctx: Context) => void ctx.provide(Branch, 2) }),
},
{
id: "root",
provides: { root: Root },
renderer: async () => ({ default: (ctx: Context) => void ctx.provide(Root, 1) }),
},
],
})
await until(() => host.ready())
const blocked = {
branch: host.status("branch"),
leaf: host.status("leaf"),
live: observed.read(),
starts: observed.starts,
const bridge: Bridge = {
packaged: false,
call: async () => undefined,
subscribe: async () => ({ available: false }),
on: () => () => {},
embed() {},
capture: async () => undefined,
runMenubarItem() {},
configure() {},
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
initial: Promise.resolve(installed),
list: async () => installed,
enable: async () => {},
disable: async () => {},
reload: async () => {},
},
}
host.disable([])
await until(() => host.status("leaf") === "active")
const recovered = { live: observed.read(), starts: observed.starts }
host.unmount()
const host = mountPlugins({
settings: true,
bridge,
definitions: installed.flatMap((item) =>
item.unsupported ? [] : [{ id: item.id, windowEntry: async () => ({ default: () => {} }) }],
),
})
return { blocked, recovered }
await until(() => !!host.container.textContent?.includes("cli.json"))
}, fixture)
expect(result).toEqual({
blocked: { branch: "blocked", leaf: "blocked", live: { status: "inactive", reason: "blocked" }, starts: 0 },
recovered: { live: { status: "active", value: 2, generation: 1 }, starts: 1 },
})
const settings = page.getByRole("region", { name: "Plugins", exact: true })
await settings.screenshot({ path: info.outputPath("plugin-parts.png") })
// Only plugins from the config tag their other parts, and one note says how to turn those off.
await expect(settings.getByText("Server", { exact: true })).toHaveCount(1)
await expect(settings.getByText("TUI", { exact: true })).toHaveCount(1)
await expect(settings.getByText(/Switches turn off only a plugin's desktop UI/)).toHaveCount(1)
await expect(settings.getByText("Not available on this system.", { exact: true })).toBeVisible()
// A built-in always runs, so it has no switch; the switches carry on and off without a status label.
await expect(settings.getByRole("switch")).toHaveCount(2)
await expect(settings.getByRole("switch", { name: "terminal" })).toHaveCount(0)
await expect(settings.getByText("Active", { exact: true })).toHaveCount(0)
})
const invalidSetups = ["promise", "thenable"]
@ -806,17 +899,17 @@ invalidSetups.forEach((kind) => {
story(`window setup rejects a returned ${kind}`, async ({ page }) => {
const result = await page.evaluate(
async (input) => {
const { mountExtensions, until } = await import(input.fixture)
const { mountPlugins, until } = await import(input.fixture)
const resume = Promise.withResolvers<void>()
const done = Promise.withResolvers<void>()
const registry = { kind: "registry" as const, id: "invalid-setup" }
const observed = { aborted: false }
const host = mountExtensions({
const host = mountPlugins({
definitions: [
{
id: "invalid",
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
ctx.add(registry, "before")
@ -866,17 +959,17 @@ invalidSetups.forEach((kind) => {
story("declared global stores load before setup, so setup reads the stored value", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { mountExtensions, until, Schema, Store } = await import(fixture)
const { mountPlugins, until, Schema, Store } = await import(fixture)
const Prefs = Schema.Struct({ open: Schema.Boolean })
const seen: unknown[] = []
const host = mountExtensions({
stored: { "extension.fixture.prefs": { open: true } },
const host = mountPlugins({
stored: { "plugin.fixture.prefs": { open: true } },
definitions: [
{
id: "fixture",
stores: { prefs: Store.global(Prefs, { open: false }) },
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context & { stores: { prefs: { value: { open: boolean } } } }) =>
void seen.push(ctx.stores.prefs.value.open),
}),
@ -899,9 +992,8 @@ story("declared global stores load before setup, so setup reads the stored value
story("startup enable state does not wait for the manager, and live updates beat older replies", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { Contract, mountExtensions, until } = await import(fixture)
const { Contract, mountPlugins, until } = await import(fixture)
const Provider: Contract<number, "disabled.value"> = Contract.define("disabled.value")
const Dependent: Contract<number, "dependent.value"> = Contract.define("dependent.value")
const observed = { read: (): Live<number> => ({ status: "pending" }) }
const initial = Promise.withResolvers<readonly EnableState[]>()
const reply = Promise.withResolvers<readonly Installed[]>()
@ -909,13 +1001,7 @@ story("startup enable state does not wait for the manager, and live updates beat
const setups: string[] = []
const list = (disabled: readonly string[]): Installed[] =>
["dependent", "enabled", "disabled"].map((id) => ({
id,
name: id,
version: "1",
builtin: true,
enabled: !disabled.includes(id),
}))
["enabled", "disabled"].map((id) => ({ id, builtin: false, enabled: !disabled.includes(id) }))
const bridge: Bridge = {
packaged: false,
@ -930,49 +1016,32 @@ story("startup enable state does not wait for the manager, and live updates beat
capture: async () => undefined,
runMenubarItem() {},
configure() {},
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
initial: initial.promise,
list: () => reply.promise,
enable: async () => {},
disable: async () => {},
reload: async () => {},
install: async () => {},
remove: async () => {},
source: async () => "",
asset: () => "",
},
}
const host = mountExtensions({
const host = mountPlugins({
bridge,
// The consumer comes first; the provider's old-id setting arrives asynchronously from the preload.
// The consumer comes first; the provider's setting arrives asynchronously from the preload.
definitions: [
{
id: "dependent",
requires: { provider: Provider },
provides: { value: Dependent },
renderer: async () => ({
default: (ctx: Context) => {
setups.push("dependent")
ctx.provide(Dependent, 2)
},
}),
},
{
id: "enabled",
uses: { value: Dependent },
renderer: async () => ({
default: (ctx: Context & { uses: { value: () => Live<number> } }) => {
windowEntry: async () => ({
default: (ctx: Context) => {
setups.push("enabled")
observed.read = ctx.uses.value
observed.read = ctx.use(Provider)
},
}),
},
{
id: "disabled",
legacy: ["previous"],
provides: { value: Provider },
renderer: async () => ({
windowEntry: async () => ({
default: (ctx: Context) => {
setups.push("disabled")
ctx.provide(Provider, 1)
@ -984,26 +1053,27 @@ story("startup enable state does not wait for the manager, and live updates beat
await new Promise((resolve) => setTimeout(resolve, 50))
const before = [...setups]
initial.resolve([{ id: "previous", enabled: false }])
initial.resolve([{ id: "disabled", enabled: false }])
await until(() => host.ready())
const started = {
setups: [...setups],
status: host.status("disabled"),
dependent: host.status("dependent"),
live: observed.read(),
}
const unknown: { ready: boolean; setups: string[]; status?: string }[] = []
// A failed startup reply must not temporarily activate the disabled extension while list() waits.
// A failed startup reply must not temporarily activate the disabled plugin while list() waits.
for (const failure of ["unknown", "rejected"]) {
const initial = failure === "unknown" ? Promise.resolve(undefined) : Promise.reject(new Error("snapshot failed"))
const reply = Promise.withResolvers<readonly Installed[]>()
const failed = mountExtensions({
const failed = mountPlugins({
bridge: { ...bridge, manager: { ...bridge.manager, initial, list: () => reply.promise } },
definitions: [{ id: "disabled", renderer: async () => ({ default: () => void setups.push("wrongly enabled") }) }],
definitions: [
{ id: "disabled", windowEntry: async () => ({ default: () => void setups.push("wrongly enabled") }) },
],
})
await new Promise((resolve) => setTimeout(resolve, 50))
@ -1015,19 +1085,14 @@ story("startup enable state does not wait for the manager, and live updates beat
failed.unmount()
}
listeners.forEach((listener) => listener({ type: "extensions", list: list(["enabled"]) }))
await until(
() =>
host.status("disabled") === "active" &&
host.status("enabled") === "disabled" &&
host.status("dependent") === "active",
)
listeners.forEach((listener) => listener({ type: "installed", list: list(["enabled"]) }))
await until(() => host.status("disabled") === "active" && host.status("enabled") === "disabled")
reply.resolve(list(["disabled"]))
await new Promise((resolve) => setTimeout(resolve, 50))
const updated = {
setups: [...setups],
status: [host.status("enabled"), host.status("disabled"), host.status("dependent")],
status: [host.status("enabled"), host.status("disabled")],
}
host.unmount()
@ -1040,14 +1105,101 @@ story("startup enable state does not wait for the manager, and live updates beat
started: {
setups: ["enabled"],
status: "disabled",
dependent: "blocked",
live: { status: "inactive", reason: "blocked" },
live: { status: "inactive", reason: "disabled" },
},
unknown: [
{ ready: false, setups: ["enabled"], status: "disabled" },
{ ready: false, setups: ["enabled"], status: "disabled" },
],
updated: { setups: ["enabled", "disabled", "dependent"], status: ["disabled", "active", "active"] },
updated: { setups: ["enabled", "disabled"], status: ["disabled", "active"] },
listeners: 0,
})
})
story("composer pills show per session, open their rows, and fail only their own plugin", async ({ page }) => {
const statuses = await page.evaluate(async (fixture) => {
const { mountComposerPills, until, ComposerPill } = await import(fixture)
const host = mountComposerPills({
definitions: [
{
id: "acme",
windowEntry: async () => ({
default: (ctx: Context) =>
void ctx.add(ComposerPill, {
id: "pulls",
show: (input: { readonly session: { readonly directory: string } }) => ({
icon: "github",
label: "2 pull requests",
tone: "danger",
title: "Pull requests",
rows: [
{
id: "12",
label: "#12 Fix the tree",
icon: "circle-x",
tone: "danger",
detail: input.session.directory,
run: () => void (document.body.dataset.picked = "12"),
},
{ id: "13", label: "#13 Draft", icon: "branch" },
],
}),
}),
}),
},
// A pill with nothing to show for this session renders nothing.
{
id: "quiet",
windowEntry: async () => ({
default: (ctx: Context) => void ctx.add(ComposerPill, { id: "none", show: () => undefined }),
}),
},
{
id: "broken",
windowEntry: async () => ({
default: (ctx: Context) =>
void ctx.add(ComposerPill, {
id: "boom",
show: () => {
throw new Error("pill failed")
},
}),
}),
},
],
})
await until(() => !!host.failure("broken") && host.status("acme") === "active")
return {
acme: host.status("acme"),
quiet: host.status("quiet"),
broken: host.failure("broken"),
}
}, fixture)
expect(statuses).toEqual({
acme: "active",
quiet: "active",
broken: { phase: "render", error: expect.stringContaining("pill failed") },
})
const pills = page.getByTestId("composer-pills").locator('[data-slot="session-plugin-pill"]')
await expect(pills).toHaveCount(1)
await expect(pills).toHaveText("2 pull requests")
await expect(pills).toHaveAttribute("aria-label", "Pull requests")
await expect(pills.locator("svg").first()).toHaveClass(/text-v2-state-fg-danger/)
await pills.click()
const menu = page.locator('[data-slot="session-plugin-pill-menu"]')
await expect(menu.getByText("Pull requests")).toBeVisible()
const rows = menu.locator('[data-slot="session-plugin-pill-row"]')
await expect(rows).toHaveCount(2)
await expect(rows.nth(0)).toContainText("/repo")
// A row without `run` only shows.
await expect(rows.nth(1)).toHaveAttribute("data-disabled", "")
await rows.nth(0).click()
await expect(page.locator("body")).toHaveAttribute("data-picked", "12")
})

View file

@ -5,9 +5,9 @@ import { expect, sourceURL, story } from "../../stories/playwright/story"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("./extension-host.fixture.tsx"),
definition: source("../../gui-extensions/src/sources/index.ts"),
renderer: source("../../gui-extensions/src/sources/renderer.tsx"),
fixture: source("./plugin-host.fixture.tsx"),
definition: source("../../gui-plugins/src/sources/index.ts"),
renderer: source("../../gui-plugins/src/sources/renderer.tsx"),
tuning: source("../../ui/src/motion-tuning.ts"),
}
@ -72,7 +72,7 @@ story("turning the Sources experiment off closes its open panel and loads no mor
const host: { container: HTMLElement; unmount: () => void } = mountSessionRegion({
active: "sources:main",
messages: JSON.parse(input.messages),
definitions: [{ ...definition, renderer: async () => ({ default: renderer }) }],
definitions: [{ ...definition, id: "sources", windowEntry: async () => ({ default: renderer }) }],
})
const panel = () => host.container.querySelector('[data-slot="session-sources-panel"]')

View file

@ -1,7 +1,7 @@
import type { Page } from "@playwright/test"
import { expect, sourceURL, story } from "../../stories/playwright/story"
const fixture = sourceURL(new URL("../../gui-extensions/src/terminal/terminal.fixture.tsx", import.meta.url))
const fixture = sourceURL(new URL("../../gui-plugins/src/terminal/terminal.fixture.tsx", import.meta.url))
const mountTerminal = async (page: Page, autoFocus: boolean) => {
await page.evaluate(

View file

@ -1,5 +1,5 @@
import { Terminal } from "ghostty-web"
import { SerializeAddon } from "../../../../gui-extensions/src/terminal/serialize"
import { SerializeAddon } from "../../../../gui-plugins/src/terminal/serialize"
export type TerminalProbe = {
term?: Terminal
@ -39,7 +39,8 @@ Terminal.prototype.open = function (element) {
open.call(this, element)
// Ghostty does not expose render events. This benchmark-only wrapper observes its
// actual renderer; it does not alter scheduling, parsing, or drawing.
const renderer = (this as unknown as { renderer: { render: (...args: unknown[]) => void } }).renderer
// SAFETY: ghostty-web keeps its renderer on this undeclared field; the probe only wraps its render method.
const renderer = (this as Terminal & { renderer: { render: (...args: unknown[]) => void } }).renderer
const render = renderer.render
let hidden = false
renderer.render = function (...args) {
@ -68,7 +69,7 @@ const write = Terminal.prototype.write
Terminal.prototype.write = function (data, done) {
probe.writes++
probe.pending++
probe.bytes += typeof data === "string" ? new TextEncoder().encode(data).byteLength : data.byteLength
probe.bytes += data instanceof Uint8Array ? data.byteLength : new TextEncoder().encode(data).byteLength
return write.call(this, data, () => {
probe.pending--

View file

@ -5,7 +5,7 @@ import { openWithDirection } from "../utils/direction"
for (const scheme of ["light", "dark"] as const) {
for (const direction of ["ltr", "rtl"] as const) {
test(`mobile extensions reuse the session drawer in ${scheme} ${direction}`, async ({ page }, testInfo) => {
test(`mobile plugins reuse the session drawer in ${scheme} ${direction}`, async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockStressTimeline(page)
await page.addInitScript((scheme) => {
@ -37,15 +37,15 @@ for (const scheme of ["light", "dark"] as const) {
]) {
const trigger = details.getByRole("button", { name, exact: true })
await trigger.click()
const extension = page.getByRole("dialog", { name, exact: true })
await expect(extension.getByText(empty, { exact: true })).toBeVisible()
await expect(extension).toHaveAttribute("data-drawer-probe", "single")
const plugin = page.getByRole("dialog", { name, exact: true })
await expect(plugin.getByText(empty, { exact: true })).toBeVisible()
await expect(plugin).toHaveAttribute("data-drawer-probe", "single")
await expect(page.getByRole("dialog")).toHaveCount(1)
await expect(page.locator('[data-slot="mobile-drawer-overlay"]')).toHaveCount(1)
await expect(extension.getByRole("button", { name: "Close", exact: true })).toHaveCount(0)
await expect(extension.locator(".session-service-flyout")).toHaveCount(0)
await expect(extension).toBeInViewport({ ratio: 1 })
await extension.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(plugin.getByRole("button", { name: "Close", exact: true })).toHaveCount(0)
await expect(plugin.locator(".session-service-flyout")).toHaveCount(0)
await expect(plugin).toBeInViewport({ ratio: 1 })
await plugin.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(details.getByRole("button", { name: "MCP", exact: true })).toBeVisible()
await expect(trigger).toBeFocused()
}
@ -54,8 +54,8 @@ for (const scheme of ["light", "dark"] as const) {
await expect(
page.getByRole("dialog", { name: "Skills", exact: true }).getByText("No skills configured", { exact: true }),
).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("extensions.png") })
await testInfo.attach("extensions", { path: testInfo.outputPath("extensions.png"), contentType: "image/png" })
await page.screenshot({ path: testInfo.outputPath("plugins.png") })
await testInfo.attach("plugins", { path: testInfo.outputPath("plugins.png"), contentType: "image/png" })
await page.keyboard.press("Escape")
await expect(page.getByRole("dialog")).toHaveCount(0)
await expect(more).toBeFocused()
@ -70,7 +70,7 @@ for (const scheme of ["light", "dark"] as const) {
}
}
test("mobile extension drawers keep configured lists, retry, refresh, and MCP status working", async ({ page }) => {
test("mobile plugin drawers keep configured lists, retry, refresh, and MCP status working", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockStressTimeline(page)
const state = { fail: true, extra: false, enabled: true }
@ -175,9 +175,9 @@ test("mobile extension drawers keep configured lists, retry, refresh, and MCP st
["LSP", "drawer-lsp"],
]) {
await details.getByRole("button", { name, exact: true }).click()
const extension = page.getByRole("dialog", { name, exact: true })
await expect(extension.getByText(item, { exact: true })).toBeVisible()
await extension.getByRole("button", { name: "Navigate back", exact: true }).click()
const plugin = page.getByRole("dialog", { name, exact: true })
await expect(plugin.getByText(item, { exact: true })).toBeVisible()
await plugin.getByRole("button", { name: "Navigate back", exact: true }).click()
}
await details.getByRole("button", { name: "MCP", exact: true }).click()

View file

@ -205,9 +205,7 @@ test("mobile changes summarize expanded diffs, stage comments, wrap by setting,
const wrapControl = settings.locator('[data-action="settings-mobile-diff-wrap"] [data-slot="switch-control"]')
const storedWrap = () =>
page.evaluate(
() => JSON.parse(localStorage.getItem("opencode.global.dat:extension.review.mobileDiff") ?? "{}").wrap,
)
page.evaluate(() => JSON.parse(localStorage.getItem("opencode.global.dat:plugin.review.mobileDiff") ?? "{}").wrap)
await expect(wrap).toBeChecked()
await wrapControl.click()

View file

@ -316,7 +316,7 @@ for (const listed of [false, true]) {
}
test("context closes the side region only when its button opened it", async ({ page }) => {
// A /btw tab saved before extensions must not linger as a hidden tab that keeps the region open.
// A /btw tab saved before plugins must not linger as a hidden tab that keeps the region open.
await openSession(page, {
name: "ReviewContextOpener",
seed: {
@ -1128,7 +1128,7 @@ test("shows and restores last turn changes from the session diff", async ({ page
await expect(panel.locator('[data-slot="session-review-v2-file-name"]')).toHaveText("delta.ts")
})
test("keeps the review state a session stored before extensions", async ({ page }) => {
test("keeps the review state a session stored before plugins", async ({ page }) => {
const directory = "C:/OpenCode/ReviewLegacy"
await openSession(page, {
name: "ReviewLegacy",
@ -1222,7 +1222,7 @@ test("desktop review waits for the session's stored mode before it loads changes
.poll(() =>
page.evaluate(() =>
Object.entries(localStorage).some(
([key, value]) => key.includes("extension.review.session") && value.includes('"branch"'),
([key, value]) => key.includes("plugin.review.session") && value.includes('"branch"'),
),
),
)
@ -1230,7 +1230,7 @@ test("desktop review waits for the session's stored mode before it loads changes
// The reopened window's review mounts before its session store has loaded.
working.length = 0
await page.goto(desktop("extension.review.session"))
await page.goto(desktop("plugin.review.session"))
await expectSessionTitle(page, title)
await expect(toggle).toHaveAttribute("aria-expanded", "true")
await expect(page.locator("#review-panel").getByText("Loading changes…", { exact: true })).toBeVisible()

View file

@ -243,7 +243,7 @@ test("the details follow the routed session when it moves to another worktree",
await page.keyboard.press("Escape")
await expect(summary).toBeHidden()
// The server moves the session; the screen stays mounted while its extensions read the new worktree.
// The server moves the session; the screen stays mounted while its plugins read the new worktree.
const moved = sessions.find((item) => item.id === fixture.targetID)
if (moved) moved.directory = `${root}/other`

View file

@ -50,7 +50,7 @@ for (const mode of ["failed", "stopped", "ready"] as const) {
})
}
test("adding a WSL server while the WSL extension is down shows that WSL is unavailable", async ({ page }) => {
test("adding a WSL server while the WSL plugin is down shows that WSL is unavailable", async ({ page }) => {
await mockOpenCodeServer(page, {
directory: "/repo",
project: project({ id: "proj_wsl_unavailable", directory: "/repo", name: "WSL project" }),
@ -62,7 +62,7 @@ test("adding a WSL server while the WSL extension is down shows that WSL is unav
const settings = page.getByTestId("settings-screen")
await settings.getByRole("tab", { name: "Servers", exact: true }).click()
await expect(settings.getByRole("region", { name: "Ubuntu", exact: true })).toHaveCount(1)
await page.getByRole("checkbox", { name: "WSL extension" }).uncheck()
await page.getByRole("checkbox", { name: "WSL plugin" }).uncheck()
await settings.getByRole("button", { name: "Add server", exact: true }).press("Enter")
await page.getByRole("menuitem", { name: "Add WSL server", exact: true }).click()
@ -72,7 +72,7 @@ test("adding a WSL server while the WSL extension is down shows that WSL is unav
await expect(dialog.getByText("WSL is unavailable", { exact: true })).toBeVisible()
})
test("adding an SSH server while the SSH extension is down fails instead of connecting forever", async ({ page }) => {
test("adding an SSH server while the SSH plugin is down fails instead of connecting forever", async ({ page }) => {
await mockOpenCodeServer(page, {
directory: "/repo",
project: project({ id: "proj_ssh_unavailable", directory: "/repo", name: "SSH project" }),
@ -84,7 +84,7 @@ test("adding an SSH server while the SSH extension is down fails instead of conn
const settings = page.getByTestId("settings-screen")
await settings.getByRole("tab", { name: "Servers", exact: true }).click()
await expect(settings.getByRole("region", { name: "Ubuntu", exact: true })).toHaveCount(1)
await page.getByRole("checkbox", { name: "SSH extension" }).uncheck()
await page.getByRole("checkbox", { name: "SSH plugin" }).uncheck()
await settings.getByRole("button", { name: "Add server", exact: true }).press("Enter")
await page.getByRole("menuitem", { name: "Add SSH server", exact: true }).click()
@ -137,7 +137,7 @@ test("an open session's terminal follows its WSL server to the endpoint it resta
expect(servers[REMOTE_SERVER]!.pty.sockets.map((socket) => socket.id)).toEqual(["pty_before1"])
})
test("WSL session and draft tabs outlive the extension going away until the server is removed", async ({ page }) => {
test("WSL session and draft tabs outlive the plugin going away until the server is removed", async ({ page }) => {
const directory = "/home/ubuntu/project"
const wsl = session({ id: "ses_wsl_tabs", directory, title: "WSL tabs session" })
@ -170,11 +170,11 @@ test("WSL session and draft tabs outlive the extension going away until the serv
await expectTabs()
const extension = page.getByRole("checkbox", { name: "WSL extension" })
await extension.uncheck()
const plugin = page.getByRole("checkbox", { name: "WSL plugin" })
await plugin.uncheck()
await expectTabs()
await expect(editor).toHaveText("keep this draft")
await extension.check()
await plugin.check()
await expectTabs()
await tabs.nth(0).click()
await expectSessionTitle(page, wsl.title)

View file

@ -257,8 +257,8 @@ test("closing the last restored terminal does not create a hidden replacement",
await expect(tab).toHaveAttribute("aria-selected", "true")
})
// A terminal tab restored open in the side panel, with the terminal in the pre-extension store, which the terminal
// extension imports.
// A terminal tab restored open in the side panel, with the terminal in the pre-plugin store, which the terminal
// plugin imports.
function restoredTerminal(pty: { id: string; title: string }) {
const key = `terminal:${pty.id}`

View file

@ -8,9 +8,9 @@ import { mockWorkspace } from "../utils/workspace"
// The web app's version, which What's New compares with the version last seen.
const current = pkg.version
const SEEN = "opencode.global.dat:extension.updater.seen"
const SEEN = "opencode.global.dat:plugin.updater.seen"
const RELEASE_NOTES = "opencode.global.dat:extension.updater.releaseNotes"
const RELEASE_NOTES = "opencode.global.dat:plugin.updater.releaseNotes"
const cors = { "access-control-allow-origin": "*" }
@ -62,7 +62,7 @@ const changelog = {
// The list form, whose one release in range has no desktop highlights.
const cliOnly = [{ tag: current, highlights: [{ source: "cli", title: "Terminal only", description: "Not here." }] }]
// A user who last saw 1.9.1, stored where the app kept it before the updater extension owned What's New.
// A user who last saw 1.9.1, stored where the app kept it before the updater plugin owned What's New.
const upgraded = { storage: { "highlights.v1": { version: "1.9.1" } } }
test("What's New shows the highlights since the version seen, pages to Get started, and is seen once shown", async ({
@ -132,7 +132,7 @@ test("What's New opened after the attachment mounts waits for the routes, then k
const app = await openHeldStart(page, "/settings")
await app.start()
held.resolve()
// What's New marks the release seen as it opens: after attachment, while an extension still holds the routes.
// What's New marks the release seen as it opens: after attachment, while a plugin still holds the routes.
await expect.poll(() => stored(page, SEEN)).toEqual({ version: "test" })
const dialog = page.getByRole("dialog")

View file

@ -6,14 +6,14 @@ import { useLanguage, type Direction } from "../../src/runtime/i18n/language"
import { PlatformProvider } from "../../src/runtime/platform/platform"
import { createWebPlatform } from "../../src/runtime/platform/web"
import { ServerConnection } from "../../src/runtime/server/registry"
import { Command } from "@opencode/gui-extensions/sdk"
import { useExtensionHost } from "../../src/runtime/extension/host"
import { Command } from "@opencode/plugin/gui"
import { usePluginHost } from "../../src/runtime/plugin/host"
import { useCommand } from "../../src/shell/commands/command"
/**
* Mounts the app at a route. With `held`, the window's providers and extensions start at once and the app interface
* Mounts the app at a route. With `held`, the window's providers and plugins start at once and the app interface
* mounts only when "Start app" is pressed, over its preloaded route, as the desktop shell mounts it once its server is up.
* One extension's load also waits for "Finish startup", so the attachment can mount before the routes render.
* One plugin's load also waits for "Finish startup", so the attachment can mount before the routes render.
*/
export function mount(input: { server: string; route: string; direction: Direction; held?: boolean }) {
const root = document.getElementById("root")
@ -27,14 +27,14 @@ export function mount(input: { server: string; route: string; direction: Directi
const held = Promise.withResolvers<void>()
function StartupGate() {
const host = useExtensionHost()
const host = usePluginHost()
const command = useCommand()
// ExtensionCommands publishes before ready, proving the attachment mounted even while the routes wait.
// PluginCommands publishes before ready, proving the attachment mounted even while the routes wait.
const registered = () =>
host
.items(Command)
.some((item) => command.options.some((option) => option.id === `${item.extension}.${item.value.id}`))
.some((item) => command.options.some((option) => option.id === `${item.plugin}.${item.value.id}`))
return (
<button
@ -67,15 +67,15 @@ export function mount(input: { server: string; route: string; direction: Directi
}
function Startup() {
const host = useExtensionHost()
const definition = host.definitions().find((item) => item.renderer)
const load = definition?.renderer
const host = usePluginHost()
const definition = host.definitions().find((item) => item.windowEntry)
const load = definition?.windowEntry
// Hold a real extension through the public reload API before the startup gate first settles.
// Hold a real plugin through the public reload API before the startup gate first settles.
if (input.held && definition && load)
host.reload(definition.id, {
...definition,
renderer: async () => {
windowEntry: async () => {
await held.promise
return load()

View file

@ -6,8 +6,8 @@ export async function openWithDirection(page: Page, route: string, direction: "l
}
/**
* Opens the app at a route as the desktop shell starts it: the window's extensions run at once, and the app interface
* mounts over the preloaded route only when `start` runs, as it does once the desktop's server is up. One extension
* Opens the app at a route as the desktop shell starts it: the window's plugins run at once, and the app interface
* mounts over the preloaded route only when `start` runs, as it does once the desktop's server is up. One plugin
* stays loading until `finish` runs; commands are published meanwhile, but the routes wait.
*/
export async function openHeldStart(page: Page, route: string) {

View file

@ -2,13 +2,13 @@ import { MemoryRouter, createMemoryHistory } from "@solidjs/router"
import { createMemo, Show } from "solid-js"
import { createStore, unwrap } from "solid-js/store"
import { render } from "solid-js/web"
import type { Bridge, BridgeMessage } from "@opencode/gui-extensions/sdk/bridge"
import type { SshItem, SshState } from "../../../gui-extensions/src/ssh/contract"
import type { WslServerRuntime, WslServersState } from "../../../gui-extensions/src/wsl/contract"
import type { Bridge, BridgeMessage } from "@opencode/plugin/gui/host"
import type { SshItem, SshState } from "../../../gui-plugins/src/ssh/contract"
import type { WslServerRuntime, WslServersState } from "../../../gui-plugins/src/wsl/contract"
import { AppBaseProviders, AppInterface } from "../../src/app"
import { PlatformProvider, type Platform } from "../../src/runtime/platform/platform"
import { ServerConnection } from "../../src/runtime/server/registry"
import { useExtensionServers } from "../../src/runtime/extension/servers"
import { usePluginServers } from "../../src/runtime/plugin/servers"
/** The input of a WSL or SSH method this fixture answers. */
type FixtureInput = { id?: string; name?: string }
@ -112,7 +112,7 @@ export function mount(input: {
},
})
// The main-process WSL and SSH extensions, as the extension bridge sees them.
// The main-process WSL and SSH plugins, as the plugin bridge sees them.
const listeners = new Set<(message: BridgeMessage) => void>()
const snapshot = (ipc: string) => structuredClone(unwrap(ipc === "ssh" ? store.ssh : store.state))
@ -202,15 +202,12 @@ export function mount(input: {
capture: async () => undefined,
runMenubarItem: () => undefined,
configure: () => undefined,
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
list: async () => [],
enable: async () => undefined,
disable: async () => undefined,
reload: async () => undefined,
install: async () => undefined,
remove: async () => undefined,
source: async () => "",
asset: () => "",
},
}
@ -226,21 +223,21 @@ export function mount(input: {
openDirectoryPickerDialog: async () => null,
notify: async () => undefined,
restart: unused,
extensions: bridge,
plugins: bridge,
}
if (input.storage === "async") platform.storage = storage
function Interface() {
const extensions = useExtensionServers()
const pluginServers = usePluginServers()
const servers = createMemo<ServerConnection.Any[]>(() => [
{ type: "sidecar", variant: "base", displayName: "Local Server", http: { url: input.server } },
...extensions.list(),
...pluginServers.list(),
])
return (
<Show when={extensions.ready()}>
<Show when={pluginServers.ready()}>
<AppInterface servers={servers()} router={(props) => <MemoryRouter {...props} history={history} />} />
</Show>
)
@ -250,7 +247,7 @@ export function mount(input: {
<PlatformProvider value={platform}>
<AppBaseProviders locale="en">
<output aria-label="WSL actions">{store.calls.join(",")}</output>
{/* The WSL extension's main side going away, as on a reload or failure, and coming back. */}
{/* The WSL plugin's main side going away, as on a reload or failure, and coming back. */}
<label>
<input
type="checkbox"
@ -263,9 +260,9 @@ export function mount(input: {
if (available) publish("wsl")
}}
/>
WSL extension
WSL plugin
</label>
{/* The SSH extension's main side going away and coming back. */}
{/* The SSH plugin's main side going away and coming back. */}
<label>
<input
type="checkbox"
@ -277,7 +274,7 @@ export function mount(input: {
if (available) publish("ssh")
}}
/>
SSH extension
SSH plugin
</label>
{/* The SSH tunnel dropping, which only main notices. */}
<Show when={input.ssh}>

View file

@ -1,7 +1,7 @@
import { MemoryRouter, createMemoryHistory } from "@solidjs/router"
import { createStore } from "solid-js/store"
import { render } from "solid-js/web"
import type { Bridge } from "@opencode/gui-extensions/sdk/bridge"
import type { Bridge } from "@opencode/plugin/gui/host"
import { AppBaseProviders, AppInterface } from "../../src/app"
import { PlatformProvider, type Platform } from "../../src/runtime/platform/platform"
@ -21,7 +21,7 @@ export function mount(input: { server: string; path?: string }) {
throw new Error("Unexpected fixture action")
}
// No main-process extensions run in this fixture.
// No main-process plugins run in this fixture.
const bridge: Bridge = {
packaged: false,
call: unused,
@ -31,15 +31,12 @@ export function mount(input: { server: string; path?: string }) {
capture: async () => undefined,
runMenubarItem: () => undefined,
configure: () => undefined,
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
list: async () => [],
enable: async () => undefined,
disable: async () => undefined,
reload: async () => undefined,
install: async () => undefined,
remove: async () => undefined,
source: async () => "",
asset: () => "",
},
}
@ -51,7 +48,7 @@ export function mount(input: { server: string; path?: string }) {
openDirectoryPickerDialog: async () => null,
notify: async () => undefined,
restart: unused,
extensions: bridge,
plugins: bridge,
runDesktopMenuAction: (action) => setStore("actions", (actions) => [...actions, action]),
}

View file

@ -65,7 +65,8 @@
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
"@opencode/schema": "workspace:*",
"@opencode/gui-extensions": "workspace:*",
"@opencode/gui-plugins": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/session-ui": "workspace:*",
"@opencode/ui": "workspace:*",
"@opencode/util": "workspace:*",

View file

@ -20,7 +20,7 @@ import { SettingsProvider } from "@/settings/model"
import { TabsProvider } from "@/shell/tabs/tabs"
import { ErrorPage } from "@/shell/errors/error"
import { AppRoutes, File, preloadRoute } from "@/shell/routes/routes"
import { ExtensionRoot } from "@/runtime/extension/root"
import { PluginRoot } from "@/runtime/plugin/root"
export { preloadRoute }
@ -75,9 +75,9 @@ export function AppBaseProviders(
>
<QueryProvider>
<DialogProvider>
<ExtensionRoot>
<PluginRoot>
<FileComponentProvider component={File}>{props.children}</FileComponentProvider>
</ExtensionRoot>
</PluginRoot>
</DialogProvider>
</QueryProvider>
</ErrorBoundary>

View file

@ -28,7 +28,7 @@ import { useLanguage } from "@/runtime/i18n/language"
import { CommentsProvider } from "@/composer/comments"
import { ComposerPersistenceProvider } from "@/composer/persistence"
import { ModelsProvider } from "@/providers/models/models"
import { Contribution } from "@/runtime/extension/render"
import { Contribution } from "@/runtime/plugin/render"
import { ServerProvider, useServer } from "@/runtime/server/current"
import { ServerConnection, useServers } from "@/runtime/server/registry"
import { useGlobal } from "@/runtime/server/runtime"
@ -63,7 +63,7 @@ const modules = import.meta.glob<StoryModule>([
"../**/*.stories.tsx",
"../../../ui/src/**/*.stories.tsx",
"../../../session-ui/src/**/*.stories.tsx",
"../../../gui-extensions/src/**/*.stories.tsx",
"../../../gui-plugins/src/**/*.stories.tsx",
])
// Each file's text, for the order its states were written in.
@ -72,7 +72,7 @@ const sources = import.meta.glob<string>(
"../**/*.stories.tsx",
"../../../ui/src/**/*.stories.tsx",
"../../../session-ui/src/**/*.stories.tsx",
"../../../gui-extensions/src/**/*.stories.tsx",
"../../../gui-plugins/src/**/*.stories.tsx",
],
{ query: "?raw", import: "default" },
)
@ -484,7 +484,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark"
onPointerDown={pause}
>
<Workspace>
<Extension file={entry.file}>
<Plugin file={entry.file}>
<DialogProvider container={canvas()}>
<Show when={render()} keyed fallback={language.t("lab.empty")}>
{(fn) => (
@ -505,7 +505,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark"
)}
</Show>
</DialogProvider>
</Extension>
</Plugin>
</Workspace>
</div>
)
@ -567,11 +567,11 @@ function Project(props: { children: JSX.Element }) {
)
}
// A story of an extension renders as its contributions do: inside that extension's context from the app's host.
function Extension(props: { file: string; children: JSX.Element }) {
const id = props.file.match(/gui-extensions\/src\/([^/]+)\//)?.[1]
// A story of a plugin renders as its contributions do: inside that plugin's context from the app's host.
function Plugin(props: { file: string; children: JSX.Element }) {
const id = props.file.match(/gui-plugins\/src\/([^/]+)\//)?.[1]
return id ? <Contribution extension={id}>{() => props.children}</Contribution> : props.children
return id ? <Contribution plugin={id}>{() => props.children}</Contribution> : props.children
}
/** The tree under `path`: a folder for each further title segment and a row for each story, by name. */

View file

@ -14,9 +14,9 @@ const durable = {
const note = { ...durable, live: { subject: 'the "button#save" element (browser ref @e42)' } }
describe("extension notes", () => {
describe("plugin notes", () => {
test("read from message metadata beside file comments and skip malformed entries", () => {
// Metadata a build before extension notes sent for a browser element comment.
// Metadata a build before plugin notes sent for a browser element comment.
const browser = {
type: "browser",
tabID: "tab_00000000-0000-4000-8000-000000000000",

View file

@ -1,7 +1,7 @@
import { ImagePreview } from "@opencode/ui/image-preview"
import { useDialog } from "@opencode/ui/context/dialog"
import type { ReferenceInfo } from "@opencode/client/promise"
import type { Links, MountedSession } from "@opencode/gui-extensions/sdk"
import type { Links, MountedSession } from "@opencode/plugin/gui"
import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
import { Predicate } from "effect"
import type { ComposerSuggestion } from "./types"
@ -10,8 +10,8 @@ import { selectionFromLines, type SelectedLineRange, useFile } from "@/workspace
import { useComments } from "@/composer/comments"
import { useCommand } from "@/shell/commands/command"
import { useLanguage } from "@/runtime/i18n/language"
import { useExtensionHost } from "@/runtime/extension/host"
import { useExtensionAttachment } from "@/runtime/extension/host-apis"
import { usePluginHost } from "@/runtime/plugin/host"
import { usePluginAttachment } from "@/runtime/plugin/host-apis"
import { usePlatform } from "@/runtime/platform/platform"
import { useWorkspaceLocation } from "@/workspaces/location"
import { useData, useServer } from "@/runtime/server/current"
@ -50,11 +50,11 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const server = useServer()
const available = () =>
server.conn.type !== "extension" || !server.conn.managed || server.ctx.sdk.connection.status() === "connected"
server.conn.type !== "plugin" || !server.conn.managed || server.ctx.sdk.connection.status() === "connected"
const files = useFile()
const links = useExtensionHost().links
const extensions = useExtensionAttachment()
const links = usePluginHost().links
const plugins = usePluginAttachment()
const comments = useComments()
const dialog = useDialog()
const command = useCommand()
@ -86,8 +86,8 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const history = createComposerHistory()
const recent = createMemo(() => {
const all = extensions.files.opened()
const active = extensions.files.active()
const all = plugins.files.opened()
const active = plugins.files.active()
return active ? [active, ...all.filter((path) => path !== active)] : all
})
@ -440,15 +440,15 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const item = controller.contextItem(key)
if (item?.type === "note") {
// The extension that attached the note reveals its subject.
// The plugin that attached the note reveals its subject.
const href = item.live?.href ?? item.href
if (href) links.open({ href, origin: item.origin, session: extensions.current() })
if (href) links.open({ href, origin: item.origin, session: plugins.current() })
return
}
if (item?.type === "file") openComment(item, links, extensions.current(), files, comments)
if (item?.type === "file") openComment(item, links, plugins.current(), files, comments)
},
onEditor(element) {
// SAFETY: the editor's only `setEditor` call passes its editable root, a `<div>` (`editor/editor.tsx`).
@ -629,7 +629,7 @@ function openComment(
})
}
// The extension that owns the comment's origin reveals it (the review diff or a file tab), keeping the conversation.
// The plugin that owns the comment's origin reveals it (the review diff or a file tab), keeping the conversation.
links.open({ href: item.path, origin: item.commentOrigin, exact: true, background: true, session })
if (item.commentOrigin === "review") return queueFocus()

View file

@ -125,7 +125,7 @@ describe("buildPromptRequest", () => {
expect(result.text).toContain("focus here")
})
test("sends an extension note with its live subject and attaches only the files it mentions", () => {
test("sends a plugin note with its live subject and attaches only the files it mentions", () => {
const note = {
type: "note" as const,
origin: "example",

View file

@ -74,7 +74,7 @@ describe("composer persistence schemas", () => {
expect(decode({}).prompt).toEqual(DEFAULT_PROMPT)
})
test("restores extension notes and legacy browser comments without their process-bound refs", () => {
test("restores plugin notes and legacy browser comments without their process-bound refs", () => {
const durable = {
type: "note" as const,
origin: "example",
@ -91,7 +91,7 @@ describe("composer persistence schemas", () => {
live: { subject: 'the "button#save" element (browser ref @e42)', href: `${durable.href}#e42` },
}
// A draft stored by a build before extension notes, as its composer schema encoded it.
// A draft stored by a build before plugin notes, as its composer schema encoded it.
const browser = {
type: "browser" as const,
tabID: "tab_00000000-0000-4000-8000-000000000000",

View file

@ -175,7 +175,7 @@ const NoteFields = {
comment: Schema.String,
}
/** An extension's comment on something other than workspace lines, as sent in message metadata. */
/** A plugin's comment on something other than workspace lines, as sent in message metadata. */
export const NoteComment = Persistence.struct(NoteFields)
export type NoteComment = typeof NoteComment.Type
@ -184,7 +184,7 @@ export const NoteContextItem = Persistence.struct({ ...NoteFields, commentID: Sc
export type NoteContextItem = typeof NoteContextItem.Type
/** Where text quoted from outside the timeline came from, such as an extension's terminal. */
/** Where text quoted from outside the timeline came from, such as a plugin's terminal. */
export const QuoteSource = Persistence.struct({
label: Schema.String,
icon: Schema.String,
@ -219,8 +219,8 @@ export function durableNote<Note extends NoteComment>(note: Note) {
return Struct.omit(note, ["live"])
}
// Legacy data: desktop builds before extension notes stored browser element comments as their own type, in drafts
// and in message metadata. They read as the browser extension's note, without the element ref of their process.
// Legacy data: desktop builds before plugin notes stored browser element comments as their own type, in drafts
// and in message metadata. They read as the browser plugin's note, without the element ref of their process.
const LegacyBrowserComment = Persistence.struct({
type: Schema.Literal("browser"),
tabID: Schema.String,

View file

@ -20,4 +20,4 @@ export { createNamespaceStorage, type NamespaceStorage } from "./runtime/persist
export { flushPersisted } from "./runtime/persistence/persist"
export { useExtensionServers } from "./runtime/extension/servers"
export { usePluginServers } from "./runtime/plugin/servers"

View file

@ -46,7 +46,7 @@ export function createHomeProjectsController(home: HomeController) {
}
// An expired pairing session or a changed password signs the app out of an HTTP server; signing in again edits it,
// and the action that asked for sign-in continues once the dialog saves, as it does for extension servers. It continues
// and the action that asked for sign-in continues once the dialog saves, as it does for plugin servers. It continues
// with the saved connection: the one it started with still carries the rejected credentials.
function authenticate(conn: ServerConnection.Any, onConnected?: (conn: ServerConnection.Any) => void) {
if (conn.type !== "http" || !home.server.health(conn)?.unauthorized)

View file

@ -29,10 +29,10 @@ const HOME_PROJECT_NAV_LABEL = "min-w-0 flex-1 overflow-hidden text-ellipsis whi
const serverContextMenuID = (server: ServerConnection.Any) => `server:${ServerConnection.key(server)}`
// Extension servers ask for sign-in themselves; an HTTP server that rejects its saved credentials needs a new
// Plugin servers ask for sign-in themselves; an HTTP server that rejects its saved credentials needs a new
// pairing link or password.
const signInRequired = (server: ServerConnection.Any, health: ServerHealth | undefined) =>
(server.type === "extension" && server.authenticationRequired) || (server.type === "http" && !!health?.unauthorized)
(server.type === "plugin" && server.authenticationRequired) || (server.type === "http" && !!health?.unauthorized)
const projectContextMenuID = (server: ServerConnection.Any, directory: string) =>
`project:${ServerConnection.key(server)}:${directory}`
@ -216,7 +216,7 @@ function HomeProjectsPanel(props: HomeProjectsViewProps) {
props.servers.some(
(server) =>
signInRequired(server, props.serverHealth(server)) ||
(server.type === "extension" && server.connecting),
(server.type === "plugin" && server.connecting),
)
}
fallback={
@ -251,7 +251,7 @@ function HomeProjectsPanel(props: HomeProjectsViewProps) {
const hasProjects = () => projects().length > 0
const collapsed = () => props.collapsed(item)
const authentication = () => signInRequired(item, props.serverHealth(item))
const connecting = () => item.type === "extension" && item.connecting
const connecting = () => item.type === "plugin" && item.connecting
return (
<div class="flex min-w-0 flex-col gap-1">
@ -422,7 +422,7 @@ function HomeServerRow(props: {
<div class="flex size-4 shrink-0 items-center justify-center -mr-0.5">
<ServerHealthIndicator
health={props.health}
connecting={props.server.type === "extension" && props.server.connecting}
connecting={props.server.type === "plugin" && props.server.connecting}
authenticationRequired={authentication()}
/>
</div>

View file

@ -71,6 +71,7 @@ function NewSessionLocationDialog(props: {
const global = useGlobal()
const servers = useServers()
const serverSDK = useServerSDK()
const [store, setStore] = createStore<{
drilled?: PromptProject
/** Picking the server to add a project to. */
@ -101,6 +102,7 @@ function NewSessionLocationDialog(props: {
[],
}),
)
// `latest` only skips Suspense once the resource has resolved at least once. Before that it behaves like a plain
// read, which suspends the dialog and makes it flash on the first drill into a project.
const listedItems = (project: PromptProject) => {
@ -204,9 +206,11 @@ function NewSessionLocationDialog(props: {
createEffect(() => {
if (!activeEntry()) return
const frame = requestAnimationFrame(() =>
resultsRef?.querySelector("[data-active]")?.scrollIntoView({ block: "nearest" }),
)
onCleanup(() => cancelAnimationFrame(frame))
})
@ -277,6 +281,7 @@ function NewSessionLocationDialog(props: {
}
const handleKeyDown = (event: KeyboardEvent) => {
// SAFETY: this handler is only attached to the search TextInput's <input>, so currentTarget is that element.
const target = event.currentTarget as HTMLInputElement
const atEnd = target.selectionStart === target.value.length && target.selectionEnd === target.value.length
const atStart = target.selectionStart === 0 && target.selectionEnd === 0
@ -559,12 +564,20 @@ function ServerTag(props: { server?: PromptServer }) {
)
}
function workspaceIcon(value: string) {
if (value === "main") return "monitor"
if (value === "create") return "plus"
return "outline-worktree"
}
function WorkspaceRow(props: { title: string; value: string; description: string }) {
return (
<>
<div class="command-palette-row-main">
<Icon
name={props.value === "main" ? "monitor" : props.value === "create" ? "plus" : "outline-worktree"}
name={workspaceIcon(props.value)}
class="command-palette-row-icon"
classList={{ "!text-v2-icon-icon-accent": props.value !== "main" && props.value !== "create" }}
/>
@ -590,5 +603,5 @@ function tagged(server?: PromptServer) {
function serverIcon(server: PromptServer) {
if (server.kind === "current") return "monitor"
return server.kind === "extension" ? "terminal" : "globe"
return server.kind === "plugin" ? "terminal" : "globe"
}

View file

@ -37,7 +37,7 @@ export function createComposerProjectControls(props: { draftId: string; worktree
key: ServerConnection.key(connection),
name: servers.label(connection),
hint: servers.hint(connection),
kind: servers.current(connection) ? "current" : connection.type === "extension" ? "extension" : "remote",
kind: servers.current(connection) ? "current" : connection.type === "plugin" ? "plugin" : "remote",
label: connection.label,
}
}
@ -45,7 +45,7 @@ export function createComposerProjectControls(props: { draftId: string; worktree
// Servers that are down or still connecting contribute nothing.
const ready = createMemo(() =>
servers.list.filter((connection) => {
if (connection.type === "extension" && connection.state !== "ready") return false
if (connection.type === "plugin" && connection.state !== "ready") return false
return global.servers.health[ServerConnection.key(connection)]?.healthy !== false
}),

View file

@ -9,8 +9,8 @@ export type PromptServer = {
name: string
/** "This computer" beside the current server's name in the server picker. */
hint?: string
kind: "current" | "remote" | "extension"
/** The extension's short badge, e.g. "SSH". */
kind: "current" | "remote" | "plugin"
/** The plugin's short badge, e.g. "SSH". */
label?: string
}

View file

@ -2,9 +2,9 @@ import { expect, test } from "bun:test"
import { authServerName } from "./remote"
const contributed = {
type: "extension",
type: "plugin",
key: "ssh:production",
extension: "ssh",
plugin: "ssh",
state: "ready",
connecting: false,
authenticationRequired: false,
@ -39,7 +39,7 @@ test.each([
},
{
name: "WSL",
server: { ...contributed, key: "wsl:Ubuntu", extension: "wsl", displayName: "Ubuntu" } as const,
server: { ...contributed, key: "wsl:Ubuntu", plugin: "wsl", displayName: "Ubuntu" } as const,
expected: "Ubuntu",
},
{

View file

@ -1,15 +0,0 @@
import type { Definition } from "@opencode/gui-extensions/sdk"
import { builtins } from "@opencode/gui-extensions/renderer"
export { builtins }
/** Dispatched in development with the re-evaluated built-in list after an extension's files change. */
export const BUILTINS_UPDATED = "opencode:gui-extensions-updated"
// Accepting the list here keeps an extension edit from reloading the window; hmr.tsx reloads that extension.
if (import.meta.hot)
import.meta.hot.accept("@opencode/gui-extensions/renderer", (module) => {
const next: readonly Definition[] | undefined = module?.builtins
if (next) window.dispatchEvent(new CustomEvent(BUILTINS_UPDATED, { detail: next }))
})

View file

@ -1,15 +0,0 @@
import type { Panel } from "@opencode/gui-extensions/sdk"
/** The key the host stores a panel tab under. */
export function panelKey(extension: string, id: string) {
return `${extension}:${id}`
}
/** The stored keys the panels map with `Panel.legacy`, each to the key of the tab it is now. */
export function legacyKeys(providers: readonly { readonly extension: string; readonly value: Panel }[]) {
return new Map(
providers.flatMap((item) =>
Object.entries(item.value.legacy ?? {}).map(([key, id]) => [key, panelKey(item.extension, id)] as const),
),
)
}

View file

@ -1,107 +0,0 @@
import { createMemo, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js"
import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge"
import type { Definition } from "@opencode/gui-extensions/sdk"
import { builtins } from "./builtins"
import { createInstalled } from "./installed"
import { createMenubarItems, MenubarItemsProvider } from "./menubar-items"
import { usePlatform } from "@/runtime/platform/platform"
import { ExtensionHostProvider, useExtensionHost } from "./host"
import { createIpcClients } from "./ipc"
import { createExtensionAttachment, createHostApis, ExtensionAttachmentProvider, type HostApis } from "./host-apis"
import { ExtensionCommands } from "./commands"
import { ExtensionStyles } from "./render"
import { ExtensionServersProvider } from "./servers"
import { ExtensionServerEndpoints } from "./server-shell"
import { createContext, useContext } from "solid-js"
const HostApisContext = createContext<HostApis>()
const ExtensionHotReload = import.meta.env.DEV ? lazy(() => import("./hmr")) : undefined
export function useHostApis() {
const value = useContext(HostApisContext)
if (!value) throw new Error("Host APIs are unavailable")
return value
}
/** Mounts the extension host for the window. Lives above the app interface so extensions can contribute servers. */
export function ExtensionRoot(props: ParentProps) {
const platform = usePlatform()
const apis = createHostApis()
const bridge = platform.extensions
const menubar = createMenubarItems(bridge)
const ipcs = createIpcClients(bridge)
onCleanup(ipcs.dispose)
const installed = createInstalled(bridge)
const os = platform.platform === "desktop" ? platform.os : undefined
// Built-ins only: installed `.ocdx` archives run their main entry until that format ships renderer bundles.
const definitions = builtins.filter(
(definition: Definition) => !definition.os || (!!os && definition.os.includes(os)),
)
// Only enable preferences cross this boundary; the host derives blocked status from live hard dependencies.
const disabled = createMemo(() => {
const state = installed.enableState()
if (!state) return undefined
return new Set(definitions.flatMap((definition) => (extensionEnabled(definition, state) ? [] : [definition.id])))
})
const failed = (id: string) => installed.list().some((item) => item.id === id && item.error !== undefined)
return (
<HostApisContext.Provider value={apis}>
<ExtensionHostProvider
definitions={definitions}
disabled={disabled}
apis={apis.apis}
whenMounted={apis.whenMounted}
ipc={bridge ? (token) => ipcs.client(token) : undefined}
generation={ipcs.generation}
failed={failed}
>
<ExtensionStyles />
{ExtensionHotReload && (
<Suspense>
<ExtensionHotReload />
</Suspense>
)}
<MenubarItemsProvider value={menubar}>
<ExtensionServersProvider failed={failed}>{props.children}</ExtensionServersProvider>
</MenubarItemsProvider>
</ExtensionHostProvider>
</HostApisContext.Provider>
)
}
/** Attaches the session and layout HostApis and publishes extension commands. Renders once extensions are active. */
export function ExtensionAttachment(props: ParentProps) {
const host = useExtensionHost()
const attachment = createExtensionAttachment(useHostApis())
return (
<ExtensionAttachmentProvider value={attachment}>
<ExtensionCommands />
<ExtensionServerEndpoints />
<Show when={host.ready()}>
<MountedInterface attach={attachment.attach} />
{props.children}
</Show>
</ExtensionAttachmentProvider>
)
}
/**
* The app interface as the HostApis see it, mounted as the routes first render and not before: writes and dialogs made
* while extensions set up wait until then.
*/
function MountedInterface(props: { attach: () => () => void }) {
onCleanup(props.attach())
return null
}

View file

@ -1,96 +0,0 @@
import { For, onCleanup, Show } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import { Button } from "@opencode/ui/button"
import { Switch } from "@opencode/ui/switch"
import type { Installed } from "@opencode/gui-extensions/sdk/bridge"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { SettingsList } from "@/settings/list"
import { SettingsRow } from "@/settings/row"
import { useExtensionHost } from "./host"
/** Development builds: every built-in GUI extension of this window, with enable and reload controls. */
export function GuiExtensionsSettings() {
const language = useLanguage()
const host = useExtensionHost()
const bridge = usePlatform().extensions
const [installed, setInstalled] = createStore<{ list: Installed[] }>({ list: [] })
if (bridge) {
void bridge.manager.list().then((list) => setInstalled("list", reconcile([...list])))
onCleanup(
bridge.on((message) => {
if (message.type === "extensions") setInstalled("list", reconcile([...message.list]))
}),
)
}
const enabled = (id: string) => installed.list.find((item) => item.id === id)?.enabled ?? true
const status = (id: string) => {
const value = host.state.status[id] ?? "loading"
if (value === "active") return language.t("settings.guiExtensions.status.active")
if (value === "failed") return language.t("settings.guiExtensions.status.failed")
if (value === "disabled") return language.t("settings.guiExtensions.status.disabled")
if (value === "blocked") return language.t("settings.guiExtensions.status.blocked")
return language.t("settings.guiExtensions.status.loading")
}
const toggle = (id: string, next: boolean) => void (next ? bridge?.manager.enable(id) : bridge?.manager.disable(id))
// Main entries reload through the manager; the renderer entry reloads here.
const reload = (id: string) => {
host.reload(id)
void bridge?.manager.reload(id)
}
return (
<>
<div class="settings-tab-header">
<div class="settings-tab-header-row">
<div class="flex flex-col gap-1">
<h2 class="settings-tab-title">{language.t("settings.guiExtensions.title")}</h2>
<span class="text-11-regular text-v2-text-text-muted">
{language.t("settings.guiExtensions.description")}
</span>
</div>
</div>
</div>
<div class="settings-tab-body settings-tab-body--sectioned">
<section class="settings-section" aria-label={language.t("settings.guiExtensions.title")}>
<SettingsList>
<For each={host.definitions()}>
{(definition) => (
<SettingsRow
title={<bdi dir="ltr">{definition.id}</bdi>}
description={
<>
{status(definition.id)}
<Show when={host.state.failures[definition.id]?.error}>
{(error) => <pre class="mt-1 whitespace-pre-wrap text-text-danger-base">{error()}</pre>}
</Show>
</>
}
>
<div class="flex items-center gap-3">
<Button size="small" variant="ghost" onClick={() => reload(definition.id)}>
{language.t("settings.guiExtensions.reload")}
</Button>
<Switch hideLabel checked={enabled(definition.id)} onChange={(next) => toggle(definition.id, next)}>
{definition.id}
</Switch>
</div>
</SettingsRow>
)}
</For>
</SettingsList>
</section>
</div>
</>
)
}

View file

@ -1,36 +0,0 @@
import { createMemo } from "solid-js"
import { createMediaQuery } from "@solid-primitives/media"
import { SettingsPage } from "@opencode/gui-extensions/sdk"
import { usePlatform } from "@/runtime/platform/platform"
import { useExtensionHost } from "./host"
/** Extension settings pages that apply to this platform and viewport. */
export function createSettingsPages() {
const host = useExtensionHost()
const platform = usePlatform()
const mobile = createMediaQuery("(max-width: 767px)")
const items = createMemo(() =>
host.items(SettingsPage).filter((item) => {
if (item.value.available === "desktop") return platform.platform === "desktop"
if (item.value.available === "mobile") return mobile()
return true
}),
)
const pages = createMemo(() => items().filter((item) => !item.value.page))
const tabs = createMemo<ReadonlySet<string>>(() => new Set(pages().map((item) => item.value.id)))
return {
items,
/** Settings pages without a host page, in contribution order. */
pages,
/** Their tab values. */
tabs,
/** Sections on a host page, or with `section`, the rows placed in that host section. */
sections: (page: "general" | "servers", section?: "general") =>
items().filter((item) => item.value.page === page && item.value.section === section),
}
}

View file

@ -765,14 +765,19 @@ export const dict = {
"settings.experimental.row.newIcons.description": "Preview the updated icon set",
"settings.experimental.row.newModelPicker.title": "New model picker",
"settings.experimental.row.newModelPicker.description": "Preview the redesigned model picker",
"settings.guiExtensions.title": "Extensions",
"settings.guiExtensions.description": "Built-in GUI extensions in this window. Development builds only.",
"settings.guiExtensions.reload": "Reload",
"settings.guiExtensions.status.loading": "Loading",
"settings.guiExtensions.status.active": "Active",
"settings.guiExtensions.status.failed": "Failed",
"settings.guiExtensions.status.disabled": "Disabled",
"settings.guiExtensions.status.blocked": "Blocked",
"settings.plugins.title": "Plugins",
"settings.plugins.description": "Built-in plugins and plugins from your OpenCode config",
"settings.plugins.reload": "Reload",
"settings.plugins.status.loading": "Loading",
"settings.plugins.status.failed": "Failed",
"settings.plugins.error.notFound": "Plugin not found",
"settings.plugins.builtin": "Built-in",
"settings.plugins.reserved": "Not loaded. A built-in plugin already uses this ID.",
"settings.plugins.unsupported": "Not available on this system.",
"settings.plugins.part.server": "Server",
"settings.plugins.part.tui": "TUI",
"settings.plugins.parts.note":
'Switches turn off only a plugin\'s desktop UI. Add "-<id>" to plugins in your global opencode.json to turn off its server part, or "-" and its TUI plugin\'s ID to plugins in cli.json to turn off its TUI part.',
"settings.tab.about": "About",
"settings.about.version": "Version {{version}}",
"settings.about.devVersion": "development",

View file

@ -3,7 +3,7 @@ import type { AsyncStorage, SyncStorage } from "@solid-primitives/storage"
import type { Accessor } from "solid-js"
import type { DesktopMenuAction, DesktopZoomLevel } from "@/shell/commands/desktop-menu"
import type { DraftStore } from "@/runtime/persistence/drafts"
import type { Bridge } from "@opencode/gui-extensions/sdk/bridge"
import type { Bridge } from "@opencode/plugin/gui/host"
type PickerPaths = string | string[] | null
@ -124,8 +124,8 @@ type PlatformBase = {
/** Record a fatal renderer error in platform logs (desktop only) */
recordFatalRendererError?(error: FatalRendererErrorLog): Promise<void>
/** GUI extension bridge to the main-process extension host (desktop only). */
extensions?: Bridge
/** GUI plugin bridge to the main-process plugin host (desktop only). */
plugins?: Bridge
}
export type Platform = PlatformBase &

View file

@ -1,15 +1,15 @@
import { createContext, useContext } from "solid-js"
import type { createExtensionAttachment } from "./host-apis"
import type { createPluginAttachment } from "./host-apis"
// Apart from `host-apis.tsx`, so session code such as the side panels reads the attachment without loading the HostApis.
const AttachmentContext = createContext<ReturnType<typeof createExtensionAttachment>>()
const AttachmentContext = createContext<ReturnType<typeof createPluginAttachment>>()
export function useExtensionAttachment() {
export function usePluginAttachment() {
const value = useContext(AttachmentContext)
if (!value) throw new Error("Extension attachment is unavailable")
if (!value) throw new Error("Plugin attachment is unavailable")
return value
}
export const ExtensionAttachmentProvider = AttachmentContext.Provider
export const PluginAttachmentProvider = AttachmentContext.Provider

View file

@ -0,0 +1,15 @@
import { builtins } from "@opencode/gui-plugins/renderer"
import type { Entry } from "@opencode/plugin/gui/host"
export { builtins }
/** Dispatched in development with the re-evaluated built-in list after a plugin's files change. */
export const BUILTINS_UPDATED = "opencode:gui-plugins-updated"
// Accepting the list here keeps a plugin edit from reloading the window; hmr.tsx reloads that plugin.
if (import.meta.hot)
import.meta.hot.accept("@opencode/gui-plugins/renderer", (module) => {
const next: readonly Entry[] | undefined = module?.builtins
if (next) window.dispatchEvent(new CustomEvent(BUILTINS_UPDATED, { detail: next }))
})

View file

@ -1,12 +1,5 @@
import { expect, test } from "bun:test"
import type {
MountedSession,
Panel,
PanelProps,
PanelTab,
SessionRef,
SessionScreen,
} from "@opencode/gui-extensions/sdk"
import type { MountedSession, Panel, PanelProps, PanelTab, SessionRef, SessionScreen } from "@opencode/plugin/gui"
import { CLOSED_TABS_LIMIT, closedEntry, createClosedTabs } from "./closed-tabs"
// SAFETY: the in-memory store reads only `key`; the rest of a session reference is never touched.

View file

@ -1,7 +1,7 @@
import { createSignal } from "solid-js"
import { createStore } from "solid-js/store"
import { createEventListener } from "@solid-primitives/event-listener"
import type { Panel, PanelProps, SessionRef } from "@opencode/gui-extensions/sdk"
import type { Panel, PanelProps, SessionRef } from "@opencode/plugin/gui"
import { adjacentTabKey } from "@/shell/titlebar/tab-order"
/** The most closed tabs a session keeps. */
@ -9,7 +9,7 @@ export const CLOSED_TABS_LIMIT = 30
/** A side tab the user closed, as the new tab view lists it and ⌘⇧T brings it back. */
export type ClosedSideTab = {
/** `${extension}:${tab id}`. */
/** `${plugin}:${tab id}`. */
readonly key: string
readonly title: string
/** An icon name; stored, so check it before drawing. */

View file

@ -1,24 +1,24 @@
import { createMemo } from "solid-js"
import { Command } from "@opencode/gui-extensions/sdk"
import { BuiltinCommand } from "@opencode/plugin/gui/builtin"
import { useCommand, type CommandSource } from "@/shell/commands/command"
import { useSettings } from "@/settings/model"
import { migrateKeybinds } from "@/settings/keybinds/migration"
import { useExtensionHost, type Item } from "./host"
import { usePluginHost, type Item } from "./host"
/** Publishes extension commands as `${extension}.${id}` in the host command registry. */
export function ExtensionCommands() {
const host = useExtensionHost()
/** Publishes plugin commands as `${plugin}.${id}` in the host command registry. */
export function PluginCommands() {
const host = usePluginHost()
const command = useCommand()
migrateKeybinds(useSettings())
// Extensions activate in whatever order their entries load; list them in definition order, then registration order.
// Plugins activate in whatever order their entries load; list them in definition order, then registration order.
const rank = createMemo(() => new Map(host.definitions().map((definition, index) => [definition.id, index])))
const order = (extension: string) => rank().get(extension) ?? rank().size
command.register("extensions", () =>
const order = (plugin: string) => rank().get(plugin) ?? rank().size
command.register("plugins", () =>
host
.items(Command)
.toSorted((a, b) => order(a.extension) - order(b.extension))
.items(BuiltinCommand)
.toSorted((a, b) => order(a.plugin) - order(b.plugin))
.map((item) => ({
id: `${item.extension}.${item.value.id}`,
id: `${item.plugin}.${item.value.id}`,
title: item.value.title,
description: item.value.description,
keywords: item.value.keywords,
@ -42,19 +42,20 @@ export function ExtensionCommands() {
return null
}
// A command scoped to a selector runs only while the event's target is inside it.
const scopedTo = (scope: string) => (event: KeyboardEvent) =>
event.target instanceof Element && !!event.target.closest(scope)
/** Whether an enabled extension command scoped around the key's target is bound to that key, so it answers instead. */
export function useExtensionClaims() {
const host = useExtensionHost()
/** Whether an enabled plugin command scoped around the key's target is bound to that key, so it answers instead. */
export function usePluginClaims() {
const host = usePluginHost()
const command = useCommand()
return (event: KeyboardEvent) => extensionClaims(host.items(Command), command.matches, event)
return (event: KeyboardEvent) => pluginClaims(host.items(BuiltinCommand), command.matches, event)
}
export function extensionClaims(
commands: readonly Item<Command>[],
export function pluginClaims(
commands: readonly Item<BuiltinCommand>[],
matches: (id: string, event: KeyboardEvent) => boolean,
event: KeyboardEvent,
) {
@ -63,15 +64,15 @@ export function extensionClaims(
!!item.value.scope &&
item.value.enabled !== false &&
scopedTo(item.value.scope)(event) &&
matches(`${item.extension}.${item.value.id}`, event),
matches(`${item.plugin}.${item.value.id}`, event),
)
}
/** Focus inside an extension command's scope belongs to that extension, which binds its own shortcuts there. */
export function useExtensionScoped() {
const host = useExtensionHost()
/** Focus inside a plugin command's scope belongs to that plugin, which binds its own shortcuts there. */
export function usePluginScoped() {
const host = usePluginHost()
return (target: EventTarget | null) =>
target instanceof Element &&
host.items(Command).some((item) => !!item.value.scope && !!target.closest(item.value.scope))
host.items(BuiltinCommand).some((item) => !!item.value.scope && !!target.closest(item.value.scope))
}

View file

@ -3,8 +3,8 @@ import { createStore } from "solid-js/store"
import { createEventListener } from "@solid-primitives/event-listener"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { prefersReducedMotion } from "@opencode/ui/motion"
import type { EmbedProps, Embeds } from "@opencode/gui-extensions/sdk"
import type { Bridge } from "@opencode/gui-extensions/sdk/bridge"
import type { EmbedProps, Embeds } from "@opencode/plugin/gui"
import type { Bridge } from "@opencode/plugin/gui/host"
const geometry =
/^(inset|left|right|top|bottom|translate|transform|scale|rotate|margin|padding|flex|grid|gap|row-gap|column-gap)|(^|-)(width|height)$/
@ -29,7 +29,7 @@ type Still = {
image: HTMLImageElement
}
/** Main-process embeds laid out over the DOM box an extension renders for them. */
/** Main-process embeds laid out over the DOM box a plugin renders for them. */
export function createEmbeds(input: Input): Embeds {
return {
View: (props) => {

View file

@ -1,14 +1,14 @@
import { makeEventListener } from "@solid-primitives/event-listener"
import type { Definition } from "@opencode/gui-extensions/sdk"
import type { Entry } from "@opencode/plugin/gui/host"
import { BUILTINS_UPDATED } from "./builtins"
import { useExtensionHost } from "./host"
import { usePluginHost } from "./host"
/** Development only: reloads the built-in extensions whose renderer code or English copy changed. */
export default function ExtensionHotReload() {
const host = useExtensionHost()
/** Development only: reloads the built-in plugins whose renderer code or English copy changed. */
export default function PluginHotReload() {
const host = usePluginHost()
makeEventListener(window, BUILTINS_UPDATED, (event) => {
if (!(event instanceof CustomEvent)) return
const next: readonly Definition[] = event.detail
const next: readonly Entry[] = event.detail
next.forEach((definition) => {
const current = host.definitions().find((item) => item.id === definition.id)
@ -23,11 +23,11 @@ export default function ExtensionHotReload() {
}
// Unchanged modules keep their URL, so importing them again returns the same module.
async function changed(current: Definition, next: Definition) {
async function changed(current: Entry, next: Entry) {
if (current.i18n?.en !== next.i18n?.en) return true
if (!current.renderer || !next.renderer) return current.renderer !== next.renderer
const [before, after] = await Promise.all([current.renderer().catch(() => undefined), next.renderer()])
if (!current.windowEntry || !next.windowEntry) return current.windowEntry !== next.windowEntry
const [before, after] = await Promise.all([current.windowEntry().catch(() => undefined), next.windowEntry()])
return before?.default !== after.default
}

View file

@ -15,8 +15,7 @@ import type { Schema } from "effect"
import { useDialog } from "@opencode/ui/context/dialog"
import { base64Encode } from "@opencode/util/encode"
import {
Panel,
type Build,
type App,
type Layout,
type MountedSession,
type OpenOptions,
@ -27,9 +26,8 @@ import {
type SessionScreen,
type Storage,
type StorageScope,
type StoreFrom,
type StoreOptions,
} from "@opencode/gui-extensions/sdk"
} from "@opencode/plugin/gui"
import { BuiltinPanel, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin"
import { usePlatform } from "@/runtime/platform/platform"
import { same } from "@/runtime/persistence/equality"
import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage"
@ -49,11 +47,19 @@ import { useLanguage } from "@/runtime/i18n/language"
import { closedEntry, createClosedTabs } from "./closed-tabs"
import { panelsMoving } from "@/shell/panel-motion"
import { createEmbeds } from "./embeds"
import { useExtensionHost, type HostApiFactories } from "./host"
import { usePluginHost, type HostApiFactories } from "./host"
import { createLocatedWrites } from "./located"
import { createSessionPanelMenu } from "./panel-menu"
import type { Region } from "./panels"
import { deferredHandle, globalStoreTarget, persistedHandle, storeImports, storeName } from "./stores"
import {
deferredHandle,
globalStoreTarget,
persistedHandle,
renamedFrom,
renamedStoreName,
storeImports,
storeName,
} from "./stores"
type Attached = {
sessions: Accessor<readonly SessionRef[]>
@ -63,7 +69,7 @@ type Attached = {
/** Records a session-scoped store so layout pruning drops it with the session. */
scoped: (name: string) => void
layout: Omit<Layout, "narrow" | "settings" | "project" | "draft" | "command" | "stored"> & {
stored(extension: string, session: SessionRef): readonly string[]
stored(plugin: string, session: SessionRef): readonly string[]
}
settings: (page?: string) => void
project: (server: string, title: string) => void
@ -115,13 +121,13 @@ export function createHostApis() {
early
.splice(0)
.forEach(
(run) => void Promise.try(() => run(value)).catch((cause: unknown) => console.error("[extension]", cause)),
(run) => void Promise.try(() => run(value)).catch((cause: unknown) => console.error("[plugin]", cause)),
),
)
}
const embeds = createEmbeds({
bridge: platform.extensions,
bridge: platform.plugins,
zoom: () => platform.webviewZoom?.() ?? 1,
dialog: () => !!dialog.active,
moving: panelsMoving,
@ -129,39 +135,47 @@ export function createHostApis() {
// A server or session store's key needs the server's scope, which the mounted interface provides.
const target = (
extension: string,
plugin: string,
key: string,
scope: Exclude<StorageScope, "global">,
from: StoreFrom | readonly StoreFrom[] | undefined,
from: BuiltinStoreFrom | readonly BuiltinStoreFrom[] | undefined,
builtin: boolean,
connected: Attached,
) => {
const name = storeName(extension, key)
const name = storeName(plugin, key)
const renamed = renamedStoreName(plugin, key)
// Only a built-in stored values before the rename.
const older = (at: { readonly storage?: string; readonly key: string }) => (builtin ? [renamedFrom(at)] : [])
if ("session" in scope) {
const location = scope.session.location
if (!location) throw new Error("Session storage requires a session location")
// Pruning a session drops its value under both names.
connected.scoped(name)
connected.scoped(renamed)
const server = connected.scope(scope.session.server.id)
const directory = base64Encode(location.directory)
const session = SessionStateKey.from(server, SessionRouteKey.fromRoute(directory, scope.session.id))
const at = (store: string) => Persist.serverSession(server, directory, scope.session.id, store)
return {
...Persist.serverSession(server, directory, scope.session.id, name),
copyFrom: storeImports(from, session),
}
return { ...at(name), copyFrom: [...older(at(renamed)), ...storeImports(from, session)] }
}
const copyFrom = storeImports(from)
const server = connected.scope(scope.server)
const directory = scope.directory
if (!scope.directory) return { ...Persist.serverGlobal(connected.scope(scope.server), name), copyFrom }
const at = (store: string) =>
directory === undefined
? Persist.serverGlobal(server, store)
: Persist.serverWorkspace(server, base64Encode(directory), store)
return { ...Persist.serverWorkspace(connected.scope(scope.server), base64Encode(scope.directory), name), copyFrom }
return { ...at(name), copyFrom: [...older(at(renamed)), ...storeImports(from)] }
}
const apis: HostApiFactories = {
storage: (extension, owner) => ({
store<S extends Schema.ConstraintCodec<object, unknown>>(key: string, options: StoreOptions<S>) {
storage: (plugin, owner, _context, _register, builtin) => ({
store<S extends Schema.ConstraintCodec<object, unknown>>(key: string, options: BuiltinStoreOptions<S>) {
const open = (at: Parameters<typeof persisted>[0]) => {
const pair = persisted(at, options.schema, options.initial, platform)
@ -172,10 +186,10 @@ export function createHostApis() {
// Persistence owns effects and resources; code after an await in setup has no owner.
return runWithOwner(getOwner() ?? owner, () => {
if (!scope || scope === "global") return open(globalStoreTarget(extension, key, options.from))
if (!scope || scope === "global") return open(globalStoreTarget(plugin, key, options.from, builtin))
const scoped = (connected: Attached | undefined) =>
connected && open(target(extension, key, scope, options.from, connected))
connected && open(target(plugin, key, scope, options.from, builtin, connected))
// A server store opens once the interface mounts. A session store also waits for the session's location, and
// opens again in a new directory; the store a run opened disposes with the next run.
@ -191,11 +205,11 @@ export function createHostApis() {
})!
},
memory<T extends object>(key: string, options: { readonly initial: T }) {
const name = `${extension}.${key}`
const name = `${plugin}.${key}`
const existing = memory.get(name)
if (existing) {
// SAFETY: a memory key is one extension's store, which that extension always opens with the same shape.
// SAFETY: a memory key is one plugin's store, which that plugin always opens with the same shape.
return existing as readonly [Store<T>, (mutation: (draft: T) => void) => void]
}
@ -210,10 +224,10 @@ export function createHostApis() {
const scope = options?.scope
if (!scope || scope === "global")
return removePersisted(globalStoreTarget(extension, key, options?.from), platform)
return removePersisted(globalStoreTarget(plugin, key, options?.from, builtin), platform)
const run = (connected: Attached) =>
removePersisted(target(extension, key, scope, options?.from, connected), platform)
removePersisted(target(plugin, key, scope, options?.from, builtin, connected), platform)
// A session's store is found through its location: the removal waits for it, as layout writes do.
write((connected) =>
@ -246,7 +260,6 @@ export function createHostApis() {
platform.platform === "desktop"
? {
os: platform.os ?? "linux",
window: platform.windowID,
zoom: () => platform.webviewZoom?.() ?? 1,
launch: (path, app) => platform.openPath?.(path, app) ?? Promise.resolve(),
reveal: (path) => platform.revealPath?.(path) ?? Promise.resolve(false),
@ -254,12 +267,13 @@ export function createHostApis() {
forceFocus: (enabled) => platform.setForceFocus?.(enabled) ?? Promise.resolve(),
}
: undefined,
build: () => ({
app: () => ({
name: "opencode",
version: platform.version ?? "",
// SAFETY: the build sets VITE_OPENCODE_CHANNEL to one of the release channels, or leaves it unset locally.
channel: (import.meta.env.VITE_OPENCODE_CHANNEL ?? "local") as Build["channel"],
channel: (import.meta.env.VITE_OPENCODE_CHANNEL ?? "local") as App["channel"],
platform: platform.platform,
packaged: platform.extensions?.packaged ?? false,
packaged: platform.plugins?.packaged ?? false,
}),
locale: () => ({
locale: language.intl,
@ -281,7 +295,7 @@ export function createHostApis() {
list: () => current()?.servers() ?? [],
get: (id) => current()?.server(id),
}),
workspaces: (_extension, _owner, _context, register) => ({
workspaces: (_plugin, _owner, _context, register) => ({
on(_event, handler) {
removed.add(handler)
@ -302,7 +316,7 @@ export function createHostApis() {
},
}),
// Before the interface mounts, reads return what an empty layout holds and writes wait for it.
layout: (extension) => ({
layout: (plugin) => ({
narrow,
ready: () => current()?.layout.ready() ?? false,
open: (key, session, options) => write((value) => value.layout.open(key, session, options)),
@ -310,7 +324,7 @@ export function createHostApis() {
toggle: (key, session) => write((value) => value.layout.toggle(key, session)),
hide: (key, session) => write((value) => value.layout.hide(key, session)),
state: (key, session) => current()?.layout.state(key, session) ?? "closed",
stored: (session) => current()?.layout.stored(extension, session) ?? [],
stored: (session) => current()?.layout.stored(plugin, session) ?? [],
side: {
opened: (session) => current()?.layout.side.opened(session) ?? false,
toggle: (session) => write((value) => value.layout.side.toggle(session)),
@ -363,17 +377,17 @@ export function createHostApis() {
export type HostApis = ReturnType<typeof createHostApis>
export { ExtensionAttachmentProvider, useExtensionAttachment } from "./attachment"
export { PluginAttachmentProvider, usePluginAttachment } from "./attachment"
/** Builds the session and layout attachment before readiness; its `attach` connects HostApis as the routes render. */
export function createExtensionAttachment(apis: HostApis) {
export function createPluginAttachment(apis: HostApis) {
const global = useGlobal()
const tabs = useTabs()
const layout = useLayout()
const route = useCurrentRoute()
const settings = useSettings()
const surface = useSettingsSurface()
const host = useExtensionHost()
const host = usePluginHost()
const command = useCommand()
const location = useLocation()
const menu = createSessionPanelMenu()
@ -589,11 +603,11 @@ export function createExtensionAttachment(apis: HostApis) {
// a new token, so a region reopened any other way belongs to the user.
const openedFor = new WeakMap<object, string>()
// Keys are `${extension}:${tab id}`.
// Keys are `${plugin}:${tab id}`.
const provider = (key: string) => {
const extension = key.slice(0, key.indexOf(":"))
const plugin = key.slice(0, key.indexOf(":"))
return host.items(Panel).find((item) => item.extension === extension)
return host.items(BuiltinPanel).find((item) => item.plugin === plugin)
}
const mountedSession = (session: SessionRef) => {
@ -632,10 +646,10 @@ export function createExtensionAttachment(apis: HostApis) {
return untrack(() =>
host
.items(Panel)
.items(BuiltinPanel)
.filter((item) => item.value.region === "side")
.flatMap((item) => {
const prefix = `${item.extension}:`
const prefix = `${item.plugin}:`
const open = stored.flatMap((key) => (key.startsWith(prefix) ? [key.slice(prefix.length)] : []))
return item.value
@ -692,7 +706,7 @@ export function createExtensionAttachment(apis: HostApis) {
const first = known.some((entry) => entry.key === key && entry.tab.first)
batch(() => {
if (narrow() && !options?.background) {
if (item?.value.mobile) selectMobile(session, `${item.extension}:${item.value.id}`)
if (item?.value.mobile) selectMobile(session, `${item.plugin}:${item.value.id}`)
// A tab its panel does not list, or a transient one, stays unstored: the open only selects the panel's view.
if (mountedSession(session) && !known.some((entry) => entry.key === key && !entry.tab.transient)) return
@ -858,7 +872,7 @@ export function createExtensionAttachment(apis: HostApis) {
matches: command.matches,
servers: () => global.servers.list().map(ServerConnection.key),
server,
// SAFETY: an extension names a page it contributed through `SettingsPage`, which settings lists as an extension tab.
// SAFETY: a plugin names a page it contributed through `SettingsPage`, which settings lists as a plugin tab.
settings: (page) => surface.open(page as Parameters<typeof surface.open>[0]),
layout: {
ready: layout.ready,
@ -867,11 +881,11 @@ export function createExtensionAttachment(apis: HostApis) {
toggle,
hide,
state,
stored(extension, session) {
stored(plugin, session) {
const value = stateKey(session)
if (!value) return []
const prefix = `${extension}:`
const prefix = `${plugin}:`
return layout.panel
.state(value)
@ -898,7 +912,7 @@ export function createExtensionAttachment(apis: HostApis) {
return {
/**
* Mounts the interface for the HostApis; returns its detach. Called as the routes first render, which waits for
* every extension to settle, so writes and dialogs made before then apply after that render.
* every plugin to settle, so writes and dialogs made before then apply after that render.
*/
attach: () => apis.attach(mounted),
/** The routed `MountedSession`. */
@ -950,7 +964,7 @@ export function createExtensionAttachment(apis: HostApis) {
if (routedView() === view) setRoutedView(undefined)
}
},
/** Starts loading every extension's declared session stores for a session the screen routes. */
/** Starts loading every plugin's declared session stores for a session the screen routes. */
preload(view: MountedSession) {
untrack(() => host.preload(view))
},

View file

@ -7,7 +7,6 @@ import {
createRenderEffect,
createResource,
createRoot,
createSignal,
ErrorBoundary,
getOwner,
on,
@ -21,66 +20,74 @@ import {
type ParentProps,
} from "solid-js"
import { createStore } from "solid-js/store"
import { LifetimeContext, liveAccessor, PluginContext, type Entry } from "@opencode/plugin/gui/host"
import type { BuiltinCatalog, BuiltinContext } from "@opencode/plugin/gui/builtin"
import { Predicate } from "effect"
import { useDialog } from "@opencode/ui/context/dialog"
import { pluralCategory, resolveTemplate } from "@opencode/ui/context/i18n"
import {
ExtensionContext,
LifetimeContext,
LinkHandler,
Live,
type BaseContext,
type Catalog,
type Cleanup,
type Context,
type Contract,
type Definition,
type Dialogs,
type Link,
type Links,
type Live,
type Messages,
type Persisted,
type PluginOptions,
type Registry,
type Ipc,
type IpcClient,
type IpcRef,
type IpcSpec,
type SessionRef,
type SetupContext,
type Token,
} from "@opencode/gui-extensions/sdk"
} from "@opencode/plugin/gui"
import { OpenCode, type OpenCodeClient } from "@opencode/client/promise"
import { useLanguage } from "@/runtime/i18n/language"
import { createSessionStore, whenLoaded } from "./stores"
type Entry = { key: string; registry: string; extension: string; value: Accessor<unknown> }
type Contribution = { key: string; registry: string; plugin: string; value: Accessor<unknown> }
export type Item<T> = { readonly key: string; readonly extension: string; readonly value: T }
export type Item<T> = { readonly key: string; readonly plugin: string; readonly value: T }
/** The context the host builds: every `Setup<D>` of the definition receives it, and contributions read it as `Context`. */
type InstanceContext = SetupContext<Definition> & Context
/**
* The context the host builds: every `Setup<D>` of the definition receives it, and contributions read it as `Context`.
* It has the members only built-ins use, which `builtinContext` reads.
*/
type InstanceContext = SetupContext<Entry> & BuiltinContext
type Instance = {
definition: Definition
definition: Entry
context: InstanceContext
dispose: () => void
/** Runs `fn` when the instance goes away, as a cleanup a setup returns. */
own(fn: Cleanup): Cleanup
/** Opens the declared stores. Settles once the global stores have loaded. */
prepare(): Promise<readonly void[]>
/** Starts loading the declared session stores for a mounted session. */
preload(session: SessionRef): void
}
/** What a plugin's GUI reads of its plugin: its options, and the client of the server that runs it, read each time. */
export type PluginInput = { readonly options: PluginOptions; readonly client: () => OpenCodeClient | undefined }
/** The APIs a window context exposes as properties. */
type HostApis = Omit<Context, keyof BaseContext | "signal" | "provide">
type HostApis = Omit<BuiltinContext, keyof BaseContext | "provide" | "use" | "main">
/**
* Creates one HostApi for an extension instance, on the instance's first read of it. `register` withdraws what it is
* given with the caller's owner, else with the extension.
* Creates one HostApi for a plugin instance, on the instance's first read of it. `register` withdraws what it is
* given with the caller's owner, else with the plugin. `builtin` is true for a plugin that ships with the app.
*/
type HostApiFactory<T> = (
extension: string,
plugin: string,
owner: Owner | null,
context: Context,
register: (fn: Cleanup) => Cleanup,
builtin: boolean,
) => T
/** The HostApis a window provides, by context property. The host itself provides `links` and `dialogs`. */
@ -88,21 +95,18 @@ export type HostApiFactories = {
readonly [K in Exclude<keyof HostApis, "links" | "dialogs">]: HostApiFactory<HostApis[K]>
}
type ExtensionStatus = "loading" | "active" | "failed" | "disabled" | "blocked"
export type PluginStatus = "loading" | "active" | "failed" | "disabled"
/** The last error an extension raised: in its setup or an effect, or while one of its contributions rendered. */
type ExtensionFailure = { readonly phase: "setup" | "render"; readonly error: string }
/** The last error a plugin raised: in its setup or an effect, or while one of its contributions rendered. */
export type PluginFailure = { readonly phase: "setup" | "render"; readonly error: string }
type Absent = Exclude<Live<never>, { readonly status: "active" }>
/** A provider as the gate and `requires` see it: its generation while active, else why it is absent. */
type Provider = Absent | { readonly status: "active"; readonly generation: number }
type HostState = {
entries: Record<string, Entry[] | undefined>
entries: Record<string, Contribution[] | undefined>
contracts: Record<string, number | undefined>
status: Record<string, ExtensionStatus | undefined>
failures: Record<string, ExtensionFailure | undefined>
status: Record<string, PluginStatus | undefined>
failures: Record<string, PluginFailure | undefined>
}
type Stores = Record<string, Persisted<object> | ((session: SessionRef) => Persisted<object>)>
@ -112,22 +116,20 @@ const pending: Absent = { status: "pending" }
const inactive = {
disabled: { status: "inactive", reason: "disabled" },
failed: { status: "inactive", reason: "failed" },
blocked: { status: "inactive", reason: "blocked" },
restarting: { status: "inactive", reason: "restarting" },
} as const satisfies Record<string, Absent>
const HostContext = createContext<ReturnType<typeof createHost>>()
export function useExtensionHost() {
export function usePluginHost() {
const host = useContext(HostContext)
if (!host) throw new Error("Extension host is unavailable")
if (!host) throw new Error("Plugin host is unavailable")
return host
}
type HostInput = {
definitions: readonly Definition[]
definitions: Accessor<readonly Entry[]>
disabled: Accessor<ReadonlySet<string> | undefined>
apis: HostApiFactories
/**
@ -137,13 +139,15 @@ type HostInput = {
whenMounted: (run: () => void) => () => void
/** The renderer client of an Ipc while it is available; omitted where there is no main process. */
ipc?: (token: Ipc) => IpcClient<IpcSpec> | undefined
/** What a plugin's GUI reads of its plugin: its options, and the client of the server that runs it. */
plugin?: (id: string) => PluginInput | undefined
/** How many times an Ipc became available. Reactive. */
generation?: (token: Ipc) => number
/** An extension's main entry failed. Reactive. */
/** A plugin's main entry failed. Reactive. */
failed?: (id: string) => boolean
}
export function ExtensionHostProvider(props: ParentProps<HostInput>) {
export function PluginHostProvider(props: ParentProps<HostInput>) {
const host = createHost(props)
return <HostContext.Provider value={host}>{props.children}</HostContext.Provider>
@ -163,90 +167,52 @@ function createHost(input: HostInput) {
const sequence = { value: 0 }
// An entry that finishes loading after the host is gone must not create a root nothing disposes.
const lifetime = { disposed: false }
// The current load of each extension. Deactivating drops it and a reload replaces it, so an older load
// The current load of each plugin. Deactivating drops it and a reload replaces it, so an older load
// neither sets up nor reports a failure over its replacement.
const loads = new Map<string, object>()
// The extension that provides a token: the one declaring it in `provides`, else the one whose id prefixes it.
// The plugin that provides a token: the one whose id the token's id is, or prefixes.
const providers = new Map<string, string | undefined>()
const all = input.definitions
const providerOf = (id: string) => {
if (providers.has(id)) return providers.get(id)
const current = providers.get(id)
const found =
input.definitions.find((definition) =>
Object.values(definition.provides ?? {}).some((token) => token.id === id),
) ?? input.definitions.find((definition) => definition.id === id || id.startsWith(`${definition.id}.`))
if (current) return current
providers.set(id, found?.id)
// Tracked while unresolved: a plugin that joins later resolves its readers.
const definitions = all()
const found = definitions.find((definition) => owns(definition.id, id))
if (found) providers.set(id, found.id)
return found?.id
}
// Why a token has no active provider. Main-side providers report through the installed list.
const absent = (id: string, generation: number, main: boolean): Absent => {
const extension = providerOf(id)
const absent = (id: string, main: boolean): Absent => {
const plugin = providerOf(id)
if (!extension) return inactive.disabled
if (!plugin) return inactive.disabled
if (main ? input.disabled()?.has(extension) : state.status[extension] === "disabled") return inactive.disabled
if (main ? input.disabled()?.has(plugin) : state.status[plugin] === "disabled") return inactive.disabled
if (main ? input.failed?.(extension) : state.status[extension] === "failed") return inactive.failed
// A blocked provider cannot offer its own contracts either, so hard-dependency chains settle as unavailable.
if (!main && state.status[extension] === "blocked") return inactive.blocked
if (main ? input.failed?.(plugin) : state.status[plugin] === "failed") return inactive.failed
// A renderer provider that is up but does not provide the token (e.g. on this platform) is not coming.
if (!main && state.status[extension] === "active") return inactive.disabled
if (!main && state.status[plugin] === "active") return inactive.disabled
return generation > 0 ? inactive.restarting : pending
return pending
}
const contractLive = (token: Contract<unknown>): Live<unknown> => {
void state.contracts[token.id]
return provided.get(token.id)?.live ?? absent(token.id, generations.get(token.id) ?? 0, false)
return provided.get(token.id)?.live ?? absent(token.id, false)
}
// Full Ipc tokens by id. A reference (`Ipc.ref`) carries no spec and resolves through the full token once code
// in this window uses it; until then it is absent, as pending as its provider allows.
const [known, setKnown] = createSignal<ReadonlyMap<string, Ipc>>(new Map())
const learn = (token: Token) => {
if (token.kind !== "ipc" || !token.spec || untrack(known).has(token.id)) return
setKnown((map) => new Map(map).set(token.id, token))
}
const resolve = (token: Ipc | IpcRef) => (token.spec ? token : known().get(token.id))
// One object per Ipc generation, so reading a provider allocates nothing while it is unchanged.
const actives = new Map<string, Provider & { readonly status: "active" }>()
const providerState = (token: Token): Provider => {
if (token.kind === "contract") return contractLive(token)
if (!input.ipc) return inactive.disabled
const full = resolve(token)
if (!full || !input.ipc(full)) return absent(token.id, full ? (input.generation?.(full) ?? 0) : 0, true)
const generation = input.generation?.(full) ?? 1
const cached = actives.get(token.id)
if (cached?.generation === generation) return cached
const active = { status: "active", generation } as const
actives.set(token.id, active)
return active
}
const satisfied = (definition: Definition) =>
Object.values(definition.requires ?? {}).every((token) => untrack(() => providerState(token)).status === "active")
// Reuses each item object while its value is unchanged so keyed renders do not remount.
const createItems = (id: string) => {
const cache = new Map<string, Item<unknown>>()
@ -262,7 +228,7 @@ function createHost(input: HostInput) {
if (previous?.value === value) return [previous]
const item = { key: entry.key, extension: entry.extension, value }
const item = { key: entry.key, plugin: entry.plugin, value }
cache.set(entry.key, item)
@ -326,14 +292,14 @@ function createHost(input: HostInput) {
...input.apis,
links: () => links,
// Bound to the instance that asked, so an older async call after a disable or reload opens and closes nothing.
dialogs: (extension, _, context, register): Dialogs => ({
dialogs: (plugin, _, context, register): Dialogs => ({
open(render, options) {
const id = `extension:${extension}:${sequence.value++}`
const id = `plugin:${plugin}:${sequence.value++}`
const waiting = { cancel: () => {} }
// This open alone: once it aborts, a deferred open neither mounts nor replaces another dialog.
const opening = new AbortController()
// Each handle names its own dialog, so it never closes one another extension or instance opened. Closing a
// Each handle names its own dialog, so it never closes one another plugin or instance opened. Closing a
// dialog that still waits for the app interface, or for its deferred open, cancels it.
const close = () => {
abort(opening)
@ -345,7 +311,7 @@ function createHost(input: HostInput) {
if (context.signal.aborted) return handle
// Closes this dialog, not whichever is on top, when the extension or the scope that opened it goes away.
// Closes this dialog, not whichever is on top, when the plugin or the scope that opened it goes away.
const release = register(close)
// A dialog opened before the app interface mounts, as during setup, shows after its first render: never behind
@ -362,21 +328,19 @@ function createHost(input: HostInput) {
fallback={(error) => {
onMount(() => {
dialog.close(id)
fail(extension, error, "render")
fail(plugin, error, "render")
})
return null
}}
>
<ExtensionContext.Provider value={context}>
{untrack(() => render(handle))}
</ExtensionContext.Provider>
<PluginContext.Provider value={context}>{untrack(() => render(handle))}</PluginContext.Provider>
</ErrorBoundary>
)
},
undefined,
id,
// The stack mounts in a later transition. Its handle, its owner or the extension ending before then keeps
// The stack mounts in a later transition. Its handle, its owner or the plugin ending before then keeps
// it closed.
AbortSignal.any([opening.signal, context.signal]),
),
@ -388,23 +352,14 @@ function createHost(input: HostInput) {
}),
} satisfies { readonly [K in keyof HostApis]: HostApiFactory<HostApis[K]> }
const activate = async (definition: Definition) => {
const load = definition.renderer
const activate = async (definition: Entry) => {
const load = definition.windowEntry
// A disabled extension, e.g. one reloaded from settings, stays disabled: marking it loading would make the
// A disabled plugin, e.g. one reloaded from settings, stays disabled: marking it loading would make the
// enable watcher skip it later. Before the list loads nothing activates; the watcher starts each entry then.
if (!load || input.disabled()?.has(definition.id) !== false) return
const unavailable = Object.values(definition.requires ?? {}).some((token) => {
const provider = untrack(() => providerState(token))
return blocked(provider)
})
setState("status", definition.id, unavailable ? "blocked" : "loading")
// Waits for its hard contracts; the requirement watcher starts it once they are active.
if (!satisfied(definition)) return
setState("status", definition.id, "loading")
const attempt = {}
const current = () => loads.get(definition.id) === attempt
@ -437,8 +392,8 @@ function createHost(input: HostInput) {
instances.set(definition.id, instance)
// Setup and every scope under it read the extension's context, e.g. `createKeyed` with a token.
if (root) root.context = { ...root.context, [ExtensionContext.id]: instance.context }
// Setup and every scope under it read the plugin's context, e.g. `createKeyed` with a token.
if (root) root.context = { ...root.context, [PluginContext.id]: instance.context }
const crash = (cause: unknown) => {
if (instances.get(definition.id) !== instance) return
@ -450,21 +405,24 @@ function createHost(input: HostInput) {
}
// SAFETY: the host context implements the parameter of every `Setup<D>` of this definition.
const setup = module.default as (ctx: InstanceContext) => void
const setup = module.default as (ctx: InstanceContext) => Cleanup | void
const start = () =>
void Promise.try(() =>
// Errors from the extension's own effects, at setup or later, fail the extension and nothing else.
// Errors from the plugin's own effects, at setup or later, fail the plugin and nothing else.
catchError(
() =>
untrack(() => {
const returned = setup(instance.context)
// A returned cleanup runs when the plugin goes away, as server and TUI plugins' do.
if (Predicate.isFunction(returned)) return void instance.own(returned)
if (!Predicate.isPromiseLike(returned)) return
// Do not await invalid setup, but consume its eventual rejection after the instance is aborted.
void Promise.resolve(returned).catch((cause: unknown) =>
console.error(`[extension] ${definition.id}`, cause),
console.error(`[plugin] ${definition.id}`, cause),
)
throw new Error(
"Window setup must be synchronous. Start async work with createKeyed or createLatest.",
@ -478,7 +436,7 @@ function createHost(input: HostInput) {
setState("status", definition.id, "active")
}, crash)
// Setup runs synchronously inside the extension root so its effects and memos are owned.
// Setup runs synchronously inside the plugin root so its effects and memos are owned.
if (windowStores(definition).length === 0) return start()
// Global stores load in their storage namespace's one read before setup, so setup reads them as plain values.
@ -489,13 +447,8 @@ function createHost(input: HostInput) {
)
}
const createInstance = (
definition: Definition,
dispose: () => void,
root: Owner | null,
initial: Messages,
): Instance => {
const extension = definition.id
const createInstance = (definition: Entry, dispose: () => void, root: Owner | null, initial: Messages): Instance => {
const plugin = definition.id
const controller = new AbortController()
const cleanups = new Set<Cleanup>()
@ -507,10 +460,10 @@ function createHost(input: HostInput) {
// Promise.try runs the cleanup synchronously and isolates a throw from the others.
const release = (fn: Cleanup) =>
void Promise.try(fn).catch((cause: unknown) => console.error(`[extension] ${extension}`, cause))
void Promise.try(fn).catch((cause: unknown) => console.error(`[plugin] ${plugin}`, cause))
const own = (fn: Cleanup): Cleanup => {
// Work that outlives the extension, e.g. a promise callback, is released as soon as it registers.
// Work that outlives the plugin, e.g. a promise callback, is released as soon as it registers.
if (controller.signal.aborted) {
release(fn)
@ -526,10 +479,10 @@ function createHost(input: HostInput) {
return cleanup
}
// The extension went away, or the scope registering (e.g. through a captured owner) already ended.
// The plugin went away, or the scope registering (e.g. through a captured owner) already ended.
const late = () => controller.signal.aborted || !!useContext(LifetimeContext)?.ended
// Withdrawn with the current owner, or with the extension when there is none (after an await).
// Withdrawn with the current owner, or with the plugin when there is none (after an await).
const register = (fn: Cleanup): Cleanup => {
if (late()) {
release(fn)
@ -548,15 +501,14 @@ function createHost(input: HostInput) {
const clients = new Map<string, { client: IpcClient<IpcSpec>; live: Live<unknown> }>()
// One accessor per token, and one Live object per transition, so readers re-run only when the provider changes.
const ipcLive = (token: Ipc | IpcRef): Live<unknown> => {
const ipcLive = (token: Ipc): Live<unknown> => {
if (!input.ipc) return inactive.disabled
const full = resolve(token)
const client = full && input.ipc(full)
const client = input.ipc(token)
if (!full || !client) return absent(token.id, full ? (input.generation?.(full) ?? 0) : 0, true)
if (!client) return absent(token.id, true)
const generation = input.generation?.(full) ?? 1
const generation = input.generation?.(token) ?? 1
const cached = clients.get(token.id)
if (cached?.client === client && cached.live.status === "active" && cached.live.generation === generation)
@ -580,51 +532,134 @@ function createHost(input: HostInput) {
if (existing) return existing
const read = Live.accessor(token.kind === "contract" ? () => contractLive(token) : () => ipcLive(token))
const read = liveAccessor(token.kind === "contract" ? () => contractLive(token) : () => ipcLive(token))
lives.set(token.id, read)
return read
}
const value = (read: Accessor<Live<unknown>>) => {
const current = read()
const mains = new Map<string, IpcClient<IpcSpec>>()
return current.status === "active" ? current.value : undefined
}
// The client of the plugin's own Ipc: calls wait while its main entry starts and reject once it cannot answer.
const mainClient = (token: Ipc): IpcClient<IpcSpec> => {
if (!owns(plugin, token.id)) throw new Error(`${plugin} calls only its own main entry, not Ipc "${token.id}"`)
// A declared reference resolves once the chunk that loads its full token passes it to `load`, here and in other
// extensions.
const used = (token: Token) => {
const read = liveOf(token)
const existing = mains.get(token.id)
if (token.kind !== "ipc" || token.spec) return read
if (existing) return existing
return Object.assign(read, {
load(full: Ipc) {
if (full.id !== token.id) throw new Error(`Ipc "${full.id}" does not resolve the reference "${token.id}"`)
learn(full)
// SAFETY: an Ipc's active value is the client `ipcLive` builds for it.
const read = liveOf(token) as Accessor<Live<IpcClient<IpcSpec>>>
return read
const unavailable = (reason: string) => new Error(`Ipc "${token.id}" is unavailable: ${reason}`)
const ready = (): Promise<IpcClient<IpcSpec>> => {
// A client kept past the plugin's instance never reaches main again, even while main still provides.
if (controller.signal.aborted) return Promise.reject(unavailable("the plugin went away"))
const current = untrack(read)
if (current.status === "active") return Promise.resolve(current.value)
if (current.status === "inactive") return Promise.reject(unavailable(current.reason))
return new Promise((resolve, reject) =>
runWithOwner(owner, () =>
createRoot((dispose) => {
const stop = () => {
controller.signal.removeEventListener("abort", aborted)
dispose()
}
const aborted = () => {
stop()
reject(unavailable("the plugin went away"))
}
controller.signal.addEventListener("abort", aborted)
createRenderEffect(
on(
read,
(live) => {
if (live.status === "pending") return
stop()
if (live.status === "active") return resolve(live.value)
reject(unavailable(live.reason))
},
{ defer: true },
),
)
}),
),
)
}
const methods = Object.fromEntries(
Object.keys(token.spec.methods).map((name) => [
name,
(...args: readonly unknown[]) =>
ready().then((client) => {
const method = Predicate.hasProperty(client, name) ? client[name] : undefined
if (!isMethod(method)) throw unavailable(`no method "${name}"`)
return method(...args)
}),
]),
)
const client = Object.assign(methods, {
state() {
const live = read()
return live.status === "active" ? live.value.state() : undefined
},
on(name: string, listener: Parameters<IpcClient<IpcSpec>["on"]>[1]) {
// Follows the main entry across restarts: each active client gets the listener, removed when it changes.
return register(
runWithOwner(root, () =>
createRoot((dispose) => {
createRenderEffect(() => {
const live = read()
if (live.status === "active") live.value.on(name, listener)
})
return dispose
}),
) ?? (() => {}),
)
},
})
// SAFETY: `methods` has one function per method of the token's spec, as `IpcClient` types it.
const typed = client as IpcClient<IpcSpec>
mains.set(token.id, typed)
return typed
}
// `ctx.uses` holds the extension's own tokens too; `Extension.define` refuses a key that names two tokens.
const usable = { ...definition.provides, ...definition.uses }
Object.values(usable).forEach(learn)
Object.values(definition.requires ?? {}).forEach(learn)
const stores: Stores = {}
const gui = input.plugin?.(plugin)
const context = {
id: extension,
id: plugin,
options: gui?.options ?? {},
get client() {
return gui?.client() ?? unavailableClient()
},
signal: controller.signal,
add<T>(registry: Registry<T>, item: T | (() => T | undefined)) {
if (late()) return () => {}
// Promise callbacks may have no owner; fall back to the extension root.
// Promise callbacks may have no owner; fall back to the plugin root.
const read =
// SAFETY: a function item is the SDK's reactive form; registries take no function values.
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- see SAFETY above
@ -632,11 +667,11 @@ function createHost(input: HostInput) {
? runWithOwner(getOwner() ?? root, () => createMemo(item as () => T | undefined))
: () => item
const key = `${extension}/${++sequence.value}`
const key = `${plugin}/${++sequence.value}`
setState("entries", registry.id, (entries = []) => [
...entries,
{ key, registry: registry.id, extension, value: read ?? (() => undefined) },
{ key, registry: registry.id, plugin, value: read ?? (() => undefined) },
])
return register(() =>
@ -645,7 +680,9 @@ function createHost(input: HostInput) {
},
list,
provide<T>(token: Contract<T> | Ipc, impl: T) {
if (token.kind === "ipc") throw new Error("Ipcs are provided by an extension's main entry")
if (token.kind === "ipc") throw new Error("Ipcs are provided by a plugin's main entry")
if (!owns(plugin, token.id)) throw new Error(`${plugin} provides only its own contracts, not "${token.id}"`)
if (late()) return () => {}
@ -665,18 +702,15 @@ function createHost(input: HostInput) {
setState("contracts", token.id, (version = 0) => version + 1)
})
},
uses: Object.fromEntries(Object.entries(usable).map(([name, token]) => [name, used(token)])),
// The host starts the extension only while every hard contract is active, and restarts it when one changes.
requires: Object.fromEntries(
Object.entries(definition.requires ?? {}).map(([name, token]) => [name, untrack(() => value(liveOf(token)))]),
),
use: liveOf,
main: mainClient,
stores,
t(key: string, params?: Record<string, string | number | boolean>) {
const template = messages()[key]
if (template !== undefined) return resolveTemplate(template, params)
// SAFETY: a key the extension's catalog lacks is one of the app's shared keys, such as `common.*`.
// SAFETY: a key the plugin's catalog lacks is one of the app's shared keys, such as `common.*`.
return language.t(key as Parameters<typeof language.t>[0], params)
},
plural(key: string, count: number, params?: Record<string, string | number | boolean>) {
@ -685,7 +719,7 @@ function createHost(input: HostInput) {
if (template !== undefined) return resolveTemplate(template, { ...params, count })
// SAFETY: a key the extension's catalog lacks is one of the app's shared keys, such as `common.*`.
// SAFETY: a key the plugin's catalog lacks is one of the app's shared keys, such as `common.*`.
return language.plural(key as Parameters<typeof language.plural>[0], count, params)
},
}
@ -701,7 +735,7 @@ function createHost(input: HostInput) {
{
enumerable: true,
get() {
if (!created.has(name)) created.set(name, create(extension, root, typed, register))
if (!created.has(name)) created.set(name, create(plugin, root, typed, register, !gui))
return created.get(name)
},
@ -720,12 +754,19 @@ function createHost(input: HostInput) {
return {
definition,
context: typed,
own,
prepare() {
const storage = typed.storage
const loaded = windowStores(definition).flatMap(([name, declaration]) => {
const options = {
schema: declaration.schema,
initial: declaration.initial,
from: declaration.builtinFrom ?? declaration.from,
}
if (declaration.scope === "global") {
const handle = storage.store(name, { ...declaration, scope: "global" })
const handle = storage.store(name, { ...options, scope: "global" })
stores[name] = handle
@ -733,7 +774,7 @@ function createHost(input: HostInput) {
}
const store = createSessionStore({
open: (session) => storage.store(name, { ...declaration, scope: { session } }),
open: (session) => storage.store(name, { ...options, scope: { session } }),
owner: root,
sessions: typed.sessions,
})
@ -751,17 +792,17 @@ function createHost(input: HostInput) {
preload: (session) => sessions.forEach((store) => store.get(session)),
dispose() {
abort(controller)
// One batch: every contribution and contract of the extension disappears in the same frame.
// One batch: every contribution and contract of the plugin disappears in the same frame.
batch(() => {
Array.from(cleanups).reverse().forEach(release)
cleanups.clear()
Object.entries(state.entries).forEach(([registry, entries]) => {
if (!entries?.some((entry) => entry.extension === extension)) return
if (!entries?.some((entry) => entry.plugin === plugin)) return
setState("entries", registry, (list = []) => list.filter((entry) => entry.extension !== extension))
setState("entries", registry, (list = []) => list.filter((entry) => entry.plugin !== plugin))
})
})
// A throwing onCleanup in the extension's root must not stop the host disposing the rest.
// A throwing onCleanup in the plugin's root must not stop the host disposing the rest.
release(dispose)
},
}
@ -778,10 +819,10 @@ function createHost(input: HostInput) {
instance.dispose()
}
const fail = (id: string, cause: unknown, phase: ExtensionFailure["phase"] = "setup") => {
console.error(`[extension] ${id}`, cause)
const fail = (id: string, cause: unknown, phase: PluginFailure["phase"] = "setup") => {
console.error(`[plugin] ${id}`, cause)
batch(() => {
// A contribution that fails to render renders nothing; the extension and its other contributions stay.
// A contribution that fails to render renders nothing; the plugin and its other contributions stay.
if (phase === "setup") setState("status", id, "failed")
setState("failures", id, {
@ -791,87 +832,78 @@ function createHost(input: HostInput) {
})
}
const replaced = new Map<string, Definition>()
const latest = (definition: Definition) => replaced.get(definition.id) ?? definition
const replaced = new Map<string, Entry>()
const latest = (definition: Entry) => replaced.get(definition.id) ?? definition
// The startup gate: once every entry settled it stays open, so enabling or reloading an extension later
// never unmounts the app. An entry waiting on a hard contract that is disabled or failed has settled too.
// The definitions the host starts with: the built-ins. Definitions that join later (plugins) never hold the gate.
const initial = new Set(untrack(all))
// The startup gate: once every entry settled it stays open, so enabling or reloading a plugin later
// never unmounts the app.
const ready = createMemo<boolean>(
(settled) =>
settled ||
(!!input.disabled() &&
input.definitions.every((definition) => {
if (!definition.renderer) return true
[...initial].every((definition) => {
if (!definition.windowEntry) return true
const status = state.status[definition.id]
if (status === "active" || status === "failed" || status === "disabled" || status === "blocked") return true
return Object.values(definition.requires ?? {}).some((token) => {
const provider = providerState(token)
return blocked(provider)
})
return status === "active" || status === "failed" || status === "disabled"
})),
false,
)
// `requires` gating: an extension starts once every hard contract is active and restarts with a new generation of
// any of them. Activation is never ordered by the graph; only these extensions wait, and only for their contracts.
input.definitions.forEach((definition) => {
const tokens = Object.values(definition.requires ?? {})
// The definition object each id was last listed with; a new object for a listed id replaces it.
const listed = new Map<string, Entry>()
if (tokens.length === 0) return
const key = createMemo(() => {
const providers = tokens.map(providerState)
if (providers.every((provider) => provider.status === "active"))
return providers.map((provider) => (provider.status === "active" ? provider.generation : 0)).join(",")
return providers.some(blocked) ? "blocked" : undefined
// Forgets everything about a plugin whose definition left or was replaced, so the next pass starts it afresh.
const forget = (id: string) => {
deactivate(id)
replaced.delete(id)
providers.forEach((plugin, token) => {
if (plugin === id) providers.delete(token)
})
setState("status", id, undefined)
setState("failures", id, undefined)
}
createRenderEffect(
on(key, (value) =>
untrack(() =>
batch(() => {
const id = definition.id
deactivate(id)
if (input.disabled()?.has(id) !== false) return
if (value === undefined) return setState("status", id, "loading")
if (value === "blocked") return setState("status", id, "blocked")
void activate(latest(definition))
}),
),
),
)
})
// Establish requirement watchers before activation, including their initial state. Publish every disabled status
// before starting enabled entries, so declaration order cannot leave a hard-dependency chain loading forever.
// Publish every disabled status before starting enabled entries.
createMemo(() => {
const disabled = input.disabled()
const definitions = all()
if (!disabled) return
untrack(() =>
batch(() => {
input.definitions
const ids = new Set(definitions.map((definition) => definition.id))
Array.from(listed.keys()).forEach((id) => {
if (ids.has(id)) return
listed.delete(id)
forget(id)
})
definitions.forEach((definition) => {
const before = listed.get(definition.id)
listed.set(definition.id, definition)
if (before && before !== definition) forget(definition.id)
})
definitions
.filter((definition) => disabled.has(definition.id))
.forEach((definition) => {
deactivate(definition.id)
setState("status", definition.id, "disabled")
// A plugin that is off shows no error from its last run.
setState("failures", definition.id, undefined)
})
input.definitions
definitions
.filter((definition) => !disabled.has(definition.id))
.forEach((definition) => {
if (instances.has(definition.id) || state.status[definition.id] === "loading") return
// A failed plugin waits for Reload or a new revision, as in main.
if (instances.has(definition.id)) return
if (state.status[definition.id] === "loading" || state.status[definition.id] === "failed") return
void activate(latest(definition))
})
@ -891,16 +923,16 @@ function createHost(input: HostInput) {
list,
items,
links,
definitions: () => input.definitions.map(latest),
definitions: () => all().map(latest),
context: (id: string): Context | undefined => instances.get(id)?.context,
fail,
/** Starts loading every active extension's declared session stores for a session that mounts. */
/** Starts loading every active plugin's declared session stores for a session that mounts. */
preload(session: SessionRef) {
instances.forEach((instance) => instance.preload(session))
},
/** `next` replaces the definition, e.g. after a development hot update. */
reload(id: string, next?: Definition) {
const definition = next ?? input.definitions.find((item) => item.id === id)
reload(id: string, next?: Entry) {
const definition = next ?? untrack(all).find((item) => item.id === id)
if (!definition) return
@ -915,27 +947,47 @@ function createHost(input: HostInput) {
}
}
/** The window's declared stores; a `Store.main` store belongs to the main process. */
function windowStores(definition: Definition) {
return Object.entries(definition.stores ?? {}).flatMap(([name, declaration]) =>
declaration.scope === "main" ? [] : [[name, declaration] as const],
)
/** The window's declared stores. */
function windowStores(definition: Entry) {
return Object.entries(definition.stores ?? {})
}
/** A hard dependency that is not coming until its provider or configuration changes. */
function blocked(provider: Provider) {
return provider.status === "inactive" && provider.reason !== "restarting"
/** The client `unavailableClient` made, once a plugin first read it. */
type Unavailable = { client?: OpenCodeClient }
const unavailable: Unavailable = {}
/** The client a plugin reads while the server that runs it is unreachable: every call rejects. */
function unavailableClient() {
return (unavailable.client ??= OpenCode.make({
baseUrl: "http://unavailable.invalid/",
fetch: Object.assign(() => Promise.reject(new Error("The server that runs this plugin is unavailable")), {
preconnect() {},
}),
}))
}
// An Ipc client from the bridge is plain JavaScript; check a method before calling it.
// SAFETY: the method's output schema decodes its reply; the `IpcClient` the plugin holds types it.
// oxlint-disable-next-line anti-slop/no-unknown-returns -- see SAFETY above
function isMethod(value: unknown): value is (...args: readonly unknown[]) => Promise<unknown> {
return Predicate.isFunction(value)
}
/** Whether a plugin owns a token: its id is the plugin's, or is under it (`<plugin>.<name>`). */
function owns(plugin: string, id: string) {
return id === plugin || id.startsWith(`${plugin}.`)
}
/** English merged under the locale's messages. A catalog that fails to load leaves English. */
async function loadMessages(catalog: Catalog | undefined, locale: string): Promise<Messages> {
async function loadMessages(catalog: BuiltinCatalog | undefined, locale: string): Promise<Messages> {
const english = catalog?.en ?? {}
const source = catalog?.[locale]
if (!source || locale === "en") return english
const loaded =
// SAFETY: a catalog entry is either inline messages or the loader of a locale module, as `Catalog` types it.
// SAFETY: a catalog entry is either inline messages or the loader of a locale module, as `BuiltinCatalog` types it.
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- see SAFETY above
typeof source === "function"
? await source().then(

View file

@ -1,8 +1,8 @@
import { createMemo, createResource, onCleanup } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import type { Bridge, Installed } from "@opencode/gui-extensions/sdk/bridge"
import type { Bridge, Installed } from "@opencode/plugin/gui/host"
/** Saved enable preferences and manager metadata; activation and blocked-dependency status belong to the host. */
/** Saved enable preferences and the plugins main lists; activation status belongs to the host. */
export function createInstalled(bridge: Bridge | undefined) {
const [state, setState] = createStore<{ list?: readonly Installed[] }>({})
// A pushed list is newer than the initial reply, so a reply that arrives after one is dropped.
@ -22,14 +22,22 @@ export function createInstalled(bridge: Bridge | undefined) {
if (bridge)
onCleanup(
bridge.on((message) => {
if (message.type !== "extensions") return
if (message.type !== "installed") return
pushed.count++
setState("list", reconcile([...message.list]))
}),
)
return {
enableState: createMemo(() => state.list ?? initial.latest),
// Main lists a plugin only once it read it from the app's own server, so until then the preload rows hold its
// saved setting.
enableState: createMemo(() => {
const list = state.list
if (!list) return initial.latest
return [...(initial.latest ?? []).filter((row) => !list.some((item) => item.id === row.id)), ...list]
}),
list: () => state.list ?? [],
}
}

View file

@ -1,7 +1,7 @@
import { expect, test } from "bun:test"
import { Ipc } from "@opencode/gui-extensions/sdk"
import { Ipc } from "@opencode/plugin/gui"
import { Schema } from "effect"
import type { Bridge, BridgeMessage } from "@opencode/gui-extensions/sdk/bridge"
import type { Bridge, BridgeMessage } from "@opencode/plugin/gui/host"
import { createIpcClients } from "./ipc"
const token: Ipc = { kind: "ipc", id: "fixture", spec: { id: "fixture", methods: {} } }
@ -91,15 +91,12 @@ function fakeBridge() {
capture: async () => undefined,
runMenubarItem: () => {},
configure: () => {},
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
list: async () => [],
enable: async () => {},
disable: async () => {},
reload: async () => {},
install: async () => {},
remove: async () => {},
source: async () => "",
asset: () => "",
},
}

View file

@ -1,8 +1,8 @@
import { batch } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import { Schema } from "effect"
import type { Ipc, IpcCallOptions, IpcClient, IpcSpec } from "@opencode/gui-extensions/sdk"
import type { Bridge } from "@opencode/gui-extensions/sdk/bridge"
import type { Ipc, IpcCallOptions, IpcClient, IpcSpec } from "@opencode/plugin/gui"
import type { Bridge } from "@opencode/plugin/gui/host"
type Codec = NonNullable<IpcSpec["state"]>
@ -19,7 +19,7 @@ type IpcState = {
generations: Record<string, number | undefined>
}
/** Renderer-side clients for the Ipcs that extensions provide in the main process. */
/** Renderer-side clients for the Ipcs that plugins provide in the main process. */
export function createIpcClients(bridge: Bridge | undefined) {
const [state, setState] = createStore<IpcState>({ available: {}, values: {}, generations: {} })
@ -98,16 +98,19 @@ export function createIpcClients(bridge: Bridge | undefined) {
const before = { ...changesOf(token.id) }
void connected.subscribe(token.id).then((result) => {
const after = changesOf(token.id)
void connected
.subscribe(token.id)
.then((result) => {
const after = changesOf(token.id)
batch(() => {
if (after.available === before.available) setAvailable(token.id, result.available)
batch(() => {
if (after.available === before.available) setAvailable(token.id, result.available)
if (after.state === before.state && result.state !== undefined)
setState("values", token.id, decodeState(token.id, result.state))
if (after.state === before.state && result.state !== undefined)
setState("values", token.id, decodeState(token.id, result.state))
})
})
})
.catch((cause: unknown) => console.error(`[plugin] ${token.id}`, cause))
}
const create = (connected: Bridge, token: Ipc): IpcClient<IpcSpec> => {

View file

@ -1,5 +1,5 @@
import { batch, createEffect, createSignal, untrack } from "solid-js"
import type { SessionRef } from "@opencode/gui-extensions/sdk"
import type { SessionRef } from "@opencode/plugin/gui"
/**
* Layout writes find a session's stored layout through its location, which is unknown until the server reports it

View file

@ -1,8 +1,8 @@
import { createContext, onCleanup, useContext } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import type { Bridge, BridgeMenubarItem } from "@opencode/gui-extensions/sdk/bridge"
import type { Bridge, BridgeMenubarItem } from "@opencode/plugin/gui/host"
/** MenubarItem contributions from main extensions, for the in-app menu on Windows and Linux. */
/** MenubarItem contributions from main plugins, for the in-app menu on Windows and Linux. */
export function createMenubarItems(bridge: Bridge | undefined) {
const [state, setState] = createStore<{ items: BridgeMenubarItem[] }>({ items: [] })

View file

@ -2,15 +2,9 @@ import { createMemo, For, lazy, Show, Suspense, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { Tabs } from "@opencode/ui/tabs"
import { Icon } from "@opencode/ui/icon"
import {
Panel,
type PanelSidebar,
type PanelTab,
type MountedSession,
type SessionScreen,
} from "@opencode/gui-extensions/sdk"
import { Panel, type PanelSidebar, type PanelTab, type MountedSession, type SessionScreen } from "@opencode/plugin/gui"
import { useLanguage } from "@/runtime/i18n/language"
import { useExtensionHost } from "./host"
import { usePluginHost } from "./host"
import { panelKey } from "./panel-keys"
import { MobilePanel, type Region, type RegionEntry } from "./panels"
@ -22,9 +16,9 @@ const MobilePanelDrawer = lazy(async () => {
export type MobileEntry = RegionEntry & { readonly mobile: NonNullable<Panel["mobile"]> }
/** Panels that offer a narrow-screen view, keyed `${extension}:${panel id}`. */
/** Panels that offer a narrow-screen view, keyed `${plugin}:${panel id}`. */
export function createMobileViews() {
const host = useExtensionHost()
const host = usePluginHost()
const entries = createMemo(() =>
host.items(Panel).flatMap((item): MobileEntry[] => {
@ -33,9 +27,7 @@ export function createMobileViews() {
if (!mobile) return []
const tab: PanelTab = { id: item.value.id, title: mobile.title }
return [
{ key: panelKey(item.extension, item.value.id), extension: item.extension, tab, provider: item.value, mobile },
]
return [{ key: panelKey(item.plugin, item.value.id), plugin: item.plugin, tab, provider: item.value, mobile }]
}),
)
@ -195,7 +187,7 @@ export function MobileViewTabs(props: {
screen={props.screen}
sidebar={props.sidebar}
visible={store.open}
open={() => props.region.openFor(entry.extension)}
open={() => props.region.openFor(entry.plugin)}
/>
)}
</Show>

View file

@ -0,0 +1,57 @@
import { describe, expect, test } from "bun:test"
import { Command, type Registry } from "@opencode/plugin/gui"
import { pluginDefinition } from "./module"
// One `./gui-experimental` bundle for both processes, as a bundler emits it: requires hoisted to module scope,
// including Electron and Node built-ins that only the main setup uses.
const bundle = `
const sdk = require("@opencode/plugin/gui")
const mainSdk = require("@opencode/plugin/gui/main")
const solid = require("solid-js")
const electron = require("electron")
const fs = require("node:fs")
const app = new electron.BrowserWindow().app.whenReady()
exports.default = sdk.Plugin.define({
i18n: { en: { title: "Notes" } },
setup(ctx) {
const [count] = solid.createSignal(1)
ctx.add(sdk.Command, { id: "open", title: ctx.t("title") + count(), run() {} })
return () => ctx.add(sdk.Command, { id: "closed", title: "", run() {} })
},
main: () => app.then(() => fs.readFileSync("notes.json")),
})
`
describe("plugin GUIs in a window", () => {
test("declare their definition before they start, with the app's module instances and Electron inert", async () => {
const definition = await pluginDefinition("acme", bundle)
const added: { readonly registry: Registry<Command>; readonly item: Command }[] = []
// The host gives the bundle the server plugin's id.
expect(definition.id).toBe("acme")
expect(definition.i18n?.en).toEqual({ title: "Notes" })
const entry = await definition.windowEntry?.()
const ctx = {
add: (registry: Registry<Command>, item: Command) => void added.push({ registry, item }),
t: () => "Notes",
}
// SAFETY: the window setup only calls `add` and `t`, which this stand-in context provides.
const cleanup = entry?.default(ctx as never)
// The bundle's `Command` is the app's own token, so the host recognizes what it contributes.
expect(added[0]?.registry).toBe(Command)
expect(added[0]?.item).toMatchObject({ id: "open", title: "Notes1" })
// The setup's returned cleanup reaches the host.
expect(cleanup).toBeFunction()
})
test("fail only their own entry when they require a module the app does not share", async () => {
const definition = await pluginDefinition("acme", 'require("left-pad"); exports.default = { setup() {} }')
expect(definition.id).toBe("acme")
await expect(definition.windowEntry?.()).rejects.toThrow("left-pad")
})
})

View file

@ -0,0 +1,64 @@
import {
evaluatePluginBundle,
inertModule,
mainOnlyModule,
type PluginModule,
type Entry,
} from "@opencode/plugin/gui/host"
// Plugin bundles share the host's module instances, so tokens, contexts and schemas they import are the same objects
// the host checks against. In a window, the main SDK's name resolves to the window SDK.
const modules = {
effect: () => import("effect"),
"@opencode/plugin/gui": () => import("@opencode/plugin/gui"),
"@opencode/plugin/gui/main": () => import("@opencode/plugin/gui"),
"@opencode/plugin/gui/file": () => import("@opencode/plugin/gui/file"),
"@opencode/plugin/gui/review": () => import("@opencode/plugin/gui/review"),
"@opencode/plugin/gui/browser": () => import("@opencode/plugin/gui/browser"),
"@opencode/plugin/rpc": () => import("@opencode/plugin/rpc"),
"@opencode/schema/rpc": () => import("@opencode/schema/rpc"),
"@opencode/client": () => import("@opencode/client"),
"@opencode/client/effect": () => import("@opencode/client/effect"),
"@opencode/client/solid": () => import("@opencode/client/solid"),
"solid-js": () => import("solid-js"),
"solid-js/web": () => import("solid-js/web"),
"solid-js/store": () => import("solid-js/store"),
} satisfies Record<PluginModule, () => Promise<object>>
/**
* Builds a host `Entry` for a plugin's `./gui-experimental` bundle, read from the desktop app's own server. The
* bundle is evaluated here so the host reads its `Plugin.define` declarations (`os`, `stores`, `i18n`) before it
* activates the plugin. A plugin with only a `main` setup gets an empty window setup, so it still lists as active. It
* takes the server plugin's id. A bundle that fails to evaluate becomes an entry that fails, so Settings > Plugins
* reports it.
*/
export async function pluginDefinition(id: string, code: string): Promise<Entry> {
const loaded = new Map<string, object>(
await Promise.all(Object.entries(modules).map(async ([name, load]) => [name, await load()] as const)),
)
const bundle = await Promise.try(() =>
evaluatePluginBundle(code, {
process: "window",
require: (name) => {
const module = loaded.get(name)
if (module) return module
if (mainOnlyModule(name)) return inertModule(name)
throw new Error(`Plugin GUI bundle requires a module the app does not share: ${name}`)
},
}),
).then(
(value) => ({ ok: true as const, value }),
(cause: unknown) => ({ ok: false as const, cause }),
)
if (!bundle.ok) return { id, windowEntry: () => Promise.reject(bundle.cause) }
const setup = bundle.value.setup
// A setup's returned cleanup reaches the host, which runs it when the plugin goes away.
return { ...bundle.value.definition, id, windowEntry: async () => ({ default: (ctx: never) => setup?.(ctx) }) }
}

View file

@ -20,7 +20,7 @@ import type {
ServerRef,
MountedSession,
SessionScreen,
} from "@opencode/gui-extensions/sdk"
} from "@opencode/plugin/gui"
import { useComments } from "@/composer/comments"
import { useComposerState } from "@/composer/persistence"
import { useServer } from "@/runtime/server/current"
@ -29,7 +29,7 @@ import { sessionInWorkspace, sessionProject, type SessionModel } from "@/session
import { useFile } from "@/workspaces/files/model"
import { useWorkspaceLocation } from "@/workspaces/location"
import { pathKey } from "@/workspaces/path-key"
import { useExtensionAttachment } from "./host-apis"
import { usePluginAttachment } from "./host-apis"
const noTasks: readonly BackgroundTask[] = []
@ -37,7 +37,7 @@ const noTasks: readonly BackgroundTask[] = []
type ObjectRoot = { dispose?: () => void }
/**
* The routed session as extensions see it: one frozen object per routed session, a new one each time the screen
* The routed session as plugins see it: one frozen object per routed session, a new one each time the screen
* routes another session, and the `SessionScreen` that owns the route-following files, comments and composer.
*/
export function createMountedSession(session: SessionModel) {
@ -47,7 +47,7 @@ export function createMountedSession(session: SessionModel) {
const server = useServer()
const servers = useServers()
const location = useWorkspaceLocation()
const attachment = useExtensionAttachment()
const attachment = usePluginAttachment()
// The composer region owns background tasks and is created after the view.
const [background, setBackground] = createSignal<Accessor<readonly BackgroundTask[]>>()
// The screen's composer view, created after this object, says whether it takes quotes and focuses its prompt.

View file

@ -0,0 +1,15 @@
import type { BuiltinPanel } from "@opencode/plugin/gui/builtin"
/** The key the host stores a panel tab under. */
export function panelKey(plugin: string, id: string) {
return `${plugin}:${id}`
}
/** The stored keys the panels map with `BuiltinPanel.legacy`, each to the key of the tab it is now. */
export function legacyKeys(providers: readonly { readonly plugin: string; readonly value: BuiltinPanel }[]) {
return new Map(
providers.flatMap((item) =>
Object.entries(item.value.legacy ?? {}).map(([key, id]) => [key, panelKey(item.plugin, id)] as const),
),
)
}

View file

@ -1,10 +1,10 @@
import { createMemo } from "solid-js"
import { MenuItem } from "@opencode/gui-extensions/sdk"
import { useExtensionHost } from "./host"
import { MenuItem } from "@opencode/plugin/gui"
import { usePluginHost } from "./host"
/** The side region's + menu: every extension's `session.panel` item, in order. */
/** The side region's + menu: every plugin's `session.panel` item, in order. */
export function createSessionPanelMenu() {
const host = useExtensionHost()
const host = usePluginHost()
return createMemo(() =>
host

View file

@ -5,16 +5,17 @@ import { IconButton } from "@opencode/ui/icon-button"
import { Keybind } from "@opencode/ui/keybind"
import { Tooltip } from "@opencode/ui/tooltip"
import { Tabs } from "@opencode/ui/tabs"
import type { MountedSession, PanelTab } from "@opencode/gui-extensions/sdk"
import type { MountedSession } from "@opencode/plugin/gui"
import type { BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import { useLanguage } from "@/runtime/i18n/language"
import { useCommand } from "@/shell/commands/command"
import { Contribution } from "./render"
/** One panel tab trigger. The extension supplies the content; the host owns close, drag, and ids. */
/** One panel tab trigger. The plugin supplies the content; the host owns close, drag, and ids. */
export function PanelTrigger(props: {
value: string
extension: string
tab: PanelTab
plugin: string
tab: BuiltinPanelTab
session: MountedSession
active: boolean
preview: boolean
@ -50,7 +51,7 @@ export function PanelTrigger(props: {
if (!render) return
return <Contribution extension={props.extension}>{() => untrack(() => render(state))}</Contribution>
return <Contribution plugin={props.plugin}>{() => untrack(() => render(state))}</Contribution>
})
const content = () => rendered() ?? props.tab.title

View file

@ -18,22 +18,16 @@ import {
SESSION_REVIEW_V2_SIDEBAR_WIDTH_MAX,
SESSION_REVIEW_V2_SIDEBAR_WIDTH_MIN,
} from "@opencode/session-ui/v2/session-review-v2"
import {
Panel,
PanelContext,
type PanelFrame,
type PanelSidebar,
type PanelTab,
type MountedSession,
type SessionScreen,
} from "@opencode/gui-extensions/sdk"
import type { PanelFrame, PanelSidebar, MountedSession, SessionScreen } from "@opencode/plugin/gui"
import { BuiltinPanel, type BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import { PanelContext } from "@opencode/plugin/gui/host"
import { same } from "@/runtime/persistence/equality"
import { sessionTabPane, type SessionPane, type SessionTabs } from "@/shell/state/session-tabs"
import { Persist, persisted } from "@/runtime/persistence/storage"
import { Persistence } from "@/runtime/persistence/schema"
import { useExtensionHost } from "./host"
import { usePluginHost } from "./host"
import { Contribution } from "./render"
import { useExtensionAttachment } from "./attachment"
import { usePluginAttachment } from "./attachment"
import { legacyKeys, panelKey } from "./panel-keys"
import { closedEntry, createSideFocus, type ClosedTabs } from "./closed-tabs"
@ -49,9 +43,9 @@ type Tabs = Accessor<{
export type RegionEntry = {
readonly key: string
readonly extension: string
readonly tab: PanelTab
readonly provider: Panel
readonly plugin: string
readonly tab: BuiltinPanelTab
readonly provider: BuiltinPanel
}
/** One pane of the region: its tabs, in strip order, and the tab it shows. */
@ -63,8 +57,8 @@ export type RegionPane = {
readonly keys: Accessor<string[]>
readonly active: Accessor<string | undefined>
readonly selected: Accessor<RegionEntry | undefined>
/** An extension's tab ids stored in this pane. */
readonly openFor: (extension: string) => string[]
/** A plugin's tab ids stored in this pane. */
readonly openFor: (plugin: string) => string[]
readonly lead: () => boolean
}
@ -77,7 +71,7 @@ const SidebarState = Persistence.struct({
})
/**
* The inner sidebar preference every side panel shares. The key predates extensions. `Layout.sidebar` reads it while
* The inner sidebar preference every side panel shares. The key predates plugins. `Layout.sidebar` reads it while
* the session screen that created it is mounted.
*/
export function createPanelSidebar(): PanelSidebar {
@ -99,17 +93,17 @@ export function createPanelSidebar(): PanelSidebar {
toggle: () => setStore("sidebarOpened", (opened) => !opened),
}
onCleanup(useExtensionAttachment().sidebar(sidebar))
onCleanup(usePluginAttachment().sidebar(sidebar))
return sidebar
}
/**
* Every panel extensions offer in one region of the routed session, merged with the stored strip. `view` returns the
* Every panel plugins offer in one region of the routed session, merged with the stored strip. `view` returns the
* routed session's object, a new one per routed session.
*/
export function createRegion(input: {
region: Panel["region"]
region: BuiltinPanel["region"]
view: Accessor<MountedSession>
screen: SessionScreen
tabs: Tabs
@ -126,19 +120,19 @@ export function createRegion(input: {
const settled = input.settled ?? ((run: () => void) => run())
// The text field focus left when the user opened the side region, which a close from inside it returns to.
let returnFocus: HTMLElement | undefined
const host = useExtensionHost()
const host = usePluginHost()
const stored = () => input.tabs().all()
const providers = createMemo(() => host.items(Panel).filter((item) => item.value.region === input.region))
const providers = createMemo(() => host.items(BuiltinPanel).filter((item) => item.value.region === input.region))
const entries = createMemo(() =>
providers().flatMap((item) => {
const prefix = `${item.extension}:`
const prefix = `${item.plugin}:`
const open = stored().flatMap((key) => (key.startsWith(prefix) ? [key.slice(prefix.length)] : []))
return item.value.list(panelInput(input.view, input.screen, { open })).map(
(tab): RegionEntry => ({
key: panelKey(item.extension, tab.id),
extension: item.extension,
key: panelKey(item.plugin, tab.id),
plugin: item.plugin,
tab,
provider: item.value,
}),
@ -148,8 +142,8 @@ export function createRegion(input: {
const byKey = createMemo(() => new Map(entries().map((entry) => [entry.key, entry])))
// Rewrites stored keys once their panel is present: keys stored before extensions (e.g. "context") or under an
// extension's earlier id, and ids a panel writes more than one way. Duplicates collapse, so one file stored two ways
// Rewrites stored keys once their panel is present: keys stored before plugins (e.g. "context") or under an
// plugin's earlier id, and ids a panel writes more than one way. Duplicates collapse, so one file stored two ways
// is one tab.
createEffect(() => {
const legacy = legacyKeys(providers())
@ -161,15 +155,15 @@ export function createRegion(input: {
const moved = legacy.get(key)
if (moved) return moved
const item = normalizers.find((provider) => key.startsWith(`${provider.extension}:`))
const item = normalizers.find((provider) => key.startsWith(`${provider.plugin}:`))
if (!item?.value.normalize) return key
return panelKey(
item.extension,
item.plugin,
item.value.normalize(
panelInput(input.view, input.screen, {
id: key.slice(item.extension.length + 1),
id: key.slice(item.plugin.length + 1),
}),
),
)
@ -182,7 +176,7 @@ export function createRegion(input: {
// Transient panels are not restored: their stored keys leave once the panel stops listing them.
createEffect(() => {
const listed = new Set(entries().map((entry) => entry.key))
const transient = providers().flatMap((item) => (item.value.transient ? [`${item.extension}:`] : []))
const transient = providers().flatMap((item) => (item.value.transient ? [`${item.plugin}:`] : []))
if (transient.length === 0) return
const all = stored()
@ -206,14 +200,14 @@ export function createRegion(input: {
})
// A pinned tab shows in the side pane. A listed tab the strip does not store, e.g. a terminal another session opened,
// belongs with its extension's last stored tab, so a grouped render stays in one pane.
// belongs with its plugin's last stored tab, so a grouped render stays in one pane.
const paneOf = (entry: RegionEntry): SessionPane => {
const tabs = input.tabs().tabs()
if (entry.tab.pinned) return "side"
if (tabs.all.includes(entry.key)) return sessionTabPane(tabs, entry.key)
const sibling = tabs.all.findLast((key) => key.startsWith(`${entry.extension}:`))
const sibling = tabs.all.findLast((key) => key.startsWith(`${entry.plugin}:`))
return sibling ? sessionTabPane(tabs, sibling) : "side"
}
@ -287,10 +281,10 @@ export function createRegion(input: {
return key ? byKey().get(key) : undefined
}),
openFor: (extension: string) =>
openFor: (plugin: string) =>
stored().flatMap((key) =>
key.startsWith(`${extension}:`) && sessionTabPane(input.tabs().tabs(), key) === pane
? [key.slice(extension.length + 1)]
key.startsWith(`${plugin}:`) && sessionTabPane(input.tabs().tabs(), key) === pane
? [key.slice(plugin.length + 1)]
: [],
),
lead: () => !!drawn().find((entry) => !entry.tab.pinned)?.tab.first,
@ -355,9 +349,9 @@ export function createRegion(input: {
return entry ? paneOf(entry) : sessionTabPane(input.tabs().tabs(), key)
},
wide: createMemo(() => providers().some((item) => item.value.wide)),
/** An extension's tab ids in the stored strip. */
openFor: (extension: string) =>
stored().flatMap((key) => (key.startsWith(`${extension}:`) ? [key.slice(extension.length + 1)] : [])),
/** A plugin's tab ids in the stored strip. */
openFor: (plugin: string) =>
stored().flatMap((key) => (key.startsWith(`${plugin}:`) ? [key.slice(plugin.length + 1)] : [])),
select(key: string) {
input.tabs().setActive(key)
},
@ -455,14 +449,14 @@ export function createRegion(input: {
const entry = input.closed.take(input.view(), key)
if (!entry) return
const extension = entry.key.slice(0, entry.key.indexOf(":"))
const provider = providers().find((item) => item.extension === extension)?.value
const plugin = entry.key.slice(0, entry.key.indexOf(":"))
const provider = providers().find((item) => item.plugin === plugin)?.value
if (!provider?.restore) return input.open(entry.key)
provider.restore({
session: input.view(),
screen: input.screen,
id: entry.key.slice(extension.length + 1),
id: entry.key.slice(plugin.length + 1),
data: entry.data,
})
},
@ -509,8 +503,8 @@ export function RegionContent(props: {
})
return (
<Show when={member()?.extension} keyed>
{(extension) => (
<Show when={member()?.plugin} keyed>
{(plugin) => (
<div
id={member()?.tab.dom?.panel}
role="tabpanel"
@ -524,10 +518,10 @@ export function RegionContent(props: {
value={{
...props.frame,
visible: () => props.frame.shown() && active(),
open: () => props.pane.openFor(extension),
open: () => props.pane.openFor(plugin),
}}
>
<Contribution extension={extension}>
<Contribution plugin={plugin}>
{() =>
member()!.provider.render(
panelInput(() => props.view, props.screen, {
@ -550,8 +544,8 @@ export function RegionContent(props: {
const entry = createMemo(() => props.pane.entries().find((item) => item.key === key))
return (
<Show when={entry()?.extension} keyed>
{(extension) => (
<Show when={entry()?.plugin} keyed>
{(plugin) => (
<div
id={entry()?.tab.dom?.panel}
role="tabpanel"
@ -561,9 +555,9 @@ export function RegionContent(props: {
class="flex flex-col h-full overflow-hidden contain-strict"
>
<PanelContext.Provider
value={{ ...props.frame, visible: props.frame.shown, open: () => props.pane.openFor(extension) }}
value={{ ...props.frame, visible: props.frame.shown, open: () => props.pane.openFor(plugin) }}
>
<Contribution extension={extension}>
<Contribution plugin={plugin}>
{() =>
entry()!.provider.render(
panelInput(() => props.view, props.screen, {
@ -586,7 +580,7 @@ export function RegionContent(props: {
}
function groupKey(entry: RegionEntry) {
return `${entry.extension}/${entry.tab.group ?? entry.key}`
return `${entry.plugin}/${entry.tab.group ?? entry.key}`
}
/** Keeps session and tab getters live while the owning screen stays constant. Spreading would snapshot getters. */
@ -623,7 +617,7 @@ export function MobilePanel(props: {
open: props.open,
}}
>
<Contribution extension={props.entry.extension}>
<Contribution plugin={props.entry.plugin}>
{() =>
props.entry.provider.render(
panelInput(() => props.view, props.screen, {

View file

@ -0,0 +1,103 @@
import { createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js"
import type { PluginOptions } from "@opencode/plugin/gui"
import type { Bridge, BridgePluginGui, BridgePluginGuis, Entry } from "@opencode/plugin/gui/host"
import type { OpenCodeClient } from "@opencode/client/promise"
import { useGlobal } from "@/runtime/server/runtime"
import { ServerConnection } from "@/runtime/server/registry"
import { pluginDefinition } from "./module"
/** A plugin's `./gui-experimental` bundle as this window evaluated it, at one revision. */
type Loaded = {
readonly id: string
readonly revision: string
readonly definition: Entry
readonly options: PluginOptions
}
/** A plugin's GUI as the plugin host runs it: its definition, options, and the client of the server that runs it. */
export type PluginGui = {
readonly definition: Entry
readonly options: PluginOptions
readonly client: () => OpenCodeClient | undefined
}
/**
* Loads the plugin GUIs main runs. Main alone lists the plugins on the desktop app's own server and reads their
* `./gui-experimental` bundles; this window evaluates what main sends, so every window and main run the same set. That
* server already runs the plugins' server entries, so their bundles add no new source of code; other servers' plugins
* load no GUI.
*
* Mounted below the app's server providers, which the plugin root sits above, for the client of that server; it
* hands the definitions up through `onChange` rather than the root reading them.
*/
export function PluginGuiLoader(props: {
bridge: Bridge
/** The GUIs that load, and the ids of plugins whose GUI cannot load because a built-in claims the id. */
onChange: (plugins: readonly PluginGui[], reserved: readonly string[]) => void
}) {
const global = useGlobal()
const controller = createMemo(() => {
const conn = global.servers.list().find(ServerConnection.builtin)
return conn ? global.serverCtx(ServerConnection.key(conn)) : undefined
})
// One evaluation per plugin revision, so an unchanged plugin keeps its definition and the host does not reload it.
const cache = new Map<string, Loaded>()
const [guis, setGuis] = createSignal<BridgePluginGuis>()
onCleanup(
props.bridge.on((message) => {
if (message.type === "pluginGuis") setGuis({ plugins: message.plugins, reserved: message.reserved })
}),
)
// A change main pushed while this request was in flight is newer than its reply.
void props.bridge.pluginGuis().then(
(initial) => setGuis((current) => current ?? initial),
() => undefined,
)
const [found] = createResource(guis, async (input) => {
const plugins = await Promise.all(input.plugins.map((plugin) => load(plugin, cache)))
const ids = new Set(plugins.map((plugin) => plugin.id))
cache.forEach((_, id) => {
if (!ids.has(id)) cache.delete(id)
})
return { plugins, reserved: input.reserved }
})
// Syncs the loaded plugins out to the plugin host.
createEffect(() => {
const latest = found.latest
if (!latest) return
// The server that runs the plugin, read each time: it is a new client after that server restarts.
const client = () => controller()?.sdk.api
props.onChange(
latest.plugins.map((plugin) => ({ definition: plugin.definition, options: plugin.options, client })),
latest.reserved,
)
})
return null
}
/** Evaluates a plugin's bundle when its revision is new to this window. */
async function load(plugin: BridgePluginGui, cache: Map<string, Loaded>): Promise<Loaded> {
const cached = cache.get(plugin.id)
if (cached?.revision === plugin.revision) return cached
const next = {
id: plugin.id,
revision: plugin.revision,
options: plugin.options,
definition: await pluginDefinition(plugin.id, plugin.code),
}
cache.set(plugin.id, next)
return next
}

View file

@ -3,41 +3,47 @@ import { Portal } from "solid-js/web"
import { MarkdownProvider, useMarkdown } from "@opencode/session-ui/context/markdown"
import { SourcesProvider } from "@opencode/session-ui/context/sources"
import { sourcesExperiment } from "@opencode/session-ui/sources/experiment"
import { ExtensionContext, Slot, Style, type MountedSession, type SlotMap } from "@opencode/gui-extensions/sdk"
import { useExtensionHost } from "./host"
import { Style, type MountedSession } from "@opencode/plugin/gui"
import { BuiltinSlot, type BuiltinSlotMap } from "@opencode/plugin/gui/builtin"
import { PluginContext } from "@opencode/plugin/gui/host"
import { usePluginHost } from "./host"
/**
* Renders one extension contribution with its context and error isolation: a contribution that throws records the
* Renders one plugin contribution with its context and error isolation: a contribution that throws records the
* error and renders nothing, and the rest of the window keeps working. Contributions never render on timeline rows;
* the session header slot is per timeline.
*/
export function Contribution(props: { extension: string; children: () => JSX.Element }) {
const host = useExtensionHost()
export function Contribution(props: { plugin: string; children: () => JSX.Element }) {
const host = usePluginHost()
return (
<Show when={host.context(props.extension)} keyed>
<Show when={host.context(props.plugin)} keyed>
{(context) => (
<ErrorBoundary
fallback={(error) => {
onMount(() => host.fail(props.extension, error, "render"))
onMount(() => host.fail(props.plugin, error, "render"))
return null
}}
>
{/* Untracked: a contribution renders once; its own reactivity updates it in place. */}
<ExtensionContext.Provider value={context}>{untrack(props.children)}</ExtensionContext.Provider>
<PluginContext.Provider value={context}>{untrack(props.children)}</PluginContext.Provider>
</ErrorBoundary>
)}
</Show>
)
}
export function ExtensionSlot<At extends keyof SlotMap>(props: { at: At; input: SlotMap[At]; fallback?: JSX.Element }) {
const host = useExtensionHost()
export function PluginSlot<At extends keyof BuiltinSlotMap>(props: {
at: At
input: BuiltinSlotMap[At]
fallback?: JSX.Element
}) {
const host = usePluginHost()
const items = createMemo(() =>
host
.items(Slot)
.items(BuiltinSlot)
.filter((item) => item.value.at === props.at)
.toSorted((a, b) => (a.value.order ?? 0) - (b.value.order ?? 0)),
)
@ -45,10 +51,10 @@ export function ExtensionSlot<At extends keyof SlotMap>(props: { at: At; input:
return (
<For each={items()} fallback={props.fallback}>
{(item) => (
<Contribution extension={item.extension}>
<Contribution plugin={item.plugin}>
{() =>
// SAFETY: items are filtered to `at === props.at`, and a slot's render takes that slot's input.
(item.value.render as (input: SlotMap[At]) => JSX.Element)(props.input)
(item.value.render as (input: BuiltinSlotMap[At]) => JSX.Element)(props.input)
}
</Contribution>
)}
@ -56,22 +62,22 @@ export function ExtensionSlot<At extends keyof SlotMap>(props: { at: At; input:
)
}
export function ExtensionStyles() {
const host = useExtensionHost()
export function PluginStyles() {
const host = usePluginHost()
return (
<Portal mount={document.head}>
<For each={host.items(Style)}>{(item) => <style data-extension={item.extension}>{item.value}</style>}</For>
<For each={host.items(Style)}>{(item) => <style data-plugin={item.plugin}>{item.value}</style>}</For>
</Portal>
)
}
/**
* Routes local markdown links in the session to extension LinkHandler contributions, keeping image loading. A turn's
* sources chip opens its turn through the Sources extension's handler.
* Routes local markdown links in the session to plugin LinkHandler contributions, keeping image loading. A turn's
* sources chip opens its turn through the Sources plugin's handler.
*/
export function ExtensionLinks(props: ParentProps<{ session: MountedSession }>) {
const host = useExtensionHost()
export function PluginLinks(props: ParentProps<{ session: MountedSession }>) {
const host = usePluginHost()
const markdown = useMarkdown()
return (

View file

@ -0,0 +1,155 @@
import { batch, createMemo, createSignal, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js"
import { pluginEnabled, runsOn, type Bridge, type Entry } from "@opencode/plugin/gui/host"
import { builtins } from "./builtins"
import { createInstalled } from "./installed"
import { PluginGuiLoader, type PluginGui } from "./plugins"
import { createMenubarItems, MenubarItemsProvider } from "./menubar-items"
import { usePlatform } from "@/runtime/platform/platform"
import { PluginHostProvider, usePluginHost } from "./host"
import { createIpcClients } from "./ipc"
import { createPluginAttachment, createHostApis, PluginAttachmentProvider, type HostApis } from "./host-apis"
import { PluginCommands } from "./commands"
import { PluginStyles } from "./render"
import { PluginServersProvider } from "./servers"
import { PluginServerEndpoints } from "./server-shell"
import { createContext, useContext } from "solid-js"
const HostApisContext = createContext<HostApis>()
// Desktop only: a window loads the plugin GUIs main sends.
const PluginsContext = createContext<{
bridge: Bridge
set: (plugins: readonly PluginGui[], reserved: readonly string[]) => void
reserved: () => readonly string[]
}>()
const PluginHotReload = import.meta.env.DEV ? lazy(() => import("./hmr")) : undefined
/** The ids of plugins on the app's own server whose GUI cannot load because a built-in plugin claims the id. */
export function useReservedPlugins() {
const plugins = useContext(PluginsContext)
return () => plugins?.reserved() ?? []
}
export function useHostApis() {
const value = useContext(HostApisContext)
if (!value) throw new Error("Host APIs are unavailable")
return value
}
/** Mounts the plugin host for the window. Lives above the app interface so plugins can contribute servers. */
export function PluginRoot(props: ParentProps) {
const platform = usePlatform()
const apis = createHostApis()
const bridge = platform.plugins
const menubar = createMenubarItems(bridge)
const ipcs = createIpcClients(bridge)
onCleanup(ipcs.dispose)
const installed = createInstalled(bridge)
const os = platform.platform === "desktop" ? platform.os : undefined
const localBuiltins = builtins.filter((definition) => runsOn(definition, os))
// The GUIs of the plugins on the app's own server, as main sends them.
const [plugins, setPlugins] = createSignal<readonly PluginGui[]>([])
// Plugins whose GUI cannot load because a built-in claims the id, as main reports them; Settings > Plugins shows them.
const [reserved, setReserved] = createSignal<readonly string[]>([])
// The same definitions in the same order are no change, so a refetch that found nothing new restarts nothing.
const definitions = createMemo<readonly Entry[]>(
() => [...localBuiltins, ...plugins().map((plugin) => plugin.definition)],
[],
{
equals: (a, b) => a.length === b.length && a.every((definition, index) => definition === b[index]),
},
)
// Only enable preferences cross this boundary.
const disabled = createMemo(() => {
const state = installed.enableState()
if (!state) return undefined
return new Set(
definitions().flatMap((definition) =>
pluginEnabled({ id: definition.id, builtin: builtins.some((builtin) => builtin.id === definition.id) }, state)
? []
: [definition.id],
),
)
})
const failed = (id: string) => installed.list().some((item) => item.id === id && item.error !== undefined)
return (
<HostApisContext.Provider value={apis}>
<PluginsContext.Provider
value={
bridge && {
bridge,
set: (next, ids) =>
batch(() => {
setPlugins(next)
setReserved(ids)
}),
reserved,
}
}
>
<PluginHostProvider
definitions={definitions}
disabled={disabled}
apis={apis.apis}
whenMounted={apis.whenMounted}
ipc={bridge ? (token) => ipcs.client(token) : undefined}
plugin={(id) => plugins().find((plugin) => plugin.definition.id === id)}
generation={ipcs.generation}
failed={failed}
>
<PluginStyles />
{PluginHotReload && (
<Suspense>
<PluginHotReload />
</Suspense>
)}
<MenubarItemsProvider value={menubar}>
<PluginServersProvider failed={failed}>{props.children}</PluginServersProvider>
</MenubarItemsProvider>
</PluginHostProvider>
</PluginsContext.Provider>
</HostApisContext.Provider>
)
}
/** Attaches the session and layout HostApis and publishes plugin commands. Renders once plugins are active. */
export function PluginAttachment(props: ParentProps) {
const host = usePluginHost()
const attachment = createPluginAttachment(useHostApis())
const plugins = useContext(PluginsContext)
return (
<PluginAttachmentProvider value={attachment}>
<PluginCommands />
<PluginServerEndpoints />
<Show when={plugins}>{(value) => <PluginGuiLoader bridge={value().bridge} onChange={value().set} />}</Show>
<Show when={host.ready()}>
<MountedInterface attach={attachment.attach} />
{props.children}
</Show>
</PluginAttachmentProvider>
)
}
/**
* The app interface as the HostApis see it, mounted as the routes first render and not before: writes and dialogs made
* while plugins set up wait until then.
*/
function MountedInterface(props: { attach: () => () => void }) {
onCleanup(props.attach())
return null
}

View file

@ -1,29 +1,32 @@
import { Match } from "effect"
import { createEffect, createMemo, Show, type ParentProps } from "solid-js"
import { usePlatform } from "@/runtime/platform/platform"
import { ServerConnection, useServers } from "@/runtime/server/registry"
import { useCurrentRoute } from "@/shell/state/layout"
import { useTabs } from "@/shell/tabs/tabs"
import { Contribution } from "./render"
import { useExtensionServers } from "./servers"
import { usePluginServers } from "./servers"
/**
* Keeps the routed session or draft mounted and lets its server's extension cover it while the
* Keeps the routed session or draft mounted and lets its server's plugin cover it while the
* server is not ready.
*/
export function ExtensionServerCover(props: ParentProps) {
const servers = useExtensionServers()
export function PluginServerCover(props: ParentProps) {
const servers = usePluginServers()
const route = useCurrentRoute()
const tabs = useTabs()
const covered = createMemo(() => {
const current = route()
const key =
current.type === "session"
? current.server
: current.type === "draft"
? tabs.store.find((tab) => tab.type === "draft" && tab.draftID === current.draftID)?.server
: undefined
const key = Match.value(current).pipe(
Match.when({ type: "session" }, (session) => session.server),
Match.when(
{ type: "draft" },
(draft) => tabs.store.find((tab) => tab.type === "draft" && tab.draftID === draft.draftID)?.server,
),
Match.orElse(() => undefined),
)
if (!key) return
const source = servers.entry(key)
@ -63,7 +66,7 @@ export function ExtensionServerCover(props: ParentProps) {
return (
<div class="absolute inset-0">
<Contribution extension={source.extension}>
<Contribution plugin={source.plugin}>
{() =>
cover({
get tab() {
@ -80,20 +83,22 @@ export function ExtensionServerCover(props: ParentProps) {
)
}
/** Tells main the server endpoints so main extensions can reach them. */
export function ExtensionServerEndpoints() {
/** Tells main the server endpoints so main plugins can reach them. */
export function PluginServerEndpoints() {
const servers = useServers()
const bridge = usePlatform().extensions
const bridge = usePlatform().plugins
if (bridge) {
const sent = { value: "" }
createEffect(() => {
const endpoints = servers.list.flatMap((conn) => {
// Main knows the built-in server first-hand; a contributed server has no endpoint until it is ready.
if (conn.type === "sidecar" || (conn.type === "extension" && conn.state !== "ready")) return []
if (conn.type === "sidecar" || (conn.type === "plugin" && conn.state !== "ready")) return []
const password = conn.http.password
return [{ id: ServerConnection.key(conn), url: conn.http.url, ...(password ? { password } : {}) }]
const endpoint = { id: ServerConnection.key(conn), url: conn.http.url }
return [password ? { ...endpoint, password } : endpoint]
})
const value = JSON.stringify(endpoints)

View file

@ -1,19 +1,20 @@
import { createContext, createEffect, createMemo, createSignal, useContext, type ParentProps } from "solid-js"
import { reconcile } from "solid-js/store"
import { Schema } from "effect"
import { MenuItem, Server, type ServerEntry } from "@opencode/gui-extensions/sdk"
import { MenuItem, Server, type ServerEntry } from "@opencode/plugin/gui"
import { Persistence } from "@/runtime/persistence/schema"
import { Persist, persisted } from "@/runtime/persistence/storage"
import type { ServerConnection } from "@/runtime/server/registry"
import { useExtensionHost } from "./host"
import { usePluginHost } from "./host"
import { renamedFrom } from "./stores"
/** A server an extension contributes. `key` is `${extension}:${entry.id}`. */
export type ExtensionServer = { readonly key: string; readonly extension: string; readonly entry: ServerEntry }
/** A server a plugin contributes. `key` is `${plugin}:${entry.id}`. */
export type PluginServer = { readonly key: string; readonly plugin: string; readonly entry: ServerEntry }
// Endpoint of a contributed server before its extension reports one.
// Endpoint of a contributed server before its plugin reports one.
const offline = { url: "http://127.0.0.1:0" }
// The last complete inventory of each extension that contributes servers, without endpoints or credentials.
// The last complete inventory of each plugin that contributes servers, without endpoints or credentials.
const Inventories = Schema.Record(
Schema.String,
Schema.mutableKey(
@ -31,26 +32,30 @@ const Inventories = Schema.Record(
),
)
const ServersContext = createContext<ReturnType<typeof createExtensionServers>>()
const ServersContext = createContext<ReturnType<typeof createPluginServers>>()
export function useExtensionServers() {
export function usePluginServers() {
const value = useContext(ServersContext)
if (!value) throw new Error("Extension servers are unavailable")
if (!value) throw new Error("Plugin servers are unavailable")
return value
}
/** Collects Server contributions. `failed` reports extensions whose main entry failed, so startup stops waiting for them. */
export function ExtensionServersProvider(props: ParentProps<{ failed: (extension: string) => boolean }>) {
return (
<ServersContext.Provider value={createExtensionServers(props.failed)}>{props.children}</ServersContext.Provider>
)
/** Collects Server contributions. `failed` reports plugins whose main entry failed, so startup stops waiting for them. */
export function PluginServersProvider(props: ParentProps<{ failed: (plugin: string) => boolean }>) {
return <ServersContext.Provider value={createPluginServers(props.failed)}>{props.children}</ServersContext.Provider>
}
function createExtensionServers(failed: (extension: string) => boolean) {
const host = useExtensionHost()
const [known, setKnown, , knownReady] = persisted(Persist.global("extension.servers"), Inventories, {})
function createPluginServers(failed: (plugin: string) => boolean) {
const host = usePluginHost()
const [known, setKnown, , knownReady] = persisted(
{ ...Persist.global("plugin.servers"), copyFrom: [renamedFrom(Persist.global("extension.servers"))] },
Inventories,
{},
)
const sources = createMemo(() => host.items(Server).toSorted((a, b) => (a.value.order ?? 0) - (b.value.order ?? 0)))
// Only a ready source reports its complete inventory. One that reloads, fails or has not started keeps its last
// inventory as stopped entries, so its servers' tabs, drafts and routes outlive the outage.
@ -69,19 +74,18 @@ function createExtensionServers(failed: (extension: string) => boolean) {
})),
}
if (JSON.stringify(known[item.extension]) !== JSON.stringify(inventory))
setKnown(item.extension, reconcile(inventory))
if (JSON.stringify(known[item.plugin]) !== JSON.stringify(inventory)) setKnown(item.plugin, reconcile(inventory))
}
})
const entries = createMemo(() => {
const live = available()
const down = Object.entries(known).filter(([extension]) => !live.some((item) => item.extension === extension))
const down = Object.entries(known).filter(([plugin]) => !live.some((item) => item.plugin === plugin))
return [
...live.map((item) => ({ extension: item.extension, order: item.value.order ?? 0, entries: item.value.entries })),
...down.map(([extension, inventory]) => ({
extension,
...live.map((item) => ({ plugin: item.plugin, order: item.value.order ?? 0, entries: item.value.entries })),
...down.map(([plugin, inventory]) => ({
plugin,
order: inventory.order,
entries: inventory.servers.map((server): ServerEntry => ({ ...server, state: "stopped" })),
})),
@ -89,17 +93,14 @@ function createExtensionServers(failed: (extension: string) => boolean) {
.toSorted((a, b) => a.order - b.order)
.flatMap((group) =>
group.entries.map(
(entry): ExtensionServer => ({ key: `${group.extension}:${entry.id}`, extension: group.extension, entry }),
(entry): PluginServer => ({ key: `${group.plugin}:${entry.id}`, plugin: group.plugin, entry }),
),
)
})
// Routes key on the connection object. Keep one per key across entry updates so reconnecting
// never unmounts an open conversation or composer.
const connections = new Map<
string,
{ update: (server: ExtensionServer) => void; value: ServerConnection.Extension }
>()
const connections = new Map<string, { update: (server: PluginServer) => void; value: ServerConnection.Plugin }>()
const list = createMemo(() => {
const listed = entries().filter((item) => item.entry.listed !== false)
@ -127,8 +128,7 @@ function createExtensionServers(failed: (extension: string) => boolean) {
// Startup waits for every source once; a source that reloads later does not hide the app again.
const ready = createMemo<boolean>(
(previous) =>
previous ||
(knownReady() && host.ready() && sources().every((item) => item.value.ready || failed(item.extension))),
previous || (knownReady() && host.ready() && sources().every((item) => item.value.ready || failed(item.plugin))),
false,
)
@ -137,22 +137,22 @@ function createExtensionServers(failed: (extension: string) => boolean) {
/** Contributed servers the app lists, as stable connections. */
list,
/**
* Every contributed server, including those settings lists before they are ready and those of an extension
* that is down. A server leaves only when its ready extension stops reporting it.
* Every contributed server, including those settings lists before they are ready and those of a plugin
* that is down. A server leaves only when its ready plugin stops reporting it.
*/
entries,
entry: (key: string) => entries().find((item) => item.key === key),
}
}
function connection(initial: ExtensionServer) {
function connection(initial: PluginServer) {
const [current, setCurrent] = createSignal(initial)
const entry = () => current().entry
const value: ServerConnection.Extension = {
type: "extension",
const value: ServerConnection.Plugin = {
type: "plugin",
key: initial.key,
extension: initial.extension,
plugin: initial.plugin,
get displayName() {
return entry().name
},
@ -174,7 +174,7 @@ function connection(initial: ExtensionServer) {
get http() {
return entry().http ?? offline
},
// Resolved per call: the connection outlives a reload of the extension that provides it.
// Resolved per call: the connection outlives a reload of the plugin that provides it.
get reconnect() {
if (!entry().reconnect) return undefined
@ -183,12 +183,12 @@ function connection(initial: ExtensionServer) {
connect: () => entry().connect?.() ?? Promise.resolve(entry().state === "ready"),
}
return { update: (server: ExtensionServer) => setCurrent(server), value }
return { update: (server: PluginServer) => setCurrent(server), value }
}
/** MenuItem "server.row" contributions that apply to a server. */
export function useServerRowItems(server: () => string) {
const host = useExtensionHost()
const host = usePluginHost()
return createMemo(() =>
host
@ -200,7 +200,7 @@ export function useServerRowItems(server: () => string) {
/** MenuItem "server.add" contributions, in order. */
export function useServerAddItems() {
const host = useExtensionHost()
const host = usePluginHost()
return createMemo(() =>
host

View file

@ -3,15 +3,15 @@ import { Tabs } from "@opencode/ui/tabs"
import { useSettingsSurface } from "@/settings/surface"
import { Contribution } from "./render"
/** One settings panel per extension page; the tab value is the SettingsPage id. */
export function ExtensionSettingsPages() {
/** One settings panel per plugin page; the tab value is the SettingsPage id. */
export function PluginSettingsPages() {
const surface = useSettingsSurface()
return (
<For each={surface.extensions.pages()}>
<For each={surface.plugins.pages()}>
{(item) => (
<Tabs.Content value={item.value.id} class="settings-panel">
<Contribution extension={item.extension}>
<Contribution plugin={item.plugin}>
{() =>
item.value.render({
get target() {
@ -29,16 +29,16 @@ export function ExtensionSettingsPages() {
}
/**
* Extension sections on a host settings page, in contribution order; with `section`, the extension rows placed in
* Plugin sections on a host settings page, in contribution order; with `section`, the plugin rows placed in
* that host section, rendered where the host lists them.
*/
export function ExtensionSettingsSections(props: { page: "general" | "servers"; section?: "general" }) {
export function PluginSettingsSections(props: { page: "general" | "servers"; section?: "general" }) {
const surface = useSettingsSurface()
return (
<For each={surface.extensions.sections(props.page, props.section)}>
<For each={surface.plugins.sections(props.page, props.section)}>
{(item) => (
<Contribution extension={item.extension}>
<Contribution plugin={item.plugin}>
{() =>
item.value.render({
get target() {

View file

@ -0,0 +1,23 @@
import { createMemo } from "solid-js"
import { SettingsPage } from "@opencode/plugin/gui"
import { usePluginHost } from "./host"
/** The settings pages plugins contribute. */
export function createSettingsPages() {
const host = usePluginHost()
const items = createMemo(() => host.items(SettingsPage))
const pages = createMemo(() => items().filter((item) => !item.value.page))
const tabs = createMemo<ReadonlySet<string>>(() => new Set(pages().map((item) => item.value.id)))
return {
items,
/** Settings pages without a host page, in contribution order. */
pages,
/** Their tab values. */
tabs,
/** Sections on a host page, or with `section`, the rows placed in that host section. */
sections: (page: "general" | "servers", section?: "general") =>
items().filter((item) => item.value.page === page && item.value.section === section),
}
}

View file

@ -0,0 +1,184 @@
import { Predicate } from "effect"
import { For, Show } from "solid-js"
import { Badge } from "@opencode/ui/badge"
import { Button } from "@opencode/ui/button"
import { Icon } from "@opencode/ui/icon"
import { Switch } from "@opencode/ui/switch"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
import { SettingsList } from "@/settings/list"
import { showToast } from "@/shell/notifications/toast"
import "@/settings/settings.css"
import { builtins } from "./builtins"
import { usePluginHost } from "./host"
import { createInstalled } from "./installed"
import { useReservedPlugins } from "./root"
/** Every plugin of this desktop window, built-in or from the app's own server, with reload and enable controls. */
export function PluginsSettings() {
const language = useLanguage()
const host = usePluginHost()
const bridge = usePlatform().plugins
const installed = createInstalled(bridge)
const reserved = useReservedPlugins()
const itemOf = (id: string) => installed.list().find((item) => item.id === id)
// Built-ins always run, so they have no switch.
const builtin = (id: string) => builtins.some((definition) => definition.id === id)
const enabled = (id: string) => itemOf(id)?.enabled ?? true
// Plugins main lists that this window does not load: limited to other systems, or a bundle main could not read.
const unloaded = () =>
installed
.list()
.filter(
(item) =>
item.unsupported ||
(!item.builtin &&
item.error !== undefined &&
!host.definitions().some((definition) => definition.id === item.id)),
)
// Why the window entry or main's entry failed; either fails the plugin.
const errorOf = (id: string) => host.state.failures[id]?.error ?? itemOf(id)?.error
// The switch already shows whether a plugin runs; only the states it cannot show get a label.
const status = (id: string) => {
const value = host.state.status[id] ?? "loading"
if (value === "failed" || (value === "active" && itemOf(id)?.error))
return language.t("settings.plugins.status.failed")
if (value === "active" || value === "disabled") return undefined
return language.t("settings.plugins.status.loading")
}
const run = (work: Promise<void> | undefined) =>
void work?.catch((cause: unknown) =>
showToast({
variant: "error",
title:
Predicate.hasProperty(cause, "code") && cause.code === "notFound"
? language.t("settings.plugins.error.notFound")
: language.t("common.requestFailed"),
}),
)
const toggle = (id: string, next: boolean) => run(next ? bridge?.manager.enable(id) : bridge?.manager.disable(id))
// Main entries reload through the manager; the renderer entry reloads here.
const reload = (id: string) => {
host.reload(id)
run(bridge?.manager.reload(id))
}
return (
<>
<div class="settings-tab-header">
<div class="settings-tab-header-row">
<div class="flex flex-col gap-1">
<h2 class="settings-tab-title">{language.t("settings.plugins.title")}</h2>
<span class="text-11-regular text-v2-text-text-muted">{language.t("settings.plugins.description")}</span>
</div>
</div>
</div>
<div class="settings-tab-body settings-tab-body--sectioned">
<section class="settings-section" aria-label={language.t("settings.plugins.title")}>
{/* The rows of the server Extensions tab, with the Providers tab's badges. */}
<SettingsList variant="catalog">
<For each={host.definitions()}>
{(definition) => (
<div class="settings-extension-row">
<div class="settings-extension-lead">
<Icon name="cube" class="text-v2-icon-icon-muted shrink-0" />
<div class="flex min-w-0 flex-col gap-0.5">
<div class="settings-provider-main">
<bdi dir="ltr" class="settings-extension-name truncate">
{definition.id}
</bdi>
<Show when={builtin(definition.id)}>
<Badge>{language.t("settings.plugins.builtin")}</Badge>
</Show>
{/* The parts besides the desktop UI that this row's switch leaves running. */}
<Show when={itemOf(definition.id)?.server}>
<Badge>{language.t("settings.plugins.part.server")}</Badge>
</Show>
<Show when={itemOf(definition.id)?.tui}>
<Badge>{language.t("settings.plugins.part.tui")}</Badge>
</Show>
<Show when={status(definition.id)}>
{(label) => <span class="text-11-regular text-v2-text-text-muted">{label()}</span>}
</Show>
</div>
<Show when={errorOf(definition.id)}>
{(error) => <pre class="settings-server-dialog-error whitespace-pre-wrap">{error()}</pre>}
</Show>
</div>
</div>
<div class="settings-servers-actions">
<Button size="small" variant="ghost" onClick={() => reload(definition.id)}>
{language.t("settings.plugins.reload")}
</Button>
{/* A built-in keeps the switch's width, so every Reload lines up. */}
<Show when={!builtin(definition.id)} fallback={<span class="w-6 shrink-0" aria-hidden="true" />}>
<Switch
hideLabel
checked={enabled(definition.id)}
onChange={(next) => toggle(definition.id, next)}
>
{definition.id}
</Switch>
</Show>
</div>
</div>
)}
</For>
<For each={unloaded()}>
{(item) => (
<div class="settings-extension-row">
<div class="settings-extension-lead">
<Icon name="cube" class="text-v2-icon-icon-muted shrink-0" />
<div class="flex min-w-0 flex-col gap-0.5">
<bdi dir="ltr" class="settings-extension-name truncate">
{item.id}
</bdi>
<Show
when={item.unsupported}
fallback={<pre class="settings-server-dialog-error whitespace-pre-wrap">{item.error}</pre>}
>
<span class="text-11-regular text-v2-text-text-muted">
{language.t("settings.plugins.unsupported")}
</span>
</Show>
</div>
</div>
</div>
)}
</For>
<For each={reserved()}>
{(id) => (
<div class="settings-extension-row">
<div class="settings-extension-lead">
<Icon name="cube" class="text-v2-icon-icon-muted shrink-0" />
<div class="flex min-w-0 flex-col gap-0.5">
<bdi dir="ltr" class="settings-extension-name truncate">
{id}
</bdi>
<span class="settings-server-dialog-error">{language.t("settings.plugins.reserved")}</span>
</div>
</div>
</div>
)}
</For>
</SettingsList>
<Show when={installed.list().some((item) => !item.builtin)}>
<p class="text-11-regular text-v2-text-text-muted">{language.t("settings.plugins.parts.note")}</p>
</Show>
</section>
</div>
</>
)
}

View file

@ -26,7 +26,7 @@ import {
type SessionScreen,
type PanelSidebar,
type SessionPanelMenuItem,
} from "@opencode/gui-extensions/sdk"
} from "@opencode/plugin/gui"
import { useCommand } from "@/shell/commands/command"
import { guardClosingFocus } from "@/shell/panel-motion"
import { useLanguage } from "@/runtime/i18n/language"
@ -36,7 +36,7 @@ import type { Sizing } from "@/session/helpers"
import { PanelTrigger } from "./panel-trigger"
import { createSessionPanelMenu } from "./panel-menu"
import { RegionContent, type Region, type RegionPane } from "./panels"
import { ExtensionSlot } from "./render"
import { PluginSlot } from "./render"
import { createTabStripScroll } from "./tab-strip-scroll"
import { closedTabsModifier, type ClosedSideTab } from "./closed-tabs"
import { ClosedTabsSection, NewTabButton } from "./closed-tabs-view"
@ -194,7 +194,7 @@ export function PaneTabs(props: {
drag: PaneDrag
/** Shows the empty state while the pane selects nothing. */
placeholder?: boolean
/** Renders the extensions' strip actions and keeps room for the session's review toggle. */
/** Renders the plugins' strip actions and keeps room for the session's review toggle. */
actions?: boolean
/** Controls after the strip, e.g. the bottom pane's hide button. */
end?: JSX.Element
@ -263,7 +263,7 @@ export function PaneTabs(props: {
{(entry) => (
<PanelTrigger
value={key}
extension={entry().extension}
plugin={entry().plugin}
tab={entry().tab}
session={props.view}
active={props.pane.active() === key}
@ -355,7 +355,7 @@ export function PaneTabs(props: {
onClick={(event) => event.stopPropagation()}
>
<Show when={props.actions}>
<ExtensionSlot
<PluginSlot
at="session.panel.end"
input={{
get session() {

View file

@ -11,7 +11,8 @@ import {
} from "solid-js"
import { produce, reconcile, type SetStoreFunction } from "solid-js/store"
import { Predicate } from "effect"
import type { Mutable, Persisted, SessionRef, StoreFrom } from "@opencode/gui-extensions/sdk"
import type { Mutable, Persisted, SessionRef } from "@opencode/plugin/gui"
import type { BuiltinStoreFrom } from "@opencode/plugin/gui/builtin"
import { Persist, type persisted } from "@/runtime/persistence/storage"
import type { SessionStateKey } from "@/runtime/server/scope"
@ -20,14 +21,36 @@ type CopyFrom = NonNullable<Exclude<Parameters<typeof persisted>[0], string>["co
const loads = new WeakMap<object, Promise<void>>()
/** The storage key of an extension's store: the extension id is its namespace. */
export function storeName(extension: string, key: string) {
return `extension.${extension}.${key}`
/** The storage key of a plugin's store: the plugin id is its namespace. */
export function storeName(plugin: string, key: string) {
return `plugin.${plugin}.${key}`
}
/** Where `Storage.store` keeps an extension's app-wide store, with the older keys it imports. */
export function globalStoreTarget(extension: string, key: string, from: StoreFrom | readonly StoreFrom[] | undefined) {
return { ...Persist.global(storeName(extension, key)), copyFrom: storeImports(from) }
/** The key the same store of a built-in had before plugins were renamed from extensions. */
export function renamedStoreName(plugin: string, key: string) {
return `extension.${plugin}.${key}`
}
/**
* Imports a built-in's store value once from where it lived before the rename: the same place under
* `renamedStoreName`. It copies instead of moving, so an older build opened on the same storage still finds the value.
* Other plugins never stored values there.
*/
export function renamedFrom(target: { readonly storage?: string; readonly key: string }): CopyFrom {
return { key: target.key, storage: target.storage, pick: (value) => value }
}
/** Where `Storage.store` keeps a plugin's app-wide store, with the older keys it imports. */
export function globalStoreTarget(
plugin: string,
key: string,
from: BuiltinStoreFrom | readonly BuiltinStoreFrom[] | undefined,
builtin: boolean,
) {
return {
...Persist.global(storeName(plugin, key)),
copyFrom: [...(builtin ? [renamedFrom(Persist.global(renamedStoreName(plugin, key)))] : []), ...storeImports(from)],
}
}
/**
@ -35,17 +58,17 @@ export function globalStoreTarget(extension: string, key: string, from: StoreFro
* state under one field imports only that session's entry.
*/
export function storeImports(
from: StoreFrom | readonly StoreFrom[] | undefined,
from: BuiltinStoreFrom | readonly BuiltinStoreFrom[] | undefined,
session?: SessionStateKey,
): CopyFrom[] {
return [from ?? []].flat().map((item) => (session && sessionCopy(item, session)) || copySpec(item))
}
function copySpec(from: StoreFrom): CopyFrom {
function copySpec(from: BuiltinStoreFrom): CopyFrom {
return Predicate.isString(from) ? { key: from } : from
}
function sessionCopy(from: StoreFrom, session: SessionStateKey): CopyFrom | undefined {
function sessionCopy(from: BuiltinStoreFrom, session: SessionStateKey): CopyFrom | undefined {
if (Predicate.isString(from) || !from.sessions) return
const field = from.sessions
@ -89,7 +112,7 @@ export function persistedHandle<T extends object>(input: {
)
// Runtime-key stores have no setup awaiter: a failed queued mutation must still report its contract error.
void load?.catch((cause: unknown) => console.error("[extension storage] Load or queued write failed", cause))
void load?.catch((cause: unknown) => console.error("[plugin storage] Load or queued write failed", cause))
const handle: Persisted<T> = {
get value() {

View file

@ -1,9 +1,9 @@
import { For } from "solid-js"
import type { TitlebarItem } from "@opencode/gui-extensions/sdk"
import type { TitlebarItem } from "@opencode/plugin/gui"
import { TitlebarItems } from "./titlebar-items"
const catalogs = import.meta.glob<{ default: Record<string, string> }>(
"../../../../gui-extensions/src/updater/i18n/*.ts",
"../../../../gui-plugins/src/updater/i18n/*.ts",
{ eager: true },
)

View file

@ -1,13 +1,13 @@
import { createMemo, For, Show } from "solid-js"
import { syncSpinPhase } from "@opencode/ui/hooks"
import { Icon } from "@opencode/ui/icon"
import { TitlebarItem } from "@opencode/gui-extensions/sdk"
import { useExtensionHost } from "./host"
import { TitlebarItem } from "@opencode/plugin/gui"
import { usePluginHost } from "./host"
import "./titlebar-items.css"
/** TitlebarItem contributions shown in the titlebar. */
export function useTitlebarItems() {
const host = useExtensionHost()
const host = usePluginHost()
const items = createMemo(() => host.list(TitlebarItem))

View file

@ -78,7 +78,7 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
const platform = usePlatform()
const transport = createServerTransport({ http: server.http, fetch: platform.fetch })
if (server.type === "extension") {
if (server.type === "plugin") {
createEffect(
on(
() => `${server.http.url}\0${server.http.password ?? ""}`,
@ -89,7 +89,7 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
}
const events = createOpenCodeEventSource()
const reconnect = server.type === "extension" || server.type === "sidecar" ? server.reconnect : undefined
const reconnect = server.type === "plugin" || server.type === "sidecar" ? server.reconnect : undefined
const connection = createClientConnection(transport.api, {
reconnect: reconnect ? async (signal) => transport.update(await reconnect(signal)) : undefined,
@ -126,11 +126,17 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
}
}
export type ServerTransport = {
/** A server's HTTP and PTY clients, rebuilt when its endpoint changes. */
export interface ServerTransport {
/** Rebuilds the clients for a new endpoint and returns the new API client. */
update(http: ServerConnection.HttpBase): ServerApi
/** The current base URL. */
readonly url: string
/** The current endpoint. */
readonly http: ServerConnection.HttpBase
/** The current API client. */
readonly api: ServerApi
/** The current PTY client. */
readonly pty: ReturnType<typeof createPtyClient>
}

View file

@ -2,6 +2,7 @@ import { usePlatform } from "@/runtime/platform/platform"
import { ServerConnection } from "@/runtime/server/registry"
import { authTokenFromCredentials } from "./api"
import { ClientError, isUnauthorizedError, OpenCode } from "@opencode/client"
import { Match } from "effect"
import { Accessor, createEffect, createSignal, onCleanup } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
@ -39,15 +40,14 @@ function cacheKey(server: ServerConnection.HttpBase) {
return `${server.url}\n${server.password ?? ""}`
}
function timeoutSignal(timeoutMs: number) {
const timeout = (AbortSignal as unknown as { timeout?: (ms: number) => AbortSignal }).timeout
/** A signal that aborts after a timeout, and how to stop its timer early when one runs. */
type Timeout = { readonly signal: AbortSignal; readonly clear?: () => void }
if (timeout) {
function timeoutSignal(timeoutMs: number): Timeout {
// Some runtimes lack `AbortSignal.timeout` or throw from it; a timer stands in.
if ("timeout" in AbortSignal) {
try {
return {
signal: timeout.call(AbortSignal, timeoutMs),
clear: undefined as (() => void) | undefined,
}
return { signal: AbortSignal.timeout(timeoutMs) }
} catch {}
}
@ -79,6 +79,8 @@ function wait(ms: number, signal?: AbortSignal) {
})
}
// SAFETY: a rejection's reason is unknown by contract; this is the boundary that classifies it, by `instanceof` only.
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
function retryable(error: unknown, signal?: AbortSignal) {
if (signal?.aborted) return false
@ -109,8 +111,8 @@ export async function checkServerHealth(
}
: undefined
const next = (count: number, error: unknown) => {
if (count >= retryCount || !retryable(error, signal)) return Promise.resolve({ healthy: false } as const)
const next = (count: number, retry: boolean) => {
if (count >= retryCount || !retry) return Promise.resolve({ healthy: false } as const)
return wait(retryDelayMs * (count + 1), signal)
.then(() => attempt(count + 1))
@ -135,7 +137,7 @@ export async function checkServerHealth(
if (isUnauthorizedError(current.error)) return { healthy: false, unauthorized: true }
return next(count, current.error)
return next(count, retryable(current.error, signal))
}
return attempt(0).finally(() => timeout?.clear?.())
@ -143,6 +145,14 @@ export async function checkServerHealth(
const pollMs = 10_000
// What a contributed server that is not ready reports: failed and incompatible are known; any other stage is unknown.
const stageHealth = (stage: ServerConnection.Plugin["state"]) =>
Match.value(stage).pipe(
Match.when("failed", (): ServerHealth | undefined => ({ healthy: false })),
Match.when("incompatible", (): ServerHealth | undefined => ({ healthy: false, incompatible: true })),
Match.orElse((): ServerHealth | undefined => undefined),
)
export function useCheckServerHealth() {
const platform = usePlatform()
const fetcher = platform.fetch ?? globalThis.fetch
@ -177,7 +187,7 @@ export function createServerHealth(
enabled: Accessor<boolean>,
check: (http: ServerConnection.HttpBase) => Promise<ServerHealth>,
) {
const [status, setStatus] = createStore({} as Record<ServerConnection.Key, ServerHealth | undefined>)
const [status, setStatus] = createStore<Record<ServerConnection.Key, ServerHealth | undefined>>({})
const [attempt, setAttempt] = createSignal(0)
const endpoints = new Map<ServerConnection.Key, string>()
// Callers of `retry` wait for the probe round it starts.
@ -198,24 +208,15 @@ export function createServerHealth(
// invalidates both the old result and any probe still using the old endpoint.
const list = servers().map((conn) => ({
key: ServerConnection.key(conn),
managed: conn.type === "extension" && conn.managed,
managed: conn.type === "plugin" && conn.managed,
http: conn.http,
stage: conn.type === "extension" ? conn.state : undefined,
stage: conn.type === "plugin" ? conn.state : undefined,
}))
for (const conn of list) {
if (conn.stage && conn.stage !== "ready") {
endpoints.delete(conn.key)
setStatus(
conn.key,
reconcile(
conn.stage === "failed"
? { healthy: false }
: conn.stage === "incompatible"
? { healthy: false, incompatible: true }
: undefined,
),
)
setStatus(conn.key, reconcile(stageHealth(conn.stage)))
continue
}
@ -239,12 +240,7 @@ export function createServerHealth(
await Promise.all(
list.map(async (conn) => {
if (conn.stage && conn.stage !== "ready") {
results[conn.key] =
conn.stage === "failed"
? { healthy: false }
: conn.stage === "incompatible"
? { healthy: false, incompatible: true }
: undefined
results[conn.key] = stageHealth(conn.stage)
return
}

View file

@ -55,9 +55,9 @@ test("startup auth_token credentials override a persisted same-url server; witho
test("treats WSL sidecars as remote server connections", () => {
expect(
ServerConnection.local({
type: "extension",
type: "plugin",
key: "wsl:Debian",
extension: "wsl",
plugin: "wsl",
state: "ready",
connecting: false,
authenticationRequired: false,
@ -87,6 +87,9 @@ test("keeps exact persisted server identities and prevents removing provided ser
expect(canRemoveServer({ key, stored, provided: [{ type: "http", http: { url: key } }] })).toBe(false)
})
/** The server props a project store follows, which the test changes. */
type ProjectScopeProps = { server: ServerConnection.Key; canonicalLocalServer?: ServerConnection.Key }
test("used and last projects follow dynamic server scopes, and migration consumes only its scope", () => {
const [store, setStore] = createStore(
Schema.decodeUnknownSync(serverSchema())({
@ -94,9 +97,7 @@ test("used and last projects follow dynamic server scopes, and migration consume
}),
)
const props: { server: ServerConnection.Key; canonicalLocalServer?: ServerConnection.Key } = {
server: ServerConnection.Key.make("https://remote.example"),
}
const props: ProjectScopeProps = { server: ServerConnection.Key.make("https://remote.example") }
const projects = createServerProjects({
store,

View file

@ -4,7 +4,7 @@ import { batch, createMemo } from "solid-js"
import { reconcile, type SetStoreFunction, type Store } from "solid-js/store"
import { Persist, persisted } from "@/runtime/persistence/storage"
import { ServerScope } from "@/runtime/server/scope"
import type { ServerEntry } from "@opencode/gui-extensions/sdk"
import type { ServerEntry } from "@opencode/plugin/gui"
import { ServerHttp, ServerHttpBase, ServerKey, ServerState } from "./persistence"
type StoredState = typeof ServerState.Type
@ -146,15 +146,15 @@ export namespace ServerConnection {
reconnect?: (signal: AbortSignal) => Promise<HttpBase>
} & Base
// A server a GUI extension contributes (e.g. SSH or WSL), keyed `${extension}:${id}`
export type Extension = {
type: "extension"
// A server a GUI plugin contributes (e.g. SSH or WSL), keyed `${plugin}:${id}`
export type Plugin = {
type: "plugin"
key: string
extension: string
plugin: string
state: ServerEntry["state"]
connecting: boolean
authenticationRequired: boolean
/** The extension re-resolves the endpoint (e.g. a tunnel), so the connection can drop and come back. */
/** The plugin re-resolves the endpoint (e.g. a tunnel), so the connection can drop and come back. */
managed: boolean
http: HttpBase
reconnect?: (signal: AbortSignal) => Promise<HttpBase>
@ -165,7 +165,7 @@ export namespace ServerConnection {
export type Any =
| Http
// All these are desktop-only
| (Sidecar | Extension)
| (Sidecar | Plugin)
export const key = (conn: Any): Key => {
switch (conn.type) {
@ -173,7 +173,7 @@ export namespace ServerConnection {
return Key.make(conn.http.url)
case "sidecar":
return Key.make("sidecar")
case "extension":
case "plugin":
return Key.make(conn.key)
}
}
@ -184,7 +184,7 @@ export namespace ServerConnection {
export const builtin = (conn: Any) => conn.type === "sidecar" && conn.variant === "base"
/** Starts sign-in for a server that asks for it; false when it does not. */
export const authenticate = (conn: Any, onConnected?: () => void) => {
if (conn.type !== "extension" || !conn.authenticationRequired || !conn.connect) return false
if (conn.type !== "plugin" || !conn.authenticationRequired || !conn.connect) return false
void conn.connect().then((ready) => {
if (ready) onConnected?.()
})
@ -209,6 +209,7 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex
ServerState,
{ list: [], hidden: {}, lastProjectID: {}, usedProjectIDs: {}, hostnames: {}, projects: {} },
)
const language = useLanguage()
const allServers = createMemo((): Array<ServerConnection.Any> => {

View file

@ -3,10 +3,10 @@ import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { Menu } from "@opencode/ui/menu"
import { For, Show } from "solid-js"
import { useServerAddItems } from "@/runtime/extension/servers"
import { useServerAddItems } from "@/runtime/plugin/servers"
import { useLanguage } from "@/runtime/i18n/language"
/** The add-server button; extensions that add their own kinds of server turn it into a menu. */
/** The add-server button; plugins that add their own kinds of server turn it into a menu. */
export function AddServerMenu(props: { onAddServer: () => void; compact?: boolean }) {
const language = useLanguage()
const items = useServerAddItems()

View file

@ -5,7 +5,7 @@ import { ServerConnection, useServers } from "@/runtime/server/registry"
import { useTabs } from "@/shell/tabs/tabs"
import { type ServerHealth } from "@/runtime/server/health"
import { showToast } from "@/shell/notifications/toast"
import { useExtensionServers } from "@/runtime/extension/servers"
import { usePluginServers } from "@/runtime/plugin/servers"
export function sortServerConnections(input: {
servers: ServerConnection.Any[]
@ -32,13 +32,13 @@ export function sortServerConnections(input: {
export function useServerActionsController() {
const server = useServers()
const extensions = useExtensionServers()
const plugins = usePluginServers()
const tabs = useTabs()
const language = useLanguage()
const remove = async (key: ServerConnection.Key) => {
try {
await extensions.entry(key)?.entry.remove?.()
await plugins.entry(key)?.entry.remove?.()
tabs.removeServer(key)
server.remove(key)
} catch (err) {

View file

@ -1,16 +1,16 @@
import { untrack } from "solid-js"
import type { ServerRow } from "@opencode/gui-extensions/sdk"
import { Contribution } from "@/runtime/extension/render"
import { useExtensionServers } from "@/runtime/extension/servers"
import type { ServerRow } from "@opencode/plugin/gui"
import { Contribution } from "@/runtime/plugin/render"
import { usePluginServers } from "@/runtime/plugin/servers"
import type { ServerConnection } from "@/runtime/server/registry"
import type { ServerCollectionController } from "./controller"
import { ServerHealthIndicator } from "./row"
import { ServerRowItems } from "./row-items"
/** A contributed server's connection row; the extension renders it with the host's shared parts. */
export function ExtensionServerRow(props: { server: ServerConnection.Key; controller: ServerCollectionController }) {
const servers = useExtensionServers()
// The entry changes with every state update; its row follows the extension's state on its own.
/** A contributed server's connection row; the plugin renders it with the host's shared parts. */
export function PluginServerRow(props: { server: ServerConnection.Key; controller: ServerCollectionController }) {
const servers = usePluginServers()
// The entry changes with every state update; its row follows the plugin's state on its own.
const source = untrack(() => servers.entry(props.server))
const row: ServerRow = {
@ -29,5 +29,5 @@ export function ExtensionServerRow(props: { server: ServerConnection.Key; contro
if (!source) return null
return <Contribution extension={source.extension}>{() => untrack(() => source.entry.row?.(row))}</Contribution>
return <Contribution plugin={source.plugin}>{() => untrack(() => source.entry.row?.(row))}</Contribution>
}

View file

@ -1,8 +1,8 @@
import { Menu } from "@opencode/ui/menu"
import { For } from "solid-js"
import { useServerRowItems } from "@/runtime/extension/servers"
import { useServerRowItems } from "@/runtime/plugin/servers"
/** Extension "server.row" menu items for one server, placed inside that row's menu. */
/** Plugin "server.row" menu items for one server, placed inside that row's menu. */
export function ServerRowItems(props: { server: string }) {
const items = useServerRowItems(() => props.server)

View file

@ -16,9 +16,9 @@ import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "@/
import { usePlatform } from "@/runtime/platform/platform"
import type { SessionModel } from "@/session/model"
import type { SessionRevert } from "@/session/revert"
import { useExtensionClaims, useExtensionScoped } from "@/runtime/extension/commands"
import type { Region } from "@/runtime/extension/panels"
import { sideTabShortcuts } from "@/runtime/extension/closed-tabs"
import { usePluginClaims, usePluginScoped } from "@/runtime/plugin/commands"
import type { Region } from "@/runtime/plugin/panels"
import { sideTabShortcuts } from "@/runtime/plugin/closed-tabs"
type SessionCommandSource = {
identity: SessionModel["identity"]
@ -59,8 +59,8 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const data = useData()
const settings = useSettings()
const platform = usePlatform()
const extensionScoped = useExtensionScoped()
const extensionClaims = useExtensionClaims()
const pluginScoped = usePluginScoped()
const pluginClaims = usePluginClaims()
const openDialog = async <T,>(load: () => Promise<T>, show: (value: T) => void) => {
const owner = actions.session.ownership.capture()
@ -82,7 +82,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const inSide = actions.region.focus
// ⌘T and ⌘W inside the side region open and close its tabs, unless the focused panel binds the key itself there.
const sideKey = (event: KeyboardEvent) => inSide(event) && !extensionClaims(event)
const sideKey = (event: KeyboardEvent) => inSide(event) && !pluginClaims(event)
// ⌘W on the side panel's last tab closes the panel and moves focus out of it, where one press too many would close
// the session tab. Until the user moves on, by clicking, focusing, another key, or another session, ⌘W closes nothing.
// The close moves focus synchronously, before this is set, so its own focusin does not clear it.
@ -95,6 +95,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
"keydown",
(event) => {
if (["Meta", "Control", "Shift", "Alt"].includes(event.key)) return
if (!command.matches("file.close", event)) resetEmptied()
},
{ capture: true },
@ -112,7 +113,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
? target
: document.activeElement
return element instanceof Element && !!element.closest("#review-panel") && !extensionScoped(element)
return element instanceof Element && !!element.closest("#review-panel") && !pluginScoped(element)
}
const selectionPreview = (path: string, selection: FileSelection) => {

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