mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
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.
This commit is contained in:
parent
c909f4e6dd
commit
5c873ff272
11 changed files with 770 additions and 0 deletions
72
packages/cli-rs/docs/H.3.md
Normal file
72
packages/cli-rs/docs/H.3.md
Normal file
|
|
@ -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 <url>` 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/<step>/<name>.cli.ts ...]
|
||||
bun run --cwd packages/cli-rs parity:pty [--sides ts,rs] [parity/scenarios/<step>/<name>.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}/<name>.<n>-<side>.json`.
|
||||
|
||||
## A scenario
|
||||
|
||||
One file in `parity/scenarios/<step>/`. 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.
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
112
packages/cli-rs/parity/cli/client.ts
Normal file
112
packages/cli-rs/parity/cli/client.ts
Normal file
|
|
@ -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<ReturnType<typeof sandbox>>
|
||||
|
||||
// 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<string, string> = {}) {
|
||||
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 <url>` 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, "<server>"] as const] : []),
|
||||
[context.root, "<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, "<time>"] as const,
|
||||
[/\bv?\d+\.\d+\.\d+(-[\w.]+)?\b/g, "<version>"] as const,
|
||||
[/\b\d+(\.\d+)?\s?(ms|s)\b/g, "<duration>"] as const,
|
||||
[/127\.0\.0\.1:\d+/g, "127.0.0.1:<port>"] as const,
|
||||
].reduce((current, [pattern, replacement]) => current.replaceAll(pattern, replacement), text)
|
||||
}
|
||||
|
||||
export function nameOf(file: string) {
|
||||
const relative = path.relative(path.join(rs, "parity/scenarios"), file)
|
||||
return (relative.startsWith("..") ? path.basename(file) : relative).replace(/\.(cli|pty)\.ts$/, "")
|
||||
}
|
||||
|
||||
export const parityRoot = path.join(rs, "parity")
|
||||
28
packages/cli-rs/parity/cli/diff.ts
Normal file
28
packages/cli-rs/parity/cli/diff.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// A readable report of how two P-CLI or P-PTY records differ: one block per differing field, with
|
||||
// the lines of each side marked where they differ. An empty string means equal.
|
||||
|
||||
export function diffRecords(left: Record<string, unknown>, right: Record<string, unknown>, sides: readonly string[]) {
|
||||
const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])]
|
||||
return keys
|
||||
.flatMap((key) => {
|
||||
const a = lines(left[key])
|
||||
const b = lines(right[key])
|
||||
if (a.join("\n") === b.join("\n")) return []
|
||||
const width = Math.max(a.length, b.length)
|
||||
const rows = Array.from({ length: width }, (_, index) => {
|
||||
const same = a[index] === b[index]
|
||||
return [
|
||||
` ${same ? " " : "-"} ${sides[0]} | ${a[index] ?? "<none>"}`,
|
||||
...(same ? [] : [` + ${sides[1]} | ${b[index] ?? "<none>"}`]),
|
||||
]
|
||||
})
|
||||
return [`${key}:`, ...rows.flat()]
|
||||
})
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
function lines(value: unknown) {
|
||||
if (value === undefined) return []
|
||||
if (typeof value === "string") return value.split("\n")
|
||||
return JSON.stringify(value, null, 2).split("\n")
|
||||
}
|
||||
124
packages/cli-rs/parity/cli/run.ts
Normal file
124
packages/cli-rs/parity/cli/run.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
// P-CLI (plan 7.1): runs one command with the TS CLI and with `opencode-rs`, each against its own fake
|
||||
// server, and compares exit code, stdout, stderr, and the requests after normalization.
|
||||
//
|
||||
// bun run parity/cli/run.ts [--sides ts,rs] [scenario.cli.ts ...]
|
||||
//
|
||||
// Without files it runs every `parity/scenarios/**/*.cli.ts`. `--sides ts,ts` checks that a case is
|
||||
// deterministic. Each side's record goes to `$TMPDIR/opencode-parity/cli/<name>.<n>-<side>.json`.
|
||||
|
||||
import { parseArgs } from "node:util"
|
||||
import { Glob } from "bun"
|
||||
import path from "node:path"
|
||||
import { tmpdir } from "node:os"
|
||||
import { rm } from "node:fs/promises"
|
||||
import { startFakeServer, type Logged, type Options } from "../lib/fake-server"
|
||||
import {
|
||||
buildRust,
|
||||
command,
|
||||
nameOf,
|
||||
normalize,
|
||||
parityRoot,
|
||||
parseSides,
|
||||
sandbox,
|
||||
withServer,
|
||||
type Context,
|
||||
type Side,
|
||||
} from "./client"
|
||||
import { diffRecords } from "./diff"
|
||||
|
||||
export type CliCase = {
|
||||
args: string[]
|
||||
// A fake server for `--server`; omit it for commands that need no server (`--version`, help).
|
||||
server?: Options
|
||||
env?: Record<string, string>
|
||||
stdin?: string
|
||||
timeout?: number
|
||||
// Rust lacks the command so far: the case runs only with `--sides ts,ts`.
|
||||
tsOnly?: boolean
|
||||
}
|
||||
|
||||
export function defineCli(value: CliCase) {
|
||||
return value
|
||||
}
|
||||
|
||||
export type CliRecord = Awaited<ReturnType<typeof runCli>>
|
||||
|
||||
export async function runCli(side: Side, value: CliCase) {
|
||||
const box = await sandbox(value.env)
|
||||
const server = value.server ? await startFakeServer(value.server) : undefined
|
||||
const proc = Bun.spawn(command(side, withServer(value.args, server?.url)), {
|
||||
cwd: box.cwd,
|
||||
env: box.env,
|
||||
stdin: value.stdin === undefined ? "ignore" : new TextEncoder().encode(value.stdin),
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
timeout: value.timeout ?? 30_000,
|
||||
})
|
||||
const [stdout, stderr, exit] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
])
|
||||
await server?.stop()
|
||||
await rm(box.root, { recursive: true, force: true })
|
||||
const context = { server: server?.url, root: box.root }
|
||||
return {
|
||||
exit,
|
||||
...(proc.signalCode ? { signal: proc.signalCode } : {}),
|
||||
stdout: normalize(stdout, context),
|
||||
stderr: normalize(stderr, context),
|
||||
requests: requestLog(server?.requests ?? [], context),
|
||||
}
|
||||
}
|
||||
|
||||
// Plan 7.1 P-REQ: mutating requests in order, reads as a sorted set.
|
||||
export function requestLog(requests: Logged[], context: Context) {
|
||||
const line = (entry: Logged) => {
|
||||
// Decoded, so the normalizers see paths and IDs inside query values.
|
||||
const query = Object.entries(entry.query)
|
||||
.flatMap(([key, values]) => values.map((value) => `${key}=${value}`))
|
||||
.join("&")
|
||||
const target = `${entry.method} ${entry.path}${query ? `?${query}` : ""}${entry.unmatched ? " (unmatched)" : ""}`
|
||||
return normalize(entry.body === undefined ? target : `${target} ${JSON.stringify(entry.body)}`, context)
|
||||
}
|
||||
return {
|
||||
reads: [...new Set(requests.filter((entry) => entry.method === "GET").map(line))].toSorted(),
|
||||
writes: requests.filter((entry) => entry.method !== "GET").map(line),
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const parsed = parseArgs({ args: Bun.argv.slice(2), options: { sides: { type: "string" } }, allowPositionals: true })
|
||||
const sides = parseSides(parsed.values.sides)
|
||||
const files = parsed.positionals.length
|
||||
? parsed.positionals.map((file) => path.resolve(file))
|
||||
: [...new Glob("scenarios/**/*.cli.ts").scanSync({ cwd: parityRoot, absolute: true })].toSorted()
|
||||
await buildRust(sides)
|
||||
const results = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const value: CliCase = (await import(file)).default
|
||||
const name = nameOf(file)
|
||||
if (value.tsOnly && sides.includes("rs")) return { name, skipped: true, report: "" }
|
||||
const records = await Promise.all(sides.map((side) => runCli(side, value)))
|
||||
await Promise.all(
|
||||
records.map((record, index) =>
|
||||
Bun.write(
|
||||
path.join(tmpdir(), "opencode-parity/cli", `${name}.${index}-${sides[index]}.json`),
|
||||
JSON.stringify(record, null, 2) + "\n",
|
||||
),
|
||||
),
|
||||
)
|
||||
return { name, skipped: false, report: diffRecords(records[0], records[1], sides) }
|
||||
}),
|
||||
)
|
||||
results.forEach((result) =>
|
||||
console.log(
|
||||
result.skipped
|
||||
? `skip ${result.name} (tsOnly)`
|
||||
: result.report
|
||||
? `FAIL ${result.name}\n${result.report}`
|
||||
: `ok ${result.name}`,
|
||||
),
|
||||
)
|
||||
process.exit(results.some((result) => result.report) ? 1 : 0)
|
||||
}
|
||||
141
packages/cli-rs/parity/lib/fake-server.ts
Normal file
141
packages/cli-rs/parity/lib/fake-server.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
// A fake OpenCode server for P-CLI and P-PTY: it serves a scenario's route table and logs every
|
||||
// request, so both clients can run with `--server <url>` and never touch the user's service.
|
||||
|
||||
import { createEventStream, createFetch } from "../../../tui/test/fixture/tui-client"
|
||||
|
||||
export type Route = {
|
||||
method?: string
|
||||
// An exact path, or a pattern where `:name` matches one segment (`/api/session/:id`).
|
||||
path: string
|
||||
status?: number
|
||||
// Sent as `application/json`.
|
||||
json?: unknown
|
||||
// Sent as is, with `headers` (default `text/plain`).
|
||||
body?: string
|
||||
headers?: Record<string, string>
|
||||
// An event stream: each event is one `data:` frame. The stream stays open until the server stops.
|
||||
events?: unknown[]
|
||||
}
|
||||
|
||||
export type Logged = {
|
||||
method: string
|
||||
path: string
|
||||
query: Record<string, string[]>
|
||||
body?: unknown
|
||||
authorization?: string
|
||||
// No route and no fallback answered; the server replied 404.
|
||||
unmatched?: true
|
||||
}
|
||||
|
||||
export type Options = {
|
||||
routes?: Route[]
|
||||
// `/api/info` for a server with this version. `false` leaves `/api/info` to the routes.
|
||||
version?: string | false
|
||||
// `tui` answers the startup reads of the TUI with the defaults of `packages/tui/test/fixture/tui-client.ts`,
|
||||
// including the event stream, after the routes.
|
||||
fallback?: "tui"
|
||||
}
|
||||
|
||||
export type FakeServer = Awaited<ReturnType<typeof startFakeServer>>
|
||||
|
||||
export async function startFakeServer(options: Options = {}) {
|
||||
const requests: Logged[] = []
|
||||
const routes = [...(options.routes ?? []), ...infoRoute(options.version ?? "local")]
|
||||
const events = options.fallback === "tui" ? createEventStream() : undefined
|
||||
const fallback = events ? createFetch(undefined, events).fetch : undefined
|
||||
const streams = new Set<ReadableStreamDefaultController<Uint8Array>>()
|
||||
const server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
idleTimeout: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
const entry = await logEntry(request, url)
|
||||
requests.push(entry)
|
||||
const route = routes.find((route) => matches(route, request.method, url.pathname))
|
||||
if (route) return respond(route, streams)
|
||||
const fallen = await Promise.resolve(fallback?.(url, request)).catch(() => undefined)
|
||||
if (fallen) return fallen
|
||||
entry.unmatched = true
|
||||
return Response.json(
|
||||
{ _tag: "NotFound", message: `fake server: no route for ${request.method} ${url.pathname}` },
|
||||
{ status: 404 },
|
||||
)
|
||||
},
|
||||
})
|
||||
return {
|
||||
url: `http://127.0.0.1:${server.port}`,
|
||||
requests,
|
||||
// Pushes an event to the open `fallback: "tui"` stream.
|
||||
emit: (event: Parameters<NonNullable<typeof events>["emit"]>[0]) => events?.emit(event),
|
||||
async stop() {
|
||||
events?.disconnect()
|
||||
for (const controller of streams) controller.close()
|
||||
await server.stop(true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function infoRoute(version: string | false): Route[] {
|
||||
if (version === false) return []
|
||||
return [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/api/info",
|
||||
json: { version, pid: 0, urls: [], paths: { tmp: "/tmp" }, capabilities: { persistentPty: true } },
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function matches(route: Route, method: string, path: string) {
|
||||
if ((route.method ?? "GET").toUpperCase() !== method) return false
|
||||
const want = route.path.split("/")
|
||||
const have = path.split("/")
|
||||
return want.length === have.length && want.every((part, index) => part.startsWith(":") || part === have[index])
|
||||
}
|
||||
|
||||
function respond(route: Route, streams: Set<ReadableStreamDefaultController<Uint8Array>>) {
|
||||
const status = route.status ?? 200
|
||||
if (route.events) {
|
||||
const frames = route.events.map((event) => new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`))
|
||||
let current: ReadableStreamDefaultController<Uint8Array> | undefined
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
current = controller
|
||||
streams.add(controller)
|
||||
frames.forEach((frame) => controller.enqueue(frame))
|
||||
},
|
||||
cancel() {
|
||||
if (current) streams.delete(current)
|
||||
},
|
||||
})
|
||||
return new Response(stream, { status, headers: { "content-type": "text/event-stream", ...route.headers } })
|
||||
}
|
||||
if (route.json !== undefined) return Response.json(route.json, { status, headers: route.headers })
|
||||
if (route.body !== undefined)
|
||||
return new Response(route.body, { status, headers: { "content-type": "text/plain", ...route.headers } })
|
||||
return new Response(null, { status: route.status ?? 204, headers: route.headers })
|
||||
}
|
||||
|
||||
async function logEntry(request: Request, url: URL): Promise<Logged> {
|
||||
const query = [...url.searchParams.keys()]
|
||||
.toSorted()
|
||||
.reduce<Record<string, string[]>>((all, key) => ({ ...all, [key]: url.searchParams.getAll(key) }), {})
|
||||
// A clone, so the fallback can still read the body.
|
||||
const text = request.body ? await request.clone().text() : ""
|
||||
return {
|
||||
method: request.method,
|
||||
path: url.pathname,
|
||||
query,
|
||||
...(text ? { body: parseBody(text) } : {}),
|
||||
...(request.headers.get("authorization") ? { authorization: request.headers.get("authorization")! } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function parseBody(text: string): unknown {
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return text
|
||||
}
|
||||
}
|
||||
231
packages/cli-rs/parity/pty/run.ts
Normal file
231
packages/cli-rs/parity/pty/run.ts
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
// P-PTY (plan 7.1): runs one command with the TS CLI and with `opencode-rs` under a fixed-size
|
||||
// pseudo-terminal, renders the output through OpenTUI's embedded terminal (which also answers the
|
||||
// program's terminal queries), and compares the OSC log, the screens at checkpoints, and the exit.
|
||||
//
|
||||
// bun run parity/pty/run.ts [--sides ts,rs] [scenario.pty.ts ...]
|
||||
//
|
||||
// Without files it runs every `parity/scenarios/**/*.pty.ts`. Sides run one after the other. Each
|
||||
// side's record goes to `$TMPDIR/opencode-parity/pty/<name>.<n>-<side>.json`.
|
||||
|
||||
import { parseArgs } from "node:util"
|
||||
import { Glob } from "bun"
|
||||
import path from "node:path"
|
||||
import { tmpdir } from "node:os"
|
||||
import { rm } from "node:fs/promises"
|
||||
import { EmbeddedTerminalRenderable } from "@opentui/core"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { startFakeServer, type Options } from "../lib/fake-server"
|
||||
import {
|
||||
buildRust,
|
||||
command,
|
||||
nameOf,
|
||||
normalize,
|
||||
parityRoot,
|
||||
parseSides,
|
||||
sandbox,
|
||||
withServer,
|
||||
type Side,
|
||||
} from "../cli/client"
|
||||
import { requestLog } from "../cli/run"
|
||||
import { diffRecords } from "../cli/diff"
|
||||
|
||||
export type OscKind = "title" | "progress" | "clipboard" | "notify" | "other"
|
||||
|
||||
export type PtyStep = {
|
||||
// Written to the terminal as is, for example "\x03" for Ctrl+C.
|
||||
keys?: string
|
||||
// Waits until an OSC sequence or the screen matches (a string matches as a substring).
|
||||
until?: { osc?: string | RegExp; screen?: string | RegExp }
|
||||
// Waits until the screen has not changed for this long.
|
||||
settle?: number
|
||||
// Records the screen under this name.
|
||||
checkpoint?: string
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
export type PtyCase = {
|
||||
args: string[]
|
||||
server?: Options
|
||||
env?: Record<string, string>
|
||||
cols?: number
|
||||
rows?: number
|
||||
steps: PtyStep[]
|
||||
// The OSC kinds the comparison keeps. Terminal queries (colors, pointer shape) are `other`.
|
||||
osc?: OscKind[]
|
||||
// Wait for the program to exit after the last step and record the code; otherwise it is killed.
|
||||
exits?: boolean
|
||||
// Plan 7.5: line masks for checkpoints. Each match becomes `<masked>`; say why in `reason`.
|
||||
masks?: { pattern: RegExp; reason: string }[]
|
||||
// Compare the request log too.
|
||||
requests?: boolean
|
||||
tsOnly?: boolean
|
||||
}
|
||||
|
||||
export function definePty(value: PtyCase) {
|
||||
return value
|
||||
}
|
||||
|
||||
export async function runPty(side: Side, value: PtyCase) {
|
||||
const cols = value.cols ?? 100
|
||||
const rows = value.rows ?? 30
|
||||
const box = await sandbox({ TERM: "xterm-256color", COLORTERM: "truecolor", ...value.env })
|
||||
const server = value.server ? await startFakeServer(value.server) : undefined
|
||||
const setup = await createTestRenderer({ width: cols, height: rows })
|
||||
const decoder = new TextDecoder()
|
||||
const output = { text: "" }
|
||||
const terminal = new EmbeddedTerminalRenderable(setup.renderer, {
|
||||
cols,
|
||||
rows,
|
||||
onData: (data) => proc.terminal?.write(data),
|
||||
})
|
||||
setup.renderer.root.add(terminal)
|
||||
const proc = Bun.spawn(command(side, withServer(value.args, server?.url)), {
|
||||
cwd: box.cwd,
|
||||
env: box.env,
|
||||
terminal: {
|
||||
cols,
|
||||
rows,
|
||||
data(_terminal, data) {
|
||||
output.text += decoder.decode(data, { stream: true })
|
||||
terminal.write(data)
|
||||
},
|
||||
},
|
||||
})
|
||||
const exited = proc.exited.then((code) => ({ code }))
|
||||
const screen = async () => {
|
||||
await setup.renderOnce()
|
||||
return terminal.screen().lines
|
||||
}
|
||||
const checkpoints: Record<string, string[]> = {}
|
||||
const failures: string[] = []
|
||||
for (const step of value.steps) {
|
||||
if (step.keys !== undefined) proc.terminal?.write(step.keys)
|
||||
const failure = await waitFor(step, { screen, osc: () => oscLog(output.text), exited })
|
||||
if (failure) {
|
||||
failures.push(failure)
|
||||
break
|
||||
}
|
||||
if (step.checkpoint) checkpoints[step.checkpoint] = await screen()
|
||||
}
|
||||
const exit =
|
||||
value.exits && !failures.length ? await Promise.race([exited, Bun.sleep(10_000).then(() => undefined)]) : undefined
|
||||
if (exit === undefined) proc.kill("SIGKILL")
|
||||
await proc.exited
|
||||
proc.terminal?.close()
|
||||
setup.renderer.destroy()
|
||||
await server?.stop()
|
||||
await rm(box.root, { recursive: true, force: true })
|
||||
const context = { server: server?.url, root: box.root }
|
||||
const kinds = value.osc ?? ["title", "progress", "clipboard", "notify"]
|
||||
return {
|
||||
...(failures.length ? { failures } : {}),
|
||||
exit: value.exits ? (exit?.code ?? "timeout") : "killed",
|
||||
osc: oscLog(output.text)
|
||||
.filter((entry) => kinds.includes(entry.kind))
|
||||
.map((entry) => normalize(`${entry.kind} ${entry.data}`, context)),
|
||||
checkpoints: Object.fromEntries(
|
||||
Object.entries(checkpoints).map(([name, lines]) => [
|
||||
name,
|
||||
lines.map((line) =>
|
||||
(value.masks ?? []).reduce(
|
||||
(current, mask) => current.replace(mask.pattern, "<masked>"),
|
||||
normalize(line, context),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
...(value.requests ? { requests: requestLog(server?.requests ?? [], context) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// OSC sequences in the order the program wrote them: ESC ] … terminated by BEL or ESC \.
|
||||
export function oscLog(text: string) {
|
||||
return [...text.matchAll(/\x1b\]([^\x07\x1b]*)(?:\x07|\x1b\\)/g)].map((match) => ({
|
||||
kind: oscKind(match[1]),
|
||||
data: match[1],
|
||||
}))
|
||||
}
|
||||
|
||||
function oscKind(data: string): OscKind {
|
||||
const code = data.split(";")[0]
|
||||
if (["0", "1", "2"].includes(code)) return "title"
|
||||
if (data.startsWith("9;4;")) return "progress"
|
||||
if (code === "52") return "clipboard"
|
||||
// `99;…:p=?;` asks the terminal which kitty notification features it has.
|
||||
if (code === "99" && /[:;]p=\?/.test(data)) return "other"
|
||||
if (["9", "99", "777"].includes(code)) return "notify"
|
||||
return "other"
|
||||
}
|
||||
|
||||
type Probe = {
|
||||
screen: () => Promise<string[]>
|
||||
osc: () => ReturnType<typeof oscLog>
|
||||
exited: Promise<{ code: number }>
|
||||
}
|
||||
|
||||
async function waitFor(step: PtyStep, probe: Probe) {
|
||||
const deadline = Date.now() + (step.timeout ?? 15_000)
|
||||
const done = { exited: false }
|
||||
probe.exited.then(() => (done.exited = true))
|
||||
const state = { last: "", since: Date.now() }
|
||||
while (Date.now() < deadline) {
|
||||
const lines = await probe.screen()
|
||||
const text = lines.join("\n")
|
||||
if (text !== state.last) Object.assign(state, { last: text, since: Date.now() })
|
||||
const osc = step.until?.osc
|
||||
const oscOk =
|
||||
osc === undefined ||
|
||||
probe.osc().some((entry) => (typeof osc === "string" ? entry.data.includes(osc) : osc.test(entry.data)))
|
||||
const want = step.until?.screen
|
||||
const screenOk = want === undefined || (typeof want === "string" ? text.includes(want) : want.test(text))
|
||||
const settled = step.settle === undefined || Date.now() - state.since >= step.settle
|
||||
if (oscOk && screenOk && settled) return
|
||||
if (done.exited && !(oscOk && screenOk)) return `exited while waiting for ${describe(step)}\n${text}`
|
||||
await Bun.sleep(25)
|
||||
}
|
||||
return `timed out waiting for ${describe(step)}\n${state.last}`
|
||||
}
|
||||
|
||||
function describe(step: PtyStep) {
|
||||
return JSON.stringify({ ...step.until, settle: step.settle }, (_key, value) =>
|
||||
value instanceof RegExp ? String(value) : value,
|
||||
)
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const parsed = parseArgs({ args: Bun.argv.slice(2), options: { sides: { type: "string" } }, allowPositionals: true })
|
||||
const sides = parseSides(parsed.values.sides)
|
||||
const files = parsed.positionals.length
|
||||
? parsed.positionals.map((file) => path.resolve(file))
|
||||
: [...new Glob("scenarios/**/*.pty.ts").scanSync({ cwd: parityRoot, absolute: true })].toSorted()
|
||||
await buildRust(sides)
|
||||
const failed = { any: false }
|
||||
for (const file of files) {
|
||||
const value: PtyCase = (await import(file)).default
|
||||
const name = nameOf(file)
|
||||
if (value.tsOnly && sides.includes("rs")) {
|
||||
console.log(`skip ${name} (tsOnly)`)
|
||||
continue
|
||||
}
|
||||
const records = []
|
||||
for (const side of sides) records.push(await runPty(side, value))
|
||||
await Promise.all(
|
||||
records.map((record, index) =>
|
||||
Bun.write(
|
||||
path.join(tmpdir(), "opencode-parity/pty", `${name}.${index}-${sides[index]}.json`),
|
||||
JSON.stringify(record, null, 2) + "\n",
|
||||
),
|
||||
),
|
||||
)
|
||||
const report = diffRecords(records[0], records[1], sides)
|
||||
const broken = records.some((record) => record.failures)
|
||||
if (report || broken) failed.any = true
|
||||
console.log(
|
||||
report || broken
|
||||
? `FAIL ${name}\n${report || records.flatMap((record) => record.failures ?? []).join("\n")}`
|
||||
: `ok ${name}`,
|
||||
)
|
||||
}
|
||||
// The renderers keep timers; exit explicitly.
|
||||
process.exit(failed.any ? 1 : 0)
|
||||
}
|
||||
25
packages/cli-rs/parity/scenarios/H.3/models.cli.ts
vendored
Normal file
25
packages/cli-rs/parity/scenarios/H.3/models.cli.ts
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// `models` against a server with three models: one GET of `/api/model` for the working directory,
|
||||
// sorted `provider/model` lines. Rust gets the command in C.1.
|
||||
import { defineCli } from "../../cli/run"
|
||||
|
||||
const location = { directory: "/work", project: { id: "proj_test", directory: "/work", canonical: "/work" } }
|
||||
|
||||
export default defineCli({
|
||||
args: ["models"],
|
||||
tsOnly: true,
|
||||
server: {
|
||||
routes: [
|
||||
{
|
||||
path: "/api/model",
|
||||
json: {
|
||||
location,
|
||||
data: [
|
||||
{ providerID: "openai", id: "gpt-5" },
|
||||
{ providerID: "anthropic", id: "claude-sonnet-5-5" },
|
||||
{ providerID: "anthropic", id: "claude-opus-5-5" },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
20
packages/cli-rs/parity/scenarios/H.3/title.pty.ts
vendored
Normal file
20
packages/cli-rs/parity/scenarios/H.3/title.pty.ts
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
// The TUI on home against an empty server sets the title to "OpenCode" (`packages/tui/src/app.tsx:644`)
|
||||
// and resets it when it exits. The server answers the TUI's startup reads with the TUI test defaults.
|
||||
// Rust gets the TUI in T.1 and the title in E.1.
|
||||
import { definePty } from "../../pty/run"
|
||||
|
||||
export default definePty({
|
||||
args: [],
|
||||
tsOnly: true,
|
||||
cols: 100,
|
||||
rows: 30,
|
||||
server: { fallback: "tui" },
|
||||
steps: [
|
||||
// The title can come before the first paint, so wait for the prompt as well.
|
||||
{ until: { osc: "OpenCode", screen: "Ask anything" }, settle: 500, checkpoint: "home", timeout: 30_000 },
|
||||
{ keys: "\x03", settle: 300 },
|
||||
{ keys: "\x03" },
|
||||
],
|
||||
masks: [{ pattern: /(?<=Ask anything… )".*"/, reason: "the home placeholder is picked at random" }],
|
||||
exits: true,
|
||||
})
|
||||
5
packages/cli-rs/parity/scenarios/H.3/version.cli.ts
vendored
Normal file
5
packages/cli-rs/parity/scenarios/H.3/version.cli.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// `--version` prints `<name> v<version>` and needs no server. Both sides run from source, so both
|
||||
// report `local`.
|
||||
import { defineCli } from "../../cli/run"
|
||||
|
||||
export default defineCli({ args: ["--version"] })
|
||||
10
packages/cli-rs/parity/scenarios/H.3/version.pty.ts
vendored
Normal file
10
packages/cli-rs/parity/scenarios/H.3/version.pty.ts
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
// `--version` under a terminal: the same line on screen, no OSC sequences, exit 0.
|
||||
import { definePty } from "../../pty/run"
|
||||
|
||||
export default definePty({
|
||||
args: ["--version"],
|
||||
cols: 40,
|
||||
rows: 4,
|
||||
steps: [{ until: { screen: "opencode v" }, checkpoint: "version" }],
|
||||
exits: true,
|
||||
})
|
||||
Loading…
Add table
Reference in a new issue