// 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 ` 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 // Answers only a request with exactly this query. query?: Record status?: number // Sent as `application/json`. A function computes it from the request and the log so far, for replies // that echo what a client generated (the prompt ID of `run`). json?: unknown | ((entry: Logged, requests: Logged[]) => unknown) // Sent as is, with `headers` (default `text/plain`). body?: string // Binary bytes, sent as `application/octet-stream` unless `headers` says otherwise. base64?: string headers?: Record // An event stream: each event is one `data:` frame. The stream stays open until the server stops. events?: unknown[] // Events pushed to every open `events` stream once this request is answered. then?: (entry: Logged, requests: Logged[]) => unknown[] // Waits this long (ms) before answering; a function computes it from the request and the log so far. delay?: number | ((entry: Logged, requests: Logged[]) => number) // Waits this long (ms) after answering before pushing `then`'s events. thenDelay?: number // Answers only once a `release` step names this route's path (P-APP's `{ release: path }`, P-PTY's // `release: path`), so a scenario orders the answer after a state it observed. hold?: boolean } // A `then` event that closes the open `events` streams instead, so the clients reconnect. export const DROP = Symbol("drop") export type Logged = { method: string path: string query: Record 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> 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>() const released = new Set() const waiting: { path: string; go: () => void }[] = [] const release = (path: string) => { released.add(path) waiting.filter((held) => held.path === path).forEach((held) => held.go()) } const push = (events: unknown[]) => events.forEach((event) => { if (event !== DROP) return streams.forEach((controller) => controller.enqueue(encode(event))) streams.forEach((controller) => controller.close()) streams.clear() }) const password = crypto.randomUUID() const authorization = "Basic " + Buffer.from(`opencode:${password}`).toString("base64") const server = Bun.serve({ hostname: "127.0.0.1", port: 0, idleTimeout: 0, async fetch(request) { // A request without this run's credential belongs to no side of the scenario: another run's client, or a // live service client that reconnected to the port the kernel recycled for this server. Answer it, but // keep it out of the log a scenario compares (M.2/shell: a drive client's goal read). if (request.headers.get("authorization") !== authorization) return new Response(null, { status: 401 }) 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) && (route.query === undefined || Bun.deepEquals(route.query, entry.query)), ) if (route) { if (route.hold && !released.has(route.path)) await new Promise((go) => waiting.push({ path: route.path, go })) const delay = typeof route.delay === "function" ? route.delay(entry, requests) : route.delay if (delay) await Bun.sleep(delay) const response = respond(route, streams, entry, requests) if (route.then) { const events = route.then(entry, requests) setTimeout(() => push(events), route.thenDelay ?? 0) } return response } 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}`, // This run's server password: the runner puts it in its clients' environment, and no one else has it. password, requests, // Pushes events to every open `events` stream, as a route's `then` does. push, // Answers the held requests of the `hold` route with this path, and later ones at once. release, // Pushes an event to the open `fallback: "tui"` stream. emit: (event: Parameters["emit"]>[0]) => events?.emit(event), async stop() { waiting.forEach((held) => held.go()) 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 encode(event: unknown) { return new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`) } function respond( route: Route, streams: Set>, entry: Logged, requests: Logged[], ) { const status = route.status ?? 200 if (route.events) { const frames = route.events.map(encode) let current: ReadableStreamDefaultController | undefined const stream = new ReadableStream({ 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 } }) } const json = typeof route.json === "function" ? route.json(entry, requests) : route.json if (json !== undefined) return Response.json(json, { status, headers: route.headers }) if (route.body !== undefined) return new Response(route.body, { status, headers: { "content-type": "text/plain", ...route.headers } }) if (route.base64 !== undefined) return new Response(Buffer.from(route.base64, "base64"), { status, headers: { "content-type": "application/octet-stream", ...route.headers }, }) return new Response(null, { status: route.status ?? 204, headers: route.headers }) } async function logEntry(request: Request, url: URL): Promise { const query = [...url.searchParams.keys()] .toSorted() .reduce>((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 } }