日本語
ドキュメント
OpenCode で開発
プラグイン
GUI プラグイン
GUI

GUI

@opencode/plugin/gui を使用して、OpenCode Desktop 向けの OpenCode プラグインの GUI パートを構築します。

GUI プラグインは、GUI プラグイン SDK である @opencode/plugin/gui を用いて OpenCode Desktop にパネル、コマンド、設定ページ、ネイティブ連携機能を追加します。これはプラグインパッケージの ./gui-experimental パートであり、単独で提供することも、サーバーパートや TUI パートと並べて提供することもできます。

注: GUI プラグイン API は実験的(experimental)であり、リリース間で変更される可能性があります。パッケージのエクスポート名に -experimental が付いているのはそのためです。

./gui-experimental ファイルでは、サーバーパートや TUI パートと同様に Plugin.define をデフォルトエクスポートします。

src/gui.tsx
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 プラグインは 2 つのプロセスで動作できます。

  • setup はすべてのデスクトップアプリウィンドウで実行されます。パネル、コマンド、設定ページ、スロット、サーバーソース、リンクハンドラー、スタイルを追加します。詳細は「ウィンドウ」セクションを参照してください。
  • main は Electron のメインプロセスで 1 回だけ実行されます。型付きの Ipc コントラクト、ネイティブメニュー項目、WebContentsView の埋め込み、Node および Electron との連携を提供します。詳細は「メインプロセス」セクションを参照してください。

パッケージ

1 つの npm パッケージにサーバー、TUI、GUI のコードをまとめて出荷できます。./tui と並べて ./gui-experimental エクスポートを 1 つ追加するだけで、OpenCode Desktop は自身のバックグラウンドサーバー上で稼働する各プラグインの GUI を読み込みます。

package.json
{
  "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 専用のインストール手順は不要です。

opencode.jsonc
{
  "plugins": ["opencode-acme-plugin"],
}

GUI は独自の ID を宣言せず、プラグイン自身の ID(サーバーパートの id、またはサーバーパートがないパッケージの場合はパッケージ名、name のないローカルディレクトリの場合はディレクトリ名)を引き継ぎます。これは ctx.id から読み取れます。

1 つのファイル、2 つのプロセス

どちらのプロセスも ./gui-experimental ファイル全体を評価し、そのデフォルトエクスポートを読み取ります。ウィンドウは setup を実行し、デスクトップアプリのメインプロセスは main を実行します。

src/gui.tsx
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())
  },
})

両方のプロセスが同じファイルを評価するため、各プロセスは相手側プロセスのモジュールに対して無害なプレースホルダーを代わりに差し込みます。

  • ウィンドウ内では、 electron や Node 組み込みモジュールが無害なプレースホルダーになります。
  • メインプロセス内では、 Solid やウィンドウ専用モジュールが無害なプレースホルダーになります。

プレースホルダーは、Solid が巻き上げるテンプレートやバンドラーが巻き上げる require 呼び出しなど、モジュールスコープでの任意のプロパティ読み取り・関数呼び出し・コンストラクター呼び出しを受け付けます。各プロセスのコードは必ず自身の setup 内に記述してください。誤ったプロセスで実行されたコードには、機能する値の代わりにプレースホルダーが渡されます。

Plugin.define やコントラクトヘルパーは両プロセスで単一の SDK から提供されます。メインプロセスでは @opencode/plugin/gui がメイン用 SDK に解決され、同じ Plugin、Store、Ipc、Contract、Registry をエクスポートするため、1 つの定義を両プロセスで共用できます。Command、bindPlugin、createKeyed などのウィンドウ専用エクスポートはメインプロセスでは undefined になるため、setup の中でのみ使用してください。

バンドルのビルド

./gui-experimental は事前にビルドされた単一の CommonJS ファイルである必要があります。@opencode/plugin/gui/vite が提供する Vite プリセットを使ってビルドしてください。

vite.config.ts
import { defineConfig } from "vite"
import { gui } from "@opencode/plugin/gui/vite"
 
export default defineConfig({ plugins: [gui()] })
vite build

このプリセットは以下の処理を行います。

  • vite-plugin-solid で Solid JSX をコンパイルします。
  • アプリは 2 つ目のチャンクを読み込めないため、単一の CommonJS ファイルを出力し、すべての動的 import() をインライン化します。
  • アプリの共有モジュール、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() にオプションを渡します。

