From 5c873ff272bc82ba8e81359153c3c19072111398 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 4 Nov 2026 18:47:33 +0100 Subject: [PATCH] feat(cli-rs): add the P-CLI and P-PTY parity runners A fake server serves a scenario's route table and logs requests. P-CLI runs the TS CLI from source and opencode-rs against it in isolated homes and compares exit code, stdout, stderr and requests. P-PTY runs both under a PTY through OpenTUI's embedded terminal and compares the OSC log and screen checkpoints. --- packages/cli-rs/docs/H.3.md | 72 ++++++ packages/cli-rs/package.json | 2 + packages/cli-rs/parity/cli/client.ts | 112 +++++++++ packages/cli-rs/parity/cli/diff.ts | 28 +++ packages/cli-rs/parity/cli/run.ts | 124 ++++++++++ packages/cli-rs/parity/lib/fake-server.ts | 141 +++++++++++ packages/cli-rs/parity/pty/run.ts | 231 ++++++++++++++++++ .../cli-rs/parity/scenarios/H.3/models.cli.ts | 25 ++ .../cli-rs/parity/scenarios/H.3/title.pty.ts | 20 ++ .../parity/scenarios/H.3/version.cli.ts | 5 + .../parity/scenarios/H.3/version.pty.ts | 10 + 11 files changed, 770 insertions(+) create mode 100644 packages/cli-rs/docs/H.3.md create mode 100644 packages/cli-rs/parity/cli/client.ts create mode 100644 packages/cli-rs/parity/cli/diff.ts create mode 100644 packages/cli-rs/parity/cli/run.ts create mode 100644 packages/cli-rs/parity/lib/fake-server.ts create mode 100644 packages/cli-rs/parity/pty/run.ts create mode 100644 packages/cli-rs/parity/scenarios/H.3/models.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/H.3/title.pty.ts create mode 100644 packages/cli-rs/parity/scenarios/H.3/version.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/H.3/version.pty.ts diff --git a/packages/cli-rs/docs/H.3.md b/packages/cli-rs/docs/H.3.md new file mode 100644 index 00000000000..9ddd88a01ee --- /dev/null +++ b/packages/cli-rs/docs/H.3.md @@ -0,0 +1,72 @@ +# H.3: P-CLI and P-PTY + +Both runners start the TS CLI from source (`bun packages/cli/src/index.ts`) and `opencode-rs` +(`target/debug/opencode-rs`, built by the runner, or `OPENCODE_RS_BIN`) with the same arguments. Each +run gets a fresh home with its own XDG roots and `TMPDIR`, an environment without the caller's +`OPENCODE_*` variables, `OPENCODE_CLI_NAME=opencode`, and its own fake server. `--server ` is +appended to the arguments, or replaces a `$SERVER` argument. Neither client touches the user's +service. + +```sh +bun run --cwd packages/cli-rs parity:cli [--sides ts,rs] [parity/scenarios//.cli.ts ...] +bun run --cwd packages/cli-rs parity:pty [--sides ts,rs] [parity/scenarios//.pty.ts ...] +``` + +`--sides ts,ts` checks that a case is deterministic. Without files, a runner runs every scenario. +Records go to `$TMPDIR/opencode-parity/{cli,pty}/.-.json`. + +## A scenario + +One file in `parity/scenarios//`. A case whose Rust command does not exist yet sets +`tsOnly: true`. The runner skips it when one side is `rs`. + +```ts +// parity/scenarios/C.1/models.cli.ts +import { defineCli } from "../../cli/run" + +export default defineCli({ + args: ["models"], + server: { routes: [{ path: "/api/model", json: { location, data: [{ providerID: "openai", id: "gpt-5" }] } }] }, +}) +``` + +P-CLI compares the exit code, stdout, stderr, and the requests: writes in order, reads as a sorted set +(P-REQ). + +```ts +// parity/scenarios/E.1/title.pty.ts +import { definePty } from "../../pty/run" + +export default definePty({ + args: [], + server: { fallback: "tui" }, + steps: [ + { until: { osc: "OpenCode", screen: "Ask anything" }, settle: 500, checkpoint: "home" }, + { keys: "\x03", settle: 300 }, + { keys: "\x03" }, + ], + masks: [{ pattern: /(?<=Ask anything… )".*"/, reason: "the placeholder is random" }], + exits: true, +}) +``` + +P-PTY runs the program under a PTY of `cols` x `rows` (default 100x30). It feeds the output to +OpenTUI's `EmbeddedTerminalRenderable`, which also answers the program's terminal queries. Each step +writes `keys`, then waits for `until` (an OSC sequence or screen text, a string or a RegExp) and for +`settle` ms without a screen change, then records the screen at `checkpoint`. P-PTY compares the OSC log +(kinds `title`, `progress`, `clipboard`, `notify`; set `osc` to change them), the checkpoints after masks, +the exit code (`exits: true`), and the requests (`requests: true`). + +## The fake server (`parity/lib/fake-server.ts`) + +- `routes`: `{ method = GET, path, status, json | body | events, headers }`. `:name` in `path` matches + one segment. `events` keeps an event stream open with one `data:` frame per event. +- `/api/info` reports version `local`, the version both clients have when run from source. Use + `version: "x"` for another version, or `false` to take it out of the defaults. +- `fallback: "tui"` answers the remaining requests with the TUI test defaults of + `packages/tui/test/fixture/tui-client.ts`, including `/api/event`. `emit(event)` pushes an event. +- Every request is logged. A request without a route returns 404 and appears as `(unmatched)` in the + request log. + +Normalizers (plan 7.5): the server URL, the sandbox root, prefixed IDs, ISO times, versions, +durations, and `127.0.0.1` ports. diff --git a/packages/cli-rs/package.json b/packages/cli-rs/package.json index 183e731bbb0..8030e61210f 100644 --- a/packages/cli-rs/package.json +++ b/packages/cli-rs/package.json @@ -8,6 +8,8 @@ "cargo": "cargo", "generate": "bun run script/generate.ts", "fixtures": "bun run parity/fixtures.ts", + "parity:cli": "bun run parity/cli/run.ts", + "parity:pty": "bun run parity/pty/run.ts", "live": "sh script/live.sh", "opentui-lib": "sh script/opentui-lib.sh", "typecheck": "bun check --no-script", diff --git a/packages/cli-rs/parity/cli/client.ts b/packages/cli-rs/parity/cli/client.ts new file mode 100644 index 00000000000..e7cc35091ee --- /dev/null +++ b/packages/cli-rs/parity/cli/client.ts @@ -0,0 +1,112 @@ +// How P-CLI and P-PTY start the two clients: the TS CLI from source and the Rust `opencode-rs`, each +// in a fresh home with its own XDG roots, so neither reads or writes the user's config, state, or service. + +import { mkdir, mkdtemp } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" + +export type Side = "ts" | "rs" + +const rs = path.resolve(import.meta.dir, "../..") +const cli = path.resolve(rs, "../cli") + +export function parseSides(value: string | undefined): [Side, Side] { + const sides = (value ?? "ts,rs").split(",") + if (sides.length !== 2 || !sides.every((side): side is Side => side === "ts" || side === "rs")) + throw new Error(`--sides takes two of ts and rs, for example ts,rs (got ${value})`) + return [sides[0], sides[1]] +} + +// `bun run src/index.ts` as `packages/cli`'s `dev` script runs it, from the scenario's working +// directory. The bunfig preload (`packages/cli/bunfig.toml`) would resolve from that directory, so it +// is passed resolved; `--no-install` keeps Bun from auto-installing anything it cannot resolve. +export function command(side: Side, args: string[]) { + if (side === "ts") + return [ + "bun", + "--no-install", + `--preload=${Bun.resolveSync("@opentui/solid/preload", cli)}`, + path.join(cli, "src/index.ts"), + ...args, + ] + return [process.env.OPENCODE_RS_BIN ?? path.join(rs, "target/debug/opencode-rs"), ...args] +} + +// Builds the debug `opencode-rs` once per run, unless OPENCODE_RS_BIN names a binary. +export async function buildRust(sides: Side[]) { + if (!sides.includes("rs") || process.env.OPENCODE_RS_BIN) return + const proc = Bun.spawn(["cargo", "build", "--quiet", "-p", "opencode-cli", "--bin", "opencode-rs"], { + cwd: rs, + stdout: "inherit", + stderr: "inherit", + }) + if ((await proc.exited) !== 0) throw new Error("cargo build -p opencode-cli failed") +} + +export type Sandbox = Awaited> + +// A temporary root with `home`, the XDG roots, `tmp`, and `work` (the working directory). The +// environment starts empty, so no OPENCODE_* variable of the calling session leaks in. +export async function sandbox(env: Record = {}) { + const root = await mkdtemp(path.join(tmpdir(), "opencode-parity-")) + const dirs = { + home: "home", + config: "home/.config", + data: "home/.local/share", + state: "home/.local/state", + cache: "home/.cache", + tmp: "tmp", + work: "work", + } + const paths = Object.fromEntries(Object.entries(dirs).map(([key, dir]) => [key, path.join(root, dir)])) as Record< + keyof typeof dirs, + string + > + await Promise.all(Object.values(paths).map((dir) => mkdir(dir, { recursive: true }))) + return { + root, + cwd: paths.work, + env: { + PATH: process.env.PATH ?? "/usr/bin:/bin", + LANG: "C.UTF-8", + HOME: paths.home, + XDG_CONFIG_HOME: paths.config, + XDG_DATA_HOME: paths.data, + XDG_STATE_HOME: paths.state, + XDG_CACHE_HOME: paths.cache, + TMPDIR: paths.tmp, + OPENCODE_CLI_NAME: "opencode", + OPENCODE_DISABLE_AUTOUPDATE: "1", + ...env, + }, + } +} + +// `$SERVER` in the arguments becomes the fake server's URL; without it, `--server ` goes last. +export function withServer(args: string[], url: string | undefined) { + if (url === undefined) return args + if (args.includes("$SERVER")) return args.map((arg) => (arg === "$SERVER" ? url : arg)) + return [...args, "--server", url] +} + +export type Context = { server?: string; root: string } + +// Plan 7.5: the values that differ between runs or between the clients for no user-visible reason. +export function normalize(text: string, context: Context) { + return [ + ...(context.server ? [[context.server, ""] as const] : []), + [context.root, ""] as const, + [/\b(ses|msg|prt|per|frm|evt|prj|proj|wrk|pty|tool|call)_[A-Za-z0-9]{6,}\b/g, "<$1>"] as const, + [/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z\b/g, "