docs(cli-rs): explain what the retained plugin examples demonstrate

Replace command-by-command narration with each example’s purpose. Keep fixture behavior, actual feature names and the SDK quick start intact. Both C and Rust transcript replays passed, as did the Luau prelude test and check:luau-types.
This commit is contained in:
Simon Klee
2026-11-18 20:53:17 +01:00
Unverified
parent 372af0679e
commit 848310f13c
28 changed files with 63 additions and 229 deletions
+4 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "opencode-plugin"
description = "The Rust plugin API (P.1)."
description = "Plugin loaders and host runtime for the native TUI."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -13,7 +13,6 @@ workspace = true
opentui.workspace = true
opencode-ui.workspace = true
log.workspace = true
# Native plugins (P.4): the C ABI, and dlopen.
opencode-plugin-abi.workspace = true
opencode-util.workspace = true
serde.workspace = true
@@ -21,22 +20,18 @@ serde_json.workspace = true
unicode-segmentation = "1"
unicode-width.workspace = true
opencode-api-types.workspace = true
# The URLs of git specs, parsed as `new URL` parses them (the npm cache's keys, js-npm).
url.workspace = true
# The hash an approval of a project plugin names (rich-plugins 3.9).
ring.workspace = true
[features]
# TypeScript TUI plugins on the JS host: the pipe carrier, the JS host and its embedded `host.ts` and `compat.js`
# (ts-feature). On by default; `OPENCODE_PLUGIN_JS=0` still turns the host off at run time.
# Disable the JS host at runtime with `OPENCODE_PLUGIN_JS=0`.
default = ["ts", "luau"]
ts = []
# Luau plugins, in process (O-178). On by default; `OPENCODE_PLUGIN_LUAU=0` turns them off at run time.
# Disable Luau at runtime with `OPENCODE_PLUGIN_LUAU=0`.
luau = ["dep:mlua"]
# Luau plugins (O-178): a fourth carrier of contract 2.0, behind the default feature `luau`. Not on x86_64 Windows MSVC
# until OpenTUI's library links beside it (build.rs).
# The Luau and OpenTUI native libraries cannot link together on x86_64 Windows MSVC.
[target.'cfg(not(all(target_arch = "x86_64", target_os = "windows", target_env = "msvc")))'.dependencies]
mlua = { workspace = true, optional = true }
@@ -1,6 +1,4 @@
# A plugin of contract 2.0 (P4): a route of memoized cards, commands, and a thread that floods its mailbox. The TUI's
# `plugin_carriers` tests build it as a `cdylib` and link `src/board.rs` itself, and compare the two
# (`carrier-equal`). Not a workspace member.
# The carrier harness builds this library and links the same source into the test process.
[package]
name = "opencode-board-plugin"
version = "0.1.0"
@@ -1,29 +1,5 @@
//! A board of cards on a route of contract 2.0, in a scroll that takes the page below the header. Each card shows a
//! value and a patch by content handle, memoized on its value; the header shows the plugin's own call log: how many
//! views ran, how many cards they built, and how many messages arrived. A meter, a canvas below the header, draws the
//! cards' total as a bar, with the frame it drew for: its version follows the total, and it animates on request,
//! adding up the animation's time. Commands bump a card, toast, panic, animate the meter or make its next draw panic,
//! start a task that awaits a confirm and then a fetch, and start threads: one that floods the mailbox, waiting on
//! `Full`, and one that panics. Keys of the route (P2) bump
//! a card, pass a key on to the plugin's own global layer, set a mode in which the same key bumps another card, and
//! panic; the header lists the keys the handlers heard, each with the mode the handler read. A panel beside a session,
//! `notes`, focuses its pad, reads where the focus is and the pad's place, holds a key and releases it, opens an
//! overlay under its pad, gives its field the focus (`focus-input`), and gives the focus back; a centered select lists
//! the cards a search finds. `board.facts`, also `/inspect`, reads the host's locale, UTC offset and measure of a text, shows
//! them in a row its layout bounds at both widths, and asks for a name in a prompt filled with a value under a
//! description (contract ergonomics 2.6 and 2.9). `board.hotkey`, on `ctrl+p` and in the palette, starts disabled, so
//! the host's own `ctrl+p` takes the key; `board.gate` enables or disables it, and `board.passing` makes its run decline
//! the key, which goes on to the host as if it were not there (contract ergonomics 2.5). `board.dialog` shows its
//! dialog surface `ask` (2.7), whose field the command focuses, whose key moves the focus to its long scroll, and whose
//! close the board toasts.
//!
//! Its `files` route is P3's: a windowed list of files whose estimates are not their heights, each an anchor of group
//! `file` with its hunks in group `hunk`. Commands bring a file to the top, step between hunks and show a file with
//! `Nearest`; `layout` paints the header from the top file, and the header shows where the last step landed and how
//! many `layout` calls ran.
//! It also claims the calls of a `board` tool and the `board` fences of the transcript (Pr): each part is a card
//! of its own, and a fence's card holds the host's own code view of it (`fence-node`), which follows the fence as it
//! streams.
//! Scrollable card board for carrier comparisons. Each card memoizes its patch by value. Header counters expose
//! view calls, rebuilt cards and delivered messages.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -55,11 +31,9 @@ struct Board {
/// The meter's next draw panics.
broken: bool,
keys: Vec<String>,
/// What the panel's input told its handler (P3's `Input` on P2's events).
said: Vec<String>,
/// What `board.facts` read of the host, which a row under the header shows.
facts: Option<String>,
/// A box with a top and a bottom border title shows under the header (CT-26).
titled: bool,
/// What the dialog's field told its handler.
answered: Vec<String>,
@@ -190,8 +164,7 @@ pub fn setup(setup: &mut Setup) -> Result<(), String> {
});
notes(setup, &board);
asking(setup, &board);
// The plugin's own layer hears the key the route's handler passes. A global bind takes a key with a modifier: a
// plain letter is the user's typing in the composer (FT-14).
// An unmodified printable key belongs to the composer; use a modified key for the global binding.
let global = board.clone();
let layer = Layer::default().scope(LayerScope::Global).keys(vec![Bind::new("alt+h", "help")]);
setup.layer(layer, move |_, _| {
@@ -320,8 +293,8 @@ fn files_view(files: &Files) -> v2::Node {
v2::Node::column(vec![head, list]).layout(Layout::default().grow())
}
/// The dialog surface `ask` (contract ergonomics 2.7): a field, which the command that shows it focuses, and a long
/// scroll, which its key `ctrl+l` focuses; its handler hears the field's edits and the dialog's close.
/// The dialog surface `ask`: a field, which the command that shows it focuses, and a long scroll, which its key
/// `ctrl+l` focuses; its handler hears the field's edits and the dialog's close.
fn asking(setup: &mut Setup, board: &Rc<RefCell<Board>>) {
setup.command(command("board.dialog"), |host, _| {
host.dialog(Dialog::Surface(DialogSurface::new("ask").title("Ask the board").size(PanelSize::Large)));
@@ -1,7 +1,4 @@
# The conformance plugin (Pc): the reference behavior the golden transcripts in `crates/plugin/conformance` were
# recorded from. The loader's conformance tests link `src/conformance.rs` itself as the reference, and build this crate
# as a `cdylib` to replay the transcripts against it; `plugin.c` beside it is the same plugin in C. Not a workspace
# member. Its version is the one the transcripts' `describe` records.
# Builds the transcript reference as a standalone plugin.
[package]
name = "opencode-conformance-plugin"
version = "1.0.0"
@@ -1,5 +1,5 @@
/*
* The conformance plugin (Pc) in C, on `crates/plugin-abi/include/opencode_plugin.h` alone: the behavior of
* The conformance plugin in C, on `crates/plugin-abi/include/opencode_plugin.h` alone: the behavior of
* `src/conformance.rs`, request for request, so the golden transcripts of `crates/plugin/conformance`, recorded from the
* Rust source, replay against it. The loader's conformance tests build it with the system's C compiler, with symbols
* hidden and every warning an error.
@@ -275,7 +275,7 @@ static const char *const COMMANDS[] = {
"conf.field", "conf.fence", "conf.dialogs", "conf.plugins",
};
/* The last command, `conf.facts`, has a slash name and an alias (contract ergonomics 2.6). */
/* The last command, `conf.facts`, has a slash name and an alias. */
#define FACTS \
"{\"name\":\"conf.facts\",\"title\":\"conf.facts\",\"group\":null,\"slash\":\"conf-facts\",\"keybind\":null," \
"\"palette\":false,\"aliases\":[\"cf\"]}"
@@ -337,7 +337,7 @@ static int32_t create(const opencode_host_api *host, opencode_bytes options, voi
static int string_after(opencode_bytes request, const char *needle, char *out, size_t room);
/* `conf.ui`: each verb and read of P2 once, then what the reads answered. */
/* `conf.ui`: each verb and read once, then what the reads answered. */
static void ui(const opencode_host_api *host) {
char answer[256];
ask(host, "{\"type\":\"focus\",\"node\":\"i2\"}", NULL, 0);
@@ -388,7 +388,7 @@ static void dialogs(const opencode_host_api *host) {
NULL, 0);
}
/* `conf.plugins` and a change of the plugin list (P6b): the entries the host lists and the first one's key, said as
/* `conf.plugins` and a change of the plugin list: the entries the host lists and the first one's key, said as
* `said N KEY`. */
static void read_plugins(const opencode_host_api *host, const char *said) {
char answer[2048], key[96] = "", message[192];
@@ -403,7 +403,7 @@ static void read_plugins(const opencode_host_api *host, const char *said) {
toast(host, "info", message);
}
/* `conf.facts` (contract ergonomics 2.6, 2.9): the host's locale, its UTC offset at 0 and its measure of "ab日", then
/* `conf.facts`: the host's locale, its UTC offset at 0 and its measure of "ab日", then
* a prompt filled with a value under a description. */
static void facts(const opencode_host_api *host) {
char answer[512], locale[64] = "", offset[32] = "0", message[192];
@@ -422,7 +422,7 @@ static void facts(const opencode_host_api *host) {
NULL, 0);
}
/* `conf.message` (P6a): a read of one message, and its ID or none. */
/* `conf.message`: a read of one message, and its ID or none. */
static void read_message(const opencode_host_api *host) {
char answer[512], id[64], message[96] = "message none";
int32_t status = ask(host, "{\"type\":\"message\",\"session\":\"ses_a\",\"message\":\"msg_1\"}", answer, sizeof answer);
@@ -579,7 +579,7 @@ static int32_t rows(opencode_owned *out) {
return OPENCODE_OK;
}
/* The view of the route `kept` (P6a): its root kept while it would show the bumps it showed last, unless the host says
/* The view of the route `kept`: its root kept while it would show the bumps it showed last, unless the host says
* everything changed; a hidden box beside. */
static int32_t kept(instance *self, opencode_bytes request, opencode_owned *out) {
if (find(request, "\"all\":true") == NULL && self->kept == self->bumps + 1) {
@@ -626,7 +626,7 @@ static int32_t input(instance *self, opencode_bytes request, opencode_owned *out
char said[96], text[64];
int consume = 1;
if (is(request, "mount")) {
/* A mount of `kept` begins or ends (P6a). */
/* A mount of `kept` begins or ends. */
snprintf(said, sizeof said, "mount %s", find(request, "\"mounted\":true") != NULL ? "begins" : "ends");
consume = 0;
} else if (find(request, "\"bind\":\"conf\"") != NULL) {
@@ -1,49 +1,5 @@
//! The conformance plugin (Pc): the behavior every golden transcript of `crates/plugin/conformance` was recorded from,
//! with this source linked into the loader's tests, and that a library must show to pass `plugin test --conformance`.
//! `plugin.c` beside this crate is the same plugin in C, on `opencode_plugin.h` alone. A change here is a change of
//! both, and of the transcripts, which the tests write again.
//!
//! - Commands: `conf.toast` toasts "hello"; `conf.store` writes 1 under its storage key `count`, reads it back and
//! toasts "stored 1"; `conf.send` sends "ping", then "a" and "b" under the key `k`, and toasts "sent"; `conf.wake`
//! wakes the host, whose wake toasts "woken"; `conf.panic` toasts "before panic" and panics with "boom"; `conf.dup`
//! makes the next view hold the id `count` twice; `conf.read` toasts "read", the theme mode and whether the host is
//! interactive; `conf.pad` moves the canvas `pad` to its next version; `conf.down` scrolls `items` by 2 rows,
//! `conf.step` steps it to the next anchor of `items`, and `conf.where` toasts where it is (P3); `conf.ui` makes
//! each verb and read of P2 once (focus, the focus read, a rect, a mode and its read, releasing held keys, a focus
//! of the field `field` and the focus read, a blur, a panel and an overlay opened and closed) and toasts what the
//! reads answered; `conf.bump` changes what `kept` shows; `conf.message` reads message `msg_1` of session `ses_a`
//! and toasts "message ID", or "message none" (P6a); `conf.plugins` reads the plugin list and toasts "plugins N
//! KEY", its length and its first entry's key (P6b); `conf.fence` makes the next view of `conf` hold a fence node,
//! which only a fence claim's tree may; `conf.field` gives the field `field` of `rows` the focus, or on a host
//! without `focus-input` toasts "field needs a click"; `conf.dialogs` shows a select, an alert and a confirm, each
//! centered, the select and the alert extra large (contract 2.x additions); `conf.facts`, also `/cf`, toasts "facts
//! LOCALE OFFSET CELLS GRAPHEMES", the host's locale, its UTC offset at 0 and its measure of "ab日", and asks in a
//! prompt `name` filled with "conf" under "described", whose text runs `conf.toast` (contract ergonomics 2.6, 2.9).
//! - It hears that the plugin list changed (P6b), and toasts "plugins changed N KEY" from the list read then.
//! - A route surface `conf`: a column `root` of a text `count`, "views N, messages M" (the views run and the messages
//! arrived, in this instance), and a Markdown node `fixed` of the content "# fixed", memoized: built once a mount and
//! kept after.
//! - A route surface `pad` (P5): a column `pad-root` of a canvas `pad`, 20 by 1 cells, at the version `conf.pad`
//! counts. Its draw writes one text at its corner, "draw N CAUSE", in the terminal's colors: the draws run in this
//! instance, and why the host asked.
//! - A route surface `rows` (P3): a column `rows-root` of a text `where` and a scroll `items`, 3 rows high, of six boxes
//! `i0` to `i5`, each an anchor of group `items` holding "item N". Its `layout` is told of `items`, and paints
//! `where` on `#203040` while `items` is scrolled down. Between `where` and `items`, a box `button` that takes the
//! pointer (P2) holds "press". Under `items`, an empty field `field`.
//! - A route surface `kept` (P6a) that hears its mounts begin and end: a column `kept-root` of a text `kept`, "kept N"
//! (the bumps), and a hidden box `hidden`. A view told nothing changed (not `all`) while N is what it last showed
//! keeps its root.
//! - One handler of input (P2), for `rows`, `kept` and a key layer of setup (`ctrl+g` as `conf`, `ctrl+o` as `pass`,
//! everywhere, with pastes): it toasts "key conf", "paste TEXT", "pressed NODE" (a press, not a release),
//! "landed ID" (where a step landed) and "mount begins" or "mount ends", and consumes the first three; everything
//! else passes on.
//! - A renderer claim (Pr) of the calls of tool `conf-tool`: Markdown of the content "claimed N", given anew in each
//! view, N the views it ran; one of the fences of language `conf-fence`: a column `fence` of a text "fence LANGUAGE"
//! over the host's code view of the fence (a fence node), which it lowers to a text "fenced CODE" for a host without
//! `fence-node`; and one of the fences of language `conf-fences`, whose tree holds a text "fences" and two fence
//! nodes, which the host refuses.
//! - A search `conf.find` (P2): the values of the options whose title holds the query, in their order.
//! - Options that hold `fail-setup` make setup fail with "setup refused", before it registers anything.
//! Reference plugin for ABI transcript recording and replay. Keep its behavior in sync with the C implementation in
//! `plugin.c`.
use std::cell::Cell;
use std::rc::Rc;
@@ -240,7 +196,6 @@ pub fn setup(setup: &mut Setup) -> Result<(), String> {
Ok(())
}
/// The surface `kept` (P6a): it keeps its root while what it shows is the same, and hears its mounts.
fn kept(state: Rc<State>) -> v2::Surface {
v2::Surface::new("kept", v2::Place::Route("kept".to_owned()), move |view| {
let bumps = state.bumps.get();
@@ -308,7 +263,6 @@ fn handle(host: &dyn Host, event: &interact::Event) -> Handled {
handled
}
/// `conf.plugins` and a change of the plugin list (P6b): what the list holds, said as `said N KEY`.
fn plugins(host: &dyn Host, said: &str) {
let list = host.plugins();
let key = list.first().map_or("", |entry| entry.key.as_str());
@@ -1,5 +1,4 @@
# A plugin that fails on command, for containment (synthesis 4.5, P4c): the P-PTY restart scenarios install it and
# drive a real crash and a real hang. Not a workspace member.
# Containment fixture loaded by the PTY restart tests.
[package]
name = "opencode-fault-plugin"
version = "0.1.0"
@@ -1,15 +1,6 @@
//! A plugin that fails on command (synthesis 4.5, P4c). `/fault-<kind>` fails inline in the command handler
//! (`run-command`); `/fault-render-<kind>` makes the next render of its `prompt.footer` line fail (`render-slot`);
//! `/fault-thread-<kind>` fails on a thread of its own, 300 ms later, when no call of the plugin runs. The kinds:
//! `panic`, `hang` (spins), `slow` (150 ms, an overrun), `segv` (`raise(SIGSEGV)` on Unix, a null write elsewhere),
//! `abort`, `stack` (an overflow).
//!
//! The features `b` and `c` build the same plugin as `example.fault.b` and `example.fault.c`, with commands of their
//! own (`Fault B in render: segv`, `/fault-b-segv`) and line `fault plugin b`, so a harness can crash the client with
//! three different plugins.
//!
//! Before it fails it writes the wall clock, in ns since the epoch, to `$FAULT_STAMP`, so a harness can time the
//! recovery from the fault itself.
//! Exercises plugin failure in a command, in the next footer render, or on a worker thread after the call returns.
//! `FAULT_STAMP` records nanoseconds since the epoch at the fault so the harness can measure recovery. Features `b`
//! and `c` give the variants distinct IDs.
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -1,7 +1,4 @@
# The built-in home footer (P6a), its own source in `crates/tui/src/plugins/home_footer.rs`, built as a `cdylib`, so
# the TUI's `home_footer` tests load a built-in from a library file through the loader and compare it with the linked
# one. `shim` stands in for the host crate `opencode-plugin`: the ABI crate and the two slot paths the source names.
# Not a workspace member.
# Builds the TUI's built-in footer as a library for comparison with its linked behavior.
[package]
name = "opencode-home-footer-plugin"
version = "0.1.0"
@@ -1,6 +1,5 @@
// A plugin whose registrations follow a file outside it, for the pipe's tests (P7, review carbon-2): its setup reads
// the count the file at its `file` option holds and registers that many commands, `dyn.c1` to `dyn.c<n>`, each toasting
// its name. Set up again on a new JS host after the file changed, it registers others than the host has.
// Registers the command count in the configured file so the harness can change registrations without editing the
// plugin.
import { readFileSync } from "node:fs"
@@ -1,6 +1,4 @@
// A V2 plugin that imports the `effect` package, which the layer does not serve (O-170): its load fails, and the row
// checks the reason names the package. Its setup, did it run, would log what it computed with effect to the file its
// `log` option names.
// Imports a deliberately unavailable package to check the loader diagnostic.
import { Plugin } from "@opencode/plugin/tui"
import { Option, Schema } from "effect"
import { appendFileSync } from "node:fs"
@@ -1,6 +1,5 @@
// Contract 2.x, step D: code-block renderers on the JS host, through the V2 compatibility layer, as a `{ id, setup }`
// module written against `@opencode/plugin/tui`, as an npm plugin is. Each language is a behavior a row of
// `plugin_fences.rs` checks:
// Tests code-block renderers through the public V2 plugin context. Each language selects a distinct renderer
// behavior.
//
// - `probe`: good-fences' shape, a box of a label (`| <lang> (<n>)`, numbered by render) and the host's own code
// view in the raised color;
@@ -1,6 +1,5 @@
//! The linked twin of `kept/tui.ts`, for `carrier-equal` of the built-ins' contract (P6a) on the pipe: a route that
//! hears its mounts begin and end, keeps its root while what it shows is the same, holds a box it can hide, and shows
//! what a read of one message gives. The two are two programs; neither shares code with the host.
//! Linked counterpart to `kept/tui.ts`. Its route reports mount events and keeps its last tree across unrelated
//! updates.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -1,6 +1,4 @@
// The twin of `../kept.rs` on the JS host (P6a on the pipe, `carrier-equal`): a V2 `{ id, setup }` module whose route
// hears its mounts begin and end, keeps its root while what it shows is the same, holds a box it can hide, and shows
// what a read of one message gives.
// JS counterpart to `../kept.rs` for mount and subtree reuse checks.
export default {
id: "example.kept",
@@ -1,9 +1,4 @@
// The input probe of the pipe's tests (P7 with P2): contract 2.0's input over the pipe. A modal composer: `ctrl+n`
// sets the mode `normal`, whose layer takes `d`, `w` and `i` (back to insert); `x` sets the composer. Each of those
// keys holds the keys after it until its answer applied and released them, as a key's answer comes a round trip late
// (synthesis 3.7). A listener of every key hears each. A panel `side` with a focusable node and a surface layer, whose
// view shows the reads it watches (the mode, the focus), whose node takes the pointer, and whose `o` opens an overlay
// `menu` with a layer of its own. Every handler logs what it got to `.keys.log.jsonl` beside its directory.
// Modal composer input probe. Its log lets the harness compare plugin and host key order.
import { appendFileSync } from "node:fs"
import path from "node:path"
@@ -1,8 +1,4 @@
// The lab of the pipe's tests (P7, review carbon): a V2 `{ id, setup }` module whose commands each show one thing the
// carrier keeps. What the setup context says (`app`, `themeMode`); what an effect answered; a stored value it watches,
// and stops watching; more watches than the host keeps; an effect or a view that is not JSON; a view that ends the JS
// host. Its slot on the home footer has a memo within a memo, whose inner builds it counts by mount, content it gives
// and releases on each view, and no rows at all once asked.
// Exercises reads, effects and snapshots through the public plugin context.
export default {
id: "example.lab",
@@ -1,7 +1,4 @@
// A plugin that prints, for the pipe's tests (P7, review F4): its own module, a module of its own it imports, and a
// dependency from `node_modules` (`chatty`, which the test writes there) print at import, in setup and in a command,
// through every console method and `process.stdout`. None of it may reach the protocol. Its log is a hidden file beside
// its directory; a write's callback is logged once it ran.
// Writes from import, setup and a command to check stdout attribution, including dependency output.
import { appendFileSync } from "node:fs"
import path from "node:path"
@@ -24,7 +21,7 @@ export default {
console.error("error")
console.debug("debug")
console.trace("trace")
// Bun's own console writes these to standard output directly (review carbon-5).
// Bun writes these methods directly to stdout.
console.dir({ dir: true })
console.table([{ table: 1 }])
console.count("count")
@@ -1,12 +1,9 @@
// The probe of the pipe carrier's tests (P7): a V2 `{ id, setup }` module that writes its own call log, one JSON line a
// call, to the file its `log` option names, so the test's oracle never reads the host's. Its commands step (and toast
// the step, an effect), hold the keys after them, throw, hang, exit, flood the host with effects, write raw bytes to
// standard output, print, and grow its memory. Its slot surface on the home footer shows `rows` lines.
// Writes one JSON line per plugin call to the configured log, independent of the host's observations.
import { appendFileSync, existsSync, readFileSync, writeSync } from "node:fs"
import path from "node:path"
// Beside its directory, or where `log.txt` in it says: a project's plugin runs from a copy of its files (P8).
// Staged project plugins use the path from `log.txt` to log outside their private copy.
const named = path.join(import.meta.dir, "log.txt")
const beside = existsSync(named) ? readFileSync(named, "utf8").trim() : path.join(import.meta.dir, "..", ".probe.log.jsonl")
@@ -92,8 +89,6 @@ export default {
children: Array.from({ length: rows }, (_, index) => ({ type: "text", spans: [{ text: `probe line ${index}` }] })),
}
})
// A route with a scroll the host moves: a verb from a command, its state as a watched read, and the user's wheel
// as a scroll event (contract 2.0's P3 requests, over the pipe).
const list = { type: "node", surface: "pane", id: "list" }
carrier.watch("list", { type: "scroll-state", target: list })
carrier.command({ name: "probe.bottom", title: "probe.bottom" }, () => {
@@ -1,6 +1,4 @@
// The reload probe of the pipe's tests (P7, review bigboi-6): its command toasts what its helper module says, so an
// edit of the helper alone shows whether a reload imported the plugin's modules afresh. The test replaces this file
// with a setup that waits, or one that throws.
// Toasts an imported helper's value so changing just that helper tests the module cache on reload.
import { label } from "./label"
@@ -1,6 +1,4 @@
// A plugin that starts processes, for the pipe's tests (review: no orphans): its setup starts `sleep` as a child, and
// another through a shell that exits at once, in a session of its own (it leaves the JS host's process group, and its
// parent is gone). It writes their process IDs to the file its `pids` option names. Its command spins forever.
// Exercises descendant cleanup, including a process that leaves the host's process group.
import { writeFileSync } from "node:fs"
@@ -1,7 +1,4 @@
//! The linked twin of `twin/tui.ts`, for `carrier-equal` on the pipe (P7): a board of cards on a route of contract 2.0,
//! each a value and a patch by content handle, memoized on its value, below a header with their total. Commands bump a
//! card, toast, and fail. The two are two programs; each is checked against the other's frames, and neither shares code
//! with the host.
//! Linked counterpart to `twin/tui.ts`: a route of memoized cards with a content handle per patch.
use std::cell::RefCell;
use std::rc::Rc;
@@ -41,7 +38,6 @@ fn view(values: &[u32], cx: &mut v2::View<'_>) -> v2::Node {
})
.collect();
let total: u32 = values.iter().sum();
// The width it was built for: a revision built for another size shows (review bigboi-7).
let header = v2::Node::text(vec![Span::new(format!("twin {total} · {}", cx.input.width))]).with_id("header");
let cards = v2::Node::scroll(cards).with_id("cards").layout(Layout::default().grow());
v2::Node::column(vec![header, cards]).with_id("twin").layout(Layout::default().grow())
@@ -1,6 +1,4 @@
// The twin of `../twin.rs` on the JS host (P7, `carrier-equal`): a V2 `{ id, setup }` module whose route surface is a
// board of cards, each a value and a patch by content handle, memoized on its value, below a header with their total.
// Its commands come through `keymap.layer` as a V2 plugin's do; its surface and effects through the carrier.
// JS counterpart to `../twin.rs` for comparing memoized card views and content handles.
const CARDS = 6
@@ -1,11 +1,6 @@
/** @jsxImportSource @opentui/solid */
// The V2 probe of the compatibility layer's tests (P8): a `{ id, setup }` module written against `@opencode/plugin/tui`
// as an npm plugin is, with JSX over OpenTUI's intrinsics. It logs each call, one JSON line, to the file its `log`
// option names. Its commands add an item to the list its home footer claim draws, make that render throw, spin, use an
// intrinsic without a node or bare text, flood the host with toasts, ask the host's dialogs (also sized and centered),
// show a dialog of its own, open its pages (one whose commands have no `id`, one whose registrations never settle, one
// that shows a field and focuses it in one handler), toast a theme color, and use what the layer does not map. An event
// it hears is logged.
// Exercises the public V2 plugin context and JSX intrinsics. The configured log records the plugin side of each
// call.
import { Plugin } from "@opencode/plugin/tui"
import { RGBA } from "@opentui/core"
@@ -70,7 +65,7 @@ export default Plugin.define({
},
},
{ id: "v2probe.arm", run: (input?: string) => void (keyArm = String(input)) },
// A printable key bound globally by a command whose `enabled` follows a signal (contract ergonomics 2.5).
// A printable key bound globally by a command whose `enabled` follows a signal.
{ id: "v2probe.caret", bind: "^", enabled: () => caret(), run: () => log({ caret: true }) },
{ id: "v2probe.caretOn", run: (input?: string) => void setCaret(input === "on") },
// Declares a store, which reloads the plugin's registrations (a layer's commands change in place), and enables
@@ -82,7 +77,6 @@ export default Plugin.define({
setTimeout(() => setCaret(true), 0)
},
},
// A palette command on `ctrl+p` that declines its key (ce-4): the host's palette opens, and lists it.
{ id: "v2probe.hotkey", title: "Probe hotkey", bind: "ctrl+p", palette: true, run: () => false },
// A key listener (contract gaps 2), registered with the first run: it takes `ctrl+p` with `preventDefault`
// while the run's input is "take", and lets it go on otherwise.
@@ -135,7 +129,7 @@ export default Plugin.define({
},
},
// A select, then an alert, each sized and centered by `dialog.set` right after, as opencode-session-time's
// `/time` (contract 2.x, addition 4).
// `/time`.
{
id: "v2probe.centered",
run: async () => {
@@ -168,20 +162,17 @@ export default Plugin.define({
},
},
{ id: "v2probe.unshow", run: () => context.ui.dialog.clear() },
// A dialog of its own with an uncontrolled field, which a registration after setup reloads under (big-boi ds-2).
{
id: "v2probe.draft",
run: () =>
context.ui.dialog.show(() => <input id="draft" focused onInput={(value: string) => log({ draft: value })} />),
},
// A key that opens a dialog of its own with a focused field, which the user types into at once (big-boi ds-3).
{
id: "v2probe.ahead",
bind: "f2",
run: () =>
context.ui.dialog.show(() => <input id="ahead" focused onInput={(value: string) => log({ ahead: value })} />),
},
// A key that opens a dialog of its own with nothing to focus, which the user types past at once (big-boi ds-3).
{ id: "v2probe.plain", bind: "f3", run: () => context.ui.dialog.show(() => <text>Plain dialog</text>) },
{ id: "v2probe.relayer", run: () => context.keymap.layer(() => ({ commands: [{ id: "v2probe.relayered", run() {} }] })) },
{
@@ -203,12 +194,10 @@ export default Plugin.define({
{ id: "v2probe.restless", run: () => context.ui.router.navigate({ type: "plugin", name: "restless" }) },
{ id: "v2probe.grow", run: () => context.ui.router.navigate({ type: "plugin", name: "grow" }) },
{ id: "v2probe.panel", run: () => log({ opened: context.ui.panel.open("probe.panel") }) },
// What the panel's input does (CT-38): close it, full screen and back, and take the focus.
{ id: "v2probe.panel-close", run: () => shownPanel?.close() },
{ id: "v2probe.panel-full", run: () => shownPanel?.toggleFullscreen() },
{ id: "v2probe.panel-focus", run: () => shownPanel?.focus() },
{ id: "v2probe.settle", run: () => context.ui.router.navigate({ type: "plugin", name: "settle" }) },
// A handler that rejects later, after a reload perhaps (carbon-5).
{
id: "v2probe.reject",
run: async () => {
@@ -216,7 +205,6 @@ export default Plugin.define({
throw new Error("late")
},
},
// A store made after setup, written at once (carbon-2).
{
id: "v2probe.late",
run: async () => {
@@ -225,7 +213,6 @@ export default Plugin.define({
log({ stored: true })
},
},
// Two reloads of the registrations, apart (carbon-2).
{
id: "v2probe.twice",
run: () => {
@@ -309,8 +296,6 @@ export default Plugin.define({
)
},
})
// A page whose layer's commands have no `id`, as tokscope's (CT-1), and one whose command is new each mount, which
// never settles.
context.ui.router.register({
name: "inline",
render: () => {
@@ -323,7 +308,6 @@ export default Plugin.define({
return <text>inline page</text>
},
})
// A page that names its layer's command anew each time it mounts, as opencode-navigator does (CT-21).
let churns = 0
context.ui.router.register({
name: "churn",
@@ -332,8 +316,6 @@ export default Plugin.define({
return <text>churn page</text>
},
})
// A session panel whose render registers a key layer, as opencode-self-improvement's /memory panel does: the panel
// stays open (CT-29). It keeps its input for the panel commands, and has a field to take the focus (CT-38).
context.ui.slot({
append: "session.panel",
render: (panel: PanelInput) => {
@@ -347,9 +329,9 @@ export default Plugin.define({
)
},
})
// Two pages sized from their own width (contract 2.x, addition 1, R3): `grow` widens its box by a cell each time
// its size comes, without end; `settle` takes the width it first measured plus one, once. Built as Solid compiles
// a plugin's JSX, so the box and its width signal stay as the size changes.
// Two pages sized from their own width: `grow` widens its box by a cell each time its size comes, without end;
// `settle` takes the width it first measured plus one, once. Built as Solid compiles a plugin's JSX, so the box
// and its width signal stay as the size changes.
const sized = (name: string, next: (width: number) => number) =>
context.ui.router.register({
name,
@@ -1,5 +1,4 @@
# The sample native plugin (P.4): a `cdylib` on `opencode-plugin-abi`. The loader's tests build it with `cargo build`
# and load the library. Not a workspace member.
# Standalone native plugin loaded by the integration tests.
[package]
name = "opencode-sample-plugin"
version = "0.1.0"
@@ -19,10 +18,9 @@ setup-fails = []
app = []
# Starts no ticker, so the slot changes only when the host draws it again for a change batch.
still = []
# The probe of P0a (`src/p0a.rs`): dialogs, the composer and a styled box.
# Dialogs, composer edits and styled boxes.
p0a = []
# Adds `/p0btitle`, which sets the terminal title, and `/p0brun <shell command>`, which runs it in the foreground and
# toasts how it ended, for the P-PTY scenarios `P.0b/*`.
# Terminal-title and foreground-process commands.
pty = []
# A static constructor that appends a line to `opencode-sample-witness-<pid>` in the temp directory as the library
# loads, before any of its code is called: the TUI's approval test sees whether the library was mapped at all.
@@ -141,10 +141,7 @@ fn setup(setup: &mut Setup) -> Result<(), String> {
Ok(())
}
/// The commands of the P-PTY scenarios `P.0b/*`: `/p0btitle` sets the title (`parity/plugins/title/tui.ts` in TS),
/// `/p0blong` sets one of 6009 bytes,
/// `/p0brun <shell command>` runs `sh -c <command>` in the foreground, twice with `/p0btwice`, and toasts how each
/// ended and sets it as the title.
/// Commands for exercising terminal titles and foreground processes in a PTY.
fn pty(setup: &mut Setup) {
let title = command("p0b.title", "Set the title", None).slash("p0btitle");
setup.command(title, |host, _| host.set_title("p0b title"));
@@ -1,10 +1,4 @@
//! The dialogs, the composer and the box styling (P0a): a confirm and an alert whose answers come back as toasts, the composer's read and
//! edits, and a home footer claim in a styled box. The TUI's tests run this one file linked, through the C ABI's
//! byte shims, and in the sample library (`--features p0a`), so the three carriers run the same source. Every
//! command is hidden: a test or a click dispatches it.
//!
//! The probe keeps its own log in its storage key `log`, which only grows: each activation numbers itself (`setup N`)
//! and tags what it hears with that number, so a test tells an old activation's answer from a new one's.
//! Dialogs, composer edits and a styled footer exercised through the linked and native carriers.
use super::abi::{
Action, Alert, Border, BorderStyle, Command, ComposerEdit, Confirm, Dialog, Edges, Host, Layout, Node, Overflow,
@@ -69,8 +63,7 @@ pub fn setup(setup: &mut Setup) -> Result<(), String> {
host.edit_composer(ComposerEdit::Set { text: input.unwrap_or_default().to_owned() });
host.edit_composer(ComposerEdit::Submit);
});
// Every effect of P0a, in one call; with the input `panic` the call panics after them, so none may happen. The
// confirm replaces the alert, whose action then runs: both effects show without the panic.
// The panic branch must discard every requested effect.
setup.command(hidden("p0a.all"), |host, input| {
host.edit_composer(ComposerEdit::Set { text: "all".to_owned() });
host.edit_composer(ComposerEdit::Insert { text: " of it".to_owned() });
@@ -1,6 +1,4 @@
//! The small reads and verbs (P0b): a `home.footer` claim that shows its own size and what it reads, a
//! command that asks for every verb and toasts what each answered, a handler of the streaming deltas, and the reply
//! of a program in the foreground. The loader's tests run it in process and from the library and compare the two.
//! Renders host reads in the footer and reports the results of host commands.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -91,9 +91,7 @@ local function traceback(co: thread, message: any): string
return table.concat(lines, "\n")
end
-- Each parked task's owner (`host:owner` of the stretch that parked): it goes on under that owner, whichever call
-- wakes it, so what it asks for is its starting mount's (carbon tm2-1). And the plugin's raw calls to read and set the
-- call's owner, once its setup started, and the owner a wake set for the call now.
-- Resume a parked task under the mount that owned it when it yielded, regardless of which call wakes it.
local owners: { [thread]: number } = {}
local ownerOf: (() -> number)? = nil
local setOwner: ((number?) -> ())? = nil
@@ -335,10 +333,8 @@ function plugin.every(ms: number, f: (any) -> boolean?)
end)
end
-- How many answer commands the dialogs take turns on. A dialog takes a command no dialog holds, and holds it until its
-- answer or its close runs; the host runs a dialog's answer before its close, so an answer that runs late, after other
-- dialogs showed, still reaches its own dialog (big-boi `acf-1`). A dialog that finds every command held answers `nil`
-- at once. The commands, the generation from 1 and the close's input are the Rust SDK's tasks' (`task::ANSWERS`).
-- Reserve each answer command until its dialog answers or closes. If all slots are held, return nil immediately.
-- Command names and generations must match the Rust SDK.
local SLOTS = 64
-- The setup object a plugin's setup gets: the host's, with each handler a task, the waiting calls on `host`, and the
@@ -520,8 +516,8 @@ local function tasked(raw)
run(handler, a, b, c)
end
end
-- A command that returns "pass" declines the key that ran it, which goes on to whatever else takes it (contract
-- ergonomics 2.5); one that waits has taken it.
-- A command that returns "pass" declines the key that ran it, which goes on to whatever else takes it; one that
-- waits has taken it.
local function commanded(handler)
return function(a, b)
local ended, result = run(handler, a, b)