GUI 插件
使用 @opencode/plugin/gui 为 OpenCode Desktop 开发插件的 GUI 部分。
GUI 插件通过 GUI 插件 SDK(@opencode/plugin/gui)为 OpenCode Desktop 添加面板、命令、设置页面以及原生集成能力。它是插件包中的 ./gui-experimental 导出部分,既可单独存在,也可与服务端部分和 TUI 部分并存。
注意: GUI 插件 API 目前处于实验阶段,版本间可能发生变更。包中的
-experimental导出名正是为此标识。
与服务端和 TUI 部分类似,./gui-experimental 文件默认导出 Plugin.define:
import { Command, Plugin } from "@opencode/plugin/gui"
import { Acme } from "./rpc"
export default Plugin.define({
i18n: { en: { "command.open": "Open Acme" } },
setup(ctx) {
ctx.add(Command, () => ({
id: "open",
title: ctx.t("command.open"),
run: () => void ctx.client.rpc(Acme).open({}),
}))
},
main(ctx) {
ctx.log.write("info", "acme started")
},
})GUI 插件可以在两个进程中运行:
setup:在每个桌面应用窗口中运行,用于贡献面板、命令、设置页面、插槽、服务器来源、链接处理器和样式。详见窗口进程。main:在 Electron 主进程中仅运行一次,用于提供类型化Ipc契约、原生菜单项、WebContentsView嵌入以及 Node 和 Electron 集成。详见主进程。
插件包结构
单个 npm 插件包可以同时发布服务端、TUI 和 GUI 代码。只需在 ./tui 旁添加一个 ./gui-experimental 导出,OpenCode Desktop 就会为后台服务器加载的每个插件自动加载其 GUI 部分:
{
"name": "opencode-acme-plugin",
"type": "module",
"exports": {
".": "./src/index.ts",
"./tui": "./src/tui.tsx",
"./gui-experimental": "./dist/gui-experimental.cjs"
},
"dependencies": {
"@opencode/plugin": "latest"
},
"devDependencies": {
"solid-js": "^1.9.0",
"vite": "^7.0.0",
"vite-plugin-solid": "^2.11.0"
}
}用户安装方式与其他插件完全相同,无需单独的 GUI 安装步骤:
{
"plugins": ["opencode-acme-plugin"],
}GUI 部分不自行声明 ID,而是沿用插件的 ID——即服务端部分的 id;对于不含服务端部分的包则使用包名(不含 name 的本地目录使用目录名)。可通过 ctx.id 读取。
单文件,双进程
两个进程都会求值整个 ./gui-experimental 文件并读取其默认导出:窗口进程执行 setup,桌面应用主进程执行 main:
import { shell } from "electron"
import { Plugin } from "@opencode/plugin/gui"
export default Plugin.define({
setup(ctx) {
// Window code: Solid components, ctx.layout, ctx.add(Command, …).
},
main(ctx) {
// Main code: electron, Node built-ins, ctx.windows.
ctx.windows.on("open", () => shell.beep())
},
})由于两个进程都会求值同一个文件,每个进程都会为另一进程专属的模块提供惰性占位符(inert placeholder):
- 在窗口进程中:
electron与 Node 内置模块为惰性占位符。 - 在主进程中:Solid 与仅限窗口的模块为惰性占位符。
占位符允许模块顶层作用域中的任意属性读取、函数调用或构造(例如 Solid 提升的模板或打包器提升的 require 调用)。请务必将每个进程的代码留在各自的 setup 或 main 中——在错误进程中运行的代码拿到的将是占位符而非真实可用的值。
Plugin.define 及契约辅助工具在两个进程中来自同一份 SDK。在主进程中,@opencode/plugin/gui 会解析为主进程 SDK,导出相同的 Plugin、Store、Ipc、Contract 和 Registry,使一份定义同时服务两个进程。仅限窗口的导出(如 Command、bindPlugin 和 createKeyed)在主进程中为 undefined,请仅在 setup 中使用它们。
构建产物
./gui-experimental 必须是单个预构建的 CommonJS 文件。请使用 @opencode/plugin/gui/vite 提供的 Vite 预设进行构建:
import { defineConfig } from "vite"
import { gui } from "@opencode/plugin/gui/vite"
export default defineConfig({ plugins: [gui()] })vite build该预设会自动完成以下处理:
- 使用
vite-plugin-solid编译 Solid JSX。 - 输出单个 CommonJS 文件,并内联所有动态
import(),因为桌面应用无法加载第二个 chunk。 - 将应用的共享模块、Electron 以及 Node 内置模块保持为 external,同时将其余全部依赖打包进来。
- 遇到任何其他
effect/*、solid-js/*或@opencode/*模块时直接构建失败,因为应用不提供它们,而单独打包的副本无法与应用共享实例。
effect/Schema is not a module the OpenCode app provides to plugin GUIs: effect, @opencode/plugin/gui, …请改从共享入口导入,例如 import { Schema } from "effect"。
预设选项
向 gui() 传入选项以修改入口文件或输出文件路径:
export default defineConfig({ plugins: [gui({ entry: "src/desktop.tsx", outFile: "dist/desktop.cjs" })] })entry:默认导出Plugin.define的入口文件,默认为src/gui.tsx。outFile:./gui-experimental导出指向的产物路径,默认为dist/gui-experimental.cjs。
类型参考
function gui(options?: GuiOptions): Plugin[]
interface GuiOptions {
entry?: string
outFile?: string
}依赖配置
将构建工具添加到 devDependencies。应用在运行时提供 @opencode/plugin/gui,因此打包时只需从 @opencode/plugin 依赖获取类型定义:
bun add -d vite vite-plugin-solid solid-js如需在 main 中使用 Electron 与 Node 类型,请一并安装 electron 和 @types/node:
bun add -d electron @types/node共享模块
两个进程分别为产物提供以下运行时模块。require 两个进程均未提供的外部模块会导致插件 GUI 加载失败:
import { Schema } from "effect" // Both processes
import { createSignal } from "solid-js" // Windows; an inert placeholder in the main process
import { readFile } from "node:fs/promises" // The main process; an inert placeholder in windows- 双进程共享:
effect、@opencode/plugin/gui、@opencode/plugin/gui/main、@opencode/plugin/rpc、@opencode/schema/rpc、@opencode/client与@opencode/client/effect。 - 仅窗口进程:
solid-js、solid-js/web、solid-js/store、@opencode/client/solid与@opencode/plugin/gui/{file,review,browser};主进程中为惰性占位符。 - 仅主进程:
electron与 Node 内置模块(如node:fs);窗口进程中为惰性占位符。
GUI 入口的加载位置
OpenCode Desktop 从其自身后台服务器加载 GUI 入口——该服务器本就负责加载你配置中的插件,因此不会引入新的代码来源。在全局 opencode.json(c) 中配置插件即可让其 GUI 在所有窗口中可用。
注意: TUI 从
cli.json读取插件,而桌面应用只读取opencode.json(c)。原本仅包含 TUI 部分、且用户配置在cli.json中的插件包,一旦新增了./gui-experimental,也必须添加到opencode.json(c)中。
桌面应用主进程使用仅自己持有的凭据,从内置服务器列出插件并读取其构建产物,再将同一份清单下发给各窗口。窗口进程无法自行提供主进程代码。
如果插件的服务端部分加载失败,则不会加载其 GUI。
热重载与更新
从本地目录加载插件,并在每次改动后自动重新构建:
vite build --watch- 若本地目录的
package.json包含name与exports,则通过它们解析./gui-experimental;否则加载根目录下的gui-experimental.cjs(或.js)。入口扩展名必须为.cjs或.js,其他文件会被忽略。 - 每次重新构建都会在所有窗口和主进程中重新加载该插件的 GUI,服务端入口不会重启。
- 已安装 npm 包的 GUI 仅随版本号变化而更新。
- 修改
opencode.json(c)中该插件的options会重新加载插件。 opencode plugin update完成后会自动替换对应包的 GUI。- Settings > Extensions > Plugins 会列出该插件并提供关闭其 GUI 的开关。如需彻底移除,请从
opencode.json(c)删除或运行opencode plugin remove <package>。
注意: 应用内置插件的 ID 为保留名称。如果你的插件 ID 与之同名、通过
.嵌套在其下、将其嵌套在自身下,或位于opencode命名空间内,其 GUI 将不会加载,并在 Settings > Extensions > Plugins 中显示为未加载。
定义 GUI 插件
Plugin.define 用于声明插件支持的操作系统、窗口持久化状态、图标以及多语言文案。宿主会在任意 setup 运行前先读取这些声明:
import { Schema } from "effect"
import { Plugin, Store } from "@opencode/plugin/gui"
export const definition = Plugin.define({
os: ["macos", "linux"],
stores: {
prefs: Store.global(Schema.Struct({ enabled: Schema.Boolean }), { enabled: true }),
},
i18n: {
en: { title: "Acme", "command.open": "Open Acme" },
de: { title: "Acme", "command.open": "Acme öffnen" },
},
})- 宿主为插件分配 ID(
ctx.id):取服务端部分的id,无服务端部分时取包名(无name的本地目录取目录名)。该 ID 会作为插件创建的所有标识的前缀:命令(<id>.<command>)、面板键(<id>:<tab>)、存储键(plugin.<id>.<key>)以及提供的契约与 Ipc 的 ID。 os将插件限定在特定操作系统上运行,省略则支持所有系统。若os未包含当前系统,插件不会运行,且 Settings > Extensions > Plugins 会保留其条目并标注“Not available on this system.”。stores声明窗口使用的持久化状态,通过ctx.stores.<key>读取。icons声明插件自定义图标,每项为 SVG 文件文本,通过ctx.icons.<name>读取图标名。i18n按语言区域存放文案。请内联编写各语言文案,缺失的键会自动回退到英文。使用ctx.t(key, params)与ctx.plural(key, count)读取;在窗口中ctx.t还可读取应用共享键(如common.*),在main中缺失键会原样返回键名。- 至少定义
setup或main之一,两者皆无的 GUI 会加载失败。 - 不传
setup/main时,Plugin.define返回Plugin.Declarations声明对象,便于其他文件中的 setup 推导类型。完整定义类型为Plugin.Definition。 - 插件无需静态声明提供或消费的契约,而是在运行时按需提供与读取,详见契约与令牌。
类型参考
interface Declarations {
os?: ("macos" | "windows" | "linux")[]
stores?: Record<string, StoreDeclaration>
icons?: Record<string, string>
i18n?: { en: Messages; [locale: string]: Messages }
}
interface Definition extends Declarations {
setup?(ctx: SetupContext<this>): Cleanup | void
main?(ctx: MainContext): Cleanup | void | Promise<Cleanup | void>
}
type Messages = Record<string, string>
type Cleanup = () => void | Promise<void>拆分多文件
小型 GUI 插件可以全部写在 src/gui.tsx 中。对于大型插件,建议在 definition.ts 中声明元信息,在 contract.ts 中放置共享令牌,将各进程 setup 写在独立文件中,最后在 src/gui.tsx 中组合:
src/
├── index.ts Server part: Plugin.define from @opencode/plugin
├── rpc.ts RPC contract between the server part and its clients
├── gui.tsx ./gui-experimental entry: export default Plugin.define({ ...definition, setup, main })
└── gui/
├── definition.ts Plugin.define: os, stores, icons, i18n
├── contract.ts Tokens other code may import: Ipc, Contract, Registry
├── window.tsx Window setup: Plugin.Setup<typeof definition>
├── main.ts Main setup: Plugin.MainSetup (desktop only)
├── page.tsx Components that panels and pages render
├── icons/logo.svg The plugin's own icons
└── i18n/en.ts English copy窗口启动时会求值整个 ./gui-experimental 文件,因此请保持模块顶层和 setup 足够轻量:在此注册各项贡献,将耗时逻辑放到组件、createKeyed 或 createLatest 中执行。
大型插件可先声明定义,再基于声明分别为各 setup 标注类型,最后组合导出:
import { Schema } from "effect"
import { Plugin, Store } from "@opencode/plugin/gui"
export const definition = Plugin.define({
stores: { notes: Store.global(Schema.Struct({ count: Schema.Number }), { count: 0 }) },
})import type { Plugin } from "@opencode/plugin/gui"
import { Notes } from "./contract"
import type { definition } from "./definition"
export const setup: Plugin.Setup<typeof definition> = (ctx) => {
ctx.provide(Notes, { count: () => ctx.stores.notes.value.count })
}import type { Plugin } from "@opencode/plugin/gui"
export const main: Plugin.MainSetup = (ctx) => {
ctx.log.write("info", "acme started")
}import { Plugin } from "@opencode/plugin/gui"
import { definition } from "./gui/definition"
import { main } from "./gui/main"
import { setup } from "./gui/window"
export default Plugin.define({ ...definition, setup, main })Plugin.Setup<typeof definition>是窗口setup的类型,它会根据声明的 stores 与 icons 自动推导ctx.stores和ctx.icons。Plugin.MainSetup是主进程main的类型,Plugin.Cleanup是两者可返回的清理函数类型。- 从
@opencode/plugin/gui导入注册表、令牌及辅助工具,如Command、SettingsPage、Panel、Slot、Contract、Ipc、Registry、Store、createKeyed、usePlugin和bindPlugin。 - 从
@opencode/plugin/gui/main导入主进程专属注册表,如MenubarItem。
共享上下文
与服务端和 TUI 部分类似,两个进程的 setup 都会收到插件配置选项、OpenCode 服务器客户端以及应用元数据。
配置选项(Options)
ctx.options 包含 opencode.json(c) 中为该插件配置的 options,与服务端部分收到的值一致:
{
"plugins": [{ "package": "opencode-acme-plugin", "options": { "team": "core" } }],
}setup(ctx) {
const team = ctx.options.team
}- 修改配置选项会自动重新加载插件。
服务器客户端
ctx.client 是运行该插件的服务器(即桌面应用内置服务器)的 OpenCode 客户端,可通过它调用插件服务端部分的 RPC:
import { Command } from "@opencode/plugin/gui"
import { Acme } from "./rpc"
ctx.add(Command, () => ({
id: "search",
title: ctx.t("command.search"),
run: async () => {
const result = await ctx.client.rpc(Acme).search({ query: "todo" })
console.log(result)
},
}))- 请在每次调用处实时读取
ctx.client,因为服务器重启后客户端引用会更新。 - 服务器不可达时,所有调用都会 reject。
应用元数据
ctx.app 描述当前运行中的应用:
if (!ctx.app.packaged) console.log(`Acme on ${ctx.app.name} ${ctx.app.version} (${ctx.app.channel})`)name为"opencode",与服务端插件的ctx.app.name一致。platform在 Electron 桌面应用及main中为"desktop",在浏览器标签页中为"web"。packaged在桌面应用以打包形态运行时为true,在 Web 端始终为false。- 服务端插件获得
name、version和channel;TUI 插件获得version和channel。
类型参考
interface App {
name: string
version: string
channel: "local" | "dev" | "beta" | "prod"
platform: "web" | "desktop"
packaged: boolean
}契约与令牌(Contracts and tokens)
令牌(token)让 GUI 插件能够在跨进程及插件之间通信,而无需导入对方的运行时代码。请将所有令牌集中在 contract.ts 中:令牌只包含类型、ID 以及 Ipc 所需的 Schema,便于其他插件零副作用导入。
ctx.provide(token, impl):提供属于自己的令牌——在窗口setup中提供Contract,或在main中提供Ipc。ctx.use(token):追踪其他插件提供的Contract或Ipc,返回一个Live访问器。ctx.main(ipc):返回由你自己插件的main所提供Ipc的客户端。
插件只能提供 ID 等于自身 ID 或以 <id>.<name> 开头的令牌。为其他 ID 调用 ctx.provide,或为非自身 ID 的 Ipc 调用 ctx.main 都会抛出异常。本文示例假设插件 ID 为 acme,因此令牌 ID 均以 acme. 开头:
Contract.define<AcmeBadge, "acme.badge">("acme.badge") // Plugin acme can provide it.
Contract.define<AcmeBadge, "badge">("badge") // ctx.provide throws in plugin acme.契约(Contracts)
当某个插件的窗口 setup 需要向其他插件的窗口 setup 暴露 API 或 Solid 组件时,请使用 Contract.define:
import type { JSX } from "solid-js"
import { Contract } from "@opencode/plugin/gui"
export interface AcmeBadge {
Badge(props: { readonly label: string }): JSX.Element
count(): number
}
export const AcmeBadge = Contract.define<AcmeBadge, "acme.badge">("acme.badge")在窗口 setup 中使用 ctx.provide 提供实现。如果契约包含组件,请在 setup 期间用 bindPlugin 包装它,使组件内部的 usePlugin() 读取提供方而非消费方的上下文:
import { bindPlugin, Plugin } from "@opencode/plugin/gui"
import { AcmeBadge } from "./gui/contract"
export default Plugin.define({
i18n: { en: { title: "Acme" } },
setup(ctx) {
ctx.provide(AcmeBadge, {
Badge: bindPlugin((props: { readonly label: string }) => (
<span>
{ctx.t("title")}: {props.label}
</span>
)),
count: () => 42,
})
},
})- 请为传给
bindPlugin的组件显式标注 props 类型,如bindPlugin((props: FileTreeProps) => ...),TypeScript 无法在ctx.provide内自动推导。 count等普通数据方法无需包装。ctx.provide返回一个提前撤回契约的函数;宿主也会在当前 owner 释放或插件停止时自动撤回。
使用其他插件的契约
从你的包中导出 contract.ts(例如 ./contract),方便其他插件导入令牌。其他插件使用 ctx.use(token) 追踪该契约。随着提供方启动、停止或重启,访问器的值会动态变化,请在使用位置读取:
import { Plugin, Slot } from "@opencode/plugin/gui"
import { AcmeBadge } from "opencode-acme-plugin/contract"
export default Plugin.define({
setup(ctx) {
const badge = ctx.use(AcmeBadge)
const count = () => {
const live = badge()
return live.status === "active" ? live.value.count() : 0
}
ctx.add(Slot, { at: "window.bottom", render: () => <span>{count()}</span> })
},
})- 对同一令牌每次调用
ctx.use都返回同一个访问器。 - 即使提供方未运行,消费方依然可以正常工作,详见实时依赖与故障处理。
主进程与窗口间的 IPC
使用 Ipc.define 结合 Effect Schema 编解码器在 main 与 setup 之间建立类型安全桥梁。main 通过 ctx.provide 实现它,窗口通过 ctx.main 调用它:
import { Schema } from "effect"
import { Ipc } from "@opencode/plugin/gui"
export const KeepAwake = Ipc.define({
id: "acme.awake",
methods: {
screenActive: { output: Schema.Boolean },
setScreenActive: { input: Schema.Boolean },
},
})const awake = ctx.main(KeepAwake)
await awake.setScreenActive(true)- 其他插件可像普通契约一样通过
ctx.use(KeepAwake)订阅你的Ipc。 - 关于状态、事件和提供方实现,详见定义与提供 Ipc。
插件自有的注册表
使用 Registry.define 定义归你插件所有的扩展点列表。其他插件可通过 ctx.add 贡献条目,你的插件则通过 ctx.list 读取:
import { Registry } from "@opencode/plugin/gui"
export interface Exporter {
readonly id: string
readonly title: string
run(text: string): void
}
export const Exporter = Registry.define<Exporter>("acme.exporter")// Another plugin contributes an item.
ctx.add(Exporter, () => ({ id: "gist", title: ctx.t("exporter.gist"), run: (text) => upload(text) }))
// The owner lists every contribution. Reactive: read it in render or in a memo.
const exporters = () => ctx.list(Exporter)窗口进程(The window)
插件的 setup 会在每个桌面应用窗口中运行。在./gui-experimental 文件中将其传给 @opencode/plugin/gui 的 Plugin.define。setup 必须是同步函数,可返回一个清理函数,详见生命周期与清理:
import { Command, Plugin } from "@opencode/plugin/gui"
export default Plugin.define({
i18n: { en: { open: "Open Acme" } },
setup(ctx) {
ctx.add(Command, () => ({
id: "open",
title: ctx.t("open"),
run: () => ctx.system.openExternal("https://acme.example"),
}))
},
})组件
在 Solid 组件内部调用 usePlugin<typeof definition>() 即可获取与 setup 相同的上下文对象。建议将声明放在独立文件(参见拆分多文件)中供组件做类型引用,避免循环导入:
import { Slot, usePlugin, type Plugin } from "@opencode/plugin/gui"
import type { definition } from "./definition"
function StatusLabel() {
const ctx = usePlugin<typeof definition>()
return <span>{ctx.t("title")}</span>
}
export const setup: Plugin.Setup<typeof definition> = (ctx) => {
ctx.add(Slot, { at: "window.bottom", render: () => <StatusLabel /> })
}在插件贡献范围之外调用 usePlugin 会抛出异常。在由其他插件渲染的组件中,它返回渲染方的上下文,因此通过契约对外提供的组件务必用 bindPlugin 包装,参见契约。
图标(Icons)
SDK 中的所有 icon 字段以及 ctx.ui.Icon 都接受 IconName:即应用内置图标名,或你插件自行声明的图标名。传入任何其他字符串均无法通过编译:
ctx.add(TitlebarItem, () => ({ id: "sync", label: ctx.t("sync"), icon: "server", run: () => sync() }))声明自定义图标
对于应用未提供的图形(如你的产品标志),可将 SVG 文件保存在包中并在 icons 里声明。使用 ?raw 后缀导入,Vite gui() 预设会自动将其打包为字符串文本:
import { Plugin } from "@opencode/plugin/gui"
import logo from "./icons/logo.svg?raw"
export const definition = Plugin.define({
icons: { logo },
})随后在任意接受 IconName 的位置传入 ctx.icons 中的图标名即可:
import { ComposerPill, Slot, type Plugin } from "@opencode/plugin/gui"
import type { definition } from "./definition"
export const setup: Plugin.Setup<typeof definition> = (ctx) => {
ctx.add(ComposerPill, {
id: "sync",
show: () => ({ label: ctx.t("synced"), icon: ctx.icons.logo, tone: "success" }),
})
ctx.add(Slot, { at: "window.bottom", render: () => <ctx.ui.Icon name={ctx.icons.logo} size="small" /> })
}ctx.icons为每个已声明的图标生成一个键;引用未声明的名称会在编译阶段报错。- 宿主在
setup运行前注册你的图标,并在插件卸载时自动撤回。 - 非合法 SVG 文档的值会导致插件启动失败。
- 如需让
?raw导入通过类型检查,请在tsconfig.json的types中添加"vite/client"。
绘制图标
宿主会像绘制内置图标一样渲染你的图标,自动适配所在位置的尺寸与颜色:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none">
<circle cx="8" cy="8" r="6.5" stroke="currentColor" />
<path d="M5 8.5 7 10.5 11 6" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" />
</svg>- 图形边界由
viewBox(无viewBox时由width和height)决定。宿主会缩放到 14、16 或 20 像素,建议基于 16 像素网格绘制。 - 请使用
currentColor着色,这样图标才能自动继承所在位置的颜色(例如胶囊标签的tone或菜单行的弱化图标色)。 - SVG 内的
id作用于整个窗口 DOM,请确保 ID 全局唯一或直接省略。
动画图标
图标可以带有动效(例如表示任务进行中)。请在 SVG 文件内部使用 animate、animateTransform 等 SVG 动画元素:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none">
<circle cx="8" cy="8" r="6.5" stroke="currentColor" />
<circle cx="8" cy="8" r="2" fill="currentColor">
<animate attributeName="r" values="2;4.5;2" dur="2.4s" repeatCount="indefinite" />
</circle>
</svg>- 同一图标在界面上所有展示位置都会保持动画同步。
- 当宿主重新渲染所在区域(如胶囊标签的
show重新求值)时,动画不会中断。 - 当用户开启系统“减弱动态效果”偏好时,宿主会将所有图标定格在第一帧,请确保第一帧是完整的静止图形。
- 未在界面上显示的图标不消耗任何资源。
持久化图标名
图标名本质上是 <plugin id>:<name> 格式的字符串,因此宿主可以像保存内置图标一样持久化它。编辑器附注或引用会随草稿和已发送消息保留该图标,已关闭标签页也会随会话布局保留它:
ctx.screen.current()?.composer.attach({
type: "note",
origin: ctx.id,
commentID: crypto.randomUUID(),
label: "button#submit",
icon: ctx.icons.logo,
subject: 'element <button id="submit">Save</button>',
comment: "",
})- 当插件未激活时,该图标不绘制内容但仍保留占位尺寸。
- 请在使用处始终从
ctx.icons读取图标名,手写字符串无法通过类型检查。
类型参考
type IconName = AppIconName | PluginIconName
// One of the app's own icons, such as "folder", "github" or "terminal".
type AppIconName = string
// The name of an icon the plugin declared, from ctx.icons.
type PluginIconName = string
interface Declarations {
icons?: Record<string, string>
}
interface SetupContext<D> extends Context {
icons: Record<string, PluginIconName>
}注册表(Registries)
向 ctx.add 传入注册表令牌和条目即可向窗口外壳贡献功能。当条目依赖响应式状态(如界面语言)时,请以函数形式 () => item | undefined 传入;宿主会在依赖变化时自动重新求值。返回 undefined 会暂时撤回该条目,直到函数再次返回有效条目:
ctx.add(Command, () => ({ id: "open", title: ctx.t("command.open"), run: () => open() }))- 请在函数内部使用
ctx.t读取文案。在静态固定对象中读取的文案会一直停留在读取时的语言。 - 当条目包含字面量类型字段(如
hidden: true、section、icon或菜单名)时,请为函数标注返回类型:(): Command => ({ ... })。否则 TypeScript 会将字段拓宽为string或boolean,导致无法匹配重载。 - 对永不变化的内容(如样式)可直接传入固定对象。
- 宿主会保持部分对象引用稳定:面板
list返回的标签页,以及带render的条目(如面板和设置页)。请用 getter 读取其标签,例如get title() { return ctx.t("title") }。 ctx.add返回一个函数,可用于提前撤回该条目。
命令(Commands)
Command 可向命令面板、Settings > Shortcuts 以及可选的输入框 / 菜单添加操作。宿主会以 <plugin id>.<command id> 形式发布该命令:
import { Command } from "@opencode/plugin/gui"
ctx.add(
Command,
(): Command => ({
id: "toggle",
title: ctx.t("command.toggle"),
keywords: "notes scratch",
group: ctx.t("command.category.view"),
section: "terminal",
bind: "ctrl+`",
slash: { name: "notes", after: "open" },
featured: true,
enabled: !!ctx.sessions.current(),
run: () => {
const session = ctx.sessions.current()
if (session) ctx.layout.toggle(`${ctx.id}:main`, session)
},
}),
)title为命令面板标题,description为副标题行,group为分组名,均传入翻译后的文本。keywords包含额外的空格分隔搜索关键词。section指定 Settings > Shortcuts 中的分区,默认为general。bind为默认快捷键(如mod+shift+t),用户可自行修改。slash同时将该命令暴露到/菜单中;设arguments: true时,命令名后的文本会传给run(input)。hidden将命令从命令面板中隐藏,但其快捷键依然生效。suggested在命令启用时将其列在 Suggested 下;featured在未输入搜索词打开命令面板时展示。enabled: false会将命令移出命令面板并禁用其快捷键,支持响应式更新。scope为 CSS 选择器,键盘焦点位于其内部时快捷键才会生效;配置editable后在文本输入框聚焦时同样触发。- 如需从代码中主动触发命令,请使用
ctx.commands.run,详见运行命令。
通过快捷键触发时,run 可以同步返回 false 放弃消费该按键,事件将继续传递给原始目标,就像该命令未绑定快捷键一样。下例在空提示词中按 Enter 时继续会话,而将其他情况下的 Enter 交还给输入框:
ctx.add(Command, () => ({
id: "continue",
title: ctx.t("command.continue"),
bind: "enter",
editable: true,
hidden: true,
run: () => {
const composer = ctx.screen.current()?.composer
const session = ctx.sessions.current()
if (!composer?.focused() || composer.text().trim() || !session) return false
void session.server.client.session.prompt({ sessionID: session.id, text: ctx.t("continue") })
},
}))- 必须同步返回
false;返回 Promise 表示已接管该按键。 - 从命令面板或斜杠命令返回
false不会触发额外行为。
类型参考
interface Command {
id: string
title: string
description?: string
keywords?: string
group?: string
section?: "general" | "session" | "navigation" | "model" | "terminal" | "prompt"
bind?: string
slash?: { name: string; arguments?: true; after?: string }
hidden?: true
suggested?: boolean
featured?: true
enabled?: boolean
scope?: string
editable?: true
run(input?: string): void | false | Promise<void>
}面板(Panels)
Panel 向会话的侧边区域(region: "side")贡献标签页。用户也可以将标签页拖拽到时间线下方的底部窗格中:
import { Panel, type PanelTab } from "@opencode/plugin/gui"
const mainTab: PanelTab = {
id: "main",
get title() {
return ctx.t("panel.title")
},
closable: "compact",
fallback: true,
}
ctx.add(Panel, {
id: "main",
region: "side",
mobile: {
get title() {
return ctx.t("panel.title")
},
order: 45,
kind: "menu",
icon: "file-tree",
},
list: (input) => (input.open.includes("main") ? [mainTab] : []),
render: (props) => <NotesView session={props.session} screen={props.screen} tab={props.tab} />,
})所有面板回调(list、render、focus、enter、close、closed、restore、normalize)均接收单个输入对象:
- 请在使用处通过响应式 getter 读取
props.session与props.tab,切勿在render顶部解构:当用户从会话 A 切换到会话 B 时,面板保持挂载,props.session会原地更新。 props.screen是恒定的所属SessionScreen(含file、comment、composer),其操作始终作用于当前路由到的会话。- 只要某个标签页未变化,
list应返回同一个PanelTab对象,避免宿主重新挂载标签触发器;通过 getter 读取其标签文本,即可在不创建新对象的情况下响应语言切换。
面板回调函数说明:
list:返回要显示的标签页列表。input.open保存了本插件在该会话中已存储打开的标签 ID,具有响应式特性。render:一次性渲染标签页内容。focus:选中标签页时运行;当区域挂载时自动恢复选中态时restored为true。enter:用户通过开关按钮打开侧边区域并呈现该标签页后触发,可将键盘焦点移动到标签内的目标元素(如输入框);若焦点仍停留在区域外,宿主会自动聚焦该区域。close:宿主移除标签页后触发。closed与restore:允许用户重新打开已关闭标签页,详见重新打开已关闭标签页。normalize:对于存在多种存储形式的标签 ID,返回其规范化形式。
面板配置选项说明:
mobile:提供窄屏视图;设cached: true时在切换至其他视图后保持挂载,默认每次展示重新挂载。wide:侧边区域打开时请求更宽的会话最小宽度。width:为面板设置专属侧边栏宽度,详见面板宽度。transient:临时面板的标签页不会被恢复。
面板宽度
默认情况下,侧边区域中的所有标签页共享会话配置的宽度。当你的面板比代码审查或浏览器需要更窄或更宽的空间时,可设置 width——传入 CSS 像素值,或传入 "narrow" 表示区域允许的最窄宽度:
ctx.add(Panel, {
id: "quota",
region: "side",
width: "narrow",
list: (input) => (input.open.includes("quota") ? [tab] : []),
render: () => <Quota />,
})- 该宽度仅在侧边窗格显示该面板的标签页时生效,其他标签页仍沿用会话宽度。
- 当用户在你的面板标签页上拖动分隔线调整宽度后,宿主会在全应用范围内记住该宽度,并优先于默认
width。 - 宿主会确保对话区不低于最小宽度,且侧边区域不窄于
"narrow"。 ctx.layout.side.width(panel)读取已保存宽度,ctx.layout.side.resize(panel, width)保存新宽度(效果等同于用户拖拽);即使面板未配置width,已保存的宽度同样生效。
标签页选项说明:
id为标签页 ID,宿主键为<plugin id>:<id>;title为无障碍名称,label用于自定义标签头内容。pinned固定标签无需打开即展示,排在最前且不可关闭或拖拽。draggable允许用户拖拽排序,默认为true。closable设置关闭按钮样式:"compact"、"hover"或false(无关闭按钮)。transient标记启动器类标签(如 Open file),下一次预览会将其替换。fallback在已保存的选中标签缺失时允许回退选中该标签。- 同一
group内的标签共享同一个保持挂载的渲染实例。 missing为标签添加删除线(例如对应文件已不存在)。hidden保持已恢复的标签在列表中且可选中,但在其内容尚未就绪时不绘制。file为该标签展示的工作区文件路径,会列在会话已打开文件列表中。tabbable将标签面板纳入键盘 Tab 顺序,适用于内部不含可聚焦元素的内容。
类型参考
interface Panel {
id: string
region: "side"
mobile?: MobileView
wide?: boolean
width?: number | "narrow"
transient?: boolean
list(input: { session: MountedSession; screen: SessionScreen; open: string[] }): PanelTab[]
render(props: PanelProps): JSX.Element
focus?(input: PanelProps & { restored: boolean }): void
enter?(input: PanelProps): void
close?(input: PanelProps): void
closed?(input: PanelProps): ClosedPanelTab | false | undefined
restore?(input: { session: MountedSession; screen: SessionScreen; id: string; data?: string }): void
normalize?(input: { id: string; session: MountedSession; screen: SessionScreen }): string
}
interface PanelProps {
tab: PanelTab
session: MountedSession
screen: SessionScreen
}
interface PanelTab {
id: string
title: string
label?(state: { active: boolean; preview: boolean; session: MountedSession }): JSX.Element
pinned?: boolean
draggable?: boolean
closable?: "compact" | "hover" | false
transient?: boolean
fallback?: boolean
group?: string
missing?: boolean
hidden?: boolean
file?: string
tabbable?: boolean
}
interface MobileView {
title: string
order: number
kind: "tab" | "menu" | "drawer"
icon?: IconName
cached?: boolean
}重新打开已关闭标签页
宿主会为每个被用户关闭的侧边标签保留记录。当焦点位于侧边区域时,按 ⌘⇧T 会重新打开最近关闭的标签;侧边区域的 New tab 视图也会在 Recently closed 下展示带 file 的已关闭标签。实现 closed 与 restore 即可自定义条目展示方式与恢复逻辑:
ctx.add(Panel, {
id: "page",
region: "side",
list: (input) => input.open.map(pageTab),
render: (props) => <PageView tab={props.tab} />,
closed: (input) => {
const url = pages.get(input.tab.id)
return url ? { icon: "globe", detail: new URL(url).host, data: url } : false
},
restore: (input) => {
if (input.data) openPage(input.session, input.data)
},
})closed在用户关闭标签页时执行。此时应捕获恢复所需的信息:返回条目展示字段及restore所需的data,若不可恢复则返回false。title默认取标签标题,icon默认取面板移动端图标;带file的标签自动显示文件图标,并以所在目录作为detail。- 宿主会持久化存储该记录,请保持
data尽量精简(如仅存 URL)。 restore接收关闭标签的id以及closed返回的data;省略restore时宿主直接重新打开原键。- 省略
closed时,非transient标签会按其标题列入记录并以原键重新打开。
类型参考
interface ClosedPanelTab {
title?: string
icon?: IconName
detail?: string
data?: string
}设置页面(Settings pages)
SettingsPage 可向 Settings 贡献独立页面、向宿主页面(page: "general" 或 page: "servers")添加分区,或向宿主 General 分区添加设置行(page: "general", section: "general"):
import { SettingsPage } from "@opencode/plugin/gui"
import { AcmeSettings } from "./settings"
ctx.add(SettingsPage, {
id: "acme",
icon: "server",
get title() {
return ctx.t("title")
},
get entries() {
return [{ id: "sync", title: ctx.t("settings.sync"), keywords: "sync remote" }]
},
render: (input) => <AcmeSettings highlight={input.target} />,
})id既是该设置标签页的路由参数(/settings?tab=<id>),也是ctx.layout.settings的入参。- 指定
page会在宿主页面内添加分区而非独立页面;同时指定section: "general"则直接向该页的 General 分区添加行。 title与icon为独立设置页的导航标题和图标。entries为搜索索引元数据,无需挂载页面即可被设置搜索检索;搜索定位到某条记录时,render会收到其id作为target。- 设置页带有
render,因此宿主会保持对象稳定,请使用 getter 读取其标题与entries。
请使用应用内置的设置组件渲染页面,以确保外观与原生设置页一致并支持搜索定位高亮:
const ui = ctx.ui
const AcmeSettings = () => (
<ui.SettingsLayout title={ctx.t("title")} description={ctx.t("description")}>
<ui.SettingsSection title={ctx.t("settings.section")}>
<ui.SettingsRow id="sync" title={ctx.t("settings.sync")} description={ctx.t("settings.sync.description")}>
<ui.Switch label={ctx.t("settings.sync")} hideLabel checked={sync()} onChange={setSync} />
</ui.SettingsRow>
</ui.SettingsSection>
</ui.SettingsLayout>
)- 独立页面渲染
SettingsLayout,宿主页面中的分区(page)渲染SettingsSection,宿主分区中的行(section)直接渲染SettingsRow。 - 行组件上的
id对应触发定位的SettingEntry.id,搜索会自动滚动并高亮该行。 - 组件属性详见设置组件。
类型参考
interface SettingsPage {
id: string
page?: "general" | "servers"
section?: "general"
title: string
icon?: IconName
entries?: SettingEntry[]
render(input: { target?: string }): JSX.Element
}
interface SettingEntry {
id: string
title: string
description?: string
keywords?: string
}插槽(Slots)
Slot 将 UI 渲染到四个窗口插槽之一:
import { Slot } from "@opencode/plugin/gui"
ctx.add(Slot, {
at: "session.header",
order: 10,
render: (input) => <UsageRing session={input.session} active={input.active} />,
})window.bottom:窗口底部的全宽条带,位于轻提示(toasts)上方。session.header:会话时间线的标题行。缓存的时间线隐藏时仍保持挂载,此时active为false。session.location.menu:向项目菜单追加条目,位于其位置信息之后。session.panel.end:位于侧边区域标签栏末尾的操作位。order用于对同一插槽内的条目排序。
session.location.menu 会接收 shown 属性,仅当项目菜单打开时为 true,建议仅在此期间订阅位置数据:
ctx.add(Slot, {
at: "session.location.menu",
render: (input) => <BranchStatus session={input.session} screen={input.screen} shown={input.shown} />,
})项目菜单是宿主原生菜单:请使用 ctx.ui.MenuItem、MenuSub、MenuGroup 与 MenuSeparator 渲染行项,以获得与宿主一致的键盘导航及选中关闭行为,详见菜单行组件:
ctx.add(Slot, {
at: "session.location.menu",
render: (input) => <ctx.ui.MenuItem label={ctx.t("usage")} icon="status" onSelect={() => openUsage(input.session)} />,
})类型参考
type Slot = {
[At in keyof SlotMap]: { at: At; order?: number; render(input: SlotMap[At]): JSX.Element }
}[keyof SlotMap]
interface SlotMap {
"window.bottom": Record<string, never>
"session.header": { screen: SessionScreen; session: MountedSession; active: boolean }
"session.location.menu": { screen: SessionScreen; session: MountedSession; shown: boolean }
"session.panel.end": { screen: SessionScreen; session: MountedSession }
}菜单项(Menu items)
MenuItem 向侧边面板的 + 菜单("session.panel")、Add server 菜单("server.add")或设置中每行服务器的菜单("server.row")添加条目:
import { MenuItem } from "@opencode/plugin/gui"
ctx.add(MenuItem, (): MenuItem => {
const session = ctx.sessions.current()
return {
menu: "session.panel",
id: "open",
title: ctx.t("menu.open"),
icon: "folder",
keybind: `${ctx.id}.open`,
opened: !!session && ctx.layout.state(`${ctx.id}:main`, session) !== "closed",
run: () => {
if (session) ctx.layout.open(`${ctx.id}:main`, session)
},
}
})order按升序排列条目,默认为0。server.row条目的run会接收对应行的服务器键;when控制仅在部分行显示该条目,enabled控制在其他行置灰禁用。
session.panel 条目同时充当启动器。当用户打开空的侧边区域,或在无 primary 条目时点击 +,宿主会显示列出所有启动器的 New tab 视图:
icon为条目图标,keybind为已发布命令的 ID,用于展示对应快捷键。description为启动器行标题后的弱化补充信息(如计数)。opened: true表示该条目对应的标签页已打开:启动器列表会隐藏它,但 + 菜单仍会显示。primary: true使点击 + 直接执行该条目而非显示启动器列表,按order排在最前的 primary 条目胜出。打开空侧边区域时仍显示 New tab 视图,列出非 primary 且未打开的条目。ctx.layout.side.menu()返回全部插件的session.panel条目,供你构建自定义启动器,详见布局。
类型参考
type MenuItem = SessionPanelMenuItem | ServerAddMenuItem | ServerRowMenuItem
interface SessionPanelMenuItem {
menu: "session.panel"
id: string
title: string
order?: number
icon?: IconName
keybind?: string
description?: string
opened?: boolean
primary?: true
run(): void
}
interface ServerAddMenuItem {
menu: "server.add"
id: string
title: string
order?: number
run(): void
}
interface ServerRowMenuItem {
menu: "server.row"
id: string
title: string
order?: number
when?(server: string): boolean
enabled?(server: string): boolean
run(server: string): void
}标题栏项(Titlebar items)
TitlebarItem 在窗口标题栏或标签栏底部渲染一个胶囊按钮,悬停时显示其 label:
import { TitlebarItem } from "@opencode/plugin/gui"
ctx.add(TitlebarItem, (): TitlebarItem | undefined =>
syncing() ? { id: "sync", label: ctx.t("syncing"), icon: "server", busy: true, run: () => sync() } : undefined,
)title用于指定与label不同的无障碍名称。busy显示加载指示器并禁用按钮;pressed呈现按下态。run在点击时触发;仅用于状态展示时可省略。
类型参考
interface TitlebarItem {
id: string
label: string
title?: string
icon?: IconName
busy?: boolean
pressed?: boolean
run?(): void
}编辑器胶囊状态(Composer pills)
ComposerPill 在会话编辑器上方的一行中添加胶囊标签,紧邻应用的后台任务与待办胶囊。适用于展示当前会话相关的状态(例如当前分支的 Pull Request)。胶囊悬浮于时间线上方,出现或消失都不会导致编辑器抖动缩放。该行遵循用户的后台活动对齐设置,且不会在子代理会话中显示。
show 为单个会话返回胶囊配置,或返回 undefined 表示不显示。宿主会为每个已挂载的编辑器运行它,并在依赖变化时自动更新。下例通过服务端插件的 RPC 列出每个会话目录的未合并 Pull Request,并以单个胶囊展示:
import { createStore } from "solid-js/store"
import { ComposerPill, createKeyed } from "@opencode/plugin/gui"
import { GitHub, type Pull } from "./rpc"
const [pulls, setPulls] = createStore<Record<string, readonly Pull[]>>({})
createKeyed(
() => ctx.sessions.current()?.directory,
(directory) =>
void ctx.client
.rpc(GitHub)
.pulls({ directory })
.then((list) => setPulls(directory, list)),
)
ctx.add(ComposerPill, {
id: "pulls",
show: (input) => {
const list = pulls[input.session.directory] ?? []
if (list.length === 0) return undefined
return {
icon: "github",
label: ctx.plural("pulls", list.length),
tone: list.some((pull) => pull.checks === "failure") ? "danger" : undefined,
title: ctx.t("pulls.title"),
rows: list.map((pull) => ({
id: String(pull.number),
label: `#${pull.number} ${pull.title}`,
icon: pull.checks === "failure" ? "circle-x" : "circle-check",
tone: pull.checks === "failure" ? "danger" : "success",
detail: pull.branch,
run: () => ctx.system.openExternal(pull.url),
})),
}
},
})label为胶囊文本,过长时自动截断;icon可选。tone为图标着色:"success"、"warning"或"danger"。- 如需应用内置图标之外的图形(如动态状态图标),请声明自定义图标并传入
ctx.icons.<name>。它同样响应tone,且show重新执行时动画持续不中断。 - 配置
rows后,点击胶囊会打开菜单,顶部标题取title(省略时取label)。每行可配icon、tone、弱化文本detail及点击回调run;省略run的行仅作展示。 - 未配置
rows时,点击胶囊直接执行run。 - 当无障碍名称与
label不同时可通过title指定。 order用于在多个插件胶囊之间升序排列;应用内置胶囊始终排在最前。show抛出异常仅影响本插件的该条贡献。
类型参考
interface ComposerPill {
id: string
order?: number
show(input: ComposerPillProps): ComposerPillView | undefined
}
interface ComposerPillProps {
session: MountedSession
screen: SessionScreen
}
interface ComposerPillView {
label: string
icon?: IconName
tone?: ComposerPillTone
title?: string
rows?: ComposerPillRow[]
run?(): void
}
interface ComposerPillRow {
id: string
label: string
icon?: IconName
tone?: ComposerPillTone
detail?: string
run?(): void
}
type ComposerPillTone = "success" | "warning" | "danger"代码块渲染器(Code blocks)
CodeBlock 将指定语言的围栏代码块替换为你的自定义 UI,取代默认语法高亮。适合图表或排版优于源码阅读的内容,例如 ```csv 表格或 ```latex 公式:
import { For } from "solid-js"
import { CodeBlock } from "@opencode/plugin/gui"
ctx.add(CodeBlock, {
languages: ["csv"],
render: (props) => {
const rows = props.code.split("\n").map((line) => line.split(","))
if (rows.length < 2) return undefined
return (
<table>
<tbody>
<For each={rows}>
{(row) => (
<tr>
<For each={row}>{(cell) => <td>{cell}</td>}</For>
</tr>
)}
</For>
</tbody>
</table>
)
},
})languages与代码块围栏 info 字符串的首个单词(小写)比对,例如```CSV title="Q3"会匹配csv。宿主不解析语言别名,请列出你接受的所有名称。render接收代码块的code、language以及所在session。返回undefined或null可回退显示高亮源码(例如解析失败时)。- 如果
render抛出异常,错误会记录在你的插件名下,代码块回退显示源码,你的其他贡献不受影响。 - 若多个插件声明了同一语言,以最先注册的为准。声明
mermaid还会替换应用内置的 Mermaid 图表渲染器。
流式输出
宿主仅在代码块的闭合围栏到达后才调用自定义渲染器。流式传输过程中,以及在中途中断的消息里,用户会先看到高亮源码;闭合后你的 UI 会原地替换上去。因此 render 永远不会收到半截代码块。
生效范围
| 界面区域 | 是否启用自定义代码块 |
|---|---|
| 时间线:助手文本与工具输出 | 是 |
| 会话界面侧边面板(如 Markdown 预览) | 是 |
在会话界面中渲染的 ctx.ui.Markdown | 是 |
ctx.ui.Code,以及你自己 CodeBlock 渲染器内部的 Markdown | 否 |
| 设置页面、弹窗及其他非会话界面 | 否 |
布局与性能
- 未被任何插件声明的语言代码块零开销;只有匹配语言的代码块才会在其时间线行进入视口时渲染你的 UI。
- 代码块高度随你的 UI 自适应伸缩。对于异步加载内容,建议设置最小高度以减少内容到达时的时间线跳动。
- 代码块右上角仍保留复制源码的 Copy 按钮,以及你注册的
CodeBlockAction按钮。
代码块操作按钮(Code block actions)
CodeBlockAction 在指定语言代码块的 Copy 按钮旁添加自定义按钮,run 接收与 CodeBlock 渲染器相同的代码块对象:
import { CodeBlockAction } from "@opencode/plugin/gui"
ctx.add(CodeBlockAction, {
id: "run",
languages: ["sh", "bash", "shell", "zsh"],
icon: "terminal",
get title() {
return ctx.t("run")
},
run: (input) => runInTerminal(input.code, input.session),
})- 按钮仅在代码块闭合围栏到达后显示,避免对不完整命令执行操作。
- 悬停或键盘聚焦时按钮会按
order升序排列显示在 Copy 按钮之前。 - 请用 getter 读取
title,使其跟随界面语言更新。 run抛出的同步错误或异步 reject 会记入你的插件日志,不影响其他功能。
类型参考
interface CodeBlock {
languages: string[]
render(props: CodeBlockProps): JSX.Element | undefined
}
interface CodeBlockAction {
id: string
languages: string[]
icon: IconName
title: string
order?: number
run(input: CodeBlockProps): void | Promise<void>
}
interface CodeBlockProps {
code: string
language: string
session?: MountedSession
}链接处理器(Link handlers)
LinkHandler 负责打开用户在消息或编辑器标签中点击的本地文件或自定义链接。所有 match 返回 true 的处理器中,priority 最高者负责打开该链接:
import { LinkHandler } from "@opencode/plugin/gui"
ctx.add(LinkHandler, {
priority: 10,
match: (link) => link.href.endsWith(".acme"),
open: (link) => openAcmeFile(link.href, link.session),
exists: (link) => acmeFileExists(link.href),
})href为目标地址:文件路径、URL 或file://链接。origin为生成该链接条目的插件。exact表示该路径为已知工作区文件,而非从文本猜测。background链接不得切换窄屏视图。base为书写该链接时所在的工作区相对目录。- 若未提供
exists,ctx.links.exists返回false,避免将无法打开的文本误渲染为可点击链接。
类型参考
interface LinkHandler {
priority?: number
match(link: Link): boolean
open(link: Link): void
exists?(link: Link): boolean | Promise<boolean>
}
interface Link {
href: string
origin?: string
exact?: boolean
background?: boolean
base?: string
session?: SessionRef
}服务器源(Servers)
Server 用于贡献一组服务器连接列表,例如你插件在其他主机上启动的服务器:
import { Server } from "@opencode/plugin/gui"
ctx.add(
Server,
(): Server => ({
ready: loaded(),
entries: machines().map((machine) => ({
id: machine.id,
name: machine.name,
label: "Acme",
state: machine.url ? "ready" : "starting",
http: machine.url ? { url: machine.url } : undefined,
})),
}),
)- 启动阶段会等待每个服务器源进入
ready状态;就绪源的条目构成其完整清单。 order按升序排列各服务器源。- 每个条目的键为
<plugin id>:<id>,label为显示在name旁的简短徽章。 auth表示服务器正等待用户登录,incompatible表示服务器版本与当前应用不兼容。listed: false将条目从应用服务器列表中隐藏,但设置页面中仍会显示。- 服务器就绪后,
http提供对应的端点信息。 reconnect重新解析断开的端点,connect准备尚未就绪的服务器,remove在移除条目前运行。row渲染该服务器在设置中的行,cover在服务器未就绪时覆盖当前路由的会话界面。row会收到宿主的状态Indicator、最新的health()检查结果以及该行的server.row菜单Items;调用其remove()会先运行条目的remove再关闭该服务器的全部标签页。
类型参考
interface Server {
ready: boolean
order?: number
entries: ServerEntry[]
}
interface ServerEntry {
id: string
name: string
label?: string
state: "stopped" | "starting" | "auth" | "ready" | "failed" | "incompatible"
listed?: boolean
http?: { url: string; password?: string }
reconnect?(signal: AbortSignal): Promise<{ url: string; password?: string }>
connect?(): Promise<boolean>
remove?(): Promise<void>
row?(row: ServerRow): JSX.Element
cover?(input: { tab: string }): JSX.Element
}
interface ServerRow {
key: string
health(): ServerHealth | undefined
Indicator(props: { health?: ServerHealth; connecting?: boolean; auth?: boolean }): JSX.Element
remove(): Promise<void>
Items(): JSX.Element
}
interface ServerHealth {
healthy: boolean
version?: string
incompatible?: boolean
checking?: boolean
}样式(Styles)
Style 在贡献活跃期间向文档注入一段 CSS 字符串:
import { Style } from "@opencode/plugin/gui"
import css from "./panel.css?inline"
ctx.add(Style, css)主题(Themes)
Theme 向 Settings › Appearance › Theme 添加配色主题。其格式与应用内置主题文件完全一致,可直接原样导入主题文件:
import { Theme } from "@opencode/plugin/gui"
import midnight from "./midnight.json"
ctx.add(Theme, midnight)主题文件包含自身名称以及浅色(light)和深色(dark)两套变体。每套变体必须基于 palette 或 seeds 之一(不可混用),并可用 overrides 精确固定单个令牌:
{
"$schema": "https://opencode.ai/desktop-theme.json",
"name": "Midnight",
"id": "midnight",
"light": {
"palette": {
"neutral": "#eceff4",
"ink": "#2e3440",
"primary": "#5e81ac",
"success": "#8fbcbb",
"warning": "#d08770",
"error": "#bf616a",
"info": "#81a1c1"
}
},
"dark": {
"palette": {
"neutral": "#1b1f27",
"ink": "#e5e9f0",
"primary": "#88c0d0",
"success": "#a3be8c",
"warning": "#d08770",
"error": "#bf616a",
"info": "#81a1c1"
},
"overrides": { "syntax-keyword": "#88c0d0" }
}
}- 主题选择器会将插件主题与应用内置主题混合,按
name字母序排列。 - 宿主以
<plugin id>:<theme id>为键保存主题,因此不会覆盖内置主题或其他插件的主题。 - 撤回主题或停用插件会将其移出选择器,但已选中该主题的用户仍会保留其偏好:在主题恢复前窗口回退显示默认主题。
- 应用启动时,在插件重新贡献主题之前,窗口会先使用上次运行缓存的配色。
宿主 API(Host APIs)
宿主 API 均挂载在 ctx 上,在应用界面挂载前调用也不会抛出异常:读取操作会返回文档声明的默认值;早期写入操作(如 ctx.layout.open、ctx.dialogs.open 与 store 更新)会自动排队,待首个路由渲染完成后按调用顺序应用:
ctx.add(Command, () => ({
id: "copy-directory",
title: ctx.t("command.copyDirectory"),
run: () => {
const session = ctx.sessions.current()
if (session) void ctx.system.copy(session.directory)
},
}))下文将逐一介绍各项 API。ctx.options、ctx.client 和 ctx.app 属于共享上下文;ctx.provide、ctx.use 和 ctx.main 用于操作契约与令牌;ctx.stores 持有插件声明的 store;ctx.icons 持有声明的图标名。
类型参考
interface SetupContext<D> extends Context {
stores: Record<string, Persisted<unknown> | ((session: SessionRef) => Persisted<unknown>)>
icons: Record<string, PluginIconName>
}
interface Context {
id: string
options: PluginOptions
client: OpenCodeClient
app: App
signal: AbortSignal
add<T>(registry: Registry<T>, item: () => T | undefined): Cleanup
add<T>(registry: Registry<T>, item: T): Cleanup
list<T>(registry: Registry<T>): T[]
provide<T>(token: Contract<T>, impl: T): Cleanup
use<T>(token: Contract<T>): () => Live<T>
use<S extends IpcSpec>(token: Ipc<S>): () => Live<IpcClient<S>>
main<S extends IpcSpec>(token: Ipc<S>): IpcClient<S>
t(key: string, params?: Record<string, string | number | boolean>): string
plural(key: string, count: number, params?: Record<string, string | number | boolean>): string
layout: Layout
sessions: Sessions
screen: Screen
servers: Servers
storage: Storage
dialogs: Dialogs
toast: Toasts
attention: Attention
tabs: Tabs
keybinds: Keybinds
commands: Commands
links: Links
embeds: Embeds
ui: Ui
system: System
desktop: Desktop | undefined
locale: Locale
appearance: Appearance
router: Router
workspaces: Workspaces
}布局(Layout)
ctx.layout.open(key, session, options?) 通过键 <plugin id>:<tab id> 打开面板标签页,即使目标会话当前未挂载也能生效:
const session = ctx.sessions.current()
if (session) ctx.layout.open(`${ctx.id}:main`, session, { tab: "select", background: true })tab: "open"(默认)在预览槽位中选中该标签;"preview"将其设为新预览标签;"append"追加但不选中;"select"追加并选中且保留原有预览。background: true在窄屏下保持当前视图不变并打开侧边区域,适用于并非从面板内发起的操作。close(key, session)移除标签并调用其面板的close;toggle(key, session)在标签可见时关闭它,否则打开它。hide(key, session)隐藏显示该可见标签的窗格(侧边区域或用户拖去的底部窗格)而不关闭标签本身;再次打开标签会重新显示其窗格。state(key, session):不在标签栏中为"closed";在标签栏但窗格显示其他标签为"open";窗格选中它但窗格隐藏(侧边区关闭或底部窗格隐藏)为"active";正在屏幕上显示为"visible"。stored(session)返回本插件保存在该会话侧边栏中的标签 ID 列表。ready()在持久化布局加载完成后为true;narrow()在视口宽度小于 768px 时为true。side.opened(session)在侧边区域打开时为true,side.toggle(session)用于切换开关状态。side.menu()按order列出所有插件的session.panel菜单项,供自定义启动器使用。side.width(panel)与side.resize(panel, width)读写你某个面板的侧边区域宽度,详见面板宽度。sidebar.opened()为所有侧边面板共享的内部侧栏展开偏好。scroll按会话与键保存滚动偏移量。settings(page?)打开设置界面;project(server, title)打开项目目录选择器并创建新草稿。draft({ server, directory, prompt })在独立标签页中打开新的草稿会话,并预填提示词供用户审阅后发送。
const session = ctx.sessions.current()
const launchers = () => ctx.layout.side.menu().filter((item) => !item.primary && !item.opened)
if (session) {
ctx.layout.draft({ server: session.server.id, directory: session.directory, prompt: ctx.t("setup.prompt") })
}类型参考
interface Layout {
open(key: string, session: SessionRef, options?: OpenOptions): void
close(key: string, session: SessionRef): void
toggle(key: string, session: SessionRef): void
hide(key: string, session: SessionRef): void
state(key: string, session: SessionRef): PanelState
stored(session: SessionRef): string[]
ready(): boolean
narrow(): boolean
side: {
opened(session: SessionRef): boolean
toggle(session: SessionRef): void
menu(): SessionPanelMenuItem[]
width(panel: string): number | undefined
resize(panel: string, width: number): void
}
sidebar: {
opened(): boolean
}
scroll: {
get(session: SessionRef, key: string): { x: number; y: number } | undefined
set(session: SessionRef, key: string, value: { x: number; y: number }): void
}
settings(page?: string): void
project(server: string, title: string): void
draft(input: { server: string; directory: string; prompt: string }): void
}
type PanelState = "closed" | "open" | "active" | "visible"
interface OpenOptions {
tab?: "open" | "preview" | "append" | "select"
background?: boolean
}会话与会话界面(Sessions and the session screen)
ctx.sessions.current() 返回当前路由到的会话,ctx.screen.current() 返回其界面对象。在首页和草稿页上两者均为 undefined。请在执行操作处实时读取,切勿在 setup 中只读一次:
const session = ctx.sessions.current()
const file = ctx.screen.current()?.file
if (session && file) void file.sync("README.md")key为<server id>\n<session id>,跨服务器唯一,适合用作按会话隔离状态的键。tab为所属外壳标签页的键;服务器仍在创建会话时pending为true。directory为会话工作区目录;若与项目根目录一致则local为true。listedProject为会话所属的侧栏项目。visit在每次路由进入该会话时都会生成新对象。background列出会话中正在运行的子代理与 Shell 命令。ctx.sessions.list()返回所有已打开外壳标签页对应的会话。- 界面对象上的
file用于读取工作区文件,comment持有下一次提示词的行级批注,composer表示下一次提示词(文本、附加分片及模型),详见附加内容到编辑器。 file.sync(path)加载文件并请求服务器监听其变更;文件标签页关闭时请调用file.unwatch(path)。
类型参考
interface Sessions {
list(): SessionRef[]
current(): MountedSession | undefined
}
interface SessionRef {
key: string
id: string
tab: string
server: ServerRef
pending: boolean
location: LocationRef | undefined
}
interface MountedSession extends SessionRef {
visit: object
project: Project | undefined
listedProject: { worktree: string; name?: string; icon?: Project["icon"] } | undefined
directory: string
local: boolean
background: BackgroundTask[]
}
interface Screen {
current(): SessionScreen | undefined
}
interface SessionScreen {
file: Files
comment: Comments
composer: Composer
}
interface Files {
root: string
ready(): boolean
resolve(path: string): string
absolute(path: string): boolean
get(path: string): FileState | undefined
missing(path: string): boolean
sync(path: string, options?: { force?: boolean; silent?: boolean }): Promise<void>
unwatch(path: string): void
exists(path: string): Promise<boolean>
search(query: string, options?: { kind?: "file" | "any"; limit?: number; signal?: AbortSignal }): Promise<string[]>
selection: {
get(path: string): LineRange | null | undefined
set(path: string, range: LineRange | null): void
}
scroll: {
get(path: string): { top?: number; left?: number }
set(path: string, value: { top?: number; left?: number }): void
}
tree: {
list(path: string): FileNode[]
state(path: string): { expanded: boolean; loaded?: boolean; loading?: boolean; error?: string } | undefined
sync(path: string, options?: { force?: boolean }): Promise<void>
expand(path: string, options?: { list?: boolean }): void
collapse(path: string): void
}
}
interface Comments {
list(file?: string): Comment[]
add(input: Omit<Comment, "id" | "time">): Comment
update(id: string, comment: string): void
remove(id: string): void
focus: {
current(): { file: string; id: string } | null
set(value: { file: string; id: string } | null): void
}
active: {
current(): { file: string; id: string } | null
set(value: { file: string; id: string } | null): void
}
}附加内容到编辑器(Attach to the composer)
在事件处理器或命令中使用 ctx.screen.current()?.composer,即可将文件、附注(note)或引用(quote)附加到用户的下一次提示词中:
const composer = ctx.screen.current()?.composer
composer?.attach({
type: "note",
origin: ctx.id,
commentID: crypto.randomUUID(),
label: "button#submit",
icon: "globe",
subject: 'element <button id="submit">Save</button>',
comment: "Make this button primary and disable it while saving.",
href: "http://localhost:3000/settings",
})attach不会改变当前键盘焦点;如需聚焦到输入框,请调用focus()。update(commentID, { comment?, preview? })修改已附加分片;附注或引用仅支持更新comment。detach(commentID)移除已附加分片。- 附注的
live字段在附注停留于当前应用进程期间替代其subject与href,适用于仅本进程可解析的引用(如页面 DOM 元素)。草稿持久化以及通过回退或分叉恢复的已发送消息会丢弃live。
引用(quote)是用户从你插件展示内容(如日志输出)中摘录的文本及可选批注。它会像会话时间线引用一样,以来源图标和标签渲染。调用前请先检查 quotable():在没有编辑器的子代理会话中,或编辑器处于 Shell 命令模式时,它为 false:
const composer = ctx.screen.current()?.composer
if (composer?.quotable()) {
const commentID = crypto.randomUUID()
composer.attach({
type: "quote",
commentID,
text: selection,
source: { label: ctx.t("source.label"), icon: "console", subject: "the Acme log" },
})
composer.focus(commentID)
}source.subject为提供给模型的来源名称(如the terminal),无需本地化翻译。- 省略
comment允许用户直接从标签芯片补充批注。 focus(commentID)打开已附加引用的批注编辑器;如果编辑器当前不可见(例如窄屏下正显示面板),会在编辑器重新出现时自动打开。- 模型收到的内容格式为:
The user quoted the following from <subject>:,随后是每行带>前缀的引用文本,以及可选批注。
类型参考
interface ComposerFile {
type: "file"
path: string
selection?: { startLine: number; endLine: number; startChar: number; endChar: number }
preview?: string
comment?: string
commentID?: string
commentOrigin?: "review" | "file"
}
interface ComposerNote {
type: "note"
origin: string
commentID: string
label: string
icon: IconName
subject: string
comment: string
href?: string
live?: { subject: string; href?: string }
}
interface ComposerQuote {
type: "quote"
commentID: string
text: string
comment?: string
source: { label: string; icon: IconName; subject: string }
}读写提示词
使用 text() 读取用户输入的内容,使用 focused() 判断用户是否正在输入:
const composer = ctx.screen.current()?.composer
const empty = !composer?.text().trim()text()返回纯文本形式的提示词:提及(mention)读作其@文本,不包含附件与附加分片。在 Shell 模式下返回 Shell 命令。在会话草稿加载完成前以及没有编辑器的子代理会话中均为""。该方法是响应式的。focused()在键盘焦点位于提示词输入框时为true。它不是响应式的,请在执行动作处(如命令的run中)读取。
insert(text) 将文本插入提示词供用户审阅并发送。编辑器 API 本身不会自动发送提示词:
const composer = ctx.screen.current()?.composer
composer?.insert(`Explain ${path}`)
composer?.focus()insert会在用户上次在输入框留下的光标位置(否则在末尾)插入文本,并将光标移至新文本之后;不会替换选中文本。- 插入文本不会被解析:
@path保持纯文本,不会变成提及。 setText(text)替换整个提示词文本(含提及),但保留附件与附加分片;setText("")清空文本。- 两者均不改变键盘焦点,如需聚焦请调用
focus()。 - 在会话存储草稿加载完成前调用的写入操作(
insert、setText、attach、update或detach)会自动等待草稿就绪,然后按调用顺序应用到发起调用时所路由的会话,绝不会覆盖已有草稿。 - 在没有编辑器的子代理会话中,所有写入操作为空操作。
选择模型
model() 返回下一次提示词将使用的模型,setModel 则像模型选择器一样切换模型:
const composer = ctx.screen.current()?.composer
if (composer && !composer.setModel({ providerID: "anthropic", modelID: "claude-sonnet-4-5", variant: "high" })) {
ctx.toast.show({ variant: "error", title: ctx.t("model.unavailable") })
}model()返回当前路由会话用户选择的模型,其次回退到代理默认模型,再其次是应用默认模型。当模型目录加载中、无已连接提供商提供该模型或处于子代理会话时返回undefined。该方法是响应式的。setModel将指定模型设为当前会话选择并置于最近使用列表首位。省略variant时保留选择器会显示的默认变体。setVariant(variant)切换当前模型的变体,传入undefined选择默认变体。- 若目录尚未加载、无已连接提供商提供该模型或模型不存在该变体,
setModel返回false且不做更改。 - 若无当前模型或模型不存在该变体,
setVariant返回false且不做更改。 - 在子代理会话中两者均返回
false。
类型参考
interface Composer {
text(): string
insert(text: string): void
setText(text: string): void
model(): ComposerModel | undefined
setModel(model: ComposerModel): boolean
setVariant(variant: string | undefined): boolean
attach(part: ComposerFile | ComposerNote | ComposerQuote): void
quotable(): boolean
focus(commentID?: string): void
update(id: string, patch: { comment?: string; preview?: string }): void
detach(id: string): void
focused(): boolean
}
interface ComposerModel {
providerID: string
modelID: string
variant?: string
}服务器与服务器事件
ctx.servers.get(id) 返回实时更新的 ServerRef。运行你插件的桌面应用内置服务器 ID 为 "sidecar",使用 data.on 响应其事件:
import { onCleanup } from "solid-js"
import { createKeyed } from "@opencode/plugin/gui"
createKeyed(
() => ctx.servers.get("sidecar")?.data,
(data) => onCleanup(data.on("session.created", (event) => console.log(event))),
)id为宿主键:"sidecar"、HTTP URL 或自定义服务器源的<plugin id>:<id>。data是该服务器的同步数据(如会话与项目)以及事件监听方法on(type, handler),具有响应式特性。builtin对应用内置服务器为true。compatible表示服务器版本与本应用兼容,connected表示事件流连接在线。password为用户配置的 HTTP Basic 认证密码(如有)。- 请每次从实时
ServerRef读取client、data与url:服务器重启后会在同一 ID 下分配新客户端。 ctx.servers.list()返回应用列出的所有服务器 ID。
类型参考
interface Servers {
list(): string[]
get(id: string): ServerRef | undefined
}
interface ServerRef {
id: string
name: string
url: string
password?: string
client: OpenCodeClient
data: Data
local: boolean
builtin: boolean
compatible: boolean
connected: boolean
}弹窗(Dialogs)
ctx.dialogs.open(render, { replace? }) 在现有弹窗之上打开新弹窗,并返回一个带 close() 方法的句柄。所属作用域结束时弹窗也会自动关闭:
const handle = ctx.dialogs.open((dialog) => <ConfirmDialog onDone={dialog.close} />)replace: true会先关闭所有已打开的弹窗(含宿主与其他插件的弹窗)。- 只要任意弹窗处于打开状态,
ctx.dialogs.active()即为true。 - 请用
ctx.ui.Dialog包裹内容以复用应用弹窗框架,详见应用内置组件。
向用户询问(Ask the user)
confirm、alert、prompt 和 select 直接使用应用原生弹窗询问用户,插件无需自建弹窗 UI,每个方法均返回包含用户答复的 Promise:
const ok = await ctx.dialogs.confirm({ title: ctx.t("end.title"), confirm: ctx.t("end"), danger: true })confirm仅在用户确认时 resolvetrue。设danger会将确认按钮渲染为危险样式,并将初始焦点置于取消按钮。- 每个弹窗的打开行为与
open相同,且随发起询问的 owner(否则随插件)自动关闭。 - 点击取消、按 Escape、点击弹窗外部、被新弹窗替换或 owner 结束时,
confirmresolvefalse,prompt与selectresolveundefined。
alert 展示一条需要用户知晓的信息(单按钮),无论以何种方式关闭弹窗都会 resolve:
await ctx.dialogs.alert({ title: ctx.t("export.done"), description: path })prompt 请求用户输入单行文本。初始 value 默认全选以便直接键入覆盖。它永远不会 resolve 空字符串——输入框为空时提交无效果。设 secret: true 可隐藏输入内容,适合密码或令牌:
const token = await ctx.dialogs.prompt({ title: ctx.t("token.title"), placeholder: "ghp_…", secret: true })select 在可搜索列表中展示选项(类似命令面板),并 resolve 所选项的 value:
const url = await ctx.dialogs.select({
title: ctx.t("links.title"),
options: links.map((link) => ({ title: link.title, description: link.url, value: link.url, group: link.host })),
})
if (url) ctx.system.openExternal(url)- 搜索同时匹配每个选项的
title与description。 - 拥有相同
group的选项会归类到同一分组标题下。 current指定初始高亮的选项值。
类型参考
interface Dialogs {
open(render: (dialog: DialogHandle) => JSX.Element, options?: { replace?: boolean }): DialogHandle
confirm(options: ConfirmOptions): Promise<boolean>
alert(options: AlertOptions): Promise<void>
prompt(options: PromptOptions): Promise<string | undefined>
select<T>(options: SelectOptions<T>): Promise<T | undefined>
active(): boolean
}
interface DialogHandle {
close(): void
}
interface ConfirmOptions {
title: string
description?: string
confirm?: string
cancel?: string
danger?: boolean
}
interface AlertOptions {
title: string
description?: string
ok?: string
}
interface PromptOptions {
title: string
description?: string
placeholder?: string
value?: string
secret?: boolean
submit?: string
}
interface SelectOptions<T> {
title: string
placeholder?: string
options: { title: string; value: T; description?: string; group?: string }[]
current?: T
}应用内置组件(App components)
插件产物不能直接导入 @opencode/ui,而是通过 ctx.ui 使用应用内置组件。它们自动适配用户的主题、字体和界面语言,确保插件 UI 与应用原生体验浑然一体:
import { Show } from "solid-js"
import { createLatest, Panel } from "@opencode/plugin/gui"
const ui = ctx.ui
const summary = createLatest(
() => ctx.sessions.current()?.directory,
(directory, signal) => fetchSummary(directory, signal),
)
ctx.add(Panel, {
id: "summary",
region: "side",
list: () => [summaryTab],
render: () => (
<div>
<ui.Tooltip value={ctx.t("copy")}>
<ui.IconButton icon="copy" label={ctx.t("copy")} onClick={() => void ctx.system.copy(summary.latest ?? "")} />
</ui.Tooltip>
<Show when={summary.latest} fallback={<ui.Loader size="large" />}>
{(text) => <ui.Markdown text={text()} />}
</Show>
</div>
),
})Icon、Button和IconButton像 SDK 中所有icon字段一样接受任意IconName(内置图标或通过ctx.icons声明的自定义图标)。IconButton的label作为无障碍名称,如需悬停提示请用Tooltip包裹。- 按钮的
busy属性会将图标替换为加载指示器并禁用按钮,直至恢复为false。 - 对于非 AI 思考状态的加载场景(如窗格加载、搜索或建立连接),请统一使用
Loader。 Menu打开由items组成的菜单,支持操作项、{ type: "separator" }与{ type: "group", label, items }。Switch与TextInput均为受控组件,不保存内部状态,请将onChange或onInput的值传回checked或value。Keybind将快捷键渲染为按键芯片,例如传入ctx.keybinds.keybind(command)。Markdown按时间线消息样式渲染内容,Code显示只读语法高亮代码块;两者会在挂载后片刻完成高亮填充。
Dialog 是应用的弹窗外框(标题、正文与按钮)。请仅在 ctx.dialogs.open 内渲染它,在其他位置不会呈现有效内容:
const ui = ctx.ui
ctx.dialogs.open((dialog) => (
<ui.Dialog
title={ctx.t("rename.title")}
footer={
<ui.Button variant="contrast" onClick={dialog.close}>
{ctx.t("done")}
</ui.Button>
}
>
<ui.TextInput label={ctx.t("rename.label")} value={name()} onInput={setName} onSubmit={dialog.close} autofocus />
</ui.Dialog>
))size默认为"fit"(宽 480px,高度自适应内容);"normal"、"large"和"x-large"为固定尺寸。- 按 Escape 或点击外部会自动关闭弹窗;
closable: false可隐藏标题栏关闭按钮。
菜单行组件(Menu rows)
MenuItem、MenuSub、MenuGroup 和 MenuSeparator 专用于宿主渲染的菜单(如 session.location.menu 插槽),自带键盘导航、弱化图标与快捷键芯片,并在选中时自动关闭菜单:
import { For } from "solid-js"
const ui = ctx.ui
ctx.add(Slot, {
at: "session.location.menu",
render: (input) => (
<>
<ui.MenuItem
label={ctx.t("usage")}
icon="status"
keys={["Ctrl", "U"]}
onSelect={() => openUsage(input.session)}
/>
<ui.MenuSub label={ctx.t("openIn")} icon="outline-share">
<For each={apps()}>{(app) => <ui.MenuItem label={app.name} onSelect={() => launch(app, input.session)} />}</For>
</ui.MenuSub>
</>
),
})MenuItem接受与Menu的items条目相同的字段。MenuSub在行旁展开子菜单,onOpenChange回调可通知展开状态,便于按需加载子菜单行。MenuGroup将若干行归入标题下,MenuSeparator在行间绘制分隔线。- 在菜单外部渲染
MenuItem、MenuSub或MenuGroup会抛出异常:宿主会记录错误并跳过该条贡献的渲染。
下拉选择框(Selects)
Select 用于从选项列表中单选一项(如设置页中的语言选择)。其值为字符串,类型由 options 自动收窄:
const [period, setPeriod] = createSignal<"day" | "month">("day")
<ui.Select
label={ctx.t("period")}
options={[
{ value: "day", label: ctx.t("period.day") },
{ value: "month", label: ctx.t("period.month") },
]}
value={period()}
onChange={setPeriod}
/>label为无障碍名称,界面展示的是当前选中项的label。- 当
value不匹配任何选项时显示placeholder。重复选择当前已选项不会触发onChange。
设置组件(Settings components)
SettingsLayout、SettingsSection 与 SettingsRow 以与应用原生一致的风格渲染设置页面:页头、带标题和边框列表的分区,以及包含标题、描述和末尾控件的设置行:
<ui.SettingsLayout title={ctx.t("title")} description={ctx.t("description")} actions={<HelpButton />}>
<ui.SettingsSection title={ctx.t("section.display")} footer={<Show when={error()}>{ctx.t("error")}</Show>}>
<ui.SettingsRow id="acme-period" title={ctx.t("period")} description={ctx.t("period.description")}>
<ui.Select label={ctx.t("period")} options={periods()} value={period()} onChange={setPeriod} />
</ui.SettingsRow>
</ui.SettingsSection>
</ui.SettingsLayout>- 独立页面使用
SettingsLayout,宿主页面中的分区使用SettingsSection,宿主分区内的单行直接使用SettingsRow。任何情况下行布局都会与宿主原生行对齐。 - 行上的
id对应触发定位的SettingEntry.id;若搜索定位到页面自身 ID 则高亮页头。 actions显示在标题行末尾;分区的footer显示在列表边框下方。- 这些组件依赖设置界面的样式上下文,请务必在
SettingsPage中渲染。
类型参考
interface Ui {
Icon(props: UiIconProps): JSX.Element
Button(props: UiButtonProps): JSX.Element
IconButton(props: UiIconButtonProps): JSX.Element
Tooltip(props: UiTooltipProps): JSX.Element
Menu(props: UiMenuProps): JSX.Element
MenuItem(props: UiMenuItem): JSX.Element
MenuSeparator(): JSX.Element
MenuGroup(props: UiMenuGroupProps): JSX.Element
MenuSub(props: UiMenuSubProps): JSX.Element
Loader(props: UiLoaderProps): JSX.Element
Dialog(props: UiDialogProps): JSX.Element
Switch(props: UiSwitchProps): JSX.Element
TextInput(props: UiTextInputProps): JSX.Element
Select<T extends string>(props: UiSelectProps<T>): JSX.Element
Keybind(props: UiKeybindProps): JSX.Element
Markdown(props: UiMarkdownProps): JSX.Element
Code(props: UiCodeProps): JSX.Element
SettingsLayout(props: UiSettingsLayoutProps): JSX.Element
SettingsSection(props: UiSettingsSectionProps): JSX.Element
SettingsRow(props: UiSettingsRowProps): JSX.Element
}
interface UiIconProps {
name: IconName
size?: "small" | "normal" | "large"
class?: string
}
interface UiButtonProps {
children: JSX.Element
onClick?: (event: MouseEvent) => void
variant?: "neutral" | "contrast" | "ghost" | "ghost-muted" | "danger"
size?: "small" | "normal" | "large"
icon?: IconName
disabled?: boolean
busy?: boolean
type?: "button" | "submit"
autofocus?: boolean
class?: string
}
interface UiIconButtonProps {
icon: IconName
label: string
onClick?: (event: MouseEvent) => void
variant?: "neutral" | "ghost" | "ghost-muted"
size?: "small" | "normal" | "large"
disabled?: boolean
pressed?: boolean
busy?: boolean
class?: string
}
interface UiTooltipProps {
value: JSX.Element
keys?: string[]
placement?: "top" | "bottom" | "left" | "right"
children: JSX.Element
}
interface UiMenuProps {
label: string
items: UiMenuEntry[]
trigger?: "icon" | "button"
icon?: IconName
placement?: "bottom-start" | "bottom-end" | "top-start" | "top-end"
disabled?: boolean
}
type UiMenuEntry = UiMenuItem | UiMenuSeparator | UiMenuGroup
interface UiMenuItem {
type?: "item"
label: string
icon?: IconName
keys?: string[]
disabled?: boolean
onSelect(): void
}
interface UiMenuSeparator {
type: "separator"
}
interface UiMenuGroup {
type: "group"
label: string
items: UiMenuItem[]
}
interface UiMenuGroupProps {
label: string
children: JSX.Element
}
interface UiMenuSubProps {
label: string
icon?: IconName
disabled?: boolean
onOpenChange?: (open: boolean) => void
children: JSX.Element
}
interface UiLoaderProps {
size?: "small" | "normal" | "large"
class?: string
}
interface UiDialogProps {
title: string
description?: string
children?: JSX.Element
footer?: JSX.Element
size?: "fit" | "normal" | "large" | "x-large"
closable?: boolean
}
interface UiSwitchProps {
checked: boolean
onChange: (checked: boolean) => void
label: string
hideLabel?: boolean
description?: string
disabled?: boolean
}
interface UiTextInputProps {
value: string
onInput: (value: string) => void
label: string
placeholder?: string
onSubmit?: (value: string) => void
type?: "text" | "password" | "search" | "url"
size?: "normal" | "large"
disabled?: boolean
invalid?: boolean
autofocus?: boolean
class?: string
}
interface UiKeybindProps {
keys: string[]
class?: string
}
interface UiMarkdownProps {
text: string
class?: string
}
interface UiCodeProps {
content: string
language?: string
class?: string
}
interface UiSelectProps<T extends string> {
options: UiSelectOption<T>[]
value: T | undefined
onChange: (value: T) => void
label: string
placeholder?: string
disabled?: boolean
invalid?: boolean
placement?: "bottom-start" | "bottom-end" | "top-start" | "top-end"
class?: string
}
interface UiSelectOption<T extends string> {
value: T
label: string
}
interface UiSettingsLayoutProps {
title: string
description?: string
actions?: JSX.Element
children: JSX.Element
}
interface UiSettingsSectionProps {
title?: string
children: JSX.Element
footer?: JSX.Element
}
interface UiSettingsRowProps {
title: JSX.Element
description?: JSX.Element
id?: string
children?: JSX.Element
}轻提示(Toasts)
ctx.toast.show 在窗口角落显示一条简短消息,并返回带有 dismiss() 的关闭句柄:
ctx.toast.show({ variant: "success", title: ctx.t("invite.copied") })variant可选"default"、"success"、"error"或"loading";除非另行指定icon,success默认显示勾选图标。duration指定显示毫秒数,默认为 5 秒。persistent: true使轻提示持续保留直至用户手动关闭或调用dismiss(),同时忽略duration。- 若与当前仍在显示的轻提示内容相同,会原地替换而非堆叠重复副本。
- 插件停止时会自动关闭其全部轻提示,避免按钮残留;但创建轻提示的组件或
createKeyed销毁时不会关闭轻提示。
任务执行期间显示 loading 提示,结束后将其关闭:
const saving = ctx.toast.show({ variant: "loading", title: ctx.t("saving"), persistent: true })
await save()
saving.dismiss()actions 可添加操作按钮,点击后执行动作并自动关闭轻提示:
ctx.toast.show({
variant: "error",
title: ctx.t("sync.failed"),
actions: [{ label: ctx.t("retry"), run: () => void sync() }],
})类型参考
interface Toasts {
show(options: ToastOptions): ToastHandle
}
interface ToastHandle {
dismiss(): void
}
interface ToastOptions {
title: string
description?: string
variant?: "default" | "success" | "error" | "loading"
icon?: IconName
duration?: number
persistent?: boolean
actions?: ToastAction[]
}
interface ToastAction {
label: string
run(): void
}系统通知(Notifications)
ctx.attention.notify 在用户关注其他窗口时通过系统通知和提示音吸引注意,遵循与应用内置通知完全相同的规则:
const session = ctx.sessions.current()
if (session) {
void ctx.attention.notify({
title: ctx.t("tests.done"),
message: ctx.t("tests.summary", { failed: 0 }),
session: { server: session.server.id, id: session.id },
id: run.id,
})
}- 系统通知仅在所有应用窗口均未聚焦时弹出,提示音则无论焦点状态均可播放。
- 两者均遵循 Settings > Notifications:
variant: "default"遵循 Agent 设置,variant: "error"遵循 Errors 设置。桌面通知默认关闭,提示音默认开启。 - 设
sound: false永不播放提示音。 - 点击通知会将应用带到前台,并在提供了
session时打开对应会话。 - 每个应用窗口都运行着你插件的一份副本。传入事件唯一
id(如某次运行的 ID)可确保只有最先触发的窗口弹出通知和播放提示音;省略id时每次调用都会通知。 - 若在应用界面挂载前调用,
notify会等待挂载完成。
notify 永不 reject,而是 resolve 实际执行结果:应用向系统请求展示通知时 notification 为 true,开始播放提示音时 sound 为 true:
const result = await ctx.attention.notify({ title: ctx.t("deploy.failed"), variant: "error" })
if (!result.notification) ctx.toast.show({ variant: "error", title: ctx.t("deploy.failed") })- 当用户关闭通知、应用窗口处于聚焦状态或其他窗口已发送过相同
id时,notification为false。即使应用请求展示了通知,操作系统仍可能隐藏它(例如用户拒绝了浏览器通知权限)。
类型参考
interface Attention {
notify(options: NotifyOptions): Promise<NotifyResult>
}
interface NotifyOptions {
title: string
message?: string
variant?: "default" | "error"
session?: { server: string; id: string }
sound?: boolean
id?: string
}
interface NotifyResult {
notification: boolean
sound: boolean
}用量数据(Usage data)
会话的 Token、费用及套餐用量位于其服务器数据中,与应用顶部栏展示“28k · $0.28”读取的是同一份响应式 store。请直接从这里读取,不要去读 opencode 数据库:
import { lastAssistantWithUsage } from "@opencode/client/solid"
const data = session.server.data
const info = () => data.session.get(session.id)
const tokens = () => info()?.tokens // this session's tokens by kind
const cost = () => data.session.cost(session.id) // USD, with subagent sessions
const step = () => lastAssistantWithUsage(data.session.message.list(session.id), info()?.revert?.messageID)
const limits = () => (session.location ? data.location.usage.limits(session.location) : undefined)step()是当前占据上下文窗口的助手步骤(与应用上下文进度环所用数据一致),可将其tokens与data.location.model.list中模型的limit.context对比。limits()在data.location.usage.sync(location)加载完成后包含 OpenCode Console 预算与 Go 套餐额度;服务器未返回时为null。
标签页(Tabs)
ctx.tabs 用于读取和操作外壳标签栏(以标签页形式打开的会话与草稿)。下例在会话运行结束后将其标签移至最前:
import { onCleanup } from "solid-js"
import { createKeyed } from "@opencode/plugin/gui"
createKeyed(
() => ctx.servers.get("sidecar")?.data,
(data) =>
onCleanup(
data.on("session.execution.succeeded", (event) => {
const tab = ctx.tabs.list().find((item) => item.session?.id === event.data.sessionID)
if (tab) ctx.tabs.move(tab.key, 0)
}),
),
)list()按标签栏顺序返回所有已打开标签,具有响应式特性。草稿标签的session为undefined,当前屏幕显示的标签active为true。open({ server, id }, { focus? })在标签栏末尾以标签页形式打开会话;除非focus为true,否则在后台打开。已打开的会话保持现有标签,由父标签展示的子代理亦然。focus(key)切换至该标签,move(key, index)移动其位置,close(key)像用户点击一样关闭它。- 传入不存在的键为空操作;应用界面挂载前的写入会自动排队等待。
类型参考
interface Tabs {
list(): ShellTab[]
open(session: { server: string; id: string }, options?: { focus?: boolean }): void
focus(key: string): void
move(key: string, index: number): void
close(key: string): void
}
interface ShellTab {
key: string
session: SessionRef | undefined
active: boolean
}快捷键(Keybinds)
ctx.keybinds 读取用户为某个已发布命令 ID 配置的快捷键:
const label = ctx.keybinds.keybind(`${ctx.id}.open`)
const chord = ctx.keybinds.keys("mod+k")
const pressed = (event: KeyboardEvent) => ctx.keybinds.matches(`${ctx.id}.open`, event)keybind(command)返回命令当前生效快捷键的展示按键数组(如["Ctrl", "K"]),未绑定时为空数组。keys(bind)返回非应用托管组合键的展示按键数组(例如页面自行处理的快捷键)。matches(command, event)判断键盘事件是否命中该命令当前生效的快捷键。
类型参考
interface Keybinds {
keybind(command: string): string[]
keys(bind: string): string[]
matches(command: string, event: KeyboardEvent): boolean
}运行命令(Run commands)
ctx.commands.run(id) 以与命令面板选择相同的方式执行命令;无法执行时返回 false:
if (!ctx.commands.run("terminal.toggle")) ctx.toast.show({ title: ctx.t("terminal.unavailable") })id可为任意插件发布的命令<plugin id>.<command id>,或应用内置命令(如command.palette)。- 应用内置命令 ID 不属于稳定 API,版本间可能变更。
- 当不存在对应 ID 的已启用命令时返回
false;已列出但被禁用的命令不会执行。 - 应用界面挂载前尚未注册任何命令,此时返回
false。 run不会等待命令内部的异步工作完成。
类型参考
interface Commands {
run(id: string): boolean
}系统与环境(System and environment)
ctx.system 在所有平台可用;ctx.desktop 提供仅限桌面端的能力,在 Web 端为 undefined:
const show = async (path: string) => {
if (ctx.desktop && (await ctx.desktop.reveal(path))) return
await ctx.system.copy(path)
}system.save在桌面端弹出保存对话框,在 Web 端触发文件下载;用户取消时返回false。system.openExternal用系统默认浏览器打开 URL;应用内部链接请使用ctx.links.open,它会将Link路由给对应的链接处理器。desktop.launch(path, app?)使用指定应用(或系统默认应用)打开路径;desktop.reveal(path)在文件管理器中定位显示该路径。ctx.embeds在窗口中渲染主进程创建的网页视图,详见嵌入式网页视图。ctx.locale读取界面语言和书写方向;ctx.appearance.font("mono")返回用户终端字体的 CSSfont-family。ctx.router读取当前路由路径以及是否正处于路由切换中。ctx.workspaces.on("remove", handler)在用户从服务器移除工作区目录时触发,便于清理按目录隔离的 store。
desktop.pick(options) 打开系统文件/文件夹选择对话框,并 resolve 所选条目的绝对路径:
const [folder] = (await ctx.desktop?.pick({ directory: true, title: ctx.t("pick.folder") })) ?? []
if (folder) await ctx.client.rpc(Acme).index({ directory: folder })directory: true改为选择文件夹而非文件;multiple: true允许多选。extensions限制可选文件扩展名(不含前导点,如["json"]),选择文件夹时忽略此项。title为对话框标题,并非所有操作系统均会展示。- 用户取消时返回空数组;对话框无法打开时 reject。
pick仅桌面端可用:浏览器不会向网页暴露所选文件的本地绝对路径。
ctx.appearance.mode() 返回界面当前显示的配色方案("light" 或 "dark"),具有响应式特性:
const background = () => (ctx.appearance.mode() === "dark" ? "#000" : "#fff")- 它遵循 Settings > Appearance 中的用户选择,其中 System 会自动解析为系统当前主题。
- 应用界面挂载前直接返回系统配色方案。
类型参考
interface System {
copy(text: string): Promise<void>
save(file: { name: string; content: string }): Promise<boolean>
openExternal(url: string): void
}
interface Desktop {
os: "macos" | "windows" | "linux"
zoom(): number
launch(path: string, app?: string): Promise<void>
reveal(path: string): Promise<boolean>
installed(app: string): Promise<boolean>
pick(options?: PickOptions): Promise<string[]>
}
interface PickOptions {
directory?: boolean
multiple?: boolean
title?: string
extensions?: string[]
}
interface Links {
open(link: Link): boolean
exists(link: Link): boolean | Promise<boolean>
}
interface Locale {
locale(): string
direction(): "ltr" | "rtl"
}
interface Appearance {
font(kind: "mono"): string
mode(): "light" | "dark"
}
interface Router {
path(): string
routing(): boolean
}
interface Workspaces {
on(event: "remove", handler: (value: { server: string; directory: string }) => void): Cleanup
}持久化状态(Stored state)
桌面窗口通过 IPC 异步加载持久化状态,而 Web 端则立即从 localStorage 读取。在 Plugin.define({ stores }) 中声明 store,由宿主统一负责加载:
Store.global:全应用共享一份值,在setup运行前即加载完毕,因此ctx.stores.name.value永不为undefined。Store.session:每个会话独立保存一份值,在会话挂载时加载;加载完成前ctx.stores.name(session).value为undefined。
声明式 store 仅面向窗口进程。main 进程使用同步读取的 ctx.storage.store 打开状态,详见主进程上下文。
使用 update(draft => …) 原地修改草稿(不得有返回值),或使用 set(next) 整体替换:
const enabled = ctx.stores.prefs.value.enabled
ctx.stores.prefs.update((draft) => {
draft.enabled = !draft.enabled
})- 值加载完成后
ready()为true。加载前的写入会排队等待并按调用顺序应用。 from指定在当前 store 尚无值时一次性迁移数据的旧存储键(例如重命名 store 时的"plugin.acme.settings")。可传入数组按新到旧依次尝试;原键会保留其副本直至该 store 被移除。
stores: {
prefs: Store.global(Prefs, { enabled: true }, ["plugin.acme.settings.v2", "plugin.acme.settings"]),
}类型参考
const Store: {
global(schema: Schema, initial: T, from?: string | string[]): StoreDeclaration
session(schema: Schema, initial: T, from?: string | string[]): StoreDeclaration
}
interface Persisted<T, V = T | undefined> {
value: V
ready(): boolean
update(mutate: (draft: T) => undefined): void
set(next: T): void
}运行时 Store
ctx.storage.store(key, options) 用于打开运行时才确定键名的 store。通过 scope 可按服务器、目录或会话维度隔离存储:
import { Schema } from "effect"
import { usePlugin, type MountedSession } from "@opencode/plugin/gui"
import type { definition } from "./definition"
function DraftView(props: { readonly session: MountedSession }) {
const ctx = usePlugin<typeof definition>()
const draft = ctx.storage.store("draft", {
schema: Schema.Struct({ text: Schema.String }),
initial: { text: "" },
scope: { server: props.session.server.id, directory: props.session.directory },
})
return <p>{draft.value?.text}</p>
}scope: "global"(默认):全应用共享一份值。scope: { server, directory? }:按服务器或按服务器上的工作区目录隔离。scope: { session }:按会话隔离,且会话移动到新目录时会重新打开。- 运行时 store 的
value在加载完成前为undefined。 ctx.storage.memory(key, { initial })保存窗口本地内存状态:在插件重载期间保留,窗口刷新后丢失。ctx.storage.remove(key, { scope, from })删除已存储的值,使该键恢复为initial。
类型参考
interface Storage {
store(key: string, options: StoreOptions): Persisted<T>
memory(key: string, options: { initial: T }): [Store<T>, (mutation: (draft: T) => void) => void]
remove(key: string, options?: { scope?: StorageScope; from?: string | string[] }): void
}
interface StoreOptions {
schema: Schema
initial: T
scope?: StorageScope
from?: string | string[]
}
type StorageScope = "global" | { server: string; directory?: string } | { session: SessionRef }响应式原语(Reactive primitives)
建议优先使用以下辅助函数而非原生的 createEffect、createRenderEffect 和 createComputed。它们自动遵循插件生命周期与依赖重启边界,避免了手写 effect 容易出错的问题。
createKeyed
createKeyed(source, fn, { otherwise?, equals? }) 会为每个键在全新的 Solid owner 中运行 fn——对于 ctx.use 访问器按每次活跃代数(generation)区分,对于普通访问器按值区分。在 fn 内部注册的所有内容都会随该次运行销毁而自动清理:
import { onCleanup } from "solid-js"
import { createKeyed, usePlugin, type SessionScreen } from "@opencode/plugin/gui"
import { Changes } from "@opencode/plugin/gui/review"
function ChangedFiles(props: { readonly screen: SessionScreen }) {
const ctx = usePlugin()
// Each active generation of Changes keeps this view's changes loaded; the watch ends with it.
createKeyed(ctx.use(Changes), (changes) => onCleanup(changes.watch(props.screen, "files")))
return <FileMarkers screen={props.screen} />
}- 当源没有有效键时运行
otherwise(例如Live访问器未激活,或普通访问器值为undefined、null、false)。 equals用于判断普通访问器的新值是否属于同一键,从而避免重复执行fn(当源每次构造新对象时尤为有用)。Live访问器始终按代数区分。
类型参考
function createKeyed<T>(
source: () => Live<T> | T,
fn: (value: T) => void,
options?: { otherwise?(): void; equals?(previous: T, next: T): boolean },
): voidcreateLatest
createLatest(source, (value, signal) => promise) 在 source 变化时发起异步拉取、自动中止过时请求,且永不触发 Suspense 挂起:
const summary = createLatest(
() => ctx.sessions.current()?.directory,
(directory, signal) => fetchSummary(directory, signal),
)
const text = () => summary.latest ?? ""latest:最近一次成功结果,在新请求进行期间保持显示;首次完成前为undefined。loading:当前值对应的请求正在进行时为true。error:当前请求的拒绝错误(如有)。
类型参考
function createLatest<S, T>(
source: () => Live<S> | S,
fetch: (value: S, signal: AbortSignal) => Promise<T>,
): { latest: T | undefined; loading: boolean; error: unknown }createVisitState
createVisitState(initial) 创建一个 [value, setValue] 信号,每当用户离开当前会话再返回时自动重置为初始值:
const [expanded, setExpanded] = createVisitState(false)类型参考
function createVisitState<T>(initial: T): [value: () => T, set: (next: T) => void]usePanel 与 useDrawer
usePanel() 读取外层面板框架状态,在面板渲染外调用会抛出异常;useDrawer() 返回包裹当前贡献的移动端抽屉控制对象,不在抽屉内时返回 undefined:
const panel = usePanel()
const drawer = useDrawer()
const compact = () => panel.placement() === "mobile"
const close = () => drawer?.close()placement():在侧边区域为"side",在窄屏视图为"mobile"。visible():区域打开且当前标签页被选中时为true;present()在区域关闭动画期间仍保持true。reserve():提示你在面板标题栏末尾为宿主的区域开关按钮预留空间。sidebar:所有侧边面板共享的内部侧栏偏好;带内部侧栏的面板需自行渲染切换按钮。drawer.open(view):在抽屉中切换展示新视图并附带返回按钮。
类型参考
function usePanel(): PanelFrame
function useDrawer(): { close(): void; open(view: DrawerView): void } | undefined
interface PanelFrame {
visible(): boolean
present(): boolean
placement(): "side" | "mobile"
reserve(): boolean
animate(): boolean
open(): string[]
sidebar: {
opened(): boolean
width(): number
transition(): boolean
resize(width: number): void
toggle(): void
}
}
interface DrawerView {
title: string
content: JSX.Element
trigger: HTMLElement
}应用内置契约(App contracts)
应用会向所有插件提供以下内置契约。请像其他插件契约一样使用 ctx.use(token) 订阅,并妥善处理非 active 状态(例如 Browser 在 Web 端始终为 inactive)。
文件(Files)
@opencode/plugin/gui/file 导出应用的文件树、Open in 按钮以及 FileViewer 注册表:
import { bindPlugin } from "@opencode/plugin/gui"
import { FileViewer, type FileViewerProps } from "@opencode/plugin/gui/file"
// A viewer for a kind of file the file view does not render itself.
ctx.add(FileViewer, {
kinds: ["document"],
View: bindPlugin((props: FileViewerProps) => <AcmeDoc bytes={props.bytes} onError={props.onError} />),
})FileTree(契约):Tree与List渲染带变更标记的虚拟化工作区文件树或列表,通过ctx.use(FileTree)读取。树的labels可在目录名后附加文本(如条目数量)。OpenInApp(契约):Button为桌面端会话工作区的 Open in 按钮。FileViewer(注册表):查看器声明其支持的kinds,可通过problem拒绝不支持的字节流,并渲染上报onDetails与onError的View。
类型参考
interface FileTree {
Tree(props: FileTreeProps): JSX.Element
List(props: FileListProps): JSX.Element
}
interface FileTreeProps {
screen: SessionScreen
session: MountedSession
allowed: string[]
kinds?: Map<string, ChangeKind>
labels?: Map<string, string>
active?: string
onFileClick(path: string): void
}
interface FileListProps {
screen: SessionScreen
session: MountedSession
files: string[]
kinds?: Map<string, ChangeKind>
active?: string
highlighted?: string
onFileClick(path: string): void
}
interface OpenInApp {
Button(props: { screen: SessionScreen; session: MountedSession }): JSX.Element
}
interface FileViewer {
kinds: ArtifactKind[]
problem?(bytes: Uint8Array): string | undefined
View: Component<FileViewerProps>
}
interface FileViewerProps {
bytes: Uint8Array
onDetails(details: string[]): void
onError(reason?: string): void
}变更审查(Review changes)
@opencode/plugin/gui/review 导出应用对会话变更的视图 Changes 以及 ChangeKind("add"、"del" 或 "mix"):
import { Changes } from "@opencode/plugin/gui/review"
const changes = ctx.use(Changes)
const count = () => {
const live = changes()
const session = ctx.sessions.current()
return live.status === "active" && session ? live.value.diffs(session).length : 0
}diffs(session)返回当前审查模式的差异列表,ready(session)在加载完成后为true,两者均为响应式。仅当前路由会话包含变更,其他会话读取为空。kinds(session)将每个有变更的文件与目录映射到对应的ChangeKind。active(session)为审查面板当前显示的文件。details(session)返回会话目录的未提交变更,不受审查模式影响。focus(session, path)在审查面板中聚焦特定文件,open(session)打开全部变更。watch(screen, source)在视图展示变更期间持续保持数据加载,并自动跟随视图切换会话。请传入面板或插槽输入提供的所属screen,返回停止监听的函数,详见createKeyed。tree监听维护持久化变更列表,打开侧边区域时会自动刷新;details监听负责加载details(session)。
类型参考
interface Changes {
diffs(session: SessionRef): FileDiffInfo[]
ready(session: SessionRef): boolean
kinds(session: SessionRef): Map<string, ChangeKind>
active(session: SessionRef): string | undefined
details(session: SessionRef): FileDiffInfo[] | undefined
focus(session: SessionRef, path: string): void
open(session: SessionRef): void
watch(screen: SessionScreen, source: "tree" | "files" | "details"): () => void
}
type ChangeKind = "add" | "del" | "mix"浏览器(Browser)
@opencode/plugin/gui/browser 导出会话的桌面浏览器窗格契约 Browser:
import { Browser } from "@opencode/plugin/gui/browser"
const session = ctx.sessions.current()
const live = ctx.use(Browser)()
const url = "http://localhost:3000"
if (session && live.status === "active" && live.value.canOpen(session, url)) live.value.open(session, url)attached(session):会话拥有浏览器窗格时为true。canOpen(session, path?):工作区文件或 http(s) URL 可在窗格中打开时为true。open(session, url):在会话侧边面板中以浏览器标签页打开 URL。openFile(session, path):以file://标签页打开工作区文件。
类型参考
interface Browser {
attached(session: SessionRef): boolean
canOpen(session: SessionRef, path?: string): boolean
open(session: SessionRef, url: string): void
openFile(session: SessionRef, path: string): void
}主进程(The main process)
在 OpenCode Desktop 中,插件的 main 会在 Electron 主进程中作为全应用单例仅运行一次,拥有对 Node.js 内置模块、electron 以及主进程宿主 API 的完整访问权限。在./gui-experimental 文件中将其传给 Plugin.define,既可与窗口 setup 并存也可单独提供:
import { Schema } from "effect"
import { powerSaveBlocker } from "electron"
import { Plugin } from "@opencode/plugin/gui"
import { KeepAwake } from "./gui/contract"
export default Plugin.define({
main(ctx) {
const stored = ctx.storage.store("keepScreenActive", { schema: Schema.Boolean, initial: false })
let blockerId: number | undefined
const release = () => {
if (blockerId === undefined) return
powerSaveBlocker.stop(blockerId)
blockerId = undefined
}
const setActive = (enabled: boolean) => {
if (enabled && blockerId === undefined) blockerId = powerSaveBlocker.start("prevent-display-sleep")
if (!enabled) release()
stored.set(enabled)
}
if (stored.value) setActive(true)
ctx.provide(KeepAwake, {
screenActive: () => blockerId !== undefined && powerSaveBlocker.isStarted(blockerId),
setScreenActive: (enabled) => setActive(enabled),
})
return release
},
})在窗口进程中 electron 是惰性占位符,因此在共享的 ./gui-experimental 文件中导入它是安全的,详见单文件,双进程。
主进程上下文(Main context)
main 接收一个 MainContext。与窗口 setup 不同,main 可以是 async 函数,并可直接返回或 resolve 一个清理函数:
main(ctx) {
ctx.log.write("info", "acme started", { version: ctx.app.version })
}ctx.options、ctx.client和ctx.app属于共享上下文。在main中,ctx.app.platform始终为"desktop"。ctx.storage.store(key, { schema, initial })在插件命名空间内同步打开 store:其value始终有定义,且每次set或update在返回前均已落盘数据库。ctx.storage.remove(key)删除该键。ctx.signal在插件被停用、重载、移除或应用退出时触发中止;ctx.onCleanup(fn)注册此时执行的回调,详见生命周期与清理。ctx.provide在插件 ID 下实现Ipc,详见定义与提供 Ipc。ctx.add向主进程注册表(如MenubarItem)贡献条目。ctx.windows列出应用所有窗口并通知窗口打开与关闭。ctx.embeds在窗口布局中放置WebContentsView,详见嵌入式网页视图。ctx.serverEndpoints.get(id)返回服务器的 URL 与凭据;桌面应用内置服务器为"sidecar"。ctx.cli描述桌面应用所运行的 OpenCode CLI。ctx.log.write写入桌面应用日志文件。
类型参考
@opencode/plugin/gui/main 将下方的 MainStorage 和 MainEmbeds 分别导出为 Storage 与 Embeds:
interface MainContext {
id: string
options: PluginOptions
client: OpenCodeClient
app: App
signal: AbortSignal
onCleanup(fn: Cleanup): void
storage: MainStorage
provide<S extends IpcSpec>(token: Ipc<S>, impl: IpcImpl<S>): IpcProvider<S>
add<T>(registry: Registry<T>, item: () => T | undefined): Cleanup
add<T>(registry: Registry<T>, item: T): Cleanup
list<T>(registry: Registry<T>): T[]
t(key: string, params?: Record<string, string | number | boolean>): string
plural(key: string, count: number, params?: Record<string, string | number | boolean>): string
windows: Windows
embeds: MainEmbeds
serverEndpoints: { get(id: string): ServerEndpoint | undefined }
cli: { version: string; command: string[]; binary?: string; development: boolean }
log: { write(level: "debug" | "info" | "warn" | "error", message: string, data?: Record<string, unknown>): void }
}
interface MainStorage {
store(key: string, options: { schema: Schema; initial: T }): Persisted<T, T>
remove(key: string): void
}
interface Windows {
get(id: number): BrowserWindow | undefined
list(): BrowserWindow[]
focused(): BrowserWindow | undefined
on(event: "open" | "close", handler: (window: BrowserWindow) => void): Cleanup
}
interface ServerEndpoint {
id: string
url: string
headers: Record<string, string>
sameMachine: boolean
password?: string
}定义与提供 Ipc
Ipc 规范可声明按窗口隔离的 state、可调用的 methods 以及主动推送的 events。所有跨进程数据均由 Effect Schema 完成校验与编解码:
import { Schema } from "effect"
import { Ipc } from "@opencode/plugin/gui"
export const Counter = Ipc.define({
id: "acme.counter",
state: Schema.Struct({ count: Schema.Number }),
methods: {
increment: {
input: Schema.Number,
output: Schema.Number,
},
reset: {},
},
events: {
overflow: Schema.Struct({ limit: Schema.Number }),
},
})- ID 必须是你的插件 ID 或以之开头(如
acme.counter)。其他 ID 在main的ctx.provide与窗口的ctx.main中均会抛出异常。 - 无参数的方法请省略
input,无返回值的方法请省略output。
类型参考
interface IpcSpec {
id: string
state?: Schema
methods: Record<string, { input?: Schema; output?: Schema }>
events?: Record<string, Schema>
}在主进程实现提供方
每个方法都会收到解码后的输入以及 Caller({ window, signal })。当 state 变化时调用 provider.changed(window?) 向已订阅窗口推送最新快照;调用 provider.emit(name, payload, window?) 主动推送事件:
import type { Plugin } from "@opencode/plugin/gui"
import { Counter } from "./contract"
export const main: Plugin.MainSetup = (ctx) => {
const counts = new Map<number, number>()
const provider = ctx.provide(Counter, {
state: (window: number) => ({ count: counts.get(window) ?? 0 }),
increment: (step, caller) => {
const next = (counts.get(caller.window) ?? 0) + step
counts.set(caller.window, next)
provider.changed(caller.window)
if (next > 100) provider.emit("overflow", { limit: 100 }, caller.window)
return next
},
reset: (_input, caller) => {
counts.set(caller.window, 0)
provider.changed(caller.window)
},
})
}- 声明了
state的规范必须在实现中提供state(window)。主进程会在窗口订阅时及每次changed时调用它。 - 方法抛出异常会使窗口侧的调用 reject。
- 省略
window时,changed与emit会广播给所有窗口。 dispose()可提前撤回该Ipc:窗口会看到其变为pending,ctx.main调用会等待,直到插件重新提供或停止。插件停止时宿主也会自动撤回。
类型参考
type IpcImpl<S extends IpcSpec> = {
[Name in keyof S["methods"]]: (input: Input<Name>, caller: Caller) => Output<Name> | Promise<Output<Name>>
} & { state(window: number): State }
interface Caller {
window: number
signal: AbortSignal
}
interface IpcProvider<S extends IpcSpec> {
changed(window?: number): void
emit(name: keyof S["events"], data: EventData, window?: number): void
dispose(): void
}在窗口中使用 Ipc
在窗口中,ctx.main(Counter) 返回由你自己插件 main 提供的 Ipc 客户端。没有 input Schema 的方法仅接受可选的 { signal } 调用选项,切勿将 undefined 作为第一个参数传入:
import { Command, type Plugin } from "@opencode/plugin/gui"
import { Counter } from "./contract"
import type { definition } from "./definition"
export const setup: Plugin.Setup<typeof definition> = (ctx) => {
const counter = ctx.main(Counter)
// Follows main across restarts; removed when the plugin stops.
counter.on("overflow", (data) => console.log(`Counter exceeded ${data.limit}`))
ctx.add(Command, () => ({
id: "increment",
title: ctx.t("command.increment"),
enabled: ctx.app.platform === "desktop",
run: async () => {
await counter.increment(1, { signal: ctx.signal })
await counter.reset({ signal: ctx.signal })
},
}))
}- 调用会在
main启动期间自动等待;当main无法响应(在 Web 端、main已停用或启动失败、或方法内部抛出错误)时会 reject。请在需要向用户反馈的地方捕获该 reject。 state()与on()会自动跟随main重启。事件监听器随当前 owner(否则随插件)自动销毁。- 对同一令牌每次调用
ctx.main返回同一个客户端实例。
使用 client.state() 读取当前窗口的状态。首个快照到达前它为 undefined,此后每次 main 调用 changed 时自动更新:
const count = () => ctx.main(Counter).state()?.count ?? 0类型参考
type IpcClient<S extends IpcSpec> = {
[Name in keyof S["methods"]]: S["methods"][Name] extends { input: Schema }
? (input: Input<Name>, options?: { signal?: AbortSignal }) => Promise<Output<Name>>
: (options?: { signal?: AbortSignal }) => Promise<Output<Name>>
} & {
state(): State | undefined
on(name: keyof S["events"], listener: (data: EventData) => void): Cleanup
}在 src/gui.tsx 中用两个 setup 共同定义插件:Plugin.define({ ...definition, setup, main })。
供其他插件消费
其他插件可像消费普通契约一样通过 ctx.use(Counter) 追踪你的 Ipc。当状态为 active 时,其 value 即为同一个 IpcClient:
const counter = ctx.use(Counter)
const count = () => {
const live = counter()
return live.status === "active" ? (live.value.state()?.count ?? 0) : 0
}- 在没有主进程的 Web 端,所有
Ipc均为inactive。
原生应用菜单(Native app menu)
main 可使用 @opencode/plugin/gui/main 的 MenubarItem 向原生菜单(macOS 应用菜单、File、Edit、View、Go、Window 和 Help)以及 Windows 和 Linux 的应用内菜单添加菜单项:
import { MenubarItem } from "@opencode/plugin/gui/main"
ctx.add(
MenubarItem,
(): MenubarItem => ({
menu: "help",
id: "diagnostics",
after: "logs.export",
label: ctx.t("menu.diagnostics"),
enabled: () => true,
run: (focusedWindow) => {
focusedWindow?.webContents.focus()
},
}),
)after指定紧跟在哪个菜单项之后:可填本插件另一个菜单项的 ID,或内置项的 command / action / role(如logs.export、edit.copy、about)。若均未匹配则追加到菜单末尾。app菜单项仅在 macOS 上显示。run接收当前获得焦点的窗口(如有)。- 每次重建菜单时主进程都会重新调用该函数,因此标签会自动跟随界面语言切换。
类型参考
interface MenubarItem {
menu: "app" | "file" | "edit" | "view" | "go" | "window" | "help"
id: string
label: string
after?: string
enabled?(): boolean
run(window: BrowserWindow | undefined): void
}嵌入式网页视图(Embedded web views)
如需在面板中嵌入隔离的 WebContentsView,请在 main 中创建它并在窗口中渲染其占位盒:
import { type BrowserWindow, WebContentsView } from "electron"
import type { Plugin } from "@opencode/plugin/gui"
export const main: Plugin.MainSetup = (ctx) => {
const attach = (window: BrowserWindow) => {
const view = new WebContentsView()
const embed = ctx.embeds.create(view, window)
void view.webContents.loadURL("https://acme.example")
embed.show(true)
// Send embed.id to the window over your Ipc.
}
ctx.windows.list().forEach(attach)
ctx.windows.on("open", attach)
}<ctx.embeds.View id={embedId} visible radius={8} />"open"事件仅对之后新打开的窗口触发,因此请先遍历ctx.windows.list()为现有窗口挂载。- 窗口将嵌入实例的
id传给ctx.embeds.View与ctx.embeds.capture。 show(visible)控制页面侧的可见性:仅当窗口正在布局该视图且show(true)生效时才会显示。on("visible", handler)在视图进入或离开屏幕时触发(包括窗口用静态截图替代绘制时)。capture()返回当前页面的静态截图,视图隐藏时返回undefined。dispose()仅从窗口移除视图,不会关闭其页面;用完后请自行调用view.webContents.close()。插件卸载时宿主也会释放该嵌入。- 在窗口中,
View会用嵌入视图填满容器。宿主自动同步视图的边界、缩放比例、圆角以及弹窗遮挡状态,并在窗口隐藏或弹窗打开时将其隐藏。 frozen用静态截图替代实时视图,以便 DOM 内容浮在其上方;radius设置底部圆角,background指定圆角露出的背景色。page标识嵌入当前展示的内容(如 URL)。面板移动期间宿主会绘制静态截图占位,并丢弃在page变更前截取的旧图。- 窗口侧
capture(id)返回 JPEG 静态图;嵌入隐藏时以及在 Web 端始终返回undefined。
类型参考
interface MainEmbeds {
create(view: WebContentsView, window: BrowserWindow): Embed
}
interface Embed {
id: string
show(visible: boolean): void
on(event: "visible", handler: (visible: boolean) => void): Cleanup
capture(): Promise<NativeImage | undefined>
dispose(): void
}
interface Embeds {
View(props: EmbedProps): JSX.Element
capture(id: string): Promise<Uint8Array | undefined>
}
interface EmbedProps {
id: string | undefined
visible: boolean
frozen?: boolean
page?: string
radius?: number
background?: string
class?: string
children?: JSX.Element
}实时依赖与故障处理(Live dependencies and failure handling)
ctx.use(token) 返回一个响应式 Live<T> 访问器,反映提供该令牌的插件状态。即使提供方已关闭,你的插件仍会继续运行,因此务必妥善处理非 active 状态:不要留下点击无效的死控件,也不要让加载动画无限旋转:
import { Browser } from "@opencode/plugin/gui/browser"
const browser = ctx.use(Browser)
ctx.add(Command, () => {
const live = browser()
const session = ctx.sessions.current()
return {
id: "preview",
title: ctx.t("command.preview"),
enabled: live.status === "active" && !!session,
run: () => {
if (live.status === "active" && session) live.value.open(session, "http://localhost:3000")
},
}
})pending:提供方尚未启动完成(例如插件正在加载或重启)。请显示加载态,或暂时隐藏可选控件。active:提供方正在运行,value为其契约或Ipc客户端。generation记录激活代数,提供方重启后会递增为新值。inactive(disabled):提供方已关闭、缺失或当前平台不支持(例如 Web 端的所有Ipc)。请展示不可用提示或省略该控件。inactive(failed):提供方初始化抛出异常,请展示不可用提示。- 插件自身的
main不具备Live状态;通过ctx.main发起的调用会在启动期间自动等待,并在无法响应时 reject。
类型参考
type Live<T> =
| { status: "pending" }
| { status: "active"; value: T; generation: number }
| { status: "inactive"; reason: "disabled" | "failed" }生命周期与清理(Lifetimes and cleanup)
通过 ctx 注册的所有内容(ctx.add、ctx.provide、ctx.dialogs.open、ctx.embeds.create 以及 Ipc 事件监听器)都会在其所属作用域结束时自动撤回:
- 在组件或
createKeyed回调中注册的内容,随该组件或该次createKeyed运行销毁而结束。 - 在窗口
setup顶层注册的内容,在插件被停用、重载、移除或所在窗口关闭时结束。 - 在
main中注册的内容,在插件被停用、重载、移除或应用退出时结束;嵌入视图还会在所属窗口关闭时一并结束。
对于定时器、套接字等其他资源,请从 setup 返回清理函数,它会在同一时机执行:
- 窗口
setup不能是async函数,因为它运行在 Solid owner 之下。请返回清理函数,或使用onCleanup/ctx.signal。 main可以是async函数。可直接返回或 resolve 清理函数,或使用ctx.onCleanup(fn)。
窗口 Setup
窗口 setup 必须保持同步,异步任务请在 createKeyed 或 createLatest 中启动:
import { Command, createKeyed, Plugin } from "@opencode/plugin/gui"
import { Changes } from "@opencode/plugin/gui/review"
export default Plugin.define({
i18n: { en: { changes: "Show changes" } },
setup(ctx) {
// Runs once per active generation of Changes; the command is withdrawn with it.
createKeyed(ctx.use(Changes), (changes) => {
ctx.add(Command, () => ({
id: "changes",
title: ctx.t("changes"),
run: () => {
const session = ctx.sessions.current()
if (session) changes.open(session)
},
}))
})
const timer = setInterval(() => console.log("still here"), 60_000)
return () => clearInterval(timer)
},
})主进程 Setup
main 可以是 async 函数。对于打开的资源,返回或 resolve 清理函数,或通过 ctx.onCleanup(fn) 注册:
async main(ctx) {
const socket = await connect(ctx.options)
ctx.onCleanup(() => socket.close())
}ctx.onCleanup会在插件被停用、重载、移除或应用退出时按后进先出(LIFO)顺序执行已注册函数;若插件此时已卸载,则立即执行。- 每次
await之后,在继续注册或修改任何状态之前,请先检查ctx.signal是否已中止并及时返回。 async清理函数会延迟应用退出直至其完成,最长等待 3 秒。