vite.config.ts
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:fs などの Node 組み込みモジュール。ウィンドウでは無害なプレースホルダーになります。

GUI エントリーの読み込み元

OpenCode Desktop は自身のバックグラウンドサーバーから GUI エントリーを読み込みます。このサーバーはすでに設定ファイルからプラグインを読み込んでいるため、新たなコード供給源が追加されることはありません。すべてのウィンドウで GUI を利用できるようにするには、グローバルの opencode.json(c) にプラグインを設定してください。

注: 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 がリロードされます。サーバーエントリーは再起動されません。
  • インストール済みパッケージの GUI は、パッケージバージョンが更新されたときにのみ変更されます。
  • opencode.json(c) でプラグインの options を変更すると、プラグインがリロードされます。
  • opencode plugin update を実行すると、アップデート完了後にパッケージの GUI が差し替えられます。
  • Settings > Extensions > Plugins にはプラグインと GUI をオフにするスイッチが表示されます。削除するには opencode.json(c) から外すか、opencode plugin remove <package> を実行してください。

注: アプリ自身の組み込みプラグインはそれぞれの ID を予約しています。プラグインの ID が予約 ID と一致する場合、. でその配下にネストしている場合、予約 ID を配下に持つ場合、または opencode 名前空間に属している場合、その GUI は読み込まれず、Settings > Extensions > Plugins に未読み込みとして表示されます。

GUI プラグインの定義

Plugin.define はプラグインが動作する OS、ウィンドウ用の永続状態、アイコン、テキスト(i18n)を宣言します。ホストはいずれの setup を実行するよりも前にこれらの宣言を読み取ります。

src/gui/definition.ts
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 のプレフィックスになります(コマンドは <id>.<command>、パネルキーは <id>:<tab>、保存キーは plugin.<id>.<key>、および提供するコントラクトや IPC の ID)。
  • os はプラグインを特定の OS に限定します。省略するとすべての OS で動作します。現在のシステムが os に含まれないプラグインは実行されず、Settings > Extensions > Plugins には「Not available on this system.」と表示されます。
  • stores はウィンドウ向けの永続状態を宣言します。ctx.stores.<key> として読み取ります。
  • icons はプラグイン独自のアイコンを SVG ファイルのテキストとして宣言します。アイコン名は ctx.icons.<name> で参照します。
  • i18n はロケールごとの文言を保持します。すべてのロケールをインラインで記述してください。他のロケールで欠けているキーは英語(en)で補完されます。ctx.t(key, params) および ctx.plural(key, count) で読み取ります。ウィンドウ内では ctx.t で common.* などアプリ共通のキーも参照できます。main では存在しないキーを指定するとキー文字列自体が返ります。
  • setup、main、またはその両方を定義してください。どちらも定義されていない GUI は読み込みに失敗します。
  • setup を渡さずに 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 1 ファイルに収まります。規模が大きい場合は、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 を型付けし、最後にまとめてプラグインを定義します。

src/gui/definition.ts
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 }) },
})
src/gui/window.tsx
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 })
}
src/gui/main.ts
import type { Plugin } from "@opencode/plugin/gui"
 
export const main: Plugin.MainSetup = (ctx) => {
  ctx.log.write("info", "acme started")
}
src/gui.tsx
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 の型です。宣言されたストアから ctx.stores を、宣言されたアイコンから ctx.icons を型付けします。
  • Plugin.MainSetup はメイン用 setup の型、Plugin.Cleanup はどちらの setup でも返却できるクリーンアップ関数の型です。
  • Command、SettingsPage、Panel、Slot、Contract、Ipc、Registry、Store、createKeyed、usePlugin、bindPlugin などのレジストリ・トークン・ヘルパーは @opencode/plugin/gui からインポートします。
  • MenubarItem などのメイン専用レジストリは @opencode/plugin/gui/main からインポートします。

共有コンテキスト

どちらの setup も、サーバーパートや TUI パートと同様に、プラグインのオプション、OpenCode サーバー用クライアント、アプリメタデータを受け取ります。

オプション

