构建 TUI 插件
使用 @opencode/plugin/tui 构建 OpenCode 插件的终端 UI(TUI)部分。
TUI 插件可通过命令、路由、插槽(slots)、Markdown 渲染器、通知与本地状态来扩展终端界面。TUI 插件是插件包中的 ./tui 导出部分,通常会与服务端部分并存:
import { Plugin } from "@opencode/plugin/tui"
export default Plugin.define({
id: "acme.cli",
setup(context) {
context.ui.toast.show({ message: "TUI plugin loaded", variant: "success" })
},
})直接导入 @opencode/plugin/tui 即可。OpenCode 会在运行时自动解析该导入,因此本地 TUI 插件不需要指向 OpenCode 源码仓库的绝对路径。
上下文(Context)
setup 会接收插件配置、应用元数据、当前位置、OpenCode 客户端、本地缓存数据、主题令牌、OpenTUI 渲染器以及下文介绍的所有 UI API:
setup(context) {
const compact = context.options.compact === true
const location = context.location ?? context.data.location.default()
const version = context.app.version
const channel = context.app.channel
const client = context.client
const renderer = context.renderer
const theme = context.theme
}对于插件自身持有的资源,请返回一个清理函数:
setup(context) {
const stop = context.data.on("session.execution.succeeded", () => {})
return () => stop()
}客户端(Client)
context.client 是自动生成的 OpenCode 客户端,可用于调用当前连接的服务器(包括远程服务器):
const response = await context.client.plugin.list({
location: context.location ?? context.data.location.default(),
})
const plugins = response.data事件
使用 data.on 监听单一类型的强类型事件,或使用 data.listen 监听全部服务器事件;两者都会返回一个取消订阅函数:
const stopPermission = context.data.on("permission.asked", (event) => {
context.ui.toast.show({ message: `Permission ${event.data.id}` })
})
const stopAll = context.data.listen(({ details }) => console.log(details.type))
return () => {
stopPermission()
stopAll()
}会话(Sessions)
会话数据支持列表查询、单项查找、父子层级关系、费用统计、运行状态、数据同步及缓存失效:
const sessions = context.data.session.list()
const session = context.data.session.get(sessionID)
const rootID = context.data.session.root(sessionID)
const familyIDs = context.data.session.family(sessionID)
const cost = context.data.session.cost(sessionID)
const status = context.data.session.status(sessionID)
await context.data.session.sync(sessionID)
context.data.session.invalidate(sessionID)待处理收件箱条目与消息同样提供列表、查找、同步与失效 API:
await context.data.session.pending.sync(sessionID)
const pending = context.data.session.pending.list(sessionID)
context.data.session.pending.invalidate(sessionID)
await context.data.session.message.sync(sessionID)
const messages = context.data.session.message.list(sessionID)
const message = context.data.session.message.get(sessionID, messageID)
context.data.session.message.invalidate(sessionID)可以读取并刷新会话中的权限审批请求:
await context.data.session.permission.sync(sessionID)
const requests = context.data.session.permission.list(sessionID) ?? []
context.data.session.permission.invalidate(sessionID)在指定位置下,表单(forms)支持列出、刷新、回复或取消操作:
import type { SessionFormCancelInput, SessionFormReplyInput } from "@opencode/client"
async function handleForm(reply: SessionFormReplyInput, cancel: SessionFormCancelInput) {
const location = context.location
await context.data.session.form.sync(sessionID, location)
const forms = context.data.session.form.list(sessionID, location) ?? []
await context.data.session.form.reply(reply, location)
await context.data.session.form.cancel(cancel, location)
context.data.session.form.invalidate(sessionID, location)
}项目与 Shell
项目列表及已保存权限支持列出、查找、同步与缓存失效操作:
await context.data.project.sync()
const projects = context.data.project.list()
const project = context.data.project.get(projectID)
context.data.project.invalidate()
await context.data.project.permission.sync(projectID)
const saved = context.data.project.permission.list(projectID) ?? []
context.data.project.permission.invalidate(projectID)Shell 数据支持按位置隔离的列出、查找、同步与失效操作:
await context.data.shell.sync(context.location)
const shells = context.data.shell.list(context.location)
const shell = context.data.shell.get(shellID)
context.data.shell.invalidate(context.location)位置数据(Location data)
位置状态暴露默认位置及刷新控制:
const location = context.data.location.default()
await context.data.location.sync(location)
context.data.location.invalidate(location)版本控制(VCS)状态暴露指定位置的仓库信息:
await context.data.location.vcs.sync(context.location)
const vcs = context.data.location.vcs.info(context.location)
const branch = vcs?.branch.current
context.data.location.vcs.invalidate(context.location)代理、命令、集成、模型、提供商、引用、技能以及 MCP 数据均统一提供 list、sync 和 invalidate 方法:
const location = context.location
await Promise.all([
context.data.location.agent.sync(location),
context.data.location.command.sync(location),
context.data.location.integration.sync(location),
context.data.location.model.sync(location),
context.data.location.provider.sync(location),
context.data.location.reference.sync(location),
context.data.location.skill.sync(location),
context.data.location.mcp.server.sync(location),
context.data.location.mcp.resource.sync(location),
])
const agents = context.data.location.agent.list(location) ?? []
const commands = context.data.location.command.list(location) ?? []
const integrations = context.data.location.integration.list(location) ?? []
const models = context.data.location.model.list(location) ?? []
const providers = context.data.location.provider.list(location) ?? []
const references = context.data.location.reference.list(location) ?? []
const skills = context.data.location.skill.list(location) ?? []
const servers = context.data.location.mcp.server.list(location) ?? []
const resources = context.data.location.mcp.resource.list(location) ?? []
context.data.location.model.invalidate(location)提醒通知(Attention)
提醒请求可根据终端焦点状态弹出系统通知、播放已配置提示音,或同时执行两者:
const result = await context.attention.notify({
title: "OpenCode",
message: "Session done",
notification: { when: "blurred" },
sound: { name: "done", volume: 0.5, when: "always" },
})
console.log(result.ok, result.notification, result.sound, result.skipped)主题与渲染器
配合 OpenTUI 元素使用语义化主题令牌,并将 context.renderer 传入依赖渲染器的辅助函数:
const Status = () => <text fg={context.theme.text.base}>Ready</text>
const renderer = context.renderer由渲染器绘制的 OpenTUI 资源必须以 context.renderer.nativeScene 作为所有者(owner)。例如 <markdown> 和 <code> 需要一个 SyntaxStyle。请在绘制该资源的最后一帧结束后、渲染器空闲时再销毁它:
import { SyntaxStyle } from "@opentui/core"
const style = SyntaxStyle.fromStyles({ default: { fg: context.theme.text.base } }, context.renderer.nativeScene)
context.ui.slot({ append: "home.footer", render: () => <markdown content="Ready" syntaxStyle={style} /> })
return () => context.renderer.idle().then(() => style.destroy())如需读取某个 renderable 的布局样式,请调用与 Yoga Node getter 同名的方法,例如 box.getPadding(Yoga.Edge.Bottom) 或 box.getMaxWidth()。宿主内部 renderable 不属于插件公开 API,其结构与样式可能在任意版本中变更。
面向 OpenTUI 0.5 构建的插件
OpenCode 使用自身内置的 OpenTUI 运行插件。自 OpenTUI 0.6 起:
SyntaxStyle.create()、SyntaxStyle.fromStyles()、SyntaxStyle.fromTheme()、TextBuffer.create()与EditBuffer.create()均在最后一个参数接受 owner;OptimizedBuffer.create()则通过owner选项传入。请统一传入context.renderer.nativeScene。OpenTUI 0.5 会忽略多余参数,因此插件依然兼容旧版 OpenCode。@opencode/theme/tui中的generateSyntax()将 owner 作为第二个参数:generateSyntax(context.theme, context.renderer.nativeScene)。旧版@opencode/theme构建样式时不带 owner,因此请一并更新该包。getLayoutNode()已被移除。在 OpenTUI 0.6.5 及更高版本中,请将getLayoutNode().getMaxWidth()及其他样式 getter 替换为 renderable 上的同名方法;将getComputedLayout()及其他计算位置/尺寸 getter 替换为getLayout();将markDirty()替换为invalidateIntrinsicSize()。计算后的 padding、margin 与 border 无替代接口,且getPadding(edge)仅读取为该边显式设置的 padding。在 OpenTUI 0.6.6 及更高版本中,如需还原 getter 报告为未设置(Unit.Undefined)的样式,请为对应属性赋值undefined。
完整变更列表请参阅 OpenTUI 0.6.0 发布说明 (opens in a new tab)。
Solid 组件
在路由、弹窗或插槽渲染的 JSX 组件内,使用 usePlugin 获取当前插件上下文:
import { usePlugin } from "@opencode/plugin/tui"
function Status() {
const context = usePlugin()
return <text fg={context.theme.text.base}>{context.app.version}</text>
}Markdown
按代码语言注册围栏代码块渲染器,返回的函数用于注销:
const unregister = context.markdown.registerCodeBlockRenderer("acme", (_token, render) => render.defaultRender())
return unregister命令与快捷键层
在响应式快捷键层(keymap layer)中注册命令面板、斜杠命令与快捷键命令:
context.keymap.layer(() => ({
mode: "global",
priority: 10,
commands: [
{
id: "acme.status",
title: "Show Acme status",
group: "Acme",
bind: "ctrl+g",
palette: true,
slash: { name: "acme", aliases: ["status"], arguments: true },
enabled: () => true,
suggested: true,
run: async (input) => context.ui.toast.show({ message: input ?? "Ready" }),
},
],
bindings: ["acme.status"],
}))你可以在 setup 中(包括 await 之后)或在组件内部调用 layer。当以下任一事件率先发生时,对应快捷键层会被自动移除:
- 插件被停用、重载或初始化失败。
- 创建它的组件或响应式计算(例如插槽、路由或弹窗)被销毁。
快捷键层工厂函数必须是纯函数。OpenCode 会先在不追踪依赖的情况下求值一次以校验初始命令结构,之后再以响应式方式运行。初始结构错误(如缺少 ID 的命令面板项)会直接由 layer() 抛出;快捷键解析错误由 OpenTUI 处理;后续响应式更新中的错误则遵循 Solid 的错误处理机制。
async setup(context) {
const settings = await loadSettings()
context.keymap.layer(() => ({
mode: "global",
commands: [{ id: "acme.sync", title: "Sync Acme", palette: true, run: () => sync(settings) }],
}))
}快捷键层可以绑定到单个 OpenTUI renderable,且命令返回 false 可让键盘事件继续向下分发:
context.keymap.layer(() => ({
target: () => panel,
commands: [{ bind: "escape", run: (_input, event) => (event ? false : undefined) }],
}))你还可以主动派发命令、查询快捷键与命令状态,或压入临时的输入模式:
context.keymap.dispatch("acme.status", "verbose")
const shortcuts = context.keymap.shortcuts("acme.status")
const commands = context.keymap.commands()
const pending = context.keymap.pending()
const active = context.keymap.active()
const currentMode = context.keymap.mode.current()
const popMode = context.keymap.mode.push("acme-search")
popMode()存储
持久化存储会跨重启保存 JSON 数据,并在多个 TUI 实例间自动同步:
const [settings, updateSettings] = context.storage.store("settings", {
initial: { compact: false },
})
await updateSettings((draft) => {
draft.compact = true
})内存存储在插件重载期间保留,但在 TUI 退出时丢弃:
const [state, updateState] = context.storage.memory("state", {
initial: { count: 0 },
})
updateState((draft) => {
draft.count++
})弹窗与轻提示(Toasts)
使用基于 Promise 的弹窗 API 实现提示框、确认框、文本输入与列表选择:
await context.ui.dialog.alert({ title: "Acme", message: "Ready" })
const confirmed = await context.ui.dialog.confirm({
title: "Continue?",
message: "Run the Acme action?",
label: { confirm: "Run", cancel: "Cancel" },
})
const name = await context.ui.dialog.prompt({ title: "Name", placeholder: "release" })
const mode = await context.ui.dialog.select({
title: "Mode",
current: "safe",
options: [
{ title: "Safe", value: "safe", description: "Ask before changes" },
{ title: "Fast", value: "fast", disabled: false, category: "Advanced" },
],
})选择框自定义搜索
传入 search 回调即可接管匹配与排序逻辑。每次查询(包括空查询)都会调用该回调,且仅传入已启用的选项。结果按返回顺序展示,每个分类以内联方式显示:
const project = await context.ui.dialog.select({
title: "Projects",
options: [
{ title: "Alpha", value: "alpha", category: "Recent" },
{ title: "Beta", value: "beta", category: "Pinned" },
],
search: (query, options) =>
options
.filter((option) => option.title.toLowerCase().includes(query.toLowerCase()))
.toSorted((left, right) => right.title.localeCompare(left.title)),
})选择框底部操作
操作项显示在弹窗底部,可通过绑定的快捷键、鼠标点击或 Tab 聚焦后按 Enter 触发。默认情况下操作项会接收当前选中值,若无选中项则不可用;对无需选中项的操作请设置 selection: "none":
await context.ui.dialog.select({
title: "Projects",
options: [{ title: "Alpha", value: "alpha" }],
actions: [
{ bind: "ctrl+o", title: "Inspect", onTrigger: (value) => context.ui.toast.show({ message: value }) },
{ bind: "ctrl+a", title: "Close", side: "right", selection: "none", onTrigger: () => context.ui.dialog.clear() },
],
})- 触发操作项不会关闭弹窗,也不会结算 Promise。
- 按 Enter 或点击选项会 resolve 为选中值。
- 按 Escape、调用
clear()或打开另一个弹窗会 resolve 为undefined。 - 请勿绑定
ctrl+n或ctrl+p,弹窗保留这两个按键用于导航,且弹窗自身绑定优先级更高。
自定义 JSX 弹窗可以设置尺寸并自行关闭:
context.ui.dialog.set({ size: "large", centered: true })
context.ui.dialog.show(
() => (
<box>
<text>Acme</text>
</box>
),
() => console.log("closed"),
)
context.ui.dialog.clear()轻提示(Toast)支持标题、消息、变体样式和持续时长:
context.ui.toast.show({
title: "Acme",
message: "Saved",
variant: "success",
duration: 3000,
})路由与标签页
注册 JSX 路由、读取当前路由,以及导航至首页、特定会话或插件页面:
const unregister = context.ui.router.register({
name: "dashboard",
render: ({ data }) => <text>{String(data?.title ?? "Acme")}</text>,
})
const current = context.ui.router.current()
context.ui.router.navigate({ type: "plugin", name: "dashboard", data: { title: "Status" } })
context.ui.router.navigate({ type: "session", sessionID })
context.ui.router.navigate({ type: "home" })
return unregister当启用会话标签页时,可以列出、打开、聚焦、移动和关闭标签页。open 不会改变当前焦点;focus 会在需要时自动打开该标签页:
if (context.ui.tabs.enabled()) {
context.ui.tabs.open(backgroundSessionID)
context.ui.tabs.focus(sessionID)
const tabs = context.ui.tabs.list()
context.ui.tabs.move(backgroundSessionID, tabs.length - 1)
context.ui.tabs.close(sessionID)
context.ui.tabs.close()
}模型
读取提示词当前选中的模型并切换其变体(variant)。在 Solid 响应式计算中读取 current() 与 variant.list() 会自动建立响应式追踪。variant 为 undefined 表示使用模型默认配置:
const selected = context.ui.model.current()
const variants = context.ui.model.variant.list()
context.ui.model.variant.set("high")
context.ui.model.variant.set(undefined)当未选中模型或该模型不存在对应变体时,variant.set 返回 false。你可以将其绑定到自定义命令来替换内置变体轮换行为(例如跳过默认变体):
context.keymap.layer(() => ({
commands: [
{
id: "acme.variant.cycle",
title: "Cycle variants",
bind: "tab",
run() {
const variants = context.ui.model.variant.list()
if (variants.length === 0) return
const index = variants.indexOf(context.ui.model.current()?.variant ?? "")
context.ui.model.variant.set(variants[(index + 1) % variants.length])
},
},
],
}))插槽(Slots)
插槽可在 app、home.footer、home.footer.status、prompt.footer、prompt.footer.status、prompt.footer.file、session.composer.top、sidebar.content 或 sidebar.footer 位置插入或替换 JSX:
return context.ui.slot({
append: "sidebar.content",
render: ({ sessionID }) => <text>{context.data.session.get(sessionID)?.title}</text>,
})支持使用 prepend、append、before、after 或 replace 控制插入位置:
context.ui.slot({ prepend: "home.footer", render: () => <text>Before footer content</text> })
context.ui.slot({ append: "home.footer", render: () => <text>After footer content</text> })
context.ui.slot({ before: "home.footer", render: () => <text>Before footer slot</text> })
context.ui.slot({ after: "home.footer", render: () => <text>After footer slot</text> })
context.ui.slot({ replace: "home.footer", render: () => <text>New footer</text> })使用 home.footer.status 可在不替换内置页脚的前提下向状态栏追加内容。状态贡献项会显示在 OpenCode 健康指示器之后、版本号之前:
context.ui.slot({ append: "home.footer.status", render: () => <text>SYNCED</text> })会话面板(Session panels)
向 session.panel 插槽注册内容贡献项,再通过命令打开面板。宿主负责尺寸、焦点与全屏展示,插件负责面板内部渲染。当前选中的面板名会通过 panel.name 传递给所有贡献项,由各贡献项自行决定是否渲染:
import { Show } from "solid-js"
context.ui.slot({
append: "session.panel",
render: (panel) => (
<Show when={panel.name === "acme.review"}>
<ReviewPanel panel={panel} />
</Show>
),
})
context.ui.slot({
append: "app",
render: () => {
context.keymap.layer(() => ({
mode: "global",
commands: [
{
id: "acme.review",
title: "Open review",
slash: { name: "review" },
run: () => {
context.ui.panel.open("acme.review")
},
},
],
}))
return null
},
})- 在会话外部打开面板会返回
false。 - 这是一个常规插槽,五种定位方式及既有的替换优先级规则均适用。
- 独立可选的面板贡献项请使用
append以便多插件共存;replace依然会接管整个插槽。 - 面板名是共享的选择值而非独占注册项。建议使用带插件前缀的名称(如
acme.review)避免冲突。打开没有对应渲染器的名称会让插槽保持空白。 - 切换展示模式(侧栏/全屏)会保留已挂载的组件;关闭面板则会销毁它们;停用插件时通过常规插槽清理机制移除其贡献项。
- 面板内的快捷键层与输入模式仅在面板拥有输入焦点时激活。
该插槽会收到响应式的 name、sessionID、width、presentation 和 focused 属性,以及 focus、close 和 toggleFullscreen 操作方法。在窄终端中宿主会强制保持全屏,直到有足够宽度容纳侧边面板时 toggleFullscreen 才会生效:
import type { PanelInput } from "@opencode/plugin/tui/context"
import { usePlugin } from "@opencode/plugin/tui"
function ReviewPanel(props: { panel: PanelInput }) {
const context = usePlugin()
context.keymap.layer(() => ({
commands: [
{
id: "acme.review.fullscreen",
bind: "f",
run: props.panel.toggleFullscreen,
},
],
}))
return <text>Reviewing {props.panel.sessionID}</text>
}你可以在打开时直接请求全屏模式、检查当前激活面板,或在不妨碍其他插件面板的情况下关闭当前面板:
context.ui.panel.open("acme.review", { presentation: "fullscreen" })
const current = context.ui.panel.current()
context.ui.panel.close()格式化
格式化文件系统路径用于界面展示(包括将主目录缩写为 ~):
const displayPath = context.ui.format.path(context.location?.directory ?? "/home/me/project")发布与加载
通过 ./tui 导出入口暴露 TUI 插件;若插件渲染了 JSX,请添加 OpenTUI 的 peerDependencies:
{
"name": "opencode-acme-plugin",
"type": "module",
"exports": {
".": "./src/index.ts",
"./tui": "./src/tui.tsx"
},
"dependencies": {
"@opencode/plugin": "latest"
},
"peerDependencies": {
"@opentui/core": ">=0.6.6",
"@opentui/solid": ">=0.6.6",
"solid-js": ">=1.9.0"
}
}将 ./tui 与服务端部分或 GUI 部分一并导出即可自动加载:
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "acme.server",
setup() {},
})对于仅包含 TUI 部分的插件包,请将其配置在 cli.json 中,以确保连接远程服务器时依然保持激活:
{
"plugins": ["opencode-acme-plugin"]
}