ctx.options には、プラグインの opencode.json(c) エントリの options が格納されます(サーバーパートが受け取るものと同じ値です)。

opencode.jsonc
{
  "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 はサーバープラグインの ctx.app.name と同じく "opencode" です。
  • 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
}

コントラクトとトークン

トークンを使用すると、GUI プラグイン同士やプロセス間で互いのランタイムコードをインポートすることなく通信できます。すべてのトークンは contract.ts に配置してください。トークンが保持するのは種別と ID(および Ipc のスキーマ)のみであるため、他のプラグインはあなたのランタイムコードを読み込まずにトークンをインポートできます。

  • ctx.provide(token, impl) は自身のトークンを提供します(ウィンドウの setup からは Contract、main からは Ipc)。
  • ctx.use(token) は別のプラグインが提供するコントラクトまたは Ipc を購読し、Live アクセサーを返します(詳細は「ライブ依存関係と障害処理」セクションを参照してください)。
  • ctx.main(ipc) は自身の main が提供する Ipc に対するクライアントを返します。

プラグインが提供できるのは、自身の ID と一致するか <id>.<name> のように自身の ID で始まるトークンのみです。それ以外の 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.

コントラクト

あるプラグインのウィンドウ setup から他のプラグインのウィンドウ setup へ API や Solid コンポーネントを公開する場合は Contract.define を使用します。

src/gui/contract.ts
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() が利用側ではなく提供側のコンテキストを読み取るようになります。

src/gui.tsx
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 でラップするコンポーネントには、bindPlugin((props: FileTreeProps) => ...) のように props の型注釈を付けてください。ctx.provide 内部では TypeScript が型を推論できません。
  • count のようなデータメソッドはラップせずそのまま渡してください。
  • ctx.provide はコントラクトを早期に撤回するための関数を返します。また、現在のオーナーが破棄されるかプラグインが停止した際にもホストが自動的に撤回します。

他のプラグインのコントラクトを利用する

他のプラグインがトークンをインポートできるよう、パッケージから contract.ts を(たとえば ./contract として)エクスポートしてください。別のプラグインは ctx.use(token) でそのコントラクトを追従します。提供元の開始・停止・再起動に応じてアクセサーの値が変化するため、使用する場所で毎回読み取ってください。

src/gui.tsx
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

Effect の Schema コーデックとともに Ipc.define を使用すると、main と setup の間に型付きブリッジを定義できます。main が ctx.provide で実装し、ウィンドウが ctx.main 経由で呼び出します。

src/gui/contract.ts
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 でそれらを読み取ります。

src/gui/contract.ts
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)

ウィンドウ

プラグインの setup はすべてのデスクトップアプリウィンドウで実行されます。./gui-experimental ファイルで @opencode/plugin/gui の Plugin.define に渡してください。setup は同期的であり、クリーンアップ関数を返すことができます(詳細は「ライフタイムとクリーンアップ」セクションを参照してください)。

src/gui.tsx
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 が受け取るものと同じコンテキストオブジェクトを取得できます。コンポーネントと定義が循環インポートにならないよう、別ファイルの宣言(「ファイルの分割」セクション参照)から型付けしてください。

src/gui/window.tsx
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 でラップしてください(詳細は「コントラクト」セクションを参照してください)。

アイコン

SDK のすべての icon フィールドおよび ctx.ui.Icon は IconName(アプリ独自のアイコン名、またはプラグインが宣言したアイコン名)を受け取ります。それ以外の文字列はコンパイルエラーになります。

ctx.add(TitlebarItem, () => ({ id: "sync", label: ctx.t("sync"), icon: "server", run: () => sync() }))

独自アイコンの宣言

プロダクトのロゴマークなど、アプリに含まれていないアートワークを使う場合は、SVG ファイルをパッケージに含めて icons に宣言します。ファイルは ?raw 付きでインポートすると、gui() プリセットによってテキストとしてバンドルされます。

src/gui/definition.ts
import { Plugin } from "@opencode/plugin/gui"
import logo from "./icons/logo.svg?raw"
 
export const definition = Plugin.define({
  icons: { logo },
})

その後、IconName を受け取る任意の場所に ctx.icons からアイコン名を渡します。

src/gui/window.tsx
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" を追加してください。

アイコンの描画ガイドライン

ホストは組み込みアイコンと同じように、表示場所に応じたサイズと色でプラグインのアイコンを描画します。

src/gui/icons/logo.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" />
  <path d="M5 8.5 7 10.5 11 6" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" />
</svg>
  • viewBox(未指定時は width と height)が描画領域を定義します。ホストは 14、16、または 20 ピクセルにスケーリングするため、16 ピクセルグリッドで描画してください。
  • currentColor で描画してください。これにより、ピルの tone やメニュー行の控えめなアイコン色など、配置場所の色が自動的に適用されます。
  • SVG 内の id はウィンドウ全体で共有されます。ID を一意にするか、使用しないでください。

アイコンのアニメーション

作業中を示す場合など、アイコンにアニメーションを付けることもできます。SVG ファイル内で animate や animateTransform などの SVG アニメーション要素を使用してください。

src/gui/icons/working.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 が再実行されるなどホストがその場所を再レンダリングしても、アニメーションは途切れず継続します。
  • ユーザーの「視差効果を減らす(reduced motion)」設定が有効な場合、ホストはすべてのアイコンを最初のフレームで静止させます。最初のフレームは静止状態のデザインにしてください。
  • どこにも表示されていないアイコンはコストを消費しません。

保存されるアイコン名

アイコン名は <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>
}

レジストリ

レジストリトークンとアイテムを 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 を持つアイテムはホストがオブジェクト参照を安定保持します。これらのラベルは 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 は 2 行目の説明、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)は単一の入力オブジェクトを受け取ります。

  • props.session と props.tab は使用する箇所でリアクティブなゲッターとして読み取ってください。render の先頭で分割代入してはいけません。ユーザーがセッション A からセッション B へ切り替えてもパネルはマウントされたまま維持され、props.session がその場で更新されるためです。
  • props.screen は所有元の定数 SessionScreen(file、comment、composer)です。そのアクションは常に現在ルーティングされているセッションを対象とします。
  • タブに変更がない間はホストがトリガーを再マウントしないよう、list から同じ PanelTab オブジェクトを返してください。ラベルはゲッターから読み取ることで、新しいオブジェクトを作らずに言語切り替えへ追従できます。

パネルのコールバックは以下の通りです。

  • 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 ビューでは、file を表示する閉じたタブが Recently closed に一覧表示されます。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 があるため、ホストがオブジェクトを安定保持します。ラベルや 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 に対応し、検索時にその行へスクロールしてハイライト表示されます。
  • Props の詳細は「設定コンポーネント」セクションを参照してください。

リファレンス

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 はウィンドウ内の 4 つのスロットのいずれかに 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 はウィンドウ最下部、トーストの上に配置される全幅のストリップです。
  • session.header はセッションタイムラインのタイトル行です。キャッシュされたタイムラインは非表示中も active が false の状態でマウントされたまま残ります。
  • session.location.menu はプロジェクトメニューのロケーション詳細の後に項目を追加します。
  • session.panel.end はサイド領域のタブストリップ末尾にアクションを配置します。
  • order は同一スロット内の項目を並べ替えます。

session.location.menu はプロジェクトメニューが開いている間 true になる shown を受け取ります。ロケーションデータへのサブスクライブは 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 項目はランチャーとしても機能します。タブが 1 つもない状態でサイド領域を開いた場合や、primary 項目が存在しない状態で + をクリックした場合、ホストはランチャー一覧を表示する New tab ビューを表示します。

  • icon は項目のアイコン、keybind はショートカットを表示する公開済みコマンド ID です。
  • description はランチャー行でタイトルの後ろに表示される控えめな短い補足情報(件数など)です。
  • opened: true はその項目が開くタブがすでに開いていることを示します。ランチャー一覧からは除外されますが、+ メニューには引き続き表示されます。
  • primary: true を設定すると、ランチャー一覧を表示する代わりに + クリックでその項目を直接実行します。order が最も早い primary 項目が優先されます。タブがない状態でサイド領域を開いた場合は引き続き New tab ビューが表示され、primary でなく開いてもいない項目が一覧表示されます。
  • 独自のランチャーを作るために、すべてのプラグインの session.panel 項目を取得するには ctx.layout.side.menu() を使用してください(「レイアウト」セクション参照)。

リファレンス

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 はウィンドウのタイトルバーまたはタブフッターにピルボタンをレンダリングします。ラベルはホバー時に表示されます。

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 はセッションのコンポーザー上部の行(アプリのバックグラウンド作業ピルや Todo ピルの隣)にピルを追加します。現在作業中のセッションに紐づくブランチのプルリクエストなど、そのセッション固有のステータス表示に使用します。ピルはタイムライン上にフロート表示されるため、表示・非表示が切り替わってもコンポーザーのサイズは変わりません。この行はユーザーのバックグラウンドアクティビティ配置設定に従い、サブエージェントのセッションには表示されません。

show は 1 つのセッションに対するピルを返し、そのセッションで表示しない場合は undefined を返します。ホストはマウントされている各コンポーザーに対してこれを実行し、内部で読み取った値が変化すると再実行します。次のプラグインは、サーバーパートの RPC 経由で各セッションのディレクトリにあるオープンなプルリクエスト一覧を取得し、1 つのピルとして表示します。

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 が実行されます。
  • title は label と異なる場合にピルのアクセシブル名としても使用されます。
  • 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 string)の先頭単語を小文字化した値と比較されます。たとえば ```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 の render と同じブロック情報を受け取ります。

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),
})
  • 途中の未完コマンドを実行してしまわないよう、ボタンはブロックの閉じフェンスが到着した後に表示されます。
  • ボタンはホバーまたはキーボードフォーカス時に、Copy ボタンの手前に order 昇順で表示されます。
  • ロケールに追従するよう 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 が true になるまで待機します。ready になったソースの entries が完全なインベントリとして扱われます。
  • order はソースを昇順に並べ替えます。
  • 各エントリのキーは <plugin id>:<id> です。label は name の横に表示される短いバッジです。
  • auth はユーザーのサインイン待ち、incompatible はこのアプリがサポートしないバージョンであることを示します。
  • listed: false を指定するとアプリのサーバー一覧には表示されませんが、設定画面には引き続き表示されます。
  • http はサーバーが ready になったときのエンドポイントです。
  • 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)

テーマファイルは自身の名称とライト/ダークの 2 つのバリアントを定義します。各バリアントは 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

ホスト API は ctx のプロパティとして提供されます。アプリインターフェースのマウント前に呼び出しても例外をスローすることはありません。読み取りはドキュメント記載のデフォルト値を返し、ctx.layout.open、ctx.dialogs.open、ストア更新などの早期書き込みは最初のルートがレンダリングされるまで待機し、呼び出し順に適用されます。

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 については「GUI プラグインの定義」、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() は独自のランチャー用に、全プラグインの session.panel メニュー項目を order 順で返します。
  • 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
}

セッションとセッション画面

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 はセッション内で実行中のサブエージェントおよびシェルコマンドの一覧です。
  • 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
  }
}

コンポーザーへの添付

イベントハンドラーやコマンド内で 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? }) は添付済みパーツを更新します(note および quote で変更できるのは comment のみです)。
  • detach(commentID) は添付済みパーツを削除します。
  • note の live は、ページ要素など現在のアプリプロセス内でのみ解決できる参照向けに、そのプロセス内に留まっている間だけ subject と href を差し替えます。保存されたドラフトや、リバート/フォークで復元された送信済みメッセージでは live は破棄されます。

quote(引用)は、ログ出力などプラグインが表示している内容からユーザーが引用したテキストと任意のコメントです。ソースのアイコンとラベルの下に、セッションタイムラインからの引用と同じ見た目で表示されます。まず quotable() を確認してください。コンポーザーを持たないサブエージェントのセッションや、コンポーザーがシェルコマンドを実行している間は 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() はプロンプトのプレーンテキストです。メンションは @ テキストとして読み取られ、添付ファイルや添付パーツは含まれません。シェルモードではシェルコマンドになります。セッションのドラフト読み込み前およびコンポーザーのないサブエージェントセッションでは "" を返します。これはリアクティブです。
  • 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 はサーバーのバージョンがこのアプリと互換性がある場合に true、connected はイベント接続が確立している間 true になります。
  • password はユーザーが設定した HTTP Basic 認証パスワード(設定されている場合)です。
  • 再起動されたサーバーは同じ ID のまま新しいクライアントになるため、client、data、url は毎回ライブの ServerRef から読み取ってください。
  • 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 はユーザーが確定した場合のみ true を返します。danger を指定すると確定ボタンが破壊的操作のスタイルになり、初期フォーカスがキャンセルボタンに置かれます。
  • 各ダイアログは open と同様に開き、呼び出し元のオーナー(なければプラグイン)の終了とともに閉じます。
  • キャンセル、Escape キー、外側クリック、置換ダイアログの表示、オーナー終了のいずれかが発生した場合、confirm は false を、prompt と select は undefined を返します。

alert は確認ボタン 1 つでユーザーに通知し、どのような方法であれダイアログが閉じた時点で resolve されます。

await ctx.dialogs.alert({ title: ctx.t("export.done"), description: path })

prompt は 1 行のテキスト入力を求めます。初期値 value は全選択状態になるため、そのまま入力すると置き換わります。空文字列を resolve することはなく、入力欄が空の間は送信しても反応しません。パスワードやトークン用に secret: true で入力文字を隠すこともできます。

const token = await ctx.dialogs.prompt({ title: ctx.t("token.title"), placeholder: "ghp_…", secret: true })

select はコマンドパレットのような検索可能な一覧から選択肢を選び、選択された項目の 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 はアクション、{ type: "separator" }、{ type: "group", label, items } から成る 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 は、設定画面の言語選択行のように選択肢のリストから 1 つを選択します。値は文字列であり、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" のいずれかです。success トーストでは icon を指定しない限りチェックアイコンが表示されます。
  • 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,
  })
}
  • システム通知はアプリのウィンドウが 1 つもフォーカスされていない場合にのみ表示されます。サウンドはフォーカス状態にかかわらず再生されます。
  • どちらも Settings > Notifications の設定に従います。variant: "default" は Agent 行、variant: "error" は Errors 行に従います。デフォルトではどちらもデスクトップ通知がオフ、サウンドがオンです。
  • sound: false を指定するとサウンドは再生されません。
  • 通知をクリックするとアプリが前面に表示され、session を指定していた場合はそのセッションが開きます。
  • アプリの各ウィンドウがそれぞれプラグインのコピーを実行しています。実行 ID などのイベント id を渡すと、最初に送信したウィンドウのみが通知とサウンドを鳴らします。id を省略するとすべての呼び出しで通知されます。
  • アプリインターフェースのマウント前に呼ばれた場合、notify はマウント完了まで待機します。

notify は決して reject しません。実行結果として、アプリがシステムへ通知表示を依頼した場合は notification: true、サウンド再生を開始した場合は sound: true で resolve されます。

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)

セッションのトークン数、コスト、プランの数値は、アプリがヘッダーの「28k · $0.28」を表示するために読み取っているのと同じリアクティブストア(サーバーデータ)に格納されています。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) はキーボードイベントがコマンドの実効キーバインドに一致する場合に true を返します。

リファレンス

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 を持つ有効なコマンドが存在しない場合、run は false を返します。登録されていても無効化されているコマンドは実行されません。
  • アプリインターフェースのマウント前はコマンドが未登録のため、run は 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 を開きます。アプリ内リンクには Link をリンクハンドラーへルーティングする ctx.links.open を使用してください。
  • desktop.launch(path, app?) は指定したアプリ(またはデフォルトアプリ)でパスを開きます。desktop.reveal(path) はファイルマネージャーでそのパスを表示します。
  • ctx.embeds はウィンドウ内にメインプロセスの Web ビューをレンダリングします(「埋め込み Web ビュー」セクション参照)。
  • ctx.locale はインターフェース言語と文字の書字方向を読み取ります。ctx.appearance.font("mono") はユーザーのターミナルフォントの CSS フォントファミリーを返します。
  • ctx.router は現在のルートパスとルート遷移中かどうかを読み取ります。
  • ctx.workspaces.on("remove", handler) はユーザーがサーバーからワークスペースディレクトリを削除したときに実行され、そのディレクトリにスコープされたストアをクリーンアップできます。

desktop.pick(options) は OS のファイル選択ダイアログでユーザーにファイルまたはフォルダを選択させ、絶対パスの配列を返します。

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 はダイアログのタイトルです(OS によっては表示されない場合があります)。
  • ユーザーがキャンセルした場合は空配列が返ります。ダイアログを開けない場合は reject されます。
  • pick はデスクトップ専用です(ブラウザーは選択されたファイルのローカルパスをページに公開しません)。

ctx.appearance.mode() はインターフェースが現在表示しているカラースキーム("light" または "dark")を返します。これはリアクティブです。

const background = () => (ctx.appearance.mode() === "dark" ? "#000" : "#fff")
  • Settings > Appearance のユーザー選択に従い、System の場合は OS 現在のスキームに解決されます。
  • アプリインターフェースのマウント前はシステムのスキームが返ります。

リファレンス

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.global はアプリ全体で 1 つの値を保持します。setup 実行前に読み込まれるため、ctx.stores.name.value が undefined になることはありません。
  • Store.session はセッションごとに 1 つの値を保持します。セッションがマウントされたタイミングで読み込まれるため、それまで ctx.stores.name(session).value は undefined です。

宣言されたストアはウィンドウ用です。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 はストアに値がまだない場合に一度だけインポート元とする別キー(リネーム前のストアキー "plugin.acme.settings" など)を指定します。配列を渡すと新しい順に複数キーを試します。元のキーのコピーはストアが削除されるまで保持されます。
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
}

ランタイムストア

実行時に初めて決まるキーには ctx.storage.store(key, options) でストアを開きます。scope によりサーバー、ディレクトリ、またはセッションごとに 1 つの値を保持できます。

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" はアプリ全体で 1 つの値を保持します。
  • scope: { server, directory? } はサーバー単位、またはそのサーバー上のワークスペースディレクトリ単位で 1 つの値を保持します。
  • scope: { session } はセッション単位で 1 つの値を保持し、セッションが別ディレクトリへ移動すると再度開かれます。
  • ランタイムストアの 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 }

リアクティブプリミティブ

生の createEffect、createRenderEffect、createComputed よりも以下のヘルパーを優先して使用してください。手書きのエフェクトでは誤りやすいプラグインのライフタイムや依存先の再起動に正しく追従します。

createKeyed

createKeyed(source, fn, { otherwise?, equals? }) はキーごと(ctx.use アクセサーの各アクティブ世代、または通常アクセサーの各値)に新しいオーナー内で fn を実行します。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 アクセサーは常に世代(generation)をキーとします。

リファレンス

function createKeyed<T>(
  source: () => Live<T> | T,
  fn: (value: T) => void,
  options?: { otherwise?(): void; equals?(previous: T, next: T): boolean },
): void

createLatest

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
}

メインプロセス

OpenCode Desktop では、プラグインの main setup が Electron のメインプロセス内でアプリ全体のシングルトンとして 1 回だけ実行されます。Node.js 組み込みモジュール、electron、およびメインホスト API への完全なアクセス権限を持ちます。プラグインの ./gui-experimental ファイルで、ウィンドウの setup と並べて、あるいは単独で Plugin.define に渡してください。

src/gui.tsx
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 ファイル内にこのインポートを記述しても安全です(「1 つのファイル、2 つのプロセス」セクション参照)。

メインコンテキスト

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 }) はプラグインの名前空間内にストアを同期的に開きます。value は常に定義されており、各 set および update は戻る前にデータベースへ永続化されます。ctx.storage.remove(key) は値を削除します。
  • ctx.signal はプラグインが無効化・リロード・削除されたとき、またはアプリ終了時にアボートされます。ctx.onCleanup(fn) はそのタイミングで fn を実行します(「ライフタイムとクリーンアップ」セクション参照)。
  • ctx.provide はプラグイン ID 配下の Ipc を実装します(「IPC の定義と提供」セクション参照)。
  • ctx.add は MenubarItem などメインプロセス用のレジストリへ項目を追加します(「ネイティブアプリメニュー」セクション参照)。
  • ctx.windows はアプリのウィンドウ一覧を返し、ウィンドウの開閉を通知します。
  • ctx.embeds はウィンドウのレイアウト内に WebContentsView を配置します(「埋め込み Web ビュー」セクション参照)。
  • 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 によって検証・エンコードされます。

src/gui/contract.ts
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 は acme.counter のように自身のプラグイン ID と一致するか、自身の ID で始まる必要があります。それ以外の 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>
}

main でのプロバイダー実装

各メソッドはデコード済みの入力と Caller({ window, signal })を受け取ります。state が変化したら provider.changed(window?) を呼び出してサブスクライブ中のウィンドウへ最新のスナップショットをプッシュし、イベントを送信するには provider.emit(name, payload, window?) を呼び出します。

src/gui/main.ts
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 スキーマを持たないメソッドはオプションの { signal } 呼び出しオプションのみを受け取ります。第 1 引数に undefined を渡さないでください。

src/gui/window.tsx
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 の起動中は待機します。Web 環境、プラグインの main が停止・失敗している場合、またはメソッドが例外をスローした場合など main が応答できないときは reject されます。ユーザーにフィードバックが必要な箇所では reject を catch してください。
  • state() と on() は main の再起動をまたいで追従します。リスナーは現在のオーナー(なければプラグイン)の終了とともに解除されます。
  • ctx.main は同じトークンに対するすべての呼び出しで同一のクライアントを返します。

このウィンドウの state は 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 の間、その値は同じ IpcClient です。

const counter = ctx.use(Counter)
 
const count = () => {
  const live = counter()
 
  return live.status === "active" ? (live.value.state()?.count ?? 0) : 0
}
  • メインプロセスが存在しない Web 環境では、すべての Ipc が inactive になります。

ネイティブアプリメニュー

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、組み込み項目ならコマンド名・アクション名・ロール名の順で一致判定。例: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
}

埋め込み Web ビュー

パネル内に分離された WebContentsView を埋め込むには、main でビューを作成し、ウィンドウ側でそのボックスをレンダリングします。

src/gui/main.ts
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)
}
src/gui/pane.tsx
<ctx.embeds.View id={embedId} visible radius={8} />
  • "open" は後から開かれるウィンドウでのみ発火するため、最初に ctx.windows.list() に対してもアタッチしてください。
  • ウィンドウ側は ctx.embeds.View と ctx.embeds.capture に埋め込みの id を渡します。
  • 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
}

ライブ依存関係と障害処理

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 は起動回数を数えるため、再起動した提供元は新しい generation 値で復帰します。
  • inactive, disabled: 提供元がオフ、未導入、またはこのプラットフォームでは利用不可(Web 環境のすべての Ipc など)の状態です。利用不可の表示を出すか、コントロールを省略してください。
  • inactive, failed: 提供元の setup がエラーをスローした状態です。利用不可の表示を出してください。
  • 自身の main には Live 状態がありません。ctx.main 経由の呼び出し(「ウィンドウでの IPC 利用」セクション参照)は起動完了まで待機し、応答できない場合に reject されます。

リファレンス

type Live<T> =
  | { status: "pending" }
  | { status: "active"; value: T; generation: number }
  | { status: "inactive"; reason: "disabled" | "failed" }

ライフタイムとクリーンアップ

ctx を通じて登録したすべてのもの(ctx.add、ctx.provide、ctx.dialogs.open、ctx.embeds.create、Ipc イベントリスナー)は、それを所有するスコープの終了時に自動的に撤回されます。

  • コンポーネントまたは createKeyed コールバック内での登録は、そのコンポーネントや createKeyed 実行が破棄されたときに終了します。
  • setup のトップレベルでの登録は、プラグインが無効化・リロード・削除されたとき、またはウィンドウが閉じたときに終了します。
  • main での登録は、プラグインが無効化・リロード・削除されたとき、またはアプリ終了時に終了します。埋め込みビューはそのウィンドウが閉じたときにも終了します。

タイマーやソケットなどその他のリソースについては、setup からクリーンアップ関数を返してください。同じタイミングで実行されます。

  • ウィンドウの setup は Solid オーナーの下で実行されるため async にはできません。クリーンアップ関数を返すか、onCleanup または ctx.signal を使用してください。
  • main は async にできます。クリーンアップ関数を返す(または resolve する)か、ctx.onCleanup(fn) を使用してください。

ウィンドウの setup

ウィンドウの setup は同期的である必要があります。非同期処理は createKeyed または createLatest の内部で開始してください。

src/gui.tsx
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 秒間待機させます。